id
int64
0
1.54k
text
stringlengths
59.2k
431k
1,500
32 - (b))) while (left >= 4) { k1 = read32le(data); k1 *= c1; k1 = ROTL32(k1, 15); k1 *= c2; h1 ^= k1; h1 = ROTL32(h1, 13); h1 = h1 * 5 + UINT32_C(0xe6546b64); data += 4; left -= 4; } k1 = 0; switch (left) { case 3: k1 ^= (uint32_t)data[2] << 16; case 2: k1 ^= (uint32_t)data[1] << 8; case 1: k1 ^= (uint32_t)data[0] << 0; k1 *= c1; k1 = ROTL32(k1, 15); k1 *= c2; h1 ^= k1; } #undef ROTL32 h1 ^= len; h1 ^= h1 >> 16; h1 *= UINT32_C(0x85ebca6b); h1 ^= h1 >> 13; h1 *= UINT32_C(0xc2b2ae35); h1 ^= h1 >> 16; return h1; } uint32_t murmur3_tweak(const unsigned char *data, size_t len, uint32_t n, uint32_t tweak) { uint32_t seed = (n * UINT32_C(0xfba4c795)) + tweak; return murmur3_sum(data, len, seed); } ======================= File: node_modules/bcrypto/deps/torsion/include/torsion/hash.h ======================= /*! * hash.h - hash functions for libtorsion * Copyright (c) 2020, <NAME> (MIT License). * https://github.com/bcoin-org/libtorsion */ #ifndef TORSION_HASH_H #define TORSION_HASH_H #ifdef __cplusplus extern "C" { #endif #include <stddef.h> #include <stdint.h> #include "common.h" /* * Symbol Aliases */ #define blake2b_init torsion_blake2b_init #define blake2b_update torsion_blake2b_update #define blake2b_final torsion_blake2b_final #define blake2b160_init torsion_blake2b160_init #define blake2b160_update torsion_blake2b160_update #define blake2b160_final torsion_blake2b160_final #define blake2b256_init torsion_blake2b256_init #define blake2b256_update torsion_blake2b256_update #define blake2b256_final torsion_blake2b256_final #define blake2b384_init torsion_blake2b384_init #define blake2b384_update torsion_blake2b384_update #define blake2b384_final torsion_blake2b384_final #define blake2b512_init torsion_blake2b512_init #define blake2b512_update torsion_blake2b512_update #define blake2b512_final torsion_blake2b512_final #define blake2s_init torsion_blake2s_init #define blake2s_update torsion_blake2s_update #define blake2s_final torsion_blake2s_final #define blake2s128_init torsion_blake2s128_init #define blake2s128_update torsion_blake2s128_update #define blake2s128_final torsion_blake2s128_final #define blake2s160_init torsion_blake2s160_init #define blake2s160_update torsion_blake2s160_update #define blake2s160_final torsion_blake2s160_final #define blake2s224_init torsion_blake2s224_init #define blake2s224_update torsion_blake2s224_update #define blake2s224_final torsion_blake2s224_final #define blake2s256_init torsion_blake2s256_init #define blake2s256_update torsion_blake2s256_update #define blake2s256_final torsion_blake2s256_final #define gost94_init torsion_gost94_init #define gost94_update torsion_gost94_update #define gost94_final torsion_gost94_final #define hash160_init torsion_hash160_init #define hash160_update torsion_hash160_update #define hash160_final torsion_hash160_final #define hash256_init torsion_hash256_init #define hash256_update torsion_hash256_update #define hash256_final torsion_hash256_final #define keccak_init torsion_keccak_init #define keccak_update torsion_keccak_update #define keccak_final torsion_keccak_final #define keccak224_init torsion_keccak224_init #define keccak224_update torsion_keccak224_update #define keccak224_final torsion_keccak224_final #define keccak256_init torsion_keccak256_init #define keccak256_update torsion_keccak256_update #define keccak256_final torsion_keccak256_final #define keccak384_init torsion_keccak384_init #define keccak384_update torsion_keccak384_update #define keccak384_final torsion_keccak384_final #define keccak512_init torsion_keccak512_init #define keccak512_update torsion_keccak512_update #define keccak512_final torsion_keccak512_final #define md2_init torsion_md2_init #define md2_update torsion_md2_update #define md2_final torsion_md2_final #define md4_init torsion_md4_init #define md4_update torsion_md4_update #define md4_final torsion_md4_final #define md5_init torsion_md5_init #define md5_update torsion_md5_update #define md5_final torsion_md5_final #define md5sha1_init torsion_md5sha1_init #define md5sha1_update torsion_md5sha1_update #define md5sha1_final torsion_md5sha1_final #define ripemd160_init torsion_ripemd160_init #define ripemd160_update torsion_ripemd160_update #define ripemd160_final torsion_ripemd160_final #define sha1_init torsion_sha1_init #define sha1_update torsion_sha1_update #define sha1_final torsion_sha1_final #define sha224_init torsion_sha224_init #define sha224_update torsion_sha224_update #define sha224_final torsion_sha224_final #define sha256_init torsion_sha256_init #define sha256_update torsion_sha256_update #define sha256_final torsion_sha256_final #define sha384_init torsion_sha384_init #define sha384_update torsion_sha384_update #define sha384_final torsion_sha384_final #define sha512_init torsion_sha512_init #define sha512_update torsion_sha512_update #define sha512_final torsion_sha512_final #define sha3_224_init torsion_sha3_224_init #define sha3_224_update torsion_sha3_224_update #define sha3_224_final torsion_sha3_224_final #define sha3_256_init torsion_sha3_256_init #define sha3_256_update torsion_sha3_256_update #define sha3_256_final torsion_sha3_256_final #define sha3_384_init torsion_sha3_384_init #define sha3_384_update torsion_sha3_384_update #define sha3_384_final torsion_sha3_384_final #define sha3_512_init torsion_sha3_512_init #define sha3_512_update torsion_sha3_512_update #define sha3_512_final torsion_sha3_512_final #define shake128_init torsion_shake128_init #define shake128_update torsion_shake128_update #define shake128_final torsion_shake128_final #define shake256_init torsion_shake256_init #define shake256_update torsion_shake256_update #define shake256_final torsion_shake256_final #define whirlpool_init torsion_whirlpool_init #define whirlpool_update torsion_whirlpool_update #define whirlpool_final torsion_whirlpool_final #define hash_init torsion_hash_init #define hash_update torsion_hash_update #define hash_final torsion_hash_final #define hash_has_backend torsion_hash_has_backend #define hash_output_size torsion_hash_output_size #define hash_block_size torsion_hash_block_size #define hmac_init torsion_hmac_init #define hmac_update torsion_hmac_update #define hmac_final torsion_hmac_final /* * Definitions */ #define HASH_MAX_OUTPUT_SIZE 64 #define HASH_MAX_BLOCK_SIZE 168 /* * Hashes */ typedef enum hash_id { HASH_NONE, HASH_BLAKE2B_160, HASH_BLAKE2B_256, HASH_BLAKE2B_384, HASH_BLAKE2B_512, HASH_BLAKE2S_128, HASH_BLAKE2S_160, HASH_BLAKE2S_224, HASH_BLAKE2S_256, HASH_GOST94, HASH_HASH160, HASH_HASH256, HASH_KECCAK224, HASH_KECCAK256, HASH_KECCAK384, HASH_KECCAK512, HASH_MD2, HASH_MD4, HASH_MD5, HASH_MD5SHA1, HASH_RIPEMD160, HASH_SHA1, HASH_SHA224, HASH_SHA256, HASH_SHA384, HASH_SHA512, HASH_SHA3_224, HASH_SHA3_256, HASH_SHA3_384, HASH_SHA3_512, HASH_SHAKE128, HASH_SHAKE256, HASH_WHIRLPOOL } hash_id_t; /* * Types */ typedef struct blake2b_s { uint64_t h[8]; uint64_t t[2]; unsigned char block[128]; size_t pos; size_t len; } blake2b_t; typedef struct blake2s_s { uint32_t h[8]; uint32_t t[2]; unsigned char block[64]; size_t pos; size_t len; } blake2s_t; typedef struct gost94_s { uint8_t state[32]; uint8_t sigma[32]; unsigned char block[32]; uint64_t size[4]; } gost94_t; typedef struct keccak_s { size_t bs; uint64_t state[25]; unsigned char block[192]; size_t pos; int std; } keccak_t; typedef struct md2_s { uint8_t state[48]; uint8_t checksum[16]; unsigned char block[16]; size_t pos; } md2_t; typedef struct md5_s { uint32_t state[4]; unsigned char block[64]; uint64_t size; } md5_t; typedef struct ripemd160_s { uint32_t state[5]; unsigned char block[64]; uint64_t size; } ripemd160_t; typedef struct sha1_s { uint32_t state[5]; unsigned char block[64]; uint64_t size; } sha1_t; typedef struct md5sha1_s { md5_t md5; sha1_t sha1; } md5sha1_t; typedef struct sha256_s { uint32_t state[8]; unsigned char block[64]; uint64_t size; } sha256_t; typedef struct sha512_s { uint64_t state[8]; unsigned char block[128]; uint64_t size[2]; } sha512_t; typedef struct whirlpool_s { uint64_t state[8]; unsigned char block[64]; uint64_t size[4]; } whirlpool_t; typedef md5_t md4_t; typedef sha256_t sha224_t; typedef sha512_t sha384_t; typedef sha256_t hash160_t; typedef sha256_t hash256_t; typedef keccak_t sha3_t; typedef struct hash_s { hash_id_t type; union { blake2b_t blake2b; blake2s_t blake2s; gost94_t gost94; keccak_t keccak; md2_t md2; md5_t md5; md5sha1_t md5sha1; ripemd160_t ripemd160; sha1_t sha1; sha256_t sha256; sha512_t sha512; whirlpool_t whirlpool; } ctx; } hash_t; typedef struct hmac_s { hash_id_t type; hash_t inner; hash_t outer; } hmac_t; /* * BLAKE2b */ TORSION_EXTERN void blake2b_init(blake2b_t *ctx, size_t len, const unsigned char *key, size_t keylen); TORSION_EXTERN void blake2b_update(blake2b_t *ctx, const void *data, size_t len); TORSION_EXTERN void blake2b_final(blake2b_t *ctx, unsigned char *out); /* * BLAKE2b-{160,256,384,512} */ #define TORSION__DEFINE_BLAKE2(name, bits) \ TORSION_EXTERN void \ torsion_##name##bits##_init(name##_t *ctx, \ const unsigned char *key, size_t keylen); \ \ TORSION_EXTERN void \ torsion_##name##bits##_update(name##_t *ctx, \ const void *data, size_t len); \ \ TORSION_EXTERN void \ torsion_##name##bits##_final(name##_t *ctx, unsigned char *out); TORSION__DEFINE_BLAKE2(blake2b, 160) TORSION__DEFINE_BLAKE2(blake2b, 256) TORSION__DEFINE_BLAKE2(blake2b, 384) TORSION__DEFINE_BLAKE2(blake2b, 512) /* * BLAKE2s */ TORSION_EXTERN void blake2s_init(blake2s_t *ctx, size_t len, const unsigned char *key, size_t keylen); TORSION_EXTERN void blake2s_update(blake2s_t *ctx, const void *data, size_t len); TORSION_EXTERN void blake2s_final(blake2s_t *ctx, unsigned char *out); /* * BLAKE2s-{128,160,224,256} */ TORSION__DEFINE_BLAKE2(blake2s, 128) TORSION__DEFINE_BLAKE2(blake2s, 160) TORSION__DEFINE_BLAKE2(blake2s, 224) TORSION__DEFINE_BLAKE2(blake2s, 256) /* * GOST94 */ TORSION_EXTERN void gost94_init(gost94_t *ctx); TORSION_EXTERN void gost94_update(gost94_t *ctx, const void *data, size_t len); TORSION_EXTERN void gost94_final(gost94_t *ctx, unsigned char *out); /* * Hash160 */ TORSION_EXTERN void hash160_init(hash160_t *ctx); TORSION_EXTERN void hash160_update(hash160_t *ctx, const void *data, size_t len); TORSION_EXTERN void hash160_final(hash160_t *ctx, unsigned char *out); /* * Hash256 */ TORSION_EXTERN void hash256_init(hash256_t *ctx); TORSION_EXTERN void hash256_update(hash256_t *ctx, const void *data, size_t len); TORSION_EXTERN void hash256_final(hash256_t *ctx, unsigned char *out); /* * Keccak */ TORSION_EXTERN void keccak_init(keccak_t *ctx, unsigned int bits); TORSION_EXTERN void keccak_update(keccak_t *ctx, const void *data, size_t len); TORSION_EXTERN void keccak_final(keccak_t *ctx, unsigned char *out, unsigned int pad, size_t len); /* * Keccak{224,256,384,512} */ #define TORSION__DEFINE_KECCAK(name) \ TORSION_EXTERN void \ torsion_##name##_init(sha3_t *ctx); \ \ TORSION_EXTERN void \ torsion_##name##_update(sha3_t *ctx, const void *data, size_t len); \ \ TORSION_EXTERN void \ torsion_##name##_final(sha3_t *ctx, unsigned char *out); TORSION__DEFINE_KECCAK(keccak224) TORSION__DEFINE_KECCAK(keccak256) TORSION__DEFINE_KECCAK(keccak384) TORSION__DEFINE_KECCAK(keccak512) /* * MD2 */ TORSION_EXTERN void md2_init(md2_t *ctx); TORSION_EXTERN void md2_update(md2_t *ctx, const void *data, size_t len); TORSION_EXTERN void md2_final(md2_t *ctx, unsigned char *out); /* * MD4 */ TORSION_EXTERN void md4_init(md4_t *ctx); TORSION_EXTERN void md4_update(md4_t *ctx, const void *data, size_t len); TORSION_EXTERN void md4_final(md4_t *ctx, unsigned char *out); /* * MD5 */ TORSION_EXTERN void md5_init(md5_t *ctx); TORSION_EXTERN void md5_update(md5_t *ctx, const void *data, size_t len); TORSION_EXTERN void md5_final(md5_t *ctx, unsigned char *out); /* * MD5SHA1 */ TORSION_EXTERN void md5sha1_init(md5sha1_t *ctx); TORSION_EXTERN void md5sha1_update(md5sha1_t *ctx, const void *data, size_t len); TORSION_EXTERN void md5sha1_final(md5sha1_t *ctx, unsigned char *out); /* * RIPEMD160 */ TORSION_EXTERN void ripemd160_init(ripemd160_t *ctx); TORSION_EXTERN void ripemd160_update(ripemd160_t *ctx, const void *data, size_t len); TORSION_EXTERN void ripemd160_final(ripemd160_t *ctx, unsigned char *out); /* * SHA1 */ TORSION_EXTERN void sha1_init(sha1_t *ctx); TORSION_EXTERN void sha1_update(sha1_t *ctx, const void *data, size_t len); TORSION_EXTERN void sha1_final(sha1_t *ctx, unsigned char *out); /* * SHA224 */ TORSION_EXTERN void sha224_init(sha224_t *ctx); TORSION_EXTERN void sha224_update(sha224_t *ctx, const void *data, size_t len); TORSION_EXTERN void sha224_final(sha224_t *ctx, unsigned char *out); /* * SHA256 */ TORSION_EXTERN void sha256_init(sha256_t *ctx); TORSION_EXTERN void sha256_update(sha256_t *ctx, const void *data, size_t len); TORSION_EXTERN void sha256_final(sha256_t *ctx, unsigned char *out); /* * SHA384 */ TORSION_EXTERN void sha384_init(sha384_t *ctx); TORSION_EXTERN void sha384_update(sha384_t *ctx, const void *data, size_t len); TORSION_EXTERN void sha384_final(sha384_t *ctx, unsigned char *out); /* * SHA512 */ TORSION_EXTERN void sha512_init(sha512_t *ctx); TORSION_EXTERN void sha512_update(sha512_t *ctx, const void *data, size_t len); TORSION_EXTERN void sha512_final(sha512_t *ctx, unsigned char *out); /* * SHA3-{224,256,384,512} */ TORSION__DEFINE_KECCAK(sha3_224) TORSION__DEFINE_KECCAK(sha3_256) TORSION__DEFINE_KECCAK(sha3_384) TORSION__DEFINE_KECCAK(sha3_512) /* * SHAKE{128,256} */ #define TORSION__DEFINE_SHAKE(name) \ TORSION_EXTERN void \ torsion_##name##_init(sha3_t *ctx); \ \ TORSION_EXTERN void \ torsion_##name##_update(sha3_t *ctx, const void *data, size_t len); \ \ TORSION_EXTERN void \ torsion_##name##_final(sha3_t *ctx, unsigned char *out, size_t len); TORSION__DEFINE_SHAKE(shake128) TORSION__DEFINE_SHAKE(shake256) /* * Whirlpool */ TORSION_EXTERN void whirlpool_init(whirlpool_t *ctx); TORSION_EXTERN void whirlpool_update(whirlpool_t *ctx, const void *data, size_t len); TORSION_EXTERN void whirlpool_final(whirlpool_t *ctx, unsigned char *out); /* * Hash */ TORSION_EXTERN void hash_init(hash_t *hash, hash_id_t type); TORSION_EXTERN void hash_update(hash_t *hash, const void *data, size_t len); TORSION_EXTERN void hash_final(hash_t *hash, unsigned char *out, size_t len); TORSION_EXTERN int hash_has_backend(hash_id_t type); TORSION_EXTERN size_t hash_output_size(hash_id_t type); TORSION_EXTERN size_t hash_block_size(hash_id_t type); /* * HMAC */ TORSION_EXTERN void hmac_init(hmac_t *hmac, hash_id_t type, const unsigned char *key, size_t len); TORSION_EXTERN void hmac_update(hmac_t *hmac, const void *data, size_t len); TORSION_EXTERN void hmac_final(hmac_t *hmac, unsigned char *out); #ifdef __cplusplus } #endif #endif /* TORSION_HASH_H */ ======================= File: node_modules/bcrypto/deps/torsion/src/fields/p448.h ======================= /*! * p448.h - p448 field element for libtorsion * Copyright (c) 2020, <NAME> (MIT License). * https://github.com/bcoin-org/libtorsion */ #if defined(TORSION_HAVE_INT128) typedef uint64_t p448_fe_word_t; #define P448_FIELD_WORDS 8 #include "p448_64.h" #else typedef uint32_t p448_fe_word_t; #define P448_FIELD_WORDS 18 #include "p448_32.h" #endif typedef p448_fe_word_t p448_fe_t[P448_FIELD_WORDS]; #define p448_fe_add fiat_p448_add #define p448_fe_sub fiat_p448_sub #define p448_fe_neg fiat_p448_opp #define p448_fe_mul fiat_p448_carry_mul #define p448_fe_sqr fiat_p448_carry_square static void p448_fe_set(p448_fe_t z, const p448_fe_t x) { z[0] = x[0]; z[1] = x[1]; z[2] = x[2]; z[3] = x[3]; z[4] = x[4]; z[5] = x[5]; z[6] = x[6]; z[7] = x[7]; #if P448_FIELD_WORDS == 18 z[8] = x[8]; z[9] = x[9]; z[10] = x[10]; z[11] = x[11]; z[12] = x[12]; z[13] = x[13]; z[14] = x[14]; z[15] = x[15]; z[16] = x[16]; z[17] = x[17]; #endif } static int p448_fe_equal(const p448_fe_t x, const p448_fe_t y) { uint32_t z = 0; uint8_t u[56]; uint8_t v[56]; int i; fiat_p448_to_bytes(u, x); fiat_p448_to_bytes(v, y); for (i = 0; i < 56; i++) z |= (uint32_t)u[i] ^ (uint32_t)v[i]; return (z - 1) >> 31; } static void p448_fe_sqrn(p448_fe_t z, const p448_fe_t x, int n) { int i; p448_fe_sqr(z, x); for (i = 1; i < n; i++) p448_fe_sqr(z, z); } static void p448_fe_pow_core(p448_fe_t z, const p448_fe_t x1, const p448_fe_t x2) { /* Exponent: 2^222 - 1 */ /* Bits: 222x1 */ p448_fe_t t1, t2; /* x3 = x2^(2^1) * x1 */ p448_fe_sqr(t1, x2); p448_fe_mul(t1, t1, x1); /* x6 = x3^(2^3) * x3 */ p448_fe_sqrn(t2, t1, 3); p448_fe_mul(t2, t2, t1); /* x9 = x6^(2^3) * x3 */ p448_fe_sqrn(t2, t2, 3); p448_fe_mul(t2, t2, t1); /* x11 = x9^(2^2) * x2 */ p448_fe_sqrn(t1, t2, 2); p448_fe_mul(t1, t1, x2); /* x22 = x11^(2^11) * x11 */ p448_fe_sqrn(t2, t1, 11); p448_fe_mul(t2, t2, t1); /* x44 = x22^(2^22) * x22 */ p448_fe_sqrn(t1, t2, 22); p448_fe_mul(t1, t1, t2); /* x88 = x44^(2^44) * x44 */ p448_fe_sqrn(t2, t1, 44); p448_fe_mul(t2, t2, t1); /* x176 = x88^(2^88) * x88 */ p448_fe_sqrn(z, t2, 88); p448_fe_mul(z, z, t2); /* x220 = x176^(2^44) * x44 */ p448_fe_sqrn(z, z, 44); p448_fe_mul(z, z, t1); /* x222 = x220^(2^2) * x2 */ p448_fe_sqrn(z, z, 2); p448_fe_mul(z, z, x2); } static void p448_fe_pow_pm3d4(p448_fe_t z, const p448_fe_t x) { /* Exponent: (p - 3) / 4 */ /* Bits: 223x1 1x0 222x1 */ p448_fe_t x1, x2, x222; /* x1 = x */ p448_fe_set(x1, x); /* x2 = x1^(2^1) * x1 */ p448_fe_sqr(x2, x1); p448_fe_mul(x2, x2, x1); /* x222 = x1^(2^222 - 1) */ p448_fe_pow_core(x222, x1, x2); /* z = x222^(2^1) * x1 */ p448_fe_sqr(z, x222); p448_fe_mul(z, z, x1); /* z = z^(2^1) */ p448_fe_sqr(z, z); /* z = z^(2^222) * x222 */ p448_fe_sqrn(z, z, 222); p448_fe_mul(z, z, x222); } static void p448_fe_invert(p448_fe_t z, const p448_fe_t x) { /* Exponent: p - 2 */ /* Bits: 223x1 1x0 222x1 1x0 1x1 */ p448_fe_t x1; /* x1 = x */ p448_fe_set(x1, x); /* z = x1^((p - 3) / 4) */ p448_fe_pow_pm3d4(z, x1); /* z = z^(2^1) */ p448_fe_sqr(z, z); /* z = z^(2^1) * x1 */ p448_fe_sqr(z, z); p448_fe_mul(z, z, x1); } static int p448_fe_sqrt(p448_fe_t z, const p448_fe_t x) { /* Exponent: (p + 1) / 4 */ /* Bits: 224x1 222x0 */ p448_fe_t x1, x2; /* x1 = x */ p448_fe_set(x1, x); /* x2 = x1^(2^1) * x1 */ p448_fe_sqr(x2, x1); p448_fe_mul(x2, x2, x1); /* z = x1^(2^222 - 1) */ p448_fe_pow_core(z, x1, x2); /* z = z^(2^2) * x2 */ p448_fe_sqrn(z, z, 2); p448_fe_mul(z, z, x2); /* z = z^(2^222) */ p448_fe_sqrn(z, z, 222); /* z^2 == x1 */ p448_fe_sqr(x2, z); return p448_fe_equal(x2, x1); } static int p448_fe_isqrt(p448_fe_t z, const p448_fe_t u, const p448_fe_t v) { p448_fe_t t, x, c; int ret; /* x = u^3 * v * (u^5 * v^3)^((p - 3) / 4) mod p */ p448_fe_sqr(t, u); /* u^2 */ p448_fe_mul(c, t, u); /* u^3 */ p448_fe_mul(t, t, c); /* u^5 */ p448_fe_sqr(x, v); /* v^2 */ p448_fe_mul(x, x, v); /* v^3 */ p448_fe_mul(x, x, t); /* v^3 * u^5 */ p448_fe_pow_pm3d4(x, x); /* (v^3 * u^5)^((p - 3) / 4) */ p448_fe_mul(x, x, v); /* (v^3 * u^5)^((p - 3) / 4) * v */ p448_fe_mul(x, x, c); /* (v^3 * u^5)^((p - 3) / 4) * v * u^3 */ /* x^2 * v == u */ p448_fe_sqr(c, x); p448_fe_mul(c, c, v); ret = p448_fe_equal(c, u); p448_fe_set(z, x); return ret; } static void fiat_p448_carry_scmul_m39081(p448_fe_t z, const p448_fe_t x) { fiat_p448_opp(z, x); fiat_p448_carry_scmul_39081(z, z); } ======================= File: node_modules/bcrypto/deps/torsion/src/fields/p256.h ======================= <filename>node_modules/bcrypto/deps/torsion/src/fields/p256.h /*! * p256.h - p256 field element for libtorsion * Copyright (c) 2020, <NAME> (MIT License). * https://github.com/bcoin-org/libtorsion * * Resources: * https://briansmith.org/ecc-inversion-addition-chains-01#p256_field_inversion */ #if defined(TORSION_HAVE_INT128) typedef uint64_t p256_fe_word_t; #define P256_FIELD_WORDS 4 #include "p256_64.h" #else typedef uint32_t p256_fe_word_t; #define P256_FIELD_WORDS 8 #include "p256_32.h" #endif typedef p256_fe_word_t p256_fe_t[P256_FIELD_WORDS]; #define p256_fe_add fiat_p256_add #define p256_fe_sub fiat_p256_sub #define p256_fe_neg fiat_p256_opp #define p256_fe_mul fiat_p256_mul #define p256_fe_sqr fiat_p256_square static void p256_fe_set(p256_fe_t z, const p256_fe_t x) { z[0] = x[0]; z[1] = x[1]; z[2] = x[2]; z[3] = x[3]; #if P256_FIELD_WORDS == 8 z[4] = x[4]; z[5] = x[5]; z[6] = x[6]; z[7] = x[7]; #endif } static int p256_fe_equal(const p256_fe_t x, const p256_fe_t y) { p256_fe_word_t z = 0; int i; for (i = 0; i < P256_FIELD_WORDS; i++) z |= x[i] ^ y[i]; z = (z >> 1) | (z & 1); return (z - 1) >> (sizeof(z) * CHAR_BIT - 1); } static void p256_fe_sqrn(p256_fe_t z, const p256_fe_t x, int n) { int i; p256_fe_sqr(z, x); for (i = 1; i < n; i++) p256_fe_sqr(z, z); } static void p256_fe_pow_pm3d4(p256_fe_t z, const p256_fe_t x) { /* Exponent: (p - 3) / 4 */ /* Bits: 32x1 31x0 1x1 96x0 94x1 */ p256_fe_t t0, t1, t2, t3, t4; /* x1 = x */ p256_fe_set(t0, x); /* x2 = x1^(2^1) * x1 */ p256_fe_sqr(t1, t0); p256_fe_mul(t1, t1, t0); /* x3 = x2^(2^1) * x1 */ p256_fe_sqr(t2, t1); p256_fe_mul(t2, t2, t0); /* x6 = x3^(2^3) * x3 */ p256_fe_sqrn(t3, t2, 3); p256_fe_mul(t3, t3, t2); /* x12 = x6^(2^6) * x6 */ p256_fe_sqrn(t4, t3, 6); p256_fe_mul(t4, t4, t3); /* x15 = x12^(2^3) * x3 */ p256_fe_sqrn(t3, t4, 3); p256_fe_mul(t3, t3, t2); /* x30 = x15^(2^15) * x15 */ p256_fe_sqrn(t2, t3, 15); p256_fe_mul(t2, t2, t3); /* x32 = x30^(2^2) * x2 */ p256_fe_sqrn(t3, t2, 2); p256_fe_mul(t3, t3, t1); /* z = x32^(2^31) */ p256_fe_sqrn(z, t3, 31); /* z = z^(2^1) * x1 */ p256_fe_sqr(z, z); p256_fe_mul(z, z, t0); /* z = z^(2^96) */ p256_fe_sqrn(z, z, 96); /* z = z^(2^32) * x32 */ p256_fe_sqrn(z, z, 32); p256_fe_mul(z, z, t3); /* z = z^(2^32) * x32 */ p256_fe_sqrn(z, z, 32); p256_fe_mul(z, z, t3); /* z = z^(2^30) * x30 */ p256_fe_sqrn(z, z, 30); p256_fe_mul(z, z, t2); } static void p256_fe_invert(p256_fe_t z, const p256_fe_t x) { /* Exponent: p - 2 */ /* Bits: 32x1 31x0 1x1 96x0 94x1 1x0 1x1 */ p256_fe_t x1; /* x1 = x */ p256_fe_set(x1, x); /* z = x1^((p - 3) / 4) */ p256_fe_pow_pm3d4(z, x1); /* z = z^(2^1) */ p256_fe_sqr(z, z); /* z = z^(2^1) * x1 */ p256_fe_sqr(z, z); p256_fe_mul(z, z, x1); } static int p256_fe_sqrt(p256_fe_t z, const p256_fe_t x) { /* Exponent: (p + 1) / 4 */ /* Bits: 32x1 31x0 1x1 95x0 1x1 94x0 */ p256_fe_t t0, t1, t2; /* x1 = x */ p256_fe_set(t0, x); /* x2 = x1^(2^1) * x1 */ p256_fe_sqr(t1, t0); p256_fe_mul(t1, t1, t0); /* x4 = x2^(2^2) * x2 */ p256_fe_sqrn(t2, t1, 2); p256_fe_mul(t2, t2, t1); /* x8 = x4^(2^4) * x4 */ p256_fe_sqrn(t1, t2, 4); p256_fe_mul(t1, t1, t2); /* x16 = x8^(2^8) * x8 */ p256_fe_sqrn(t2, t1, 8); p256_fe_mul(t2, t2, t1); /* x32 = x16^(2^16) * x16 */ p256_fe_sqrn(z, t2, 16); p256_fe_mul(z, z, t2); /* z = x32^(2^31) */ p256_fe_sqrn(z, z, 31); /* z = z^(2^1) * x1 */ p256_fe_sqr(z, z); p256_fe_mul(z, z, t0); /* z = z^(2^95) */ p256_fe_sqrn(z, z, 95); /* z = z^(2^1) * x1 */ p256_fe_sqr(z, z); p256_fe_mul(z, z, t0); /* z = z^(2^94) */ p256_fe_sqrn(z, z, 94); /* z^2 == x1 */ p256_fe_sqr(t1, z); return p256_fe_equal(t1, t0); } static int p256_fe_isqrt(p256_fe_t z, const p256_fe_t u, const p256_fe_t v) { p256_fe_t t, x, c; int ret; /* x = u^3 * v * (u^5 * v^3)^((p - 3) / 4) mod p */ p256_fe_sqr(t, u); /* u^2 */ p256_fe_mul(c, t, u); /* u^3 */ p256_fe_mul(t, t, c); /* u^5 */ p256_fe_sqr(x, v); /* v^2 */ p256_fe_mul(x, x, v); /* v^3 */ p256_fe_mul(x, x, t); /* v^3 * u^5 */ p256_fe_pow_pm3d4(x, x); /* (v^3 * u^5)^((p - 3) / 4) */ p256_fe_mul(x, x, v); /* (v^3 * u^5)^((p - 3) / 4) * v */ p256_fe_mul(x, x, c); /* (v^3 * u^5)^((p - 3) / 4) * v * u^3 */ /* x^2 * v == u */ p256_fe_sqr(c, x); p256_fe_mul(c, c, v); ret = p256_fe_equal(c, u); p256_fe_set(z, x); return ret; } static void fiat_p256_scmul_3(p256_fe_t z, const p256_fe_t x) { p256_fe_t t; fiat_p256_add(t, x, x); fiat_p256_add(z, t, x); } static void fiat_p256_scmul_4(p256_fe_t z, const p256_fe_t x) { fiat_p256_add(z, x, x); fiat_p256_add(z, z, z); } static void fiat_p256_scmul_8(p256_fe_t z, const p256_fe_t x) { fiat_p256_add(z, x, x); fiat_p256_add(z, z, z); fiat_p256_add(z, z, z); } ======================= File: node_modules/bcrypto/deps/torsion/src/fields/p192.h ======================= <gh_stars>1000+ /*! * p192.h - p192 field element for libtorsion * Copyright (c) 2020, <NAME> (MIT License). * https://github.com/bcoin-org/libtorsion */ #if defined(TORSION_HAVE_INT128) typedef uint64_t p192_fe_word_t; #define P192_FIELD_WORDS 4 #include "p192_64.h" #else typedef uint32_t p192_fe_word_t; #define P192_FIELD_WORDS 9 #include "p192_32.h" #endif typedef p192_fe_word_t p192_fe_t[P192_FIELD_WORDS]; #define p192_fe_add fiat_p192_add #define p192_fe_sub fiat_p192_sub #define p192_fe_neg fiat_p192_opp #define p192_fe_mul fiat_p192_carry_mul #define p192_fe_sqr fiat_p192_carry_square static void p192_fe_set(p192_fe_t z, const p192_fe_t x) { z[0] = x[0]; z[1] = x[1]; z[2] = x[2]; z[3] = x[3]; #if P192_FIELD_WORDS == 9 z[4] = x[4]; z[5] = x[5]; z[6] = x[6]; z[7] = x[7]; z[8] = x[8]; #endif } static int p192_fe_equal(const p192_fe_t x, const p192_fe_t y) { uint32_t z = 0; uint8_t u[24]; uint8_t v[24]; int i; fiat_p192_to_bytes(u, x); fiat_p192_to_bytes(v, y); for (i = 0; i < 24; i++) z |= (uint32_t)u[i] ^ (uint32_t)v[i]; return (z - 1) >> 31; } static void p192_fe_sqrn(p192_fe_t z, const p192_fe_t x, int n) { int i; p192_fe_sqr(z, x); for (i = 1; i < n; i++) p192_fe_sqr(z, z); } static void p192_fe_pow_pm3d4(p192_fe_t z, const p192_fe_t x1) { /* Exponent: (p - 3) / 4 */ /* Bits: 127x1 1x0 62x1 */ p192_fe_t t1, t2, t3, t4; /* x2 = x1^(2^1) * x1 */ p192_fe_sqr(t1, x1); p192_fe_mul(t1, t1, x1); /* x3 = x2^(2^1) * x1 */ p192_fe_sqr(t1, t1); p192_fe_mul(t1, t1, x1); /* x6 = x3^(2^3) * x3 */ p192_fe_sqrn(t2, t1, 3); p192_fe_mul(t2, t2, t1); /* x12 = x6^(2^6) * x6 */ p192_fe_sqrn(t3, t2, 6); p192_fe_mul(t3, t3, t2); /* x24 = x12^(2^12) * x12 */ p192_fe_sqrn(t4, t3, 12); p192_fe_mul(t4, t4, t3); /* x30 = x24^(2^6) * x6 */ p192_fe_sqrn(t3, t4, 6); p192_fe_mul(t3, t3, t2); /* x31 = x30^(2^1) * x1 */ p192_fe_sqr(t3, t3); p192_fe_mul(t3, t3, x1); /* x62 = x31^(2^31) * x31 */ p192_fe_sqrn(t4, t3, 31); p192_fe_mul(t4, t4, t3); /* x124 = x62^(2^62) * x62 */ p192_fe_sqrn(z, t4, 62); p192_fe_mul(z, z, t4); /* x127 = x124^(2^3) * x3 */ p192_fe_sqrn(z, z, 3); p192_fe_mul(z, z, t1); /* z = x127^(2^1) */ p192_fe_sqr(z, z); /* z = z^(2^62) * x62 */ p192_fe_sqrn(z, z, 62); p192_fe_mul(z, z, t4); } static void p192_fe_invert(p192_fe_t z, const p192_fe_t x) { /* Exponent: p - 2 */ /* Bits: 127x1 1x0 62x1 1x0 1x1 */ p192_fe_t x1; /* x1 = x */ p192_fe_set(x1, x); /* z = x1^((p - 3) / 4) */ p192_fe_pow_pm3d4(z, x1); /* z = z^(2^1) */ p192_fe_sqr(z, z); /* z = z^(2^1) * x1 */ p192_fe_sqr(z, z); p192_fe_mul(z, z, x1); } static int p192_fe_sqrt(p192_fe_t z, const p192_fe_t x) { /* Exponent: (p + 1) / 4 */ /* Bits: 128x1 62x0 */ p192_fe_t t0, t1, t2; /* x1 = x */ p192_fe_set(t0, x); /* x2 = x1^(2^1) * x1 */ p192_fe_sqr(t1, t0); p192_fe_mul(t1, t1, t0); /* x4 = x2^(2^2) * x2 */ p192_fe_sqrn(t2, t1, 2); p192_fe_mul(t2, t2, t1); /* x8 = x4^(2^4) * x4 */ p192_fe_sqrn(t1, t2, 4); p192_fe_mul(t1, t1, t2); /* x16 = x8^(2^8) * x8 */ p192_fe_sqrn(t2, t1, 8); p192_fe_mul(t2, t2, t1); /* x32 = x16^(2^16) * x16 */ p192_fe_sqrn(t1, t2, 16); p192_fe_mul(t1, t1, t2); /* x64 = x32^(2^32) * x32 */ p192_fe_sqrn(t2, t1, 32); p192_fe_mul(t2, t2, t1); /* x128 = x64^(2^64) * x64 */ p192_fe_sqrn(z, t2, 64); p192_fe_mul(z, z, t2); /* z = x128^(2^62) */ p192_fe_sqrn(z, z, 62); /* z^2 == x1 */ p192_fe_sqr(t1, z); return p192_fe_equal(t1, t0); } static int p192_fe_isqrt(p192_fe_t z, const p192_fe_t u, const p192_fe_t v) { p192_fe_t t, x, c; int ret; /* x = u^3 * v * (u^5 * v^3)^((p - 3) / 4) mod p */ p192_fe_sqr(t, u); /* u^2 */ p192_fe_mul(c, t, u); /* u^3 */ p192_fe_mul(t, t, c); /* u^5 */ p192_fe_sqr(x, v); /* v^2 */ p192_fe_mul(x, x, v); /* v^3 */ p192_fe_mul(x, x, t); /* v^3 * u^5 */ p192_fe_pow_pm3d4(x, x); /* (v^3 * u^5)^((p - 3) / 4) */ p192_fe_mul(x, x, v); /* (v^3 * u^5)^((p - 3) / 4) * v */ p192_fe_mul(x, x, c); /* (v^3 * u^5)^((p - 3) / 4) * v * u^3 */ /* x^2 * v == u */ p192_fe_sqr(c, x); p192_fe_mul(c, c, v); ret = p192_fe_equal(c, u); p192_fe_set(z, x); return ret; } ======================= File: node_modules/bcrypto/deps/torsion/src/fields/secp256k1.h ======================= <gh_stars>1000+ /*! * secp256k1.h - secp256k1 for libtorsion * Copyright (c) 2020, <NAME> (MIT License). * https://github.com/bcoin-org/libtorsion * * Resources: * https://briansmith.org/ecc-inversion-addition-chains-01#secp256k1_field_inversion */ #if defined(TORSION_HAVE_INT128) typedef uint64_t secp256k1_fe_word_t; #define SECP256K1_FIELD_WORDS 6 #include "secp256k1_64.h" #else typedef uint32_t secp256k1_fe_word_t; #define SECP256K1_FIELD_WORDS 12 #include "secp256k1_32.h" #endif typedef secp256k1_fe_word_t secp256k1_fe_t[SECP256K1_FIELD_WORDS]; #define secp256k1_fe_add fiat_secp256k1_add #define secp256k1_fe_sub fiat_secp256k1_sub #define secp256k1_fe_neg fiat_secp256k1_opp #define secp256k1_fe_mul fiat_secp256k1_carry_mul #define secp256k1_fe_sqr fiat_secp256k1_carry_square static void secp256k1_fe_set(secp256k1_fe_t z, const secp256k1_fe_t x) { z[0] = x[0]; z[1] = x[1]; z[2] = x[2]; z[3] = x[3]; z[4] = x[4]; z[5] = x[5]; #if SECP256K1_FIELD_WORDS == 12 z[6] = x[6]; z[7] = x[7]; z[8] = x[8]; z[9] = x[9]; z[10] = x[10]; z[11] = x[11]; #endif } static int secp256k1_fe_equal(const secp256k1_fe_t x, const secp256k1_fe_t y) { uint32_t z = 0; uint8_t u[32]; uint8_t v[32]; int i; fiat_secp256k1_to_bytes(u, x); fiat_secp256k1_to_bytes(v, y); for (i = 0; i < 32; i++) z |= (uint32_t)u[i] ^ (uint32_t)v[i]; return (z - 1) >> 31; } static void secp256k1_fe_sqrn(secp256k1_fe_t z, const secp256k1_fe_t x, int n) { int i; secp256k1_fe_sqr(z, x); for (i = 1; i < n; i++) secp256k1_fe_sqr(z, z); } static void secp256k1_fe_pow_core(secp256k1_fe_t z, const secp256k1_fe_t x1, const secp256k1_fe_t x2) { /* Exponent: (p - 47) / 64 */ /* Bits: 223x1 1x0 22x1 4x0 */ secp256k1_fe_t t1, t2, t3, t4; /* x3 = x2^(2^1) * x1 */ secp256k1_fe_sqr(t1, x2); secp256k1_fe_mul(t1, t1, x1); /* x6 = x3^(2^3) * x3 */ secp256k1_fe_sqrn(t2, t1, 3); secp256k1_fe_mul(t2, t2, t1); /* x9 = x6^(2^3) * x3 */ secp256k1_fe_sqrn(t3, t2, 3); secp256k1_fe_mul(t3, t3, t1); /* x11 = x9^(2^2) * x2 */ secp256k1_fe_sqrn(t2, t3, 2); secp256k1_fe_mul(t2, t2, x2); /* x22 = x11^(2^11) * x11 */ secp256k1_fe_sqrn(t3, t2, 11); secp256k1_fe_mul(t3, t3, t2); /* x44 = x22^(2^22) * x22 */ secp256k1_fe_sqrn(t2, t3, 22); secp256k1_fe_mul(t2, t2, t3); /* x88 = x44^(2^44) * x44 */ secp256k1_fe_sqrn(t4, t2, 44); secp256k1_fe_mul(t4, t4, t2); /* x176 = x88^(2^88) * x88 */ secp256k1_fe_sqrn(z, t4, 88); secp256k1_fe_mul(z, z, t4); /* x220 = x176^(2^44) * x44 */ secp256k1_fe_sqrn(z, z, 44); secp256k1_fe_mul(z, z, t2); /* x223 = x220^(2^3) * x3 */ secp256k1_fe_sqrn(z, z, 3); secp256k1_fe_mul(z, z, t1); /* z = x223^(2^1) */ secp256k1_fe_sqr(z, z); /* z = z^(2^22) * x22 */ secp256k1_fe_sqrn(z, z, 22); secp256k1_fe_mul(z, z, t3); /* z = z^(2^4) */ secp256k1_fe_sqrn(z, z, 4); } static void secp256k1_fe_pow_pm3d4(secp256k1_fe_t z, const secp256k1_fe_t x) { /* Exponent: (p - 3) / 4 */ /* Bits: 223x1 1x0 22x1 4x0 1x1 1x0 2x1 */ secp256k1_fe_t x1, x2; /* x1 = x */ secp256k1_fe_set(x1, x); /* x2 = x1^(2^1) * x1 */ secp256k1_fe_sqr(x2, x1); secp256k1_fe_mul(x2, x2, x1); /* z = x1^((p - 47) / 64) */ secp256k1_fe_pow_core(z, x1, x2); /* z = z^(2^1) * x1 */ secp256k1_fe_sqr(z, z); secp256k1_fe_mul(z, z, x1); /* z = z^(2^1) */ secp256k1_fe_sqr(z, z); /* z = z^(2^2) * x2 */ secp256k1_fe_sqrn(z, z, 2); secp256k1_fe_mul(z, z, x2); } static void secp256k1_fe_invert(secp256k1_fe_t z, const secp256k1_fe_t x) { /* Exponent: p - 2 */ /* Bits: 223x1 1x0 22x1 4x0 1x1 1x0 2x1 1x0 1x1 */ secp256k1_fe_t x1, x2; /* x1 = x */ secp256k1_fe_set(x1, x); /* x2 = x1^(2^1) * x1 */ secp256k1_fe_sqr(x2, x1); secp256k1_fe_mul(x2, x2, x1); /* z = x1^((p - 47) / 64) */ secp256k1_fe_pow_core(z, x1, x2); /* z = z^(2^1) * x1 */ secp256k1_fe_sqr(z, z); secp256k1_fe_mul(z, z, x1); /* z = z^(2^1) */ secp256k1_fe_sqr(z, z); /* z = z^(2^2) * x2 */ secp256k1_fe_sqrn(z, z, 2); secp256k1_fe_mul(z, z, x2); /* z = z^(2^1) */ secp256k1_fe_sqr(z, z); /* z = z^(2^1) * x1 */ secp256k1_fe_sqr(z, z); secp256k1_fe_mul(z, z, x1); } static int secp256k1_fe_sqrt(secp256k1_fe_t z, const secp256k1_fe_t x) { /* Exponent: (p + 1) / 4 */ /* Bits: 223x1 1x0 22x1 4x0 2x1 2x0 */ secp256k1_fe_t x1, x2; /* x1 = x */ secp256k1_fe_set(x1, x); /* x2 = x1^(2^1) * x1 */ secp256k1_fe_sqr(x2, x1); secp256k1_fe_mul(x2, x2, x1); /* z = x1^((p - 47) / 64) */ secp256k1_fe_pow_core(z, x1, x2); /* z = z^(2^2) * x2 */ secp256k1_fe_sqrn(z, z, 2); secp256k1_fe_mul(z, z, x2); /* z = z^(2^2) */ secp256k1_fe_sqrn(z, z, 2); /* z^2 == x1 */ secp256k1_fe_sqr(x2, z); return secp256k1_fe_equal(x2, x1); } static int secp256k1_fe_isqrt(secp256k1_fe_t z, const secp256k1_fe_t u, const secp256k1_fe_t v) { secp256k1_fe_t t, x, c; int ret; /* x = u^3 * v * (u^5 * v^3)^((p - 3) / 4) mod p */ secp256k1_fe_sqr(t, u); /* u^2 */ secp256k1_fe_mul(c, t, u); /* u^3 */ secp256k1_fe_mul(t, t, c); /* u^5 */ secp256k1_fe_sqr(x, v); /* v^2 */ secp256k1_fe_mul(x, x, v); /* v^3 */ secp256k1_fe_mul(x, x, t); /* v^3 * u^5 */ secp256k1_fe_pow_pm3d4(x, x); /* (v^3 * u^5)^((p - 3) / 4) */ secp256k1_fe_mul(x, x, v); /* (v^3 * u^5)^((p - 3) / 4) * v */ secp256k1_fe_mul(x, x, c); /* (v^3 * u^5)^((p - 3) / 4) * v * u^3 */ /* x^2 * v == u */ secp256k1_fe_sqr(c, x); secp256k1_fe_mul(c, c, v); ret = secp256k1_fe_equal(c, u); secp256k1_fe_set(z, x); return ret; } ======================= File: node_modules/bcrypto/deps/torsion/src/fields/scalar.h ======================= <reponame>pradyuman-verma/bcoin<gh_stars>1000+ /*! * scalar.h - scalar inversion chains for libtorsion * Copyright (c) 2020, <NAME> (MIT License). * https://github.com/bcoin-org/libtorsion * * Parts of this software are based on bitcoin-core/secp256k1: * Copyright (c) 2013 <NAME> * https://github.com/bitcoin-core/secp256k1 */ static void q192_sc_invert(const scalar_field_t *sc, sc_t z, const sc_t x) { sc_t x1, x3, x5, x7, x9, x11, x13, x15, t1, t2; sc_mont(sc, x1, x); sc_montsqr(sc, t1, x1); sc_montmul(sc, x3, x1, t1); sc_montmul(sc, x5, x3, t1); sc_montmul(sc, x7, x5, t1); sc_montmul(sc, x9, x7, t1); sc_montmul(sc, x11, x9, t1); sc_montmul(sc, x13, x11, t1); sc_montmul(sc, x15, x13, t1); sc_montsqrn(sc, t1, x15, 4); /* x8 */ sc_montmul(sc, t1, t1, x15); sc_montsqrn(sc, t2, t1, 8); /* x16 */ sc_montmul(sc, t2, t2, t1); sc_montsqrn(sc, t1, t2, 16); /* x32 */ sc_montmul(sc, t1, t1, t2); sc_montsqrn(sc, t2, t1, 32); /* x64 */ sc_montmul(sc, t2, t2, t1); sc_montsqrn(sc, z, t2, 32); /* x96 */ sc_montmul(sc, z, z, t1); sc_montsqrn(sc, z, z, 0 + 4); /* 1001 */ sc_montmul(sc, z, z, x9); sc_montsqrn(sc, z, z, 0 + 4); /* 1001 */ sc_montmul(sc, z, z, x9); sc_montsqrn(sc, z, z, 0 + 4); /* 1101 */ sc_montmul(sc, z, z, x13); sc_montsqrn(sc, z, z, 0 + 3); /* 111 */ sc_montmul(sc, z, z, x7); sc_montsqrn(sc, z, z, 1 + 2); /* 011 */ sc_montmul(sc, z, z, x3); sc_montsqrn(sc, z, z, 0 + 3); /* 111 */ sc_montmul(sc, z, z, x7); sc_montsqrn(sc, z, z, 5 + 2); /* 0000011 */ sc_montmul(sc, z, z, x3); sc_montsqrn(sc, z, z, 1 + 2); /* 011 */ sc_montmul(sc, z, z, x3); sc_montsqrn(sc, z, z, 4 + 3); /* 0000101 */ sc_montmul(sc, z, z, x5); sc_montsqrn(sc, z, z, 3 + 4); /* 0001101 */ sc_montmul(sc, z, z, x13); sc_montsqrn(sc, z, z, 1 + 4); /* 01111 */ sc_montmul(sc, z, z, x15); sc_montsqrn(sc, z, z, 2 + 4); /* 001001 */ sc_montmul(sc, z, z, x9); sc_montsqrn(sc, z, z, 0 + 4); /* 1011 */ sc_montmul(sc, z, z, x11); sc_montsqrn(sc, z, z, 3 + 4); /* 0001101 */ sc_montmul(sc, z, z, x13); sc_montsqrn(sc, z, z, 0 + 3); /* 101 */ sc_montmul(sc, z, z, x5); sc_montsqrn(sc, z, z, 2 + 4); /* 001101 */ sc_montmul(sc, z, z, x13); sc_montsqrn(sc, z, z, 2 + 1); /* 001 */ sc_montmul(sc, z, z, x1); sc_montsqrn(sc, z, z, 3 + 3); /* 000101 */ sc_montmul(sc, z, z, x5); sc_montsqrn(sc, z, z, 5 + 3); /* 00000101 */ sc_montmul(sc, z, z, x5); sc_montsqrn(sc, z, z, 0 + 3); /* 111 */ sc_montmul(sc, z, z, x7); sc_normal(sc, z, z); sc_cleanse(sc, x1); } static void q224_sc_invert(const scalar_field_t *sc, sc_t z, const sc_t x) { sc_t x1, x3, x5, x7, x11, x15, x23, t1, t2; sc_mont(sc, x1, x); sc_montsqr(sc, t1, x1); sc_montsqr(sc, t2, t1); sc_montmul(sc, x3, x1, t1); sc_montmul(sc, x5, x3, t1); sc_montmul(sc, x7, x5, t1); sc_montmul(sc, x11, x7, t2); sc_montmul(sc, x15, x11, t2); sc_montsqr(sc, t2, t2); sc_montmul(sc, x23, x15, t2); sc_montmul(sc, t1, x23, t2); /* x5 */ sc_montsqrn(sc, t1, t1, 2); /* x7 */ sc_montmul(sc, t1, t1, x3); sc_montsqrn(sc, t2, t1, 7); /* x14 */ sc_montmul(sc, t2, t2, t1); sc_montsqrn(sc, t1, t2, 14); /* x28 */ sc_montmul(sc, t1, t1, t2); sc_montsqrn(sc, t2, t1, 28); /* x56 */ sc_montmul(sc, t2, t2, t1); sc_montsqrn(sc, z, t2, 56); /* x112 */ sc_montmul(sc, z, z, t2); sc_montsqrn(sc, z, z, 3 + 4); /* 0001011 */ sc_montmul(sc, z, z, x11); sc_montsqrn(sc, z, z, 1 + 3); /* 0101 */ sc_montmul(sc, z, z, x5); sc_montsqrn(sc, z, z, 3 + 5); /* 00010111 */ sc_montmul(sc, z, z, x23); sc_montsqrn(sc, z, z, 5 + 5); /* 0000010111 */ sc_montmul(sc, z, z, x23); sc_montsqrn(sc, z, z, 3 + 4); /* 0001111 */ sc_montmul(sc, z, z, x15); sc_montsqrn(sc, z, z, 6 + 3); /* 000000111 */ sc_montmul(sc, z, z, x7); sc_montsqrn(sc, z, z, 0 + 2); /* 11 */ sc_montmul(sc, z, z, x3); sc_montsqrn(sc, z, z, 4 + 1); /* 00001 */ sc_montmul(sc, z, z, x1); sc_montsqrn(sc, z, z, 2 + 3); /* 00111 */ sc_montmul(sc, z, z, x7); sc_montsqrn(sc, z, z, 0 + 4); /* 1011 */ sc_montmul(sc, z, z, x11); sc_montsqrn(sc, z, z, 0 + 3); /* 101 */ sc_montmul(sc, z, z, x5); sc_montsqrn(sc, z, z, 2 + 3); /* 00101 */ sc_montmul(sc, z, z, x5); sc_montsqrn(sc, z, z, 2 + 3); /* 00101 */ sc_montmul(sc, z, z, x5); sc_montsqrn(sc, z, z, 3 + 3); /* 000101 */ sc_montmul(sc, z, z, x5); sc_montsqrn(sc, z, z, 1 + 5); /* 010111 */ sc_montmul(sc, z, z, x23); sc_montsqrn(sc, z, z, 3 + 5); /* 00010111 */ sc_montmul(sc, z, z, x23); sc_montsqrn(sc, z, z, 4 + 3); /* 0000101 */ sc_montmul(sc, z, z, x5); sc_montsqrn(sc, z, z, 1 + 1); /* 01 */ sc_montmul(sc, z, z, x1); sc_montsqrn(sc, z, z, 3 + 2); /* 00011 */ sc_montmul(sc, z, z, x3); sc_montsqrn(sc, z, z, 0 + 4); /* 1011 */ sc_montmul(sc, z, z, x11); sc_normal(sc, z, z); sc_cleanse(sc, x1); } static void q256_sc_invert(const scalar_field_t *sc, sc_t z, const sc_t x) { /* https://briansmith.org/ecc-inversion-addition-chains-01#p256_scalar_inversion */ /* https://github.com/briansmith/ring/blob/master/src/ec/suite_b/ops/p256.rs#L169 */ sc_t d0, d1, d2, d3, d4, d5, d6, d7; sc_t b10 /* 1010 */, b42 /* 101010 */, b63 /* 111111 */; sc_t x8 /* ff */, x16 /* ffff */, x32 /* ffffffff */; sc_mont(sc, d0, x); sc_montsqr(sc, d1, d0); sc_montmul(sc, d2, d1, d0); sc_montmul(sc, d3, d1, d2); sc_montmul(sc, d4, d3, d1); sc_montsqr(sc, b10, d3); sc_montmul(sc, d5, b10, d3); sc_montsqrn(sc, d6, b10, 1); sc_montmul(sc, d6, d6, d0); sc_montsqr(sc, b42, d6); sc_montmul(sc, d7, b42, d3); sc_montmul(sc, b63, b42, d6); sc_montsqrn(sc, x8, b63, 2); sc_montmul(sc, x8, x8, d2); sc_montsqrn(sc, x16, x8, 8); sc_montmul(sc, x16, x16, x8); sc_montsqrn(sc, x32, x16, 16); sc_montmul(sc, x32, x32, x16); sc_montsqrn(sc, z, x32, 32); sc_montsqrn(sc, z, z, 32); sc_montmul(sc, z, z, x32); sc_montsqrn(sc, z, z, 32); sc_montmul(sc, z, z, x32); sc_montsqrn(sc, z, z, 0 + 6); /* 101111 */ sc_montmul(sc, z, z, d7); sc_montsqrn(sc, z, z, 2 + 3); /* 00111 */ sc_montmul(sc, z, z, d4); sc_montsqrn(sc, z, z, 2 + 2); /* 0011 */ sc_montmul(sc, z, z, d2); sc_montsqrn(sc, z, z, 1 + 4); /* 01111 */ sc_montmul(sc, z, z, d5); sc_montsqrn(sc, z, z, 0 + 5); /* 10101 */ sc_montmul(sc, z, z, d6); sc_montsqrn(sc, z, z, 1 + 3); /* 0101 */ sc_montmul(sc, z, z, d3); sc_montsqrn(sc, z, z, 0 + 3); /* 101 */ sc_montmul(sc, z, z, d3); sc_montsqrn(sc, z, z, 0 + 3); /* 101 */ sc_montmul(sc, z, z, d3); sc_montsqrn(sc, z, z, 2 + 3); /* 00111 */ sc_montmul(sc, z, z, d4); sc_montsqrn(sc, z, z, 3 + 6); /* 000101111 */ sc_montmul(sc, z, z, d7); sc_montsqrn(sc, z, z, 2 + 4); /* 001111 */ sc_montmul(sc, z, z, d5); sc_montsqrn(sc, z, z, 1 + 1); /* 01 */ sc_montmul(sc, z, z, d0); sc_montsqrn(sc, z, z, 4 + 1); /* 00001 */ sc_montmul(sc, z, z, d0); sc_montsqrn(sc, z, z, 2 + 4); /* 001111 */ sc_montmul(sc, z, z, d5); sc_montsqrn(sc, z, z, 2 + 3); /* 00111 */ sc_montmul(sc, z, z, d4); sc_montsqrn(sc, z, z, 1 + 3); /* 0111 */ sc_montmul(sc, z, z, d4); sc_montsqrn(sc, z, z, 2 + 3); /* 00111 */ sc_montmul(sc, z, z, d4); sc_montsqrn(sc, z, z, 2 + 3); /* 00101 */ sc_montmul(sc, z, z, d3); sc_montsqrn(sc, z, z, 1 + 2); /* 011 */ sc_montmul(sc, z, z, d2); sc_montsqrn(sc, z, z, 4 + 6); /* 0000101111 */ sc_montmul(sc, z, z, d7); sc_montsqrn(sc, z, z, 0 + 2); /* 11 */ sc_montmul(sc, z, z, d2); sc_montsqrn(sc, z, z, 3 + 2); /* 00011 */ sc_montmul(sc, z, z, d2); sc_montsqrn(sc, z, z, 3 + 2); /* 00011 */ sc_montmul(sc, z, z, d2); sc_montsqrn(sc, z, z, 2 + 1); /* 001 */ sc_montmul(sc, z, z, d0); sc_montsqrn(sc, z, z, 2 + 5); /* 0010101 */ sc_montmul(sc, z, z, d6); sc_montsqrn(sc, z, z, 2 + 4); /* 001111 */ sc_montmul(sc, z, z, d5); sc_normal(sc, z, z); sc_cleanse(sc, d0); } static void q384_sc_invert(const scalar_field_t *sc, sc_t z, const sc_t x) { /* https://briansmith.org/ecc-inversion-addition-chains-01#p384_scalar_inversion */ /* https://github.com/briansmith/ring/blob/master/src/ec/suite_b/ops/p384.rs#L193 */ sc_t d0, d1, d2, d3, d4, d5, d6, d7; sc_t b2 /* 10 */; sc_t x8 /* ff */, x16 /* ffff */, x32 /* ffffffff */; sc_t x64 /* ffffffffffffffff */, x96 /* ffffffffffffffffffffffff */; sc_mont(sc, d0, x); sc_montsqr(sc, b2, d0); sc_montmul(sc, d1, d0, b2); sc_montmul(sc, d2, d1, b2); sc_montmul(sc, d3, d2, b2); sc_montmul(sc, d4, d3, b2); sc_montmul(sc, d5, d4, b2); sc_montmul(sc, d6, d5, b2); sc_montmul(sc, d7, d6, b2); sc_montsqrn(sc, x8, d7, 4); sc_montmul(sc, x8, x8, d7); sc_montsqrn(sc, x16, x8, 8); sc_montmul(sc, x16, x16, x8); sc_montsqrn(sc, x32, x16, 16); sc_montmul(sc, x32, x32, x16); sc_montsqrn(sc, x64, x32, 32); sc_montmul(sc, x64, x64, x32); sc_montsqrn(sc, x96, x64, 32); sc_montmul(sc, x96, x96, x32); sc_montsqrn(sc, z, x96, 96); sc_montmul(sc, z, z, x96); sc_montsqrn(sc, z, z, 0 + 2); /* 11 */ sc_montmul(sc, z, z, d1); sc_montsqrn(sc, z, z, 3 + 3); /* 000111 */ sc_montmul(sc, z, z, d3); sc_montsqrn(sc, z, z, 1 + 2); /* 011 */ sc_montmul(sc, z, z, d1); sc_montsqrn(sc, z, z, 3 + 2); /* 00011 */ sc_montmul(sc, z, z, d1); sc_montsqrn(sc, z, z, 1 + 4); /* 01001 */ sc_montmul(sc, z, z, d4); sc_montsqrn(sc, z, z, 0 + 4); /* 1011 */ sc_montmul(sc, z, z, d5); sc_montsqrn(sc, z, z, 6 + 4); /* 0000001111 */ sc_montmul(sc, z, z, d7); sc_montsqrn(sc, z, z, 0 + 3); /* 101 */ sc_montmul(sc, z, z, d2); sc_montsqrn(sc, z, z, 4 + 1); /* 00001 */ sc_montmul(sc, z, z, d0); sc_montsqrn(sc, z, z, 0 + 4); /* 1011 */ sc_montmul(sc, z, z, d5); sc_montsqrn(sc, z, z, 0 + 4); /* 1001 */ sc_montmul(sc, z, z, d4); sc_montsqrn(sc, z, z, 1 + 4); /* 01101 */ sc_montmul(sc, z, z, d6); sc_montsqrn(sc, z, z, 0 + 4); /* 1101 */ sc_montmul(sc, z, z, d6); sc_montsqrn(sc, z, z, 0 + 4); /* 1111 */ sc_montmul(sc, z, z, d7); sc_montsqrn(sc, z, z, 1 + 4); /* 01011 */ sc_montmul(sc, z, z, d5); sc_montsqrn(sc, z, z, 6 + 4); /* 0000001101 */ sc_montmul(sc, z, z, d6); sc_montsqrn(sc, z, z, 5 + 4); /* 000001101 */ sc_montmul(sc, z, z, d6); sc_montsqrn(sc, z, z, 0 + 4); /* 1011 */ sc_montmul(sc, z, z, d5); sc_montsqrn(sc, z, z, 2 + 4); /* 001001 */ sc_montmul(sc, z, z, d4); sc_montsqrn(sc, z, z, 2 + 1); /* 001 */ sc_montmul(sc, z, z, d0); sc_montsqrn(sc, z, z, 3 + 4); /* 0001011 */ sc_montmul(sc, z, z, d5); sc_montsqrn(sc, z, z, 4 + 3); /* 0000101 */ sc_montmul(sc, z, z, d2); sc_montsqrn(sc, z, z, 2 + 3); /* 00111 */ sc_montmul(sc, z, z, d3); sc_montsqrn(sc, z, z, 1 + 4); /* 01111 */ sc_montmul(sc, z, z, d7); sc_montsqrn(sc, z, z, 1 + 4); /* 01011 */ sc_montmul(sc, z, z, d5); sc_montsqrn(sc, z, z, 0 + 4); /* 1011 */ sc_montmul(sc, z, z, d5); sc_montsqrn(sc, z, z, 2 + 3); /* 00111 */ sc_montmul(sc, z, z, d3); sc_montsqrn(sc, z, z, 1 + 2); /* 011 */ sc_montmul(sc, z, z, d1); sc_montsqrn(sc, z, z, 5 + 2); /* 0000011 */ sc_montmul(sc, z, z, d1); sc_montsqrn(sc, z, z, 2 + 4); /* 001011 */ sc_montmul(sc, z, z, d5); sc_montsqrn(sc, z, z, 1 + 3); /* 0101 */ sc_montmul(sc, z, z, d2); sc_montsqrn(sc, z, z, 1 + 2); /* 011 */ sc_montmul(sc, z, z, d1); sc_montsqrn(sc, z, z, 2 + 2); /* 0011 */ sc_montmul(sc, z, z, d1); sc_montsqrn(sc, z, z, 2 + 2); /* 0011 */ sc_montmul(sc, z, z, d1); sc_montsqrn(sc, z, z, 3 + 3); /* 000101 */ sc_montmul(sc, z, z, d2); sc_montsqrn(sc, z, z, 2 + 3); /* 00101 */ sc_montmul(sc, z, z, d2); sc_montsqrn(sc, z, z, 2 + 3); /* 00101 */ sc_montmul(sc, z, z, d2); sc_montsqrn(sc, z, z, 0 + 2); /* 11 */ sc_montmul(sc, z, z, d1); sc_montsqrn(sc, z, z, 3 + 1); /* 0001 */ sc_montmul(sc, z, z, d0); sc_normal(sc, z, z); sc_cleanse(sc, d0); } static void q521_sc_invert(const scalar_field_t *sc, sc_t z, const sc_t x) { sc_t x1, x3, x5, x7, x9, x11, x13, x15, t1, t2; sc_mont(sc, x1, x); sc_montsqr(sc, t1, x1); sc_montmul(sc, x3, x1, t1); sc_montmul(sc, x5, x3, t1); sc_montmul(sc, x7, x5, t1); sc_montmul(sc, x9, x7, t1); sc_montmul(sc, x11, x9, t1); sc_montmul(sc, x13, x11, t1); sc_montmul(sc, x15, x13, t1); sc_montsqrn(sc, t1, x15, 4); /* x8 */ sc_montmul(sc, t1, t1, x15); sc_montsqrn(sc, t2, t1, 8); /* x16 */ sc_montmul(sc, t2, t2, t1); sc_montsqrn(sc, t1, t2, 16); /* x32 */ sc_montmul(sc, t1, t1, t2); sc_montsqrn(sc, t2, t1, 32); /* x64 */ sc_montmul(sc, t2, t2, t1); sc_montsqrn(sc, t1, t2, 64); /* x128 */ sc_montmul(sc, t1, t1, t2); sc_montsqrn(sc, z, t1, 128); /* x256 */ sc_montmul(sc, z, z, t1); sc_montsqrn(sc, z, z, 0 + 4); /* 1111 */ sc_montmul(sc, z, z, x15); sc_montsqrn(sc, z, z, 0 + 4); /* 1101 */ sc_montmul(sc, z, z, x13); sc_montsqrn(sc, z, z, 2 + 3); /* 00101 */ sc_montmul(sc, z, z, x5); sc_montsqrn(sc, z, z, 3 + 2); /* 00011 */ sc_montmul(sc, z, z, x3); sc_montsqrn(sc, z, z, 4 + 4); /* 00001101 */ sc_montmul(sc, z, z, x13); sc_montsqrn(sc, z, z, 4 + 4); /* 00001111 */ sc_montmul(sc, z, z, x15); sc_montsqrn(sc, z, z, 5 + 3); /* 00000111 */ sc_montmul(sc, z, z, x7); sc_montsqrn(sc, z, z, 1 + 1); /* 01 */ sc_montmul(sc, z, z, x1); sc_montsqrn(sc, z, z, 0 + 4); /* 1111 */ sc_montmul(sc, z, z, x15); sc_montsqrn(sc, z, z, 0 + 4); /* 1001 */ sc_montmul(sc, z, z, x9); sc_montsqrn(sc, z, z, 1 + 4); /* 01111 */ sc_montmul(sc, z, z, x15); sc_montsqrn(sc, z, z, 0 + 4); /* 1001 */ sc_montmul(sc, z, z, x9); sc_montsqrn(sc, z, z, 1 + 2); /* 011 */ sc_montmul(sc, z, z, x3); sc_montsqrn(sc, z, z, 2 + 4); /* 001101 */ sc_montmul(sc, z, z, x13); sc_montsqrn(sc, z, z, 1 + 4); /* 01101 */ sc_montmul(sc, z, z, x13); sc_montsqrn(sc, z, z, 0 + 4); /* 1111 */ sc_montmul(sc, z, z, x15); sc_montsqrn(sc, z, z, 0 + 4); /* 1111 */ sc_montmul(sc, z, z, x15); sc_montsqrn(sc, z, z, 2 + 2); /* 0011 */ sc_montmul(sc, z, z, x3); sc_montsqrn(sc, z, z, 9 + 3); /* 000000000101 */ sc_montmul(sc, z, z, x5); sc_montsqrn(sc, z, z, 2 + 1); /* 001 */ sc_montmul(sc, z, z, x1); sc_montsqrn(sc, z, z, 3 + 4); /* 0001111 */ sc_montmul(sc, z, z, x15); sc_montsqrn(sc, z, z, 1 + 3); /* 0111 */ sc_montmul(sc, z, z, x7); sc_montsqrn(sc, z, z, 4 + 4); /* 00001001 */ sc_montmul(sc, z, z, x9); sc_montsqrn(sc, z, z, 0 + 3); /* 101 */ sc_montmul(sc, z, z, x5); sc_montsqrn(sc, z, z, 2 + 3); /* 00101 */ sc_montmul(sc, z, z, x5); sc_montsqrn(sc, z, z, 0 + 4); /* 1101 */ sc_montmul(sc, z, z, x13); sc_montsqrn(sc, z, z, 6 + 3); /* 000000111 */ sc_montmul(sc, z, z, x7); sc_montsqrn(sc, z, z, 1 + 3); /* 0111 */ sc_montmul(sc, z, z, x7); sc_montsqrn(sc, z, z, 1 + 4); /* 01101 */ sc_montmul(sc, z, z, x13); sc_montsqrn(sc, z, z, 1 + 3); /* 0111 */ sc_montmul(sc, z, z, x7); sc_montsqrn(sc, z, z, 2 + 4); /* 001001 */ sc_montmul(sc, z, z, x9); sc_montsqrn(sc, z, z, 0 + 3); /* 101 */ sc_montmul(sc, z, z, x5); sc_montsqrn(sc, z, z, 0 + 2); /* 11 */ sc_montmul(sc, z, z, x3); sc_montsqrn(sc, z, z, 3 + 1); /* 0001 */ sc_montmul(sc, z, z, x1); sc_montsqrn(sc, z, z, 3 + 4); /* 0001001 */ sc_montmul(sc, z, z, x9); sc_montsqrn(sc, z, z, 0 + 4); /* 1001 */ sc_montmul(sc, z, z, x9); sc_montsqrn(sc, z, z, 0 + 2); /* 11 */ sc_montmul(sc, z, z, x3); sc_montsqrn(sc, z, z, 3 + 1); /* 0001 */ sc_montmul(sc, z, z, x1); sc_montsqrn(sc, z, z, 3 + 2); /* 00011 */ sc_montmul(sc, z, z, x3); sc_montsqrn(sc, z, z, 0 + 4); /* 1101 */ sc_montmul(sc, z, z, x13); sc_montsqrn(sc, z, z, 1 + 2); /* 011 */ sc_montmul(sc, z, z, x3); sc_montsqrn(sc, z, z, 0 + 3); /* 101 */ sc_montmul(sc, z, z, x5); sc_montsqrn(sc, z, z, 1 + 3); /* 0111 */ sc_montmul(sc, z, z, x7); sc_montsqrn(sc, z, z, 1 + 2); /* 011 */ sc_montmul(sc, z, z, x3); sc_montsqrn(sc, z, z, 1 + 4); /* 01101 */ sc_montmul(sc, z, z, x13); sc_montsqrn(sc, z, z, 0 + 4); /* 1111 */ sc_montmul(sc, z, z, x15); sc_montsqrn(sc, z, z, 1 + 4); /* 01101 */ sc_montmul(sc, z, z, x13); sc_montsqrn(sc, z, z, 0 + 2); /* 11 */ sc_montmul(sc, z, z, x3); sc_montsqrn(sc, z, z, 3 + 4); /* 0001111 */ sc_montmul(sc, z, z, x15); sc_montsqrn(sc, z, z, 1 + 4); /* 01001 */ sc_montmul(sc, z, z, x9); sc_montsqrn(sc, z, z, 3 + 4); /* 0001001 */ sc_montmul(sc, z, z, x9); sc_montsqrn(sc, z, z, 0 + 2); /* 11 */ sc_montmul(sc, z, z, x3); sc_montsqrn(sc, z, z, 4 + 2); /* 000011 */ sc_montmul(sc, z, z, x3); sc_montsqrn(sc, z, z, 2 + 1); /* 001 */ sc_montmul(sc, z, z, x1); sc_montsqrn(sc, z, z, 7 + 3); /* 0000000111 */ sc_montmul(sc, z, z, x7); sc_normal(sc, z, z); sc_cleanse(sc, x1); } static void secq256k1_sc_invert(const scalar_field_t *sc, sc_t z, const sc_t x) { /* https://briansmith.org/ecc-inversion-addition-chains-01#secp256k1_scalar_inversion */ /* https://github.com/bitcoin-core/secp256k1/blob/master/src/scalar_impl.h */ sc_t x2, x3, x6, x8, x14, x28, x56, x112, x126; sc_t u1, u2, u5, u9, u11, u13; sc_mont(sc, u1, x); sc_montsqr(sc, u2, u1); sc_montmul(sc, x2, u2, u1); sc_montmul(sc, u5, u2, x2); sc_montmul(sc, x3, u5, u2); sc_montmul(sc, u9, x3, u2); sc_montmul(sc, u11, u9, u2); sc_montmul(sc, u13, u11, u2); sc_montsqr(sc, x6, u13); sc_montsqr(sc, x6, x6); sc_montmul(sc, x6, x6, u11); sc_montsqr(sc, x8, x6); sc_montsqr(sc, x8, x8); sc_montmul(sc, x8, x8, x2); sc_montsqr(sc, x14, x8); sc_montsqrn(sc, x14, x14, 5); sc_montmul(sc, x14, x14, x6); sc_montsqr(sc, x28, x14); sc_montsqrn(sc, x28, x28, 13); sc_montmul(sc, x28, x28, x14); sc_montsqr(sc, x56, x28); sc_montsqrn(sc, x56, x56, 27); sc_montmul(sc, x56, x56, x28); sc_montsqr(sc, x112, x56); sc_montsqrn(sc, x112, x112, 55); sc_montmul(sc, x112, x112, x56); sc_montsqr(sc, x126, x112); sc_montsqrn(sc, x126, x126, 13); sc_montmul(sc, z, x126, x14); sc_montsqrn(sc, z, z, 0 + 3); /* 101 */ sc_montmul(sc, z, z, u5); sc_montsqrn(sc, z, z, 1 + 3); /* 0111 */ sc_montmul(sc, z, z, x3); sc_montsqrn(sc, z, z, 1 + 3); /* 0101 */ sc_montmul(sc, z, z, u5); sc_montsqrn(sc, z, z, 1 + 4); /* 01011 */ sc_montmul(sc, z, z, u11); sc_montsqrn(sc, z, z, 0 + 4); /* 1011 */ sc_montmul(sc, z, z, u11); sc_montsqrn(sc, z, z, 1 + 3); /* 0111 */ sc_montmul(sc, z, z, x3); sc_montsqrn(sc, z, z, 2 + 3); /* 00111 */ sc_montmul(sc, z, z, x3); sc_montsqrn(sc, z, z, 2 + 4); /* 001101 */ sc_montmul(sc, z, z, u13); sc_montsqrn(sc, z, z, 1 + 3); /* 0101 */ sc_montmul(sc, z, z, u5); sc_montsqrn(sc, z, z, 0 + 3); /* 111 */ sc_montmul(sc, z, z, x3); sc_montsqrn(sc, z, z, 1 + 4); /* 01001 */ sc_montmul(sc, z, z, u9); sc_montsqrn(sc, z, z, 3 + 3); /* 000101 */ sc_montmul(sc, z, z, u5); sc_montsqrn(sc, z, z, 7 + 3); /* 0000000111 */ sc_montmul(sc, z, z, x3); sc_montsqrn(sc, z, z, 1 + 3); /* 0111 */ sc_montmul(sc, z, z, x3); sc_montsqrn(sc, z, z, 1 + 8); /* 011111111 */ sc_montmul(sc, z, z, x8); sc_montsqrn(sc, z, z, 1 + 4); /* 01001 */ sc_montmul(sc, z, z, u9); sc_montsqrn(sc, z, z, 2 + 4); /* 001011 */ sc_montmul(sc, z, z, u11); sc_montsqrn(sc, z, z, 0 + 4); /* 1101 */ sc_montmul(sc, z, z, u13); sc_montsqrn(sc, z, z, 0 + 5); /* 11 */ sc_montmul(sc, z, z, x2); sc_montsqrn(sc, z, z, 2 + 4); /* 001101 */ sc_montmul(sc, z, z, u13); sc_montsqrn(sc, z, z, 6 + 4); /* 0000001101 */ sc_montmul(sc, z, z, u13); sc_montsqrn(sc, z, z, 0 + 4); /* 1001 */ sc_montmul(sc, z, z, u9); sc_montsqrn(sc, z, z, 5 + 1); /* 000001 */ sc_montmul(sc, z, z, u1); sc_montsqrn(sc, z, z, 2 + 6); /* 00111111 */ sc_montmul(sc, z, z, x6); sc_normal(sc, z, z); sc_cleanse(sc, u1); } static void q25519_sc_invert(const scalar_field_t *sc, sc_t z, const sc_t x) { /* https://briansmith.org/ecc-inversion-addition-chains-01#curve25519_scalar_inversion */ /* https://github.com/dalek-cryptography/curve25519-dalek/blob/master/src/scalar.rs */ sc_t x1, x2 /* 10 */, x3 /* 11 */, x4 /* 100 */, x5 /* 101 */, x7 /* 111 */; sc_t x9 /* 1001 */, x11 /* 1011 */, x15 /* 1111 */; sc_mont(sc, x1, x); sc_montsqr(sc, x2, x1); sc_montsqr(sc, x4, x2); sc_montmul(sc, x3, x2, x1); sc_montmul(sc, x5, x2, x3); sc_montmul(sc, x7, x2, x5); sc_montmul(sc, x9, x2, x7); sc_montmul(sc, x11, x2, x9); sc_montmul(sc, x15, x4, x11); sc_montmul(sc, z, x15, x1); sc_montsqrn(sc, z, z, 123 + 3); /* 123x0 101 */ sc_montmul(sc, z, z, x5); sc_montsqrn(sc, z, z, 2 + 2); /* 0011 */ sc_montmul(sc, z, z, x3); sc_montsqrn(sc, z, z, 1 + 4); /* 01111 */ sc_montmul(sc, z, z, x15); sc_montsqrn(sc, z, z, 1 + 4); /* 01111 */ sc_montmul(sc, z, z, x15); sc_montsqrn(sc, z, z, 0 + 4); /* 1001 */ sc_montmul(sc, z, z, x9); sc_montsqrn(sc, z, z, 0 + 2); /* 11 */ sc_montmul(sc, z, z, x3); sc_montsqrn(sc, z, z, 1 + 4); /* 01111 */ sc_montmul(sc, z, z, x15); sc_montsqrn(sc, z, z, 1 + 3); /* 0101 */ sc_montmul(sc, z, z, x5); sc_montsqrn(sc, z, z, 3 + 3); /* 000101 */ sc_montmul(sc, z, z, x5); sc_montsqrn(sc, z, z, 0 + 3); /* 111 */ sc_montmul(sc, z, z, x7); sc_montsqrn(sc, z, z, 1 + 4); /* 01111 */ sc_montmul(sc, z, z, x15); sc_montsqrn(sc, z, z, 2 + 3); /* 00111 */ sc_montmul(sc, z, z, x7); sc_montsqrn(sc, z, z, 2 + 2); /* 0011 */ sc_montmul(sc, z, z, x3); sc_montsqrn(sc, z, z, 1 + 4); /* 01011 */ sc_montmul(sc, z, z, x11); sc_montsqrn(sc, z, z, 2 + 4); /* 001011 */ sc_montmul(sc, z, z, x11); sc_montsqrn(sc, z, z, 6 + 4); /* 0000001001 */ sc_montmul(sc, z, z, x9); sc_montsqrn(sc, z, z, 2 + 2); /* 0011 */ sc_montmul(sc, z, z, x3); sc_montsqrn(sc, z, z, 3 + 2); /* 00011 */ sc_montmul(sc, z, z, x3); sc_montsqrn(sc, z, z, 3 + 2); /* 00011 */ sc_montmul(sc, z, z, x3); sc_montsqrn(sc, z, z, 1 + 4); /* 01001 */ sc_montmul(sc, z, z, x9); sc_montsqrn(sc, z, z, 1 + 3); /* 0111 */ sc_montmul(sc, z, z, x7); sc_montsqrn(sc, z, z, 2 + 4); /* 001111 */ sc_montmul(sc, z, z, x15); sc_montsqrn(sc, z, z, 1 + 4); /* 01011 */ sc_montmul(sc, z, z, x11); sc_montsqrn(sc, z, z, 0 + 3); /* 101 */ sc_montmul(sc, z, z, x5); sc_montsqrn(sc, z, z, 2 + 4); /* 001111 */ sc_montmul(sc, z, z, x15); sc_montsqrn(sc, z, z, 0 + 3); /* 101 */ sc_montmul(sc, z, z, x5); sc_montsqrn(sc, z, z, 1 + 2); /* 011 */ sc_montmul(sc, z, z, x3); sc_normal(sc, z, z); sc_cleanse(sc, x1); } static void q448_sc_invert(const scalar_field_t *sc, sc_t z, const sc_t x) { sc_t x1, x3, x5, x7, x9, x11, x13, x15, t1, t2; sc_mont(sc, x1, x); sc_montsqr(sc, t1, x1); sc_montmul(sc, x3, x1, t1); sc_montmul(sc, x5, x3, t1); sc_montmul(sc, x7, x5, t1); sc_montmul(sc, x9, x7, t1); sc_montmul(sc, x11, x9, t1); sc_montmul(sc, x13, x11, t1); sc_montmul(sc, x15, x13, t1); sc_montsqrn(sc, t1, x15, 2); /* x6 */ sc_montmul(sc, t1, t1, x3); sc_montsqrn(sc, t2, t1, 6); /* x12 */ sc_montmul(sc, t2, t2, t1); sc_montsqrn(sc, t1, t2, 12); /* x24 */ sc_montmul(sc, t1, t1, t2); sc_montsqrn(sc, t1, t1, 3); /* x27 */ sc_montmul(sc, t1, t1, x7); sc_montsqrn(sc, t2, t1, 27); /* x54 */ sc_montmul(sc, t2, t2, t1); sc_montsqrn(sc, t1, t2, 54); /* x108 */ sc_montmul(sc, t1, t1, t2); sc_montsqrn(sc, t1, t1, 3); /* x111 */ sc_montmul(sc, t1, t1, x7); sc_montsqrn(sc, z, t1, 111); /* x222 */ sc_montmul(sc, z, z, t1); sc_montsqrn(sc, z, z, 1 + 4); /* 01111 */ sc_montmul(sc, z, z, x15); sc_montsqrn(sc, z, z, 0 + 4); /* 1001 */ sc_montmul(sc, z, z, x9); sc_montsqrn(sc, z, z, 0 + 4); /* 1001 */ sc_montmul(sc, z, z, x9); sc_montsqrn(sc, z, z, 1 + 1); /* 01 */ sc_montmul(sc, z, z, x1); sc_montsqrn(sc, z, z, 3 + 1); /* 0001 */ sc_montmul(sc, z, z, x1); sc_montsqrn(sc, z, z, 3 + 1); /* 0001 */ sc_montmul(sc, z, z, x1); sc_montsqrn(sc, z, z, 0 + 4); /* 1111 */ sc_montmul(sc, z, z, x15); sc_montsqrn(sc, z, z, 1 + 4); /* 01001 */ sc_montmul(sc, z, z, x9); sc_montsqrn(sc, z, z, 0 + 2); /* 11 */ sc_montmul(sc, z, z, x3); sc_montsqrn(sc, z, z, 3 + 1); /* 0001 */ sc_montmul(sc, z, z, x1); sc_montsqrn(sc, z, z, 3 + 4); /* 0001001 */ sc_montmul(sc, z, z, x9); sc_montsqrn(sc, z, z, 0 + 4); /* 1101 */ sc_montmul(sc, z, z, x13); sc_montsqrn(sc, z, z, 0 + 4); /* 1011 */ sc_montmul(sc, z, z, x11); sc_montsqrn(sc, z, z, 1 + 4); /* 01101 */ sc_montmul(sc, z, z, x13); sc_montsqrn(sc, z, z, 2 + 4); /* 001001 */ sc_montmul(sc, z, z, x9); sc_montsqrn(sc, z, z, 0 + 3); /* 101 */ sc_montmul(sc, z, z, x5); sc_montsqrn(sc, z, z, 1 + 3); /* 0111 */ sc_montmul(sc, z, z, x7); sc_montsqrn(sc, z, z, 1 + 4); /* 01101 */ sc_montmul(sc, z, z, x13); sc_montsqrn(sc, z, z, 1 + 2); /* 011 */ sc_montmul(sc, z, z, x3); sc_montsqrn(sc, z, z, 3 + 4); /* 0001101 */ sc_montmul(sc, z, z, x13); sc_montsqrn(sc, z, z, 0 + 3); /* 101 */ sc_montmul(sc, z, z, x5); sc_montsqrn(sc, z, z, 2 + 1); /* 001 */ sc_montmul(sc, z, z, x1); sc_montsqrn(sc, z, z, 6 + 1); /* 0000001 */ sc_montmul(sc, z, z, x1); sc_montsqrn(sc, z, z, 4 + 4); /* 00001011 */ sc_montmul(sc, z, z, x11); sc_montsqrn(sc, z, z, 1 + 2); /* 011 */ sc_montmul(sc, z, z, x3); sc_montsqrn(sc, z, z, 2 + 2); /* 0011 */ sc_montmul(sc, z, z, x3); sc_montsqrn(sc, z, z, 4 + 1); /* 00001 */ sc_montmul(sc, z, z, x1); sc_montsqrn(sc, z, z, 2 + 3); /* 00111 */ sc_montmul(sc, z, z, x7); sc_montsqrn(sc, z, z, 2 + 3); /* 00101 */ sc_montmul(sc, z, z, x5); sc_montsqrn(sc, z, z, 3 + 4); /* 0001101 */ sc_montmul(sc, z, z, x13); sc_montsqrn(sc, z, z, 0 + 2); /* 11 */ sc_montmul(sc, z, z, x3); sc_montsqrn(sc, z, z, 3 + 4); /* 0001011 */ sc_montmul(sc, z, z, x11); sc_montsqrn(sc, z, z, 3 + 4); /* 0001111 */ sc_montmul(sc, z, z, x15); sc_montsqrn(sc, z, z, 1 + 3); /* 0101 */ sc_montmul(sc, z, z, x5); sc_montsqrn(sc, z, z, 1 + 3); /* 0101 */ sc_montmul(sc, z, z, x5); sc_montsqrn(sc, z, z, 2 + 1); /* 001 */ sc_montmul(sc, z, z, x1); sc_montsqrn(sc, z, z, 3 + 4); /* 0001101 */ sc_montmul(sc, z, z, x13); sc_montsqrn(sc, z, z, 0 + 3); /* 111 */ sc_montmul(sc, z, z, x7); sc_montsqrn(sc, z, z, 3 + 2); /* 00011 */ sc_montmul(sc, z, z, x3); sc_montsqrn(sc, z, z, 4 + 3); /* 0000101 */ sc_montmul(sc, z, z, x5); sc_montsqrn(sc, z, z, 2 + 1); /* 001 */ sc_montmul(sc, z, z, x1); sc_montsqrn(sc, z, z, 2 + 3); /* 00101 */ sc_montmul(sc, z, z, x5); sc_montsqrn(sc, z, z, 1 + 3); /* 0101 */ sc_montmul(sc, z, z, x5); sc_montsqrn(sc, z, z, 1 + 4); /* 01101 */ sc_montmul(sc, z, z, x13); sc_montsqrn(sc, z, z, 1 + 2); /* 011 */ sc_montmul(sc, z, z, x3); sc_montsqrn(sc, z, z, 4 + 1); /* 00001 */ sc_montmul(sc, z, z, x1); sc_montsqrn(sc, z, z, 3 + 4); /* 0001001 */ sc_montmul(sc, z, z, x9); sc_montsqrn(sc, z, z, 0 + 3); /* 111 */ sc_montmul(sc, z, z, x7); sc_montsqrn(sc, z, z, 3 + 1); /* 0001 */ sc_montmul(sc, z, z, x1); sc_normal(sc, z, z); sc_cleanse(sc, x1); } static void q251_sc_invert(const scalar_field_t *sc, sc_t z, const sc_t x) { sc_t x1, x3, x5, x7, x9, x11, x13, x15, t1, t2; sc_mont(sc, x1, x); sc_montsqr(sc, t1, x1); sc_montmul(sc, x3, x1, t1); sc_montmul(sc, x5, x3, t1); sc_montmul(sc, x7, x5, t1); sc_montmul(sc, x9, x7, t1); sc_montmul(sc, x11, x9, t1); sc_montmul(sc, x13, x11, t1); sc_montmul(sc, x15, x13, t1); sc_montsqrn(sc, t1, x15, 2); /* x6 */ sc_montmul(sc, t1, t1, x3); sc_montsqrn(sc, t2, t1, 6); /* x12 */ sc_montmul(sc, t2, t2, t1); sc_montsqrn(sc, t2, t2, 3); /* x15 */ sc_montmul(sc, t2, t2, x7); sc_montsqrn(sc, t1, t2, 15); /* x30 */ sc_montmul(sc, t1, t1, t2); sc_montsqrn(sc, t2, t1, 30); /* x60 */ sc_montmul(sc, t2, t2, t1); sc_montsqrn(sc, z, t2, 60); /* x120 */ sc_montmul(sc, z, z, t2); sc_montsqrn(sc, z, z, 0 + 4); /* 1111 */ sc_montmul(sc, z, z, x15); sc_montsqrn(sc, z, z, 0 + 3); /* 101 */ sc_montmul(sc, z, z, x5); sc_montsqrn(sc, z, z, 0 + 4); /* 1101 */ sc_montmul(sc, z, z, x13); sc_montsqrn(sc, z, z, 0 + 3); /* 111 */ sc_montmul(sc, z, z, x7); sc_montsqrn(sc, z, z, 2 + 3); /* 00101 */ sc_montmul(sc, z, z, x5); sc_montsqrn(sc, z, z, 0 + 4); /* 1001 */ sc_montmul(sc, z, z, x9); sc_montsqrn(sc, z, z, 1 + 3); /* 0111 */ sc_montmul(sc, z, z, x7); sc_montsqrn(sc, z, z, 3 + 4); /* 0001001 */ sc_montmul(sc, z, z, x9); sc_montsqrn(sc, z, z, 0 + 4); /* 1011 */ sc_montmul(sc, z, z, x11); sc_montsqrn(sc, z, z, 0 + 4); /* 1111 */ sc_montmul(sc, z, z, x15); sc_montsqrn(sc, z, z, 0 + 3); /* 101 */ sc_montmul(sc, z, z, x5); sc_montsqrn(sc, z, z, 2 + 2); /* 0011 */ sc_montmul(sc, z, z, x3); sc_montsqrn(sc, z, z, 5 + 3); /* 00000111 */ sc_montmul(sc, z, z, x7); sc_montsqrn(sc, z, z, 2 + 2); /* 0011 */ sc_montmul(sc, z, z, x3); sc_montsqrn(sc, z, z, 1 + 4); /* 01001 */ sc_montmul(sc, z, z, x9); sc_montsqrn(sc, z, z, 3 + 1); /* 0001 */ sc_montmul(sc, z, z, x1); sc_montsqrn(sc, z, z, 2 + 3); /* 00101 */ sc_montmul(sc, z, z, x5); sc_montsqrn(sc, z, z, 3 + 4); /* 0001001 */ sc_montmul(sc, z, z, x9); sc_montsqrn(sc, z, z, 0 + 3); /* 101 */ sc_montmul(sc, z, z, x5); sc_montsqrn(sc, z, z, 1 + 1); /* 01 */ sc_montmul(sc, z, z, x1); sc_montsqrn(sc, z, z, 3 + 4); /* 0001011 */ sc_montmul(sc, z, z, x11); sc_montsqrn(sc, z, z, 0 + 4); /* 1111 */ sc_montmul(sc, z, z, x15); sc_montsqrn(sc, z, z, 0 + 3); /* 101 */ sc_montmul(sc, z, z, x5); sc_montsqrn(sc, z, z, 3 + 3); /* 000101 */ sc_montmul(sc, z, z, x5); sc_montsqrn(sc, z, z, 0 + 4); /* 1001 */ sc_montmul(sc, z, z, x9); sc_montsqrn(sc, z, z, 0 + 4); /* 1011 */ sc_montmul(sc, z, z, x11); sc_montsqrn(sc, z, z, 2 + 4); /* 001001 */ sc_montmul(sc, z, z, x9); sc_montsqrn(sc, z, z, 1 + 2); /* 011 */ sc_montmul(sc, z, z, x3); sc_montsqrn(sc, z, z, 1 + 4); /* 01111 */ sc_montmul(sc, z, z, x15); sc_normal(sc, z, z); sc_cleanse(sc, x1); } ======================= File: node_modules/bcrypto/deps/secp256k1/include/secp256k1_extra.h ======================= <filename>node_modules/bcrypto/deps/secp256k1/include/secp256k1_extra.h #ifndef SECP256K1_EXTRA_H #define SECP256K1_EXTRA_H #include "secp256k1.h" #include "secp256k1_extrakeys.h" #ifdef __cplusplus extern "C" { #endif /** Generates a private key from entropy. * * Returns: 1 if seckey was successfully generated and 0 otherwise * Args: ctx: pointer to a context object * Out: output: pointer to a 32-byte array to be filled by the function * In: entropy: pointer to a 32-byte random seed. */ SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_seckey_generate(const secp256k1_context *ctx, unsigned char *output, const unsigned char *entropy) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3); /** Inverts a private key in place. * * Returns: 1 if seckey was successfully inverted and 0 otherwise * Args: ctx: pointer to a context object * In/Out: seckey: pointer to the 32-byte private key to be inverted. The private * key should be valid according to secp256k1_ec_seckey_verify * (cannot be NULL) */ SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_seckey_invert(const secp256k1_context *ctx, unsigned char *seckey) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2); /** Exports a private key to a byte array. * * Returns: 1 if key was successfully exported and 0 otherwise * Args: ctx: pointer to a context object * Out: output: pointer to a 32-byte array to be filled by the function * In: seckey: pointer to a 32-byte array containing a private key */ SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_seckey_export(const secp256k1_context *ctx, unsigned char *output, const unsigned char *seckey) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3); /** Imports a private key from a byte array. * * Returns: 1 if key was successfully imported and 0 otherwise * Args: ctx: pointer to a context object * Out: output: pointer to a 32-byte array to be filled by the function * In: bytes: pointer to an arbitrary sized byte array * len: byte array length */ SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_seckey_import(const secp256k1_context *ctx, unsigned char *output, const unsigned char *bytes, size_t len) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2); /** Exports a public key to x/y byte arrays. * * Returns: 1 if key was successfully exported and 0 otherwise * Args: ctx: pointer to a context object * Out: x: pointer to a 32-byte array to be filled by the function * y: pointer to a 32-byte array to be filled by the function * In: pubkey: pointer to a pubkey struct */ SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_pubkey_export(const secp256k1_context *ctx, unsigned char *x, unsigned char *y, const secp256k1_pubkey *pubkey) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4); /** Imports a public key from x/y byte arrays. * * Returns: 1 if key was successfully imported and 0 otherwise * Args: ctx: pointer to a context object * Out: pubkey: pointer to a pubkey struct * In: x: pointer to an arbitrary sized byte array * x_len: byte array length * y: pointer to an arbitrary sized byte array * y_len: byte array length * sign: integer representing oddness of the y-coordinate */ SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_pubkey_import(const secp256k1_context *ctx, secp256k1_pubkey *pubkey, const unsigned char *x, size_t x_len, const unsigned char *y, size_t y_len, int sign) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2); /** Get the secret key from a keypair. * * Returns: 0 if the arguments are invalid. 1 otherwise. * Args: ctx: pointer to a context object (cannot be NULL) * Out: seckey: pointer to a 32-byte array. If 1 is returned, it is set to * the keypair secret key. If not, it's set to an invalid value. * (cannot be NULL) * In: keypair: pointer to a keypair (cannot be NULL) */ SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_keypair_priv(const secp256k1_context* ctx, unsigned char *seckey, const secp256k1_keypair *keypair) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2); /** Converts a secp256k1_xonly_pubkey into a secp256k1_pubkey. * * Returns: 1 if the public key was successfully converted * 0 otherwise * * Args: ctx: pointer to a context object (cannot be NULL) * Out: pubkey: pointer to a public key object for placing the * converted public key (cannot be NULL) * pk_parity: pointer to an integer that will be set to 1 if the point * encoded by xonly_pubkey is the negation of the pubkey and * set to 0 otherwise. (can be NULL) * In: xonly_pubkey: pointer to an x-only public key that is converted * (cannot be NULL) */ SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_pubkey_from_xonly_pubkey(const secp256k1_context *ctx, secp256k1_pubkey *pubkey, const secp256k1_xonly_pubkey *xonly_pubkey) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3); /** Exports an x-only public key to x/y byte arrays. * * Returns: 1 if key was successfully exported and 0 otherwise * Args: ctx: pointer to a context object * Out: x: pointer to a 32-byte array to be filled by the function * y: pointer to a 32-byte array to be filled by the function * In: pubkey: pointer to an x-only pubkey struct */ SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_xonly_pubkey_export(const secp256k1_context *ctx, unsigned char *x, unsigned char *y, const secp256k1_xonly_pubkey *pubkey) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4); /** Imports an x-only public key from x/y byte arrays. * * Returns: 1 if key was successfully imported and 0 otherwise * Args: ctx: pointer to a context object * Out: pubkey: pointer to an x-only pubkey struct * In: x: pointer to an arbitrary sized byte array * x_len: byte array length * y: pointer to an arbitrary sized byte array * y_len: byte array length * sign: integer representing oddness of the y-coordinate */ SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_xonly_pubkey_import(const secp256k1_context *ctx, secp256k1_xonly_pubkey *pubkey, const unsigned char *x, size_t x_len, const unsigned char *y, size_t y_len) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2); /** Truncates an ECDSA message. * * Args: ctx: pointer to a context object * Out: output: pointer to a 32-byte array * In: msg: pointer to an arbitrary sized byte array * len: byte array length */ void secp256k1_ecdsa_reduce(const secp256k1_context *ctx, unsigned char *output, const unsigned char *msg, size_t len) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2); #ifdef __cplusplus } #endif #endif /* SECP256K1_EXTRA_H */ ======================= File: node_modules/bcrypto/deps/torsion/src/drbg.c ======================= <filename>node_modules/bcrypto/deps/torsion/src/drbg.c /*! * drbg.c - drbg implementations for libtorsion * Copyright (c) 2020, <NAME> (MIT License). * https://github.com/bcoin-org/libtorsion * * Resources: * https://tools.ietf.org/html/rfc6979 * https://csrc.nist.gov/publications/detail/sp/800-90a/archive/2012-01-23 */ #include <stdlib.h> #include <stdint.h> #include <string.h> #include <torsion/cipher.h> #include <torsion/drbg.h> #include <torsion/hash.h> #include "bio.h" #include "internal.h" /* * HMAC-DRBG */ static void hmac_drbg_update(hmac_drbg_t *drbg, const unsigned char *seed, size_t seed_len) { static const unsigned char zero[1] = {0x00}; static const unsigned char one[1] = {0x01}; hmac_init(&drbg->kmac, drbg->type, drbg->K, drbg->size); hmac_update(&drbg->kmac, drbg->V, drbg->size); hmac_update(&drbg->kmac, zero, 1); hmac_update(&drbg->kmac, seed, seed_len); hmac_final(&drbg->kmac, drbg->K); hmac_init(&drbg->kmac, drbg->type, drbg->K, drbg->size); hmac_update(&drbg->kmac, drbg->V, drbg->size); hmac_final(&drbg->kmac, drbg->V); if (seed_len > 0) { hmac_init(&drbg->kmac, drbg->type, drbg->K, drbg->size); hmac_update(&drbg->kmac, drbg->V, drbg->size); hmac_update(&drbg->kmac, one, 1); hmac_update(&drbg->kmac, seed, seed_len); hmac_final(&drbg->kmac, drbg->K); hmac_init(&drbg->kmac, drbg->type, drbg->K, drbg->size); hmac_update(&drbg->kmac, drbg->V, drbg->size); hmac_final(&drbg->kmac, drbg->V); } hmac_init(&drbg->kmac, drbg->type, drbg->K, drbg->size); } void hmac_drbg_init(hmac_drbg_t *drbg, hash_id_t type, const unsigned char *seed, size_t seed_len) { size_t size = hash_output_size(type); CHECK(size!= 0); drbg->type = type; drbg->size = size; memset(drbg->K, 0x00, drbg->size); memset(drbg->V, 0x01, drbg->size); /* Zero for struct assignment. */ memset(&drbg->kmac, 0, sizeof(drbg->kmac)); hmac_drbg_update(drbg, seed, seed_len); } void hmac_drbg_reseed(hmac_drbg_t *drbg, const unsigned char *seed, size_t seed_len) { hmac_drbg_update(drbg, seed, seed_len); } void hmac_drbg_generate(hmac_drbg_t *drbg, void *out, size_t len, const unsigned char *add, size_t add_len) { unsigned char *raw = (unsigned char *)out; size_t size = drbg->size; hmac_t kmac; if (add_len > 0) hmac_drbg_update(drbg, add, add_len); while (len > 0) { kmac = drbg->kmac; hmac_update(&kmac, drbg->V, size); hmac_final(&kmac, drbg->V); if (size > len) size = len; memcpy(raw, drbg->V, size); raw += size; len -= size; } hmac_drbg_update(drbg, add, add_len); } void hmac_drbg_rng(void *out, size_t size, void *arg) { hmac_drbg_generate((hmac_drbg_t *)arg, out, size, NULL, 0); } /* * Hash-DRBG */ void hash_drbg_init(hash_drbg_t *drbg, hash_id_t type, const unsigned char *seed, size_t seed_len) { size_t size = hash_output_size(type); size_t length = size <= 32? 55 : 111; unsigned char output[165]; /* ceil(111 / 55) * 55 */ unsigned char state[6]; size_t i, blocks; CHECK(size!= 0); drbg->type = type; drbg->size = size; drbg->length = length; state[0] = 0x01; state[1] = (length >> 21) & 0xff; state[2] = (length >> 13) & 0xff; state[3] = (length >> 5) & 0xff; state[4] = (length & 0x1f) << 3; state[5] = 0x00; blocks = (length + size - 1) / size; ASSERT(sizeof(output) >= blocks * size); for (i = 0; i < blocks; i++) { hash_init(&drbg->hash, drbg->type); hash_update(&drbg->hash, state, 5); hash_update(&drbg->hash, seed, seed_len); hash_final(&drbg->hash, output + i * size, size); state[0] += 1; } memcpy(drbg->V, output, length); state[0] = 0x01; state[5] = 0x00; for (i = 0; i < blocks; i++) { hash_init(&drbg->hash, drbg->type); hash_update(&drbg->hash, state, 6); hash_update(&drbg->hash, drbg->V, length); hash_final(&drbg->hash, output + i * size, size); state[0] += 1; } memcpy(drbg->C, output, length); drbg->rounds = 1; } void hash_drbg_reseed(hash_drbg_t *drbg, const unsigned char *seed, size_t seed_len) { size_t size = drbg->size; size_t length = drbg->length; unsigned char output[165]; /* ceil(111 / 55) * 55 */ unsigned char state[6]; size_t i, blocks; state[0] = 0x01; state[1] = (length >> 21) & 0xff; state[2] = (length >> 13) & 0xff; state[3] = (length >> 5) & 0xff; state[4] = (length & 0x1f) << 3; state[5] = 0x01; blocks = (length + size - 1) / size; ASSERT(sizeof(output) >= blocks * size); for (i = 0; i < blocks; i++) { hash_init(&drbg->hash, drbg->type); hash_update(&drbg->hash, state, 6); hash_update(&drbg->hash, drbg->V, length); hash_update(&drbg->hash, seed, seed_len); hash_final(&drbg->hash, output + i * size, size); state[0] += 1; } memcpy(drbg->V, output, length); state[0] = 0x01; state[5] = 0x00; for (i = 0; i < blocks; i++) { hash_init(&drbg->hash, drbg->type); hash_update(&drbg->hash, state, 6); hash_update(&drbg->hash, drbg->V, length); hash_final(&drbg->hash, output + i * size, size); state[0] += 1; } memcpy(drbg->C, output, length); drbg->rounds = 1; } static void accumulate(unsigned char *dst, size_t dlen, const unsigned char *src, size_t slen) { unsigned int c = 0; ASSERT(dlen >= slen); while (slen > 0) { c += (unsigned int)src[--slen] + dst[--dlen]; dst[dlen] = c & 0xff; c >>= 8; } while (dlen > 0) { c += (unsigned int)dst[--dlen]; dst[dlen] = c & 0xff; c >>= 8; } } static void hash_drbg_update(hash_drbg_t *drbg) { static const unsigned char three[1] = {0x03}; unsigned char H[HASH_MAX_OUTPUT_SIZE]; unsigned char L[8]; hash_init(&drbg->hash, drbg->type); hash_update(&drbg->hash, three, 1); hash_update(&drbg->hash, drbg->V, drbg->length); hash_final(&drbg->hash, H, drbg->size); write64be(L, drbg->rounds); /* V = V + H + C + L */ accumulate(drbg->V, drbg->length, H, drbg->size); accumulate(drbg->V, drbg->length, drbg->C, drbg->length); accumulate(drbg->V, drbg->length, L, 8); } void hash_drbg_generate(hash_drbg_t *drbg, void *out, size_t len, const unsigned char *add, size_t add_len) { static const unsigned char one[1] = {0x01}; static const unsigned char two[1] = {0x02}; unsigned char *raw = (unsigned char *)out; unsigned char H[HASH_MAX_OUTPUT_SIZE]; unsigned char V[111]; if (add_len > 0) { hash_init(&drbg->hash, drbg->type); hash_update(&drbg->hash, two, 1); hash_update(&drbg->hash, drbg->V, drbg->length); hash_update(&drbg->hash, add, add_len); hash_final(&drbg->hash, H, drbg->size); accumulate(drbg->V, drbg->length, H, drbg->size); } memcpy(V, drbg->V, drbg->length); while (len > 0) { hash_init(&drbg->hash, drbg->type); hash_update(&drbg->hash, V, drbg->length); if (len < drbg->size) { hash_final(&drbg->hash, H, drbg->size); memcpy(raw, H, len); break; } hash_final(&drbg->hash, raw, drbg->size); accumulate(V, drbg->length, one, 1); raw += drbg->size; len -= drbg->size; } hash_drbg_update(drbg); drbg->rounds += 1; } void hash_drbg_rng(void *out, size_t size, void *arg) { hash_drbg_generate((hash_drbg_t *)arg, out, size, NULL, 0); } /* * CTR-DRBG */ #define MAX_KEY_SIZE 32 #define MAX_BLK_SIZE 16 #define MAX_ENT_SIZE (MAX_KEY_SIZE + MAX_BLK_SIZE) #define MAX_NONCE_SIZE 512 #define MAX_SER_SIZE (MAX_NONCE_SIZE * 2 + MAX_BLK_SIZE * 2) static void ctr_drbg_rekey(ctr_drbg_t *drbg, const unsigned char *key, const unsigned char *iv) { aes_init_encrypt(&drbg->aes, drbg->key_size * 8, key); memcpy(drbg->state, iv, drbg->blk_size); } static void ctr_drbg_encrypt(ctr_drbg_t *drbg, unsigned char *out) { increment_be(drbg->state, drbg->blk_size); aes_encrypt(&drbg->aes, out, drbg->state); } static void ctr_drbg_update(ctr_drbg_t *drbg, const unsigned char *seed, size_t seed_len) { size_t i; if (seed_len > drbg->ent_size) seed_len = drbg->ent_size; for (i = 0; i < drbg->ent_size; i += drbg->blk_size) ctr_drbg_encrypt(drbg, drbg->KV + i); for (i = 0; i < seed_len; i++) drbg->KV[i] ^= seed[i]; ctr_drbg_rekey(drbg, drbg->K, drbg->V); } static void ctr_drbg_serialize(ctr_drbg_t *drbg, unsigned char *out, size_t *blocks, const unsigned char *nonce, size_t nonce_len, const unsigned char *pers, size_t pers_len) { size_t N = drbg->ent_size; size_t L, size; if (nonce_len > MAX_NONCE_SIZE) nonce_len = MAX_NONCE_SIZE; if (pers_len > MAX_NONCE_SIZE) pers_len = MAX_NONCE_SIZE; L = nonce_len + pers_len; size = drbg->blk_size + 4 + 4 + L + 1; if (size % drbg->blk_size) size += drbg->blk_size - (size % drbg->blk_size); ASSERT(size <= MAX_SER_SIZE); ASSERT((size % drbg->blk_size) == 0); /* S = IV || (L || N || input || 0x80 || 0x00...) */ memset(out, 0, size); out += drbg->blk_size; write32be(out, L); out += 4; write32be(out, N); out += 4; if (nonce_len > 0) { memcpy(out, nonce, nonce_len); out += nonce_len; } if (pers_len > 0) { memcpy(out, pers, pers_len); out += pers_len; } *out = 0x80; *blocks = size / drbg->blk_size; } static void ctr_drbg_derive(ctr_drbg_t *drbg, unsigned char *out, const unsigned char *nonce, size_t nonce_len, const unsigned char *pers, size_t pers_len) { unsigned char tmp[MAX_ENT_SIZE + MAX_BLK_SIZE]; unsigned char slab[MAX_ENT_SIZE + MAX_BLK_SIZE]; unsigned char chain[MAX_BLK_SIZE]; unsigned char K[MAX_KEY_SIZE]; unsigned char S[MAX_SER_SIZE]; unsigned char *x = slab + drbg->key_size; size_t bits = drbg->key_size * 8; size_t i, j, k, blocks, N; aes_t aes; ctr_drbg_serialize(drbg, S, &N, nonce, nonce_len, pers, pers_len); for (i = 0; i < drbg->key_size; i++) K[i] = i; aes_init_encrypt(&aes, bits, K); blocks = (drbg->ent_size + drbg->blk_size - 1) / drbg->blk_size; for (i = 0; i < blocks; i++) { memset(chain, 0, drbg->blk_size); write32be(S, i); /* chain = BCC(K, IV || S) */ for (j = 0; j < N; j++) { for (k = 0; k < drbg->blk_size; k++) chain[k] ^= S[j * drbg->blk_size + k]; aes_encrypt(&aes, chain, chain); } memcpy(slab + i * drbg->blk_size, chain, drbg->blk_size); } aes_init_encrypt(&aes, bits, slab); for (i = 0; i < blocks; i++) { aes_encrypt(&aes, x, x); memcpy(tmp + i * drbg->blk_size, x, drbg->blk_size); } memcpy(out, tmp, drbg->ent_size); } void ctr_drbg_init(ctr_drbg_t *drbg, unsigned int bits, int derivation, const unsigned char *nonce, size_t nonce_len, const unsigned char *pers, size_t pers_len) { unsigned char entropy[MAX_ENT_SIZE]; size_t i; CHECK(bits == 128 || bits == 192 || bits == 256); drbg->key_size = bits / 8; drbg->blk_size = 16; drbg->ent_size = drbg->key_size + drbg->blk_size; drbg->derivation = derivation; drbg->K = &drbg->KV[0]; drbg->V = &drbg->KV[drbg->key_size]; if (drbg->derivation) { ctr_drbg_derive(drbg, entropy, nonce, nonce_len, pers, pers_len); } else { memset(entropy, 0, drbg->ent_size); if (nonce_len > drbg->ent_size) nonce_len = drbg->ent_size; if (pers_len > drbg->ent_size) pers_len = drbg->ent_size; if (nonce_len > 0) memcpy(entropy, nonce, nonce_len); for (i = 0; i < pers_len; i++) entropy[i] ^= pers[i]; } memset(drbg->KV, 0, drbg->ent_size); ctr_drbg_rekey(drbg, drbg->K, drbg->V); ctr_drbg_update(drbg, entropy, drbg->ent_size); } void ctr_drbg_reseed(ctr_drbg_t *drbg, const unsigned char *nonce, size_t nonce_len, const unsigned char *add, size_t add_len) { unsigned char entropy[MAX_ENT_SIZE]; size_t i; if (drbg->derivation) { ctr_drbg_derive(drbg, entropy, nonce, nonce_len, add, add_len); } else { memset(entropy, 0, drbg->ent_size); if (nonce_len > drbg->ent_size) nonce_len = drbg->ent_size; if (add_len > drbg->ent_size) add_len = drbg->ent_size; if (nonce_len > 0) memcpy(entropy, nonce, nonce_len); for (i = 0; i < add_len; i++) entropy[i] ^= add[i]; } ctr_drbg_update(drbg, entropy, drbg->ent_size); } void ctr_drbg_generate(ctr_drbg_t *drbg, void *out, size_t len, const unsigned char *add, size_t add_len) { unsigned char *raw = (unsigned char *)out; unsigned char tmp[MAX_ENT_SIZE]; if (add_len > 0) { if (drbg->derivation) { ctr_drbg_derive(drbg, tmp, add, add_len, NULL, 0); ctr_drbg_update(drbg, tmp, drbg->ent_size); add_len = drbg->ent_size; add = tmp; } else { ctr_drbg_update(drbg, add, add_len); } } while (len > 0) { if (len < drbg->blk_size) { unsigned char block[MAX_BLK_SIZE]; ctr_drbg_encrypt(drbg, block); memcpy(raw, block, len); break; } ctr_drbg_encrypt(drbg, raw); raw += drbg->blk_size; len -= drbg->blk_size; } ctr_drbg_update(drbg, add, add_len); } void ctr_drbg_rng(void *out, size_t size, void *arg) { ctr_drbg_generate((ctr_drbg_t *)arg, out, size, NULL, 0); } ======================= File: node_modules/bcrypto/deps/torsion/src/fields/p521.h ======================= <gh_stars>1000+ /*! * p521.h - p521 field element for libtorsion * Copyright (c) 2020, <NAME> (MIT License). * https://github.com/bcoin-org/libtorsion */ #if defined(TORSION_HAVE_INT128) typedef uint64_t p521_fe_word_t; #define P521_FIELD_WORDS 9 #include "p521_64.h" #else typedef uint32_t p521_fe_word_t; #define P521_FIELD_WORDS 19 #include "p521_32.h" #endif typedef p521_fe_word_t p521_fe_t[P521_FIELD_WORDS]; #define p521_fe_add fiat_p521_add #define p521_fe_sub fiat_p521_sub #define p521_fe_neg fiat_p521_opp #define p521_fe_mul fiat_p521_carry_mul #define p521_fe_sqr fiat_p521_carry_square static void p521_fe_set(p521_fe_t z, const p521_fe_t x) { z[0] = x[0]; z[1] = x[1]; z[2] = x[2]; z[3] = x[3]; z[4] = x[4]; z[5] = x[5]; z[6] = x[6]; z[7] = x[7]; z[8] = x[8]; #if P521_FIELD_WORDS == 19 z[9] = x[9]; z[10] = x[10]; z[11] = x[11]; z[12] = x[12]; z[13] = x[13]; z[14] = x[14]; z[15] = x[15]; z[16] = x[16]; z[17] = x[17]; z[18] = x[18]; #endif } static int p521_fe_equal(const p521_fe_t x, const p521_fe_t y) { uint32_t z = 0; uint8_t u[66]; uint8_t v[66]; int i; fiat_p521_to_bytes(u, x); fiat_p521_to_bytes(v, y); for (i = 0; i < 66; i++) z |= (uint32_t)u[i] ^ (uint32_t)v[i]; return (z - 1) >> 31; } static void p521_fe_sqrn(p521_fe_t z, const p521_fe_t x, int n) { int i; p521_fe_sqr(z, x); for (i = 1; i < n; i++) p521_fe_sqr(z, z); } static void p521_fe_pow_core(p521_fe_t z, const p521_fe_t x1) { /* Exponent: 2^519 - 1 */ /* Bits: 519x1 */ p521_fe_t t1, t2, t3; /* x2 = x1^(2^1) * x1 */ p521_fe_sqr(t1, x1); p521_fe_mul(t1, t1, x1); /* x3 = x2^(2^1) * x1 */ p521_fe_sqr(t1, t1); p521_fe_mul(t1, t1, x1); /* x6 = x3^(2^3) * x3 */ p521_fe_sqrn(t2, t1, 3); p521_fe_mul(t2, t2, t1); /* x7 = x6^(2^1) * x1 */ p521_fe_sqr(t1, t2); p521_fe_mul(t1, t1, x1); /* x8 = x7^(2^1) * x1 */ p521_fe_sqr(t2, t1); p521_fe_mul(t2, t2, x1); /* x16 = x8^(2^8) * x8 */ p521_fe_sqrn(t3, t2, 8); p521_fe_mul(t3, t3, t2); /* x32 = x16^(2^16) * x16 */ p521_fe_sqrn(t2, t3, 16); p521_fe_mul(t2, t2, t3); /* x64 = x32^(2^32) * x32 */ p521_fe_sqrn(t3, t2, 32); p521_fe_mul(t3, t3, t2); /* x128 = x64^(2^64) * x64 */ p521_fe_sqrn(t2, t3, 64); p521_fe_mul(t2, t2, t3); /* x256 = x128^(2^128) * x128 */ p521_fe_sqrn(t3, t2, 128); p521_fe_mul(t3, t3, t2); /* x512 = x256^(2^256) * x256 */ p521_fe_sqrn(z, t3, 256); p521_fe_mul(z, z, t3); /* x519 = x512^(2^7) * x7 */ p521_fe_sqrn(z, z, 7); p521_fe_mul(z, z, t1); } static void p521_fe_pow_pm3d4(p521_fe_t z, const p521_fe_t x) { /* Exponent: 2^519 - 1 */ /* Bits: 519x1 */ /* z = x^(2^519 - 1) */ p521_fe_pow_core(z, x); } static void p521_fe_invert(p521_fe_t z, const p521_fe_t x) { /* Exponent: p - 2 */ /* Bits: 519x1 1x0 1x1 */ p521_fe_t x1; /* x1 = x */ p521_fe_set(x1, x); /* z = x1^(2^519 - 1) */ p521_fe_pow_core(z, x1); /* z = z^(2^1) */ p521_fe_sqr(z, z); /* z = z^(2^1) * x1 */ p521_fe_sqr(z, z); p521_fe_mul(z, z, x1); } static int p521_fe_sqrt(p521_fe_t z, const p521_fe_t x) { /* Exponent: (p + 1) / 4 */ /* Bits: 1x1 519x0 */ p521_fe_t x1, c; /* x1 = x */ p521_fe_set(x1, x); /* z = x1^(2^519) */ p521_fe_sqrn(z, x1, 519); /* z^2 == x1 */ p521_fe_sqr(c, z); return p521_fe_equal(c, x1); } static int p521_fe_isqrt(p521_fe_t z, const p521_fe_t u, const p521_fe_t v) { p521_fe_t t, x, c; int ret; /* x = u^3 * v * (u^5 * v^3)^((p - 3) / 4) mod p */ p521_fe_sqr(t, u); /* u^2 */ p521_fe_mul(c, t, u); /* u^3 */ p521_fe_mul(t, t, c); /* u^5 */ p521_fe_sqr(x, v); /* v^2 */ p521_fe_mul(x, x, v); /* v^3 */ p521_fe_mul(x, x, t); /* v^3 * u^5 */ p521_fe_pow_pm3d4(x, x); /* (v^3 * u^5)^((p - 3) / 4) */ p521_fe_mul(x, x, v); /* (v^3 * u^5)^((p - 3) / 4) * v */ p521_fe_mul(x, x, c); /* (v^3 * u^5)^((p - 3) / 4) * v * u^3 */ /* x^2 * v == u */ p521_fe_sqr(c, x); p521_fe_mul(c, c, v); ret = p521_fe_equal(c, u); p521_fe_set(z, x); return ret; } ======================= File: node_modules/bcrypto/deps/torsion/src/bf.h ======================= <reponame>pradyuman-verma/bcoin<gh_stars>1-10 /*! * bf.h - extra blowfish functions for libtorsion * Copyright (c) 2020, <NAME> (MIT License). * https://github.com/bcoin-org/libtorsion */ #ifndef TORSION_BF_H #define TORSION_BF_H #include <stddef.h> #include <stdint.h> #include <torsion/cipher.h> #define blowfish_stream2word torsion__blowfish_stream2word #define blowfish_expand0state torsion__blowfish_expand0state #define blowfish_expandstate torsion__blowfish_expandstate #define blowfish_enc torsion__blowfish_enc #define blowfish_dec torsion__blowfish_dec uint32_t blowfish_stream2word(const unsigned char *data, size_t len, size_t *off); void blowfish_expand0state(blowfish_t *ctx, const unsigned char *key, size_t key_len); void blowfish_expandstate(blowfish_t *ctx, const unsigned char *key, size_t key_len, const unsigned char *data, size_t data_len); void blowfish_enc(const blowfish_t *ctx, uint32_t *data, size_t len); void blowfish_dec(const blowfish_t *ctx, uint32_t *data, size_t len); #endif /* TORSION_BF_H */ ======================= File: node_modules/bcrypto/deps/torsion/src/rsa.c ======================= /*! * rsa.c - rsa for libtorsion * Copyright (c) 2020, <NAME> (MIT License). * https://github.com/bcoin-org/libtorsion * * Parts of this software are based on golang/go: * Copyright (c) 2009 The Go Authors. All rights reserved. * https://github.com/golang/go * * References: * * [RFC8017] PKCS #1: RSA Cryptography Specifications Version 2.2 * <NAME>, <NAME>, <NAME>, <NAME> * https://tools.ietf.org/html/rfc8017 * * [FIPS186] Federal Information Processing Standards Publication 186-4 * National Institute of Standards and Technology * https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf */ #include <stdlib.h> #include <stdint.h> #include <string.h> #include <torsion/drbg.h> #include <torsion/hash.h> #include <torsion/rsa.h> #include <torsion/util.h> #include "asn1.h" #include "bio.h" #include "internal.h" #include "mpi.h" /* * Constants */ static const unsigned char digest_info[33][24] = { { /* NONE */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, { /* BLAKE2B160 */ 0x15, 0x30, 0x27, 0x30, 0x0f, 0x06, 0x0b, 0x2b, 0x06, 0x01, 0x04, 0x01, 0x8d, 0x3a, 0x0c, 0x02, 0x01, 0x05, 0x05, 0x00, 0x04, 0x14, 0x00, 0x00 }, { /* BLAKE2B256 */ 0x15, 0x30, 0x33, 0x30, 0x0f, 0x06, 0x0b, 0x2b, 0x06, 0x01, 0x04, 0x01, 0x8d, 0x3a, 0x0c, 0x02, 0x01, 0x08, 0x05, 0x00, 0x04, 0x20, 0x00, 0x00 }, { /* BLAKE2B384 */ 0x15, 0x30, 0x43, 0x30, 0x0f, 0x06, 0x0b, 0x2b, 0x06, 0x01, 0x04, 0x01, 0x8d, 0x3a, 0x0c, 0x02, 0x01, 0x0c, 0x05, 0x00, 0x04, 0x30, 0x00, 0x00 }, { /* BLAKE2B512 */ 0x15, 0x30, 0x53, 0x30, 0x0f, 0x06, 0x0b, 0x2b, 0x06, 0x01, 0x04, 0x01, 0x8d, 0x3a, 0x0c, 0x02, 0x01, 0x10, 0x05, 0x00, 0x04, 0x40, 0x00, 0x00 }, { /* BLAKE2S128 */ 0x15, 0x30, 0x23, 0x30, 0x0f, 0x06, 0x0b, 0x2b, 0x06, 0x01, 0x04, 0x01, 0x8d, 0x3a, 0x0c, 0x02, 0x02, 0x04, 0x05, 0x00, 0x04, 0x10, 0x00, 0x00 }, { /* BLAKE2S160 */ 0x15, 0x30, 0x27, 0x30, 0x0f, 0x06, 0x0b, 0x2b, 0x06, 0x01, 0x04, 0x01, 0x8d, 0x3a, 0x0c, 0x02, 0x02, 0x05, 0x05, 0x00, 0x04, 0x14, 0x00, 0x00 }, { /* BLAKE2S224 */ 0x15, 0x30, 0x2f, 0x30, 0x0f, 0x06, 0x0b, 0x2b, 0x06, 0x01, 0x04, 0x01, 0x8d, 0x3a, 0x0c, 0x02, 0x02, 0x07, 0x05, 0x00, 0x04, 0x1c, 0x00, 0x00 }, { /* BLAKE2S256 */ 0x15, 0x30, 0x33, 0x30, 0x0f, 0x06, 0x0b, 0x2b, 0x06, 0x01, 0x04, 0x01, 0x8d, 0x3a, 0x0c, 0x02, 0x02, 0x08, 0x05, 0x00, 0x04, 0x20, 0x00, 0x00 }, { /* GOST94 */ 0x10, 0x30, 0x2e, 0x30, 0x0a, 0x06, 0x06, 0x2a, 0x85, 0x03, 0x02, 0x02, 0x14, 0x05, 0x00, 0x04, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, { /* HASH160 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, { /* HASH256 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, { /* KECCAK224 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, { /* KECCAK256 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, { /* KECCAK384 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, { /* KECCAK512 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, { /* MD2 */ 0x12, 0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x02, 0x02, 0x05, 0x00, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00 }, { /* MD4 */ 0x12, 0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x02, 0x04, 0x05, 0x00, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00 }, { /* MD5 */ 0x12, 0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x02, 0x05, 0x05, 0x00, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00 }, { /* MD5SHA1 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, { /* RIPEMD160 */ 0x10, 0x30, 0x22, 0x30, 0x0a, 0x06, 0x06, 0x28, 0xcf, 0x06, 0x03, 0x00, 0x31, 0x05, 0x00, 0x04, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, { /* SHA1 */ 0x0f, 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, { /* SHA224 */ 0x13, 0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x05, 0x00, 0x04, 0x1c, 0x00, 0x00, 0x00, 0x00 }, { /* SHA256 */ 0x13, 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00, 0x04, 0x20, 0x00, 0x00, 0x00, 0x00 }, { /* SHA384 */ 0x13, 0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05, 0x00, 0x04, 0x30, 0x00, 0x00, 0x00, 0x00 }, { /* SHA512 */ 0x13, 0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05, 0x00, 0x04, 0x40, 0x00, 0x00, 0x00, 0x00 }, { /* SHA3_224 */ 0x13, 0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x07, 0x05, 0x00, 0x04, 0x1c, 0x00, 0x00, 0x00, 0x00 }, { /* SHA3_256 */ 0x13, 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x08, 0x05, 0x00, 0x04, 0x20, 0x00, 0x00, 0x00, 0x00 }, { /* SHA3_384 */ 0x13, 0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x09, 0x05, 0x00, 0x04, 0x30, 0x00, 0x00, 0x00, 0x00 }, { /* SHA3_512 */ 0x13, 0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x0a, 0x05, 0x00, 0x04, 0x40, 0x00, 0x00, 0x00, 0x00 }, { /* SHAKE128 */ 0x13, 0x30, 0x21, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x0b, 0x05, 0x00, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00 }, { /* SHAKE256 */ 0x13, 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x0c, 0x05, 0x00, 0x04, 0x20, 0x00, 0x00, 0x00, 0x00 }, { /* WHIRLPOOL */ 0x10, 0x30, 0x4e, 0x30, 0x0a, 0x06, 0x06, 0x28, 0xcf, 0x06, 0x03, 0x00, 0x37, 0x05, 0x00, 0x04, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } }; static const unsigned char pss_prefix[8] = {0, 0, 0, 0, 0, 0, 0, 0}; /* * Structs */ typedef struct rsa_pub_s { mpz_t n; mpz_t e; } rsa_pub_t; typedef struct rsa_priv_s { mpz_t n; mpz_t e; mpz_t d; mpz_t p; mpz_t q; mpz_t dp; mpz_t dq; mpz_t qi; } rsa_priv_t; /* * Helpers */ TORSION_BARRIER(uint32_t, uint32) #define B uint32_barrier static TORSION_INLINE uint32_t safe_equal(uint32_t x, uint32_t y) { return ((B(x) ^ B(y)) - 1) >> 31; } static TORSION_INLINE uint32_t safe_select(uint32_t x, uint32_t y, uint32_t v) { return (B(x) & (B(v) - 1)) | (B(y) & ~(B(v) - 1)); } static TORSION_INLINE uint32_t safe_lte(uint32_t x, uint32_t y) { return (B(x) - B(y) - 1) >> 31; } #undef B static TORSION_INLINE uint32_t safe_memequal(const unsigned char *x, const unsigned char *y, size_t len) { uint32_t v = 0; size_t i; for (i = 0; i < len; i++) v |= (uint32_t)x[i] ^ (uint32_t)y[i]; return (v - 1) >> 31; } /* * Private Key */ static void rsa_priv_init(rsa_priv_t *k) { mpz_init(k->n); mpz_init(k->e); mpz_init(k->d); mpz_init(k->p); mpz_init(k->q); mpz_init(k->dp); mpz_init(k->dq); mpz_init(k->qi); } static void rsa_priv_clear(rsa_priv_t *k) { mpz_cleanse(k->n); mpz_cleanse(k->e); mpz_cleanse(k->d); mpz_cleanse(k->p); mpz_cleanse(k->q); mpz_cleanse(k->dp); mpz_cleanse(k->dq); mpz_cleanse(k->qi); } static void rsa_priv_set(rsa_priv_t *r, const rsa_priv_t *k) { mpz_set(r->n, k->n); mpz_set(r->e, k->e); mpz_set(r->d, k->d); mpz_set(r->p, k->p); mpz_set(r->q, k->q); mpz_set(r->dp, k->dp); mpz_set(r->dq, k->dq); mpz_set(r->qi, k->qi); } static int rsa_priv_import(rsa_priv_t *k, const unsigned char *data, size_t len) { if (!asn1_read_seq(&data, &len, 1)) return 0; if (!asn1_read_version(&data, &len, 0, 1)) return 0; if (!asn1_read_mpz(k->n, &data, &len, 1)) return 0; if (!asn1_read_mpz(k->e, &data, &len, 1)) return 0; if (!asn1_read_mpz(k->d, &data, &len, 1)) return 0; if (!asn1_read_mpz(k->p, &data, &len, 1)) return 0; if (!asn1_read_mpz(k->q, &data, &len, 1)) return 0; if (!asn1_read_mpz(k->dp, &data, &len, 1)) return 0; if (!asn1_read_mpz(k->dq, &data, &len, 1)) return 0; if (!asn1_read_mpz(k->qi, &data, &len, 1)) return 0; if (len!= 0) return 0; return 1; } static void rsa_priv_export(unsigned char *out, size_t *out_len, const rsa_priv_t *k) { size_t size = 0; size_t pos = 0; size += asn1_size_version(0); size += asn1_size_mpz(k->n); size += asn1_size_mpz(k->e); size += asn1_size_mpz(k->d); size += asn1_size_mpz(k->p); size += asn1_size_mpz(k->q); size += asn1_size_mpz(k->dp); size += asn1_size_mpz(k->dq); size += asn1_size_mpz(k->qi); pos = asn1_write_seq(out, pos, size); pos = asn1_write_version(out, pos, 0); pos = asn1_write_mpz(out, pos, k->n); pos = asn1_write_mpz(out, pos, k->e); pos = asn1_write_mpz(out, pos, k->d); pos = asn1_write_mpz(out, pos, k->p); pos = asn1_write_mpz(out, pos, k->q); pos = asn1_write_mpz(out, pos, k->dp); pos = asn1_write_mpz(out, pos, k->dq); pos = asn1_write_mpz(out, pos, k->qi); *out_len = pos; } static int rsa_priv_import_dumb(rsa_priv_t *k, const unsigned char *data, size_t len) { if (!asn1_read_dumb(k->n, &data, &len)) return 0; if (!asn1_read_dumb(k->e, &data, &len)) return 0; if (!asn1_read_dumb(k->d, &data, &len)) return 0; if (!asn1_read_dumb(k->p, &data, &len)) return 0; if (!asn1_read_dumb(k->q, &data, &len)) return 0; if (!asn1_read_dumb(k->dp, &data, &len)) return 0; if (!asn1_read_dumb(k->dq, &data, &len)) return 0; if (!asn1_read_dumb(k->qi, &data, &len)) return 0; return 1; } static void rsa_priv_export_dumb(unsigned char *out, size_t *out_len, const rsa_priv_t *k) { size_t pos = 0; pos = asn1_write_dumb(out, pos, k->n); pos = asn1_write_dumb(out, pos, k->e); pos = asn1_write_dumb(out, pos, k->d); pos = asn1_write_dumb(out, pos, k->p); pos = asn1_write_dumb(out, pos, k->q); pos = asn1_write_dumb(out, pos, k->dp); pos = asn1_write_dumb(out, pos, k->dq); pos = asn1_write_dumb(out, pos, k->qi); *out_len = pos; } static int rsa_priv_generate(rsa_priv_t *k, mp_bits_t bits, uint64_t exp, const unsigned char *entropy) { /* [RFC8017] Page 9, Section 3.2. * [FIPS186] Page 51, Appendix B.3.1 * Page 55, Appendix B.3.3 * * There are two methods for choosing `d`. * Implementations differ on whether they * use Euler's totient or the Carmichael * function. * * The best explanation of Euler's phi vs. * Carmichael's lambda I've seen comes from * the crypto stackexchange[1]. * * Note that both functions are _equivalent_ * when used with RSA, however, Carmichael's * may lend itself to some perf benefits. * * [1] https://crypto.stackexchange.com/a/29595 */ mpz_t pm1, qm1, phi, lam, tmp; #if MP_LIMB_BITS == 32 mp_limb_t *limbs; #endif drbg_t rng; if (bits < RSA_MIN_MOD_BITS || bits > RSA_MAX_MOD_BITS || exp < RSA_MIN_EXP || exp > RSA_MAX_EXP || (exp & 1) == 0) { return 0; } drbg_init(&rng, HASH_SHA256, entropy, ENTROPY_SIZE); mpz_init(pm1); mpz_init(qm1); mpz_init(phi); mpz_init(lam); mpz_init(tmp); #if MP_LIMB_BITS == 64 mpz_set_ui(k->e, exp); #else limbs = mpz_limbs_write(k->e, 2); limbs[0] = (mp_limb_t)(exp >> 0); limbs[1] = (mp_limb_t)(exp >> 32); mpz_limbs_finish(k->e, 2); #endif for (;;) { mpz_randprime(k->p, (bits >> 1) + (bits & 1), drbg_rng, &rng); mpz_randprime(k->q, bits >> 1, drbg_rng, &rng); if (mpz_cmp(k->p, k->q) == 0) continue; if (mpz_cmp(k->p, k->q) < 0) mpz_swap(k->p, k->q); mpz_sub(tmp, k->p, k->q); if (mpz_bitlen(tmp) <= (bits >> 1) - 99) continue; mpz_mul(k->n, k->p, k->q); if (mpz_bitlen(k->n)!= bits) continue; /* Euler's totient: (p - 1) * (q - 1). */ mpz_sub_ui(pm1, k->p, 1); mpz_sub_ui(qm1, k->q, 1); mpz_mul(phi, pm1, qm1); mpz_gcd(tmp, k->e, phi); if (mpz_cmp_ui(tmp, 1)!= 0) continue; /* Carmichael's function: lcm(p - 1, q - 1). */ mpz_gcd(tmp, pm1, qm1); mpz_divexact(lam, phi, tmp); if (!mpz_invert(k->d, k->e, lam)) continue; if (mpz_bitlen(k->d) <= ((bits + 1) >> 1)) continue; mpz_mod(k->dp, k->d, pm1); mpz_mod(k->dq, k->d, qm1); ASSERT(mpz_invert(k->qi, k->q, k->p)); break; } torsion_memzero(&rng, sizeof(rng)); mpz_cleanse(pm1); mpz_cleanse(qm1); mpz_cleanse(phi); mpz_cleanse(lam); mpz_cleanse(tmp); return 1; } static int rsa_priv_is_sane(const rsa_priv_t *k) { /* DoS limits. */ return mpz_sgn(k->n) > 0 && mpz_sgn(k->e) > 0 && mpz_sgn(k->d) > 0 && mpz_sgn(k->p) > 0 && mpz_sgn(k->q) > 0 && mpz_sgn(k->dp) > 0 && mpz_sgn(k->dq) > 0 && mpz_sgn(k->qi) > 0 && mpz_bitlen(k->n) <= RSA_MAX_MOD_BITS && mpz_bitlen(k->e) <= RSA_MAX_EXP_BITS && mpz_bitlen(k->d) <= RSA_MAX_MOD_BITS && mpz_bitlen(k->p) <= RSA_MAX_MOD_BITS && mpz_bitlen(k->q) <= RSA_MAX_MOD_BITS && mpz_bitlen(k->dp) <= RSA_MAX_MOD_BITS && mpz_bitlen(k->dq) <= RSA_MAX_MOD_BITS && mpz_bitlen(k->qi) <= RSA_MAX_MOD_BITS; } static int rsa_priv_verify(const rsa_priv_t *k) { /* [RFC8017] Page 9, Section 3.2. */ mpz_t pm1, qm1, phi, lam, tmp; int ret = 0; if (!rsa_priv_is_sane(k)) return 0; mpz_init(pm1); mpz_init(qm1); mpz_init(phi); mpz_init(lam); mpz_init(tmp); /* n >= 2^511 and n mod 2!= 0 */ if (mpz_bitlen(k->n) < RSA_MIN_MOD_BITS ||!mpz_odd_p(k->n)) goto fail; /* e >= 3 and e mod 2!= 0 */ if (mpz_cmp_ui(k->e, RSA_MIN_EXP) < 0 ||!mpz_odd_p(k->e)) goto fail; /* p >= 3 and p mod 2!= 0 */ if (mpz_cmp_ui(k->p, 3) < 0 ||!mpz_odd_p(k->p)) goto fail; /* q >= 3 and q mod 2!= 0 */ if (mpz_cmp_ui(k->q, 3) < 0 ||!mpz_odd_p(k->q)) goto fail; /* phi = (p - 1) * (q - 1) */ mpz_sub_ui(pm1, k->p, 1); mpz_sub_ui(qm1, k->q, 1); mpz_mul(phi, pm1, qm1); /* d >= 2 and d < phi */ if (mpz_cmp_ui(k->d, 2) < 0 || mpz_cmp(k->d, phi) >= 0) goto fail; /* dp!= 0 and dp < p - 1 */ if (mpz_sgn(k->dp) == 0 || mpz_cmp(k->dp, pm1) >= 0) goto fail; /* dq!= 0 and dq < q - 1 */ if (mpz_sgn(k->dq) == 0 || mpz_cmp(k->dq, qm1) >= 0) goto fail; /* qi <= 2 and qi < p */ if (mpz_cmp_ui(k->qi, 2) < 0 || mpz_cmp(k->qi, k->p) >= 0) goto fail; /* p!= q */ if (mpz_cmp(k->p, k->q) == 0) goto fail; /* n == p * q */ mpz_mul(tmp, k->p, k->q); if (mpz_cmp(tmp, k->n)!= 0) goto fail; /* lam = lcm(p - 1, q - 1) */ mpz_gcd(tmp, pm1, qm1); mpz_divexact(lam, phi, tmp); /* e * d mod lam == 1 */ mpz_mul(tmp, k->e, k->d); mpz_mod(tmp, tmp, lam); if (mpz_cmp_ui(tmp, 1)!= 0) goto fail; /* dp == d mod (p - 1) */ mpz_mod(tmp, k->d, pm1); if (mpz_cmp(tmp, k->dp)!= 0) goto fail; /* dq == d mod (q - 1) */ mpz_mod(tmp, k->d, qm1); if (mpz_cmp(tmp, k->dq)!= 0) goto fail; /* q * qi mod p == 1 */ mpz_mul(tmp, k->q, k->qi); mpz_mod(tmp, tmp, k->p); if (mpz_cmp_ui(tmp, 1)!= 0) goto fail; ret = 1; fail: mpz_cleanse(pm1); mpz_cleanse(qm1); mpz_cleanse(phi); mpz_cleanse(lam); mpz_cleanse(tmp); return ret; } static int rsa_priv_set_pqe(rsa_priv_t *out, const mpz_t p0, const mpz_t q0, const mpz_t e) { /* Recover from (p, q, e). */ mpz_t p, q, pm1, qm1, lam; rsa_priv_t k; int ret = 0; rsa_priv_init(&k); mpz_init(p); mpz_init(q); mpz_init(pm1); mpz_init(qm1); mpz_init(lam); mpz_set(p, p0); mpz_set(q, q0); if (mpz_cmp(p, q) < 0) mpz_swap(p, q); /* Sanity checks. */ if (mpz_cmp(p, q) == 0) goto fail; if (mpz_cmp_ui(p, 3) < 0 || mpz_bitlen(p) > RSA_MAX_MOD_BITS) goto fail; if (mpz_cmp_ui(q, 3) < 0 || mpz_bitlen(q) > RSA_MAX_MOD_BITS) goto fail; if (mpz_cmp_ui(e, RSA_MIN_EXP) < 0 || mpz_bitlen(e) > RSA_MAX_EXP_BITS) goto fail; if (!mpz_odd_p(p) ||!mpz_odd_p(q) ||!mpz_odd_p(e)) goto fail; mpz_mul(k.n, p, q); ASSERT(mpz_odd_p(k.n)); if (mpz_bitlen(k.n) < RSA_MIN_MOD_BITS || mpz_bitlen(k.n) > RSA_MAX_MOD_BITS) goto fail; mpz_set(k.e, e); mpz_sub_ui(pm1, p, 1); mpz_sub_ui(qm1, q, 1); mpz_lcm(lam, pm1, qm1); if (!mpz_invert(k.d, e, lam)) goto fail; mpz_set(k.p, p); mpz_set(k.q, q); mpz_mod(k.dp, k.d, pm1); mpz_mod(k.dq, k.d, qm1); if (!mpz_invert(k.qi, q, p)) goto fail; #ifdef TORSION_DEBUG ASSERT(rsa_priv_verify(&k)); #endif rsa_priv_set(out, &k); ret = 1; fail: rsa_priv_clear(&k); mpz_cleanse(p); mpz_cleanse(q); mpz_cleanse(pm1); mpz_cleanse(qm1); mpz_cleanse(lam); return ret; } static int rsa_priv_set_pqd(rsa_priv_t *out, const mpz_t p, const mpz_t q, const mpz_t d) { /* Recover from (p, q, d). */ mpz_t pm1, qm1, phi, lam, tmp, e; int ret = 0; mpz_init(pm1); mpz_init(qm1); mpz_init(phi); mpz_init(lam); mpz_init(tmp); mpz_init(e); if (mpz_cmp_ui(p, 3) < 0 || mpz_bitlen(p) > RSA_MAX_MOD_BITS) goto fail; if (mpz_cmp_ui(q, 3) < 0 || mpz_bitlen(q) > RSA_MAX_MOD_BITS) goto fail; if (!mpz_odd_p(p) ||!mpz_odd_p(q)) goto fail; mpz_sub_ui(pm1, p, 1); mpz_sub_ui(qm1, q, 1); mpz_mul(phi, pm1, qm1); if (mpz_cmp_ui(d, 2) < 0 || mpz_cmp(d, phi) >= 0) goto fail; mpz_gcd(tmp, pm1, qm1); mpz_divexact(lam, phi, tmp); if (!mpz_invert(e, d, lam)) goto fail; /* Recover from (p, q, e). */ ret = rsa_priv_set_pqe(out, p, q, e); fail: mpz_cleanse(pm1); mpz_cleanse(qm1); mpz_cleanse(phi); mpz_cleanse(lam); mpz_cleanse(tmp); mpz_cleanse(e); return ret; } static int rsa_priv_set_ned(rsa_priv_t *out, const mpz_t n, const mpz_t e, const mpz_t d, const unsigned char *entropy) { /* Factor an RSA modulus given (n, e, d). * * This is basically the same logic as the * Miller-Rabin primality test[1][2]. * * [1] https://crypto.stackexchange.com/questions/11509 * [2] https://crypto.stackexchange.com/questions/22374 */ mpz_t f, nm1, nm3, g, a, b, c, p, q; size_t entropy_len = ENTROPY_SIZE; mp_bits_t j, s; int ret = 0; drbg_t rng; int i; mpz_init(f); mpz_init(nm1); mpz_init(nm3); mpz_init(g); mpz_init(a); mpz_init(b); mpz_init(c); mpz_init(p); mpz_init(q); /* Sanity checks. */ if (mpz_sgn(n) < 0) goto done; if (mpz_bitlen(n) < RSA_MIN_MOD_BITS || mpz_bitlen(n) > RSA_MAX_MOD_BITS) goto done; if (mpz_cmp_ui(e, RSA_MIN_EXP) < 0 || mpz_bitlen(e) > RSA_MAX_EXP_BITS) goto done; if (mpz_cmp_ui(d, 2) < 0 || mpz_bitlen(d) > RSA_MAX_MOD_BITS) goto done; if (!mpz_odd_p(n) ||!mpz_odd_p(e)) goto done; /* f = e * d - 1 */ mpz_mul(f, e, d); mpz_sub_ui(f, f, 1); /* nm1 = n - 1 */ mpz_sub_ui(nm1, n, 1); /* nm3 = nm1 - 2 */ mpz_sub_ui(nm3, nm1, 2); /* s = f factors of 2 */ s = mpz_ctz(f); /* g = f >> s */ mpz_quo_2exp(g, f, s); /* Seed RNG using the modulus as entropy. */ if (entropy == NULL) { entropy = (const unsigned char *)mpz_limbs_read(n); entropy_len = mpz_size(n) * sizeof(mp_limb_t); } /* Seed RNG. */ drbg_init(&rng, HASH_SHA256, entropy, entropy_len); for (i = 0; i < 128; i++) { /* a = random int in [2,n-2] */ mpz_urandomm(a, nm3, drbg_rng, &rng); mpz_add_ui(a, a, 2); /* b = a^g mod n */ mpz_powm(b, a, g, n); if (mpz_cmp_ui(b, 1) == 0 || mpz_cmp(b, nm1) == 0) continue; for (j = 1; j < s; j++) { /* c = b^2 mod n */ mpz_sqr(c, b); mpz_mod(c, c, n); if (mpz_cmp_ui(c, 1) == 0) { /* p = gcd(n, b - 1) */ mpz_sub_ui(c, b, 1); mpz_gcd(p, n, c); /* q = gcd(n, b + 1) */ mpz_add_ui(c, b, 1); mpz_gcd(q, n, c); /* Recover from (p, q, e). */ ret = rsa_priv_set_pqe(out, p, q, e); goto done; } if (mpz_cmp(c, nm1) == 0) break; mpz_swap(b, c); } } done: torsion_memzero(&rng, sizeof(rng)); mpz_cleanse(f); mpz_cleanse(nm1); mpz_cleanse(nm3); mpz_cleanse(g); mpz_cleanse(a); mpz_cleanse(b); mpz_cleanse(c); mpz_cleanse(p); mpz_cleanse(q); return ret; } static int rsa_priv_decrypt(const rsa_priv_t *k, unsigned char *out, const unsigned char *msg, size_t msg_len, int use_crt, const unsigned char *entropy) { /* [RFC8017] Page 13, Section 5.1.2. * Page 15, Section 5.2.1. */ mpz_t s, b, bi, c, m, mp, mq, md; int ret = 0; drbg_t rng; drbg_init(&rng, HASH_SHA256, entropy, ENTROPY_SIZE); mpz_init(s); mpz_init(b); mpz_init(bi); mpz_init(c); mpz_init(m); mpz_init(mp); mpz_init(mq); mpz_init(md); if (mpz_sgn(k->n) <= 0 || mpz_sgn(k->d) <= 0) goto fail; /* Ensure mpz_powm_sec works. */ if (mpz_sgn(k->d) <= 0 ||!mpz_odd_p(k->n)) goto fail; if (mpz_sgn(k->dp) <= 0 ||!mpz_odd_p(k->p)) goto fail; if (mpz_sgn(k->dq) <= 0 ||!mpz_odd_p(k->q)) goto fail; mpz_import(c, msg, msg_len, 1); if (mpz_cmp(c, k->n) >= 0) goto fail; /* Generate blinding factor. */ do { /* s = random integer in [1,n-1] */ /* bi = s^-1 mod n */ mpz_urandomm(s, k->n, drbg_rng, &rng); } while (!mpz_invert(bi, s, k->n)); /* b = s^e mod n */ mpz_powm(b, s, k->e, k->n); /* c = c * b mod n (blind) */ mpz_mul(c, c, b); mpz_mod(c, c, k->n); if (use_crt) { /* Leverage Chinese Remainder Theorem. * * Computation: * * mp = c^(d mod p-1) mod p * mq = c^(d mod q-1) mod q * md = (mp - mq) / q mod p * m = (md * q + mq) mod n */ mpz_powm_sec(mp, c, k->dp, k->p); mpz_powm_sec(mq, c, k->dq, k->q); mpz_sub(md, mp, mq); mpz_mul(md, md, k->qi); mpz_mod(md, md, k->p); mpz_mul(m, md, k->q); mpz_add(m, m, mq); mpz_mod(m, m, k->n); mpz_powm(mp, m, k->e, k->n); if (mpz_cmp(mp, c)!= 0) goto fail; } else { /* m = c^d mod n */ mpz_powm_sec(m, c, k->d, k->n); } /* m = m * bi mod n (unblind) */ mpz_mul(m, m, bi); mpz_mod(m, m, k->n); mpz_export(out, m, mpz_bytelen(k->n), 1); ret = 1; fail: mpz_cleanse(s); mpz_cleanse(b); mpz_cleanse(bi); mpz_cleanse(c); mpz_cleanse(m); mpz_cleanse(mp); mpz_cleanse(mq); mpz_cleanse(md); return ret; } /* * Public Key */ static void rsa_pub_init(rsa_pub_t *k) { mpz_init(k->n); mpz_init(k->e); } static void rsa_pub_clear(rsa_pub_t *k) { mpz_cleanse(k->n); mpz_cleanse(k->e); } TORSION_UNUSED static void rsa_pub_set(rsa_pub_t *r, const rsa_pub_t *k) { mpz_set(r->n, k->n); mpz_set(r->e, k->e); } static int rsa_pub_import(rsa_pub_t *k, const unsigned char *data, size_t len) { if (!asn1_read_seq(&data, &len, 1)) return 0; if (!asn1_read_mpz(k->n, &data, &len, 1)) return 0; if (!asn1_read_mpz(k->e, &data, &len, 1)) return 0; if (len!= 0) return 0; return 1; } static void rsa_pub_export(unsigned char *out, size_t *out_len, const rsa_pub_t *k) { size_t size = 0; size_t pos = 0; size += asn1_size_mpz(k->n); size += asn1_size_mpz(k->e); pos = asn1_write_seq(out, pos, size); pos = asn1_write_mpz(out, pos, k->n); pos = asn1_write_mpz(out, pos, k->e); *out_len = pos; } static int rsa_pub_import_dumb(rsa_pub_t *k, const unsigned char *data, size_t len) { if (!asn1_read_dumb(k->n, &data, &len)) return 0; if (!asn1_read_dumb(k->e, &data, &len)) return 0; return 1; } static void rsa_pub_export_dumb(unsigned char *out, size_t *out_len, const rsa_pub_t *k) { size_t pos = 0; pos = asn1_write_dumb(out, pos, k->n); pos = asn1_write_dumb(out, pos, k->e); *out_len = pos; } static int rsa_pub_verify(const rsa_pub_t *k) { mp_bits_t bits = mpz_bitlen(k->n); if (mpz_sgn(k->n) < 0) return 0; if (bits < RSA_MIN_MOD_BITS || bits > RSA_MAX_MOD_BITS) return 0; if (mpz_cmp_ui(k->e, RSA_MIN_EXP) < 0) return 0; if (mpz_bitlen(k->e) > RSA_MAX_EXP_BITS) return 0; if (!mpz_odd_p(k->n)) return 0; if (!mpz_odd_p(k->e)) return 0; return 1; } static int rsa_pub_encrypt(const rsa_pub_t *k, unsigned char *out, const unsigned char *msg, size_t msg_len) { /* [RFC8017] Page 13, Section 5.1.1. * Page 16, Section 5.2.2. */ int ret = 0; mpz_t m; mpz_init(m); if (mpz_sgn(k->n) <= 0 || mpz_sgn(k->e) <= 0) goto fail; mpz_import(m, msg, msg_len, 1); if (mpz_cmp(m, k->n) >= 0) goto fail; /* c = m^e mod n */ mpz_powm(m, m, k->e, k->n); mpz_export(out, m, mpz_bytelen(k->n), 1); ret = 1; fail: mpz_cleanse(m); return ret; } static int rsa_pub_veil(const rsa_pub_t *k, unsigned char *out, const unsigned char *msg, size_t msg_len, mp_bits_t bits, const unsigned char *entropy) { mpz_t vmax, rmax, c, v, r; int ret = 0; drbg_t rng; mpz_init(vmax); mpz_init(rmax); mpz_init(c); mpz_init(v); mpz_init(r); /* Cannot make ciphertext smaller. */ if (bits < mpz_bitlen(k->n)) goto fail; mpz_import(c, msg, msg_len, 1); if (mpz_cmp(c, k->n) >= 0) goto fail; /* vmax = 1 << bits */ mpz_set_ui(vmax, 0); mpz_setbit(vmax, bits); /* rmax = (vmax - c + n - 1) / n */ mpz_sub(rmax, vmax, c); mpz_add(rmax, rmax, k->n); mpz_sub_ui(rmax, rmax, 1); mpz_quo(rmax, rmax, k->n); ASSERT(mpz_sgn(rmax) > 0); mpz_set(v, vmax); drbg_init(&rng, HASH_SHA256, entropy, ENTROPY_SIZE); while (mpz_cmp(v, vmax) >= 0) { mpz_urandomm(r, rmax, drbg_rng, &rng); /* v = c + r * n */ mpz_mul(r, r, k->n); mpz_add(v, c, r); } mpz_mod(r, v, k->n); ASSERT(mpz_cmp(r, c) == 0); ASSERT(mpz_bitlen(v) <= bits); mpz_export(out, v, (bits + 7) / 8, 1); ret = 1; fail: torsion_memzero(&rng, sizeof(rng)); mpz_cleanse(vmax); mpz_cleanse(rmax); mpz_cleanse(c); mpz_cleanse(v); mpz_cleanse(r); return ret; } static int rsa_pub_unveil(const rsa_pub_t *k, unsigned char *out, const unsigned char *msg, size_t msg_len, mp_bits_t bits) { int ret = 0; mpz_t v; mpz_init(v); mpz_import(v, msg, msg_len, 1); if (bits!= 0 && mpz_bitlen(v) > bits) goto fail; mpz_mod(v, v, k->n); mpz_export(out, v, mpz_bytelen(k->n), 1); ret = 1; fail: mpz_cleanse(v); return ret; } /* * Digest Info */ static int get_digest_info(const unsigned char **data, size_t *len, hash_id_t type) { const unsigned char *info; if (type < 0 || (size_t)type >= ARRAY_SIZE(digest_info)) return 0; info = digest_info[type]; *data = &info[1]; *len = info[0]; return 1; } /* * MGF1 */ static void mgf1xor(hash_id_t type, unsigned char *out, size_t out_len, const unsigned char *seed, size_t seed_len) { /* [RFC8017] Page 67, Section B.2.1. */ size_t hash_size = hash_output_size(type); unsigned char digest[HASH_MAX_OUTPUT_SIZE]; uint8_t ctr[4] = {0, 0, 0, 0}; hash_t cache, hash; size_t i = 0; size_t j; /* Zero for struct assignment. */ memset(&cache, 0, sizeof(cache)); hash_init(&cache, type); hash_update(&cache, seed, seed_len); while (i < out_len) { hash = cache; hash_update(&hash, ctr, sizeof(ctr)); hash_final(&hash, digest, hash_size); j = 0; while (i < out_len && j < hash_size) out[i++] ^= digest[j++]; increment_be_var(ctr, 4); } torsion_memzero(ctr, sizeof(ctr)); torsion_memzero(digest, sizeof(digest)); torsion_memzero(&cache, sizeof(cache)); torsion_memzero(&hash, sizeof(hash)); } /* * PSS */ static int pss_encode(unsigned char *out, size_t *out_len, hash_id_t type, const unsigned char *msg, size_t msg_len, mp_bits_t embits, const unsigned char *salt, size_t salt_len) { /* [RFC8017] Page 42, Section 9.1.1. */ unsigned char *em = out; size_t hlen = hash_output_size(type); size_t slen = salt_len; size_t emlen = (embits + 7) >> 3; size_t dlen = emlen - hlen - 1; unsigned int mask = 0xff >> (8 * emlen - embits); unsigned char h0[HASH_MAX_OUTPUT_SIZE]; unsigned char *db, *h; hash_t hash; if (msg_len!= hlen) return 0; if (emlen < hlen + slen + 2) return 0; /* EM = (PS || 0x01 || salt) || H || 0xbc */ db = &em[0]; h = &em[emlen - hlen - 1]; hash_init(&hash, type); hash_update(&hash, pss_prefix, sizeof(pss_prefix)); hash_update(&hash, msg, msg_len); hash_update(&hash, salt, salt_len); hash_final(&hash, h0, hlen); memset(db, 0x00, emlen - slen - hlen - 2); db[emlen - slen - hlen - 2] = 0x01; if (salt_len > 0) memcpy(db + emlen - slen - hlen - 1, salt, salt_len); memcpy(h, h0, hlen); em[emlen - 1] = 0xbc; mgf1xor(type, db, dlen, h, hlen); db[0] &= mask; *out_len = emlen; return 1; } static int pss_verify(hash_id_t type, const unsigned char *msg, size_t msg_len, unsigned char *em, mp_bits_t embits, size_t salt_len) { /* [RFC8017] Page 44, Section 9.1.2. */ size_t hlen = hash_output_size(type); size_t slen = salt_len; size_t emlen = (embits + 7) >> 3; size_t dlen = emlen - hlen - 1; unsigned int mask = 0xff >> (8 * emlen - embits); unsigned char h0[HASH_MAX_OUTPUT_SIZE]; unsigned char *db, *h, *salt; hash_t hash; size_t i; if (msg_len!= hlen) return 0; if (emlen < hlen + slen + 2) return 0; if (em[emlen - 1]!= 0xbc) return 0; /* EM = (PS || 0x01 || salt) || H || 0xbc */ db = &em[0]; h = &em[emlen - hlen - 1]; if (em[0] & ~mask) return 0; mgf1xor(type, db, dlen, h, hlen); db[0] &= mask; if (slen == 0) { /* Auto */ for (i = 0; i < dlen; i++) { if (db[i] == 0x00) continue; if (db[i] == 0x01) break; return 0; } if (i == dlen) return 0; slen = dlen - (i + 1); } else { size_t len = dlen - slen - 1; for (i = 0; i < len; i++) { if (db[i]!= 0x00) return 0; } if (db[len]!= 0x01) return 0; } salt = &db[dlen - slen]; hash_init(&hash, type); hash_update(&hash, pss_prefix, sizeof(pss_prefix)); hash_update(&hash, msg, msg_len); hash_update(&hash, salt, slen); hash_final(&hash, h0, hlen); return safe_memequal(h0, h, hlen); } /* * RSA */ int rsa_privkey_generate(unsigned char *out, size_t *out_len, unsigned int bits, uint64_t exp, const unsigned char *entropy) { rsa_priv_t k; int ret = 0; rsa_priv_init(&k); if (bits > RSA_MAX_MOD_BITS) goto fail; if (!rsa_priv_generate(&k, bits, exp, entropy)) goto fail; rsa_priv_export(out, out_len, &k); ret = 1; fail: rsa_priv_clear(&k); return ret; } unsigned int rsa_privkey_bits(const unsigned char *key, size_t key_len) { mp_bits_t bits = 0; rsa_priv_t k; rsa_priv_init(&k); if (!rsa_priv_import(&k, key, key_len)) goto fail; if (!rsa_priv_verify(&k)) goto fail; bits = mpz_bitlen(k.n); fail: rsa_priv_clear(&k); return bits; } int rsa_privkey_verify(const unsigned char *key, size_t key_len) { rsa_priv_t k; int ret = 0; rsa_priv_init(&k); if (!rsa_priv_import(&k, key, key_len)) goto fail; if (!rsa_priv_verify(&k)) goto fail; ret = 1; fail: rsa_priv_clear(&k); return ret; } int rsa_privkey_import(unsigned char *out, size_t *out_len, const unsigned char *key, size_t key_len, const unsigned char *entropy) { rsa_priv_t k; int ret = 0; rsa_priv_init(&k); if (!rsa_priv_import_dumb(&k, key, key_len)) goto fail; if (!rsa_priv_verify(&k)) { if (mpz_sgn(k.p) > 0 && mpz_sgn(k.q) > 0) { if (mpz_sgn(k.e) > 0) ret = rsa_priv_set_pqe(&k, k.p, k.q, k.e); else ret = rsa_priv_set_pqd(&k, k.p, k.q, k.d); } else { ret = rsa_priv_set_ned(&k, k.n, k.e, k.d, entropy); } if (!ret) goto fail; } rsa_priv_export(out, out_len, &k); ret = 1; fail: rsa_priv_clear(&k); return ret; } int rsa_privkey_export(unsigned char *out, size_t *out_len, const unsigned char *key, size_t key_len) { rsa_priv_t k; int ret = 0; rsa_priv_init(&k); if (!rsa_priv_import(&k, key, key_len)) goto fail; if (!rsa_priv_verify(&k)) goto fail; rsa_priv_export_dumb(out, out_len, &k); ret = 1; fail: rsa_priv_clear(&k); return ret; } int rsa_pubkey_create(unsigned char *out, size_t *out_len, const unsigned char *key, size_t key_len) { rsa_priv_t k; rsa_pub_t p; int ret = 0; rsa_priv_init(&k); if (!rsa_priv_import(&k, key, key_len)) goto fail; if (!rsa_priv_verify(&k)) goto fail; mpz_roset(p.n, k.n); mpz_roset(p.e, k.e); rsa_pub_export(out, out_len, &p); ret = 1; fail: rsa_priv_clear(&k); return ret; } unsigned int rsa_pubkey_bits(const unsigned char *key, size_t key_len) { mp_bits_t bits = 0; rsa_pub_t k; rsa_pub_init(&k); if (!rsa_pub_import(&k, key, key_len)) goto fail; if (!rsa_pub_verify(&k)) goto fail; bits = mpz_bitlen(k.n); fail: rsa_pub_clear(&k); return bits; } int rsa_pubkey_verify(const unsigned char *key, size_t key_len) { rsa_pub_t k; int ret = 0; rsa_pub_init(&k); if (!rsa_pub_import(&k, key, key_len)) goto fail; if (!rsa_pub_verify(&k)) goto fail; ret = 1; fail: rsa_pub_clear(&k); return ret; } int rsa_pubkey_import(unsigned char *out, size_t *out_len, const unsigned char *key, size_t key_len) { rsa_pub_t k; int ret = 0; rsa_pub_init(&k); if (!rsa_pub_import_dumb(&k, key, key_len)) goto fail; if (!rsa_pub_verify(&k)) goto fail; rsa_pub_export(out, out_len, &k); ret = 1; fail: rsa_pub_clear(&k); return ret; } int rsa_pubkey_export(unsigned char *out, size_t *out_len, const unsigned char *key, size_t key_len) { rsa_pub_t k; int ret = 0; rsa_pub_init(&k); if (!rsa_pub_import(&k, key, key_len)) goto fail; if (!rsa_pub_verify(&k)) goto fail; rsa_pub_export_dumb(out, out_len, &k); ret = 1; fail: rsa_pub_clear(&k); return ret; } int rsa_sign(unsigned char *out, size_t *out_len, hash_id_t type, const unsigned char *msg, size_t msg_len, const unsigned char *key, size_t key_len, const unsigned char *entropy) { /* [RFC8017] Page 36, Section 8.2.1. * Page 45, Section 9.2. */ size_t hlen = hash_output_size(type); size_t i, prefix_len, tlen, klen; const unsigned char *prefix; unsigned char *em = out; rsa_priv_t k; int ret = 0; rsa_priv_init(&k); if (!get_digest_info(&prefix, &prefix_len, type)) goto fail; if (type == HASH_NONE) hlen = msg_len; if (msg_len!= hlen) goto fail; if (!rsa_priv_import(&k, key, key_len)) goto fail; if (!rsa_priv_verify(&k)) goto fail; tlen = prefix_len + hlen; klen = mpz_bytelen(k.n); if (klen < tlen + 11) goto fail; /* EM = 0x00 || 0x01 || PS || 0x00 || T */ em[0] = 0x00; em[1] = 0x01; for (i = 2; i < klen - tlen - 1; i++) em[i] = 0xff; em[klen - tlen - 1] = 0x00; if (prefix_len > 0) memcpy(em + klen - tlen, prefix, prefix_len); if (msg_len > 0) memcpy(em + klen - hlen, msg, msg_len); if (!rsa_priv_decrypt(&k, out, em, klen, 1, entropy)) goto fail; *out_len = klen; ret = 1; fail: rsa_priv_clear(&k); return ret; } int rsa_verify(hash_id_t type, const unsigned char *msg, size_t msg_len, const unsigned char *sig, size_t sig_len, const unsigned char *key, size_t key_len) { /* [RFC8017] Page 37, Section 8.2.2. * Page 45, Section 9.2. */ size_t hlen = hash_output_size(type); size_t i, prefix_len, tlen; size_t klen = 0; const unsigned char *prefix; unsigned char *em = NULL; uint32_t ok; rsa_pub_t k; int ret = 0; rsa_pub_init(&k); if (!get_digest_info(&prefix, &prefix_len, type)) goto fail; if (type == HASH_NONE) hlen = msg_len; if (msg_len!= hlen) goto fail; if (!rsa_pub_import(&k, key, key_len)) goto fail; if (!rsa_pub_verify(&k)) goto fail; tlen = prefix_len + hlen; klen = mpz_bytelen(k.n); if (sig_len!= klen) goto fail; if (klen < tlen + 11) goto fail; em = (unsigned char *)malloc(klen); if (em == NULL) goto fail; if (!rsa_pub_encrypt(&k, em, sig, sig_len)) goto fail; /* EM = 0x00 || 0x01 || PS || 0x00 || T */ ok = 1; ok &= safe_equal(em[0], 0x00); ok &= safe_equal(em[1], 0x01); for (i = 2; i < klen - tlen - 1; i++) ok &= safe_equal(em[i], 0xff); ok &= safe_equal(em[klen - tlen - 1], 0x00); ok &= safe_memequal(em + klen - tlen, prefix, prefix_len); ok &= safe_memequal(em + klen - hlen, msg, msg_len); ret = (ok == 1); fail: rsa_pub_clear(&k); if (em!= NULL) free(em); return ret; } int rsa_encrypt(unsigned char *out, size_t *out_len, const unsigned char *msg, size_t msg_len, const unsigned char *key, size_t key_len, const unsigned char *entropy) { /* [RFC8017] Page 28, Section 7.2.1. */ unsigned char *em = out; size_t i, mlen, plen; size_t klen = 0; rsa_pub_t k; int ret = 0; drbg_t rng; drbg_init(&rng, HASH_SHA256, entropy, ENTROPY_SIZE); rsa_pub_init(&k); if (!rsa_pub_import(&k, key, key_len)) goto fail; if (!rsa_pub_verify(&k)) goto fail; klen = mpz_bytelen(k.n); if (klen < 11) goto fail; if (msg_len > klen - 11) goto fail; /* EM = 0x00 || 0x02 || PS || 0x00 || M */ mlen = msg_len; plen = klen - mlen - 3; em[0] = 0x00; em[1] = 0x02; drbg_generate(&rng, em + 2, plen); for (i = 2; i < 2 + plen; i++) { while (em[i] == 0x00) drbg_generate(&rng, em + i, 1); } em[klen - mlen - 1] = 0x00; if (msg_len > 0) memcpy(em + klen - mlen, msg, msg_len); if (!rsa_pub_encrypt(&k, out, em, klen)) goto fail; *out_len = klen; ret = 1; fail: rsa_pub_clear(&k); torsion_memzero(&rng, sizeof(rng)); if (ret == 0) torsion_memzero(out, klen); return ret; } int rsa_decrypt(unsigned char *out, size_t *out_len, const unsigned char *msg, size_t msg_len, const unsigned char *key, size_t key_len, const unsigned char *entropy) { /* [RFC8017] Page 29, Section 7.2.2. */ unsigned char *em = out; uint32_t i, zero, two, index, looking; uint32_t equals0, validps, valid, offset; size_t klen = 0; rsa_priv_t k; int ret = 0; rsa_priv_init(&k); if (!rsa_priv_import(&k, key, key_len)) goto fail; if (!rsa_priv_verify(&k)) goto fail; klen = mpz_bytelen(k.n); if (msg_len!= klen) goto fail; if (klen < 11) goto fail; if (!rsa_priv_decrypt(&k, em, msg, msg_len, 1, entropy)) goto fail; /* EM = 0x00 || 0x02 || PS || 0x00 || M */ zero = safe_equal(em[0], 0x00); two = safe_equal(em[1], 0x02); index = 0; looking = 1; for (i = 2; i < klen; i++) { equals0 = safe_equal(em[i], 0x00); index = safe_select(index, i, looking & equals0); looking = safe_select(looking, 0, equals0); } validps = safe_lte(2 + 8, index); valid = zero & two & (looking ^ 1) & validps; offset = safe_select(0, index + 1, valid); if (valid == 0) goto fail; *out_len = klen - offset; memmove(out, em + offset, *out_len); ret = 1; fail: rsa_priv_clear(&k); if (ret == 0) torsion_memzero(out, klen); return ret; } int rsa_sign_pss(unsigned char *out, size_t *out_len, hash_id_t type, const unsigned char *msg, size_t msg_len, const unsigned char *key, size_t key_len, size_t salt_len, const unsigned char *entropy) { /* [RFC8017] Page 33, Section 8.1.1. */ size_t hlen = hash_output_size(type); unsigned char *salt = NULL; unsigned char *em = out; size_t klen = 0; mp_bits_t bits; size_t emlen; rsa_priv_t k; int ret = 0; drbg_t rng; rsa_priv_init(&k); if (!hash_has_backend(type)) goto fail; if (msg_len!= hlen) goto fail; if (!rsa_priv_import(&k, key, key_len)) goto fail; if (!rsa_priv_verify(&k)) goto fail; bits = mpz_bitlen(k.n); klen = (bits + 7) / 8; emlen = (bits + 6) / 8; if (salt_len == (size_t)RSA_SALT_LENGTH_AUTO) { if (emlen < 2 + hlen) goto fail; salt_len = emlen - 2 - hlen; } else if (salt_len == (size_t)RSA_SALT_LENGTH_HASH) { salt_len = hlen; } if (salt_len > klen) goto fail; if (salt_len > 0) { salt = (unsigned char *)malloc(salt_len); if (salt == NULL) goto fail; } drbg_init(&rng, HASH_SHA512, entropy, ENTROPY_SIZE); drbg_generate(&rng, salt, salt_len); if (!pss_encode(em, &emlen, type, msg, msg_len, bits - 1, salt, salt_len)) goto fail; /* Note that `em` may be one byte less * than the modulus size in the case * of (bits - 1) mod 8 == 0. */ if (!rsa_priv_decrypt(&k, out, em, emlen, 1, entropy)) goto fail; *out_len = klen; ret = 1; fail: rsa_priv_clear(&k); torsion_memzero(&rng, sizeof(rng)); if (salt!= NULL) free(salt); if (ret == 0) torsion_memzero(out, klen); return ret; } int rsa_verify_pss(hash_id_t type, const unsigned char *msg, size_t msg_len, const unsigned char *sig, size_t sig_len, const unsigned char *key, size_t key_len, size_t salt_len) { /* [RFC8017] Page 34, Section 8.1.2. */ size_t hlen = hash_output_size(type); unsigned char *em = NULL; size_t klen = 0; mp_bits_t bits; rsa_pub_t k; int ret = 0; rsa_pub_init(&k); if (!hash_has_backend(type)) goto fail; if (msg_len!= hlen) goto fail; if (!rsa_pub_import(&k, key, key_len)) goto fail; if (!rsa_pub_verify(&k)) goto fail; bits = mpz_bitlen(k.n); klen = (bits + 7) / 8; if (sig_len!= klen) goto fail; if (salt_len == (size_t)RSA_SALT_LENGTH_AUTO) salt_len = 0; /* Handled in pss_verify. */ else if (salt_len == (size_t)RSA_SALT_LENGTH_HASH) salt_len = hlen; if (salt_len > klen) goto fail; em = (unsigned char *)malloc(klen); if (em == NULL) goto fail; if (!rsa_pub_encrypt(&k, em, sig, sig_len)) goto fail; /* Edge case: the encoding crossed a * a byte boundary. Our encryption * function pads to the modulus size * by default, meaning there's one * extra zero byte prepended. */ if (((bits - 1) & 7) == 0) { if (em[0]!= 0x00) goto fail; if (!pss_verify(type, msg, msg_len, em + 1, bits - 1, salt_len)) goto fail; } else { if (!pss_verify(type, msg, msg_len, em, bits - 1, salt_len)) goto fail; } ret = 1; fail: rsa_pub_clear(&k); if (em!= NULL) free(em); return ret; } int rsa_encrypt_oaep(unsigned char *out, size_t *out_len, hash_id_t type, const unsigned char *msg, size_t msg_len, const unsigned char *key, size_t key_len, const unsigned char *label, size_t label_len, const unsigned char *entropy) { /* [RFC8017] Page 22, Section 7.1.1. */ unsigned char lhash[HASH_MAX_OUTPUT_SIZE]; unsigned char *em = out; unsigned char *seed, *db; size_t hlen = hash_output_size(type); size_t klen = 0; size_t mlen = msg_len; size_t slen, dlen; rsa_pub_t k; hash_t hash; int ret = 0; drbg_t rng; rsa_pub_init(&k); if (!hash_has_backend(type)) goto fail; if (!rsa_pub_import(&k, key, key_len)) goto fail; if (!rsa_pub_verify(&k)) goto fail; klen = mpz_bytelen(k.n); if (klen < 2 * hlen + 2) goto fail; if (msg_len > klen - 2 * hlen - 2) goto fail; hash_init(&hash, type); hash_update(&hash, label, label_len); hash_final(&hash, lhash, hlen); /* EM = 0x00 || (seed) || (Hash(L) || PS || 0x01 || M) */ seed = &em[1]; slen = hlen; db = &em[1 + hlen]; dlen = klen - (1 + hlen); em[0] = 0x00; drbg_init(&rng, HASH_SHA256, entropy, ENTROPY_SIZE); drbg_generate(&rng, seed, slen); memcpy(db, lhash, hlen); memset(db + hlen, 0x00, dlen - mlen - 1 - hlen); db[dlen - mlen - 1] = 0x01; if (mlen > 0) memcpy(db + dlen - mlen, msg, mlen); mgf1xor(type, db, dlen, seed, slen); mgf1xor(type, seed, slen, db, dlen); if (!rsa_pub_encrypt(&k, out, em, klen)) goto fail; *out_len = klen; ret = 1; fail: rsa_pub_clear(&k); torsion_memzero(&rng, sizeof(drbg_t)); torsion_memzero(&hash, sizeof(hash_t)); if (ret == 0) torsion_memzero(out, klen); return ret; } int rsa_decrypt_oaep(unsigned char *out, size_t *out_len, hash_id_t type, const unsigned char *msg, size_t msg_len, const unsigned char *key, size_t key_len, const unsigned char *label, size_t label_len, const unsigned char *entropy) { /* [RFC8017] Page 25, Section 7.1.2. */ unsigned char *em = out; unsigned char *seed, *db, *rest, *lhash; size_t i, slen, dlen, rlen; size_t hlen = hash_output_size(type); size_t klen = 0; uint32_t zero, lvalid, looking, index; uint32_t invalid, valid, equals0, equals1; unsigned char expect[HASH_MAX_OUTPUT_SIZE]; rsa_priv_t k; hash_t hash; int ret = 0; rsa_priv_init(&k); if (!hash_has_backend(type)) goto fail; if (!rsa_priv_import(&k, key, key_len)) goto fail; if (!rsa_priv_verify(&k)) goto fail; klen = mpz_bytelen(k.n); if (msg_len!= klen) goto fail; if (klen < hlen * 2 + 2) goto fail; if (!rsa_priv_decrypt(&k, em, msg, msg_len, 1, entropy)) goto fail; hash_init(&hash, type); hash_update(&hash, label, label_len); hash_final(&hash, expect, hlen); /* EM = 0x00 || (seed) || (Hash(L) || PS || 0x01 || M) */ zero = safe_equal(em[0], 0x00); seed = &em[1]; slen = hlen; db = &em[hlen + 1]; dlen = klen - (hlen + 1); mgf1xor(type, seed, slen, db, dlen); mgf1xor(type, db, dlen, seed, slen); lhash = &db[0]; lvalid = safe_memequal(lhash, expect, hlen); rest = &db[hlen]; rlen = dlen - hlen; looking = 1; index = 0; invalid = 0; for (i = 0; i < rlen; i++) { equals0 = safe_equal(rest[i], 0x00); equals1 = safe_equal(rest[i], 0x01); index = safe_select(index, i, looking & equals1); looking = safe_select(looking, 0, equals1); invalid = safe_select(invalid, 1, looking & (equals0 ^ 1)); } valid = zero & lvalid & (invalid ^ 1) & (looking ^ 1); if (valid == 0) goto fail; *out_len = rlen - (index + 1); memmove(out, rest + index + 1, *out_len); ret = 1; fail: rsa_priv_clear(&k); torsion_memzero(&hash, sizeof(hash)); if (ret == 0) torsion_memzero(out, klen); return ret; } int rsa_veil(unsigned char *out, size_t *out_len, const unsigned char *msg, size_t msg_len, unsigned int bits, const unsigned char *key, size_t key_len, const unsigned char *entropy) { rsa_pub_t k; int ret = 0; drbg_t rng; rsa_pub_init(&k); if (!rsa_pub_import(&k, key, key_len)) goto fail; if (!rsa_pub_verify(&k)) goto fail; if (msg_len!= mpz_bytelen(k.n)) goto fail; if (bits > RSA_MAX_MOD_BITS + 8) goto fail; if (!rsa_pub_veil(&k, out, msg, msg_len, bits, entropy)) goto fail; *out_len = (bits + 7) / 8; ret = 1; fail: torsion_memzero(&rng, sizeof(rng)); rsa_pub_clear(&k); return ret; } int rsa_unveil(unsigned char *out, size_t *out_len, const unsigned char *msg, size_t msg_len, unsigned int bits, const unsigned char *key, size_t key_len) { size_t klen = 0; rsa_pub_t k; int ret = 0; rsa_pub_init(&k); if (!rsa_pub_import(&k, key, key_len)) goto fail; if (!rsa_pub_verify(&k)) goto fail; klen = mpz_bytelen(k.n); if (msg_len < klen) goto fail; if (msg_len > RSA_MAX_MOD_SIZE + 1) goto fail; if (bits > RSA_MAX_MOD_BITS + 8) goto fail; if (!rsa_pub_unveil(&k, out, msg, msg_len, bits)) goto fail; *out_len = klen; ret = 1; fail: rsa_pub_clear(&k); return ret; } ======================= File: node_modules/bcrypto/deps/torsion/src/stream.c ======================= <filename>node_modules/bcrypto/deps/torsion/src/stream.c /*! * stream.c - stream ciphers for libtorsion * Copyright (c) 2020, <NAME> (MIT License). * https://github.com/bcoin-org/libtorsion */ #include <stdint.h> #include <stdlib.h> #include <string.h> #include <torsion/stream.h> #include <torsion/util.h> #include "bio.h" #include "internal.h" /* * ARC4 * * Resources: * https://en.wikipedia.org/wiki/RC4 * http://cypherpunks.venona.com/archive/1994/09/msg00304.html * https://web.archive.org/web/20080207125928/http://cypherpunks.venona.com/archive/1994/09/msg00304.html * https://tools.ietf.org/html/rfc4345 * https://tools.ietf.org/html/rfc6229 * https://github.com/golang/go/blob/master/src/crypto/rc4/rc4.go */ #define swap(x, y) do { \ uint8_t _x = (x); \ (x) = (y); \ (y) = _x; \ } while (0) void arc4_init(arc4_t *ctx, const unsigned char *key, size_t key_len) { uint8_t *s = ctx->s; size_t k = key_len; uint8_t j = 0; size_t i; CHECK(k >= 1 && k <= 256); for (i = 0; i < 256; i++) s[i] = i; for (i = 0; i < 256; i++) { j = (j + s[i] + key[i % k]) & 0xff; swap(s[i], s[j]); } ctx->i = 0; ctx->j = 0; } void arc4_crypt(arc4_t *ctx, unsigned char *dst, const unsigned char *src, size_t len) { uint8_t *s = ctx->s; uint8_t i = ctx->i; uint8_t j = ctx->j; size_t k; for (k = 0; k < len; k++) { i = (i + 1) & 0xff; j = (j + s[i]) & 0xff; swap(s[i], s[j]); dst[k] = src[k] ^ s[(s[i] + s[j]) & 0xff]; } ctx->i = i; ctx->j = j; } #undef swap /* * ChaCha20 * * Resources: * https://en.wikipedia.org/wiki/Chacha20 * https://tools.ietf.org/html/rfc7539#section-2 * https://cr.yp.to/chacha.html */ #define ROTL32(x, y) ((x) << (y)) | ((x) >> (32 - (y))) #define QROUND(x, a, b, c, d) \ x[a] += x[b]; x[d] = ROTL32(x[d] ^ x[a], 16); \ x[c] += x[d]; x[b] = ROTL32(x[b] ^ x[c], 12); \ x[a] += x[b]; x[d] = ROTL32(x[d] ^ x[a], 8); \ x[c] += x[d]; x[b] = ROTL32(x[b] ^ x[c], 7) void chacha20_init(chacha20_t *ctx, const unsigned char *key, size_t key_len, const unsigned char *nonce, size_t nonce_len, uint64_t counter) { uint8_t tmp[32]; CHECK(key_len == 16 || key_len == 32); if (nonce_len >= 24) { chacha20_derive(tmp, key, key_len, nonce); key = tmp; key_len = 32; nonce += 16; nonce_len -= 16; } ctx->state[0] = 0x61707865; ctx->state[1] = key_len < 32? 0x3120646e : 0x3320646e; ctx->state[2] = key_len < 32? <KEY> : 0x79622d32; ctx->state[3] = 0x6b206574; ctx->state[4] = read32le(key + 0); ctx->state[5] = read32le(key + 4); ctx->state[6] = read32le(key + 8); ctx->state[7] = read32le(key + 12); ctx->state[8] = read32le(key + 16 % key_len); ctx->state[9] = read32le(key + 20 % key_len); ctx->state[10] = read32le(key + 24 % key_len); ctx->state[11] = read32le(key + 28 % key_len); ctx->state[12] = counter; if (nonce_len == 8) { ctx->state[13] = counter >> 32; ctx->state[14] = read32le(nonce + 0); ctx->state[15] = read32le(nonce + 4); } else if (nonce_len == 12) { ctx->state[13] = read32le(nonce + 0); ctx->state[14] = read32le(nonce + 4); ctx->state[15] = read32le(nonce + 8); } else if (nonce_len == 16) { ctx->state[12] = read32le(nonce + 0); ctx->state[13] = read32le(nonce + 4); ctx->state[14] = read32le(nonce + 8); ctx->state[15] = read32le(nonce + 12); } else { torsion_abort(); /* LCOV_EXCL_LINE */ } ctx->pos = 0; torsion_memzero(tmp, sizeof(tmp)); } static void chacha20_block(chacha20_t *ctx, uint32_t *stream) { int i; for (i = 0; i < 16; i++) stream[i] = ctx->state[i]; for (i = 0; i < 10; i++) { QROUND(stream, 0, 4, 8, 12); QROUND(stream, 1, 5, 9, 13); QROUND(stream, 2, 6, 10, 14); QROUND(stream, 3, 7, 11, 15); QROUND(stream, 0, 5, 10, 15); QROUND(stream, 1, 6, 11, 12); QROUND(stream, 2, 7, 8, 13); QROUND(stream, 3, 4, 9, 14); } for (i = 0; i < 16; i++) stream[i] += ctx->state[i]; if (TORSION_BIGENDIAN) { for (i = 0; i < 16; i++) stream[i] = torsion_bswap32(stream[i]); } ctx->state[12] += 1; ctx->state[13] += (ctx->state[12] < 1); } void chacha20_crypt(chacha20_t *ctx, unsigned char *dst, const unsigned char *src, size_t len) { unsigned char *bytes = (unsigned char *)ctx->stream; size_t pos = ctx->pos; size_t want = 64 - pos; if (len >= want) { if (pos > 0) { torsion_memxor3(dst, src, bytes + pos, want); dst += want; src += want; len -= want; pos = 0; } while (len >= 64) { chacha20_block(ctx, ctx->stream); torsion_memxor3(dst, src, bytes, 64); dst += 64; src += 64; len -= 64; } } if (len > 0) { if (pos == 0) chacha20_block(ctx, ctx->stream); torsion_memxor3(dst, src, bytes + pos, len); pos += len; } ctx->pos = pos; } void chacha20_derive(unsigned char *out, const unsigned char *key, size_t key_len, const unsigned char *nonce16) { uint32_t state[16]; int i; CHECK(key_len == 16 || key_len == 32); state[0] = 0x61707865; state[1] = key_len < 32? 0x3120646e : 0x3320646e; state[2] = key_len < 32? 0x79622d36 : 0x79622d32; state[3] = 0x6b206574; state[4] = read32le(key + 0); state[5] = read32le(key + 4); state[6] = read32le(key + 8); state[7] = read32le(key + 12); state[8] = read32le(key + 16 % key_len); state[9] = read32le(key + 20 % key_len); state[10] = read32le(key + 24 % key_len); state[11] = read32le(key + 28 % key_len); state[12] = read32le(nonce16 + 0); state[13] = read32le(nonce16 + 4); state[14] = read32le(nonce16 + 8); state[15] = read32le(nonce16 + 12); for (i = 0; i < 10; i++) { QROUND(state, 0, 4, 8, 12); QROUND(state, 1, 5, 9, 13); QROUND(state, 2, 6, 10, 14); QROUND(state, 3, 7, 11, 15); QROUND(state, 0, 5, 10, 15); QROUND(state, 1, 6, 11, 12); QROUND(state, 2, 7, 8, 13); QROUND(state, 3, 4, 9, 14); } write32le(out + 0, state[0]); write32le(out + 4, state[1]); write32le(out + 8, state[2]); write32le(out + 12, state[3]); write32le(out + 16, state[12]); write32le(out + 20, state[13]); write32le(out + 24, state[14]); write32le(out + 28, state[15]); torsion_memzero(state, sizeof(state)); } #undef ROTL32 #undef QROUND /* * Salsa20 * * Resources * https://en.wikipedia.org/wiki/Salsa20 * https://cr.yp.to/snuffle.html * https://cr.yp.to/snuffle/spec.pdf * https://cr.yp.to/snuffle/812.pdf * http://www.ecrypt.eu.org/stream/salsa20pf.html */ #define ROTL32(x, y) ((x) << (y)) | ((x) >> (32 - (y))) #define QROUND(x, a, b, c, d) \ x[b] ^= ROTL32(x[a] + x[d], 7); \ x[c] ^= ROTL32(x[b] + x[a], 9); \ x[d] ^= ROTL32(x[c] + x[b], 13); \ x[a] ^= ROTL32(x[d] + x[c], 18) void salsa20_init(salsa20_t *ctx, const unsigned char *key, size_t key_len, const unsigned char *nonce, size_t nonce_len, uint64_t counter) { uint8_t tmp[32]; CHECK(key_len == 16 || key_len == 32); if (nonce_len >= 24) { salsa20_derive(tmp, key, key_len, nonce); key = tmp; key_len = 32; nonce += 16; nonce_len -= 16; } ctx->state[0] = 0x61707865; ctx->state[1] = read32le(key + 0); ctx->state[2] = read32le(key + 4); ctx->state[3] = read32le(key + 8); ctx->state[4] = read32le(key + 12); ctx->state[5] = key_len < 32? 0x3120646e : 0x3320646e; if (nonce_len == 8) { ctx->state[6] = read32le(nonce + 0); ctx->state[7] = read32le(nonce + 4); ctx->state[8] = counter; ctx->state[9] = counter >> 32; } else if (nonce_len == 12) { ctx->state[6] = read32le(nonce + 0); ctx->state[7] = read32le(nonce + 4); ctx->state[8] = read32le(nonce + 8); ctx->state[9] = counter; } else if (nonce_len == 16) { ctx->state[6] = read32le(nonce + 0); ctx->state[7] = read32le(nonce + 4); ctx->state[8] = read32le(nonce + 8); ctx->state[9] = read32le(nonce + 12); } else { torsion_abort(); /* LCOV_EXCL_LINE */ } ctx->state[10] = key_len < 32? 0x79622d36 : 0x79622d32; ctx->state[11] = read32le(key + 16 % key_len); ctx->state[12] = read32le(key + 20 % key_len); ctx->state[13] = read32le(key + 24 % key_len); ctx->state[14] = read32le(key + 28 % key_len); ctx->state[15] = 0x6b206574; ctx->pos = 0; torsion_memzero(tmp, sizeof(tmp)); } static void salsa20_block(salsa20_t *ctx, uint32_t *stream) { int i; for (i = 0; i < 16; i++) stream[i] = ctx->state[i]; for (i = 0; i < 10; i++) { QROUND(stream, 0, 4, 8, 12); QROUND(stream, 5, 9, 13, 1); QROUND(stream, 10, 14, 2, 6); QROUND(stream, 15, 3, 7, 11); QROUND(stream, 0, 1, 2, 3); QROUND(stream, 5, 6, 7, 4); QROUND(stream, 10, 11, 8, 9); QROUND(stream, 15, 12, 13, 14); } for (i = 0; i < 16; i++) stream[i] += ctx->state[i]; if (TORSION_BIGENDIAN) { for (i = 0; i < 16; i++) stream[i] = torsion_bswap32(stream[i]); } ctx->state[8] += 1; ctx->state[9] += (ctx->state[8] < 1); } void salsa20_crypt(salsa20_t *ctx, unsigned char *dst, const unsigned char *src, size_t len) { unsigned char *bytes = (unsigned char *)ctx->stream; size_t pos = ctx->pos; size_t want = 64 - pos; if (len >= want) { if (pos > 0) { torsion_memxor3(dst, src, bytes + pos, want); dst += want; src += want; len -= want; pos = 0; } while (len >= 64) { salsa20_block(ctx, ctx->stream); torsion_memxor3(dst, src, bytes, 64); dst += 64; src += 64; len -= 64; } } if (len > 0) { if (pos == 0) salsa20_block(ctx, ctx->stream); torsion_memxor3(dst, src, bytes + pos, len); pos += len; } ctx->pos = pos; } void salsa20_derive(unsigned char *out, const unsigned char *key, size_t key_len, const unsigned char *nonce16) { uint32_t state[16]; int i; CHECK(key_len == 16 || key_len == 32); state[0] = 0x61707865; state[1] = read32le(key + 0); state[2] = read32le(key + 4); state[3] = read32le(key + 8); state[4] = read32le(key + 12); state[5] = key_len < 32? 0x3120646e : 0x3320646e; state[6] = read32le(nonce16 + 0); state[7] = read32le(nonce16 + 4); state[8] = read32le(nonce16 + 8); state[9] = read32le(nonce16 + 12); state[10] = key_len < 32? 0x79622d36 : 0x79622d32; state[11] = read32le(key + 16 % key_len); state[12] = read32le(key + 20 % key_len); state[13] = read32le(key + 24 % key_len); state[14] = read32le(key + 28 % key_len); state[15] = 0x6b206574; for (i = 0; i < 10; i++) { QROUND(state, 0, 4, 8, 12); QROUND(state, 5, 9, 13, 1); QROUND(state, 10, 14, 2, 6); QROUND(state, 15, 3, 7, 11); QROUND(state, 0, 1, 2, 3); QROUND(state, 5, 6, 7, 4); QROUND(state, 10, 11, 8, 9); QROUND(state, 15, 12, 13, 14); } write32le(out + 0, state[0]); write32le(out + 4, state[5]); write32le(out + 8, state[10]); write32le(out + 12, state[15]); write32le(out + 16, state[6]); write32le(out + 20, state[7]); write32le(out + 24, state[8]); write32le(out + 28, state[9]); torsion_memzero(state, sizeof(state)); } #undef ROTL32 #undef QROUND ======================= File: node_modules/bcrypto/deps/torsion/src/fields/p448_32.h ======================= <reponame>pradyuman-verma/bcoin /* Autogenerated: /src/ExtractionOCaml/unsaturated_solinas --static p448 32 18 '2^448 - 2^224 - 1' add sub opp carry carry_mul carry_square carry_scmul3 carry_scmul4 carry_scmul8 carry_scmul39082 carry_scmul39081 selectznz to_bytes from_bytes */ /* curve description: p448 */ /* machine_wordsize = 32 (from "32") */ /* requested operations: add, sub, opp, carry, carry_mul, carry_square, carry_scmul3, carry_scmul4, carry_scmul8, carry_scmul39082, carry_scmul39081, selectznz, to_bytes, from_bytes */ /* n = 18 (from "18") */ /* s-c = 2^448 - [(2^224, 1), (1, 1)] (from "2^448 - 2^224 - 1") */ /* tight_bounds_multiplier = 1 (from "") */ /* */ /* Computed values: */ /* carry_chain = [8, 17, 9, 0, 10, 1, 11, 2, 12, 3, 13, 4, 14, 5, 15, 6, 16, 7, 17, 8, 9, 0] */ /* eval z = z[0] + (z[1] << 25) + (z[2] << 50) + (z[3] << 75) + (z[4] << 100) + (z[5] << 125) + (z[6] << 150) + (z[7] << 175) + (z[8] << 200) + (z[9] << 224) + (z[10] << 249) + (z[11] << 0x112) + (z[12] << 0x12b) + (z[13] << 0x144) + (z[14] << 0x15d) + (z[15] << 0x176) + (z[16] << 0x18f) + (z[17] << 0x1a8) */ /* bytes_eval z = z[0] + (z[1] << 8) + (z[2] << 16) + (z[3] << 24) + (z[4] << 32) + (z[5] << 40) + (z[6] << 48) + (z[7] << 56) + (z[8] << 64) + (z[9] << 72) + (z[10] << 80) + (z[11] << 88) + (z[12] << 96) + (z[13] << 104) + (z[14] << 112) + (z[15] << 120) + (z[16] << 128) + (z[17] << 136) + (z[18] << 144) + (z[19] << 152) + (z[20] << 160) + (z[21] << 168) + (z[22] << 176) + (z[23] << 184) + (z[24] << 192) + (z[25] << 200) + (z[26] << 208) + (z[27] << 216) + (z[28] << 224) + (z[29] << 232) + (z[30] << 240) + (z[31] << 248) + (z[32] << 256) + (z[33] << 0x108) + (z[34] << 0x110) + (z[35] << 0x118) + (z[36] << 0x120) + (z[37] << 0x128) + (z[38] << 0x130) + (z[39] << 0x138) + (z[40] << 0x140) + (z[41] << 0x148) + (z[42] << 0x150) + (z[43] << 0x158) + (z[44] << 0x160) + (z[45] << 0x168) + (z[46] << 0x170) + (z[47] << 0x178) + (z[48] << 0x180) + (z[49] << 0x188) + (z[50] << 0x190) + (z[51] << 0x198) + (z[52] << 0x1a0) + (z[53] << 0x1a8) + (z[54] << 0x1b0) + (z[55] << 0x1b8) */ /* balance = [0x3fffffe, 0x3fffffe, 0x3fffffe, 0x3fffffe, 0x3fffffe, 0x3fffffe, 0x3fffffe, 0x3fffffe, 0x1fffffe, 0x3fffffc, 0x3fffffe, 0x3fffffe, 0x3fffffe, 0x3fffffe, 0x3fffffe, 0x3fffffe, 0x3fffffe, 0x1fffffe] */ #include <stdint.h> typedef unsigned char fiat_p448_uint1; typedef signed char fiat_p448_int1; #if (-1 & 3)!= 3 #error "This code only works on a two's complement system" #endif /* * The function fiat_p448_addcarryx_u24 is an addition with carry. * Postconditions: * out1 = (arg1 + arg2 + arg3) mod 2^24 * out2 = ⌊(arg1 + arg2 + arg3) / 2^24⌋ * * Input Bounds: * arg1: [0x0 ~> 0x1] * arg2: [0x0 ~> 0xffffff] * arg3: [0x0 ~> 0xffffff] * Output Bounds: * out1: [0x0 ~> 0xffffff] * out2: [0x0 ~> 0x1] */ static void fiat_p448_addcarryx_u24(uint32_t* out1, fiat_p448_uint1* out2, fiat_p448_uint1 arg1, uint32_t arg2, uint32_t arg3) { uint32_t x1; uint32_t x2; fiat_p448_uint1 x3; x1 = ((arg1 + arg2) + arg3); x2 = (x1 & UINT32_C(0xffffff)); x3 = (fiat_p448_uint1)(x1 >> 24); *out1 = x2; *out2 = x3; } /* * The function fiat_p448_subborrowx_u24 is a subtraction with borrow. * Postconditions: * out1 = (-arg1 + arg2 + -arg3) mod 2^24 * out2 = -⌊(-arg1 + arg2 + -arg3) / 2^24⌋ * * Input Bounds: * arg1: [0x0 ~> 0x1] * arg2: [0x0 ~> 0xffffff] * arg3: [0x0 ~> 0xffffff] * Output Bounds: * out1: [0x0 ~> 0xffffff] * out2: [0x0 ~> 0x1] */ static void fiat_p448_subborrowx_u24(uint32_t* out1, fiat_p448_uint1* out2, fiat_p448_uint1 arg1, uint32_t arg2, uint32_t arg3) { int32_t x1; fiat_p448_int1 x2; uint32_t x3; x1 = ((int32_t)(arg2 - arg1) - (int32_t)arg3); x2 = (fiat_p448_int1)(x1 >> 24); x3 = (x1 & UINT32_C(0xffffff)); *out1 = x3; *out2 = (fiat_p448_uint1)(0x0 - x2); } /* * The function fiat_p448_addcarryx_u25 is an addition with carry. * Postconditions: * out1 = (arg1 + arg2 + arg3) mod 2^25 * out2 = ⌊(arg1 + arg2 + arg3) / 2^25⌋ * * Input Bounds: * arg1: [0x0 ~> 0x1] * arg2: [0x0 ~> 0x1ffffff] * arg3: [0x0 ~> 0x1ffffff] * Output Bounds: * out1: [0x0 ~> 0x1ffffff] * out2: [0x0 ~> 0x1] */ static void fiat_p448_addcarryx_u25(uint32_t* out1, fiat_p448_uint1* out2, fiat_p448_uint1 arg1, uint32_t arg2, uint32_t arg3) { uint32_t x1; uint32_t x2; fiat_p448_uint1 x3; x1 = ((arg1 + arg2) + arg3); x2 = (x1 & UINT32_C(0x1ffffff)); x3 = (fiat_p448_uint1)(x1 >> 25); *out1 = x2; *out2 = x3; } /* * The function fiat_p448_subborrowx_u25 is a subtraction with borrow. * Postconditions: * out1 = (-arg1 + arg2 + -arg3) mod 2^25 * out2 = -⌊(-arg1 + arg2 + -arg3) / 2^25⌋ * * Input Bounds: * arg1: [0x0 ~> 0x1] * arg2: [0x0 ~> 0x1ffffff] * arg3: [0x0 ~> 0x1ffffff] * Output Bounds: * out1: [0x0 ~> 0x1ffffff] * out2: [0x0 ~> 0x1] */ static void fiat_p448_subborrowx_u25(uint32_t* out1, fiat_p448_uint1* out2, fiat_p448_uint1 arg1, uint32_t arg2, uint32_t arg3) { int32_t
1,501
; [global::System.ComponentModel.BrowsableAttribute(false)] public System.Runtime.Serialization.ExtensionDataObject ExtensionData { get { return this.extensionDataField; } set { this.extensionDataField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] public int AnswerQuantity { get { return this.AnswerQuantityField; } set { if ((this.AnswerQuantityField.Equals(value)!= true)) { this.AnswerQuantityField = value; this.RaisePropertyChanged("AnswerQuantity"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public long CustOrder { get { return this.CustOrderField; } set { if ((this.CustOrderField.Equals(value)!= true)) { this.CustOrderField = value; this.RaisePropertyChanged("CustOrder"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string CustomerLogo { get { return this.CustomerLogoField; } set { if ((object.ReferenceEquals(this.CustomerLogoField, value)!= true)) { this.CustomerLogoField = value; this.RaisePropertyChanged("CustomerLogo"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string CustomersGroupsLogo { get { return this.CustomersGroupsLogoField; } set { if ((object.ReferenceEquals(this.CustomersGroupsLogoField, value)!= true)) { this.CustomersGroupsLogoField = value; this.RaisePropertyChanged("CustomersGroupsLogo"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string DestinationLogo { get { return this.DestinationLogoField; } set { if ((object.ReferenceEquals(this.DestinationLogoField, value)!= true)) { this.DestinationLogoField = value; this.RaisePropertyChanged("DestinationLogo"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string DetailMakeAndNum { get { return this.DetailMakeAndNumField; } set { if ((object.ReferenceEquals(this.DetailMakeAndNumField, value)!= true)) { this.DetailMakeAndNumField = value; this.RaisePropertyChanged("DetailMakeAndNum"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string DetailName { get { return this.DetailNameField; } set { if ((object.ReferenceEquals(this.DetailNameField, value)!= true)) { this.DetailNameField = value; this.RaisePropertyChanged("DetailName"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string DetailNameCust { get { return this.DetailNameCustField; } set { if ((object.ReferenceEquals(this.DetailNameCustField, value)!= true)) { this.DetailNameCustField = value; this.RaisePropertyChanged("DetailNameCust"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string DetailNum { get { return this.DetailNumField; } set { if ((object.ReferenceEquals(this.DetailNumField, value)!= true)) { this.DetailNumField = value; this.RaisePropertyChanged("DetailNum"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public float DetailPriceRUR { get { return this.DetailPriceRURField; } set { if ((this.DetailPriceRURField.Equals(value)!= true)) { this.DetailPriceRURField = value; this.RaisePropertyChanged("DetailPriceRUR"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public bool IsRowHidden { get { return this.IsRowHiddenField; } set { if ((this.IsRowHiddenField.Equals(value)!= true)) { this.IsRowHiddenField = value; this.RaisePropertyChanged("IsRowHidden"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string MakeName { get { return this.MakeNameField; } set { if ((object.ReferenceEquals(this.MakeNameField, value)!= true)) { this.MakeNameField = value; this.RaisePropertyChanged("MakeName"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public System.DateTime OrderDate { get { return this.OrderDateField; } set { if ((this.OrderDateField.Equals(value)!= true)) { this.OrderDateField = value; this.RaisePropertyChanged("OrderDate"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public long OrderDetailId { get { return this.OrderDetailIdField; } set { if ((this.OrderDetailIdField.Equals(value)!= true)) { this.OrderDetailIdField = value; this.RaisePropertyChanged("OrderDetailId"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public int OrderQuantity { get { return this.OrderQuantityField; } set { if ((this.OrderQuantityField.Equals(value)!= true)) { this.OrderQuantityField = value; this.RaisePropertyChanged("OrderQuantity"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string PriceLogo { get { return this.PriceLogoField; } set { if ((object.ReferenceEquals(this.PriceLogoField, value)!= true)) { this.PriceLogoField = value; this.RaisePropertyChanged("PriceLogo"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string Reference { get { return this.ReferenceField; } set { if ((object.ReferenceEquals(this.ReferenceField, value)!= true)) { this.ReferenceField = value; this.RaisePropertyChanged("Reference"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string SubstDetailMakeAndNum { get { return this.SubstDetailMakeAndNumField; } set { if ((object.ReferenceEquals(this.SubstDetailMakeAndNumField, value)!= true)) { this.SubstDetailMakeAndNumField = value; this.RaisePropertyChanged("SubstDetailMakeAndNum"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string SubstDetailNum { get { return this.SubstDetailNumField; } set { if ((object.ReferenceEquals(this.SubstDetailNumField, value)!= true)) { this.SubstDetailNumField = value; this.RaisePropertyChanged("SubstDetailNum"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string SubstMakeLogo { get { return this.SubstMakeLogoField; } set { if ((object.ReferenceEquals(this.SubstMakeLogoField, value)!= true)) { this.SubstMakeLogoField = value; this.RaisePropertyChanged("SubstMakeLogo"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string SupplierLogo { get { return this.SupplierLogoField; } set { if ((object.ReferenceEquals(this.SupplierLogoField, value)!= true)) { this.SupplierLogoField = value; this.RaisePropertyChanged("SupplierLogo"); } } } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if ((propertyChanged!= null)) { propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="SalesHistoryDetail", Namespace="http://schemas.datacontract.org/2004/07/Emex.DetailsHistory")] [System.SerializableAttribute()] public partial class SalesHistoryDetail : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged { [System.NonSerializedAttribute()] private System.Runtime.Serialization.ExtensionDataObject extensionDataField; [System.Runtime.Serialization.OptionalFieldAttribute()] private float BuyRURField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string CommentField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string CostField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string CountryField; [System.Runtime.Serialization.OptionalFieldAttribute()] private System.DateTime DateReadyForAccountField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string DetSubField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string DetailNumField; [System.Runtime.Serialization.OptionalFieldAttribute()] private float DetailPriceBuyRURField; [System.Runtime.Serialization.OptionalFieldAttribute()] private float DetailPriceRURField; [System.Runtime.Serialization.OptionalFieldAttribute()] private System.DateTime DocDateField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string DocLogoField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string DocNumberField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string DocTypeField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string GTDField; [System.Runtime.Serialization.OptionalFieldAttribute()] private long GlobalIdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private long InvoicesDetailIdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string MakeNameField; [System.Runtime.Serialization.OptionalFieldAttribute()] private long OrderDetailIdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private long OrderDetailSubIdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string PackerNameField; [System.Runtime.Serialization.OptionalFieldAttribute()] private int PortionField; [System.Runtime.Serialization.OptionalFieldAttribute()] private int QuantityField; [System.Runtime.Serialization.OptionalFieldAttribute()] private long ReceiptsDetailIdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string ReceiverNameField; [System.Runtime.Serialization.OptionalFieldAttribute()] private float SaleRURField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string StackerNameField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string SupplierLogoField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string UserNameField; [global::System.ComponentModel.BrowsableAttribute(false)] public System.Runtime.Serialization.ExtensionDataObject ExtensionData { get { return this.extensionDataField; } set { this.extensionDataField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] public float BuyRUR { get { return this.BuyRURField; } set { if ((this.BuyRURField.Equals(value)!= true)) { this.BuyRURField = value; this.RaisePropertyChanged("BuyRUR"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string Comment { get { return this.CommentField; } set { if ((object.ReferenceEquals(this.CommentField, value)!= true)) { this.CommentField = value; this.RaisePropertyChanged("Comment"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string Cost { get { return this.CostField; } set { if ((object.ReferenceEquals(this.CostField, value)!= true)) { this.CostField = value; this.RaisePropertyChanged("Cost"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string Country { get { return this.CountryField; } set { if ((object.ReferenceEquals(this.CountryField, value)!= true)) { this.CountryField = value; this.RaisePropertyChanged("Country"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public System.DateTime DateReadyForAccount { get { return this.DateReadyForAccountField; } set { if ((this.DateReadyForAccountField.Equals(value)!= true)) { this.DateReadyForAccountField = value; this.RaisePropertyChanged("DateReadyForAccount"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string DetSub { get { return this.DetSubField; } set { if ((object.ReferenceEquals(this.DetSubField, value)!= true)) { this.DetSubField = value; this.RaisePropertyChanged("DetSub"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string DetailNum { get { return this.DetailNumField; } set { if ((object.ReferenceEquals(this.DetailNumField, value)!= true)) { this.DetailNumField = value; this.RaisePropertyChanged("DetailNum"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public float DetailPriceBuyRUR { get { return this.DetailPriceBuyRURField; } set { if ((this.DetailPriceBuyRURField.Equals(value)!= true)) { this.DetailPriceBuyRURField = value; this.RaisePropertyChanged("DetailPriceBuyRUR"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public float DetailPriceRUR { get { return this.DetailPriceRURField; } set { if ((this.DetailPriceRURField.Equals(value)!= true)) { this.DetailPriceRURField = value; this.RaisePropertyChanged("DetailPriceRUR"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public System.DateTime DocDate { get { return this.DocDateField; } set { if ((this.DocDateField.Equals(value)!= true)) { this.DocDateField = value; this.RaisePropertyChanged("DocDate"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string DocLogo { get { return this.DocLogoField; } set { if ((object.ReferenceEquals(this.DocLogoField, value)!= true)) { this.DocLogoField = value; this.RaisePropertyChanged("DocLogo"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string DocNumber { get { return this.DocNumberField; } set { if ((object.ReferenceEquals(this.DocNumberField, value)!= true)) { this.DocNumberField = value; this.RaisePropertyChanged("DocNumber"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string DocType { get { return this.DocTypeField; } set { if ((object.ReferenceEquals(this.DocTypeField, value)!= true)) { this.DocTypeField = value; this.RaisePropertyChanged("DocType"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string GTD { get { return this.GTDField; } set { if ((object.ReferenceEquals(this.GTDField, value)!= true)) { this.GTDField = value; this.RaisePropertyChanged("GTD"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public long GlobalId { get { return this.GlobalIdField; } set { if ((this.GlobalIdField.Equals(value)!= true)) { this.GlobalIdField = value; this.RaisePropertyChanged("GlobalId"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public long InvoicesDetailId { get { return this.InvoicesDetailIdField; } set { if ((this.InvoicesDetailIdField.Equals(value)!= true)) { this.InvoicesDetailIdField = value; this.RaisePropertyChanged("InvoicesDetailId"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string MakeName { get { return this.MakeNameField; } set { if ((object.ReferenceEquals(this.MakeNameField, value)!= true)) { this.MakeNameField = value; this.RaisePropertyChanged("MakeName"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public long OrderDetailId { get { return this.OrderDetailIdField; } set { if ((this.OrderDetailIdField.Equals(value)!= true)) { this.OrderDetailIdField = value; this.RaisePropertyChanged("OrderDetailId"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public long OrderDetailSubId { get { return this.OrderDetailSubIdField; } set { if ((this.OrderDetailSubIdField.Equals(value)!= true)) { this.OrderDetailSubIdField = value; this.RaisePropertyChanged("OrderDetailSubId"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string PackerName { get { return this.PackerNameField; } set { if ((object.ReferenceEquals(this.PackerNameField, value)!= true)) { this.PackerNameField = value; this.RaisePropertyChanged("PackerName"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public int Portion { get { return this.PortionField; } set { if ((this.PortionField.Equals(value)!= true)) { this.PortionField = value; this.RaisePropertyChanged("Portion"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public int Quantity { get { return this.QuantityField; } set { if ((this.QuantityField.Equals(value)!= true)) { this.QuantityField = value; this.RaisePropertyChanged("Quantity"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public long ReceiptsDetailId { get { return this.ReceiptsDetailIdField; } set { if ((this.ReceiptsDetailIdField.Equals(value)!= true)) { this.ReceiptsDetailIdField = value; this.RaisePropertyChanged("ReceiptsDetailId"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string ReceiverName { get { return this.ReceiverNameField; } set { if ((object.ReferenceEquals(this.ReceiverNameField, value)!= true)) { this.ReceiverNameField = value; this.RaisePropertyChanged("ReceiverName"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public float SaleRUR { get { return this.SaleRURField; } set { if ((this.SaleRURField.Equals(value)!= true)) { this.SaleRURField = value; this.RaisePropertyChanged("SaleRUR"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string StackerName { get { return this.StackerNameField; } set { if ((object.ReferenceEquals(this.StackerNameField, value)!= true)) { this.StackerNameField = value; this.RaisePropertyChanged("StackerName"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string SupplierLogo { get { return this.SupplierLogoField; } set { if ((object.ReferenceEquals(this.SupplierLogoField, value)!= true)) { this.SupplierLogoField = value; this.RaisePropertyChanged("SupplierLogo"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string UserName { get { return this.UserNameField; } set { if ((object.ReferenceEquals(this.UserNameField, value)!= true)) { this.UserNameField = value; this.RaisePropertyChanged("UserName"); } } } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if ((propertyChanged!= null)) { propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="DenyType", Namespace="http://schemas.datacontract.org/2004/07/Emex.DetailsHistory")] [System.SerializableAttribute()] public partial class DenyType : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged { [System.NonSerializedAttribute()] private System.Runtime.Serialization.ExtensionDataObject extensionDataField; [System.Runtime.Serialization.OptionalFieldAttribute()] private int DenyDetailsTypeIdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string DenyDetailsTypeNameField; [global::System.ComponentModel.BrowsableAttribute(false)] public System.Runtime.Serialization.ExtensionDataObject ExtensionData { get { return this.extensionDataField; } set { this.extensionDataField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] public int DenyDetailsTypeId { get { return this.DenyDetailsTypeIdField; } set { if ((this.DenyDetailsTypeIdField.Equals(value)!= true)) { this.DenyDetailsTypeIdField = value; this.RaisePropertyChanged("DenyDetailsTypeId"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string DenyDetailsTypeName { get { return this.DenyDetailsTypeNameField; } set { if ((object.ReferenceEquals(this.DenyDetailsTypeNameField, value)!= true)) { this.DenyDetailsTypeNameField = value; this.RaisePropertyChanged("DenyDetailsTypeName"); } } } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if ((propertyChanged!= null)) { propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="DeleteType", Namespace="http://schemas.datacontract.org/2004/07/Emex.DetailsHistory")] [System.SerializableAttribute()] public partial class DeleteType : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged { [System.NonSerializedAttribute()] private System.Runtime.Serialization.ExtensionDataObject extensionDataField; [System.Runtime.Serialization.OptionalFieldAttribute()] private int DeleteTypeIdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string DeleteTypeNameField; [global::System.ComponentModel.BrowsableAttribute(false)] public System.Runtime.Serialization.ExtensionDataObject ExtensionData { get { return this.extensionDataField; } set { this.extensionDataField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] public int DeleteTypeId { get { return this.DeleteTypeIdField; } set { if ((this.DeleteTypeIdField.Equals(value)!= true)) { this.DeleteTypeIdField = value; this.RaisePropertyChanged("DeleteTypeId"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string DeleteTypeName { get { return this.DeleteTypeNameField; } set { if ((object.ReferenceEquals(this.DeleteTypeNameField, value)!= true)) { this.DeleteTypeNameField = value; this.RaisePropertyChanged("DeleteTypeName"); } } } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if ((propertyChanged!= null)) { propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="DenyStatus", Namespace="http://schemas.datacontract.org/2004/07/Emex.DetailsHistory")] [System.SerializableAttribute()] public partial class DenyStatus : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged { [System.NonSerializedAttribute()] private System.Runtime.Serialization.ExtensionDataObject extensionDataField; [System.Runtime.Serialization.OptionalFieldAttribute()] private int DenyDetailsStatusIdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string DenyDetailsStatusNameField; [global::System.ComponentModel.BrowsableAttribute(false)] public System.Runtime.Serialization.ExtensionDataObject ExtensionData { get { return this.extensionDataField; } set { this.extensionDataField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] public int DenyDetailsStatusId { get { return this.DenyDetailsStatusIdField; } set { if ((this.DenyDetailsStatusIdField.Equals(value)!= true)) { this.DenyDetailsStatusIdField = value; this.RaisePropertyChanged("DenyDetailsStatusId"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string DenyDetailsStatusName { get { return this.DenyDetailsStatusNameField; } set { if ((object.ReferenceEquals(this.DenyDetailsStatusNameField, value)!= true)) { this.DenyDetailsStatusNameField = value; this.RaisePropertyChanged("DenyDetailsStatusName"); } } } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if ((propertyChanged!= null)) { propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="ChangeAnswerLogLine", Namespace="http://schemas.datacontract.org/2004/07/Emex.DetailsHistory")] [System.SerializableAttribute()] public partial class ChangeAnswerLogLine : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged { [System.NonSerializedAttribute()] private System.Runtime.Serialization.ExtensionDataObject extensionDataField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string CommentField; [System.Runtime.Serialization.OptionalFieldAttribute()] private System.DateTime DateAddField; [System.Runtime.Serialization.OptionalFieldAttribute()] private long IdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string TypeField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string UserLogoField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string ValField; [global::System.ComponentModel.BrowsableAttribute(false)] public System.Runtime.Serialization.ExtensionDataObject ExtensionData { get { return this.extensionDataField; } set { this.extensionDataField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] public string Comment { get { return this.CommentField; } set { if ((object.ReferenceEquals(this.CommentField, value)!= true)) { this.CommentField = value; this.RaisePropertyChanged("Comment"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public System.DateTime DateAdd { get { return this.DateAddField; } set { if ((this.DateAddField.Equals(value)!= true)) { this.DateAddField = value; this.RaisePropertyChanged("DateAdd"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public long Id { get { return this.IdField; } set { if ((this.IdField.Equals(value)!= true)) { this.IdField = value; this.RaisePropertyChanged("Id"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string Type { get { return this.TypeField; } set { if ((object.ReferenceEquals(this.TypeField, value)!= true)) { this.TypeField = value; this.RaisePropertyChanged("Type"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string UserLogo { get { return this.UserLogoField; } set { if ((object.ReferenceEquals(this.UserLogoField, value)!= true)) { this.UserLogoField = value; this.RaisePropertyChanged("UserLogo"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string Val { get { return this.ValField; } set { if ((object.ReferenceEquals(this.ValField, value)!= true)) { this.ValField = value; this.RaisePropertyChanged("Val"); } } } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if ((propertyChanged!= null)) { propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="DetailDto", Namespace="http://schemas.datacontract.org/2004/07/Emex.Stock")] [System.SerializableAttribute()] public partial class DetailDto : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged { [System.NonSerializedAttribute()] private System.Runtime.Serialization.ExtensionDataObject extensionDataField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string CommentField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string DetailDescField; [System.Runtime.Serialization.OptionalFieldAttribute()] private long DetailIdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string DetailNameField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string DetailNameCustField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string DetailNameCustSField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string DetailNameRusField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string DetailNumField; [System.Runtime.Serialization.OptionalFieldAttribute()] private int DetailWeightField; [System.Runtime.Serialization.OptionalFieldAttribute()] private long MakeIdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string MakeLogoField; [global::System.ComponentModel.BrowsableAttribute(false)] public System.Runtime.Serialization.ExtensionDataObject ExtensionData { get { return this.extensionDataField; } set { this.extensionDataField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] public string Comment { get { return this.CommentField; } set { if ((object.ReferenceEquals(this.CommentField, value)!= true)) { this.CommentField = value; this.RaisePropertyChanged("Comment"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string DetailDesc { get { return this.DetailDescField; } set { if ((object.ReferenceEquals(this.DetailDescField, value)!= true)) { this.DetailDescField = value; this.RaisePropertyChanged("DetailDesc"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public long DetailId { get { return this.DetailIdField; } set { if ((this.DetailIdField.Equals(value)!= true)) { this.DetailIdField = value; this.RaisePropertyChanged("DetailId"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string DetailName { get { return this.DetailNameField; } set { if ((object.ReferenceEquals(this.DetailNameField, value)!= true)) { this.DetailNameField = value; this.RaisePropertyChanged("DetailName"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string DetailNameCust { get { return this.DetailNameCustField; } set { if ((object.ReferenceEquals(this.DetailNameCustField, value)!= true)) { this.DetailNameCustField = value; this.RaisePropertyChanged("DetailNameCust"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string DetailNameCustS { get { return this.DetailNameCustSField; } set { if ((object.ReferenceEquals(this.DetailNameCustSField, value)!= true)) { this.DetailNameCustSField = value; this.RaisePropertyChanged("DetailNameCustS"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string DetailNameRus { get { return this.DetailNameRusField; } set { if ((object.ReferenceEquals(this.DetailNameRusField, value)!= true)) { this.DetailNameRusField = value; this.RaisePropertyChanged("DetailNameRus"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string DetailNum { get { return this.DetailNumField; } set { if ((object.ReferenceEquals(this.DetailNumField, value)!= true)) { this.DetailNumField = value; this.RaisePropertyChanged("DetailNum"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public int DetailWeight { get { return this.DetailWeightField; } set { if ((this.DetailWeightField.Equals(value)!= true)) { this.DetailWeightField = value; this.RaisePropertyChanged("DetailWeight"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public long MakeId { get { return this.MakeIdField; } set { if ((this.MakeIdField.Equals(value)!= true)) { this.MakeIdField = value; this.RaisePropertyChanged("MakeId"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string MakeLogo { get { return this.MakeLogoField; } set { if ((object.ReferenceEquals(this.MakeLogoField, value)!= true)) { this.MakeLogoField = value; this.RaisePropertyChanged("MakeLogo"); } } } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if ((propertyChanged!= null)) { propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="Make", Namespace="http://schemas.datacontract.org/2004/07/Emex.Stock")] [System.SerializableAttribute()] public partial class Make : EmExServiceClient.ContragentService.NullableDataContract { [System.Runtime.Serialization.OptionalFieldAttribute()] private long MakeIdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string MakeLogoField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string MakeNameField; [System.Runtime.Serialization.DataMemberAttribute()] public long MakeId { get { return this.MakeIdField; } set { if ((this.MakeIdField.Equals(value)!= true)) { this.MakeIdField = value; this.RaisePropertyChanged("MakeId"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string MakeLogo { get { return this.MakeLogoField; } set { if ((object.ReferenceEquals(this.MakeLogoField, value)!= true)) { this.MakeLogoField = value; this.RaisePropertyChanged("MakeLogo"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string MakeName { get { return this.MakeNameField; } set { if ((object.ReferenceEquals(this.MakeNameField, value)!= true)) { this.MakeNameField = value; this.RaisePropertyChanged("MakeName"); } } } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="NullableDataContract", Namespace="http://schemas.datacontract.org/2004/07/Emex.Communication")] [System.SerializableAttribute()] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.Make))] public partial class NullableDataContract : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged { [System.NonSerializedAttribute()] private System.Runtime.Serialization.ExtensionDataObject extensionDataField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool HasErrorField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool IsNullOrEmptyField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string MessageField; [global::System.ComponentModel.BrowsableAttribute(false)] public System.Runtime.Serialization.ExtensionDataObject ExtensionData { get { return this.extensionDataField; } set { this.extensionDataField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] public bool HasError { get { return this.HasErrorField; } set { if ((this.HasErrorField.Equals(value)!= true)) { this.HasErrorField = value; this.RaisePropertyChanged("HasError"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public bool IsNullOrEmpty { get { return this.IsNullOrEmptyField; } set { if ((this.IsNullOrEmptyField.Equals(value)!= true)) { this.IsNullOrEmptyField = value; this.RaisePropertyChanged("IsNullOrEmpty"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string Message { get { return this.MessageField; } set { if ((object.ReferenceEquals(this.MessageField, value)!= true)) { this.MessageField = value; this.RaisePropertyChanged("Message"); } } } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if ((propertyChanged!= null)) { propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="SuppliersReturnsAuthority", Namespace="http://schemas.datacontract.org/2004/07/Emex.EmexMain.Supplier")] [System.SerializableAttribute()] public partial class SuppliersReturnsAuthority : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged { [System.NonSerializedAttribute()] private System.Runtime.Serialization.ExtensionDataObject extensionDataField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string AuthorityDataField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string AuthorityScanUrlField; [System.Runtime.Serialization.OptionalFieldAttribute()] private byte AuthorityStateField; [System.Runtime.Serialization.OptionalFieldAttribute()] private System.DateTime AuthorityStateDateField; [System.Runtime.Serialization.OptionalFieldAttribute()] private byte AuthorityTypeField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string BarcodeField; [System.Runtime.Serialization.OptionalFieldAttribute()] private System.DateTime CreateDateField; [System.Runtime.Serialization.OptionalFieldAttribute()] private System.DateTime DueDateField; [System.Runtime.Serialization.OptionalFieldAttribute()] private System.DateTime IssueDateField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string IssuePlaceField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string NumberField; [System.Runtime.Serialization.OptionalFieldAttribute()] private byte RevisionField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string SignerField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string SignerDocumentField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string SignerGenitiveField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string SignerPostField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string SignerPostGenitiveField; [System.Runtime.Serialization.OptionalFieldAttribute()] private long SupplierIdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private int SuppliersReturnsAuthoritiesIdField; [global::System.ComponentModel.BrowsableAttribute(false)] public System.Runtime.Serialization.ExtensionDataObject ExtensionData { get { return this.extensionDataField; } set { this.extensionDataField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] public string AuthorityData { get { return this.AuthorityDataField; } set { if ((object.ReferenceEquals(this.AuthorityDataField, value)!= true)) { this.AuthorityDataField = value; this.RaisePropertyChanged("AuthorityData"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string AuthorityScanUrl { get { return this.AuthorityScanUrlField; } set { if ((object.ReferenceEquals(this.AuthorityScanUrlField, value)!= true)) { this.AuthorityScanUrlField = value; this.RaisePropertyChanged("AuthorityScanUrl"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public byte AuthorityState { get { return this.AuthorityStateField; } set { if ((this.AuthorityStateField.Equals(value)!= true)) { this.AuthorityStateField = value; this.RaisePropertyChanged("AuthorityState"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public System.DateTime AuthorityStateDate { get { return this.AuthorityStateDateField; } set { if ((this.AuthorityStateDateField.Equals(value)!= true)) { this.AuthorityStateDateField = value; this.RaisePropertyChanged("AuthorityStateDate"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public byte AuthorityType { get { return this.AuthorityTypeField; } set { if ((this.AuthorityTypeField.Equals(value)!= true)) { this.AuthorityTypeField = value; this.RaisePropertyChanged("AuthorityType"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string Barcode { get { return this.BarcodeField; } set { if ((object.ReferenceEquals(this.BarcodeField, value)!= true)) { this.BarcodeField = value; this.RaisePropertyChanged("Barcode"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public System.DateTime CreateDate { get { return this.CreateDateField; } set { if ((this.CreateDateField.Equals(value)!= true)) { this.CreateDateField = value; this.RaisePropertyChanged("CreateDate"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public System.DateTime DueDate { get { return this.DueDateField; } set { if ((this.DueDateField.Equals(value)!= true)) { this.DueDateField = value; this.RaisePropertyChanged("DueDate"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public System.DateTime IssueDate { get { return this.IssueDateField; } set { if ((this.IssueDateField.Equals(value)!= true)) { this.IssueDateField = value; this.RaisePropertyChanged("IssueDate"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string IssuePlace { get { return this.IssuePlaceField; } set { if ((object.ReferenceEquals(this.IssuePlaceField, value)!= true)) { this.IssuePlaceField = value; this.RaisePropertyChanged("IssuePlace"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string Number { get { return this.NumberField; } set { if ((object.ReferenceEquals(this.NumberField, value)!= true)) { this.NumberField = value; this.RaisePropertyChanged("Number"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public byte Revision { get { return this.RevisionField; } set { if ((this.RevisionField.Equals(value)!= true)) { this.RevisionField = value; this.RaisePropertyChanged("Revision"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string Signer { get { return this.SignerField; } set { if ((object.ReferenceEquals(this.SignerField, value)!= true)) { this.SignerField = value; this.RaisePropertyChanged("Signer"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string SignerDocument { get { return this.SignerDocumentField; } set { if ((object.ReferenceEquals(this.SignerDocumentField, value)!= true)) { this.SignerDocumentField = value; this.RaisePropertyChanged("SignerDocument"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string SignerGenitive { get { return this.SignerGenitiveField; } set { if ((object.ReferenceEquals(this.SignerGenitiveField, value)!= true)) { this.SignerGenitiveField = value; this.RaisePropertyChanged("SignerGenitive"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string SignerPost { get { return this.SignerPostField; } set { if ((object.ReferenceEquals(this.SignerPostField, value)!= true)) { this.SignerPostField = value; this.RaisePropertyChanged("SignerPost"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string SignerPostGenitive { get { return this.SignerPostGenitiveField; } set { if ((object.ReferenceEquals(this.SignerPostGenitiveField, value)!= true)) { this.SignerPostGenitiveField = value; this.RaisePropertyChanged("SignerPostGenitive"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public long SupplierId { get { return this.SupplierIdField; } set { if ((this.SupplierIdField.Equals(value)!= true)) { this.SupplierIdField = value; this.RaisePropertyChanged("SupplierId"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public int SuppliersReturnsAuthoritiesId { get { return this.SuppliersReturnsAuthoritiesIdField; } set { if ((this.SuppliersReturnsAuthoritiesIdField.Equals(value)!= true)) { this.SuppliersReturnsAuthoritiesIdField = value; this.RaisePropertyChanged("SuppliersReturnsAuthoritiesId"); } } } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if ((propertyChanged!= null)) { propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="Consumer", Namespace="http://schemas.datacontract.org/2004/07/Emex.Online")] [System.SerializableAttribute()] public partial class Consumer : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged { [System.NonSerializedAttribute()] private System.Runtime.Serialization.ExtensionDataObject extensionDataField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string AddressField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string EmailField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string FirstNameField; [System.Runtime.Serialization.OptionalFieldAttribute()] private long IdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private long LocationIdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string MiddleNameField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string PasswordField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string PhoneNumberField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string RegionField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string SurnameField; [System.Runtime.Serialization.OptionalFieldAttribute()] private long UserIdField; [global::System.ComponentModel.BrowsableAttribute(false)] public System.Runtime.Serialization.ExtensionDataObject ExtensionData { get { return this.extensionDataField; } set { this.extensionDataField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] public string Address { get { return this.AddressField; } set { if ((object.ReferenceEquals(this.AddressField, value)!= true)) { this.AddressField = value; this.RaisePropertyChanged("Address"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string Email { get { return this.EmailField; } set { if ((object.ReferenceEquals(this.EmailField, value)!= true)) { this.EmailField = value; this.RaisePropertyChanged("Email"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string FirstName { get { return this.FirstNameField; } set { if ((object.ReferenceEquals(this.FirstNameField, value)!= true)) { this.FirstNameField = value; this.RaisePropertyChanged("FirstName"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public long Id { get { return this.IdField; } set { if ((this.IdField.Equals(value)!= true)) { this.IdField = value; this.RaisePropertyChanged("Id"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public long LocationId { get { return this.LocationIdField; } set { if ((this.LocationIdField.Equals(value)!= true)) { this.LocationIdField = value; this.RaisePropertyChanged("LocationId"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string MiddleName { get { return this.MiddleNameField; } set { if ((object.ReferenceEquals(this.MiddleNameField, value)!= true)) { this.MiddleNameField = value; this.RaisePropertyChanged("MiddleName"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string Password { get { return this.PasswordField; } set { if ((object.ReferenceEquals(this.PasswordField, value)!= true)) { this.PasswordField = value; this.RaisePropertyChanged("Password"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string PhoneNumber { get { return this.PhoneNumberField; } set { if ((object.ReferenceEquals(this.PhoneNumberField, value)!= true)) { this.PhoneNumberField = value; this.RaisePropertyChanged("PhoneNumber"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string Region { get { return this.RegionField; } set { if ((object.ReferenceEquals(this.RegionField, value)!= true)) { this.RegionField = value; this.RaisePropertyChanged("Region"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string Surname { get { return this.SurnameField; } set { if ((object.ReferenceEquals(this.SurnameField, value)!= true)) { this.SurnameField = value; this.RaisePropertyChanged("Surname"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public long UserId { get { return this.UserIdField; } set { if ((this.UserIdField.Equals(value)!= true)) { this.UserIdField = value; this.RaisePropertyChanged("UserId"); } } } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if ((propertyChanged!= null)) { propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="CustomerHistoryItem", Namespace="http://schemas.datacontract.org/2004/07/Emex.Contragent")] [System.SerializableAttribute()] public partial class CustomerHistoryItem : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged { [System.NonSerializedAttribute()] private System.Runtime.Serialization.ExtensionDataObject extensionDataField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string AppNameField; [System.Runtime.Serialization.OptionalFieldAttribute()] private System.DateTime ChangeDateField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string ChangeTypeNameField; [System.Runtime.Serialization.OptionalFieldAttribute()] private EmExServiceClient.ContragentService.User ChangeUserField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string CommentField; [System.Runtime.Serialization.OptionalFieldAttribute()] private long CustomerIdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string NewValueField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string OldValueField; [global::System.ComponentModel.BrowsableAttribute(false)] public System.Runtime.Serialization.ExtensionDataObject ExtensionData { get { return this.extensionDataField; } set { this.extensionDataField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] public string AppName { get { return this.AppNameField; } set { if ((object.ReferenceEquals(this.AppNameField, value)!= true)) { this.AppNameField = value; this.RaisePropertyChanged("AppName"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public System.DateTime ChangeDate { get { return this.ChangeDateField; } set { if ((this.ChangeDateField.Equals(value)!= true)) { this.ChangeDateField = value; this.RaisePropertyChanged("ChangeDate"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string ChangeTypeName { get { return this.ChangeTypeNameField; } set { if ((object.ReferenceEquals(this.ChangeTypeNameField, value)!= true)) { this.ChangeTypeNameField = value; this.RaisePropertyChanged("ChangeTypeName"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public EmExServiceClient.ContragentService.User ChangeUser { get { return this.ChangeUserField; } set { if ((object.ReferenceEquals(this.ChangeUserField, value)!= true)) { this.ChangeUserField = value; this.RaisePropertyChanged("ChangeUser"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string Comment { get { return this.CommentField; } set { if ((object.ReferenceEquals(this.CommentField, value)!= true)) { this.CommentField = value; this.RaisePropertyChanged("Comment"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public long CustomerId { get { return this.CustomerIdField; } set { if ((this.CustomerIdField.Equals(value)!= true)) { this.CustomerIdField = value; this.RaisePropertyChanged("CustomerId"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string NewValue { get { return this.NewValueField; } set { if ((object.ReferenceEquals(this.NewValueField, value)!= true)) { this.NewValueField = value; this.RaisePropertyChanged("NewValue"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string OldValue { get { return this.OldValueField; } set { if ((object.ReferenceEquals(this.OldValueField, value)!= true)) { this.OldValueField = value; this.RaisePropertyChanged("OldValue"); } } } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if ((propertyChanged!= null)) { propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="TransportCompany", Namespace="http://schemas.datacontract.org/2004/07/Emex.Delivery")] [System.SerializableAttribute()] public partial class TransportCompany : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged { [System.NonSerializedAttribute()] private System.Runtime.Serialization.ExtensionDataObject extensionDataField; private long IdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool IsDocumentsInBoxField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool IsOnlyOneRouteShippingField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool IsRouteShippingField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool IsShowOnPPCField; private string LogoField; private string NameField; [global::System.ComponentModel.BrowsableAttribute(false)] public System.Runtime.Serialization.ExtensionDataObject ExtensionData { get { return this.extensionDataField; } set { this.extensionDataField = value; } } [System.Runtime.Serialization.DataMemberAttribute(IsRequired=true)] public long Id { get { return this.IdField; } set { if ((this.IdField.Equals(value)!= true)) { this.IdField = value; this.RaisePropertyChanged("Id"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public bool IsDocumentsInBox { get { return this.IsDocumentsInBoxField; } set { if ((this.IsDocumentsInBoxField.Equals(value)!= true)) { this.IsDocumentsInBoxField = value; this.RaisePropertyChanged("IsDocumentsInBox"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public bool IsOnlyOneRouteShipping { get { return this.IsOnlyOneRouteShippingField; } set { if ((this.IsOnlyOneRouteShippingField.Equals(value)!= true)) { this.IsOnlyOneRouteShippingField = value; this.RaisePropertyChanged("IsOnlyOneRouteShipping"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public bool IsRouteShipping { get { return this.IsRouteShippingField; } set { if ((this.IsRouteShippingField.Equals(value)!= true)) { this.IsRouteShippingField = value; this.RaisePropertyChanged("IsRouteShipping"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public bool IsShowOnPPC { get { return this.IsShowOnPPCField; } set { if ((this.IsShowOnPPCField.Equals(value)!= true)) { this.IsShowOnPPCField = value; this.RaisePropertyChanged("IsShowOnPPC"); } } } [System.Runtime.Serialization.DataMemberAttribute(IsRequired=true)] public string Logo { get { return this.LogoField; } set { if ((object.ReferenceEquals(this.LogoField, value)!= true)) { this.LogoField = value; this.RaisePropertyChanged("Logo"); } } } [System.Runtime.Serialization.DataMemberAttribute(IsRequired=true)] public string Name { get { return this.NameField; } set { if ((object.ReferenceEquals(this.NameField, value)!= true)) { this.NameField = value; this.RaisePropertyChanged("Name"); } } } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if ((propertyChanged!= null)) { propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="Supplier", Namespace="http://schemas.datacontract.org/2004/07/Emex.Contragent")] [System.SerializableAttribute()] public partial class Supplier : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged { [System.NonSerializedAttribute()] private System.Runtime.Serialization.ExtensionDataObject extensionDataField; private System.DateTime DateCreateSupplierField; private string LogoField; private string PasswordField; private string PasswordFTPField; private string SupplierAddressField; private string SupplierDescriptionField; private long SupplierForUserField; private string SupplierINNField; private long SupplierIdField; private string SupplierNameField; [System.Runtime.Serialization.OptionalFieldAttribute()] private EmExServiceClient.ContragentService.User UserForSupplierField; [System.Runtime.Serialization.OptionalFieldAttribute()] private EmExServiceClient.ContragentService.Supplier.SupplierGroup _supplierGroupField; [System.Runtime.Serialization.OptionalFieldAttribute()] private EmExServiceClient.ContragentService.Supplier.SupplierStatus _supplierStatusField; [System.Runtime.Serialization.OptionalFieldAttribute()] private long buhContragentIdField; [global::System.ComponentModel.BrowsableAttribute(false)] public System.Runtime.Serialization.ExtensionDataObject ExtensionData { get { return this.extensionDataField; } set { this.extensionDataField = value; } } [System.Runtime.Serialization.DataMemberAttribute(IsRequired=true)] public System.DateTime DateCreateSupplier { get { return this.DateCreateSupplierField; } set { if ((this.DateCreateSupplierField.Equals(value)!= true)) { this.DateCreateSupplierField = value; this.RaisePropertyChanged("DateCreateSupplier"); } } } [System.Runtime.Serialization.DataMemberAttribute(IsRequired=true)] public string Logo { get { return this.LogoField; } set { if ((object.ReferenceEquals(this.LogoField, value)!= true)) { this.LogoField = value; this.RaisePropertyChanged("Logo"); } } } [System.Runtime.Serialization.DataMemberAttribute(IsRequired=true)] public string Password { get { return this.PasswordField; } set { if ((object.ReferenceEquals(this.PasswordField, value)!= true)) { this.PasswordField = value; this.RaisePropertyChanged("Password"); } } } [System.Runtime.Serialization.DataMemberAttribute(IsRequired=true)] public string PasswordFTP { get { return this.PasswordFTPField; } set { if ((object.ReferenceEquals(this.PasswordFTPField, value)!= true)) { this.PasswordFTPField = value; this.RaisePropertyChanged("PasswordFTP"); } } } [System.Runtime.Serialization.DataMemberAttribute(IsRequired=true)] public string SupplierAddress { get { return this.SupplierAddressField; } set { if ((object.ReferenceEquals(this.SupplierAddressField, value)!= true)) { this.SupplierAddressField = value; this.RaisePropertyChanged("SupplierAddress"); } } } [System.Runtime.Serialization.DataMemberAttribute(IsRequired=true)] public string SupplierDescription { get { return this.SupplierDescriptionField; } set { if ((object.ReferenceEquals(this.SupplierDescriptionField, value)!= true)) { this.SupplierDescriptionField = value; this.RaisePropertyChanged("SupplierDescription"); } } } [System.Runtime.Serialization.DataMemberAttribute(IsRequired=true)] public long SupplierForUser { get { return this.SupplierForUserField; } set { if ((this.SupplierForUserField.Equals(value)!= true)) { this.SupplierForUserField = value; this.RaisePropertyChanged("SupplierForUser"); } } } [System.Runtime.Serialization.DataMemberAttribute(IsRequired=true)] public string SupplierINN { get { return this.SupplierINNField; } set { if ((object.ReferenceEquals(this.SupplierINNField, value)!= true)) { this.SupplierINNField = value; this.RaisePropertyChanged("SupplierINN"); } } } [System.Runtime.Serialization.DataMemberAttribute(IsRequired=true)] public long SupplierId { get { return this.SupplierIdField; } set { if ((this.SupplierIdField.Equals(value)!= true)) { this.SupplierIdField = value; this.RaisePropertyChanged("SupplierId"); } } } [System.Runtime.Serialization.DataMemberAttribute(IsRequired=true)] public string SupplierName { get { return this.SupplierNameField; } set { if ((object.ReferenceEquals(this.SupplierNameField, value)!= true)) { this.SupplierNameField = value; this.RaisePropertyChanged("SupplierName"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public EmExServiceClient.ContragentService.User UserForSupplier { get { return this.UserForSupplierField; } set { if ((object.ReferenceEquals(this.UserForSupplierField, value)!= true)) { this.UserForSupplierField = value; this.RaisePropertyChanged("UserForSupplier"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public EmExServiceClient.ContragentService.Supplier.SupplierGroup _supplierGroup { get { return this._supplierGroupField; } set { if ((object.ReferenceEquals(this._supplierGroupField, value)!= true)) { this._supplierGroupField = value; this.RaisePropertyChanged("_supplierGroup"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public EmExServiceClient.ContragentService.Supplier.SupplierStatus _supplierStatus { get { return this._supplierStatusField; } set { if ((object.ReferenceEquals(this._supplierStatusField, value)!= true)) { this._supplierStatusField = value; this.RaisePropertyChanged("_supplierStatus"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public long buhContragentId { get { return this.buhContragentIdField; } set { if ((this.buhContragentIdField.Equals(value)!= true)) { this.buhContragentIdField = value; this.RaisePropertyChanged("buhContragentId"); } } } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if ((propertyChanged!= null)) { propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="Supplier.SupplierGroup", Namespace="http://schemas.datacontract.org/2004/07/Emex.Contragent")] [System.SerializableAttribute()] public partial class SupplierGroup : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged { [System.NonSerializedAttribute()] private System.Runtime.Serialization.ExtensionDataObject extensionDataField; public System.Runtime.Serialization.ExtensionDataObject ExtensionData { get { return this.extensionDataField; } set { this.extensionDataField = value; } } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if ((propertyChanged!= null)) { propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="Supplier.SupplierStatus", Namespace="http://schemas.datacontract.org/2004/07/Emex.Contragent")] [System.SerializableAttribute()] public partial class SupplierStatus : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged { [System.NonSerializedAttribute()] private System.Runtime.Serialization.ExtensionDataObject extensionDataField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool bitAllowTakeWithoutInvoiceField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool bitAutoDistributionField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool bitBalanceMailField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool bitBallanceInSupplierCurrencyField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool bitBarCodeField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool bitConterminousDocumentsField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool bitInvoiceAutoCloseField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool bitNeedWeightOnReceiptField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool bitNoWeightField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool bitOrderPriceField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool bitPriceMutationField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool bitRequiredCoordinationField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool bitUseProgramUploadInvoiceField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool bitUseProgramUploadPricelistsField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool bitWhiteSupplierField; public System.Runtime.Serialization.ExtensionDataObject ExtensionData { get { return this.extensionDataField; } set { this.extensionDataField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] public bool bitAllowTakeWithoutInvoice { get { return this.bitAllowTakeWithoutInvoiceField; } set { if ((this.bitAllowTakeWithoutInvoiceField.Equals(value)!= true)) { this.bitAllowTakeWithoutInvoiceField = value; this.RaisePropertyChanged("bitAllowTakeWithoutInvoice"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public bool bitAutoDistribution { get { return this.bitAutoDistributionField; } set { if ((this.bitAutoDistributionField.Equals(value)!= true)) { this.bitAutoDistributionField = value; this.RaisePropertyChanged("bitAutoDistribution"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public bool bitBalanceMail { get { return this.bitBalanceMailField; } set { if ((this.bitBalanceMailField.Equals(value)!= true)) { this.bitBalanceMailField = value; this.RaisePropertyChanged("bitBalanceMail"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public bool bitBallanceInSupplierCurrency { get { return this.bitBallanceInSupplierCurrencyField; } set { if ((this.bitBallanceInSupplierCurrencyField.Equals(value)!= true)) { this.bitBallanceInSupplierCurrencyField = value; this.RaisePropertyChanged("bitBallanceInSupplierCurrency"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public bool bitBarCode { get { return this.bitBarCodeField; } set { if ((this.bitBarCodeField.Equals(value)!= true)) { this.bitBarCodeField = value; this.RaisePropertyChanged("bitBarCode"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public bool bitConterminousDocuments { get { return this.bitConterminousDocumentsField; } set { if ((this.bitConterminousDocumentsField.Equals(value)!= true)) { this.bitConterminousDocumentsField = value; this.RaisePropertyChanged("bitConterminousDocuments"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public bool bitInvoiceAutoClose { get { return this.bitInvoiceAutoCloseField; } set { if ((this.bitInvoiceAutoCloseField.Equals(value)!= true)) { this.bitInvoiceAutoCloseField = value; this.RaisePropertyChanged("bitInvoiceAutoClose"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public bool bitNeedWeightOnReceipt { get { return this.bitNeedWeightOnReceiptField; } set { if ((this.bitNeedWeightOnReceiptField.Equals(value)!= true)) { this.bitNeedWeightOnReceiptField = value; this.RaisePropertyChanged("bitNeedWeightOnReceipt"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public bool bitNoWeight { get { return this.bitNoWeightField; } set { if ((this.bitNoWeightField.Equals(value)!= true)) { this.bitNoWeightField = value; this.RaisePropertyChanged("bitNoWeight"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public bool bitOrderPrice { get { return this.bitOrderPriceField; } set { if ((this.bitOrderPriceField.Equals(value)!= true)) { this.bitOrderPriceField = value; this.RaisePropertyChanged("bitOrderPrice"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public bool bitPriceMutation { get { return this.bitPriceMutationField; } set { if ((this.bitPriceMutationField.Equals(value)!= true)) { this.bitPriceMutationField = value; this.RaisePropertyChanged("bitPriceMutation"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public bool bitRequiredCoordination { get { return this.bitRequiredCoordinationField; } set { if ((this.bitRequiredCoordinationField.Equals(value)!= true)) { this.bitRequiredCoordinationField = value; this.RaisePropertyChanged("bitRequiredCoordination"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public bool bitUseProgramUploadInvoice { get { return this.bitUseProgramUploadInvoiceField; } set { if ((this.bitUseProgramUploadInvoiceField.Equals(value)!= true)) { this.bitUseProgramUploadInvoiceField = value; this.RaisePropertyChanged("bitUseProgramUploadInvoice"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public bool bitUseProgramUploadPricelists { get { return this.bitUseProgramUploadPricelistsField; } set { if ((this.bitUseProgramUploadPricelistsField.Equals(value)!= true)) { this.bitUseProgramUploadPricelistsField = value; this.RaisePropertyChanged("bitUseProgramUploadPricelists"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public bool bitWhiteSupplier { get { return this.bitWhiteSupplierField; } set { if ((this.bitWhiteSupplierField.Equals(value)!= true)) { this.bitWhiteSupplierField = value; this.RaisePropertyChanged("bitWhiteSupplier"); } } } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if ((propertyChanged!= null)) { propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="Contragent", Namespace="http://schemas.datacontract.org/2004/07/Emex.Contragent")] [System.SerializableAttribute()] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.Customer))] public partial class Contragent : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged { [System.NonSerializedAttribute()] private System.Runtime.Serialization.ExtensionDataObject extensionDataField; [System.Runtime.Serialization.OptionalFieldAttribute()] private EmExServiceClient.ContragentService.Contragent.Address AddAddressField; [System.Runtime.Serialization.OptionalFieldAttribute()] private EmExServiceClient.ContragentService.Contragent.Contact AddContactField; [System.Runtime.Serialization.OptionalFieldAttribute()] private EmExServiceClient.ContragentService.Contragent.ContragentDogovor AddDogovorField; [System.Runtime.Serialization.OptionalFieldAttribute()] private EmExServiceClient.ContragentService.Contragent.Address[] AddressListField; [System.Runtime.Serialization.OptionalFieldAttribute()] private int BanUserIdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private EmExServiceClient.ContragentService.Contragent.BankAccount BankAccountDefaultField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string CommentField; [System.Runtime.Serialization.OptionalFieldAttribute()] private EmExServiceClient.ContragentService.Contragent.Contact[] ContactsField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string ContragentContactPersonField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool DoNotSverkaSpamField; [System.Runtime.Serialization.OptionalFieldAttribute()] private EmExServiceClient.ContragentService.Contragent.ContragentDogovor[] DogovorField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string EMailsField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string INNField; [System.Runtime.Serialization.OptionalFieldAttribute()] private long IdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string KPPField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string LogoField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string NameField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string NameFullField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string OGRNField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string OKPOField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool OurEmployeeField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string PhonesField; [System.Runtime.Serialization.OptionalFieldAttribute()] private int StatusField; [System.Runtime.Serialization.OptionalFieldAttribute()] private int UserIdAddField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool ValidateRequisitsField; [global::System.ComponentModel.BrowsableAttribute(false)] public System.Runtime.Serialization.ExtensionDataObject ExtensionData { get { return this.extensionDataField; } set { this.extensionDataField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] public EmExServiceClient.ContragentService.Contragent.Address AddAddress { get { return this.AddAddressField; } set { if ((object.ReferenceEquals(this.AddAddressField, value)!= true)) { this.AddAddressField = value; this.RaisePropertyChanged("AddAddress"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public EmExServiceClient.ContragentService.Contragent.Contact AddContact { get { return this.AddContactField; } set { if ((object.ReferenceEquals(this.AddContactField, value)!= true)) { this.AddContactField = value; this.RaisePropertyChanged("AddContact"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public EmExServiceClient.ContragentService.Contragent.ContragentDogovor AddDogovor { get { return this.AddDogovorField; } set { if ((object.ReferenceEquals(this.AddDogovorField, value)!= true)) { this.AddDogovorField = value; this.RaisePropertyChanged("AddDogovor"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public EmExServiceClient.ContragentService.Contragent.Address[] AddressList { get { return this.AddressListField; } set { if ((object.ReferenceEquals(this.AddressListField, value)!= true)) { this.AddressListField = value; this.RaisePropertyChanged("AddressList"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public int BanUserId { get { return this.BanUserIdField; } set { if ((this.BanUserIdField.Equals(value)!= true)) { this.BanUserIdField = value; this.RaisePropertyChanged("BanUserId"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public EmExServiceClient.ContragentService.Contragent.BankAccount BankAccountDefault { get { return this.BankAccountDefaultField; } set { if ((object.ReferenceEquals(this.BankAccountDefaultField, value)!= true)) { this.BankAccountDefaultField = value; this.RaisePropertyChanged("BankAccountDefault"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string Comment { get { return this.CommentField; } set { if ((object.ReferenceEquals(this.CommentField, value)!= true)) { this.CommentField = value; this.RaisePropertyChanged("Comment"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public EmExServiceClient.ContragentService.Contragent.Contact[] Contacts { get { return this.ContactsField; } set { if ((object.ReferenceEquals(this.ContactsField, value)!= true)) { this.ContactsField = value; this.RaisePropertyChanged("Contacts"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string ContragentContactPerson { get { return this.ContragentContactPersonField; } set { if ((object.ReferenceEquals(this.ContragentContactPersonField, value)!= true)) { this.ContragentContactPersonField = value; this.RaisePropertyChanged("ContragentContactPerson"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public bool DoNotSverkaSpam { get { return this.DoNotSverkaSpamField; } set { if ((this.DoNotSverkaSpamField.Equals(value)!= true)) { this.DoNotSverkaSpamField = value; this.RaisePropertyChanged("DoNotSverkaSpam"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public EmExServiceClient.ContragentService.Contragent.ContragentDogovor[] Dogovor { get { return this.DogovorField; } set { if ((object.ReferenceEquals(this.DogovorField, value)!= true)) { this.DogovorField = value; this.RaisePropertyChanged("Dogovor"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string EMails { get { return this.EMailsField; } set { if ((object.ReferenceEquals(this.EMailsField, value)!= true)) { this.EMailsField = value; this.RaisePropertyChanged("EMails"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string INN { get { return this.INNField; } set { if ((object.ReferenceEquals(this.INNField, value)!= true)) { this.INNField = value; this.RaisePropertyChanged("INN"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public long Id { get { return this.IdField; } set { if ((this.IdField.Equals(value)!= true)) { this.IdField = value; this.RaisePropertyChanged("Id"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string KPP { get { return this.KPPField; } set { if ((object.ReferenceEquals(this.KPPField, value)!= true)) { this.KPPField = value; this.RaisePropertyChanged("KPP"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string Logo { get { return this.LogoField; } set { if ((object.ReferenceEquals(this.LogoField, value)!= true)) { this.LogoField = value; this.RaisePropertyChanged("Logo"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string Name { get { return this.NameField; } set { if ((object.ReferenceEquals(this.NameField, value)!= true)) { this.NameField = value; this.RaisePropertyChanged("Name"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string NameFull { get { return this.NameFullField; } set { if ((object.ReferenceEquals(this.NameFullField, value)!= true)) { this.NameFullField = value; this.RaisePropertyChanged("NameFull"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string OGRN { get { return this.OGRNField; } set { if ((object.ReferenceEquals(this.OGRNField, value)!= true)) { this.OGRNField = value; this.RaisePropertyChanged("OGRN"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string OKPO { get { return this.OKPOField; } set { if ((object.ReferenceEquals(this.OKPOField, value)!= true)) { this.OKPOField = value; this.RaisePropertyChanged("OKPO"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public bool OurEmployee { get { return this.OurEmployeeField; } set { if ((this.OurEmployeeField.Equals(value)!= true)) { this.OurEmployeeField = value; this.RaisePropertyChanged("OurEmployee"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string Phones { get { return this.PhonesField; } set { if ((object.ReferenceEquals(this.PhonesField, value)!= true)) { this.PhonesField = value; this.RaisePropertyChanged("Phones"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public int Status { get { return this.StatusField; } set { if ((this.StatusField.Equals(value)!= true)) { this.StatusField = value; this.RaisePropertyChanged("Status"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public int UserIdAdd { get { return this.UserIdAddField; } set { if ((this.UserIdAddField.Equals(value)!= true)) { this.UserIdAddField = value; this.RaisePropertyChanged("UserIdAdd"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public bool ValidateRequisits { get { return this.ValidateRequisitsField; } set { if ((this.ValidateRequisitsField.Equals(value)!= true)) { this.ValidateRequisitsField = value; this.RaisePropertyChanged("ValidateRequisits"); } } } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if ((propertyChanged!= null)) { propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="Contragent.Address", Namespace="http://schemas.datacontract.org/2004/07/Emex.Contragent")] [System.SerializableAttribute()] public partial class Address : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged { [System.NonSerializedAttribute()] private System.Runtime.Serialization.ExtensionDataObject extensionDataField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string AddressContragentField; [System.Runtime.Serialization.OptionalFieldAttribute()] private EmExServiceClient.ContragentService.AddressType TypeAddressField; public System.Runtime.Serialization.ExtensionDataObject ExtensionData { get { return this.extensionDataField; } set { this.extensionDataField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] public string AddressContragent { get { return this.AddressContragentField; } set { if ((object.ReferenceEquals(this.AddressContragentField, value)!= true)) { this.AddressContragentField = value; this.RaisePropertyChanged("AddressContragent"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public EmExServiceClient.ContragentService.AddressType TypeAddress { get { return this.TypeAddressField; } set { if ((this.TypeAddressField.Equals(value)!= true)) { this.TypeAddressField = value; this.RaisePropertyChanged("TypeAddress"); } } } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if ((propertyChanged!= null)) { propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="Contragent.Contact", Namespace="http://schemas.datacontract.org/2004/07/Emex.Contragent")] [System.SerializableAttribute()] [System.Runtime.Serialization.KnownTypeAttribute(typeof(int[]))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(long[]))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.OperationResult))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.OperationResultArrayOfInventory))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.OperationResultArrayOfDocumentCorrectionCard))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.OperationResultArrayOfUser))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.OperationResultArrayOfGroup))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.OperationResultstring))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.OperationResultArrayOfSalesHistoryCommon))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.OperationResultArrayOfSalesHistoryDetail))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.OperationResultTupleOfbooleanstringlonglong))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.OperationResultArrayOfDenyType))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.OperationResultArrayOfDeleteType))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.OperationResultArrayOfDenyStatus))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.OperationResultArrayOfChangeAnswerLogLine))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.OperationResultDetailDto))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.OperationResultArrayOfMake))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.NullableDataContract))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.OperationResultArrayOfSuppliersReturnsAuthority))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.OperationResultSuppliersReturnsAuthority))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.OperationResultint))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.OperationResultboolean))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.OperationResultArrayOfConsumer))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.OperationResultArrayOfCustomerHistoryItem))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.OperationResultArrayOfTransportCompany))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.OperationResultSupplier))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.OperationResultArrayOfContragent))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.OperationResultArrayOfSupplierBase))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.OperationResultArrayOfSupplierDocumentReturnCard))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.OperationResultArrayOfLocalStorageAccountNew))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.OperationResultArrayOfDetailSubstituteDto))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.OperationResultlong))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.OperationResultArrayOfLocalStorageAccount2))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.OperationResultCustomerDiscountManual))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.OperationResultActionLock))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.OperationResultNullableOfdateTime))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.OperationResultArrayOfDecommission))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.OperationResultArrayOfDecommissionDetail))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.OperationResultArrayOfAccountCard))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.OperationResultArrayOfAccountCard2))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.OperationResultArrayOfAccountCard3))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.OperationResultArrayOfDiadocDocumentStatus))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.OperationResultArrayOfDocumentReturnCard))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.OperationResultArrayOfAccountDetailViewItem))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.OperationResultArrayOfCustomer))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.OperationResultArrayOfCustomerSearchResultItem))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.OperationResultCustomer))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.OperationResultArrayOfCustomer.CustomerGroup))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.OperationResultArrayOfCustomerIdentity))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.OperationResultArrayOfContragentDocumentSetting))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.OperationResultCustomerDelivery))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.OperationResultArrayOfContragentIdentity))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.OperationResultArrayOfCustomerScheduleAttribute))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.OperationResultDeliveryRegionType))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.OperationResultCustomerScheduleAttribute))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.OperationResultArrayOfActRecycling))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.OperationResultActRecycling))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.OperationResultArrayOfLocation))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.OperationResultArrayOfRegion))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.OperationResultArrayOfCustomerDiscountHistoryItem))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.OperationResultCustomerBalance))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.OperationResultCustomerIdentity))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.Inventory[]))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.Inventory))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.DocumentCorrectionCard[]))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.DocumentCorrectionCard))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.SupplierDocumentReturnCard[]))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.SupplierDocumentReturnCard))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.DocumentSticker[]))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.DocumentSticker))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.TransportDocumentSticker[]))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.TransportDocumentSticker))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.Decommission[]))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.Decommission))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.DecommissionDetail[]))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.DecommissionDetail))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.AccountCard[]))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.AccountCard))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.AccountCard2[]))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.AccountCard2))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.AccountCard3[]))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.AccountCard3))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.DiadocDocumentStatus[]))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.DiadocDocumentStatus))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.DocumentReturnCard[]))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.DocumentReturnCard))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.DocumentOptions))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.DocumentReasonType))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.DocumentType))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.ActRecycling[]))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.ActRecycling))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.User[]))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.User))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.Group[]))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.Group))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.CustomerHistoryItem[]))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.CustomerHistoryItem))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.Contragent))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.Contragent.Address))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.AddressType))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.ContactTypes))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.Contragent.ContragentDogovor))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.Contragent.Address[]))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.Contragent.BankAccount))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.Contragent.Bank))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.Contragent.Contact[]))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.Contragent.ContragentDogovor[]))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.Contragent.BankAccount[]))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.Supplier))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.Supplier.SupplierGroup))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.Supplier.SupplierStatus))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.Contragent[]))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.SupplierBase[]))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.SupplierBase))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.CustomerDiscountManual))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.Customer[]))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.Customer))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.PartnerType))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.WorkType))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.Customer.CustomerContact))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.Customer.CustomerGroup))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.Customer.CustomerStorage))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.Customer.CustomerDispatchSetting))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.Customer.CustomerAccount))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.Customer.CustomerContract))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.Customer.CustomerPrintSetting))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.Customer.CustomerStatus))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.CustomerSearchResultItem[]))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.CustomerSearchResultItem))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.CustomerSearchResultItemType))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.Customer.CustomerGroup[]))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.CustomerIdentity[]))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.CustomerIdentity))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.ContragentDocumentSetting[]))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.ContragentDocumentSetting))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.CustomerDelivery))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.ContragentIdentity[]))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.ContragentIdentity))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.CustomerScheduleAttribute[]))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.CustomerScheduleAttribute))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.CustomerScheduleAccountMode))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.CustomerDiscountHistoryItem[]))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.CustomerDiscountHistoryItem))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.CustomerBalance))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.SalesHistoryCommon[]))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.SalesHistoryCommon))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.SalesHistoryDetail[]))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.SalesHistoryDetail))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.DenyType[]))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.DenyType))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.DeleteType[]))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.DeleteType))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.DenyStatus[]))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.DenyStatus))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.ChangeAnswerLogLine[]))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.ChangeAnswerLogLine))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(System.Tuple<bool, string, long, long>))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.DetailDto))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.Make[]))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.Make))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.PrintSticker[]))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.PrintSticker))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.StickerPrintMode))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.DetailSubstituteDto[]))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.DetailSubstituteDto))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.SuppliersReturnsAuthority[]))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.SuppliersReturnsAuthority))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.SuppliersReturnsAuthorityModel))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.ActionLock))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.ActionLockState))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.Consumer[]))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.Consumer))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.DeliveryRegionType))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.Location[]))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.Location))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.LocationUser[]))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.LocationUser))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.Region[]))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.Region))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.TransportCompany[]))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.TransportCompany))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.AccountDetailViewItem[]))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.AccountDetailViewItem))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.AccountDetail))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.GatheringSchemeType))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.CustomerDeliveryType))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.LocalStorageAccountNew[]))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.LocalStorageAccountNew))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.LocalStorageAccount2[]))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.LocalStorageAccount2))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(System.Collections.Specialized.BitVector32))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.LocationSetting[]))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.LocationSetting))] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.LocationPropertyType))] public partial class Contact : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged { [System.NonSerializedAttribute()] private System.Runtime.Serialization.ExtensionDataObject extensionDataField; [System.Runtime.Serialization.OptionalFieldAttribute()] private object ContactPersonDoljnField; [System.Runtime.Serialization.OptionalFieldAttribute()] private object ContactPersonDoljnDPField; [System.Runtime.Serialization.OptionalFieldAttribute()] private object ContactPersonNameDPField; [System.Runtime.Serialization.OptionalFieldAttribute()] private long ContragentIdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string EmailField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string FIOField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string FirstNameField; [System.Runtime.Serialization.OptionalFieldAttribute()] private object GenderField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string PhoneNumberField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string SurnameField; [System.Runtime.Serialization.OptionalFieldAttribute()] private EmExServiceClient.ContragentService.ContactTypes TypeField; public System.Runtime.Serialization.ExtensionDataObject ExtensionData { get { return this.extensionDataField; } set { this.extensionDataField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] public object ContactPersonDoljn { get { return this.ContactPersonDoljnField; } set { if ((object.ReferenceEquals(this.ContactPersonDoljnField, value)!= true)) { this.ContactPersonDoljnField = value; this.RaisePropertyChanged("ContactPersonDoljn"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public object ContactPersonDoljnDP { get { return this.ContactPersonDoljnDPField; } set { if ((object.ReferenceEquals(this.ContactPersonDoljnDPField, value)!= true)) { this.ContactPersonDoljnDPField = value; this.RaisePropertyChanged("ContactPersonDoljnDP"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public object ContactPersonNameDP { get { return this.ContactPersonNameDPField; } set { if ((object.ReferenceEquals(this.ContactPersonNameDPField, value)!= true)) { this.ContactPersonNameDPField = value; this.RaisePropertyChanged("ContactPersonNameDP"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public long ContragentId { get { return this.ContragentIdField; } set { if ((this.ContragentIdField.Equals(value)!= true)) { this.ContragentIdField = value; this.RaisePropertyChanged("ContragentId"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string Email { get { return this.EmailField; } set { if ((object.ReferenceEquals(this.EmailField, value)!= true)) { this.EmailField = value; this.RaisePropertyChanged("Email"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string FIO { get { return this.FIOField; } set { if ((object.ReferenceEquals(this.FIOField, value)!= true)) { this.FIOField = value; this.RaisePropertyChanged("FIO"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string FirstName { get { return this.FirstNameField; } set { if ((object.ReferenceEquals(this.FirstNameField, value)!= true)) { this.FirstNameField = value; this.RaisePropertyChanged("FirstName"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public object Gender { get { return this.GenderField; } set { if ((object.ReferenceEquals(this.GenderField, value)!= true)) { this.GenderField = value; this.RaisePropertyChanged("Gender"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string PhoneNumber { get { return this.PhoneNumberField; } set { if ((object.ReferenceEquals(this.PhoneNumberField, value)!= true)) { this.PhoneNumberField = value; this.RaisePropertyChanged("PhoneNumber"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string Surname { get { return this.SurnameField; } set { if ((object.ReferenceEquals(this.SurnameField, value)!= true)) { this.SurnameField = value; this.RaisePropertyChanged("Surname"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public EmExServiceClient.ContragentService.ContactTypes Type { get { return this.TypeField; } set { if ((this.TypeField.Equals(value)!= true)) { this.TypeField = value; this.RaisePropertyChanged("Type"); } } } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if ((propertyChanged!= null)) { propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="Contragent.ContragentDogovor", Namespace="http://schemas.datacontract.org/2004/07/Emex.Contragent")] [System.SerializableAttribute()] public partial class ContragentDogovor : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged { [System.NonSerializedAttribute()] private System.Runtime.Serialization.ExtensionDataObject extensionDataField; [System.Runtime.Serialization.OptionalFieldAttribute()] private short BalanceIdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private long ChiefUserIdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string CommentField; [System.Runtime.Serialization.OptionalFieldAttribute()] private long ContragentIdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private System.DateTime DateBeginField; [System.Runtime.Serialization.OptionalFieldAttribute()] private System.DateTime DateEndField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool DoNotSverkaSendField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string DogovorLogoField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string DogovorNumField; [System.Runtime.Serialization.OptionalFieldAttribute()] private int HasNDSField; [System.Runtime.Serialization.OptionalFieldAttribute()] private long MngrUserIdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private long ObjectIdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string SchetField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string SubSchetField; [System.Runtime.Serialization.OptionalFieldAttribute()] private long TrebovanieIdField; public System.Runtime.Serialization.ExtensionDataObject ExtensionData { get { return this.extensionDataField; } set { this.extensionDataField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] public short BalanceId { get { return this.BalanceIdField; } set { if ((this.BalanceIdField.Equals(value)!= true)) { this.BalanceIdField = value; this.RaisePropertyChanged("BalanceId"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public long ChiefUserId { get { return this.ChiefUserIdField; } set { if ((this.ChiefUserIdField.Equals(value)!= true)) { this.ChiefUserIdField = value; this.RaisePropertyChanged("ChiefUserId"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string Comment { get { return this.CommentField; } set { if ((object.ReferenceEquals(this.CommentField, value)!= true)) { this.CommentField = value; this.RaisePropertyChanged("Comment"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public long ContragentId { get { return this.ContragentIdField; } set { if ((this.ContragentIdField.Equals(value)!= true)) { this.ContragentIdField = value; this.RaisePropertyChanged("ContragentId"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public System.DateTime DateBegin { get { return this.DateBeginField; } set { if ((this.DateBeginField.Equals(value)!= true)) { this.DateBeginField = value; this.RaisePropertyChanged("DateBegin"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public System.DateTime DateEnd { get { return this.DateEndField; } set { if ((this.DateEndField.Equals(value)!= true)) { this.DateEndField = value; this.RaisePropertyChanged("DateEnd"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public bool DoNotSverkaSend { get { return this.DoNotSverkaSendField; } set { if ((this.DoNotSverkaSendField.Equals(value)!= true)) { this.DoNotSverkaSendField = value; this.RaisePropertyChanged("DoNotSverkaSend"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string DogovorLogo { get { return this.DogovorLogoField; } set { if ((object.ReferenceEquals(this.DogovorLogoField, value)!= true)) { this.DogovorLogoField = value; this.RaisePropertyChanged("DogovorLogo"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string DogovorNum { get { return this.DogovorNumField; } set { if ((object.ReferenceEquals(this.DogovorNumField, value)!= true)) { this.DogovorNumField = value; this.RaisePropertyChanged("DogovorNum"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public int HasNDS { get { return this.HasNDSField; } set { if ((this.HasNDSField.Equals(value)!= true)) { this.HasNDSField = value; this.RaisePropertyChanged("HasNDS"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public long MngrUserId { get { return this.MngrUserIdField; } set { if ((this.MngrUserIdField.Equals(value)!= true)) { this.MngrUserIdField = value; this.RaisePropertyChanged("MngrUserId"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public long ObjectId { get { return this.ObjectIdField; } set { if ((this.ObjectIdField.Equals(value)!= true)) { this.ObjectIdField = value; this.RaisePropertyChanged("ObjectId"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string Schet { get { return this.SchetField; } set { if ((object.ReferenceEquals(this.SchetField, value)!= true)) { this.SchetField = value; this.RaisePropertyChanged("Schet"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string SubSchet { get { return this.SubSchetField; } set { if ((object.ReferenceEquals(this.SubSchetField, value)!= true)) { this.SubSchetField = value; this.RaisePropertyChanged("SubSchet"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public long TrebovanieId { get { return this.TrebovanieIdField; } set { if ((this.TrebovanieIdField.Equals(value)!= true)) { this.TrebovanieIdField = value; this.RaisePropertyChanged("TrebovanieId"); } } } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if ((propertyChanged!= null)) { propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="Contragent.BankAccount", Namespace="http://schemas.datacontract.org/2004/07/Emex.Contragent")] [System.SerializableAttribute()] public partial class BankAccount : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged { [System.NonSerializedAttribute()] private System.Runtime.Serialization.ExtensionDataObject extensionDataField; [System.Runtime.Serialization.OptionalFieldAttribute()] private EmExServiceClient.ContragentService.Contragent.Bank BankField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool ClosedField; [System.Runtime.Serialization.OptionalFieldAttribute()] private long ContragentIdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private long IdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool IsDefaultField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string NumberField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string RSCommentPrefixField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string RSINNField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string RSKPPField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string RSNameField; [System.Runtime.Serialization.OptionalFieldAttribute()] private int RSTypeSchetIdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private long UserIdAddField; [System.Runtime.Serialization.OptionalFieldAttribute()] private long UserIdCheckedField; public System.Runtime.Serialization.ExtensionDataObject ExtensionData { get { return this.extensionDataField; } set { this.extensionDataField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] public EmExServiceClient.ContragentService.Contragent.Bank Bank { get { return this.BankField; } set { if ((object.ReferenceEquals(this.BankField, value)!= true)) { this.BankField = value; this.RaisePropertyChanged("Bank"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public bool Closed { get { return this.ClosedField; } set { if ((this.ClosedField.Equals(value)!= true)) { this.ClosedField = value; this.RaisePropertyChanged("Closed"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public long ContragentId { get { return this.ContragentIdField; } set { if ((this.ContragentIdField.Equals(value)!= true)) { this.ContragentIdField = value; this.RaisePropertyChanged("ContragentId"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public long Id { get { return this.IdField; } set { if ((this.IdField.Equals(value)!= true)) { this.IdField = value; this.RaisePropertyChanged("Id"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public bool IsDefault { get { return this.IsDefaultField; } set { if ((this.IsDefaultField.Equals(value)!= true)) { this.IsDefaultField = value; this.RaisePropertyChanged("IsDefault"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string Number { get { return this.NumberField; } set { if ((object.ReferenceEquals(this.NumberField, value)!= true)) { this.NumberField = value; this.RaisePropertyChanged("Number"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string RSCommentPrefix { get { return this.RSCommentPrefixField; } set { if ((object.ReferenceEquals(this.RSCommentPrefixField, value)!= true)) { this.RSCommentPrefixField = value; this.RaisePropertyChanged("RSCommentPrefix"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string RSINN { get { return this.RSINNField; } set { if ((object.ReferenceEquals(this.RSINNField, value)!= true)) { this.RSINNField = value; this.RaisePropertyChanged("RSINN"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string RSKPP { get { return this.RSKPPField; } set { if ((object.ReferenceEquals(this.RSKPPField, value)!= true)) { this.RSKPPField = value; this.RaisePropertyChanged("RSKPP"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string RSName { get { return this.RSNameField; } set { if ((object.ReferenceEquals(this.RSNameField, value)!= true)) { this.RSNameField = value; this.RaisePropertyChanged("RSName"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public int RSTypeSchetId { get { return this.RSTypeSchetIdField; } set { if ((this.RSTypeSchetIdField.Equals(value)!= true)) { this.RSTypeSchetIdField = value; this.RaisePropertyChanged("RSTypeSchetId"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public long UserIdAdd { get { return this.UserIdAddField; } set { if ((this.UserIdAddField.Equals(value)!= true)) { this.UserIdAddField = value; this.RaisePropertyChanged("UserIdAdd"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public long UserIdChecked { get { return this.UserIdCheckedField; } set { if ((this.UserIdCheckedField.Equals(value)!= true)) { this.UserIdCheckedField = value; this.RaisePropertyChanged("UserIdChecked"); } } } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if ((propertyChanged!= null)) { propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="Contragent.Bank", Namespace="http://schemas.datacontract.org/2004/07/Emex.Contragent")] [System.SerializableAttribute()] public partial class Bank : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged { [System.NonSerializedAttribute()] private System.Runtime.Serialization.ExtensionDataObject extensionDataField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string BIKField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string CityField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string INNField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string KSField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string NameField; public System.Runtime.Serialization.ExtensionDataObject ExtensionData { get { return this.extensionDataField; } set { this.extensionDataField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] public string BIK { get { return this.BIKField; } set { if ((object.ReferenceEquals(this.BIKField, value)!= true)) { this.BIKField = value; this.RaisePropertyChanged("BIK"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string City { get { return this.CityField; } set { if ((object.ReferenceEquals(this.CityField, value)!= true)) { this.CityField = value; this.RaisePropertyChanged("City"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string INN { get { return this.INNField; } set { if ((object.ReferenceEquals(this.INNField, value)!= true)) { this.INNField = value; this.RaisePropertyChanged("INN"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string KS { get { return this.KSField; } set { if ((object.ReferenceEquals(this.KSField, value)!= true)) { this.KSField = value; this.RaisePropertyChanged("KS"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string Name { get { return this.NameField; } set { if ((object.ReferenceEquals(this.NameField, value)!= true)) { this.NameField = value; this.RaisePropertyChanged("Name"); } } } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if ((propertyChanged!= null)) { propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="Customer", Namespace="http://schemas.datacontract.org/2004/07/Emex.Contragent")] [System.SerializableAttribute()] public partial class Customer : EmExServiceClient.ContragentService.Contragent { [System.Runtime.Serialization.OptionalFieldAttribute()] private EmExServiceClient.ContragentService.TransportCompany AlternativeTransportCompanyField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string AnswerCustLogoField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string CloseCommentField; [System.Runtime.Serialization.OptionalFieldAttribute()] private System.Nullable<System.DateTime> CloseDateField; [System.Runtime.Serialization.OptionalFieldAttribute()] private System.DateTime ContractDateField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string ContractNumberField; [System.Runtime.Serialization.OptionalFieldAttribute()] private int CustomerAccNumField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string CustomerActualAddressField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string CustomerAddressField; [System.Runtime.Serialization.OptionalFieldAttribute()] private long CustomerCityIdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string CustomerContactPersonsField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string CustomerDeliveryAddressField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string CustomerDeliveryAddressAltField; [System.Runtime.Serialization.OptionalFieldAttribute()] private long CustomerIdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string CustomerNameField; [System.Runtime.Serialization.OptionalFieldAttribute()] private decimal CustomerPayDeliveryField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string CustomerTelephonesField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string CustomerURLField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string DirFField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string DirFIField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string DirIField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string DirOField; [System.Runtime.Serialization.OptionalFieldAttribute()] private decimal DiscountField; [System.Runtime.Serialization.OptionalFieldAttribute()] private System.Nullable<short> DocumentCopiesField; [System.Runtime.Serialization.OptionalFieldAttribute()] private long DogovorIdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private decimal ExtraForWeightField; [System.Runtime.Serialization.OptionalFieldAttribute()] private long FirmIdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string FirstNameField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string InvoiceCustLogoField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool IsResidentField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string LastNameField; private string Logo1Field; [System.Runtime.Serialization.OptionalFieldAttribute()] private string MailAnswerCustField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string MailBalanceCustField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string MailBalanceCustBCCField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string MailConfidentialField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string MailDeliveryField; [System.Runtime.Serialization.OptionalFieldAttribute()] private EmExServiceClient.ContragentService.TransportCompany MainTransportCompanyField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string MiddleNameField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string OnlinePasswordField; [System.Runtime.Serialization.OptionalFieldAttribute()] private long OptovikIdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string OptovikTelField; [System.Runtime.Serialization.OptionalFieldAttribute()] private EmExServiceClient.ContragentService.PartnerType PartnerStatusField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string PasswordField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool PriAltSearchField; [System.Runtime.Serialization.OptionalFieldAttribute()] private System.Nullable<bool> PrintPacklistField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string ReceiptCustLogoField; [System.Runtime.Serialization.OptionalFieldAttribute()] private System.DateTime RegistrationDateField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string RegistrationEmailField; [System.Runtime.Serialization.OptionalFieldAttribute()] private long TransportCompanyAlternativeIdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private System.Nullable<byte> TransportCompanyGateField; [System.Runtime.Serialization.OptionalFieldAttribute()] private System.Nullable<byte> TransportCompanyGateAltField; [System.Runtime.Serialization.OptionalFieldAttribute()] private long TransportCompanyIdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private int UserIdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private EmExServiceClient.ContragentService.WorkType WorkTypeField; [System.Runtime.Serialization.OptionalFieldAttribute()] private EmExServiceClient.ContragentService.Customer.CustomerContact _customerContactField; [System.Runtime.Serialization.OptionalFieldAttribute()] private EmExServiceClient.ContragentService.Customer.CustomerGroup _customerGroupField; [System.Runtime.Serialization.OptionalFieldAttribute()] private EmExServiceClient.ContragentService.Customer.CustomerStorage _customerStorageField; [System.Runtime.Serialization.OptionalFieldAttribute()] private EmExServiceClient.ContragentService.Customer.CustomerDispatchSetting _dispatchSettingField; [System.Runtime.Serialization.OptionalFieldAttribute()] private EmExServiceClient.ContragentService.Customer.CustomerAccount _сustomerAccountField; [System.Runtime.Serialization.OptionalFieldAttribute()] private EmExServiceClient.ContragentService.Customer.CustomerContract _сustomerContractField; [System.Runtime.Serialization.OptionalFieldAttribute()] private EmExServiceClient.ContragentService.Customer.CustomerPrintSetting _сustomerPrintSettingField; [System.Runtime.Serialization.OptionalFieldAttribute()] private EmExServiceClient.ContragentService.Customer.CustomerStatus _сustomerStatusField; [System.Runtime.Serialization.OptionalFieldAttribute()] private System.Nullable<bool> bitCustomerBalanceNULLField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool bitCustomerCloseField; [System.Runtime.Serialization.OptionalFieldAttribute()] private System.Nullable<bool> bitNotRunCustomerForTimeField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool bitPublicField; [System.Runtime.Serialization.OptionalFieldAttribute()] private System.Nullable<bool> bitSendAccountWeightField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool bitTakeAllField; [System.Runtime.Serialization.OptionalFieldAttribute()] private System.Nullable<bool> bitUseGoodsTrellisField; [System.Runtime.Serialization.OptionalFieldAttribute()] private System.Nullable<bool> bitVIPCustomerField; [System.Runtime.Serialization.OptionalFieldAttribute()] private byte flagAnswersCustField; [System.Runtime.Serialization.OptionalFieldAttribute()] private byte flagBalancesCustField; [System.Runtime.Serialization.OptionalFieldAttribute()] private byte flagInvoicesCustField; [System.Runtime.Serialization.OptionalFieldAttribute()] private byte flagReceiptsCustField; [System.Runtime.Serialization.DataMemberAttribute()] public EmExServiceClient.ContragentService.TransportCompany AlternativeTransportCompany { get { return this.AlternativeTransportCompanyField; } set { if ((object.ReferenceEquals(this.AlternativeTransportCompanyField, value)!= true)) { this.AlternativeTransportCompanyField = value; this.RaisePropertyChanged("AlternativeTransportCompany"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string AnswerCustLogo { get { return this.AnswerCustLogoField; } set { if ((object.ReferenceEquals(this.AnswerCustLogoField, value)!= true)) { this.AnswerCustLogoField = value; this.RaisePropertyChanged("AnswerCustLogo"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string CloseComment { get { return this.CloseCommentField; } set { if ((object.ReferenceEquals(this.CloseCommentField, value)!= true)) { this.CloseCommentField = value; this.RaisePropertyChanged("CloseComment"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public System.Nullable<System.DateTime> CloseDate { get { return this.CloseDateField; } set { if ((this.CloseDateField.Equals(value)!= true)) { this.CloseDateField = value; this.RaisePropertyChanged("CloseDate"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public System.DateTime ContractDate { get { return this.ContractDateField; } set { if ((this.ContractDateField.Equals(value)!= true)) { this.ContractDateField = value; this.RaisePropertyChanged("ContractDate"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string ContractNumber { get { return this.ContractNumberField; } set { if ((object.ReferenceEquals(this.ContractNumberField, value)!= true)) { this.ContractNumberField = value; this.RaisePropertyChanged("ContractNumber"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public int CustomerAccNum { get { return this.CustomerAccNumField; } set { if ((this.CustomerAccNumField.Equals(value)!= true)) { this.CustomerAccNumField = value; this.RaisePropertyChanged("CustomerAccNum"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string CustomerActualAddress { get { return this.CustomerActualAddressField; } set { if ((object.ReferenceEquals(this.CustomerActualAddressField, value)!= true)) { this.CustomerActualAddressField = value; this.RaisePropertyChanged("CustomerActualAddress"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string CustomerAddress { get { return this.CustomerAddressField; } set { if ((object.ReferenceEquals(this.CustomerAddressField, value)!= true)) { this.CustomerAddressField = value; this.RaisePropertyChanged("CustomerAddress"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public long CustomerCityId { get { return this.CustomerCityIdField; } set { if ((this.CustomerCityIdField.Equals(value)!= true)) { this.CustomerCityIdField = value; this.RaisePropertyChanged("CustomerCityId"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string CustomerContactPersons { get { return this.CustomerContactPersonsField; } set { if ((object.ReferenceEquals(this.CustomerContactPersonsField, value)!= true)) { this.CustomerContactPersonsField = value; this.RaisePropertyChanged("CustomerContactPersons"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string CustomerDeliveryAddress { get { return this.CustomerDeliveryAddressField; } set { if ((object.ReferenceEquals(this.CustomerDeliveryAddressField, value)!= true)) { this.CustomerDeliveryAddressField = value; this.RaisePropertyChanged("CustomerDeliveryAddress"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string CustomerDeliveryAddressAlt { get { return this.CustomerDeliveryAddressAltField; } set { if ((object.ReferenceEquals(this.CustomerDeliveryAddressAltField, value)!= true)) { this.CustomerDeliveryAddressAltField = value; this.RaisePropertyChanged("CustomerDeliveryAddressAlt"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public long CustomerId { get { return this.CustomerIdField; } set { if ((this.CustomerIdField.Equals(value)!= true)) { this.CustomerIdField = value; this.RaisePropertyChanged("CustomerId"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string CustomerName { get { return this.CustomerNameField; } set { if ((object.ReferenceEquals(this.CustomerNameField, value)!= true)) { this.CustomerNameField = value; this.RaisePropertyChanged("CustomerName"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public decimal CustomerPayDelivery { get { return this.CustomerPayDeliveryField; } set { if ((this.CustomerPayDeliveryField.Equals(value)!= true)) { this.CustomerPayDeliveryField = value; this.RaisePropertyChanged("CustomerPayDelivery"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string CustomerTelephones { get { return this.CustomerTelephonesField; } set { if ((object.ReferenceEquals(this.CustomerTelephonesField, value)!= true)) { this.CustomerTelephonesField = value; this.RaisePropertyChanged("CustomerTelephones"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string CustomerURL { get { return this.CustomerURLField; } set { if ((object.ReferenceEquals(this.CustomerURLField, value)!= true)) { this.CustomerURLField = value; this.RaisePropertyChanged("CustomerURL"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string DirF { get { return this.DirFField; } set { if ((object.ReferenceEquals(this.DirFField, value)!= true)) { this.DirFField = value; this.RaisePropertyChanged("DirF"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string DirFI { get { return this.DirFIField; } set { if ((object.ReferenceEquals(this.DirFIField, value)!= true)) { this.DirFIField = value; this.RaisePropertyChanged("DirFI"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string DirI { get { return this.DirIField; } set { if ((object.ReferenceEquals(this.DirIField, value)!= true)) { this.DirIField = value; this.RaisePropertyChanged("DirI"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string DirO { get { return this.DirOField; } set { if ((object.ReferenceEquals(this.DirOField, value)!= true)) { this.DirOField = value; this.RaisePropertyChanged("DirO"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public decimal Discount { get { return this.DiscountField; } set { if ((this.DiscountField.Equals(value)!= true)) { this.DiscountField = value; this.RaisePropertyChanged("Discount"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public System.Nullable<short> DocumentCopies { get { return this.DocumentCopiesField; } set { if ((this.DocumentCopiesField.Equals(value)!= true)) { this.DocumentCopiesField = value; this.RaisePropertyChanged("DocumentCopies"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public long DogovorId { get { return this.DogovorIdField; } set { if ((this.DogovorIdField.Equals(value)!= true)) { this.DogovorIdField = value; this.RaisePropertyChanged("DogovorId"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public decimal ExtraForWeight { get { return this.ExtraForWeightField; } set { if ((this.ExtraForWeightField.Equals(value)!= true)) { this.ExtraForWeightField = value; this.RaisePropertyChanged("ExtraForWeight"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public long FirmId { get { return this.FirmIdField; } set { if ((this.FirmIdField.Equals(value)!= true)) { this.FirmIdField = value; this.RaisePropertyChanged("FirmId"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string FirstName { get { return this.FirstNameField; } set { if ((object.ReferenceEquals(this.FirstNameField, value)!= true)) { this.FirstNameField = value; this.RaisePropertyChanged("FirstName"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string InvoiceCustLogo { get { return this.InvoiceCustLogoField; } set { if ((object.ReferenceEquals(this.InvoiceCustLogoField, value)!= true)) { this.InvoiceCustLogoField = value; this.RaisePropertyChanged("InvoiceCustLogo"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public bool IsResident { get { return this.IsResidentField; } set { if ((this.IsResidentField.Equals(value)!= true)) { this.IsResidentField = value; this.RaisePropertyChanged("IsResident"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string LastName { get { return this.LastNameField; } set { if ((object.ReferenceEquals(this.LastNameField, value)!= true)) { this.LastNameField = value; this.RaisePropertyChanged("LastName"); } } } [System.Runtime.Serialization.DataMemberAttribute(Name="Logo", IsRequired=true)] public string Logo1 { get { return this.Logo1Field; } set { if ((object.ReferenceEquals(this.Logo1Field, value)!= true)) { this.Logo1Field = value; this.RaisePropertyChanged("Logo1"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string MailAnswerCust { get { return this.MailAnswerCustField; } set { if ((object.ReferenceEquals(this.MailAnswerCustField, value)!= true)) { this.MailAnswerCustField = value; this.RaisePropertyChanged("MailAnswerCust"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string MailBalanceCust { get { return this.MailBalanceCustField; } set { if ((object.ReferenceEquals(this.MailBalanceCustField, value)!= true)) { this.MailBalanceCustField = value; this.RaisePropertyChanged("MailBalanceCust"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string MailBalanceCustBCC { get { return this.MailBalanceCustBCCField; } set { if ((object.ReferenceEquals(this.MailBalanceCustBCCField, value)!= true)) { this.MailBalanceCustBCCField = value; this.RaisePropertyChanged("MailBalanceCustBCC"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string MailConfidential { get { return this.MailConfidentialField; } set { if ((object.ReferenceEquals(this.MailConfidentialField, value)!= true)) { this.MailConfidentialField = value; this.RaisePropertyChanged("MailConfidential"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string MailDelivery { get { return this.MailDeliveryField; } set { if ((object.ReferenceEquals(this.MailDeliveryField, value)!= true)) { this.MailDeliveryField = value; this.RaisePropertyChanged("MailDelivery"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public EmExServiceClient.ContragentService.TransportCompany MainTransportCompany { get { return this.MainTransportCompanyField; } set { if ((object.ReferenceEquals(this.MainTransportCompanyField, value)!= true)) { this.MainTransportCompanyField = value; this.RaisePropertyChanged("MainTransportCompany"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string MiddleName { get { return this.MiddleNameField; } set { if ((object.ReferenceEquals(this.MiddleNameField, value)!= true)) { this.MiddleNameField = value; this.RaisePropertyChanged("MiddleName"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string OnlinePassword { get { return this.OnlinePasswordField; } set { if ((object.ReferenceEquals(this.OnlinePasswordField, value)!= true)) { this.OnlinePasswordField = value; this.RaisePropertyChanged("OnlinePassword"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public long OptovikId { get { return this.OptovikIdField; } set { if ((this.OptovikIdField.Equals(value)!= true)) { this.OptovikIdField = value; this.RaisePropertyChanged("OptovikId"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string OptovikTel { get { return this.OptovikTelField; } set { if ((object.ReferenceEquals(this.OptovikTelField, value)!= true)) { this.OptovikTelField = value; this.RaisePropertyChanged("OptovikTel"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public EmExServiceClient.ContragentService.PartnerType PartnerStatus { get { return this.PartnerStatusField; } set { if ((this.PartnerStatusField.Equals(value)!= true)) { this.PartnerStatusField = value; this.RaisePropertyChanged("PartnerStatus"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string Password { get { return this.PasswordField; } set { if ((object.ReferenceEquals(this.PasswordField, value)!= true)) { this.PasswordField = value; this.RaisePropertyChanged("Password"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public bool PriAltSearch { get { return this.PriAltSearchField; } set { if ((this.PriAltSearchField.Equals(value)!= true)) { this.PriAltSearchField = value; this.RaisePropertyChanged("PriAltSearch"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public System.Nullable<bool> PrintPacklist { get { return this.PrintPacklistField; } set { if ((this.PrintPacklistField.Equals(value)!= true)) { this.PrintPacklistField = value; this.RaisePropertyChanged("PrintPacklist"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string ReceiptCustLogo { get { return this.ReceiptCustLogoField; } set { if ((object.ReferenceEquals(this.ReceiptCustLogoField, value)!= true)) { this.ReceiptCustLogoField = value; this.RaisePropertyChanged("ReceiptCustLogo"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public System.DateTime RegistrationDate { get { return this.RegistrationDateField; } set { if ((this.RegistrationDateField.Equals(value)!= true)) { this.RegistrationDateField = value; this.RaisePropertyChanged("RegistrationDate"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string RegistrationEmail { get { return this.RegistrationEmailField; } set { if ((object.ReferenceEquals(this.RegistrationEmailField, value)!= true)) { this.RegistrationEmailField = value; this.RaisePropertyChanged("RegistrationEmail"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public long TransportCompanyAlternativeId { get { return this.TransportCompanyAlternativeIdField; } set { if ((this.TransportCompanyAlternativeIdField.Equals(value)!= true)) { this.TransportCompanyAlternativeIdField = value; this.RaisePropertyChanged("TransportCompanyAlternativeId"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public System.Nullable<byte> TransportCompanyGate { get { return this.TransportCompanyGateField; } set { if ((this.TransportCompanyGateField.Equals(value)!= true)) { this.TransportCompanyGateField = value; this.RaisePropertyChanged("TransportCompanyGate"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public System.Nullable<byte> TransportCompanyGateAlt { get { return this.TransportCompanyGateAltField; } set { if ((this.TransportCompanyGateAltField.Equals(value)!= true)) { this.TransportCompanyGateAltField = value; this.RaisePropertyChanged("TransportCompanyGateAlt"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public long TransportCompanyId { get { return this.TransportCompanyIdField; } set { if ((this.TransportCompanyIdField.Equals(value)!= true)) { this.TransportCompanyIdField = value; this.RaisePropertyChanged("TransportCompanyId"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public int UserId { get { return this.UserIdField; } set { if ((this.UserIdField.Equals(value)!= true)) { this.UserIdField = value; this.RaisePropertyChanged("UserId"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public EmExServiceClient.ContragentService.WorkType WorkType { get { return this.WorkTypeField; } set { if ((this.WorkTypeField.Equals(value)!= true)) { this.WorkTypeField = value; this.RaisePropertyChanged("WorkType"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public EmExServiceClient.ContragentService.Customer.CustomerContact _customerContact { get { return this._customerContactField; } set { if ((object.ReferenceEquals(this._customerContactField, value)!= true)) { this._customerContactField = value; this.RaisePropertyChanged("_customerContact"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public EmExServiceClient.ContragentService.Customer.CustomerGroup _customerGroup { get { return this._customerGroupField; } set { if ((object.ReferenceEquals(this._customerGroupField, value)!= true)) { this._customerGroupField = value; this.RaisePropertyChanged("_customerGroup"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public EmExServiceClient.ContragentService.Customer.CustomerStorage _customerStorage { get { return this._customerStorageField; } set { if ((object.ReferenceEquals(this._customerStorageField, value)!= true)) { this._customerStorageField = value; this.RaisePropertyChanged("_customerStorage"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public EmExServiceClient.ContragentService.Customer.CustomerDispatchSetting _dispatchSetting { get { return this._dispatchSettingField; } set { if ((object.ReferenceEquals(this._dispatchSettingField, value)!= true)) { this._dispatchSettingField = value; this.RaisePropertyChanged("_dispatchSetting"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public EmExServiceClient.ContragentService.Customer.CustomerAccount _сustomerAccount { get { return this._сustomerAccountField; } set { if ((object.ReferenceEquals(this._сustomerAccountField, value)!= true)) { this._сustomerAccountField = value; this.RaisePropertyChanged("_сustomerAccount"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public EmExServiceClient.ContragentService.Customer.CustomerContract _сustomerContract { get { return this._сustomerContractField; } set { if ((object.ReferenceEquals(this._сustomerContractField, value)!= true)) { this._сustomerContractField = value; this.RaisePropertyChanged("_сustomerContract"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public EmExServiceClient.ContragentService.Customer.CustomerPrintSetting _сustomerPrintSetting { get { return this._сustomerPrintSettingField; } set { if ((object.ReferenceEquals(this._сustomerPrintSettingField, value)!= true)) { this._сustomerPrintSettingField = value; this.RaisePropertyChanged("_сustomerPrintSetting"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public EmExServiceClient.ContragentService.Customer.CustomerStatus _сustomerStatus { get { return this._сustomerStatusField; } set { if ((object.ReferenceEquals(this._сustomerStatusField, value)!= true)) { this._сustomerStatusField = value; this.RaisePropertyChanged("_сustomerStatus"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public System.Nullable<bool> bitCustomerBalanceNULL { get { return this.bitCustomerBalanceNULLField; } set { if ((this.bitCustomerBalanceNULLField.Equals(value)!= true)) { this.bitCustomerBalanceNULLField = value; this.RaisePropertyChanged("bitCustomerBalanceNULL"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public bool bitCustomerClose { get { return this.bitCustomerCloseField; } set { if ((this.bitCustomerCloseField.Equals(value)!= true)) { this.bitCustomerCloseField = value; this.RaisePropertyChanged("bitCustomerClose"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public System.Nullable<bool> bitNotRunCustomerForTime { get { return this.bitNotRunCustomerForTimeField; } set { if ((this.bitNotRunCustomerForTimeField.Equals(value)!= true)) { this.bitNotRunCustomerForTimeField = value; this.RaisePropertyChanged("bitNotRunCustomerForTime"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public bool bitPublic { get { return this.bitPublicField; } set { if ((this.bitPublicField.Equals(value)!= true)) { this.bitPublicField = value; this.RaisePropertyChanged("bitPublic"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public System.Nullable<bool> bitSendAccountWeight { get { return this.bitSendAccountWeightField; } set { if ((this.bitSendAccountWeightField.Equals(value)!= true)) { this.bitSendAccountWeightField = value; this.RaisePropertyChanged("bitSendAccountWeight"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public bool bitTakeAll { get { return this.bitTakeAllField; } set { if ((this.bitTakeAllField.Equals(value)!= true)) { this.bitTakeAllField = value; this.RaisePropertyChanged("bitTakeAll"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public System.Nullable<bool> bitUseGoodsTrellis { get { return this.bitUseGoodsTrellisField; } set { if ((this.bitUseGoodsTrellisField.Equals(value)!= true)) { this.bitUseGoodsTrellisField = value; this.RaisePropertyChanged("bitUseGoodsTrellis"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public System.Nullable<bool> bitVIPCustomer { get { return this.bitVIPCustomerField; } set { if ((this.bitVIPCustomerField.Equals(value)!= true)) { this.bitVIPCustomerField = value; this.RaisePropertyChanged("bitVIPCustomer"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public byte flagAnswersCust { get { return this.flagAnswersCustField; } set { if ((this.flagAnswersCustField.Equals(value)!= true)) { this.flagAnswersCustField = value; this.RaisePropertyChanged("flagAnswersCust"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public byte flagBalancesCust { get { return this.flagBalancesCustField; } set { if ((this.flagBalancesCustField.Equals(value)!= true)) { this.flagBalancesCustField = value; this.RaisePropertyChanged("flagBalancesCust"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public byte flagInvoicesCust { get { return this.flagInvoicesCustField; } set { if ((this.flagInvoicesCustField.Equals(value)!= true)) { this.flagInvoicesCustField = value; this.RaisePropertyChanged("flagInvoicesCust"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public byte flagReceiptsCust { get { return this.flagReceiptsCustField; } set { if ((this.flagReceiptsCustField.Equals(value)!= true)) { this.flagReceiptsCustField = value; this.RaisePropertyChanged("flagReceiptsCust"); } } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="Customer.CustomerContact", Namespace="http://schemas.datacontract.org/2004/07/Emex.Contragent")] [System.SerializableAttribute()] public partial class CustomerContact : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged { [System.NonSerializedAttribute()] private System.Runtime.Serialization.ExtensionDataObject extensionDataField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string AddressField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string ContactPersonsField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string DeliveryAddressField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string InfoSourceField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string MailAnswerCustField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string TelephonesField; public System.Runtime.Serialization.ExtensionDataObject ExtensionData { get { return this.extensionDataField; } set { this.extensionDataField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] public string Address { get { return this.AddressField; } set { if ((object.ReferenceEquals(this.AddressField, value)!= true)) { this.AddressField = value; this.RaisePropertyChanged("Address"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string ContactPersons { get { return this.ContactPersonsField; } set { if ((object.ReferenceEquals(this.ContactPersonsField, value)!= true)) { this.ContactPersonsField = value; this.RaisePropertyChanged("ContactPersons"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string DeliveryAddress { get { return this.DeliveryAddressField; } set { if ((object.ReferenceEquals(this.DeliveryAddressField, value)!= true)) { this.DeliveryAddressField = value; this.RaisePropertyChanged("DeliveryAddress"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string InfoSource { get { return this.InfoSourceField; } set { if ((object.ReferenceEquals(this.InfoSourceField, value)!= true)) { this.InfoSourceField = value; this.RaisePropertyChanged("InfoSource"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string MailAnswerCust { get { return this.MailAnswerCustField; } set { if ((object.ReferenceEquals(this.MailAnswerCustField, value)!= true)) { this.MailAnswerCustField = value; this.RaisePropertyChanged("MailAnswerCust"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string Telephones { get { return this.TelephonesField; } set { if ((object.ReferenceEquals(this.TelephonesField, value)!= true)) { this.TelephonesField = value; this.RaisePropertyChanged("Telephones"); } } } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if ((propertyChanged!= null)) { propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="Customer.CustomerGroup", Namespace="http://schemas.datacontract.org/2004/07/Emex.Contragent")] [System.SerializableAttribute()] public partial class CustomerGroup : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged { [System.NonSerializedAttribute()] private System.Runtime.Serialization.ExtensionDataObject extensionDataField; [System.Runtime.Serialization.OptionalFieldAttribute()] private System.Nullable<long> IdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string LogoField; public System.Runtime.Serialization.ExtensionDataObject ExtensionData { get { return this.extensionDataField; } set { this.extensionDataField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] public System.Nullable<long> Id { get { return this.IdField; } set { if ((this.IdField.Equals(value)!= true)) { this.IdField = value; this.RaisePropertyChanged("Id"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string Logo { get { return this.LogoField; } set { if ((object.ReferenceEquals(this.LogoField, value)!= true)) { this.LogoField = value; this.RaisePropertyChanged("Logo"); } } } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if ((propertyChanged!= null)) { propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="Customer.CustomerStorage", Namespace="http://schemas.datacontract.org/2004/07/Emex.Contragent")] [System.SerializableAttribute()] public partial class CustomerStorage : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged { [System.NonSerializedAttribute()] private System.Runtime.Serialization.ExtensionDataObject extensionDataField; [System.Runtime.Serialization.OptionalFieldAttribute()] private int FreeHoursBaseField; [System.Runtime.Serialization.OptionalFieldAttribute()] private int FreeHoursCorrectiveField; [System.Runtime.Serialization.OptionalFieldAttribute()] private int HoursOfFreeField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool IsPaymentField; public System.Runtime.Serialization.ExtensionDataObject ExtensionData { get { return this.extensionDataField; } set { this.extensionDataField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] public int FreeHoursBase { get { return this.FreeHoursBaseField; } set { if ((this.FreeHoursBaseField.Equals(value)!= true)) { this.FreeHoursBaseField = value; this.RaisePropertyChanged("FreeHoursBase"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public int FreeHoursCorrective { get { return this.FreeHoursCorrectiveField; } set { if ((this.FreeHoursCorrectiveField.Equals(value)!= true)) { this.FreeHoursCorrectiveField = value; this.RaisePropertyChanged("FreeHoursCorrective"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public int HoursOfFree { get { return this.HoursOfFreeField; } set { if ((this.HoursOfFreeField.Equals(value)!= true)) { this.HoursOfFreeField = value; this.RaisePropertyChanged("HoursOfFree"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public bool IsPayment { get { return this.IsPaymentField; } set { if ((this.IsPaymentField.Equals(value)!= true)) { this.IsPaymentField = value; this.RaisePropertyChanged("IsPayment"); } } } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if ((propertyChanged!= null)) { propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="Customer.CustomerDispatchSetting", Namespace="http://schemas.datacontract.org/2004/07/Emex.Contragent")] [System.SerializableAttribute()] public partial class CustomerDispatchSetting : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged { [System.NonSerializedAttribute()] private System.Runtime.Serialization.ExtensionDataObject extensionDataField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string AnswersDispatchEmailField; [System.Runtime.Serialization.OptionalFieldAttribute()] private int AnswersDispatchTypeField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string BalancesDispatchEmailField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string BalancesDispatchEmailBCCField; [System.Runtime.Serialization.OptionalFieldAttribute()] private int BalancesDispatchTypeField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string InvoicesDispatchEmailField; [System.Runtime.Serialization.OptionalFieldAttribute()] private int InvoicesDispatchTypeField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string MailConfidentialField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string UserEmailsField; public System.Runtime.Serialization.ExtensionDataObject ExtensionData { get { return this.extensionDataField; } set { this.extensionDataField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] public string AnswersDispatchEmail { get { return this.AnswersDispatchEmailField; } set { if ((object.ReferenceEquals(this.AnswersDispatchEmailField, value)!= true)) { this.AnswersDispatchEmailField = value; this.RaisePropertyChanged("AnswersDispatchEmail"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public int AnswersDispatchType { get { return this.AnswersDispatchTypeField; } set { if ((this.AnswersDispatchTypeField.Equals(value)!= true)) { this.AnswersDispatchTypeField = value; this.RaisePropertyChanged("AnswersDispatchType"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string BalancesDispatchEmail { get { return this.BalancesDispatchEmailField; } set { if ((object.ReferenceEquals(this.BalancesDispatchEmailField, value)!= true)) { this.BalancesDispatchEmailField = value; this.RaisePropertyChanged("BalancesDispatchEmail"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string BalancesDispatchEmailBCC { get { return this.BalancesDispatchEmailBCCField; } set { if ((object.ReferenceEquals(this.BalancesDispatchEmailBCCField, value)!= true)) { this.BalancesDispatchEmailBCCField = value; this.RaisePropertyChanged("BalancesDispatchEmailBCC"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public int BalancesDispatchType { get { return this.BalancesDispatchTypeField; } set { if ((this.BalancesDispatchTypeField.Equals(value)!= true)) { this.BalancesDispatchTypeField = value; this.RaisePropertyChanged("BalancesDispatchType"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string InvoicesDispatchEmail { get { return this.InvoicesDispatchEmailField; } set { if ((object.ReferenceEquals(this.InvoicesDispatchEmailField, value)!= true)) { this.InvoicesDispatchEmailField = value; this.RaisePropertyChanged("InvoicesDispatchEmail"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public int InvoicesDispatchType { get { return this.InvoicesDispatchTypeField; } set { if ((this.InvoicesDispatchTypeField.Equals(value)!= true)) { this.InvoicesDispatchTypeField = value; this.RaisePropertyChanged("InvoicesDispatchType"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string MailConfidential { get { return this.MailConfidentialField; } set { if ((object.ReferenceEquals(this.MailConfidentialField, value)!= true)) { this.MailConfidentialField = value; this.RaisePropertyChanged("MailConfidential"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string UserEmails { get { return this.UserEmailsField; } set { if ((object.ReferenceEquals(this.UserEmailsField, value)!= true)) { this.UserEmailsField = value; this.RaisePropertyChanged("UserEmails"); } } } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if ((propertyChanged!= null)) { propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="Customer.CustomerAccount", Namespace="http://schemas.datacontract.org/2004/07/Emex.Contragent")] [System.SerializableAttribute()] public partial class CustomerAccount : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged { [System.NonSerializedAttribute()] private System.Runtime.Serialization.ExtensionDataObject extensionDataField; [System.Runtime.Serialization.OptionalFieldAttribute()] private byte FlagAccountsCustField; [System.Runtime.Serialization.OptionalFieldAttribute()] private byte FlagAccountsShowField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool IsInvoicePrintField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool IsInvoiceSendField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool IsInvoiceTypeOnePrintField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool IsInvoiceTypeOneSendField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool IsInvoiceTypeOneViewField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool IsInvoiceViewField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool IsTorg12PrintField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool IsTorg12SendField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool IsTorg12ViewField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool IsUpdPrintField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool IsUpdSendField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool IsUpdViewField; [System.Runtime.Serialization.OptionalFieldAttribute()] private int LastAccountNumberField; [System.Runtime.Serialization.OptionalFieldAttribute()] private decimal MaxDebtField; [System.Runtime.Serialization.OptionalFieldAttribute()] private decimal MaxDebtCoeffField; [System.Runtime.Serialization.OptionalFieldAttribute()] private decimal PayDeliveryField; public System.Runtime.Serialization.ExtensionDataObject ExtensionData { get { return this.extensionDataField; } set { this.extensionDataField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] public byte FlagAccountsCust { get { return this.FlagAccountsCustField; } set { if ((this.FlagAccountsCustField.Equals(value)!= true)) { this.FlagAccountsCustField = value; this.RaisePropertyChanged("FlagAccountsCust"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public byte FlagAccountsShow { get { return this.FlagAccountsShowField; } set { if ((this.FlagAccountsShowField.Equals(value)!= true)) { this.FlagAccountsShowField = value; this.RaisePropertyChanged("FlagAccountsShow"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public bool IsInvoicePrint { get { return this.IsInvoicePrintField; } set { if ((this.IsInvoicePrintField.Equals(value)!= true)) { this.IsInvoicePrintField = value; this.RaisePropertyChanged("IsInvoicePrint"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public bool IsInvoiceSend { get { return this.IsInvoiceSendField; } set { if ((this.IsInvoiceSendField.Equals(value)!= true)) { this.IsInvoiceSendField = value; this.RaisePropertyChanged("IsInvoiceSend"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public bool IsInvoiceTypeOnePrint { get { return this.IsInvoiceTypeOnePrintField; } set { if ((this.IsInvoiceTypeOnePrintField.Equals(value)!= true)) { this.IsInvoiceTypeOnePrintField = value; this.RaisePropertyChanged("IsInvoiceTypeOnePrint"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public bool IsInvoiceTypeOneSend { get { return this.IsInvoiceTypeOneSendField; } set { if ((this.IsInvoiceTypeOneSendField.Equals(value)!= true)) { this.IsInvoiceTypeOneSendField = value; this.RaisePropertyChanged("IsInvoiceTypeOneSend"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public bool IsInvoiceTypeOneView { get { return this.IsInvoiceTypeOneViewField; } set { if ((this.IsInvoiceTypeOneViewField.Equals(value)!= true)) { this.IsInvoiceTypeOneViewField = value; this.RaisePropertyChanged("IsInvoiceTypeOneView"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public bool IsInvoiceView { get { return this.IsInvoiceViewField; } set { if ((this.IsInvoiceViewField.Equals(value)!= true)) { this.IsInvoiceViewField = value; this.RaisePropertyChanged("IsInvoiceView"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public bool IsTorg12Print { get { return this.IsTorg12PrintField; } set { if ((this.IsTorg12PrintField.Equals(value)!= true)) { this.IsTorg12PrintField = value; this.RaisePropertyChanged("IsTorg12Print"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public bool IsTorg12Send { get { return this.IsTorg12SendField; } set { if ((this.IsTorg12SendField.Equals(value)!= true)) { this.IsTorg12SendField = value; this.RaisePropertyChanged("IsTorg12Send"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public bool IsTorg12View { get { return this.IsTorg12ViewField; } set { if ((this.IsTorg12ViewField.Equals(value)!= true)) { this.IsTorg12ViewField = value; this.RaisePropertyChanged("IsTorg12View"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public bool IsUpdPrint { get { return this.IsUpdPrintField; } set { if ((this.IsUpdPrintField.Equals(value)!= true)) { this.IsUpdPrintField = value; this.RaisePropertyChanged("IsUpdPrint"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public bool IsUpdSend { get { return this.IsUpdSendField; } set { if ((this.IsUpdSendField.Equals(value)!= true)) { this.IsUpdSendField = value; this.RaisePropertyChanged("IsUpdSend"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public bool IsUpdView { get { return this.IsUpdViewField; } set { if ((this.IsUpdViewField.Equals(value)!= true)) { this.IsUpdViewField = value; this.RaisePropertyChanged("IsUpdView"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public int LastAccountNumber { get { return this.LastAccountNumberField; } set { if ((this.LastAccountNumberField.Equals(value)!= true)) { this.LastAccountNumberField = value; this.RaisePropertyChanged("LastAccountNumber"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public decimal MaxDebt { get { return this.MaxDebtField; } set { if ((this.MaxDebtField.Equals(value)!= true)) { this.MaxDebtField = value; this.RaisePropertyChanged("MaxDebt"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public decimal MaxDebtCoeff { get { return this.MaxDebtCoeffField; } set { if ((this.MaxDebtCoeffField.Equals(value)!= true)) { this.MaxDebtCoeffField = value; this.RaisePropertyChanged("MaxDebtCoeff"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public decimal PayDelivery { get { return this.PayDeliveryField; } set { if ((this.PayDeliveryField.Equals(value)!= true)) { this.PayDeliveryField = value; this.RaisePropertyChanged("PayDelivery"); } } } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if ((propertyChanged!= null)) { propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="Customer.CustomerContract", Namespace="http://schemas.datacontract.org/2004/07/Emex.Contragent")] [System.SerializableAttribute()] public partial class CustomerContract : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged { [System.NonSerializedAttribute()] private System.Runtime.Serialization.ExtensionDataObject extensionDataField; [System.Runtime.Serialization.OptionalFieldAttribute()] private System.Nullable<long> ContragentIdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private System.Nullable<System.DateTime> DateField; [System.Runtime.Serialization.OptionalFieldAttribute()] private System.Nullable<int> DogovorIdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool HasNdsField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string LogoField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string NumberField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string SchetField; public System.Runtime.Serialization.ExtensionDataObject ExtensionData { get { return this.extensionDataField; } set { this.extensionDataField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] public System.Nullable<long> ContragentId { get { return this.ContragentIdField; } set { if ((this.ContragentIdField.Equals(value)!= true)) { this.ContragentIdField = value; this.RaisePropertyChanged("ContragentId"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public System.Nullable<System.DateTime> Date { get { return this.DateField; } set { if ((this.DateField.Equals(value)!= true)) { this.DateField = value; this.RaisePropertyChanged("Date"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public System.Nullable<int> DogovorId { get { return this.DogovorIdField; } set { if ((this.DogovorIdField.Equals(value)!= true)) { this.DogovorIdField = value; this.RaisePropertyChanged("DogovorId"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public bool HasNds { get { return this.HasNdsField; } set { if ((this.HasNdsField.Equals(value)!= true)) { this.HasNdsField = value; this.RaisePropertyChanged("HasNds"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string Logo { get { return this.LogoField; } set { if ((object.ReferenceEquals(this.LogoField, value)!= true)) { this.LogoField = value; this.RaisePropertyChanged("Logo"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string Number { get { return this.NumberField; } set { if ((object.ReferenceEquals(this.NumberField, value)!= true)) { this.NumberField = value; this.RaisePropertyChanged("Number"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string Schet { get { return this.SchetField; } set { if ((object.ReferenceEquals(this.SchetField, value)!= true)) { this.SchetField = value; this.RaisePropertyChanged("Schet"); } } } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if ((propertyChanged!= null)) { propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="Customer.CustomerPrintSetting", Namespace="http://schemas.datacontract.org/2004/07/Emex.Contragent")] [System.SerializableAttribute()] public partial class CustomerPrintSetting : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged { [System.NonSerializedAttribute()] private System.Runtime.Serialization.ExtensionDataObject extensionDataField; [System.Runtime.Serialization.OptionalFieldAttribute()] private int DocumentCopiesField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool IsPrintPackSheetField; public System.Runtime.Serialization.ExtensionDataObject ExtensionData { get { return this.extensionDataField; } set { this.extensionDataField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] public int DocumentCopies { get { return this.DocumentCopiesField; } set { if ((this.DocumentCopiesField.Equals(value)!= true)) { this.DocumentCopiesField = value; this.RaisePropertyChanged("DocumentCopies"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public bool IsPrintPackSheet { get { return this.IsPrintPackSheetField; } set { if ((this.IsPrintPackSheetField.Equals(value)!= true)) { this.IsPrintPackSheetField = value; this.RaisePropertyChanged("IsPrintPackSheet"); } } } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if ((propertyChanged!= null)) { propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="Customer.CustomerStatus", Namespace="http://schemas.datacontract.org/2004/07/Emex.Contragent")] [System.SerializableAttribute()] public partial class CustomerStatus : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged { [System.NonSerializedAttribute()] private System.Runtime.Serialization.ExtensionDataObject extensionDataField; [System.Runtime.Serialization.OptionalFieldAttribute()] private System.Collections.Specialized.BitVector32 _flagsField; public System.Runtime.Serialization.ExtensionDataObject ExtensionData { get { return this.extensionDataField; } set { this.extensionDataField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] public System.Collections.Specialized.BitVector32 _flags { get { return this._flagsField; } set { if ((this._flagsField.Equals(value)!= true)) { this._flagsField = value; this.RaisePropertyChanged("_flags"); } } } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if ((propertyChanged!= null)) { propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } } } [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="AddressType", Namespace="http://schemas.datacontract.org/2004/07/Emex.Contragent")] public enum AddressType : int { [System.Runtime.Serialization.EnumMemberAttribute()] Legal = 0, [System.Runtime.Serialization.EnumMemberAttribute()] Actual = 1, [System.Runtime.Serialization.EnumMemberAttribute()] Delivery = 2, } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="SupplierDocumentReturnCard", Namespace="http://schemas.datacontract.org/2004/07/Emex.Document")] [System.SerializableAttribute()] public partial class SupplierDocumentReturnCard : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged { [System.NonSerializedAttribute()] private System.Runtime.Serialization.ExtensionDataObject extensionDataField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool CanOverSetField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool CanRecreateReturnDocumentField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool CanRevocationField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string CommentField; [System.Runtime.Serialization.OptionalFieldAttribute()] private System.Nullable<System.DateTime> DiadocDateSetField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string DocHyperlinkField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string DocNumberField; [System.Runtime.Serialization.OptionalFieldAttribute()] private System.Nullable<System.DateTime> DocumentDateField; [System.Runtime.Serialization.OptionalFieldAttribute()] private long DocumentIdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private System.DateTime InsertDateField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string InvoiceNumberSFField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string InvoiceNumberStandartField; [System.Runtime.Serialization.OptionalFieldAttribute()] private long InvoiceSfLostIdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool IsRowHiddenField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool RecreateReturnDocumentField; [System.Runtime.Serialization.OptionalFieldAttribute()] private long[] ReturnDocumentIdsField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool RunOverSetField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool RunRevocationField; [System.Runtime.Serialization.OptionalFieldAttribute()] private long SupplierIdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string SupplierLogoField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string TypeLostField; [global::System.ComponentModel.BrowsableAttribute(false)] public System.Runtime.Serialization.ExtensionDataObject ExtensionData { get { return this.extensionDataField; } set { this.extensionDataField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] public bool CanOverSet { get { return this.CanOverSetField; } set { if ((this.CanOverSetField.Equals(value)!= true)) { this.CanOverSetField = value; this.RaisePropertyChanged("CanOverSet"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public bool CanRecreateReturnDocument { get { return this.CanRecreateReturnDocumentField; } set { if ((this.CanRecreateReturnDocumentField.Equals(value)!= true)) { this.CanRecreateReturnDocumentField = value; this.RaisePropertyChanged("CanRecreateReturnDocument"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public bool CanRevocation { get { return this.CanRevocationField; } set { if ((this.CanRevocationField.Equals(value)!= true)) { this.CanRevocationField = value; this.RaisePropertyChanged("CanRevocation"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string Comment { get { return this.CommentField; } set { if ((object.ReferenceEquals(this.CommentField, value)!= true)) { this.CommentField = value; this.RaisePropertyChanged("Comment"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public System.Nullable<System.DateTime> DiadocDateSet { get { return this.DiadocDateSetField; } set { if ((this.DiadocDateSetField.Equals(value)!= true)) { this.DiadocDateSetField = value; this.RaisePropertyChanged("DiadocDateSet"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string DocHyperlink { get { return this.DocHyperlinkField; } set { if ((object.ReferenceEquals(this.DocHyperlinkField, value)!= true)) { this.DocHyperlinkField = value; this.RaisePropertyChanged("DocHyperlink"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string DocNumber { get { return this.DocNumberField; } set { if ((object.ReferenceEquals(this.DocNumberField, value)!= true)) { this.DocNumberField = value; this.RaisePropertyChanged("DocNumber"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public System.Nullable<System.DateTime> DocumentDate { get { return this.DocumentDateField; } set { if ((this.DocumentDateField.Equals(value)!= true)) { this.DocumentDateField = value; this.RaisePropertyChanged("DocumentDate"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public long DocumentId { get { return this.DocumentIdField; } set { if ((this.DocumentIdField.Equals(value)!= true)) { this.DocumentIdField = value; this.RaisePropertyChanged("DocumentId"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public System.DateTime InsertDate { get { return this.InsertDateField; } set { if ((this.InsertDateField.Equals(value)!= true)) { this.InsertDateField = value; this.RaisePropertyChanged("InsertDate"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string InvoiceNumberSF { get { return this.InvoiceNumberSFField; } set { if ((object.ReferenceEquals(this.InvoiceNumberSFField, value)!= true)) { this.InvoiceNumberSFField = value; this.RaisePropertyChanged("InvoiceNumberSF"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string InvoiceNumberStandart { get { return this.InvoiceNumberStandartField; } set { if ((object.ReferenceEquals(this.InvoiceNumberStandartField, value)!= true)) { this.InvoiceNumberStandartField = value; this.RaisePropertyChanged("InvoiceNumberStandart"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public long InvoiceSfLostId { get { return this.InvoiceSfLostIdField; } set { if ((this.InvoiceSfLostIdField.Equals(value)!= true)) { this.InvoiceSfLostIdField = value; this.RaisePropertyChanged("InvoiceSfLostId"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public bool IsRowHidden { get { return this.IsRowHiddenField; } set { if ((this.IsRowHiddenField.Equals(value)!= true)) { this.IsRowHiddenField = value; this.RaisePropertyChanged("IsRowHidden"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public bool RecreateReturnDocument { get { return this.RecreateReturnDocumentField; } set { if ((this.RecreateReturnDocumentField.Equals(value)!= true)) { this.RecreateReturnDocumentField = value; this.RaisePropertyChanged("RecreateReturnDocument"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public long[] ReturnDocumentIds { get { return this.ReturnDocumentIdsField; } set { if ((object.ReferenceEquals(this.ReturnDocumentIdsField, value)!= true)) { this.ReturnDocumentIdsField = value; this.RaisePropertyChanged("ReturnDocumentIds"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public bool RunOverSet { get { return this.RunOverSetField; } set { if ((this.RunOverSetField.Equals(value)!= true)) { this.RunOverSetField = value; this.RaisePropertyChanged("RunOverSet"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public bool RunRevocation { get { return this.RunRevocationField; } set { if ((this.RunRevocationField.Equals(value)!= true)) { this.RunRevocationField = value; this.RaisePropertyChanged("RunRevocation"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public long SupplierId { get { return this.SupplierIdField; } set { if ((this.SupplierIdField.Equals(value)!= true)) { this.SupplierIdField = value; this.RaisePropertyChanged("SupplierId"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string SupplierLogo { get { return this.SupplierLogoField; } set { if ((object.ReferenceEquals(this.SupplierLogoField, value)!= true)) { this.SupplierLogoField = value; this.RaisePropertyChanged("SupplierLogo"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string TypeLost { get { return this.TypeLostField; } set { if ((object.ReferenceEquals(this.TypeLostField, value)!= true)) { this.TypeLostField = value; this.RaisePropertyChanged("TypeLost"); } } } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if ((propertyChanged!= null)) { propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="DocumentSticker", Namespace="http://schemas.datacontract.org/2004/07/Emex.Document")] [System.SerializableAttribute()] public partial class DocumentSticker : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged { [System.NonSerializedAttribute()] private System.Runtime.Serialization.ExtensionDataObject extensionDataField; [System.Runtime.Serialization.OptionalFieldAttribute()] private System.DateTime DateAndTimeField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string DocDateField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string DocNumberField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string LogoField; [System.Runtime.Serialization.OptionalFieldAttribute()] private long ReestrObjectIdField; [global::System.ComponentModel.BrowsableAttribute(false)] public System.Runtime.Serialization.ExtensionDataObject ExtensionData { get { return this.extensionDataField; } set { this.extensionDataField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] public System.DateTime DateAndTime { get { return this.DateAndTimeField; } set { if ((this.DateAndTimeField.Equals(value)!= true)) { this.DateAndTimeField = value; this.RaisePropertyChanged("DateAndTime"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string DocDate { get { return this.DocDateField; } set { if ((object.ReferenceEquals(this.DocDateField, value)!= true)) { this.DocDateField = value; this.RaisePropertyChanged("DocDate"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string DocNumber { get { return this.DocNumberField; } set { if ((object.ReferenceEquals(this.DocNumberField, value)!= true)) { this.DocNumberField = value; this.RaisePropertyChanged("DocNumber"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string Logo { get { return this.LogoField; } set { if ((object.ReferenceEquals(this.LogoField, value)!= true)) { this.LogoField = value; this.RaisePropertyChanged("Logo"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public long ReestrObjectId { get { return this.ReestrObjectIdField; } set { if ((this.ReestrObjectIdField.Equals(value)!= true)) { this.ReestrObjectIdField = value; this.RaisePropertyChanged("ReestrObjectId"); } } } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if ((propertyChanged!= null)) { propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="TransportDocumentSticker", Namespace="http://schemas.datacontract.org/2004/07/Emex.Document")] [System.SerializableAttribute()] public partial class TransportDocumentSticker : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged { [System.NonSerializedAttribute()] private System.Runtime.Serialization.ExtensionDataObject extensionDataField; [System.Runtime.Serialization.OptionalFieldAttribute()] private System.DateTime DateAndTimeField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string LogoField; [System.Runtime.Serialization.OptionalFieldAttribute()] private long ReestrObjectIdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string ShipperCityField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string ShipperContactField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string ShipperNameField; [global::System.ComponentModel.BrowsableAttribute(false)] public System.Runtime.Serialization.ExtensionDataObject ExtensionData { get { return this.extensionDataField; } set { this.extensionDataField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] public System.DateTime DateAndTime { get { return this.DateAndTimeField; } set { if ((this.DateAndTimeField.Equals(value)!= true)) { this.DateAndTimeField = value; this.RaisePropertyChanged("DateAndTime"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string Logo { get { return this.LogoField; } set { if ((object.ReferenceEquals(this.LogoField, value)!= true)) { this.LogoField = value; this.RaisePropertyChanged("Logo"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public long ReestrObjectId { get { return this.ReestrObjectIdField; } set { if ((this.ReestrObjectIdField.Equals(value)!= true)) { this.ReestrObjectIdField = value; this.RaisePropertyChanged("ReestrObjectId"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string ShipperCity { get { return this.ShipperCityField; } set { if ((object.ReferenceEquals(this.ShipperCityField, value)!= true)) { this.ShipperCityField = value; this.RaisePropertyChanged("ShipperCity"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string ShipperContact { get { return this.ShipperContactField; } set { if ((object.ReferenceEquals(this.ShipperContactField, value)!= true)) { this.ShipperContactField = value; this.RaisePropertyChanged("ShipperContact"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string ShipperName { get { return this.ShipperNameField; } set { if ((object.ReferenceEquals(this.ShipperNameField, value)!= true)) { this.ShipperNameField = value; this.RaisePropertyChanged("ShipperName"); } } } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if ((propertyChanged!= null)) { propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="Decommission", Namespace="http://schemas.datacontract.org/2004/07/Emex.Document")] [System.SerializableAttribute()] public partial class Decommission : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged { [System.NonSerializedAttribute()] private System.Runtime.Serialization.ExtensionDataObject extensionDataField; [System.Runtime.Serialization.OptionalFieldAttribute()] private System.DateTime CreateDateField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string NameField; [System.Runtime.Serialization.OptionalFieldAttribute()] private int RecycledDocumentIdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string RecyclingTypeField; [System.Runtime.Serialization.OptionalFieldAttribute()] private decimal SummaWithoutNDSField; [global::System.ComponentModel.BrowsableAttribute(false)] public System.Runtime.Serialization.ExtensionDataObject ExtensionData { get { return this.extensionDataField; } set { this.extensionDataField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] public System.DateTime CreateDate { get { return this.CreateDateField; } set { if ((this.CreateDateField.Equals(value)!= true)) { this.CreateDateField = value; this.RaisePropertyChanged("CreateDate"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string Name { get { return this.NameField; } set { if ((object.ReferenceEquals(this.NameField, value)!= true)) { this.NameField = value; this.RaisePropertyChanged("Name"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public int RecycledDocumentId { get { return this.RecycledDocumentIdField; } set { if ((this.RecycledDocumentIdField.Equals(value)!= true)) { this.RecycledDocumentIdField = value; this.RaisePropertyChanged("RecycledDocumentId"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string RecyclingType { get { return this.RecyclingTypeField; } set { if ((object.ReferenceEquals(this.RecyclingTypeField, value)!= true)) { this.RecyclingTypeField = value; this.RaisePropertyChanged("RecyclingType"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public decimal SummaWithoutNDS { get { return this.SummaWithoutNDSField; } set { if ((this.SummaWithoutNDSField.Equals(value)!= true)) { this.SummaWithoutNDSField = value; this.RaisePropertyChanged("SummaWithoutNDS"); } } } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if ((propertyChanged!= null)) { propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="DecommissionDetail", Namespace="http://schemas.datacontract.org/2004/07/Emex.Document")] [System.SerializableAttribute()] public partial class DecommissionDetail : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged { [System.NonSerializedAttribute()] private System.Runtime.Serialization.ExtensionDataObject extensionDataField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string DetailNameField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string DetailNumField; [System.Runtime.Serialization.OptionalFieldAttribute()] private int DetailQuantityField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string MakeNameField; [System.Runtime.Serialization.OptionalFieldAttribute()] private long OrderDetailSubIdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private int PortionField; [System.Runtime.Serialization.OptionalFieldAttribute()] private int RecycledDetailIdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private int RecycledDocumentIdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private int RecyclingTypeField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool SendToUtilizationField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string SourceBarcodeField; [global::System.ComponentModel.BrowsableAttribute(false)] public System.Runtime.Serialization.ExtensionDataObject ExtensionData { get { return this.extensionDataField; } set { this.extensionDataField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] public string DetailName { get { return this.DetailNameField; } set { if ((object.ReferenceEquals(this.DetailNameField, value)!= true)) { this.DetailNameField = value; this.RaisePropertyChanged("DetailName"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string DetailNum { get { return this.DetailNumField; } set { if ((object.ReferenceEquals(this.DetailNumField, value)!= true)) { this.DetailNumField = value; this.RaisePropertyChanged("DetailNum"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public int DetailQuantity { get { return this.DetailQuantityField; } set { if ((this.DetailQuantityField.Equals(value)!= true)) { this.DetailQuantityField = value; this.RaisePropertyChanged("DetailQuantity"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string MakeName { get { return this.MakeNameField; } set { if ((object.ReferenceEquals(this.MakeNameField, value)!= true)) { this.MakeNameField = value; this.RaisePropertyChanged("MakeName"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public long OrderDetailSubId { get { return this.OrderDetailSubIdField; } set { if ((this.OrderDetailSubIdField.Equals(value)!= true)) { this.OrderDetailSubIdField = value; this.RaisePropertyChanged("OrderDetailSubId"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public int Portion { get { return this.PortionField; } set { if ((this.PortionField.Equals(value)!= true)) { this.PortionField = value; this.RaisePropertyChanged("Portion"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public int RecycledDetailId { get { return this.RecycledDetailIdField; } set { if ((this.RecycledDetailIdField.Equals(value)!= true)) { this.RecycledDetailIdField = value; this.RaisePropertyChanged("RecycledDetailId"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public int RecycledDocumentId { get { return this.RecycledDocumentIdField; } set { if ((this.RecycledDocumentIdField.Equals(value)!= true)) { this.RecycledDocumentIdField = value; this.RaisePropertyChanged("RecycledDocumentId"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public int RecyclingType { get { return this.RecyclingTypeField; } set { if ((this.RecyclingTypeField.Equals(value)!= true)) { this.RecyclingTypeField = value; this.RaisePropertyChanged("RecyclingType"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public bool SendToUtilization { get { return this.SendToUtilizationField; } set { if ((this.SendToUtilizationField.Equals(value)!= true)) { this.SendToUtilizationField = value; this.RaisePropertyChanged("SendToUtilization"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string SourceBarcode { get { return this.SourceBarcodeField; } set { if ((object.ReferenceEquals(this.SourceBarcodeField, value)!= true)) { this.SourceBarcodeField = value; this.RaisePropertyChanged("SourceBarcode"); } } } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if ((propertyChanged!= null)) { propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="AccountCard", Namespace="http://schemas.datacontract.org/2004/07/Emex.Document")] [System.SerializableAttribute()] public partial class AccountCard : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged { [System.NonSerializedAttribute()] private System.Runtime.Serialization.ExtensionDataObject extensionDataField; [System.Runtime.Serialization.OptionalFieldAttribute()] private System.DateTime AccountDateField; [System.Runtime.Serialization.OptionalFieldAttribute()] private long AccountIdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private int AccountNumberField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string BalanceNameField; [System.Runtime.Serialization.OptionalFieldAttribute()] private long CustomerIdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string CustomerLogoField; [System.Runtime.Serialization.OptionalFieldAttribute()] private int DocTypeField; [System.Runtime.Serialization.OptionalFieldAttribute()] private long IdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private int InvoiceNumberField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool IsArchiveField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool IsErrorField; [System.Runtime.Serialization.OptionalFieldAttribute()] private decimal TotalSumField; [System.Runtime.Serialization.OptionalFieldAttribute()] private int buhBalanceIdField; [global::System.ComponentModel.BrowsableAttribute(false)] public System.Runtime.Serialization.ExtensionDataObject ExtensionData { get { return this.extensionDataField; } set { this.extensionDataField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] public System.DateTime AccountDate { get { return this.AccountDateField; } set { if ((this.AccountDateField.Equals(value)!= true)) { this.AccountDateField = value; this.RaisePropertyChanged("AccountDate"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public long AccountId { get { return this.AccountIdField; } set { if ((this.AccountIdField.Equals(value)!= true)) { this.AccountIdField = value; this.RaisePropertyChanged("AccountId"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public int AccountNumber { get { return this.AccountNumberField; } set { if ((this.AccountNumberField.Equals(value)!= true)) { this.AccountNumberField = value; this.RaisePropertyChanged("AccountNumber"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string BalanceName { get { return this.BalanceNameField; } set { if ((object.ReferenceEquals(this.BalanceNameField, value)!= true)) { this.BalanceNameField = value; this.RaisePropertyChanged("BalanceName"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public long CustomerId { get { return this.CustomerIdField; } set { if ((this.CustomerIdField.Equals(value)!= true)) { this.CustomerIdField = value; this.RaisePropertyChanged("CustomerId"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string CustomerLogo { get { return this.CustomerLogoField; } set { if ((object.ReferenceEquals(this.CustomerLogoField, value)!= true)) { this.CustomerLogoField = value; this.RaisePropertyChanged("CustomerLogo"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public int DocType { get { return this.DocTypeField; } set { if ((this.DocTypeField.Equals(value)!= true)) { this.DocTypeField = value; this.RaisePropertyChanged("DocType"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public long Id { get { return this.IdField; } set { if ((this.IdField.Equals(value)!= true)) { this.IdField = value; this.RaisePropertyChanged("Id"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public int InvoiceNumber { get { return this.InvoiceNumberField; } set { if ((this.InvoiceNumberField.Equals(value)!= true)) { this.InvoiceNumberField = value; this.RaisePropertyChanged("InvoiceNumber"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public bool IsArchive { get { return this.IsArchiveField; } set { if ((this.IsArchiveField.Equals(value)!= true)) { this.IsArchiveField = value; this.RaisePropertyChanged("IsArchive"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public bool IsError { get { return this.IsErrorField; } set { if ((this.IsErrorField.Equals(value)!= true)) { this.IsErrorField = value; this.RaisePropertyChanged("IsError"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public decimal TotalSum { get { return this.TotalSumField; } set { if ((this.TotalSumField.Equals(value)!= true)) { this.TotalSumField = value; this.RaisePropertyChanged("TotalSum"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public int buhBalanceId { get { return this.buhBalanceIdField; } set { if ((this.buhBalanceIdField.Equals(value)!= true)) { this.buhBalanceIdField = value; this.RaisePropertyChanged("buhBalanceId"); } } } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if ((propertyChanged!= null)) { propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="AccountCard2", Namespace="http://schemas.datacontract.org/2004/07/Emex.Document")] [System.SerializableAttribute()] [System.Runtime.Serialization.KnownTypeAttribute(typeof(EmExServiceClient.ContragentService.AccountCard3))] public partial class AccountCard2 : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged { [System.NonSerializedAttribute()] private System.Runtime.Serialization.ExtensionDataObject extensionDataField; [System.Runtime.Serialization.OptionalFieldAttribute()] private System.DateTime AccountDateField; [System.Runtime.Serialization.OptionalFieldAttribute()] private long AccountIdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private int AccountNumberField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string BalanceNameField; [System.Runtime.Serialization.OptionalFieldAttribute()] private long CustomerIdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string CustomerLogoField; [System.Runtime.Serialization.OptionalFieldAttribute()] private byte DocTypeField; [System.Runtime.Serialization.OptionalFieldAttribute()] private long IdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private int InvoiceNumberField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool IsArchiveField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool IsErrorField; [System.Runtime.Serialization.OptionalFieldAttribute()] private decimal TotalSumField; [System.Runtime.Serialization.OptionalFieldAttribute()] private int buhBalanceIdField; [global::System.ComponentModel.BrowsableAttribute(false)] public System.Runtime.Serialization.ExtensionDataObject ExtensionData { get { return this.extensionDataField; } set { this.extensionDataField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] public System.DateTime AccountDate { get { return this.AccountDateField; } set { if ((this.AccountDateField.Equals(value)!= true)) { this.AccountDateField = value; this.RaisePropertyChanged("AccountDate"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public long AccountId { get { return this.AccountIdField; } set { if ((this.AccountIdField.Equals(value)!= true)) { this.AccountIdField = value; this.RaisePropertyChanged("AccountId"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public int AccountNumber { get { return this.AccountNumberField; } set { if ((this.AccountNumberField.Equals(value)!= true)) { this.AccountNumberField = value; this.RaisePropertyChanged("AccountNumber"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string BalanceName { get { return this.BalanceNameField; } set { if ((object.ReferenceEquals(this.BalanceNameField, value)!= true)) { this.BalanceNameField = value; this.RaisePropertyChanged("BalanceName"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public long CustomerId { get { return this.CustomerIdField; } set { if ((this.CustomerIdField.Equals(value)!= true)) { this.CustomerIdField = value; this.RaisePropertyChanged("CustomerId"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string CustomerLogo { get { return this.CustomerLogoField; } set { if ((object.ReferenceEquals(this.CustomerLogoField, value)!= true)) { this.CustomerLogoField = value; this.RaisePropertyChanged("CustomerLogo"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public byte DocType { get { return this.DocTypeField; } set { if ((this.DocTypeField.Equals(value)!= true)) { this.DocTypeField = value; this.RaisePropertyChanged("DocType"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public long Id { get { return this.IdField; } set { if ((this.IdField.Equals(value)!= true)) { this.IdField = value; this.RaisePropertyChanged("Id"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public int InvoiceNumber { get { return this.InvoiceNumberField; } set { if ((this.InvoiceNumberField.Equals(value)!= true)) { this.InvoiceNumberField = value; this.RaisePropertyChanged("InvoiceNumber"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public bool IsArchive { get { return this.IsArchiveField; } set { if ((this.IsArchiveField.Equals(value)!= true)) { this.IsArchiveField = value; this.RaisePropertyChanged("IsArchive"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public bool IsError { get { return this.IsErrorField; } set { if ((this.IsErrorField.Equals(value)!= true)) { this.IsErrorField = value; this.RaisePropertyChanged("IsError"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public decimal TotalSum { get { return this.TotalSumField; } set { if ((this.TotalSumField.Equals(value)!= true)) { this.TotalSumField = value; this.RaisePropertyChanged("TotalSum"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public int buhBalanceId { get { return this.buhBalanceIdField; } set { if ((this.buhBalanceIdField.Equals(value)!= true)) { this.buhBalanceIdField = value; this.RaisePropertyChanged("buhBalanceId"); } } } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if ((propertyChanged!= null)) { propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="AccountCard3", Namespace="http://schemas.datacontract.org/2004/07/Emex.Document")] [System.SerializableAttribute()] public partial class AccountCard3 : EmExServiceClient.ContragentService.AccountCard2 { [System.Runtime.Serialization.OptionalFieldAttribute()] private string DocumentLinkField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string DocumentNumberField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string InvoiceNumberStringField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string StatusDocumentField; [System.Runtime.Serialization.OptionalFieldAttribute()] private int StatusIdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string TypeDocumentField; [System.Runtime.Serialization.DataMemberAttribute()] public string DocumentLink { get { return this.DocumentLinkField; } set { if ((object.ReferenceEquals(this.DocumentLinkField, value)!= true)) { this.DocumentLinkField = value; this.RaisePropertyChanged("DocumentLink"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string DocumentNumber { get { return this.DocumentNumberField; } set { if ((object.ReferenceEquals(this.DocumentNumberField, value)!= true)) { this.DocumentNumberField = value; this.RaisePropertyChanged("DocumentNumber"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string InvoiceNumberString { get { return this.InvoiceNumberStringField; } set { if ((object.ReferenceEquals(this.InvoiceNumberStringField, value)!= true)) { this.InvoiceNumberStringField = value; this.RaisePropertyChanged("InvoiceNumberString"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string StatusDocument { get { return this.StatusDocumentField; } set { if ((object.ReferenceEquals(this.StatusDocumentField, value)!= true)) { this.StatusDocumentField = value; this.RaisePropertyChanged("StatusDocument"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public int StatusId { get { return this.StatusIdField; } set { if ((this.StatusIdField.Equals(value)!= true)) { this.StatusIdField = value; this.RaisePropertyChanged("StatusId"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string TypeDocument { get { return this.TypeDocumentField; } set { if ((object.ReferenceEquals(this.TypeDocumentField, value)!= true)) { this.TypeDocumentField = value; this.RaisePropertyChanged("TypeDocument"); } } } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="DiadocDocumentStatus", Namespace="http://schemas.datacontract.org/2004/07/Emex.Document")] [System.SerializableAttribute()] public partial class DiadocDocumentStatus : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged { [System.NonSerializedAttribute()] private System.Runtime.Serialization.ExtensionDataObject extensionDataField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string StatusDocumentField; [System.Runtime.Serialization.OptionalFieldAttribute()] private int StatusIdField; [global::System.ComponentModel.BrowsableAttribute(false)] public System.Runtime.Serialization.ExtensionDataObject ExtensionData { get { return this.extensionDataField; } set { this.extensionDataField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] public string StatusDocument { get { return this.StatusDocumentField; } set { if ((object.ReferenceEquals(this.StatusDocumentField, value)!= true)) { this.StatusDocumentField = value; this.RaisePropertyChanged("StatusDocument"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public int StatusId { get { return this.StatusIdField; } set { if ((this.StatusIdField.Equals(value)!= true)) { this.StatusIdField = value; this.RaisePropertyChanged("StatusId"); } } } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if ((propertyChanged!= null)) { propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="DocumentReturnCard", Namespace="http://schemas.datacontract.org/2004/07/Emex.Document")] [System.SerializableAttribute()] public partial class DocumentReturnCard : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged { [System.NonSerializedAttribute()] private System.Runtime.Serialization.ExtensionDataObject extensionDataField; [System.Runtime.Serialization.OptionalFieldAttribute()] private System.Nullable<System.DateTime> AccountDateField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string AccountNumberField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string CustomerLogoField; [System.Runtime.Serialization.OptionalFieldAttribute()] private System.DateTime DefectPreDateField; [System.Runtime.Serialization.OptionalFieldAttribute()] private System.Nullable<long> DefectPreIdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string DefectPreNumberField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string ListOfClaimHeadersField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string ListOfUkdHeadersField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string ListOfСorrectionInvoiceIdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private System.Nullable<System.DateTime> Torg12DateField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string Torg12NumberField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string Torg2DateField; [System.Runtime.Serialization.OptionalFieldAttribute()] private System.Nullable<long> Torg2IdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string Torg2NumberField; [System.Runtime.Serialization.OptionalFieldAttribute()] private decimal TotalSumField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string VVDocNumberField; [System.Runtime.Serialization.OptionalFieldAttribute()] private System.Nullable<decimal> VVFullPriceField; [global::System.ComponentModel.BrowsableAttribute(false)] public System.Runtime.Serialization.ExtensionDataObject ExtensionData { get { return this.extensionDataField; } set { this.extensionDataField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] public System.Nullable<System.DateTime> AccountDate { get { return this.AccountDateField; } set { if ((this.AccountDateField.Equals(value)!= true)) { this.AccountDateField = value; this.RaisePropertyChanged("AccountDate"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string AccountNumber { get { return this.AccountNumberField; } set { if ((object.ReferenceEquals(this.AccountNumberField, value)!= true)) { this.AccountNumberField = value; this.RaisePropertyChanged("AccountNumber"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string CustomerLogo { get { return this.CustomerLogoField; } set { if ((object.ReferenceEquals(this.CustomerLogoField, value)!= true)) { this.CustomerLogoField = value; this.RaisePropertyChanged("CustomerLogo"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public System.DateTime DefectPreDate { get { return this.DefectPreDateField; } set { if ((this.DefectPreDateField.Equals(value)!= true)) { this.DefectPreDateField = value; this.RaisePropertyChanged("DefectPreDate"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public System.Nullable<long> DefectPreId { get { return this.DefectPreIdField; } set { if ((this.DefectPreIdField.Equals(value)!= true)) { this.DefectPreIdField = value; this.RaisePropertyChanged("DefectPreId"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string DefectPreNumber { get { return this.DefectPreNumberField; } set { if ((object.ReferenceEquals(this.DefectPreNumberField, value)!= true)) { this.DefectPreNumberField = value; this.RaisePropertyChanged("DefectPreNumber"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string ListOfClaimHeaders { get { return this.ListOfClaimHeadersField; } set { if ((object.ReferenceEquals(this.ListOfClaimHeadersField, value)!= true)) { this.ListOfClaimHeadersField = value; this.RaisePropertyChanged("ListOfClaimHeaders"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string ListOfUkdHeaders { get { return this.ListOfUkdHeadersField; } set { if ((object.ReferenceEquals(this.ListOfUkdHeadersField, value)!= true)) { this.ListOfUkdHeadersField = value; this.RaisePropertyChanged("ListOfUkdHeaders"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string ListOfСorrectionInvoiceId { get { return this.ListOfСorrectionInvoiceIdField; } set { if ((object.ReferenceEquals(this.ListOfСorrectionInvoiceIdField, value)!= true)) { this.ListOfСorrectionInvoiceIdField = value; this.RaisePropertyChanged("ListOfСorrectionInvoiceId"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public System.Nullable<System.DateTime> Torg12Date { get { return this.Torg12DateField; } set { if ((this.Torg12DateField.Equals(value)!= true)) { this.Torg12DateField = value; this.RaisePropertyChanged("Torg12Date"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string Torg12Number { get { return this.Torg12NumberField; } set { if ((object.ReferenceEquals(this.Torg12NumberField, value)!= true)) { this.Torg12NumberField = value; this.RaisePropertyChanged("Torg12Number"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string Torg2Date { get { return this.Torg2DateField; } set { if ((object.ReferenceEquals(this.Torg2DateField, value)!= true)) { this.Torg2DateField = value; this.RaisePropertyChanged("Torg2Date"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public System.Nullable<long> Torg2Id { get { return this.Torg2IdField; } set { if ((this.Torg2IdField.Equals(value)!= true)) { this.Torg2IdField = value; this.RaisePropertyChanged("Torg2Id"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string Torg2Number { get { return this.Torg2NumberField; } set { if ((object.ReferenceEquals(this.Torg2NumberField, value)!= true)) { this.Torg2NumberField = value; this.RaisePropertyChanged("Torg2Number"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public decimal TotalSum { get { return this.TotalSumField; } set { if ((this.TotalSumField.Equals(value)!= true)) { this.TotalSumField = value; this.RaisePropertyChanged("TotalSum"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string VVDocNumber { get { return this.VVDocNumberField; } set { if ((object.ReferenceEquals(this.VVDocNumberField, value)!= true)) { this.VVDocNumberField = value; this.RaisePropertyChanged("VVDocNumber"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public System.Nullable<decimal> VVFullPrice { get { return this.VVFullPriceField; } set { if ((this.VVFullPriceField.Equals(value)!= true)) { this.VVFullPriceField = value; this.RaisePropertyChanged("VVFullPrice"); } } } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if ((propertyChanged!= null)) { propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } } [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.FlagsAttribute()] [System.Runtime.Serialization.DataContractAttribute(Name="DocumentOptions", Namespace="http://schemas.datacontract.org/2004/07/Emex.Document")] public enum DocumentOptions : int { [System.Runtime.Serialization.EnumMemberAttribute()] Print = 1, [System.Runtime.Serialization.EnumMemberAttribute()] Send = 2, [System.Runtime.Serialization.EnumMemberAttribute()] ReturnExcel = 4, [System.Runtime.Serialization.EnumMemberAttribute()] ReturnImage = 8, [System.Runtime.Serialization.EnumMemberAttribute()] ReturnPDF = 16, [System.Runtime.Serialization.EnumMemberAttribute()] ReturnCSV = 32, [System.Runtime.Serialization.EnumMemberAttribute()] Save = 48, [System.Runtime.Serialization.EnumMemberAttribute()] ReturnDoc = 64, } [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="DocumentReasonType", Namespace="http://schemas.datacontract.org/2004/07/Emex.Document")] public enum DocumentReasonType : int { [System.Runtime.Serialization.EnumMemberAttribute()] Unknown = 0, [System.Runtime.Serialization.EnumMemberAttribute()] Account = 1, [System.Runtime.Serialization.EnumMemberAttribute()] InvoiceClose = 2, [System.Runtime.Serialization.EnumMemberAttribute()] ClientReturn = 3, [System.Runtime.Serialization.EnumMemberAttribute()] CMRShipping = 4, [System.Runtime.Serialization.EnumMemberAttribute()] NoName = 5, [System.Runtime.Serialization.EnumMemberAttribute()] WMSCloseCollect = 6, [System.Runtime.Serialization.EnumMemberAttribute()] WMSCloseShipping = 7, [System.Runtime.Serialization.EnumMemberAttribute()] InvoicesSFProcessingPayment = 8, [System.Runtime.Serialization.EnumMemberAttribute()] LocalStorageAccount = 9, [System.Runtime.Serialization.EnumMemberAttribute()] SupplierPenalty = 10, [System.Runtime.Serialization.EnumMemberAttribute()] SupplierReturn = 11, [System.Runtime.Serialization.EnumMemberAttribute()] ReturnFromCustomer = 14, [System.Runtime.Serialization.EnumMemberAttribute()] BarcodeProcessingPayment = 15, [System.Runtime.Serialization.EnumMemberAttribute()] InvoicesSFOnlineClientPayment = 20, [System.Runtime.Serialization.EnumMemberAttribute()] JointProcessingPayment = 24, [System.Runtime.Serialization.EnumMemberAttribute()] OF8WebService = 27, [System.Runtime.Serialization.EnumMemberAttribute()] ProtectionFromReturnPayment = 29, [System.Runtime.Serialization.EnumMemberAttribute()] SupplierReturnSale = 32, } [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="DocumentType", Namespace="http://schemas.datacontract.org/2004/07/Emex.Document")] public enum DocumentType : int { [System.Runtime.Serialization.EnumMemberAttribute()] Torg12 = 1, [System.Runtime.Serialization.EnumMemberAttribute()] Invoice = 2, [System.Runtime.Serialization.EnumMemberAttribute()] InvoiceTypeOne = 3, [System.Runtime.Serialization.EnumMemberAttribute()] CustomerBarcodeFile = 4, [System.Runtime.Serialization.EnumMemberAttribute()] PackSheet = 5, [System.Runtime.Serialization.EnumMemberAttribute()] Statement = 6, [System.Runtime.Serialization.EnumMemberAttribute()] M11DemandBill = 7, [System.Runtime.Serialization.EnumMemberAttribute()] Torg12WithGrouping = 8, [System.Runtime.Serialization.EnumMemberAttribute()] TTN = 9, [System.Runtime.Serialization.EnumMemberAttribute()] TORG2 = 10, [System.Runtime.Serialization.EnumMemberAttribute()] ActSurplusTORG2 = 11, [System.Runtime.Serialization.EnumMemberAttribute()] M15 = 12, [System.Runtime.Serialization.EnumMemberAttribute()] InfoLost = 13, [System.Runtime.Serialization.EnumMemberAttribute()] CMR = 14, [System.Runtime.Serialization.EnumMemberAttribute()] InsuranceRequest = 15, [System.Runtime.Serialization.EnumMemberAttribute()] RegionPackSheet = 16, [System.Runtime.Serialization.EnumMemberAttribute()] BuhAccountPlan = 17, [System.Runtime.Serialization.EnumMemberAttribute()] Torg12Return = 30, [System.Runtime.Serialization.EnumMemberAttribute()] Upd = 31, [System.Runtime.Serialization.EnumMemberAttribute()] UpdReturn = 34, [System.Runtime.Serialization.EnumMemberAttribute()] Ukd = 38, [System.Runtime.Serialization.EnumMemberAttribute()] Counterfeit = 39, [System.Runtime.Serialization.EnumMemberAttribute()] Ksf = 42, [System.Runtime.Serialization.EnumMemberAttribute()] Util_2_1 = 49, [System.Runtime.Serialization.EnumMemberAttribute()] Util_2_2 = 50, [System.Runtime.Serialization.EnumMemberAttribute()] Util_2_3 = 51, [System.Runtime.Serialization.EnumMemberAttribute()] Util_2_4 = 52, [System.Runtime.Serialization.EnumMemberAttribute()] Util_2_5 = 53, [System.Runtime.Serialization.EnumMemberAttribute()] Util_2_6 = 54, [System.Runtime.Serialization.EnumMemberAttribute()] Util_2_7 = 55, [System.Runtime.Serialization.EnumMemberAttribute()] Util_2_8 = 56, [System.Runtime.Serialization.EnumMemberAttribute()] Util_2_9 = 57, [System.Runtime.Serialization.EnumMemberAttribute()] Util_2_10 = 58, [System.Runtime.Serialization.EnumMemberAttribute()] InventoryList = 59, [System.Runtime.Serialization.EnumMemberAttribute()] InventoryOrder = 60, [System.Runtime.Serialization.EnumMemberAttribute()] InventoryRegister = 61, [System.Runtime.Serialization.EnumMemberAttribute()] InventoryCollationStatement = 62, [System.Runtime.Serialization.EnumMemberAttribute()] InventoryResultDirective = 63, [System.Runtime.Serialization.EnumMemberAttribute()] DueDiligence = 64, [System.Runtime.Serialization.EnumMemberAttribute()] SupplierReturnsRegister = 65, } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="ActRecycling", Namespace="http://schemas.datacontract.org/2004/07/Emex.Document")] [System.SerializableAttribute()] public partial class ActRecycling : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged { [System.NonSerializedAttribute()] private System.Runtime.Serialization.ExtensionDataObject extensionDataField; [System.Runtime.Serialization.OptionalFieldAttribute()] private System.DateTime ActDateField; [System.Runtime.Serialization.OptionalFieldAttribute()] private int ActNumberField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string BarcodeDataField; [System.Runtime.Serialization.OptionalFieldAttribute()] private byte[] BarcodeImageField; [System.Runtime.Serialization.OptionalFieldAttribute()] private decimal SummaWithoutTaxField; [global::System.ComponentModel.BrowsableAttribute(false)] public System.Runtime.Serialization.ExtensionDataObject ExtensionData { get { return this.extensionDataField; } set { this.extensionDataField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] public System.DateTime ActDate { get { return this.ActDateField; } set { if ((this.ActDateField.Equals(value)!= true)) { this.ActDateField = value; this.RaisePropertyChanged("ActDate"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public int ActNumber { get { return this.ActNumberField; } set { if ((this.ActNumberField.Equals(value)!= true)) { this.ActNumberField = value; this.RaisePropertyChanged("ActNumber"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string BarcodeData { get { return this.BarcodeDataField; } set { if ((object.ReferenceEquals(this.BarcodeDataField, value)!= true)) { this.BarcodeDataField = value; this.RaisePropertyChanged("BarcodeData"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public byte[] BarcodeImage { get { return this.BarcodeImageField; } set { if ((object.ReferenceEquals(this.BarcodeImageField, value)!= true)) { this.BarcodeImageField = value; this.RaisePropertyChanged("BarcodeImage"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public decimal SummaWithoutTax { get { return this.SummaWithoutTaxField; } set { if ((this.SummaWithoutTaxField.Equals(value)!= true)) { this.SummaWithoutTaxField = value; this.RaisePropertyChanged("SummaWithoutTax"); } } } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if ((propertyChanged!= null)) { propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } } [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.FlagsAttribute()] [System.Runtime.Serialization.DataContractAttribute(Name="ContactTypes", Namespace="http://schemas.datacontract.org/2004/07/Emex.Contragent")] public enum ContactTypes : int { [System.Runtime.Serialization.EnumMemberAttribute()] Unknown = 0, [System.Runtime.Serialization.EnumMemberAttribute()] CEO = 1, [System.Runtime.Serialization.EnumMemberAttribute()] Director = 2, [System.Runtime.Serialization.EnumMemberAttribute()] ChiefAccountant = 4, [System.Runtime.Serialization.EnumMemberAttribute()] Accountant = 8, [System.Runtime.Serialization.EnumMemberAttribute()] Manager = 16, [System.Runtime.Serialization.EnumMemberAttribute()] ReturnDocuments = 18, } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="SupplierBase", Namespace="http://schemas.datacontract.org/2004/07/Emex.Contragent")] [System.SerializableAttribute()] public partial class SupplierBase : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged { [System.NonSerializedAttribute()] private System.Runtime.Serialization.ExtensionDataObject extensionDataField; private string LogoField; private long SupplierIdField; [global::System.ComponentModel.BrowsableAttribute(false)] public System.Runtime.Serialization.ExtensionDataObject ExtensionData { get { return this.extensionDataField; } set { this.extensionDataField = value; } } [System.Runtime.Serialization.DataMemberAttribute(IsRequired=true)] public string Logo { get { return this.LogoField; } set { if ((object.ReferenceEquals(this.LogoField, value)!= true)) { this.LogoField = value; this.RaisePropertyChanged("Logo"); } } } [System.Runtime.Serialization.DataMemberAttribute(IsRequired=true)] public long SupplierId { get { return this.SupplierIdField; } set { if ((this.SupplierIdField.Equals(value)!= true)) { this.SupplierIdField = value; this.RaisePropertyChanged("SupplierId"); } } } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if ((propertyChanged!= null)) { propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="CustomerDiscountManual", Namespace="http://schemas.datacontract.org/2004/07/Emex.Contragent")] [System.SerializableAttribute()] public partial class CustomerDiscountManual : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged { [System.NonSerializedAttribute()] private System.Runtime.Serialization.ExtensionDataObject extensionDataField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string CommentField; [System.Runtime.Serialization.OptionalFieldAttribute()] private decimal DiscountsField; [System.Runtime.Serialization.OptionalFieldAttribute()] private System.DateTime ExpireDateField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string UserLogoField; [global::System.ComponentModel.BrowsableAttribute(false)] public System.Runtime.Serialization.ExtensionDataObject ExtensionData { get { return this.extensionDataField; } set { this.extensionDataField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] public string Comment { get { return this.CommentField; } set { if ((object.ReferenceEquals(this.CommentField, value)!= true)) { this.CommentField = value; this.RaisePropertyChanged("Comment"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public decimal Discounts { get { return this.DiscountsField; } set { if ((this.DiscountsField.Equals(value)!= true)) { this.DiscountsField = value; this.RaisePropertyChanged("Discounts"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public System.DateTime ExpireDate { get { return this.ExpireDateField; } set { if ((this.ExpireDateField.Equals(value)!= true)) { this.ExpireDateField = value; this.RaisePropertyChanged("ExpireDate"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string UserLogo { get { return this.UserLogoField; } set { if ((object.ReferenceEquals(this.UserLogoField, value)!= true)) { this.UserLogoField = value; this.RaisePropertyChanged("UserLogo"); } } } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if ((propertyChanged!= null)) { propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } } [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="PartnerType", Namespace="http://schemas.datacontract.org/2004/07/Emex.Contragent")] public enum PartnerType : int { [System.Runtime.Serialization.EnumMemberAttribute()] None = 0, [System.Runtime.Serialization.EnumMemberAttribute()] Partner = 1, [System.Runtime.Serialization.EnumMemberAttribute()] Partner3Rank = 2, [System.Runtime.Serialization.EnumMemberAttribute()] Companion = 3, } [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="WorkType", Namespace="http://schemas.datacontract.org/2004/07/Emex.Contragent")] public enum WorkType : int { [System.Runtime.Serialization.EnumMemberAttribute()] AdvancePayment = 0, [System.Runtime.Serialization.EnumMemberAttribute()] WithoutAdvancePayment = 1, } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="CustomerSearchResultItem", Namespace="http://schemas.datacontract.org/2004/07/Emex.Contragent")] [System.SerializableAttribute()] public partial class CustomerSearchResultItem : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged { [System.NonSerializedAttribute()] private System.Runtime.Serialization.ExtensionDataObject extensionDataField; [System.Runtime.Serialization.OptionalFieldAttribute()] private long ContragentIdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private long IdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool IsClosedField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string NameField; [System.Runtime.Serialization.OptionalFieldAttribute()] private EmExServiceClient.ContragentService.CustomerSearchResultItemType TypeField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string WholesalerLogoField; [global::System.ComponentModel.BrowsableAttribute(false)] public System.Runtime.Serialization.ExtensionDataObject ExtensionData { get { return this.extensionDataField; } set { this.extensionDataField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] public long ContragentId { get { return this.ContragentIdField; } set { if ((this.ContragentIdField.Equals(value)!= true)) { this.ContragentIdField = value; this.RaisePropertyChanged("ContragentId"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public long Id { get { return this.IdField; } set { if ((this.IdField.Equals(value)!= true)) { this.IdField = value; this.RaisePropertyChanged("Id"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public bool IsClosed { get { return this.IsClosedField; } set { if ((this.IsClosedField.Equals(value)!= true)) { this.IsClosedField = value; this.RaisePropertyChanged("IsClosed"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string Name { get { return this.NameField; } set { if ((object.ReferenceEquals(this.NameField, value)!= true)) { this.NameField = value; this.RaisePropertyChanged("Name"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public EmExServiceClient.ContragentService.CustomerSearchResultItemType Type { get { return this.TypeField; } set { if ((this.TypeField.Equals(value)!= true)) { this.TypeField = value; this.RaisePropertyChanged("Type"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string WholesalerLogo { get { return this.WholesalerLogoField; } set { if ((object.ReferenceEquals(this.WholesalerLogoField, value)!= true)) { this.WholesalerLogoField = value; this.RaisePropertyChanged("WholesalerLogo"); } } } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if ((propertyChanged!= null)) { propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } } [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="CustomerSearchResultItemType", Namespace="http://schemas.datacontract.org/2004/07/Emex.Contragent")] public enum CustomerSearchResultItemType : int { [System.Runtime.Serialization.EnumMemberAttribute()] Wholesaler = 0, [System.Runtime.Serialization.EnumMemberAttribute()] Consumer = 1, [System.Runtime.Serialization.EnumMemberAttribute()] Manager = 2, } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="CustomerIdentity", Namespace="http://schemas.datacontract.org/2004/07/Emex.Contragent")] [System.SerializableAttribute()] public partial class CustomerIdentity : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged { [System.NonSerializedAttribute()] private System.Runtime.Serialization.ExtensionDataObject extensionDataField; [System.Runtime.Serialization.OptionalFieldAttribute()] private long CustomerIdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string INNField; [System.Runtime.Serialization.OptionalFieldAttribute()] private long IdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string LogoField; [global::System.ComponentModel.BrowsableAttribute(false)] public System.Runtime.Serialization.ExtensionDataObject ExtensionData { get { return this.extensionDataField; } set { this.extensionDataField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] public long CustomerId { get { return this.CustomerIdField; } set { if ((this.CustomerIdField.Equals(value)!= true)) { this.CustomerIdField = value; this.RaisePropertyChanged("CustomerId"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string INN { get { return this.INNField; } set { if ((object.ReferenceEquals(this.INNField, value)!= true)) { this.INNField = value; this.RaisePropertyChanged("INN"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public long Id { get { return this.IdField; } set { if ((this.IdField.Equals(value)!= true)) { this.IdField = value; this.RaisePropertyChanged("Id"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string Logo { get { return this.LogoField; } set { if ((object.ReferenceEquals(this.LogoField, value)!= true)) { this.LogoField = value; this.RaisePropertyChanged("Logo"); } } } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if ((propertyChanged!= null)) { propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="ContragentDocumentSetting", Namespace="http://schemas.datacontract.org/2004/07/Emex.Contragent")] [System.SerializableAttribute()] public partial class ContragentDocumentSetting : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged { [System.NonSerializedAttribute()] private System.Runtime.Serialization.ExtensionDataObject extensionDataField; [System.Runtime.Serialization.OptionalFieldAttribute()] private byte CopiesField; [System.Runtime.Serialization.OptionalFieldAttribute()] private EmExServiceClient.ContragentService.GatheringSchemeType GatheringSchemesField; [System.Runtime.Serialization.OptionalFieldAttribute()] private EmExServiceClient.ContragentService.DocumentOptions OptionsField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string PrinterNameField; [System.Runtime.Serialization.OptionalFieldAttribute()] private EmExServiceClient.ContragentService.DocumentReasonType ReasonTypeField; [System.Runtime.Serialization.OptionalFieldAttribute()] private EmExServiceClient.ContragentService.DocumentType TypeField; [System.Runtime.Serialization.OptionalFieldAttribute()] private int VersionIdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private byte VersionNumberField; [global::System.ComponentModel.BrowsableAttribute(false)] public System.Runtime.Serialization.ExtensionDataObject ExtensionData { get { return this.extensionDataField; } set { this.extensionDataField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] public byte Copies { get { return this.CopiesField; } set { if ((this.CopiesField.Equals(value)!= true)) { this.CopiesField = value; this.RaisePropertyChanged("Copies"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public EmExServiceClient.ContragentService.GatheringSchemeType GatheringSchemes { get { return this.GatheringSchemesField; } set { if ((this.GatheringSchemesField.Equals(value)!= true)) { this.GatheringSchemesField = value; this.RaisePropertyChanged("GatheringSchemes"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public EmExServiceClient.ContragentService.DocumentOptions Options { get { return this.OptionsField; } set { if ((this.OptionsField.Equals(value)!= true)) { this.OptionsField = value; this.RaisePropertyChanged("Options"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string PrinterName { get { return this.PrinterNameField; } set { if ((object.ReferenceEquals(this.PrinterNameField, value)!= true)) { this.PrinterNameField = value; this.RaisePropertyChanged("PrinterName"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public EmExServiceClient.ContragentService.DocumentReasonType ReasonType { get { return this.ReasonTypeField; } set { if ((this.ReasonTypeField.Equals(value)!= true)) { this.ReasonTypeField = value; this.RaisePropertyChanged("ReasonType"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public EmExServiceClient.ContragentService.DocumentType Type { get { return this.TypeField; } set { if ((this.TypeField.Equals(value)!= true)) { this.TypeField = value; this.RaisePropertyChanged("Type"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public int VersionId { get { return this.VersionIdField; } set { if ((this.VersionIdField.Equals(value)!= true)) { this.VersionIdField = value; this.RaisePropertyChanged("VersionId"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public byte VersionNumber { get { return this.VersionNumberField; } set { if ((this.VersionNumberField.Equals(value)!= true)) { this.VersionNumberField = value; this.RaisePropertyChanged("VersionNumber"); } } } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if ((propertyChanged!= null)) { propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="CustomerDelivery", Namespace="http://schemas.datacontract.org/2004/07/Emex.Contragent")] [System.SerializableAttribute()] public partial class CustomerDelivery : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged { [System.NonSerializedAttribute()] private System.Runtime.Serialization.ExtensionDataObject extensionDataField; [System.Runtime.Serialization.OptionalFieldAttribute()] private long AdditionalTransporterContragentIdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string AddressField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool BoxReturnReusingField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string CommentForAccountButtonField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string CommentForMobileRegionField; [System.Runtime.Serialization.OptionalFieldAttribute()] private long CustomerIdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string DescriptionField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string RecipientField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string RegionField; [System.Runtime.Serialization.OptionalFieldAttribute()] private System.Nullable<byte> TransportCompanyGateField; [global::System.ComponentModel.BrowsableAttribute(false)] public System.Runtime.Serialization.ExtensionDataObject ExtensionData { get { return this.extensionDataField; } set { this.extensionDataField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] public long AdditionalTransporterContragentId { get { return this.AdditionalTransporterContragentIdField; } set { if ((this.AdditionalTransporterContragentIdField.Equals(value)!= true)) { this.AdditionalTransporterContragentIdField = value; this.RaisePropertyChanged("AdditionalTransporterContragentId"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string Address { get { return this.AddressField; } set { if ((object.ReferenceEquals(this.AddressField, value)!= true)) { this.AddressField = value; this.RaisePropertyChanged("Address"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public bool BoxReturnReusing { get { return this.BoxReturnReusingField; } set { if ((this.BoxReturnReusingField.Equals(value)!= true)) { this.BoxReturnReusingField = value; this.RaisePropertyChanged("BoxReturnReusing"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string CommentForAccountButton { get { return this.CommentForAccountButtonField; } set { if ((object.ReferenceEquals(this.CommentForAccountButtonField, value)!= true)) { this.CommentForAccountButtonField = value; this.RaisePropertyChanged("CommentForAccountButton"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string CommentForMobileRegion { get { return this.CommentForMobileRegionField; } set { if ((object.ReferenceEquals(this.CommentForMobileRegionField, value)!= true)) { this.CommentForMobileRegionField = value; this.RaisePropertyChanged("CommentForMobileRegion"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public long CustomerId { get { return this.CustomerIdField; } set { if ((this.CustomerIdField.Equals(value)!= true)) { this.CustomerIdField = value; this.RaisePropertyChanged("CustomerId"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string Description { get { return this.DescriptionField; } set { if ((object.ReferenceEquals(this.DescriptionField, value)!= true)) { this.DescriptionField = value; this.RaisePropertyChanged("Description"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string Recipient { get { return this.RecipientField; } set { if ((object.ReferenceEquals(this.RecipientField, value)!= true)) { this.RecipientField = value; this.RaisePropertyChanged("Recipient"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string Region { get { return this.RegionField; } set { if ((object.ReferenceEquals(this.RegionField, value)!= true)) { this.RegionField = value; this.RaisePropertyChanged("Region"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public System.Nullable<byte> TransportCompanyGate { get { return this.TransportCompanyGateField; } set { if ((this.TransportCompanyGateField.Equals(value)!= true)) { this.TransportCompanyGateField = value; this.RaisePropertyChanged("TransportCompanyGate"); } } } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if ((propertyChanged!= null)) { propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="ContragentIdentity", Namespace="http://schemas.datacontract.org/2004/07/Emex.Contragent")] [System.SerializableAttribute()] public partial class ContragentIdentity : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged { [System.NonSerializedAttribute()] private System.Runtime.Serialization.ExtensionDataObject extensionDataField; [System.Runtime.Serialization.OptionalFieldAttribute()] private long IdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string NameField; [global::System.ComponentModel.BrowsableAttribute(false)] public System.Runtime.Serialization.ExtensionDataObject ExtensionData { get { return this.extensionDataField; } set { this.extensionDataField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] public long Id { get { return this.IdField; } set { if ((this.IdField.Equals(value)!= true)) { this.IdField = value; this.RaisePropertyChanged("Id"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string Name { get { return this.NameField; } set { if ((object.ReferenceEquals(this.NameField, value)!= true)) { this.NameField = value; this.RaisePropertyChanged("Name"); } } } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if ((propertyChanged!= null)) { propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="CustomerScheduleAttribute", Namespace="http://schemas.datacontract.org/2004/07/Emex.Contragent")] [System.SerializableAttribute()] public partial class CustomerScheduleAttribute : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged { [System.NonSerializedAttribute()] private System.Runtime.Serialization.ExtensionDataObject extensionDataField; [System.Runtime.Serialization.OptionalFieldAttribute()] private EmExServiceClient.ContragentService.CustomerScheduleAccountMode AccountModeField; [System.Runtime.Serialization.OptionalFieldAttribute()] private long CustomerIdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string DAY_1Field; [System.Runtime.Serialization.OptionalFieldAttribute()] private string DAY_2Field; [System.Runtime.Serialization.OptionalFieldAttribute()] private string DAY_3Field; [System.Runtime.Serialization.OptionalFieldAttribute()] private string DAY_4Field; [System.Runtime.Serialization.OptionalFieldAttribute()] private string DAY_5Field; [System.Runtime.Serialization.OptionalFieldAttribute()] private string DAY_6Field; [System.Runtime.Serialization.OptionalFieldAttribute()] private string DAY_7Field; [System.Runtime.Serialization.OptionalFieldAttribute()] private System.Nullable<byte> DaysField; [System.Runtime.Serialization.OptionalFieldAttribute()] private EmExServiceClient.ContragentService.DeliveryRegionType DeliveryRegionTypeAttributesField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool IsAlternativeField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool IsCustomerScheduleField; [System.Runtime.Serialization.OptionalFieldAttribute()] private decimal MinSumCostForAutoOutField; [System.Runtime.Serialization.OptionalFieldAttribute()] private long MinWeightForAutoOutField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool PrepareForAccountField; [System.Runtime.Serialization.OptionalFieldAttribute()] private long ScheduleIdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private EmExServiceClient.ContragentService.TransportCompany TransportCompanyField; [System.Runtime.Serialization.OptionalFieldAttribute()] private long TransportCompanyIdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private long TransportDaysField; [global::System.ComponentModel.BrowsableAttribute(false)] public System.Runtime.Serialization.ExtensionDataObject ExtensionData { get { return this.extensionDataField; } set { this.extensionDataField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] public EmExServiceClient.ContragentService.CustomerScheduleAccountMode AccountMode { get { return this.AccountModeField; } set { if ((this.AccountModeField.Equals(value)!= true)) { this.AccountModeField = value; this.RaisePropertyChanged("AccountMode"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public long CustomerId { get { return this.CustomerIdField; } set { if ((this.CustomerIdField.Equals(value)!= true)) { this.CustomerIdField = value; this.RaisePropertyChanged("CustomerId"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string DAY_1 { get { return this.DAY_1Field; } set { if ((object.ReferenceEquals(this.DAY_1Field, value)!= true)) { this.DAY_1Field = value; this.RaisePropertyChanged("DAY_1"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string DAY_2 { get { return this.DAY_2Field; } set { if ((object.ReferenceEquals(this.DAY_2Field, value)!= true)) { this.DAY_2Field = value; this.RaisePropertyChanged("DAY_2"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string DAY_3 { get { return this.DAY_3Field; } set { if ((object.ReferenceEquals(this.DAY_3Field, value)!= true)) { this.DAY_3Field = value; this.RaisePropertyChanged("DAY_3"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string DAY_4 { get { return this.DAY_4Field; } set { if ((object.ReferenceEquals(this.DAY_4Field, value)!= true)) { this.DAY_4Field = value; this.RaisePropertyChanged("DAY_4"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string DAY_5 { get { return this.DAY_5Field; } set { if ((object.ReferenceEquals(this.DAY_5Field, value)!= true)) { this.DAY_5Field = value; this.RaisePropertyChanged("DAY_5"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string DAY_6 { get { return this.DAY_6Field; } set { if ((object.ReferenceEquals(this.DAY_6Field, value)!= true)) { this.DAY_6Field = value; this.RaisePropertyChanged("DAY_6"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string DAY_7 { get { return this.DAY_7Field; } set { if ((object.ReferenceEquals(this.DAY_7Field, value)!= true)) { this.DAY_7Field = value; this.RaisePropertyChanged("DAY_7"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public System.Nullable<byte> Days { get { return this.DaysField; } set { if ((this.DaysField.Equals(value)!= true)) { this.DaysField = value; this.RaisePropertyChanged("Days"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public EmExServiceClient.ContragentService.DeliveryRegionType DeliveryRegionTypeAttributes { get { return this.DeliveryRegionTypeAttributesField; } set { if ((object.ReferenceEquals(this.DeliveryRegionTypeAttributesField, value)!= true)) { this.DeliveryRegionTypeAttributesField = value; this.RaisePropertyChanged("DeliveryRegionTypeAttributes"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public bool IsAlternative { get { return this.IsAlternativeField; } set { if ((this.IsAlternativeField.Equals(value)!= true)) { this.IsAlternativeField = value; this.RaisePropertyChanged("IsAlternative"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public bool IsCustomerSchedule { get { return this.IsCustomerScheduleField; } set { if ((this.IsCustomerScheduleField.Equals(value)!= true)) { this.IsCustomerScheduleField = value; this.RaisePropertyChanged("IsCustomerSchedule"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public decimal MinSumCostForAutoOut { get { return this.MinSumCostForAutoOutField; } set { if ((this.MinSumCostForAutoOutField.Equals(value)!= true)) { this.MinSumCostForAutoOutField = value; this.RaisePropertyChanged("MinSumCostForAutoOut"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public long MinWeightForAutoOut { get { return this.MinWeightForAutoOutField; } set { if ((this.MinWeightForAutoOutField.Equals(value)!= true)) { this.MinWeightForAutoOutField = value; this.RaisePropertyChanged("MinWeightForAutoOut"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public bool PrepareForAccount { get { return this.PrepareForAccountField; } set { if ((this.PrepareForAccountField.Equals(value)!= true)) { this.PrepareForAccountField = value; this.RaisePropertyChanged("PrepareForAccount"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public long ScheduleId { get { return this.ScheduleIdField; } set { if ((this.ScheduleIdField.Equals(value)!= true)) { this.ScheduleIdField = value; this.RaisePropertyChanged("ScheduleId"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public EmExServiceClient.ContragentService.TransportCompany TransportCompany { get { return this.TransportCompanyField; } set { if ((object.ReferenceEquals(this.TransportCompanyField, value)!= true)) { this.TransportCompanyField = value; this.RaisePropertyChanged("TransportCompany"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public long TransportCompanyId { get { return this.TransportCompanyIdField; } set { if ((this.TransportCompanyIdField.Equals(value)!= true)) { this.TransportCompanyIdField = value; this.RaisePropertyChanged("TransportCompanyId"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public long TransportDays { get { return this.TransportDaysField; } set { if ((this.TransportDaysField.Equals(value)!= true)) { this.TransportDaysField = value; this.RaisePropertyChanged("TransportDays"); } } } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if ((propertyChanged!= null)) { propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } } [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="CustomerScheduleAccountMode", Namespace="http://schemas.datacontract.org/2004/07/Emex.Contragent")] public enum CustomerScheduleAccountMode : int { [System.Runtime.Serialization.EnumMemberAttribute()] CollectionIsForbidden = 0, [System.Runtime.Serialization.EnumMemberAttribute()] StandardCharge = 1, [System.Runtime.Serialization.EnumMemberAttribute()] UrgentCollection = 2, } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="CustomerDiscountHistoryItem", Namespace="http://schemas.datacontract.org/2004/07/Emex.Contragent")] [System.SerializableAttribute()] public partial class CustomerDiscountHistoryItem : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged { [System.NonSerializedAttribute()] private System.Runtime.Serialization.ExtensionDataObject extensionDataField; [System.Runtime.Serialization.OptionalFieldAttribute()] private System.DateTime ChangeDateField; [System.Runtime.Serialization.OptionalFieldAttribute()] private decimal DiscountField; [System.Runtime.Serialization.OptionalFieldAttribute()] private decimal MoneyTurnoverField; [System.Runtime.Serialization.OptionalFieldAttribute()] private EmExServiceClient.ContragentService.User UserField; [global::System.ComponentModel.BrowsableAttribute(false)] public System.Runtime.Serialization.ExtensionDataObject ExtensionData { get { return this.extensionDataField; } set { this.extensionDataField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] public System.DateTime ChangeDate { get { return this.ChangeDateField; } set { if ((this.ChangeDateField.Equals(value)!= true)) { this.ChangeDateField = value; this.RaisePropertyChanged("ChangeDate"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public decimal Discount { get { return this.DiscountField; } set { if ((this.DiscountField.Equals(value)!= true)) { this.DiscountField = value; this.RaisePropertyChanged("Discount"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public decimal MoneyTurnover { get { return this.MoneyTurnoverField; } set { if ((this.MoneyTurnoverField.Equals(value)!= true)) { this.MoneyTurnoverField = value; this.RaisePropertyChanged("MoneyTurnover"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public EmExServiceClient.ContragentService.User User { get { return this.UserField; } set { if ((object.ReferenceEquals(this.UserField, value)!= true)) { this.UserField = value; this.RaisePropertyChanged("User"); } } } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if ((propertyChanged!= null)) { propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="CustomerBalance", Namespace="http://schemas.datacontract.org/2004/07/Emex.Contragent")] [System.SerializableAttribute()] public partial class CustomerBalance : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged { [System.NonSerializedAttribute()] private System.Runtime.Serialization.ExtensionDataObject extensionDataField; [System.Runtime.Serialization.OptionalFieldAttribute()] private short AllowAccountField; [System.Runtime.Serialization.OptionalFieldAttribute()] private short AllowOrderField; [System.Runtime.Serialization.OptionalFieldAttribute()] private System.DateTime BalanceDateField; [System.Runtime.Serialization.OptionalFieldAttribute()] private long CustomerIdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private decimal DebtAccountBNField; [System.Runtime.Serialization.OptionalFieldAttribute()] private decimal DebtOnLocalWarehouseField; [System.Runtime.Serialization.OptionalFieldAttribute()] private decimal DebtOrderBNField; [System.Runtime.Serialization.OptionalFieldAttribute()] private decimal FineField; [System.Runtime.Serialization.OptionalFieldAttribute()] private decimal InorderBNField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool IsPartialReceiptField; [System.Runtime.Serialization.OptionalFieldAttribute()] private decimal MaxDebtField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string MessageCustomerField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string MessageEmExField; [System.Runtime.Serialization.OptionalFieldAttribute()] private decimal OborotPrevField; [System.Runtime.Serialization.OptionalFieldAttribute()] private decimal ReadyForAccountBNField; [System.Runtime.Serialization.OptionalFieldAttribute()] private int ReadyForAccountQuantityField; [System.Runtime.Serialization.OptionalFieldAttribute()] private decimal SaldoBNField; [System.Runtime.Serialization.OptionalFieldAttribute()] private decimal SaldoForPartialField; [System.Runtime.Serialization.OptionalFieldAttribute()] private decimal StorageBNField; [System.Runtime.Serialization.OptionalFieldAttribute()] private decimal SumDetailWeightField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool bitCustomerBalanceField; [global::System.ComponentModel.BrowsableAttribute(false)] public System.Runtime.Serialization.ExtensionDataObject ExtensionData { get { return this.extensionDataField; } set { this.extensionDataField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] public short AllowAccount { get { return this.AllowAccountField; } set { if ((this.AllowAccountField.Equals(value)!= true)) { this.AllowAccountField = value; this.RaisePropertyChanged("AllowAccount"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public short AllowOrder { get { return this.AllowOrderField; } set { if ((this.AllowOrderField.Equals(value)!= true)) { this.AllowOrderField = value; this.RaisePropertyChanged("AllowOrder"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public System.DateTime BalanceDate { get { return this.BalanceDateField; } set { if ((this.BalanceDateField.Equals(value)!= true)) { this.BalanceDateField = value; this.RaisePropertyChanged("BalanceDate"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public long CustomerId { get { return this.CustomerIdField; } set { if ((this.CustomerIdField.Equals(value)!= true)) { this.CustomerIdField = value; this.RaisePropertyChanged("CustomerId"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public decimal DebtAccountBN { get { return this.DebtAccountBNField; } set { if ((this.DebtAccountBNField.Equals(value)!= true)) { this.DebtAccountBNField = value; this.RaisePropertyChanged("DebtAccountBN"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public decimal DebtOnLocalWarehouse { get { return this.DebtOnLocalWarehouseField; } set { if ((this.DebtOnLocalWarehouseField.Equals(value)!= true)) { this.DebtOnLocalWarehouseField = value; this.RaisePropertyChanged("DebtOnLocalWarehouse"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public decimal DebtOrderBN { get { return this.DebtOrderBNField; } set { if ((this.DebtOrderBNField.Equals(value)!= true)) { this.DebtOrderBNField = value; this.RaisePropertyChanged("DebtOrderBN"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public decimal Fine { get { return this.FineField; } set { if ((this.FineField.Equals(value)!= true)) { this.FineField = value; this.RaisePropertyChanged("Fine"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public decimal InorderBN { get { return this.InorderBNField; } set { if ((this.InorderBNField.Equals(value)!= true)) { this.InorderBNField = value; this.RaisePropertyChanged("InorderBN"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public bool IsPartialReceipt { get { return this.IsPartialReceiptField; } set { if ((this.IsPartialReceiptField.Equals(value)!= true)) { this.IsPartialReceiptField = value; this.RaisePropertyChanged("IsPartialReceipt"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public decimal MaxDebt { get { return this.MaxDebtField; } set { if ((this.MaxDebtField.Equals(value)!= true)) { this.MaxDebtField = value; this.RaisePropertyChanged("MaxDebt");
1,502
Repo: LineGames/Leggiero ======================= File: Engine/Modules/Sound/OboeBackend/OboeLoopingSoundPlayingContext.h ======================= //////////////////////////////////////////////////////////////////////////////// // OboeBackend/OboeLoopingSoundPlayingContext.h (Leggiero/Modules - Sound) // // Looping Playing Context in Oboe Backend //////////////////////////////////////////////////////////////////////////////// #ifndef __LM_SOUND__OBOE_BACKEND__LOOPING_SOUND_PLAYING_CONTEXT_H #define __LM_SOUND__OBOE_BACKEND__LOOPING_SOUND_PLAYING_CONTEXT_H // Leggiero.Sound #include "OboeSoundPlayingContext.h" namespace Leggiero { namespace Sound { namespace Oboe { // Looping Sound Playing Context class OboeLoopingSoundPlayingContext : public OboeSoundPlayingContext { friend class OboeSoundMixer; public: virtual ~OboeLoopingSoundPlayingContext() { } public: OboeLoopingSoundPlayingContext(std::shared_ptr<ISoundProvider> sourceSoundProvider, std::shared_ptr<Utility::Object::PointerHolder> mixerHolder, SampleNumberType loopSectionStart, SampleNumberType loopSectionFinish, bool isStartImmediately = true, float volume = 1.0f); public: void StopLooping(); protected: bool m_isLooping; }; } } } #endif ======================= File: Engine/Modules/HTTP/AsyncTaskHttpComponent.h ======================= <reponame>LineGames/Leggiero //////////////////////////////////////////////////////////////////////////////// // AsyncTaskHttpComponent.h (Leggiero/Modules - HTTP) // // Engine Component to Manage Task-based Asynchronous HTTP Communication //////////////////////////////////////////////////////////////////////////////// #ifndef __LM_HTTP__ASYNC_TASK_HTTP_COMPONENT_H #define __LM_HTTP__ASYNC_TASK_HTTP_COMPONENT_H // Standard Library #include <memory> // Leggiero.Engine #include <Engine/Module/EngineComponent.h> #include <Engine/Module/EngineComponentHolder.h> // Leggiero.HTTP #include "HttpCommonType.h" #include "HttpUtility.h" namespace Leggiero { // Forward Declaration namespace Task { class TaskManagerComponent; } namespace HTTP { namespace Async { // Forward Declarations class HTTPRequestTask; class HTTPDownloadTask; // Task Based Asynchronous HTTP Communication Component class AsyncTaskHttpComponent : public EngineComponent { public: AsyncTaskHttpComponent(); virtual ~AsyncTaskHttpComponent(); public: // EngineComponent // Get Type Id of the Component virtual EngineComponentIdType GetComponentType() const override { return EngineComponentIdType::kAsyncTaskHTTP; }; // Initialize the Component virtual void InitializeComponent(Engine::GameProcessAnchor *gameAnchor) override; // Safely Shutdown Component virtual void ShutdownComponent() override; // Get type Id list of dependent modules needed by this component virtual const std::vector<EngineModuleIdType> &GetDependentModules() const override; // Get type Id list of dependent components needed by this component virtual const std::vector<EngineComponentIdType> &GetDependentComponents() const override; // Inject Dependency to the Component. // All dependency injections will be done before the initialization. virtual void InjectDependency(EngineComponentIdType componentId, EngineComponent *dependentComponent) override; public: std::shared_ptr<HTTPRequestTask> Request(const std::string &url, RequestMethod method = RequestMethod::kGet, const POSTParameterMap &parameters = kEmptyPOSTParameterMap, long connectTimeout = HTTP::Settings::GetHTTPRequestDefaultTimeoutInSec()); std::shared_ptr<HTTPDownloadTask> Download(const std::string &downloadFilePath, const std::string &url, RequestMethod method = RequestMethod::kGet, const POSTParameterMap &parameters = kEmptyPOSTParameterMap, bool isBackgroundTask = true, long connectTimeout = HTTP::Settings::GetHTTPRequestDefaultTimeoutInSec()); protected: Task::TaskManagerComponent *m_taskManager; }; } } } DECLARE_GET_COMPONENT_INTERFACE(Leggiero::HTTP::Async::AsyncTaskHttpComponent, Leggiero::EngineComponentIdType::kAsyncTaskHTTP); #endif ======================= File: Engine/Modules/LUI/Touch/UITouch.h ======================= <filename>Engine/Modules/LUI/Touch/UITouch.h<gh_stars>10-100 //////////////////////////////////////////////////////////////////////////////// // Touch/UITouch.h (Leggiero/Modules - LegacyUI) // // UI Processing Touch //////////////////////////////////////////////////////////////////////////////// #ifndef __LM_LUI__TOUCH__UI_TOUCH_H #define __LM_LUI__TOUCH__UI_TOUCH_H // Leggiero.Basic #include <Basic/LeggieroBasic.h> // Standard Library #include <list> #include <memory> #include <tuple> #include <unordered_map> #include <unordered_set> // Leggiero.Input #include <Input/Touch/TouchEvent.h> // Leggiero.LegacyUI #include "../Common/UICommonTypes.h" namespace Leggiero { namespace LUI { // Forward Declarations class UIObject; class UITouchNegotiator; // UI Touch class UITouch : public std::enable_shared_from_this<UITouch> { friend class UITouchNegotiator; public: UITouch(Input::TouchIdType touchId, UICoordinateType startX, UICoordinateType startY, GameTimeClockType::time_point startTime); virtual ~UITouch(); public: // Subscribe events from the touch. // While not subscribing, can only receive Down and In events. // When isStrong is false, OnTouchOut, OnTouchCovered event implicitly means un-subcribing. void Subscribe(std::shared_ptr<UIObject> &subscriber, bool isStrong); void UnSubscribe(std::shared_ptr<UIObject> &subscriber); bool ClaimPrimary(std::shared_ptr<UIObject> &subscriber); void ResignPrimary(std::shared_ptr<UIObject> &subscriber); bool IsSubscribed(const std::shared_ptr<UIObject> &subscriber) const; bool IsOwnPrimary(const std::shared_ptr<UIObject> &subscriber) const; bool IsPrimaryOccupied() const; public: bool IsTouchEnded() const { return!m_isAlive; } Input::TouchIdType GetTouchId() const { return m_touchId; } GameTimeClockType::time_point GetTouchStartTime() const { return m_startTime; } UICoordinateType GetTouchStartX() const { return m_startX; } UICoordinateType GetTouchStartY() const { return m_startY; } UIVector2D GetTouchStartPosition() const { return UIVector2D(m_startX, m_startY); } GameTimeClockType::time_point GetLastTouchChangeTime() const { return m_lastChangeTime; } UICoordinateType GetLastTouchX() const { return m_lastX; } UICoordinateType GetLastTouchY() const { return m_lastY; } UIVector2D GetLastTouchPosition() const { return UIVector2D(m_lastX, m_lastY); } GameTimeClockType::time_point GetCurrentTouchChangeTime() const { return m_currentChangeTime; } UICoordinateType GetCurrentTouchX() const { return m_currentX; } UICoordinateType GetCurrentTouchY() const { return m_currentY; } UIVector2D GetCurrentTouchPosition() const { return UIVector2D(m_currentX, m_currentY); } void UpdateVirtualTouchChangeTime(GameTimeClockType::time_point currentTime) { m_currentChangeTime = currentTime; } public: void UpdateTouchDataUsingEvent(const Input::Touch::TouchEvent &touchEvent); protected: void _ProcessTouchMoveEvent(std::unordered_map<UIObjectIdType, std::tuple<std::shared_ptr<UIObject>, bool, bool> > &allTouchState, std::unordered_set<UIObjectIdType> &outProcessedObjects); void _ProcessTouchUpEvent(); void _ProcessTouchCancelEvent(); void _UpdateTouchState(std::unordered_map<UIObjectIdType, std::tuple<std::shared_ptr<UIObject>, bool, bool> > &allTouchState, std::unordered_set<UIObjectIdType> &outProcessedObjects, std::unordered_set<UIObjectIdType> &inTreeObjectIdTable); bool _NotifyMoveToStrongSubscriber(std::shared_ptr<UIObject> &targetObject, std::unordered_map<UIObjectIdType, std::tuple<std::shared_ptr<UIObject>, bool, bool> > &allTouchState, std::unordered_set<UIObjectIdType> &outProcessedObjects, bool isRealMoved); bool _NotifyMoveToWeekSubscriber(std::shared_ptr<UIObject> &targetObject, std::unordered_map<UIObjectIdType, std::tuple<std::shared_ptr<UIObject>, bool, bool> > &allTouchState, std::unordered_set<UIObjectIdType> &outProcessedObjects, bool isRealMoved); protected: bool m_isAlive; Input::TouchIdType m_touchId; GameTimeClockType::time_point m_startTime; UICoordinateType m_startX; UICoordinateType m_startY; GameTimeClockType::time_point m_lastChangeTime; UICoordinateType m_lastX; UICoordinateType m_lastY; GameTimeClockType::time_point m_currentChangeTime; UICoordinateType m_currentX; UICoordinateType m_currentY; protected: std::shared_ptr<UIObject> m_primarySubscriber; std::list<std::tuple<bool, std::weak_ptr<UIObject> > > m_subscribers; std::unordered_set<UIObjectIdType> m_lastTouchInObjects; std::unordered_set<UIObjectIdType> m_onceInObjects; }; } } #endif ======================= File: Engine/Modules/Font/Common/IFontSet.h ======================= <reponame>LineGames/Leggiero<gh_stars>10-100 //////////////////////////////////////////////////////////////////////////////// // Common/IFontSet.h (Leggiero/Modules - Font) // // Interface for a logical set of fonts //////////////////////////////////////////////////////////////////////////////// #ifndef __LM_FONT__COMMON__I_FONT_SET_H #define __LM_FONT__COMMON__I_FONT_SET_H // Standard Library #include <memory> // Leggiero.Font #include "FontTypes.h" namespace Leggiero { namespace Font { // Forward Declarations class IFontFace; // Font Set Interface class IFontSet { public: IFontSet(); virtual ~IFontSet() { } public: // Individual Font Search Result for a glyph struct EffectiveFontResult { public: std::shared_ptr<IFontFace> face; GlyphCodeInFont glyphCode; bool isBoldUnresolved; bool isItalicUnresolved; public: bool IsValid() const { return ((bool)face); } bool IsTofu() const { return (glyphCode == kGlyphCode_INVALID); } public: EffectiveFontResult(std::shared_ptr<IFontFace> face = nullptr, GlyphCodeInFont glyphCode = 0, bool isBoldUnresolved = false, bool isItalicUnresolved = false) : face(face), glyphCode(glyphCode), isBoldUnresolved(isBoldUnresolved), isItalicUnresolved(isItalicUnresolved) { } }; public: // Get Unique Id for the Font Set FontIdType GetSetUniqueId() const { return m_setUniqueId; } // Get a real font to render a given glyph virtual EffectiveFontResult GetEffectiveFont(GlyphCodePointType glyph, GlyphStyleType style = GlyphStyleType::kNone) const = 0; // Get whther the set is a valid font set virtual bool IsValidFontSet() const { return true; } public: // Empty Font Set which have NO Font static const std::shared_ptr<IFontSet> kNullFontSet; protected: FontIdType m_setUniqueId; }; } } #endif ======================= File: Engine/Modules/Graphics/Shader/Basic/ColorSimpleShader.h ======================= <reponame>LineGames/Leggiero<filename>Engine/Modules/Graphics/Shader/Basic/ColorSimpleShader.h //////////////////////////////////////////////////////////////////////////////// // Shader/Basic/ColorSimpleShader.h (Leggiero/Modules - Graphics) // // Color Simple Shader Program //////////////////////////////////////////////////////////////////////////////// #ifndef __LM_GRAPHICS__SHADER__BASIC__COLOR_SIMPLE_SHADER_H #define __LM_GRAPHICS__SHADER__BASIC__COLOR_SIMPLE_SHADER_H // Leggiero.Basics #include <Basic/LeggieroBasic.h> // Standard Library #include <memory> // External Library #include <GLES3.h> // Leggiero.Graphics #include "../CommonBaseShaderProgram.h" namespace Leggiero { namespace Graphics { // Forward Declaration class GraphicResourceManagerComponent; // Color Simple Shader Program class ColorSimpleShader : public CommonBaseShaderProgram { public: // Creation Function static std::shared_ptr<ColorSimpleShader> Create(GraphicResourceManagerComponent *resourceManager, bool isPremultipliedAlpha = false); public: ColorSimpleShader(std::shared_ptr<GLShaderProgramResource> programResource); virtual ~ColorSimpleShader(); public: virtual GLint GetPositionSlot() const override { return m_positionSlot; } virtual GLint GetColorSlot() const override { return m_colorSlot; } virtual GLint GetModelMatrixLocation() const override { return m_modelMatrixLocation; } virtual GLint GetViewMatrixLocation() const override { return m_viewMatrixLocation; } virtual GLint GetProjectionMatrixLocation() const override { return m_projMatrixLocation; } public: virtual GLVertexAttribEnabledContext EnableUsingVertexAttribArray(bool isAutoDisable = false) override; virtual void DisableAllUsingVertexAttribArray() override; protected: virtual void _RestoreAfterRecompile() override; protected: void _InitializeGLProgramLocations(); protected: GLint m_positionSlot; GLint m_colorSlot; GLint m_modelMatrixLocation; GLint m_viewMatrixLocation; GLint m_projMatrixLocation; public: // Sources static const char *s_sourceVert; static const char *s_sourceFrag; static const char *s_sourceFrag_premulAlpha; }; } } #endif ======================= File: Engine/Modules/LUI/Element/UIElementSingleSimpleButton.h ======================= <gh_stars>10-100 //////////////////////////////////////////////////////////////////////////////// // Element/UIElementSingleSimpleButton.h (Leggiero/Modules - LegacyUI) // // Single button element to process simple interaction //////////////////////////////////////////////////////////////////////////////// #ifndef __LM_LUI__ELEMENT__UI_ELEMENT_SINGLE_SIMPLE_BUTTON_H #define __LM_LUI__ELEMENT__UI_ELEMENT_SINGLE_SIMPLE_BUTTON_H // Leggiero.Basic #include <Basic/LeggieroBasic.h> // Standard Library #include <functional> #include <memory> // Leggiero.Utility #include <Utility/Sugar/EnumClass.h> // Leggiero.Graphics #include <Graphics/Common/GLColor.h> // Leggiero.LegacyUI #include "../Common/UICommonTypes.h" #include "../UIObject.h" namespace Leggiero { namespace LUI { // Forward Declarations class UIManager; class ValuedTouchComponent; class UITouch; namespace Element { // Simple UI Button class SingleSimpleButton : public UIObject { public: enum class StateType { kNormal = 0x0, kPushed = 0x1, kActive = 0x2, kDisabled = 0x4, }; public: // Rendering Controller Definition for interaction class RenderingController { public: virtual void UpdateFrameSelf(GameTimeClockType::duration frameInterval, StateType currentState) { } virtual void FrameGraphicPrepare(const UIRenderer &renderer, UIVector2D offsetPosition, const IUIClipping &effectiveClipping) { } }; public: using OnClickHandlerType = std::function<void(std::shared_ptr<SingleSimpleButton>)>; public: SingleSimpleButton(std::shared_ptr<UIManager> ownerManager, UICoordinateType touchWidth, UICoordinateType touchHeight, OnClickHandlerType onClick = ms_dummyOnClickHandler, std::shared_ptr<RenderingController> renderingController = nullptr); SingleSimpleButton(std::shared_ptr<UIManager> ownerManager, UICoordinateType touchWidth, UICoordinateType touchHeight, UICoordinateType touchCoverWidth, UICoordinateType touchCoverHeight, OnClickHandlerType onClick = ms_dummyOnClickHandler, std::shared_ptr<RenderingController> renderingController = nullptr); virtual ~SingleSimpleButton(); protected: SingleSimpleButton(std::shared_ptr<UIManager> ownerManager); public: // UIObject virtual std::shared_ptr<UIObject> Clone() const override; virtual void _UpdateFrameSelf(GameTimeClockType::duration frameInterval) override; virtual void FrameGraphicPrepare(const UIRenderer &renderer, UIVector2D offsetPosition, const IUIClipping &effectiveClipping) override; public: void SetOnClickHandler(OnClickHandlerType handler) { m_onClickHandlerFunc = handler; } void DiscardOnClickHandler() { m_onClickHandlerFunc = ms_dummyOnClickHandler; } void SetRenderingController(std::shared_ptr<RenderingController> controller); bool IsActiveState() const { return m_isActive; } void SetIsActive(bool isActive) { m_isActive = isActive; } public: void SetTouchWidth(UICoordinateType width); void SetTouchHeight(UICoordinateType height); protected: void _OnTouchDown(std::shared_ptr<UITouch> touch, UICoordinateType x, UICoordinateType y, GameTimeClockType::time_point time, bool isCoveredByDescendant); void _OnTouchIn(std::shared_ptr<UITouch> touch, UICoordinateType x, UICoordinateType y, GameTimeClockType::time_point time, bool isFirstIn, bool isCoveredByDescendant); void _OnTouchOut(std::shared_ptr<UITouch> touch, UICoordinateType x, UICoordinateType y, GameTimeClockType::time_point time); void _OnTouchCovered(std::shared_ptr<UITouch> touch, UICoordinateType x, UICoordinateType y, GameTimeClockType::time_point time); void _OnTouchCancel(std::shared_ptr<UITouch> touch, GameTimeClockType::time_point time); void _OnTouchUp(std::shared_ptr<UITouch> touch, UICoordinateType x, UICoordinateType y, GameTimeClockType::time_point time); void _OnPrimaryTouchLose(std::shared_ptr<UITouch> touch); void _SetTouchPressedState(bool isPressed); protected: UICoordinateType m_width; UICoordinateType m_height; UICoordinateType m_coverWidth; UICoordinateType m_coverHeight; protected: std::shared_ptr<UIObject> m_touchVirtualObject; std::shared_ptr<RenderingController> m_renderingController; protected: static OnClickHandlerType ms_dummyOnClickHandler; OnClickHandlerType m_onClickHandlerFunc; std::shared_ptr<UITouch> m_processingTouch; bool m_isPressed; bool m_isActive; }; MAKE_ENUM_FLAG(SingleSimpleButton::StateType); } } } #endif ======================= File: Engine/Modules/FileSystem/FileSystemUtility.h ======================= <reponame>LineGames/Leggiero<filename>Engine/Modules/FileSystem/FileSystemUtility.h<gh_stars>10-100 //////////////////////////////////////////////////////////////////////////////// // FileSystemUtility.h (Leggiero/Modules - FileSystem) // // Utilities for File System //////////////////////////////////////////////////////////////////////////////// #ifndef __LM_FILESYSTEM__FILE_SYSTEM_UTILITY_H #define __LM_FILESYSTEM__FILE_SYSTEM_UTILITY_H // Leggiero.Basic #include <Basic/LeggieroBasic.h> // Standard Library #include <string> #include <vector> namespace Leggiero { namespace FileSystem { namespace Utility { extern const char kPathDelimiter; std::string FilterDelimiter(const std::string &path, bool makeEndWithDelimeter = false); std::string TrimTopAbsoluteDelimiter(const std::string &path); // Combine two parts as a path std::string CombinePath(const std::string &path1, const std::string &path2); std::string CombinePathWithResolvingParent(const std::string &path1, const std::string &path2, bool isGoBeyondTop = false); // Check existence of the directory and create if not exists void PrepareDirectoryPath(const std::string &path); std::string GetExtension(const std::string &path); std::string GetParent(const std::string &path); std::string GetName(const std::string &path, bool isIncludeExtension = true); bool IsDirectory(const std::string &path); std::vector<GameDataString> ListSubDirectories(const std::string &path); std::vector<GameDataString> ListFiles(const std::string &path); } } } #endif ======================= File: Engine/Modules/LUI/Description/UIDescriptionUnit.h ======================= <filename>Engine/Modules/LUI/Description/UIDescriptionUnit.h<gh_stars>10-100 //////////////////////////////////////////////////////////////////////////////// // Description/UIDescriptionUnit.h (Leggiero/Modules - LegacyUI) // // Definition of an UI Description Unit which is a unit of UI Description // Processing //////////////////////////////////////////////////////////////////////////////// #ifndef __LM_LUI__DESCRIPTION__UI_DESCRIPTION_UNIT_H #define __LM_LUI__DESCRIPTION__UI_DESCRIPTION_UNIT_H // Leggiero.Basic #include <Basic/LeggieroBasic.h> // Standard Library #include <initializer_list> #include <memory> #include <string> #include <unordered_map> #include <vector> // Leggiero.LegacyUI #include "UIDescriptionTypes.h" #include "UIDescription.h" namespace Leggiero { namespace LUI { namespace Description { // Forward Declaration class DescriptionManager; // An UI Description Unit // Also is a namespace. When load UI Description data from a file, it considered as an Description Unit. class DescriptionUnit : public IDescriptionNameSpaceContext , public std::enable_shared_from_this<DescriptionUnit> { public: DescriptionUnit() { } virtual ~DescriptionUnit() { } public: static std::shared_ptr<DescriptionUnit> LoadFromXML(std::string xmlData, DescriptionManager &loadingManager); public: // IDescriptionNameSpaceContext virtual ObjectEnvironmentPair Select(const VariableNameType &name, DescriptionProcessingContext &processingContext) override; virtual bool IsNeedRecursiveSearch(DescriptionProcessingContext &processingContext) const override { return true; } public: ObjectEnvironmentPair SelectDescriptionByName(DescriptionManager &manager, const VariableNameType &name); ObjectEnvironmentPair SelectDescriptionByPath(DescriptionManager &manager, const std::string &path); ObjectEnvironmentPair SelectDescriptionByPath(DescriptionManager &manager, const VariablePathType &path); public: void AddObject(const VariableNameType &name, std::shared_ptr<IDescriptionObject> descriptionObject); protected: std::unordered_map<VariableNameType, std::shared_ptr<IDescriptionObject> > m_descriptionTable; }; } } } #endif ======================= File: Engine/Modules/Graphics/GraphicsThreadContext.h ======================= //////////////////////////////////////////////////////////////////////////////// // GraphicsThreadContext.h (Leggiero/Modules - Graphics) // // Graphics Context Related Stuffs for each Threads //////////////////////////////////////////////////////////////////////////////// #ifndef __LM_GRAPHICS__GRAPHICS_THREAD_CONTEXT_H #define __LM_GRAPHICS__GRAPHICS_THREAD_CONTEXT_H // Standard Library #include <memory> namespace Leggiero { namespace Graphics { // Common Base Interface for each Platform's Thread Context Informations class IGLThreadContextInformation { public: virtual ~IGLThreadContextInformation() { } }; //////////////////////////////////////////////////////////////////////////////// Platform Dependent Functions // For following functions, implementation must be provided for each platform // Check whether if the initialization by GL context of the main rendering thread have done or not extern bool IsMainGLContextInitialized(); // Initialize the main OpenGL Context extern void InitializeMainGLContextInGraphicThread(); // Create called thread's OpenGL Context and return the infromation object extern std::shared_ptr<IGLThreadContextInformation> MakeThreadGLContext(); // Clean up called thread's OpenGL Context extern void TerminateThreadGLContext(std::shared_ptr<IGLThreadContextInformation> contextInfo); // Check called thread's OpenGL Context's validity and restore it if needed extern void CheckAndRefreshThreadGLContext(std::shared_ptr<IGLThreadContextInformation> contextInfo); //////////////////////////////////////////////////////////////////////////////// } } #endif ======================= File: Engine/Modules/Graphics/Shader/CommonGLVertexType.h ======================= //////////////////////////////////////////////////////////////////////////////// // Shader/CommonGLVertexType.h (Leggiero/Modules - Graphics) // // Common basic vertex data structure for OpenGL //////////////////////////////////////////////////////////////////////////////// #ifndef __LM_GRAPHICS__SHADER__COMMON_GL_VERTEX_TYPE_H #define __LM_GRAPHICS__SHADER__COMMON_GL_VERTEX_TYPE_H // Leggiero.Basics #include <Basic/LeggieroBasic.h> // External Library #include <GLES3.h> // Leggiero.Utility #include <Utility/Math/SimpleMath.h> namespace Leggiero { namespace Graphics { // Make vertices have fitting size #pragma pack(push, 1) // Vertex that only have position value struct PositionVertex { public: float position[4]; public: PositionVertex LerpWith(const PositionVertex &withVertex, float param) const { return Lerp(*this, withVertex, param); } public: static void SetGLVertexAttribPointer(GLuint positionSlot, const PositionVertex *pArrayStart) { glVertexAttribPointer(positionSlot, 4, GL_FLOAT, GL_FALSE, sizeof(PositionVertex), &pArrayStart->position); } static PositionVertex Lerp(const PositionVertex &v1, const PositionVertex &v2, float param) { PositionVertex resultVertex; resultVertex.position[0] = Utility::Math::LerpValue(v1.position[0], v2.position[0], param); resultVertex.position[1] = Utility::Math::LerpValue(v1.position[1], v2.position[1], param); resultVertex.position[2] = Utility::Math::LerpValue(v1.position[2], v2.position[2], param); resultVertex.position[3] = Utility::Math::LerpValue(v1.position[3], v2.position[3], param); return resultVertex; } }; // Basic vertex with position and color of each point struct ColoredVertex { public: float position[4]; GLubyte color[4]; public: ColoredVertex LerpWith(const ColoredVertex &withVertex, float param) const { return Lerp(*this, withVertex, param); } public: static void SetGLVertexAttribPointer(GLuint positionSlot, GLuint colorSlot, const ColoredVertex *pArrayStart) { glVertexAttribPointer(positionSlot, 4, GL_FLOAT, GL_FALSE, sizeof(ColoredVertex), &pArrayStart->position); glVertexAttribPointer(colorSlot, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ColoredVertex), &pArrayStart->color); } static ColoredVertex Lerp(const ColoredVertex &v1, const ColoredVertex &v2, float param) { ColoredVertex resultVertex; resultVertex.position[0] = Utility::Math::LerpValue(v1.position[0], v2.position[0], param); resultVertex.position[1] = Utility::Math::LerpValue(v1.position[1], v2.position[1], param); resultVertex.position[2] = Utility::Math::LerpValue(v1.position[2], v2.position[2], param); resultVertex.position[3] = Utility::Math::LerpValue(v1.position[3], v2.position[3], param); resultVertex.color[0] = Utility::Math::LerpValue(v1.color[0], v2.color[0], param); resultVertex.color[1] = Utility::Math::LerpValue(v1.color[1], v2.color[1], param); resultVertex.color[2] = Utility::Math::LerpValue(v1.color[2], v2.color[2], param); resultVertex.color[3] = Utility::Math::LerpValue(v1.color[3], v2.color[3], param); return resultVertex; } }; // Vertex with position, texel uv coordinates, and blending color struct TextureColoredVertex { public: float position[4]; GLubyte color[4]; float textureUV[2]; public: TextureColoredVertex LerpWith(const TextureColoredVertex &withVertex, float param) const { return Lerp(*this, withVertex, param); } public: static void SetGLVertexAttribPointer(GLuint positionSlot, GLuint colorSlot, GLuint textureUVSlot, const TextureColoredVertex *pArrayStart) { glVertexAttribPointer(positionSlot, 4, GL_FLOAT, GL_FALSE, sizeof(TextureColoredVertex), &pArrayStart->position); glVertexAttribPointer(colorSlot, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(TextureColoredVertex), &pArrayStart->color); glVertexAttribPointer(textureUVSlot, 2, GL_FLOAT, GL_FALSE, sizeof(TextureColoredVertex), &pArrayStart->textureUV); } static TextureColoredVertex Lerp(const TextureColoredVertex &v1, const TextureColoredVertex &v2, float param) { TextureColoredVertex resultVertex; resultVertex.position[0] = Utility::Math::LerpValue(v1.position[0], v2.position[0], param); resultVertex.position[1] = Utility::Math::LerpValue(v1.position[1], v2.position[1], param); resultVertex.position[2] = Utility::Math::LerpValue(v1.position[2], v2.position[2], param); resultVertex.position[3] = Utility::Math::LerpValue(v1.position[3], v2.position[3], param); resultVertex.color[0] = Utility::Math::LerpValue(v1.color[0], v2.color[0], param); resultVertex.color[1] = Utility::Math::LerpValue(v1.color[1], v2.color[1], param); resultVertex.color[2] = Utility::Math::LerpValue(v1.color[2], v2.color[2], param); resultVertex.color[3] = Utility::Math::LerpValue(v1.color[3], v2.color[3], param); resultVertex.textureUV[0] = Utility::Math::LerpValue(v1.textureUV[0], v2.textureUV[0], param); resultVertex.textureUV[1] = Utility::Math::LerpValue(v1.textureUV[1], v2.textureUV[1], param); return resultVertex; } }; #pragma pack(pop) } } #endif ======================= File: Engine/Common/Engine/Toolbox/Scene/GameSceneTypes.h ======================= //////////////////////////////////////////////////////////////////////////////// // Toolbox/Scene/GameSceneTypes.h (Leggiero - Engine) // // Game Scene Related Type Definition //////////////////////////////////////////////////////////////////////////////// #ifndef __ENGINE__TOOLBOX__SCENE__GAME_SCENE_TYPES_H #define __ENGINE__TOOLBOX__SCENE__GAME_SCENE_TYPES_H namespace Leggiero { namespace Toolbox { namespace Scene { // Game Scene Id Type using GameSceneIdType = int; // Invalid Scene Id Constant constexpr GameSceneIdType kInvalidSceneId = static_cast<GameSceneIdType>(0); } } } #endif ======================= File: Engine/Modules/LUI/Description/UIDescriptionTypes.h ======================= <reponame>LineGames/Leggiero //////////////////////////////////////////////////////////////////////////////// // Description/UIDescriptionTypes.h (Leggiero/Modules - LegacyUI) // // Common type definitions for UI Description //////////////////////////////////////////////////////////////////////////////// #ifndef __LM_LUI__DESCRIPTION__UI_DESCRIPTION_TYPES_H #define __LM_LUI__DESCRIPTION__UI_DESCRIPTION_TYPES_H // Leggiero.Basic #include <Basic/LeggieroBasic.h> // Standard Library #include <string> #include <vector> // Leggiero.Utility #include <Utility/Math/Vector.h> #include <Utility/String/IStringBag.h> // Leggiero.Graphics #include <Graphics/Common/GLColor.h> // Leggiero.LegacyUI #include "../Common/UICommonTypes.h" // Forward Declaration namespace tinyxml2 { class XMLElement; } namespace Leggiero { namespace LUI { namespace Description { // Variable name for referencing using VariableNameType = std::string; using VariablePathType = std::vector<VariableNameType>; using UnitNameType = std::string; using SavedUnitNameType = std::string; namespace StringFormat { constexpr char kVariablePathDelimiter = ':'; constexpr char kExpressionTypeDelimiter = ';'; } namespace TypeUtility { inline VariableNameType ToVariableName(const char *variableName) { return VariableNameType(variableName); } inline VariableNameType ToVariableName(const std::string &variableName) { return VariableNameType(variableName); } inline SavedUnitNameType ToSavedUnitName(const UnitNameType &unitName) { return SavedUnitNameType(unitName); } VariablePathType ParseVariablePath(const char *variablePath); VariablePathType ParseVariablePath(const std::string &variablePath); extern const VariableNameType kInvalidName; } // Type tag for description object enum class UIDescriptionObjectType { kINVALID, kImportedUnit, kNameSpaceGroup, kOverridingNameSpace, kAliasName, kAliasPath, kUIPrefab, kVariable, kTextureSegment, kTextureSource, kFontClass, kThreePatchHClass, kThreePatchVClass, kNinePatchClass, }; // Type tag for values in description enum class UIDescriptionValueType { kINVALID, kBoolean, kInteger, kFloatingPoint, kColor, kVector2D, kVector3D, kString, }; using BooleanValueType = bool; using IntegerValueType = int; using FloatingPointValueType = float; using ColorARGBValueType = Graphics::GLByteARGB; using Vector2DValueType = Utility::Math::Vector2D<FloatingPointValueType>; using Vector3DValueType = Utility::Math::Vector3D<FloatingPointValueType>; using StringValueType = GameDataString; template <typename ValueT> inline constexpr UIDescriptionValueType GetValueTypeTag() { return UIDescriptionValueType::kINVALID; } template<> inline constexpr UIDescriptionValueType GetValueTypeTag<BooleanValueType>() { return UIDescriptionValueType::kBoolean; } template<> inline constexpr UIDescriptionValueType GetValueTypeTag<IntegerValueType>() { return UIDescriptionValueType::kInteger; } template<> inline constexpr UIDescriptionValueType GetValueTypeTag<FloatingPointValueType>() { return UIDescriptionValueType::kFloatingPoint; } template<> inline constexpr UIDescriptionValueType GetValueTypeTag<ColorARGBValueType>() { return UIDescriptionValueType::kColor; } template<> inline constexpr UIDescriptionValueType GetValueTypeTag<Vector2DValueType>() { return UIDescriptionValueType::kVector2D; } template<> inline constexpr UIDescriptionValueType GetValueTypeTag<Vector3DValueType>() { return UIDescriptionValueType::kVector3D; } template<> inline constexpr UIDescriptionValueType GetValueTypeTag<StringValueType>() { return UIDescriptionValueType::kString; } // Data String Bag using DataStringKeyType = std::string; using DataStringValueType = GameDataString; using DataStringBagType = Utility::String::IStringBag<DataStringKeyType, DataStringValueType>; DataStringBagType &GetEmptyStringBag(); // Other Setting Types enum class QuantizeType { kNo, kFloor, kRound, kCeil, }; QuantizeType ParseQuantizeType(const char *quantizationCString); // Parsing from XML using ParsingXMLElementType = tinyxml2::XMLElement; } } } #endif ======================= File: Engine/Modules/LUI/Touch/UITouchNegotiator.h ======================= //////////////////////////////////////////////////////////////////////////////// // Touch/UITouchNegotiator.h (Leggiero/Modules - LegacyUI) // // Processing touches for UI context //////////////////////////////////////////////////////////////////////////////// #ifndef __LM_LUI__TOUCH__UI_TOUCH_NEGOTIATOR_H #define __LM_LUI__TOUCH__UI_TOUCH_NEGOTIATOR_H // Leggiero.Basic #include <Basic/LeggieroBasic.h> // Standard Library #include <memory> #include <unordered_map> #include <unordered_set> #include <vector> // External Library #include <concurrentqueue/concurrentqueue.h> // Leggiero.Input #include <Input/Touch/TouchEvent.h> // Leggiero.LegacyUI #include "../Common/UICommonTypes.h" namespace Leggiero { namespace LUI { // Forward Declarations class UIManager; class UIObject; class UITouch; // UI Touch Negotiator class UITouchNegotiator { public: UITouchNegotiator(); virtual ~UITouchNegotiator(); public: void ProcessTouchEvents(const std::vector<Input::Touch::TouchEvent> &touchEvents, GameTimeClockType::time_point frameTime, UIManager &processingManager); void ClearAllTouches(); protected: std::unordered_map<Input::TouchIdType, std::shared_ptr<UITouch> > m_activeTouches; protected: // Copied UI tree node entry to deal with tree changing during processing struct UITreeCopyEntry { std::shared_ptr<UIObject> treeNode; std::vector<std::shared_ptr<UITreeCopyEntry> > m_preChildren; std::vector<std::shared_ptr<UITreeCopyEntry> > m_postChildren; void Clear() { treeNode.reset(); m_preChildren.clear(); m_postChildren.clear(); } }; // Use object pool moodycamel::ConcurrentQueue<std::shared_ptr<UITreeCopyEntry> > m_treeCopyEntryPool; std::shared_ptr<UITreeCopyEntry> _GetTreeCopyEntryObject(); void _ReleaseTreeCopyEntryObject(std::shared_ptr<UITreeCopyEntry> releasingObject); std::shared_ptr<UITreeCopyEntry> _CopyUITree(std::shared_ptr<UIObject> treeRoot, std::unordered_set<UIObjectIdType> *inTreeObjects); void _ReleaseUITreeCopy(std::shared_ptr<UITreeCopyEntry> releasingTree); protected: bool _DoDownTouchProcess(std::shared_ptr<UITreeCopyEntry> treeRoot, std::shared_ptr<UITouch> &touchObject); bool _ExtractTouchState(std::shared_ptr<UITreeCopyEntry> treeRoot, std::shared_ptr<UITouch> &touchObject, bool isCovered, std::unordered_map<UIObjectIdType, std::tuple<std::shared_ptr<UIObject>, bool, bool> > &outTouchState); void _DoTouchMoveProcess(std::shared_ptr<UITreeCopyEntry> treeRoot, std::shared_ptr<UITouch> &touchObject, std::unordered_map<UIObjectIdType, std::tuple<std::shared_ptr<UIObject>, bool, bool> > &allTouchState, std::unordered_set<UIObjectIdType> &processedObjects); void _DoTouchUpdateProcess(std::shared_ptr<UITreeCopyEntry> treeRoot, std::shared_ptr<UITouch> &touchObject, std::unordered_map<UIObjectIdType, std::tuple<std::shared_ptr<UIObject>, bool, bool> > &allTouchState, std::unordered_set<UIObjectIdType> &processedObjects); }; } } #endif ======================= File: Engine/Modules/Task/_Internal/ITaskManagerSystemFunctions.h ======================= //////////////////////////////////////////////////////////////////////////////// // _Internal/ITaskManagerSystemFunctions.h (Leggiero/Modules - Task) // // Task Manager Interface for Task Systems //////////////////////////////////////////////////////////////////////////////// #ifndef __LM_TASK___INTERNAL__I_TASK_MANAGER_SYSTEM_FUNCTIONS_H #define __LM_TASK___INTERNAL__I_TASK_MANAGER_SYSTEM_FUNCTIONS_H // Leggiero.Task #include "../TaskTypes.h" namespace Leggiero { namespace Task { // Forward Declarations struct TaskExecutionEntry; class ITaskSubSystem; // Interface for Task Systems class ITaskManagerSystemFunctions { public: virtual ~ITaskManagerSystemFunctions() { } public: // For sub-systems virtual void AttachSubSystem(std::shared_ptr<ITaskSubSystem> subSystem) = 0; virtual void AddGeneralWorkerCapability(TaskCapabilityType capabilities) = 0; public: // For processors virtual void RequestExecution(TaskExecutionEntry *execution) = 0; virtual void RequestDelayedExecution(TaskExecutionEntry *execution, SchedulingClock::duration delay) = 0; virtual void ReleaseExecution(TaskExecutionEntry *execution) = 0; }; } } #endif ======================= File: Engine/Modules/Graphics/_Internal/_InternalUpdater.h ======================= <filename>Engine/Modules/Graphics/_Internal/_InternalUpdater.h //////////////////////////////////////////////////////////////////////////////// // _Internal/_InternalUpdater.h (Leggiero/Modules - Graphics) // * DO NOT directly include this header file outside of Graphics project // // Internal Update Function Definitions for Graphics Module //////////////////////////////////////////////////////////////////////////////// #ifndef __LM_GRAPHICS___INTERNAL___INTERNAL_UPDATER_H #define __LM_GRAPHICS___INTERNAL___INTERNAL_UPDATER_H // Leggiero.Basics #include <Basic/LeggieroBasic.h> namespace Leggiero { namespace Graphics { namespace ReferenceState { namespace _Internal { // Update Reference State at the start of Each Frame void _UpdateReferenceStateAtFrame(); } } } } #endif ======================= File: Engine/Modules/HTTP/Async/AsyncHttp_iOS.h ======================= //////////////////////////////////////////////////////////////////////////////// // Async/AsyncHttp_iOS.h (Leggiero/Modules - HTTP) // // Asynchronous HTTP functions for iOS platform //////////////////////////////////////////////////////////////////////////////// #ifndef __LM_HTTP__ASYNC__ASYNC_HTTP__IOS_H #define __LM_HTTP__ASYNC__ASYNC_HTTP__IOS_H // Leggiero.Basic #include <Basic/LeggieroBasic.h> // Standard Library #include <memory> // Leggiero.HTTP #include "../HttpUtility.h" #include "AsyncHttpRequestTask.h" #include "AsyncHttpDownloadTask.h" namespace Leggiero { namespace HTTP { namespace Async { namespace iOS { std::shared_ptr<HTTPRequestTask> StartHTTPRequestAsync(const std::string &url, RequestMethod method = RequestMethod::kGet, const POSTParameterMap &parameters = kEmptyPOSTParameterMap, long connectTimeout = HTTP::Settings::GetHTTPRequestDefaultTimeoutInSec()); std::shared_ptr<HTTPDownloadTask> StartHTTPDownloadAsync(const std::string &downloadFilePath, bool isBackgroundTask, const std::string &url, RequestMethod method = RequestMethod::kGet, const POSTParameterMap &parameters = kEmptyPOSTParameterMap, long connectTimeout = HTTP::Settings::GetHTTPRequestDefaultTimeoutInSec()); } } } } #endif ======================= File: Engine/Modules/LUI/Common/UICommonTypes.h ======================= //////////////////////////////////////////////////////////////////////////////// // Common/UICommonTypes.h (Leggiero/Modules - LegacyUI) // // Common Type Definitions for Legacy UI //////////////////////////////////////////////////////////////////////////////// #ifndef __LM_LUI__COMMON__UI_COMMON_TYPES_H #define __LM_LUI__COMMON__UI_COMMON_TYPES_H // Standard Library #include <cstdint> #include <string> // Leggiero.Utility #include <Utility/Math/Vector.h> namespace Leggiero { namespace LUI { // Unique Id of UI Object using UIObjectIdType = int64_t; constexpr UIObjectIdType kInvalidObjectId = (UIObjectIdType)(~(UIObjectIdType)0); // UI Coordinate Type using UICoordinateType = float; using UICoordinateRatioType = float; constexpr UICoordinateRatioType kUICoordinateRatio_Zero = static_cast<Leggiero::LUI::UICoordinateRatioType>(0.0f); constexpr UICoordinateRatioType kUICoordinateRatio_Half = static_cast<Leggiero::LUI::UICoordinateRatioType>(0.5f); constexpr UICoordinateRatioType kUICoordinateRatio_One = static_cast<Leggiero::LUI::UICoordinateRatioType>(1.0f); using UIVector2D = Utility::Math::Vector2D<UICoordinateType>; // Size type for UI Elements struct UIElementSize { public: UICoordinateType width; UICoordinateType height; public: UIElementSize() : width(static_cast<UICoordinateType>(0.0f)), height(static_cast<UICoordinateType>(0.0f)) { } UIElementSize(UICoordinateType width, UICoordinateType height) : width(width), height(height) { } }; // Axis-parallel Rectangular Type struct UISimpleRectangular { public: UICoordinateType left; UICoordinateType top; UICoordinateType right; UICoordinateType bottom; public: UICoordinateType Width() const { return right - left; } UICoordinateType Height() const { return bottom - top; } public: UISimpleRectangular(UICoordinateType left, UICoordinateType top, UICoordinateType right, UICoordinateType bottom) : left(left), top(top), right(right), bottom(bottom) { } static UISimpleRectangular FromPositionSize(UICoordinateType x, UICoordinateType y, UICoordinateType width, UICoordinateType height) { return UISimpleRectangular(x, y, x + width, y + height); } }; // Border Alignment Type for Line enum class ShapeBorderAlignType { kInside, kCenter, kOutside, }; // Common Epsilon Value constexpr float kFloatEpsilon = 0.000001f; // UI Structural Version Number Type using StructuralVersionType = uint64_t; // Names using UITextureNameType = std::string; using UIFontNameType = std::string; } } #endif ======================= File: Engine/Modules/LUI/Rendering/TextureRenderingComponent.h ======================= <reponame>LineGames/Leggiero<filename>Engine/Modules/LUI/Rendering/TextureRenderingComponent.h //////////////////////////////////////////////////////////////////////////////// // Rendering/TextureRenderingComponent.h (Leggiero/Modules - LegacyUI) // // Rendering component to render textured rectangular image //////////////////////////////////////////////////////////////////////////////// #ifndef __LM_LUI__RENDERING__TEXTURE_RENDERING_COMPONENT_H #define __LM_LUI__RENDERING__TEXTURE_RENDERING_COMPONENT_H // Standard Library #include <memory> #include <vector> // External Library #include <GLES3.h> // Leggiero.Graphics #include <Graphics/Common/GLColor.h> #include <Graphics/Texture/TextureSection.h> #include <Graphics/Shader/CommonGLVertexType.h> // Leggiero.LegacyUI #include "UIRenderingComponent.h" #include "../Common/UISizeSettable.h" namespace Leggiero { // Forward Declaration namespace Graphics { class GLTextureResource; } namespace LUI { namespace Rendering { // Rectangular texture image rendering component class TextureRenderingComponent : public UIRenderingComponent , public IRectSizeSettable { public: TextureRenderingComponent(std::shared_ptr<Graphics::GLTextureResource> texture, Graphics::GLByteARGB color = Graphics::GLByteARGB::kWhite); TextureRenderingComponent(std::shared_ptr<Graphics::GLTextureResource> texture, const Graphics::TextureRectSection &section, Graphics::GLByteARGB color = Graphics::GLByteARGB::kWhite); TextureRenderingComponent(std::shared_ptr<Graphics::GLTextureResource> texture, const Graphics::TextureRectSection &section, UICoordinateType width, UICoordinateType height, Graphics::GLByteARGB color = Graphics::GLByteARGB::kWhite); virtual ~TextureRenderingComponent(); // IUIComponent public: virtual std::shared_ptr<IUIComponent> Clone(const UIObject &ownerObject) const override; // UIRenderingComponent public: virtual void Render(const UIRenderer &renderer, IUITransform &effectiveTransform, const IUIClipping &effectiveClipping, float alpha) override; virtual UIElementSize GetVisualSize() override { return UIElementSize(m_width, m_height); } public: void SetTexture(std::shared_ptr<Graphics::GLTextureResource> texture); void SetTexture(std::shared_ptr<Graphics::GLTextureResource> texture, const Graphics::TextureRectSection &section); void SetSize(UICoordinateType width, UICoordinateType height); virtual void SetUIWidgetRectSize(UICoordinateType width, UICoordinateType height) override { SetSize(width, height); } void SetSizeRatio(UICoordinateRatioType widthRatio, UICoordinateRatioType heightRatio); void SetColor(Graphics::GLByteARGB color) { m_color = color; } void SetFlip(bool isFlipHorizontal, bool isFlipVertical) { m_isFlipHorizontal = isFlipHorizontal; m_isFlipVertical = isFlipVertical; } protected: std::shared_ptr<Graphics::GLTextureResource> m_texture; Graphics::TextureRectSection m_section; UICoordinateType m_width; UICoordinateType m_height; bool m_isFlipHorizontal; bool m_isFlipVertical; Graphics::GLByteARGB m_color; std::vector<Graphics::TextureColoredVertex> m_vertexBuffer; std::vector<GLushort> m_indexBuffer; }; // Texture rendering component with gaussian blur effect class BlurredTextureRenderingComponent : public TextureRenderingComponent { public: BlurredTextureRenderingComponent(std::shared_ptr<Graphics::GLTextureResource> texture, Graphics::GLByteARGB color = Graphics::GLByteARGB::kWhite); BlurredTextureRenderingComponent(std::shared_ptr<Graphics::GLTextureResource> texture, const Graphics::TextureRectSection &section, Graphics::GLByteARGB color = Graphics::GLByteARGB::kWhite); BlurredTextureRenderingComponent(std::shared_ptr<Graphics::GLTextureResource> texture, const Graphics::TextureRectSection &section, UICoordinateType width, UICoordinateType height, Graphics::GLByteARGB color = Graphics::GLByteARGB::kWhite); BlurredTextureRenderingComponent(std::shared_ptr<Graphics::GLTextureResource> texture, const Graphics::TextureRectSection &section, UICoordinateType width, UICoordinateType height, float widthBlurRatio, float heightBlurRatio, Graphics::GLByteARGB color = Graphics::GLByteARGB::kWhite); virtual ~BlurredTextureRenderingComponent(); public: // IUIComponent virtual std::shared_ptr<IUIComponent> Clone(const UIObject &ownerObject) const override; public: // UIRenderingComponent virtual void Render(const UIRenderer &renderer, IUITransform &effectiveTransform, const IUIClipping &effectiveClipping, float alpha) override; public: void SetLinearBlurMultiplier(float widthRatio, float heightRatio); protected: float m_widthTexelUVRatio; float m_heightTexelUVRatio; }; } } } #endif ======================= File: Engine/Common/Basic/_Internal/_LeggieroFlags.h ======================= <filename>Engine/Common/Basic/_Internal/_LeggieroFlags.h //////////////////////////////////////////////////////////////////////////////// // _Internal/_LeggieroFlags.h (Leggiero - Basic) // * DO NOT directly include this header file outside of Basic project // // Leggiero Engine Preprocessor Definition Stuffs //////////////////////////////////////////////////////////////////////////////// #ifndef __BASIC___LEGGIERO_FLAGS_H #define __BASIC___LEGGIERO_FLAGS_H // Detect Platform #if defined(_WIN32) || defined(__WIN32__) #define _LEGGIERO_WINPC #elif defined(__APPLE__) #define _LEGGIERO_IOS #elif defined(ANDROID) || defined(__ANDROID__) #define _LEGGIERO_ANDROID #else // Unknown Platform #endif // Detect Debug Mode #ifdef NDEBUG #define _LEGGIERO_RELEASE 1 #else #define _LEGGIERO_DEBUG 1 #endif #endif ======================= File: Engine/Platform/Platform.WinPC/OpenGL/EGLView.h ======================= <filename>Engine/Platform/Platform.WinPC/OpenGL/EGLView.h<gh_stars>10-100 //////////////////////////////////////////////////////////////////////////////// // OpenGL/EGLView.h (Leggiero - Platform.WinPC) // // EGL based OpenGL ES 3.0 View //////////////////////////////////////////////////////////////////////////////// #pragma once // External Library #include <EGL/egl.h> // Leggiero.Platform.WinPC #include "../WindowsCommon.h" namespace Leggiero { namespace Platform { namespace Windows { namespace Graphics { // Graphic Device via EGL class EGLView { public: EGLView(const HWND &windowHWnd); virtual ~EGLView(); public: void SwapBuffers(); private: EGLDisplay m_eglDisplay; EGLSurface m_eglSurface; EGLContext m_eglContext; }; } } } } ======================= File: Engine/Common/Utility/Sugar/SingletonPattern.h ======================= <filename>Engine/Common/Utility/Sugar/SingletonPattern.h //////////////////////////////////////////////////////////////////////////////// // Sugar/SingletonPattern.h (Leggiero - Utility) // // GoF Singleton Pattern - referenced EC++ implementation //////////////////////////////////////////////////////////////////////////////// #ifndef __UTILITY__SUGAR__SINGLETON_PATTERN_H #define __UTILITY__SUGAR__SINGLETON_PATTERN_H // Leggiero.Basic #include <Basic/LeggieroBasic.h> // Standard Library #include <cstdlib> #include <atomic> // External Library #include <pthread.h> // Leggiero.Utility #include "Finally.h" namespace Leggiero { namespace Utility { namespace DesignPattern { // Singleton Base Class template <class T> class Singleton { public: virtual ~Singleton() { // To raise AV after deletion ms_instance = nullptr; } protected: virtual void Initialize() { } private: static T *ms_instance; static void SingletonDeleter() { delete ms_instance; } public: static T &GetInstance() { #ifdef _LEGGIERO_IOS static pthread_mutex_t initMutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER; #else static pthread_mutex_t initMutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP; #endif static std::atomic_uchar initializedFlag; unsigned char isInitialized = initializedFlag.load(); if (isInitialized == 0) { int lockResult = pthread_mutex_lock(&initMutex); if (lockResult == 0) { pthread_mutex_t *lockCopy = &initMutex; auto releaseLockFunc = [lockCopy]() mutable { pthread_mutex_unlock(lockCopy); }; FINALLY_OF_BLOCK(_RELEASE_LOCK, releaseLockFunc); isInitialized = initializedFlag.exchange(1); if (isInitialized == 0) { ms_instance = new T(); ms_instance->Initialize(); std::atexit(SingletonDeleter); } } else { // Keep going with atomic // This make sure to initialize once, but access before the initialization can be occured isInitialized = initializedFlag.exchange(1); if (isInitialized == 0) { ms_instance = new T(); ms_instance->Initialize(); std::atexit(SingletonDeleter); } } } return *ms_instance; //NOTE: We need to consider Longevity for finalization order } }; } } } //------------------------------------------------------------------------------ Singleton Macros #define LEGGIERO_MAKE_SINGLETON_UNIQUE(CLASS_NAME) \ private: \ CLASS_NAME() { } \ CLASS_NAME(const CLASS_NAME& other) {} \ CLASS_NAME& operator=(const CLASS_NAME& rhs) { return *this; } \ friend class Leggiero::Utility::DesignPattern::Singleton<CLASS_NAME>; #define LEGGIERO_DEFINE_SINGLETON_MEMBERS(CLASS_NAME) \ namespace Leggiero \ { \ namespace Utility \ { \ namespace DesignPattern \ { \ template<> \ CLASS_NAME *Singleton<CLASS_NAME>::ms_instance = nullptr; \ } \ } \ } #endif ======================= File: Engine/Common/Utility/Math/SimpleGeometry.h ======================= //////////////////////////////////////////////////////////////////////////////// // Math/SimpleGeometry.h (Leggiero - Utility) // // Simple Mathmatical Geometry Utilites //////////////////////////////////////////////////////////////////////////////// #ifndef __UTILITY__MATH__SIMPLE_GEOMETRY_H #define __UTILITY__MATH__SIMPLE_GEOMETRY_H // Standard Library #include <cmath> // Leggiero.Utility #include "SimpleMath.h" namespace Leggiero { namespace Utility { namespace Math { namespace FloatingPointLongConstants { constexpr long double kPi = 3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148L; constexpr long double kInversePi = 1.0L / kPi; constexpr long double kPiOver2 = kPi / 2.0L; constexpr long double kPiOver3 = kPi / 3.0L; constexpr long double kPiOver4 = kPi / 4.0L; constexpr long double kPiOver6 = kPi / 6.0L; constexpr long double kPiMul2 = kPi * 2.0L; constexpr long double kPiMul3 = kPi * 3.0L; constexpr long double kPiMul4 = kPi * 4.0L; constexpr long double kRad2Deg = 180.0L / kPi; constexpr long double kDeg2Rad = kPi / 180.0L; } template <typename T> class FloatingPointSimpleGeometry { public: using ValueType = T; public: // Constants static constexpr T kPi = static_cast<T>(FloatingPointLongConstants::kPi); static constexpr T kInversePi = static_cast<T>(FloatingPointLongConstants::kInversePi); static constexpr T kPiOver2 = static_cast<T>(FloatingPointLongConstants::kPiOver2); static constexpr T kPiOver3 = static_cast<T>(FloatingPointLongConstants::kPiOver3); static constexpr T kPiOver4 = static_cast<T>(FloatingPointLongConstants::kPiOver4); static constexpr T kPiOver6 = static_cast<T>(FloatingPointLongConstants::kPiOver6); static constexpr T kPiMul2 = static_cast<T>(FloatingPointLongConstants::kPiMul2); static constexpr T kPiMul3 = static_cast<T>(FloatingPointLongConstants::kPiMul3); static constexpr T kPiMul4 = static_cast<T>(FloatingPointLongConstants::kPiMul4); static constexpr T kRad2Deg = static_cast<T>(FloatingPointLongConstants::kRad2Deg); static constexpr T kDeg2Rad = static_cast<T>(FloatingPointLongConstants::kDeg2Rad); public: static constexpr T Rad2Deg(T radian) { return radian * kRad2Deg; } static constexpr T Deg2Rad(T degree) { return degree * kDeg2Rad; } static T WrapAnglePi(T angle) { return Math::WrapMinMax<T>(angle, -kPi, kPi); } static T WrapAngle2Pi(T angle) { return Math::WrapMinMax<T>(angle, 0, kPiMul2); } static T OppositeAngle(T angle) { return WrapAnglePi(angle + kPi); } static T DeltaAngle(T angleTo, T angleFrom) { if (angleFrom > angleTo) { T delta = angleFrom - angleTo; if (delta > kPi) { return angleTo + kPiMul2 - angleFrom; } return -delta; } else { T delta = angleTo - angleFrom; if (delta > kPi) { return -(angleFrom + kPiMul2 - angleTo); } return delta; } } inline T AzimuthPi(T x, T y) { constexpr T kAxisEpsilon = static_cast<T>(0.00000000000001L); if (x > -kAxisEpsilon && x < kAxisEpsilon) { if (y >= static_cast<T>(0.0)) { return kPiOver2; } return -kPiOver2; } return static_cast<T>(std::atan2l(y, x)); } }; } namespace Mathd { constexpr double kPi = Math::FloatingPointSimpleGeometry<double>::kPi; constexpr double kInversePi = static_cast<double>(Math::FloatingPointLongConstants::kInversePi); constexpr double kPiOver2 = static_cast<double>(Math::FloatingPointLongConstants::kPiOver2); constexpr double kPiOver3 = static_cast<double>(Math::FloatingPointLongConstants::kPiOver3); constexpr double kPiOver4 = static_cast<double>(Math::FloatingPointLongConstants::kPiOver4); constexpr double kPiOver6 = static_cast<double>(Math::FloatingPointLongConstants::kPiOver6); constexpr double kPiMul2 = static_cast<double>(Math::FloatingPointLongConstants::kPiMul2); constexpr double kPiMul3 = static_cast<double>(Math::FloatingPointLongConstants::kPiMul3); constexpr double kPiMul4 = static_cast<double>(Math::FloatingPointLongConstants::kPiMul4); constexpr double kRad2Deg = static_cast<double>(Math::FloatingPointLongConstants::kRad2Deg); constexpr double kDeg2Rad = static_cast<double>(Math::FloatingPointLongConstants::kDeg2Rad); constexpr double Rad2Deg(double radian) { return radian * kRad2Deg; } constexpr double Deg2Rad(double degree) { return degree * kDeg2Rad; } inline double WrapAnglePi(double angle) { return Math::WrapMinMax<double>(angle, -kPi, kPi); } inline double WrapAngle2Pi(double angle) { return Math::WrapMinMax<double>(angle, 0, kPiMul2); } inline double OppositeAngle(double angle) { return WrapAnglePi(angle + kPi); } inline double DeltaAngle(double angleTo, double angleFrom) { if (angleFrom > angleTo) { double delta = angleFrom - angleTo; if (delta > kPi) { return angleTo + kPiMul2 - angleFrom; } return -delta; } else { double delta = angleTo - angleFrom; if (delta > kPi) { return -(angleFrom + kPiMul2 - angleTo); } return delta; } } inline double AzimuthPi(double x, double y) { constexpr double kAxisEpsilon = 0.000000000001; if (x > -kAxisEpsilon && x < kAxisEpsilon) { if (y >= 0.0) { return kPiOver2; } return -kPiOver2; } return std::atan2(y, x); } } namespace Mathf { constexpr float kPi = static_cast<float>(Math::FloatingPointLongConstants::kPi); constexpr float kInversePi = static_cast<float>(Math::FloatingPointLongConstants::kInversePi); constexpr float kPiOver2 = static_cast<float>(Math::FloatingPointLongConstants::kPiOver2); constexpr float kPiOver3 = static_cast<float>(Math::FloatingPointLongConstants::kPiOver3); constexpr float kPiOver4 = static_cast<float>(Math::FloatingPointLongConstants::kPiOver4); constexpr float kPiOver6 = static_cast<float>(Math::FloatingPointLongConstants::kPiOver6); constexpr float kPiMul2 = static_cast<float>(Math::FloatingPointLongConstants::kPiMul2); constexpr float kPiMul3 = static_cast<float>(Math::FloatingPointLongConstants::kPiMul3); constexpr float kPiMul4 = static_cast<float>(Math::FloatingPointLongConstants::kPiMul4); constexpr float kRad2Deg = static_cast<float>(Math::FloatingPointLongConstants::kRad2Deg); constexpr float kDeg2Rad = static_cast<float>(Math::FloatingPointLongConstants::kDeg2Rad); constexpr float Rad2Deg(float radian) { return radian * kRad2Deg; } constexpr float Deg2Rad(float degree) { return degree * kDeg2Rad; } inline float WrapAnglePi(float angle) { return Math::WrapMinMax<float>(angle, -kPi, kPi); } inline float WrapAngle2Pi(float angle) { return Math::WrapMinMax<float>(angle, 0, kPiMul2); } inline float OppositeAngle(float angle) { return WrapAnglePi(angle + kPi); } inline float DeltaAngle(float angleTo, float angleFrom) { if (angleFrom > angleTo) { float delta = angleFrom - angleTo; if (delta > kPi) { return angleTo + kPiMul2 - angleFrom; } return -delta; } else { float delta = angleTo - angleFrom; if (delta > kPi) { return -(angleFrom + kPiMul2 - angleTo); } return delta; } } inline float AzimuthPi(float x, float y) { constexpr float kAxisEpsilon = 0.0000001f; if (x > -kAxisEpsilon && x < kAxisEpsilon) { if (y >= 0.0f) { return kPiOver2; } return -kPiOver2; } return std::atan2f(y, x); } } namespace Math { } } } #endif ======================= File: Engine/Modules/LUI/Rendering/UIRenderer.h ======================= //////////////////////////////////////////////////////////////////////////////// // Rendering/UIRenderer.h (Leggiero/Modules - LegacyUI) // // UI Renderer //////////////////////////////////////////////////////////////////////////////// #ifndef __LM_LUI__RENDERING__UI_RENDERER_H #define __LM_LUI__RENDERING__UI_RENDERER_H // Standard Library #include <memory> // External Library #include <glm/glm.hpp> // Leggiero.LegacyUI #include "../Common/UICommonTypes.h" namespace Leggiero { namespace LUI { // Forward Declarations class UIManager; class UIObject; namespace Shaders { class UIColorPrimitiveShader; class UITextureColorShader; class UITextureBlurShader; } // UI Renderer class UIRenderer { public: UIRenderer(std::shared_ptr<UIManager> manager, std::shared_ptr<Shaders::UIColorPrimitiveShader> colorShader, std::shared_ptr<Shaders::UITextureColorShader> textureShader, std::shared_ptr<Shaders::UITextureBlurShader> blurShader); virtual ~UIRenderer(); public: void Render(); public: void SetScreenTransform(const glm::mat4 &projection, const glm::mat4 &view, bool isInitializeModel = true); void SetColorModification(float hShift = 0.0f, float sMultifly = 1.0f, float sAdjust = 0.0f, float lMultifly = 1.0f, float lAdjust = 0.0f); public: std::shared_ptr<Shaders::UIColorPrimitiveShader> GetColorSimpleShader() const { return m_colorSimpleShader; } std::shared_ptr<Shaders::UITextureColorShader> GetTextureColorShader() const { return m_textureColorShader; } std::shared_ptr<Shaders::UITextureBlurShader> GetTextureBlurShader() const { return m_textureBlurShader; } public: float GetColorHShift() const { return m_colorModifyHShift; } float GetColorSMultiply() const { return m_colorModifySMultiply; } float GetColorSAdjust() const { return m_colorModifySAdjust; } float GetColorLMultiply() const { return m_colorModifyLMultiply; } float GetColorLAdjust() const { return m_colorModifyLAdjust; } protected: void _RenderObject(std::shared_ptr<UIObject> renderingObject, const UIVector2D &parentalOffset, float effectiveAlpha); protected: std::weak_ptr<UIManager> m_renderingUIManager; std::shared_ptr<Shaders::UIColorPrimitiveShader> m_colorSimpleShader; std::shared_ptr<Shaders::UITextureColorShader> m_textureColorShader; std::shared_ptr<Shaders::UITextureBlurShader> m_textureBlurShader; protected: float m_colorModifyHShift; float m_colorModifySMultiply; float m_colorModifySAdjust; float m_colorModifyLMultiply; float m_colorModifyLAdjust; }; } } #endif ======================= File: Engine/Modules/Task/_Internal/_ConcreteTaskManager.h ======================= //////////////////////////////////////////////////////////////////////////////// // _Internal/_ConcreteTaskManager.h (Leggiero/Modules - Task) // // Concrete Task Manager Component Class Definition //////////////////////////////////////////////////////////////////////////////// #ifndef __LM_TASK___INTERNAL___CONCRETE_TASK_MANAGER_H #define __LM_TASK___INTERNAL___CONCRETE_TASK_MANAGER_H // Leggiero.Basic #include <Basic/LeggieroBasic.h> // Standard Library #include <atomic> #include <memory> #include <unordered_map> #include <set> #include <vector> // External Library #include <concurrentqueue/concurrentqueue.h> #include <pthread.h> // Leggiero.Engine #include <Engine/Application/GameProcessAnchorObserver.h> // Leggiero.Application #include <Application/SystemEventObserver.h> // Leggiero.Utility #include <Utility/Threading/ManagedThreadPrimitives.h> // Leggiero.Task #include "../TaskManagerComponent.h" namespace Leggiero { // Forward Declaration namespace Application { class ApplicationComponent; } namespace Task { namespace _Internal { // Concrete Task Manager Class to Implement Separated Interface class ConcreteTaskManager : public TaskManagerComponent , public Application::IApplicationEventObserver , public Engine::GameProcessAnchorObserver::IAfterFrameHandler { public: ConcreteTaskManager(); virtual ~ConcreteTaskManager(); public: // EngineComponent // Initialize the Component virtual void InitializeComponent(Engine::GameProcessAnchor *gameAnchor) override; // Safely Shutdown Component virtual void ShutdownComponent() override; // Get type Id list of dependent modules needed by this component virtual const std::vector<EngineModuleIdType> &GetDependentModules() const override; // Get type Id list of dependent components needed by this component virtual const std::vector<EngineComponentIdType> &GetDependentComponents() const override; // Inject Dependency to the Component. // All dependency injections will be done before the initialization. virtual void InjectDependency(EngineComponentIdType componentId, EngineComponent *dependentComponent) override; public: // ITaskManagerSystemFunctions virtual void AttachSubSystem(std::shared_ptr<ITaskSubSystem> subSystem) override; virtual void AddGeneralWorkerCapability(TaskCapabilityType capabilities) override; virtual void RequestExecution(TaskExecutionEntry *execution) override; virtual void RequestDelayedExecution(TaskExecutionEntry *execution, SchedulingClock::duration delay) override; virtual void ReleaseExecution(TaskExecutionEntry *execution) override; public: // TaskManagerComponent virtual bool ExecuteTask(std::shared_ptr<ITask> task) override; public: // Observers virtual void OnGoToBackground() override; virtual void OnReturnFromBackground() override; virtual void GameProcess_OnAfterFrame(GameFrameNumberType frameNumber) override; protected: // Platform std::shared_ptr<ITaskProcessor> _CreateGeneralProcessor(); protected: TaskExecutionEntry *_RetainExecution(); void _DispatchExecution(TaskExecutionEntry *execution); protected: Application::ApplicationComponent *m_appComponentCopy; Engine::GameProcessAnchor *m_gameAnchor; moodycamel::ConcurrentQueue<TaskExecutionEntry *> m_executionEntryPool; std::vector<std::shared_ptr<ITaskSubSystem> > m_subSystems; protected: TaskCapabilityType m_generalTaskCapability; std::vector<std::shared_ptr<ITaskProcessor> > m_taskProcessorHolder; std::vector<TaskCapabilityType> m_capabilityOnlyList; std::unordered_map<TaskCapabilityType, ITaskProcessor *> m_capabilityProcessorMap; void _InitializeProcessors(); void _FinalizeProcessors(); void _RegisterProcessor(std::shared_ptr<ITaskProcessor> processor); ITaskProcessor *_GetTaskProcessor(TaskCapabilityType capability); protected: // Realtime Scheduler static constexpr size_t kRealtimeScheduleMaxBatchCount = 1024; moodycamel::ConcurrentQueue<TaskExecutionEntry *> m_realtimeWaitingQueue; std::atomic_bool m_isRealtimeScheduling; TaskExecutionEntry *m_realtimeSchedulingBuffer[kRealtimeScheduleMaxBatchCount]; void _HintRealtimeSchedule(); void _RealtimeSchedule(); protected: moodycamel::ConcurrentQueue<TaskExecutionEntry *> m_conditionWaitingQueueRealtime; moodycamel::ConcurrentQueue<TaskExecutionEntry *> m_conditionWaitingQueueShortTerm; moodycamel::ConcurrentQueue<TaskExecutionEntry *> m_conditionWaitingQueueLongTerm; void _ProcessConditionWaitingQueue(moodycamel::ConcurrentQueue<TaskExecutionEntry *> &queue); std::atomic_bool m_conditionWaitingQueueProcessing; std::vector<TaskExecutionEntry *> m_conditionWaitingProcessBuffer; protected: // Waiting Queues struct SchedulingQueueEntry { public: SchedulingClock::duration minimumWaiting; moodycamel::ConcurrentQueue<TaskExecutionEntry *> queue; pthread_t schedulingThread; ConcreteTaskManager *owner; int queueIndex; std::vector<TaskExecutionEntry *> queueProcessingBuffer; std::vector<TaskExecutionEntry *> queueProcessingNowBuffer; }; std::vector<SchedulingQueueEntry *> m_schedulingQueues; int m_schedulingQueuesCount; std::atomic_bool m_schedulerRunning; std::atomic_bool m_schedulerPause; int m_conditionCheckShortTermIndex; int m_conditionCheckLongTermIndex; Utility::Threading::SafePthreadLock m_queuesPauseMutex; Utility::Threading::SafePthreadConditionVariable m_queuesPauseCond; void _InitializeSchedulingQueues(); void _FinalizeSchedulingQueues(); void _SchedulingQueueThreadFunction(SchedulingQueueEntry &queueEntry); void _DoWaitingQueueScheduling(int queueIndex, SchedulingQueueEntry &queueEntry); static void *_SchedulingQueueThreadStartHelper(void *threadEntry); void _EnqueueWaitingExecution(TaskExecutionEntry *execution); }; } } } #endif ======================= File: Engine/Modules/Font/Common/MultiPageFontSetting.h ======================= //////////////////////////////////////////////////////////////////////////////// // Common/MultiPageFontSetting.h (Leggiero/Modules - Font) // // Font class definition for typesetting with multi-language pages setting //////////////////////////////////////////////////////////////////////////////// #ifndef __LM_FONT__COMMON__MULTI_PAGE_FONT_SETTING_H #define __LM_FONT__COMMON__MULTI_PAGE_FONT_SETTING_H // Standard Library #include <memory> #include <tuple> #include <vector> // Leggiero.Basic #include <Basic/LeggieroBasic.h> // Leggiero.Font #include "FontTypes.h" namespace Leggiero { namespace Font { // Forward Declaration class IFontFace; // Font class definition for multiple language pages class MultiPageFontSetting { public: // Single font setting to be applied struct FontSetting { public: std::shared_ptr<IFontFace> face; float baselineOffsetRatio; float scaleMultiply; float horizontalRatioMultiply; bool isForceBold; bool isForceItalic; bool isForceMonospacing; float monospacingWidthRatio; bool isPreferredForTofu; bool isNeedRenderingCheck; //note: rendering check recommended for (codepoint >= 0xAC00 && codepoint < 0xD7A4) range(Hangul Syllables), due to for weired table of some fonts including Godo public: bool IsValid() const { return (bool)face; } public: FontSetting(std::shared_ptr<IFontFace> face, float baselineOffsetRatio = 0.0f, float scaleMultiply = 1.0f, float horizontalRatioMultiply = 1.0f, bool isForceBold = false, bool isForceItalic = false, bool isForceMonospacing = false, float monospacingWidthRatio = 0.0f, bool isPreferredForTofu = false, bool isNeedRenderingCheck = false) : face(face), baselineOffsetRatio(baselineOffsetRatio), scaleMultiply(scaleMultiply), horizontalRatioMultiply(horizontalRatioMultiply) , isForceBold(isForceBold), isForceItalic(isForceItalic), isForceMonospacing(isForceMonospacing), monospacingWidthRatio(monospacingWidthRatio) , isPreferredForTofu(isPreferredForTofu), isNeedRenderingCheck(isNeedRenderingCheck) { } public: static const FontSetting kInvalid; }; // Range of page struct PageRange { public: GlyphCodePointType start; GlyphCodePointType finish; public: bool IsCodePointInRange(GlyphCodePointType codepoint) const { return ((codepoint >= start) && (codepoint <= finish)); } public: PageRange(GlyphCodePointType start, GlyphCodePointType finish) : start(start), finish(finish) { } PageRange(const PageRange &other) : start(other.start), finish(other.finish) { } PageRange(PageRange &&other) : start(other.start), finish(other.finish) { } public: static const PageRange kAll; static const PageRange kNothing; }; public: FontSetting GetSettingForGlyph(GlyphCodePointType codepoint) const; FontSetting GetTofuSetting() const; void RegisterSetting(const PageRange &applyingRange, const FontSetting &setting); protected: std::vector<std::tuple<PageRange, FontSetting> > m_fontSettings; }; } } #endif ======================= File: Engine/Platform/Platform.WinPC/Window/WindowCreateParam.h ======================= <gh_stars>10-100 //////////////////////////////////////////////////////////////////////////////// // Window/WindowCreateParam.h (Leggiero - Platform.WinPC) // // Window Create Parameter Structure Definition //////////////////////////////////////////////////////////////////////////////// #pragma once // Leggiero.Basic #include <Basic/LeggieroBasic.h> // Leggiero.Platform.WinPC #include "../WindowsCommon.h" namespace Leggiero { namespace Platform { namespace Windows { // Structure contains window creation option struct WindowCreateParam { HINSTANCE hInstance; HWND hWndParent; LPCTSTR className; LPCTSTR windowName; int nCmdShow; LPCTSTR menuName; HMENU hMenu; UINT classStyle; DWORD windowStyle; int x; int y; int width; int height; bool isSetContentsSize; HBRUSH hbrBackground; HICON hIcon; HICON hIconSm; HCURSOR hCursor; LPVOID lpParam; WindowCreateParam() : hInstance(NULL) , hWndParent(NULL) , className(L"LeggieroDefaultWin") , windowName(L"") , nCmdShow(SW_SHOWNORMAL) , menuName(NULL), hMenu(NULL) , classStyle(0), windowStyle(WS_OVERLAPPEDWINDOW) , x(CW_USEDEFAULT), y(CW_USEDEFAULT) , width(CW_USEDEFAULT), height(CW_USEDEFAULT), isSetContentsSize(false) , hbrBackground(NULL) , hIcon(NULL), hIconSm(NULL) , hCursor(NULL) , lpParam(NULL) { } }; } } } ======================= File: Engine/Modules/LUI/Description/UIDescriptionReader.h ======================= <filename>Engine/Modules/LUI/Description/UIDescriptionReader.h //////////////////////////////////////////////////////////////////////////////// // Description/UIDescriptionReader.h (Leggiero/Modules - LegacyUI) // // Parsing utility function for UI Description //////////////////////////////////////////////////////////////////////////////// #ifndef __LM_LUI__DESCRIPTION__UI_DESCRIPTION_READER_H #define __LM_LUI__DESCRIPTION__UI_DESCRIPTION_READER_H // Standard Library #include <memory> // Leggiero.LegacyUI #include "UIDescriptionTypes.h" #include "UIDescription.h" namespace Leggiero { namespace LUI { namespace Description { namespace Reader { namespace XML { // Read object name from given XML Element VariableNameType ReadObjectNameFromElement(ParsingXMLElementType *elem); // Read a description object from given XML Element std::shared_ptr<IDescriptionObject> ReadObjectFromElement(ParsingXMLElementType *elem, DescriptionManager &loadingManager); } } } } } #endif ======================= File: Tools/ProjectCreator/Template/Project/Sources/Proj/_UIBaseScene/Scene/DefaultUIScene/DefaultUIScene.h ======================= //////////////////////////////////////////////////////////////////////////////// // Scene/DefaultUIScene/DefaultUIScene.h (${{ProgramName}} - ${{ProgramName}}) // // Default Game Scene with UI Functionality from Leggiero Legacy UI //////////////////////////////////////////////////////////////////////////////// #ifndef __${{ProgramName-Upper}}__SCENE__DEFAULT_UI_SCENE__DEFAULT_UI_SCENE_H #define __${{ProgramName-Upper}}__SCENE__DEFAULT_UI_SCENE__DEFAULT_UI_SCENE_H // Leggiero.Basic #include <Basic/LeggieroBasic.h> // Leggiero.LegacyUI #include <LUI/Scene/UISceneBase.h> // ${{ProgramName}} #include "../SceneIds.h" namespace ${{ProgramName}} { namespace DefaultUISceneStuffs { // Empty Default Game Scene class DefaultUIScene : public Leggiero::LUI::UISceneBase { public: DefaultUIScene(Leggiero::Toolbox::Scene::IGameSceneContext *ownerContext, Leggiero::IGame *game); virtual ~DefaultUIScene(); public: // IGameScene // Get Id of the Scene virtual Leggiero::Toolbox::Scene::GameSceneIdType GetSceneId() const override { return SceneIds::kDefault; } protected: // UISceneBase virtual void _InitializeUIContents() override; virtual void _FinalizeUIContents() override; virtual void _SetUIBeforeEnterFrame() override; virtual void _UnSetUIAfterExitFrame() override; virtual void _ProcessFrameLogic(Leggiero::GameTimeClockType::time_point frameReferenceTime, Leggiero::GameTimeClockType::duration frameInterval) override; }; } } #endif ======================= File: Engine/Modules/LUI/Rendering/UITextureManager.h ======================= <gh_stars>10-100 //////////////////////////////////////////////////////////////////////////////// // Rendering/UITextureManager.h (Leggiero/Modules - LegacyUI) // // Manager class to manage texture resources in UI system //////////////////////////////////////////////////////////////////////////////// #ifndef __LM_LUI__RENDERING__UI_TEXTURE_MANAGER_H #define __LM_LUI__RENDERING__UI_TEXTURE_MANAGER_H // Standard Library #include <memory> #include <unordered_map> // Leggiero.Utility #include <Utility/Threading/ManagedThreadPrimitives.h> // Leggiero.LegacyUI #include "../Common/UICommonTypes.h" #include "UITexture.h" namespace Leggiero { namespace LUI { // Forward Declaration class IUIAssetLoader; // Texture Manager class UITextureManager { public: UITextureManager(IUIAssetLoader &assetLoader); virtual ~UITextureManager(); private: UITextureManager() = delete; public: std::shared_ptr<UICachedTexture> GetTexture(const UITextureNameType &textureName); void PreLoadTexture(const UITextureNameType &textureName); void RegisterExternalTexture(const UITextureNameType &textureName, std::shared_ptr<Graphics::GLTextureResource> texture, std::shared_ptr<Graphics::TextureAtlasTable> atlasTable = nullptr); std::shared_ptr<UICachedTexture> GetCachedTexture(const UITextureNameType &savedTextureName); public: void ClearCache(); protected: std::shared_ptr<UICachedTexture> _LoadTexture(const UITextureNameType &textureName); protected: IUIAssetLoader &m_assetLoader; std::unordered_map<UITextureNameType, std::shared_ptr<UICachedTexture> > m_textureCache; Utility::Threading::SafePthreadRWLock m_cacheLock; }; } } #endif ======================= File: Engine/Modules/Graphics/_Internal/_GraphicsModuleInternalState.h ======================= <gh_stars>10-100 //////////////////////////////////////////////////////////////////////////////// // _Internal/_GraphicsModuleInternalState.h (Leggiero/Modules - Graphics) // * DO NOT directly include this header file outside of Graphics project // // Internal Shared States for Graphics Module //////////////////////////////////////////////////////////////////////////////// #ifndef __LM_GRAPHICS___INTERNAL___GRAPHICS_MODULE_INTERNAL_STATE_H #define __LM_GRAPHICS___INTERNAL___GRAPHICS_MODULE_INTERNAL_STATE_H namespace Leggiero { // Forward Declarations namespace Utility { namespace Threading { class SafePthreadLock; } } namespace Graphics { namespace _Internal { namespace Synchronization { Utility::Threading::SafePthreadLock &GetTextureNameCreationLock(); } } } } #endif ======================= File: Engine/Modules/Crypto/OpenSSLCrypto/OpenSSLUtility.h ======================= <gh_stars>10-100 //////////////////////////////////////////////////////////////////////////////// // OpenSSLCrypto/OpenSSLUtility.h (Leggiero/Modules - Crypto) // // OpenSSL based cryptography utility // Recommended for internal use //////////////////////////////////////////////////////////////////////////////// #ifndef __LM_CRYPTO__OPENSSLCRYPTO__OPENSSL_UTILITY_H #define __LM_CRYPTO__OPENSSLCRYPTO__OPENSSL_UTILITY_H namespace Leggiero { namespace Crypto { namespace OpenSSL { void InitializeOpenSSLCryptoSystem(); void FinalizeOpenSSLCryptoSystem(); } } } #endif ======================= File: Engine/Modules/Sound/OpenALBackend/OpenALSoundPlayingContext.h ======================= <filename>Engine/Modules/Sound/OpenALBackend/OpenALSoundPlayingContext.h //////////////////////////////////////////////////////////////////////////////// // OpenALBackend/OpenALSoundPlayingContext.h (Leggiero/Modules - Sound) // // Base Sound Playing Context in OpenAL Backend //////////////////////////////////////////////////////////////////////////////// #ifndef __LM_SOUND__OPENAL_BACKEND__OPENAL_SOUND_PLAYING_CONTEXT_H #define __LM_SOUND__OPENAL_BACKEND__OPENAL_SOUND_PLAYING_CONTEXT_H // Standard Library #include <atomic> #include <queue> #include <memory> #include <vector> // External Library #include <OpenAL.h> // Leggiero.Utility #include <Utility/Object/PointerHolder.h> #include <Utility/Sugar/NonCopyable.h> // Leggiero.Sound #include "../Common/SoundTypes.h" #include "../Common/ISoundPlayingHandle.h" namespace Leggiero { namespace Sound { // Forward Declaration class ISoundProvider; namespace OpenAL { // Forward Declaration class OpenALSoundMixer; // OpenAL Sound Playing Context class OpenALSoundPlayingContext : public ISoundPlayingHandle , public std::enable_shared_from_this<OpenALSoundPlayingContext> , private Utility::SyntacticSugar::NonCopyable { public: friend class OpenALSoundMixer; using MixerClass = OpenALSoundMixer; public: // Platform Dependent Settings static size_t g_bufferSize; public: virtual ~OpenALSoundPlayingContext(); public: OpenALSoundPlayingContext(std::shared_ptr<ISoundProvider> soundProvider, std::shared_ptr<Utility::Object::PointerHolder> mixerHolder, ALuint source, ALuint buffers[], size_t bufferCount, bool isStartImmediately = true, float volume = 1.0f, bool isPauseAfterFinish = false); private: OpenALSoundPlayingContext() = delete; public: // ISoundPlayingHandle virtual bool IsFinished() const override; virtual void Stop() override; virtual bool IsPaused() const override { return m_isPaused; } virtual void Pause() override; virtual void Resume() override; virtual SampleNumberType GetCurrentPosition() override { return GetLastQueuedSamplePosition(); } virtual bool Seek(SampleNumberType samplePosition) override; virtual float GetVolume() const override { return m_volume; } virtual void SetVolume(float volume) override; public: SampleNumberType GetLastQueuedSamplePosition() const { return m_lastSampleNumber; } SampleNumberType GetLastProcessedSamplePosition() const { return m_lastProcessedSamplePosition; } bool IsPlayUpdateStarted() const { return m_isPlayUpdateStarted; } bool IsSeekApplied() const { return m_isSeekApplied; } void SetWillPauseAfterFinish(bool isPauseAfterFinish) { m_isPauseAfterFinish = isPauseAfterFinish; } bool IsWillPauseAfterFinish() const { return m_isPauseAfterFinish; } protected: void _Update(std::vector<ALuint> &releasingBuffers); void _CancelBufferUsage(); protected: std::shared_ptr<ISoundProvider> m_soundProvider; bool m_isPlayFinished; bool m_isAllDataQueued; SampleNumberType m_lastSampleNumber; bool m_isPaused; bool m_isPauseAfterFinish; std::atomic_bool m_isSourceReturned; ALuint m_source; std::vector<ALuint> m_reservedBuffers; size_t m_bufferCount; std::queue<SampleNumberType> m_bufferSamples; SampleNumberType m_lastProcessedSamplePosition; float m_volume; bool m_isVolumeChangeRequested; std::weak_ptr<Utility::Object::PointerHolder> m_mixerHolder; protected: bool m_isPlayUpdateStarted; bool m_isSeekApplied; }; } } } #endif ======================= File: Engine/Modules/LUI/Component/UISizeSubComponent.h ======================= //////////////////////////////////////////////////////////////////////////////// // Component/UISizeSubComponent.h (Leggiero/Modules - LegacyUI) // // Sub-Component to process size information in layouting //////////////////////////////////////////////////////////////////////////////// #ifndef __LM_LUI__COMPONENT__UI_SIZE_SUB_COMPONENT_H #define __LM_LUI__COMPONENT__UI_SIZE_SUB_COMPONENT_H // Leggiero.Basic #include <Basic/LeggieroBasic.h> // Standard Library #include <memory> // Leggiero.LegacyUI #include "../Common/UICommonTypes.h" #include "IUIComponent.h" namespace Leggiero { namespace LUI { // Forward Declarations class UIObject; class UILayoutComponent; // Base Interface for UI Size Sub-Component class IUISizeSubComponent { public: IUISizeSubComponent() { } virtual ~IUISizeSubComponent() { } public: virtual UIElementSize CalculateSize() = 0; virtual std::shared_ptr<IUISizeSubComponent> Clone() const = 0; virtual void SetParentOfOwnerObject(const UIObject &parentObject) { } virtual void SetNoParentOfOwnerObject() { } virtual bool HasParentDependency() const { return false; } virtual bool HasChildrenDependency() const { return false; } virtual bool IsParentDependencySolved() const { return false; } }; // Targeting specific owner object class IOwnerTargetingSizeSubComponent { public: IOwnerTargetingSizeSubComponent(const std::shared_ptr<UIObject> &targetObject) : m_targetObject(targetObject) { } virtual ~IOwnerTargetingSizeSubComponent() { } public: void ChangeTargetObject(std::shared_ptr<UIObject> targetObject) { m_targetObject = targetObject; } protected: std::weak_ptr<UIObject> m_targetObject; }; // Value-setted size class UIValuedSizeSubComponent : public IUISizeSubComponent { public: UIValuedSizeSubComponent(UICoordinateType width, UICoordinateType height); virtual ~UIValuedSizeSubComponent() { } public: virtual UIElementSize CalculateSize() override { return UIElementSize(m_width, m_height); } virtual std::shared_ptr<IUISizeSubComponent> Clone() const override; public: UICoordinateType GetWidth() const { return m_width; } UICoordinateType GetHeight() const { return m_height; } void SetWidth(UICoordinateType width) { m_width = width; } void SetHeight(UICoordinateType height) { m_height = height; } protected: UICoordinateType m_width; UICoordinateType m_height; }; // Size sub-component for an UI Object class UIObjectSizeSubComponent : public IUISizeSubComponent , public IOwnerTargetingSizeSubComponent { public: UIObjectSizeSubComponent(const std::shared_ptr<UIObject> &targetObject) : IOwnerTargetingSizeSubComponent(targetObject) { } virtual ~UIObjectSizeSubComponent() { } public: virtual UIElementSize CalculateSize() override; virtual std::shared_ptr<IUISizeSubComponent> Clone() const override; }; // Size sub-component for renderable class UIVisualSizeSubComponent : public IUISizeSubComponent , public IOwnerTargetingSizeSubComponent { public: UIVisualSizeSubComponent(const std::shared_ptr<UIObject> &targetObject); virtual ~UIVisualSizeSubComponent() { } public: virtual UIElementSize CalculateSize() override; virtual std::shared_ptr<IUISizeSubComponent> Clone() const override; }; // Size of parent class UIParentSizeSubComponent : public IUISizeSubComponent { public: UIParentSizeSubComponent(std::shared_ptr<UILayoutComponent> parentLayoutComponent = nullptr); virtual ~UIParentSizeSubComponent() { } public: virtual UIElementSize CalculateSize() override; virtual std::shared_ptr<IUISizeSubComponent> Clone() const override; virtual void SetParentOfOwnerObject(const UIObject &parentObject) override; virtual void SetNoParentOfOwnerObject() override; virtual bool HasParentDependency() const override { return true; } virtual bool IsParentDependencySolved() const override; protected: std::weak_ptr<UILayoutComponent> m_parentLayoutComponent; }; // Summation size of stacked children class UIChildrenStackSizeSubComponent : public IUISizeSubComponent , public IOwnerTargetingSizeSubComponent { public: UIChildrenStackSizeSubComponent(const std::shared_ptr<UIObject> &targetObject, bool isHorizontal); virtual ~UIChildrenStackSizeSubComponent() { } public: virtual UIElementSize CalculateSize() override; virtual std::shared_ptr<IUISizeSubComponent> Clone() const override; virtual bool HasChildrenDependency() const override { return true; } protected: bool m_isHorizontal; }; // Size modification decorator class ModifedSizeSubComponent : public IUISizeSubComponent { public: ModifedSizeSubComponent(std::shared_ptr<IUISizeSubComponent> original, UICoordinateType widthAdd = static_cast<UICoordinateType>(0.0f), UICoordinateType heightAdd = static_cast<UICoordinateType>(0.0f), UICoordinateRatioType widthMultiplier = static_cast<UICoordinateRatioType>(1.0f), UICoordinateRatioType heightMultiplier = static_cast<UICoordinateRatioType>(1.0f)); virtual ~ModifedSizeSubComponent() { } public: // IUISizeSubComponent virtual UIElementSize CalculateSize() override; virtual std::shared_ptr<IUISizeSubComponent> Clone() const override; virtual void SetParentOfOwnerObject(const UIObject &parentObject) override { m_original->SetParentOfOwnerObject(parentObject); } virtual void SetNoParentOfOwnerObject() override { m_original->SetNoParentOfOwnerObject(); } virtual bool HasParentDependency() const override { return m_original->HasParentDependency(); } virtual bool HasChildrenDependency() const override { return m_original->HasChildrenDependency(); } protected: std::shared_ptr<IUISizeSubComponent> m_original; UICoordinateType m_widthAdd; UICoordinateType m_heightAdd; UICoordinateRatioType m_widthMultiplier; UICoordinateRatioType m_heightMultiplier; }; } } #endif ======================= File: Engine/Common/Engine/Toolbox/ModuledGame/ModuledGame.h ======================= //////////////////////////////////////////////////////////////////////////////// // Toolbox/ModuledGame/ModuledGame.h (Leggiero - Engine) // // Provide Base Implemention for the Game as Composited Modules //////////////////////////////////////////////////////////////////////////////// #ifndef __ENGINE__TOOLBOX__MODULED_GAME__MODULED_GAME_H #define __ENGINE__TOOLBOX__MODULED_GAME__MODULED_GAME_H // Leggiero.Basic #include <Basic/LeggieroBasic.h> // Standard Library #include <map> #include <set> #include <vector> // Leggiero.Engine #include "../../Module/EngineModuleId.h" #include "../../Module/EngineComponentId.h" #include "../../Application/BaseGame.h" namespace Leggiero { // Forward Declarations class EngineModuleInterface; class EngineComponent; namespace Toolbox { namespace Game { // Module Composited Game Base Class class ModuledGame : public Engine::BaseGame { public: ModuledGame(); virtual ~ModuledGame(); protected: // IGameInitializer virtual void _InitializeGameEngineLibrary(IPlatformApplication *application) override; virtual void _FinalizeGameEngineLibrary() override; virtual void _AssembleGameEngineComponents(IPlatformApplication *application) override; virtual void _FinalizeGameEngineComponents() override; protected: void _InitializeModule(EngineModuleIdType moduleId, IPlatformApplication *application); void _RegisterEngineComponent(EngineComponent *component, bool isManagedByOther = false); protected: // Composition interface by each game // List ALL modules static std::map<EngineModuleIdType, EngineModuleInterface *> _ListAllModules(); virtual void _InitializeUsingModules(IPlatformApplication *application) = 0; virtual void _RegisterUsingComponents() = 0; private: std::map<EngineModuleIdType, EngineModuleInterface *> m_moduleInterfaceTable; std::vector<EngineModuleIdType> m_orderedModuleList; std::map<EngineModuleIdType, bool> m_moduleInitilizationTable; std::vector<EngineComponentIdType> m_orderedComponentList; std::set<EngineComponentIdType> m_unManagedComponentSet; }; } } } #endif ======================= File: Engine/Modules/Sound/Provider/BakedSoundProvider.h ======================= //////////////////////////////////////////////////////////////////////////////// // Provider/BakedSoundProvider.h (Leggiero/Modules - Sound) // // Pre-baked sound provider //////////////////////////////////////////////////////////////////////////////// #ifndef __LM_SOUND__PROVIDER__BAKED_SOUND_PROVIDER_H #define __LM_SOUND__PROVIDER__BAKED_SOUND_PROVIDER_H // Standard Library #include <functional> #include <memory> // Leggiero.Sound #include "ISoundProvider.h" namespace Leggiero { // Forward Declaration namespace Utility { namespace Data { class MemoryBuffer; } } namespace Sound { // Pre-baked sound data provider using in-memory buffer class BakedSoundProvider : public ISoundProvider { public: BakedSoundProvider(ISoundProvider &source, std::shared_ptr<Utility::Data::MemoryBuffer> buffer = nullptr, std::function<void(std::shared_ptr<Utility::Data::MemoryBuffer>)> bufferRelease = std::function<void(std::shared_ptr<Utility::Data::MemoryBuffer>)>()); virtual ~BakedSoundProvider(); private: // Prevent Creating of NULL Sound Provider BakedSoundProvider() = delete; public: // ISoundProvider virtual SampleFormat GetFormat() const override { return m_format; } virtual SamplingFrequencyType GetFrequency() const override { return m_frequency; } virtual size_t GetSampleLength() const override { return m_lengthInSample; } virtual float GetLengthInSecond() const override { return m_lengthInSecond; } virtual size_t FillSampleData(void *dataBuffer, size_t bufferSize, SampleNumberType startSample, SampleNumberType *outWrittenSamples = nullptr) override; public: bool IsValid() const { return m_isInitialized; } protected: bool m_isInitialized; SampleFormat m_format; SamplingFrequencyType m_frequency; size_t m_lengthInSample; float m_lengthInSecond; std::shared_ptr<Utility::Data::MemoryBuffer> m_buffer; std::function<void(std::shared_ptr<Utility::Data::MemoryBuffer>)> m_bufferRelease; }; } } #endif ======================= File: Engine/Modules/Font/Common/FontBackend.h ======================= //////////////////////////////////////////////////////////////////////////////// // Common/FontBackend.h (Leggiero/Modules - Font) // // Common definitions related to Backend Type //////////////////////////////////////////////////////////////////////////////// #ifndef __LM_FONT__COMMON__FONT_BACKEND_H #define __LM_FONT__COMMON__FONT_BACKEND_H namespace Leggiero { namespace Font { // Font Backend Engine Type enum class FontBackendType { kINVALID, kFreeType, }; } } #endif ======================= File: Engine/Common/Utility/Math/BitMath.h ======================= <reponame>LineGames/Leggiero<filename>Engine/Common/Utility/Math/BitMath.h //////////////////////////////////////////////////////////////////////////////// // Math/BitMath.h (Leggiero - Utility) // // Bit Manipulation Mathmatical Utilites //////////////////////////////////////////////////////////////////////////////// #ifndef __UTILITY__MATH__BIT_MATH_H #define __UTILITY__MATH__BIT_MATH_H // Standard Library #include <cmath> #include <cstdint> // External Library #if _MSC_VER &&!__INTEL_COMPILER #include <intrin.h> #endif namespace Leggiero { namespace Utility { namespace Math { template <typename ValueT> inline size_t PopCount(ValueT x) { // although there are some tricky algorithms like MIT HACKAM and etc.., lookup is the fastest(except CPU instruction). // https://gurmeet.net/puzzles/fast-bit-counting-routines/ static const size_t kNibbleBitCount[16] = { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4 }; size_t byteSize = sizeof(x); size_t bitCount = 0; for (size_t i = 0; i < byteSize; ++i) { bitCount += kNibbleBitCount[(x >> (i * 8)) & 15]; bitCount += kNibbleBitCount[(x >> (i * 8 + 4)) & 15]; } return bitCount; } template <> inline size_t PopCount(uint8_t x) { switch (x) { case 0: return 0; case 1: return 1; case 2: return 1; case 3: return 2; case 4: return 1; case 5: return 2; case 6: return 2; case 7: return 3; case 8: return 1; case 9: return 2; case 10: return 2; case 11: return 3; case 12: return 2; case 13: return 3; case 14: return 3; case 15: return 4; case 16: return 1; case 17: return 2; case 18: return 2; case 19: return 3; case 20: return 2; case 21: return 3; case 22: return 3; case 23: return 4; case 24: return 2; case 25: return 3; case 26: return 3; case 27: return 4; case 28: return 3; case 29: return 4; case 30: return 4; case 31: return 5; case 32: return 1; case 33: return 2; case 34: return 2; case 35: return 3; case 36: return 2; case 37: return 3; case 38: return 3; case 39: return 4; case 40: return 2; case 41: return 3; case 42: return 3; case 43: return 4; case 44: return 3; case 45: return 4; case 46: return 4; case 47: return 5; case 48: return 2; case 49: return 3; case 50: return 3; case 51: return 4; case 52: return 3; case 53: return 4; case 54: return 4; case 55: return 5; case 56: return 3; case 57: return 4; case 58: return 4; case 59: return 5; case 60: return 4; case 61: return 5; case 62: return 5; case 63: return 6; case 64: return 1; case 65: return 2; case 66: return 2; case 67: return 3; case 68: return 2; case 69: return 3; case 70: return 3; case 71: return 4; case 72: return 2; case 73: return 3; case 74: return 3; case 75: return 4; case 76: return 3; case 77: return 4; case 78: return 4; case 79: return 5; case 80: return 2; case 81: return 3; case 82: return 3; case 83: return 4; case 84: return 3; case 85: return 4; case 86: return 4; case 87: return 5; case 88: return 3; case 89: return 4; case 90: return 4; case 91: return 5; case 92: return 4; case 93: return 5; case 94: return 5; case 95: return 6; case 96: return 2; case 97: return 3; case 98: return 3; case 99: return 4; case 100: return 3; case 101: return 4; case 102: return 4; case 103: return 5; case 104: return 3; case 105: return 4; case 106: return 4; case 107: return 5; case 108: return 4; case 109: return 5; case 110: return 5; case 111: return 6; case 112: return 3; case 113: return 4; case 114: return 4; case 115: return 5; case 116: return 4; case 117: return 5; case 118: return 5; case 119: return 6; case 120: return 4; case 121: return 5; case 122: return 5; case 123: return 6; case 124: return 5; case 125: return 6; case 126: return 6; case 127: return 7; case 128: return 1; case 129: return 2; case 130: return 2; case 131: return 3; case 132: return 2; case 133: return 3; case 134: return 3; case 135: return 4; case 136: return 2; case 137: return 3; case 138: return 3; case 139: return 4; case 140: return 3; case 141: return 4; case 142: return 4; case 143: return 5; case 144: return 2; case 145: return 3; case 146: return 3; case 147: return 4; case 148: return 3; case 149: return 4; case 150: return 4; case 151: return 5; case 152: return 3; case 153: return 4; case 154: return 4; case 155: return 5; case 156: return 4; case 157: return 5; case 158: return 5; case 159: return 6; case 160: return 2; case 161: return 3; case 162: return 3; case 163: return 4; case 164: return 3; case 165: return 4; case 166: return 4; case 167: return 5; case 168: return 3; case 169: return 4; case 170: return 4; case 171: return 5; case 172: return 4; case 173: return 5; case 174: return 5; case 175: return 6; case 176: return 3; case 177: return 4; case 178: return 4; case 179: return 5; case 180: return 4; case 181: return 5; case 182: return 5; case 183: return 6; case 184: return 4; case 185: return 5; case 186: return 5; case 187: return 6; case 188: return 5; case 189: return 6; case 190: return 6; case 191: return 7; case 192: return 2; case 193: return 3; case 194: return 3; case 195: return 4; case 196: return 3; case 197: return 4; case 198: return 4; case 199: return 5; case 200: return 3; case 201: return 4; case 202: return 4; case 203: return 5; case 204: return 4; case 205: return 5; case 206: return 5; case 207: return 6; case 208: return 3; case 209: return 4; case 210: return 4; case 211: return 5; case 212: return 4; case 213: return 5; case 214: return 5; case 215: return 6; case 216: return 4; case 217: return 5; case 218: return 5; case 219: return 6; case 220: return 5; case 221: return 6; case 222: return 6; case 223: return 7; case 224: return 3; case 225: return 4; case 226: return 4; case 227: return 5; case 228: return 4; case 229: return 5; case 230: return 5; case 231: return 6; case 232: return 4; case 233: return 5; case 234: return 5; case 235: return 6; case 236: return 5; case 237: return 6; case 238: return 6; case 239: return 7; case 240: return 4; case 241: return 5; case 242: return 5; case 243: return 6; case 244: return 5; case 245: return 6; case 246: return 6; case 247: return 7; case 248: return 5; case 249: return 6; case 250: return 6; case 251: return 7; case 252: return 6; case 253: return 7; case 254: return 7; default: return 8; } } template <> inline size_t PopCount(uint16_t x) { #if _MSC_VER &&!__INTEL_COMPILER return __popcnt16(x); #else return PopCount<uint8_t>(static_cast<uint8_t>(x & 0xFF)) + PopCount<uint8_t>(static_cast<uint8_t>((x >> 8) & 0xFF)); #endif } template <> inline size_t PopCount(uint32_t x) { #if _MSC_VER &&!__INTEL_COMPILER return __popcnt(x); #else // Can we use __builtin_popcount? return PopCount<uint8_t>(static_cast<uint8_t>(x & 0xFF)) + PopCount<uint8_t>(static_cast<uint8_t>((x >> 8) & 0xFF)) + PopCount<uint8_t>(static_cast<uint8_t>((x >> 16) & 0xFF)) + PopCount<uint8_t>(static_cast<uint8_t>((x >> 24) & 0xFF)); #endif } template <> inline size_t PopCount(uint64_t x) { #if _MSC_VER &&!__INTEL_COMPILER return static_cast<size_t>(__popcnt64(x)); #else // Can we use __builtin_popcountll? return PopCount<uint8_t>(static_cast<uint8_t>(x & 0xFF)) + PopCount<uint8_t>(static_cast<uint8_t>((x >> 8) & 0xFF)) + PopCount<uint8_t>(static_cast<uint8_t>((x >> 16) & 0xFF)) + PopCount<uint8_t>(static_cast<uint8_t>((x >> 24) & 0xFF)) + PopCount<uint8_t>(static_cast<uint8_t>((x >> 32) & 0xFF)) + PopCount<uint8_t>(static_cast<uint8_t>((x >> 40) & 0xFF)) + PopCount<uint8_t>(static_cast<uint8_t>((x >> 48) & 0xFF)) + PopCount<uint8_t>(static_cast<uint8_t>((x >> 56) & 0xFF)); #endif } template <> inline size_t PopCount(int8_t x) { union { int8_t source; uint8_t target; } a = { x }; return PopCount<uint8_t>(a.target); } template <> inline size_t PopCount(int16_t x) { union { int16_t source; uint16_t target; } a = { x }; return PopCount<uint16_t>(a.target); } template <> inline size_t PopCount(int32_t x) { union { int32_t source; uint32_t target; } a = { x }; return PopCount<uint32_t>(a.target); } template <> inline size_t PopCount(int64_t x) { union { int64_t source; uint64_t target; } a = { x }; return PopCount<uint64_t>(a.target); } } } } #endif ======================= File: Engine/Platform/Platform.WinPC/WindowsCommon.h ======================= //////////////////////////////////////////////////////////////////////////////// // WindowsCommon.h (Leggiero - Platform.WinPC) // // Common Including Header to use Windows Platform(API) Stuffs //////////////////////////////////////////////////////////////////////////////// #pragma once // Exclude rarely-used stuff from Windows headers #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif // Windows Header Files: #include <windows.h> #include <windowsx.h> #include <tchar.h> ======================= File: Engine/Modules/LUI/Rendering/UIShapeRect.h ======================= //////////////////////////////////////////////////////////////////////////////// // Rendering/UIShapeRect.h (Leggiero/Modules - LegacyUI) // // UI Renderable Rectangular Shape //////////////////////////////////////////////////////////////////////////////// #ifndef __LM_LUI__RENDERING__UI_SHAPE_RECT_H #define __LM_LUI__RENDERING__UI_SHAPE_RECT_H // Leggiero.Basic #include <Basic/LeggieroBasic.h> // Standard Library #include <memory> #include <vector> // External Library #include <GLES3.h> // Leggiero.Graphics #include <Graphics/Common/GLColor.h> #include <Graphics/Shader/CommonGLVertexType.h> // Leggiero.LegacyUI #include "../Common/UICommonTypes.h" #include "../Common/UITransform.h" #include "../Common/UISizeSettable.h" #include "IUIRenderingShape.h" #include "UIClipping.h" namespace Leggiero { namespace LUI { // UI Rectangular Shape class UIShapeRect : public IUIRenderingShape , public IRectSizeSettable { public: UIShapeRect(UICoordinateType width, UICoordinateType height, const Graphics::GLByteARGB &color, UICoordinateType borderWidth = static_cast<UICoordinateType>(0.0f), const Graphics::GLByteARGB &borderColor = Graphics::GLByteARGB::kTransparent, ShapeBorderAlignType borderAlign = ShapeBorderAlignType::kCenter, UICoordinateType offsetX = static_cast<UICoordinateType>(0.0f), UICoordinateType offsetY = static_cast<UICoordinateType>(0.0f)); virtual ~UIShapeRect(); public: // IUIRenderingShape virtual void Render(const UIRenderer &renderer, IUITransform &effectiveTransform, const IUIClipping &effectiveClipping, float alpha) override; virtual UISimpleRectangular GetBoundingBox() override; public: void SetColor(const Graphics::GLByteARGB &color) { m_color = color; _UpdatePreCalculatedValues(); } void SetSize(UICoordinateType width, UICoordinateType height) { m_width = width; m_height = height; _UpdatePreCalculatedValues(); } virtual void SetUIWidgetRectSize(UICoordinateType width, UICoordinateType height) override { SetSize(width, height); } void SetOffset(UICoordinateType offsetX, UICoordinateType offsetY) { m_offsetX = offsetX; m_offsetY = offsetY; _UpdatePreCalculatedValues(); } void SetBorderWidth(UICoordinateType borderWidth) { m_borderWidth = borderWidth; _UpdatePreCalculatedValues(); } void SetBorderColor(const Graphics::GLByteARGB &color) { m_borderColor = color; _UpdatePreCalculatedValues(); } UICoordinateType GetWidth() const { return m_width; } UICoordinateType GetHeight() const { return m_height; } protected: virtual void _UpdatePreCalculatedValues(); protected: bool m_hasRect; UICoordinateType m_offsetX; UICoordinateType m_offsetY; UICoordinateType m_width; UICoordinateType m_height; Graphics::GLByteARGB m_color; bool m_hasBorder; UICoordinateType m_borderWidth; Graphics::GLByteARGB m_borderColor; ShapeBorderAlignType m_borderAlign; UICoordinateType m_borderOffset; UICoordinateType m_borderOffsetDouble; std::vector<Graphics::ColoredVertex> m_vertexBuffer; std::vector<GLushort> m_indexBuffer; }; } } #endif ======================= File: Engine/Modules/Graphics/Texture/RuntimeTextureAtlasEntry.h ======================= <reponame>LineGames/Leggiero //////////////////////////////////////////////////////////////////////////////// // Texture/RuntimeTextureAtlasEntry.h (Leggiero/Modules - Graphics) // // Each sub-texture entry uploaded on a runtime texture atlas //////////////////////////////////////////////////////////////////////////////// #ifndef __LM_GRAPHICS__TEXTURE__RUNTIME_TEXTURE_ATLAS_ENTRY_H #define __LM_GRAPHICS__TEXTURE__RUNTIME_TEXTURE_ATLAS_ENTRY_H // Leggiero.Basics #include <Basic/LeggieroBasic.h> // Standard Library #include <functional> #include <memory> // External Library #include <GLES3.h> // Leggiero.Utility #include <Utility/Sugar/NonCopyable.h> // Leggiero.Graphics #include "TextureSection.h" namespace Leggiero { namespace Graphics { // Forward Declarations class RuntimeTextureAtlas; class GLTextureResource; class DynamicTextureResource; namespace _Internal { struct SpaceNode; } // Runtime Atlas Texture Entry class RuntimeTextureAtlasEntry : private Utility::SyntacticSugar::NonCopyable { friend class RuntimeTextureAtlas; friend struct _Internal::SpaceNode; public: using RestorerType = std::function<bool(std::shared_ptr<DynamicTextureResource>, const TextureRectSection &)>; static RestorerType kVoidRestorer; protected: using EntryIdType = int; public: virtual ~RuntimeTextureAtlasEntry(); protected: RuntimeTextureAtlasEntry(std::shared_ptr<RuntimeTextureAtlas> atlas, EntryIdType id, const TextureRectSection &section, RestorerType restorer = kVoidRestorer); private: RuntimeTextureAtlasEntry() = delete; public: std::shared_ptr<GLTextureResource> GetTexture(); const TextureRectSection &GetTextureSection() const { return m_sectionArea; } void MarkRestored() { m_isValid = true; } bool IsValid() const { return m_isValid; } protected: void _Invalidate() { m_isValid = false; } bool _TryRestore(); protected: bool m_isValid; EntryIdType m_id; std::shared_ptr<RuntimeTextureAtlas> m_atlas; TextureRectSection m_sectionArea; RestorerType m_restorer; }; } } #endif ======================= File: Engine/Modules/Task/Tasks/ITask.h ======================= <filename>Engine/Modules/Task/Tasks/ITask.h<gh_stars>10-100 //////////////////////////////////////////////////////////////////////////////// // Tasks/ITask.h (Leggiero/Modules - Task) // // Task Base Interface //////////////////////////////////////////////////////////////////////////////// #ifndef __LM_TASK__TASKS__I_TASK_H #define __LM_TASK__TASKS__I_TASK_H // Leggiero.Basic #include <Basic/LeggieroBasic.h> // Standard Library #include <atomic> // Leggiero.Task #include "../TaskTypes.h" namespace Leggiero { namespace Task { // Interface for a Task class ITask { public: ITask() : m_currentState(TaskState::kNone) { } virtual ~ITask() { } public: // Task Properties virtual TaskPriorityClass GetTaskPriority() { return TaskPriorityClass::kDefault; } virtual TaskPropertyType GetTaskProperty() { return TaskPropertyType::kNone; } virtual TaskCapabilityType GetRequiredCapabilties() { return TaskCapabilities::kGeneral; } public: // Task States // Get Current State of the Task TaskState GetTaskState() const { return m_currentState.load(std::memory_order_consume); } std::atomic<TaskState> &State() { return m_currentState; } // Check whether the task is ready or not virtual bool IsTaskReady() { return true; } // Check Task Execution Done bool IsFinished() const { return Utility::SyntacticSugar::HasFlag(GetTaskState(), TaskState::kJobFinished); } // Check there was an error during task execution bool HasError() const { return Utility::SyntacticSugar::HasFlag(GetTaskState(), TaskState::kHasError); } public: // Task Implementations // Do Real Task Works virtual TaskDoneResult Do() = 0; // Pre-Process Function before Task All Processing virtual void OnBeforeProcess() { } // Pre-Process Function before Each Task All Processing Step virtual void OnBeforeStepProcess() { } // Function called after Each Task All Processing Step virtual void OnAfterStepProcess() { } // Function called after Task All Processing virtual void OnAfterProcess() { } public: // for task system // Set Error Flag on Task State virtual void SetErrorFlag() { TaskState storedValue; TaskState flagedValue; do { storedValue = m_currentState.load(); flagedValue = (storedValue | TaskState::kHasError); } while (!m_currentState.compare_exchange_weak(storedValue, flagedValue)); } protected: std::atomic<TaskState> m_currentState; }; } } #endif ======================= File: Engine/Modules/LUI/Prefab/UIShapeRenderingComponentPrefab.h ======================= //////////////////////////////////////////////////////////////////////////////// // Prefab/UIShapeRenderingComponentPrefab.h (Leggiero/Modules - LegacyUI) // // Prefab for Basic Shape Rendering Component //////////////////////////////////////////////////////////////////////////////// #ifndef __LM_LUI__PREFAB__UI_SHAPE_RENDERING_COMPONENT_PREFAB_H #define __LM_LUI__PREFAB__UI_SHAPE_RENDERING_COMPONENT_PREFAB_H // Standard Library #include <memory> #include <vector> // Leggiero.LegacyUI #include "../Description/UIDescriptionTypes.h" #include "UIComponentPrefab.h" namespace Leggiero { namespace LUI { // Forward Declarations class UIManager; class UIObject; class IUIComponent; class IUIRenderingShape; namespace Description { // Forward Declarations class DescriptionProcessingContext; namespace Expression { template <typename ValueT> class IExpression; } namespace Prefab { // Forward Declaration class IUIPrefabPlaceProcessor; class IRenderingShapePrefab; // Prefab for Shape Set Rendering Component class ShapeSetRenderingComponentPrefab : public IUIComponentPrefab { public: virtual ~ShapeSetRenderingComponentPrefab() { } public: // IUIComponentPrefab virtual std::shared_ptr<IUIComponent> Fabricate(DescriptionProcessingContext &processingContext, std::shared_ptr<UIManager> creatingManager, std::shared_ptr<UIObject> ownerObject, IUIPrefabPlaceProcessor *placeProcessor, ComponentPostProcessCreatingContext &postProcessingContext) override; public: static std::shared_ptr<ShapeSetRenderingComponentPrefab> ReadFromFromXMLElement(ParsingXMLElementType *elem); protected: std::vector<std::shared_ptr<IRenderingShapePrefab> > m_shapePrefabs; }; } } } } #endif ======================= File: Engine/Modules/Graphics/Common/GraphicsReferenceState.h ======================= //////////////////////////////////////////////////////////////////////////////// // Common/GraphicsReferenceState.h (Leggiero/Modules - Graphics) // // Shared Reference States of Graphics Module //////////////////////////////////////////////////////////////////////////////// #ifndef __LM_GRAPHICS__COMMON__GRAPHICS_REFERENCE_STATE_H #define __LM_GRAPHICS__COMMON__GRAPHICS_REFERENCE_STATE_H // Leggiero.Basics #include <Basic/LeggieroBasic.h> // External Library #include <GLES3.h> // Leggiero.Graphics #include "GraphicsTypes.h" namespace Leggiero { namespace Graphics { namespace ReferenceState { // Get frame rendering start time GameTimeClockType::time_point GetFrameRenderingStartTime(); // Get main frame buffer GLuint GetReferenceFrameBufferObjectName(); // Get vieport related values GLint GetReferenceViewportX(); GLint GetReferenceViewportY(); GLsizei GetReferenceViewportWidth(); GLsizei GetReferenceViewportHeight(); // Get screen related values BasicCoordType GetApproxScreenXPPI(); BasicCoordType GetApproxScreenYPPI(); // Get texture related values bool IsWholeScreenTextureAvailable(); GLint GetMaximumTextureDimension(); } } } #endif ======================= File: Engine/Common/Engine/Module/EngineComponentException.h ======================= <filename>Engine/Common/Engine/Module/EngineComponentException.h //////////////////////////////////////////////////////////////////////////////// // Module/EngineComponentException.h (Leggiero - Engine) // // Exceptions from Leggiero Engine Component System //////////////////////////////////////////////////////////////////////////////// #ifndef __ENGINE__MODULE__ENGINE_COMPONENT_EXCEPTION_H #define __ENGINE__MODULE__ENGINE_COMPONENT_EXCEPTION_H // Standard Library #include <exception> // Leggiero.Engine #include "EngineModuleId.h" #include "EngineComponentId.h" namespace Leggiero { namespace ModuleSystem { // Exception due to cyclic dependency of engine components class ComponentCyclicDependencyException : public std::exception { public: ComponentCyclicDependencyException() : ComponentCyclicDependencyException(EngineComponentIdType::kINVALID) { } ComponentCyclicDependencyException(EngineComponentIdType cyclicDetectedComponent) : cyclicDetectedComponent(cyclicDetectedComponent) { } virtual ~ComponentCyclicDependencyException() throw() { } public: virtual const char *what() const throw() { return "Engine Components have Cyclic Dependency"; } public: EngineComponentIdType cyclicDetectedComponent; }; // Missing Dependent Component class ComponentMissingDependencyException : public std::exception { public: ComponentMissingDependencyException() : ComponentMissingDependencyException(EngineComponentIdType::kINVALID) { } ComponentMissingDependencyException(EngineComponentIdType missingComponent) : missingComponentType(missingComponent) { } virtual ~ComponentMissingDependencyException() throw() { } public: virtual const char *what() const throw() { return "Dependent Engine Component NOT Exists"; } public: EngineComponentIdType missingComponentType; }; // Missing Component Dependent Module class ComponentModuleMissingDependencyException : public std::exception { public: ComponentModuleMissingDependencyException() : ComponentModuleMissingDependencyException(EngineModuleIdType::kINVALID) { } ComponentModuleMissingDependencyException(EngineModuleIdType notInitializedModule) : missingModuleType(notInitializedModule) { } virtual ~ComponentModuleMissingDependencyException() throw() { } public: virtual const char *what() const throw() { return "Dependent Engine Module need by Component NOT Initialized"; } public: EngineModuleIdType missingModuleType; }; } } #endif ======================= File: Engine/Modules/Crypto/ProtectedKey/NotSecureKey.h ======================= //////////////////////////////////////////////////////////////////////////////// // ProtectedKey/NotSecureKey.h (Leggiero/Modules - Crypto) // // Not-secure key that stores key in memory as plain text. // Can use for development, but not recommended to use in production. //////////////////////////////////////////////////////////////////////////////// #ifndef __LM_CRYPTO__PROTECTED_KEY__NOT_SECURE_KEY_H #define __LM_CRYPTO__PROTECTED_KEY__NOT_SECURE_KEY_H // Standard Library #include <memory> #include <string> // Leggiero.Crypto #include "IProtectedKey.h" namespace Leggiero { namespace Crypto { namespace Security { // Not secure key for developement class NotSecureKey : public IProtectedKey { public: NotSecureKey(const char *keyData, std::size_t keySize); NotSecureKey(const std::string &keyData); NotSecureKey(const NotSecureKey &other); NotSecureKey(NotSecureKey &&other); NotSecureKey &operator=(const NotSecureKey &other); NotSecureKey &operator=(NotSecureKey &&other); virtual ~NotSecureKey(); public: static NotSecureKey FromBase64String(const std::string &base64Key); static std::shared_ptr<NotSecureKey> NewFromBase64String(const std::string &base64Key); private: NotSecureKey() = delete; public: // IProtectedKey // Get length of the key virtual size_t GetLength() const override; // Get key byte value at given offset virtual uint8_t GetAt(size_t idx) const override; // Copy key to given buffer virtual void FillKey(void *buffer, size_t length, size_t keyOffset = 0) const override; // Do XOR on given data using the key virtual void XORKey(void *buffer, size_t length, size_t keyOffset = 0) const override; protected: uint8_t *m_keyBuffer; size_t m_keySize; }; } } } #endif ======================= File: Engine/Common/Engine/Module/EngineComponentId.h ======================= //////////////////////////////////////////////////////////////////////////////// // Module/EngineComponentId.h (Leggiero - Engine) // // Engine Component Id Definitions //////////////////////////////////////////////////////////////////////////////// #ifndef __ENGINE__MODULE__ENGINE_COMPONENT_ID_H #define __ENGINE__MODULE__ENGINE_COMPONENT_ID_H namespace Leggiero { // Engine Component Id Type enum class EngineComponentIdType { kINVALID = 0, kApplication = 1, kFileSystemPath = 11, kBundleFileResource = 12, kTaskManager = 21, kAsyncTaskHTTP = 52, kTouchInput = 101, kGraphicResourceManager = 211, kGlyphManager = 221, kSoundMixer = 301, kBGMPlayer = 302, }; } #endif ======================= File: Engine/Modules/Log/Logger.h ======================= //////////////////////////////////////////////////////////////////////////////// // Logger.h (Leggiero/Modules - Log) // // Leggiero Logger //////////////////////////////////////////////////////////////////////////////// #ifndef __LM_LOG__LOGGER_H #define __LM_LOG__LOGGER_H // Leggiero.Basic #include <Basic/LeggieroBasic.h> // Standard Library #include <cstdarg> #include <memory> #include <string_view> #include <vector> // External Library #include <concurrentqueue/concurrentqueue.h> // Leggiero.Utility #include <Utility/Sugar/NonCopyable.h> #include <Utility/Threading/ManagedThreadPrimitives.h> // Leggiero.Log #include "LogTypes.h" namespace Leggiero { namespace Log { // Forward Declarations class ILogWriter; // Logger class Logger : private Utility::SyntacticSugar::NonCopyable { public: Logger(); ~Logger(); public: void Log(LogLevelType logType, LogTime time, std::string_view log); void Log(LogLevelType logType, std::string_view log); void LogPrintf(LogLevelType logType, LogTime time, const char *const format,...); void LogPrintf(LogLevelType logType, const char *const format,...); public: void RegisterLogWriter(std::shared_ptr<ILogWriter> writer); void UnRegisterLogWriter(std::shared_ptr<ILogWriter> writer); std::vector<std::shared_ptr<ILogWriter> > GetAllLogWriters(); private: LogTime _CurrentTime(); std::vector<char> *_MessageBufferAlloc(size_t needSize); void _MessageBufferFree(std::vector<char> *buffer); void _LogPrintf(LogLevelType logType, LogTime time, const char *const format, va_list args); private: Utility::Threading::SafePthreadRWLock m_writerListLock; std::vector<std::shared_ptr<ILogWriter> > m_writers; moodycamel::ConcurrentQueue<std::vector<char> *> m_logMessageBuffer; }; // Get Engine-wide Main Logger Logger &MainLogger(); } } #endif ======================= File: Engine/Modules/Font/Common/StyledFontSet.h ======================= //////////////////////////////////////////////////////////////////////////////// // Common/StyledFontSet.h (Leggiero/Modules - Font) // // Font set with styled fonts //////////////////////////////////////////////////////////////////////////////// #ifndef __LM_FONT__COMMON__STYLED_FONT_SET_H #define __LM_FONT__COMMON__STYLED_FONT_SET_H // Standard Library #include <memory> // Leggiero.Basic #include <Basic/LeggieroBasic.h> // Leggiero.Font #include "FontTypes.h" #include "IFontSet.h" namespace Leggiero { namespace Font { // Forward Declarations class IFontFace; // Font Set with Styled Fonts class StyledFontSet : public IFontSet { public: StyledFontSet(std::shared_ptr<IFontSet> baseSet, std::shared_ptr<IFontSet> boldSet = nullptr, std::shared_ptr<IFontSet> italicSet = nullptr, std::shared_ptr<IFontSet> boldItalicSet = nullptr); StyledFontSet(std::shared_ptr<IFontFace> baseFace, std::shared_ptr<IFontFace> boldFace = nullptr, std::shared_ptr<IFontFace> italicFace = nullptr, std::shared_ptr<IFontFace> boldItalicFace = nullptr); virtual ~StyledFontSet() { } private: StyledFontSet() = delete; public: // Get a real font to render a given glyph virtual EffectiveFontResult GetEffectiveFont(GlyphCodePointType glyph, GlyphStyleType style = GlyphStyleType::kNone) const override; protected: std::shared_ptr<IFontSet> m_baseSet; std::shared_ptr<IFontSet> m_boldSet; std::shared_ptr<IFontSet> m_italicSet; std::shared_ptr<IFontSet> m_boldItalicSet; }; } } #endif ======================= File: Tools/ProjectCreator/Template/Project/Sources/App/Proj.iOS/GameViewController.h ======================= <filename>Tools/ProjectCreator/Template/Project/Sources/App/Proj.iOS/GameViewController.h //////////////////////////////////////////////////////////////////////////////// // GameViewController.h (${{ProgramName}} - iOS) // // Game View Controller //////////////////////////////////////////////////////////////////////////////// #import <LeggieroViewController.h> @interface GameViewController : LeggieroViewController @end ======================= File: Engine/Modules/LUI/Rendering/UIShaders.h ======================= //////////////////////////////////////////////////////////////////////////////// // Rendering/UIShaders.h (Leggiero/Modules - LegacyUI) // // Shaders for UI //////////////////////////////////////////////////////////////////////////////// #ifndef __LM_LUI__RENDERING__UI_SHADERS_H #define __LM_LUI__RENDERING__UI_SHADERS_H // Leggiero.Graphics #include <Graphics/Shader/CommonBaseShaderProgram.h> #include <Graphics/Shader/TexturedShaderProgram.h> namespace Leggiero { // Forward Declaration namespace Graphics { class GraphicResourceManagerComponent; } namespace LUI { namespace Shaders { // Color Primitive Shader Program class UIColorPrimitiveShader : public Graphics::CommonBaseShaderProgram { public: // Creation Function static std::shared_ptr<UIColorPrimitiveShader> Create(Graphics::GraphicResourceManagerComponent *resourceManager); public: UIColorPrimitiveShader(std::shared_ptr<Graphics::GLShaderProgramResource> programResource); virtual ~UIColorPrimitiveShader(); public: virtual GLint GetPositionSlot() const override { return m_positionSlot; } virtual GLint GetColorSlot() const override { return m_colorSlot; } virtual GLint GetModelMatrixLocation() const override { return m_modelMatrixLocation; } virtual GLint GetViewMatrixLocation() const override { return m_viewMatrixLocation; } virtual GLint GetProjectionMatrixLocation() const override { return m_projMatrixLocation; } GLint GetHSLModificationLocation() const { return m_hslModificationLocation; } public: virtual Graphics::GLVertexAttribEnabledContext EnableUsingVertexAttribArray(bool isAutoDisable = false) override; virtual void DisableAllUsingVertexAttribArray() override; protected: virtual void _RestoreAfterRecompile() override; protected: void _InitializeGLProgramLocations(); protected: GLint m_positionSlot; GLint m_colorSlot; GLint m_modelMatrixLocation; GLint m_viewMatrixLocation; GLint m_projMatrixLocation; GLint m_hslModificationLocation; public: // Sources static const char *s_sourceVert; static const char *s_sourceFrag; }; // Textured Color Shader Program class UITextureColorShader : public Graphics::TexturedShaderProgram { public: // Creation Function static std::shared_ptr<UITextureColorShader> Create(Graphics::GraphicResourceManagerComponent *resourceManager); public: UITextureColorShader(std::shared_ptr<Graphics::GLShaderProgramResource> programResource); virtual ~UITextureColorShader(); public: virtual GLint GetPositionSlot() const override { return m_positionSlot; } virtual GLint GetColorSlot() const override { return m_colorSlot; } virtual GLint GetTextureUVSlot() const override { return m_textureUVSlot; } virtual GLint GetModelMatrixLocation() const override { return m_modelMatrixLocation; } virtual GLint GetViewMatrixLocation() const override { return m_viewMatrixLocation; } virtual GLint GetProjectionMatrixLocation() const override { return m_projMatrixLocation; } virtual GLint GetTextureLocation() const override { return m_textureLocation; } GLint GetHSLModificationLocation() const { return m_hslModificationLocation; } public: virtual Graphics::GLVertexAttribEnabledContext EnableUsingVertexAttribArray(bool isAutoDisable = false) override; virtual void DisableAllUsingVertexAttribArray() override; protected: virtual void _RestoreAfterRecompile() override; protected: void _InitializeGLProgramLocations(); protected: GLint m_positionSlot; GLint m_colorSlot; GLint m_textureUVSlot; GLint m_modelMatrixLocation; GLint m_viewMatrixLocation; GLint m_projMatrixLocation; GLint m_textureLocation; GLint m_hslModificationLocation; public: // Sources static const char *s_sourceVert; static const char *s_sourceFrag; }; // Texture Gaussian Blur Shader Program class UITextureBlurShader : public Graphics::TexturedShaderProgram { public: // Creation Function static std::shared_ptr<UITextureBlurShader> Create(Graphics::GraphicResourceManagerComponent *resourceManager); public: UITextureBlurShader(std::shared_ptr<Graphics::GLShaderProgramResource> programResource); virtual ~UITextureBlurShader(); public: virtual GLint GetPositionSlot() const override { return m_positionSlot; } virtual GLint GetColorSlot() const override { return m_colorSlot; } virtual GLint GetTextureUVSlot() const override { return m_textureUVSlot; } virtual GLint GetModelMatrixLocation() const override { return m_modelMatrixLocation; } virtual GLint GetViewMatrixLocation() const override { return m_viewMatrixLocation; } virtual GLint GetProjectionMatrixLocation() const override { return m_projMatrixLocation; } virtual GLint GetTextureLocation() const override { return m_textureLocation; } GLint GetTexelWidthOffsetLocation() const { return m_texelWidthOffsetLocation; } GLint GetTexelHeightOffsetLocation() const { return m_texelHeightOffsetLocation; } GLint GetHSLModificationLocation() const { return m_hslModificationLocation; } public: virtual Graphics::GLVertexAttribEnabledContext EnableUsingVertexAttribArray(bool isAutoDisable = false) override; virtual void DisableAllUsingVertexAttribArray() override; protected: virtual void _RestoreAfterRecompile() override; protected: void _InitializeGLProgramLocations(); protected: GLint m_positionSlot; GLint m_colorSlot; GLint m_textureUVSlot; GLint m_modelMatrixLocation; GLint m_viewMatrixLocation; GLint m_projMatrixLocation; GLint m_textureLocation; GLint m_texelWidthOffsetLocation; GLint m_texelHeightOffsetLocation; GLint m_hslModificationLocation; public: // Sources static const char *s_sourceVert; static const char *s_sourceFrag; }; } } } #endif ======================= File: Engine/Modules/LUI/Common/UICommonArea.h ======================= <gh_stars>10-100 //////////////////////////////////////////////////////////////////////////////// // Common/UICommonArea.h (Leggiero/Modules - LegacyUI) // // Commonly used areas //////////////////////////////////////////////////////////////////////////////// #ifndef __LM_LUI__COMMON__UI_COMMON_AREA_H #define __LM_LUI__COMMON__UI_COMMON_AREA_H // Standard Library #include <vector> // Leggiero.LegacyUI #include "IUIArea.h" namespace Leggiero { namespace LUI { // Forward Declaration class UIObject; namespace CommonArea { namespace Operation { // Area Not Operation class Not : public IUIArea { public: Not(const std::shared_ptr<IUIArea> &sourceArea) : m_sourceArea(sourceArea) { } virtual ~Not() { } public: virtual bool IsInArea(UICoordinateType x, UICoordinateType y) const override { return!m_sourceArea->IsInArea(x, y); } protected: const std::shared_ptr<IUIArea> m_sourceArea; }; // Area Union Operation class Union : public IUIArea { public: Union() { } Union(const std::shared_ptr<IUIArea> &a, const std::shared_ptr<IUIArea> &b); Union(const std::shared_ptr<IUIArea> &a, const std::shared_ptr<IUIArea> &b, const std::shared_ptr<IUIArea> &c); Union(std::initializer_list<std::shared_ptr<IUIArea> > initializer); template <typename InputIterator> Union(InputIterator first, InputIterator last) : m_sourceAreas(first, last) { } virtual ~Union() { } public: virtual bool IsInArea(UICoordinateType x, UICoordinateType y) const override; protected: std::vector<std::shared_ptr<IUIArea> > m_sourceAreas; }; // Area Intersection Operation class Intersection : public IUIArea { public: Intersection() { } Intersection(const std::shared_ptr<IUIArea> &a, const std::shared_ptr<IUIArea> &b); Intersection(const std::shared_ptr<IUIArea> &a, const std::shared_ptr<IUIArea> &b, const std::shared_ptr<IUIArea> &c); Intersection(std::initializer_list<std::shared_ptr<IUIArea> > initializer); template <typename InputIterator> Intersection(InputIterator first, InputIterator last) : m_sourceAreas(first, last) { } virtual ~Intersection() { } public: virtual bool IsInArea(UICoordinateType x, UICoordinateType y) const override; protected: std::vector<std::shared_ptr<IUIArea> > m_sourceAreas; }; // Area Operators inline std::shared_ptr<IUIArea> operator~(const std::shared_ptr<IUIArea> &a) { return std::dynamic_pointer_cast<IUIArea>(std::make_shared<Not>(a)); } inline std::shared_ptr<IUIArea> operator-(const std::shared_ptr<IUIArea> &a) { return std::dynamic_pointer_cast<IUIArea>(std::make_shared<Not>(a)); } inline std::shared_ptr<IUIArea> operator+(const std::shared_ptr<IUIArea> &a, const std::shared_ptr<IUIArea> &b) { return std::dynamic_pointer_cast<IUIArea>(std::make_shared<Union>(a, b)); } inline std::shared_ptr<IUIArea> operator-(const std::shared_ptr<IUIArea> &a, const std::shared_ptr<IUIArea> &b) { return std::dynamic_pointer_cast<IUIArea>(std::make_shared<Union>(a, std::dynamic_pointer_cast<IUIArea>(std::make_shared<Not>(b)))); } inline std::shared_ptr<IUIArea> operator*(const std::shared_ptr<IUIArea> &a, const std::shared_ptr<IUIArea> &b) { return std::dynamic_pointer_cast<IUIArea>(std::make_shared<Intersection>(a, b)); } } namespace Shape { // Rectangular Area class Rect : public IUIArea { public: Rect(UICoordinateType width, UICoordinateType height, UICoordinateType left = static_cast<UICoordinateType>(0.0f), UICoordinateType top = static_cast<UICoordinateType>(0.0f)); virtual ~Rect() { } public: virtual bool IsInArea(UICoordinateType x, UICoordinateType y) const override; protected: UICoordinateType m_left; UICoordinateType m_top; UICoordinateType m_right; UICoordinateType m_bottom; }; // Circular Area class Circle : public IUIArea { public: Circle(UICoordinateType radius, UICoordinateType x = static_cast<UICoordinateType>(0.0f), UICoordinateType y = static_cast<UICoordinateType>(0.0f)); virtual ~Circle() { } public: virtual bool IsInArea(UICoordinateType x, UICoordinateType y) const override; protected: UICoordinateType m_radiusSquare; UICoordinateType m_x; UICoordinateType m_y; }; } // Specific rational rectangular area in the screen class ScreenArea : public IUIArea { public: ScreenArea(UICoordinateRatioType leftRatio = static_cast<UICoordinateRatioType>(0.0f), UICoordinateRatioType topRatio = static_cast<UICoordinateRatioType>(0.0f), UICoordinateRatioType rightRatio = static_cast<UICoordinateRatioType>(1.0f), UICoordinateRatioType bottomRatio = static_cast<UICoordinateRatioType>(1.0f)); virtual ~ScreenArea() { } public: virtual bool IsInArea(UICoordinateType x, UICoordinateType y) const override; protected: UICoordinateRatioType m_leftRatio; UICoordinateRatioType m_topRatio; UICoordinateRatioType m_rightRatio; UICoordinateRatioType m_bottomRatio; }; // Specific absolute rectangular area in the screen class ScreenAbsoluteArea : public IUIArea { public: ScreenAbsoluteArea(UICoordinateType left = static_cast<UICoordinateType>(0.0f), UICoordinateType top = static_cast<UICoordinateType>(0.0f), UICoordinateType right = static_cast<UICoordinateType>(0.0f), UICoordinateType bottom = static_cast<UICoordinateType>(0.0f)); virtual ~ScreenAbsoluteArea() { } public: virtual bool IsInArea(UICoordinateType x, UICoordinateType y) const override; protected: UICoordinateType m_left; UICoordinateType m_top; UICoordinateType m_right; UICoordinateType m_bottom; }; // Area of UI Object class ObjectBasedArea : public IUIArea { public: ObjectBasedArea(std::shared_ptr<UIObject> sourceObject, UICoordinateRatioType widthRatio = static_cast<UICoordinateRatioType>(1.0f), UICoordinateRatioType heightRatio = static_cast<UICoordinateRatioType>(1.0f), UICoordinateType offsetX = static_cast<UICoordinateType>(0.0f), UICoordinateType offsetY = static_cast<UICoordinateType>(0.0f)); virtual ~ObjectBasedArea() { } public: virtual bool IsInArea(UICoordinateType x, UICoordinateType y) const override; public: bool IsApplyClipping() const { return m_isApplyClipping; } void SetApplyClipping(bool isApplyClipping) { m_isApplyClipping = isApplyClipping; } protected: std::weak_ptr<UIObject> m_sourceObject; UICoordinateRatioType m_widthRatio; UICoordinateRatioType m_heightRatio; UICoordinateType m_offsetX; UICoordinateType m_offsetY; bool m_isApplyClipping; }; // Offseted area for UI Object class ObjectOffsetArea : public IUIArea { public: ObjectOffsetArea(std::shared_ptr<IUIArea> originalArea, std::shared_ptr<UIObject> sourceObject, UICoordinateRatioType referenceRatioX = static_cast<UICoordinateRatioType>(0.0f), UICoordinateRatioType referenceRatioY = static_cast<UICoordinateRatioType>(0.0f), UICoordinateType offsetX = static_cast<UICoordinateType>(0.0f), UICoordinateType offsetY = static_cast<UICoordinateType>(0.0f)); virtual ~ObjectOffsetArea() { } public: virtual bool IsInArea(UICoordinateType x, UICoordinateType y) const override; public: bool IsApplyClipping() const { return m_isApplyClipping; } void SetApplyClipping(bool isApplyClipping) { m_isApplyClipping = isApplyClipping; } protected: std::shared_ptr<IUIArea> m_originalArea; std::weak_ptr<UIObject> m_sourceObject; UICoordinateRatioType m_referenceRatioX; UICoordinateRatioType m_referenceRatioY; UICoordinateType m_offsetX; UICoordinateType m_offsetY; bool m_isApplyClipping; }; } } } #endif ======================= File: Engine/Modules/Sound/Platform/iOSBGMPlayer.h ======================= <reponame>LineGames/Leggiero //////////////////////////////////////////////////////////////////////////////// // Platform/iOSBGMPlayer.h (Leggiero/Modules - Sound) // // iOS Platform BGM Player using AVAudioPlayer //////////////////////////////////////////////////////////////////////////////// #ifndef __LM_SOUND__PLATFORM__IOS_BGM_PLAYER_H #define __LM_SOUND__PLATFORM__IOS_BGM_PLAYER_H // Leggiero.Basic #include <Basic/LeggieroBasic.h> // Standard Library #include <atomic> #include <list> // External Library #include <pthread.h> // Leggiero.Utility #include <Utility/Threading/ManagedThreadPrimitives.h> #include <Utility/Object/PointerHolder.h> // Leggiero.Sound #include "../BGMPlayerComponent.h" namespace Leggiero { // Forward Declaration namespace FileSystem { class BundleFileResourceComponent; } namespace Sound { namespace iOS { // Forward Declaration namespace _Internal { class iOSBGMPlayingContext; } // BGM Player Component class iOSBGMPlayer : public BGMPlayerComponent { public: iOSBGMPlayer(bool isUseBundleFileSystem = true); virtual ~iOSBGMPlayer(); public: // EngineComponent // Initialize the Component virtual void InitializeComponent(Engine::GameProcessAnchor *gameAnchor) override; // Safely Shutdown Component virtual void ShutdownComponent() override; // Get type Id list of dependent components needed by this component virtual const std::vector<EngineComponentIdType> &GetDependentComponents() const override; // Inject Dependency to the Component. // All dependency injections will be done before the initialization. virtual void InjectDependency(EngineComponentIdType componentId, EngineComponent *dependentComponent) override; public: // BGMPlayerComponent virtual std::shared_ptr<IBGMPlayingHandle> PlayFromFile(const std::string &filePath, bool isStartImmediately = false, float volume = 1.0f, bool isLooping = false, IBGMPlayingHandle::PlayFinishHandlerType playFinishHandler = IBGMPlayingHandle::PlayFinishHandlerType()) override; virtual std::shared_ptr<IBGMPlayingHandle> PlayInBundle(const std::string &virtualPath, bool isStartImmediately = false, float volume = 1.0f, bool isLooping = false, IBGMPlayingHandle::PlayFinishHandlerType playFinishHandler = IBGMPlayingHandle::PlayFinishHandlerType()) override; protected: std::atomic_bool m_isInitialized; std::atomic_bool m_isShutdownRequested; pthread_t m_updateThread; bool m_isUpdateThreadExists; FileSystem::BundleFileResourceComponent *m_pBundleFileSys; bool m_isUseBundleFileSystem; std::list<std::shared_ptr<_Internal::iOSBGMPlayingContext> > m_contextHolders; Utility::Threading::SafePthreadLock m_contextListLock; protected: void _UpdatePlay(); static void *_UpdatePlayThreadHelper(void *threadThis); }; } } } #endif ======================= File: Engine/Modules/Sound/SoundMixerComponent.h ======================= <filename>Engine/Modules/Sound/SoundMixerComponent.h //////////////////////////////////////////////////////////////////////////////// // SoundMixerComponent.h (Leggiero/Modules - Sound) // // Engine Sound Mixer Component //////////////////////////////////////////////////////////////////////////////// #ifndef __LM_SOUND__SOUND_MIXER_COMPONENT_H #define __LM_SOUND__SOUND_MIXER_COMPONENT_H // Leggiero.Basic #include <Basic/LeggieroBasic.h> // Standard Library #include <memory> // Leggiero.Engine #include <Engine/Module/EngineComponent.h> #include <Engine/Module/EngineComponentHolder.h> // Leggiero.Sound #include "Common/SoundTypes.h" #include "Common/SoundPlayingContext.h" namespace Leggiero { namespace Sound { // Forward Declaration class ISoundProvider; // Sound Mixer Component class SoundMixerComponent : public EngineComponent { public: // Can be created by Creation Function (for each platform sound mixers) static SoundMixerComponent *CreateComponentObject(); public: SoundMixerComponent(); virtual ~SoundMixerComponent(); public: // EngineComponent // Get Type Id of the Component virtual EngineComponentIdType GetComponentType() const override { return EngineComponentIdType::kSoundMixer; }; public: virtual std::shared_ptr<SoundPlayingContext> Play(std::shared_ptr<ISoundProvider> sound, bool isStartImmediately = true, float volume = 1.0f, bool isPauseAfterFinish = false) = 0; virtual std::shared_ptr<LoopingSoundPlayingContext> PlayLoopingSound(std::shared_ptr<ISoundProvider> sound, SampleNumberType loopStartSamplePosition, SampleNumberType loopFinishSamplePosition, bool isStartImmediately = true, float volume = 1.0f) = 0; virtual std::shared_ptr<BufferedSoundPlayingContext> PlayBufferedSound(std::shared_ptr<ISoundProvider> sound, bool isStartImmediately = true, float volume = 1.0f, bool isLooping = false, bool isPauseAfterFinish = false) = 0; virtual void ClearNonManagedSounds() = 0; public: virtual bool IsSuspended() const { return false; } virtual void HintUpdate() { } }; } } DECLARE_GET_COMPONENT_INTERFACE(Leggiero::Sound::SoundMixerComponent, Leggiero::EngineComponentIdType::kSoundMixer); #endif ======================= File: Engine/Modules/Graphics/Common/GLFrameBufferBindContext.h ======================= //////////////////////////////////////////////////////////////////////////////// // Common/GLFrameBufferBindContext.h (Leggiero/Modules - Graphics) // // Automated Frame Buffer Bind Result Context Class //////////////////////////////////////////////////////////////////////////////// #ifndef __LM_GRAPHICS__COMMON__GL_FRAME_BUFFER_BIND_CONTEXT_H #define __LM_GRAPHICS__COMMON__GL_FRAME_BUFFER_BIND_CONTEXT_H // Leggiero.Basics #include <Basic/LeggieroBasic.h> // External Library #include <GLES3.h> // Leggiero.Utility #include <Utility/Sugar/NonCopyable.h> namespace Leggiero { namespace Graphics { // Frame Buffer Bind Result Context class GLFrameBufferBindContext : private Utility::SyntacticSugar::NonCopyable { public: GLFrameBufferBindContext() : m_isUnBinded(true) { } GLFrameBufferBindContext(GLuint previousFrameBuffer, GLint previousViewportX, GLint previousViewportY, GLsizei previousViewportWidth, GLsizei previousViewportHeight, bool isAutoUnBind = false) : m_previousFrameBuffer(previousFrameBuffer) , m_previousViewportX(previousViewportX), m_previousViewportY(previousViewportY), m_previousViewportWidth(previousViewportWidth), m_previousViewportHeight(previousViewportHeight) , m_isUnBinded(false), m_isAutoUnBind(isAutoUnBind) { } virtual ~GLFrameBufferBindContext(); public: // Bind default windows's frame buffer on the context of last binding static GLFrameBufferBindContext TemporarilyBindDefaultFrameBuffer(bool isAutoUnBind = false); // Bind given region of default windows's frame buffer on the context of last binding static GLFrameBufferBindContext TemporarilyBindDefaultFrameBufferInRect(GLint leftX, GLint topY, GLsizei width, GLsizei height, bool isAutoUnBind = false); // Can move context public: GLFrameBufferBindContext(GLFrameBufferBindContext &&other); GLFrameBufferBindContext &operator=(GLFrameBufferBindContext &&other); public: // Un Bind Immediately void UnBind(); protected: void _DoUnBind(); protected: GLuint m_previousFrameBuffer; GLint m_previousViewportX; GLint m_previousViewportY; GLsizei m_previousViewportWidth; GLsizei m_previousViewportHeight; bool m_isUnBinded; bool m_isAutoUnBind; }; } } #endif ======================= File: Engine/Modules/Graphics/Shader/GLShaderProgramResource.h ======================= <filename>Engine/Modules/Graphics/Shader/GLShaderProgramResource.h //////////////////////////////////////////////////////////////////////////////// // Shader/GLShaderProgramResource.h (Leggiero/Modules - Graphics) // // OpenGL Shader Program Resource //////////////////////////////////////////////////////////////////////////////// #ifndef __LM_GRAPHICS__SHADER__GL_SHADER_PROGRAM_RESOURCE_H #define __LM_GRAPHICS__SHADER__GL_SHADER_PROGRAM_RESOURCE_H // Leggiero.Basics #include <Basic/LeggieroBasic.h> // Standard Library #include <functional> #include <memory> // External Library #include <GLES3.h> // Leggiero.Utility #include <Utility/Sugar/EventNotifier.h> #include <Utility/Sugar/NonCopyable.h> // Leggiero.Graphics #include "../Common/IGLGraphicResource.h" namespace Leggiero { // Forward Declaration namespace Utility { namespace Object { class PointerHolder; } } // Forward Declaration of File System Component namespace FileSystem { class BundleFileResourceComponent; } namespace Graphics { // Forward Declarations class GraphicResourceManagerComponent; class GLShaderProgramResource; class IGLProgramStateEventObserver; // Shader Program Creation Functions std::shared_ptr<GLShaderProgramResource> LoadGLProgramResourceFromInMemoryStrings(GraphicResourceManagerComponent *ownerManager, const std::string &vsSource, const std::string &fsSource); std::shared_ptr<GLShaderProgramResource> LoadGLProgramResourceFromInMemoryCStrings(GraphicResourceManagerComponent *ownerManager, const char *vsSource, const char *fsSource, size_t vsSourceLength = 0, size_t fsSourceLength = 0, bool isPersistenceMemory = true); std::shared_ptr<GLShaderProgramResource> LoadGLProgramResourceFromFiles(GraphicResourceManagerComponent *ownerManager, const std::string &vsFilePath, const std::string &fsFilePath); std::shared_ptr<GLShaderProgramResource> LoadGLProgramResourceFromBundle(GraphicResourceManagerComponent *ownerManager, FileSystem::BundleFileResourceComponent *bundle, const std::string &vsVirtualPath, const std::string &fsVirtualPath); // OpenGL ES Shader Program Resource class GLShaderProgramResource : public IGLGraphicResource , public std::enable_shared_from_this<GLShaderProgramResource> , private Utility::SyntacticSugar::NonCopyable { public: // Constants static constexpr GLint kLocation_INVALID = static_cast<GLint>(-2); protected: friend std::shared_ptr<GLShaderProgramResource> LoadGLProgramResourceFromInMemoryStrings(GraphicResourceManagerComponent *, const std::string &, const std::string &); friend std::shared_ptr<GLShaderProgramResource> LoadGLProgramResourceFromInMemoryCStrings(GraphicResourceManagerComponent *, const char *, const char *, size_t, size_t, bool); friend std::shared_ptr<GLShaderProgramResource> LoadGLProgramResourceFromFiles(GraphicResourceManagerComponent *, const std::string &, const std::string &); friend std::shared_ptr<GLShaderProgramResource> LoadGLProgramResourceFromBundle(GraphicResourceManagerComponent *, FileSystem::BundleFileResourceComponent *, const std::string &, const std::string &); public: // Direct calling the constructor is NOT recommended. Please use creation functions. // The constructor remains public due to std::make_shared call. GLShaderProgramResource( GraphicResourceManagerComponent *ownerManager, const std::string &vertexShaderSourceString, const char *vertexShaderSourceCString, const std::string &fragmentShaderSourceString, const char *fragmentShaderSourceCString); public: virtual ~GLShaderProgramResource(); public: GLuint GetGLProgram() const { return m_glProgram; } public: bool Use(); GLint GetAttribLocation(const GLchar *name); GLint GetUniformLocation(const GLchar *name); public: bool IsVertexShaderCompileSuccess() const { return m_isVertexShaderCompileSuccess; } const char *GetVertexShaderCompileInfoLog() const { return m_vertexShaderInfoLog; } bool IsFragmentShaderCompileSuccess() const { return m_isFragmentShaderCompileSuccess; } const char *GetFragmentShaderCompileInfoLog() const { return m_fragmentShaderInfoLog; } bool IsProgramLinkSuccess() const { return m_isProgramLinkSuccess; } const char *GetProgramLinkInfoLog() const { return m_programInfoLog; } public: void RegisterStateEventObserver(IGLProgramStateEventObserver *observer); void UnRegisterStateEventObserver(IGLProgramStateEventObserver *observer); public: // IGLGraphicResource virtual bool IsValid() override; virtual bool Restore() override; protected: std::function<void()> _GenerateResourceTrashFunc(); void _ClearCompileStatus(); bool _Compile(); protected: bool m_isInitialized; bool m_isInvalidated; GLuint m_glProgram; GLuint m_glVertexShader; GLuint m_glFragmentShader; std::weak_ptr<Utility::Object::PointerHolder> m_managerHolder; bool m_isUsingVertexShader; std::string m_vertexShaderSourceString; const char *m_vertexShaderSourceCString; bool m_isUsingFragmentShader; std::string m_fragmentShaderSourceString; const char *m_fragmentShaderSourceCString; protected: bool m_isVertexShaderCompileSuccess; char *m_vertexShaderInfoLog; bool m_isFragmentShaderCompileSuccess; char *m_fragmentShaderInfoLog; bool m_isProgramLinkSuccess; char *m_programInfoLog; protected: Utility::DesignPattern::EventNotifier<IGLProgramStateEventObserver *> m_stateEventNotifier; }; } } #endif ======================= File: Engine/Modules/LUI/Element/UIElementVariantText.h ======================= <filename>Engine/Modules/LUI/Element/UIElementVariantText.h //////////////////////////////////////////////////////////////////////////////// // Element/UIElementVariantText.h (Leggiero/Modules - LegacyUI) // // Text UI element that can be changed //////////////////////////////////////////////////////////////////////////////// #ifndef __LM_LUI__ELEMENT__UI_ELEMENT_VARIANT_TEXT_H #define __LM_LUI__ELEMENT__UI_ELEMENT_VARIANT_TEXT_H // Leggiero.Basic #include <Basic/LeggieroBasic.h> // Standard Library #include <functional> #include <memory> #include <string> // Leggiero.Graphics #include <Graphics/Common/GLColor.h> // Leggiero.Font #include <Font/Common/Typesetting.h> // Leggiero.LegacyUI #include "../Common/UICommonTypes.h" #include "../UIObject.h" namespace Leggiero { namespace LUI { // Forward Declarations class UIManager; namespace Rendering { class TextRenderingComponent; } namespace Element { // Variant UI Text class UIElementVariantText : public UIObject { public: using TypesettingGeneratorType = std::function<std::shared_ptr<Font::CachedGlyphTypesetting>(GameDataString)>; public: UIElementVariantText(std::shared_ptr<UIManager> ownerManager, TypesettingGeneratorType typesettingGeneratorFunc, const GameDataString &initialString, bool isRenderShadow = false, const Graphics::GLByteARGB &shadowColor = Graphics::GLByteARGB::kTransparent, const UIVector2D &shadowOffset = UIVector2D::kZero); virtual ~UIElementVariantText(); protected: UIElementVariantText(std::shared_ptr<UIManager> ownerManager) : UIObject(ownerManager) { } public: void Prepare(); public: // IUIObject virtual std::shared_ptr<UIObject> Clone() const override; virtual void GraphicPrepare() override; virtual void FrameGraphicPrepare(const UIRenderer &renderer, UIVector2D offsetPosition, const IUIClipping &effectiveClipping) override; virtual UIElementSize CalculateSize() override; virtual UICoordinateType CalculateWidth() override; virtual UICoordinateType CalculateHeight() override; public: virtual void SetString(const GameDataString &stringToSet); public: void SetMultiplyColor(Graphics::GLByteARGB multiplyColor); const Graphics::GLByteARGB GetMultiplyColor() const; void TurnShadow(bool isTurnOn); void SetShadow(const Graphics::GLByteARGB &shadowColor, const UIVector2D &shadowOffset); protected: TypesettingGeneratorType m_typesettingGeneratorFunc; std::shared_ptr<Font::CachedGlyphTypesetting> m_typesetting; GameDataString m_currentString; bool m_isDirty; GameDataString m_toChangeString; std::shared_ptr<Rendering::TextRenderingComponent> m_textRenderingComponent; }; } } } #endif ======================= File: Engine/Modules/LUI/Touch/UITouchComponent.h ======================= //////////////////////////////////////////////////////////////////////////////// // Touch/UITouchComponent.h (Leggiero/Modules - LegacyUI) // // Touch interaction component of an UI object //////////////////////////////////////////////////////////////////////////////// #ifndef __LM_LUI__TOUCH__UI_TOUCH_COMPONENT_H #define __LM_LUI__TOUCH__UI_TOUCH_COMPONENT_H // Leggiero.Basic #include <Basic/LeggieroBasic.h> // Standard Library #include <memory> // Leggiero.LegacyUI #include "../Common/UICommonTypes.h" #include "../Component/IUIComponent.h" namespace Leggiero { namespace LUI { // Forward Declarations class UITouch; class IUIArea; class UIObject; // Base Touch Interaction UI Component class UITouchComponent : public IUIComponent { public: UITouchComponent() { } virtual ~UITouchComponent() { } public: // IUIComponent virtual UIComponentType GetComponentType() const override { return UIComponentType::kTouchInteraction; } public: virtual std::shared_ptr<IUIArea> GetInteractionArea() const; virtual std::shared_ptr<IUIArea> GetCoverArea() const { return nullptr; } public: virtual void OnTouchDown(std::shared_ptr<UITouch> touch, UICoordinateType x, UICoordinateType y, GameTimeClockType::time_point time, bool isCoveredByDescendant) { } virtual void OnTouchIn(std::shared_ptr<UITouch> touch, UICoordinateType x, UICoordinateType y, GameTimeClockType::time_point time, bool isFirstIn, bool isCoveredByDescendant) { } virtual void OnTouchMove(std::shared_ptr<UITouch> touch, UICoordinateType x, UICoordinateType y, GameTimeClockType::time_point time) { } virtual void OnTouchOut(std::shared_ptr<UITouch> touch, UICoordinateType x, UICoordinateType y, GameTimeClockType::time_point time) { } virtual void OnTouchCovered(std::shared_ptr<UITouch> touch, UICoordinateType x, UICoordinateType y, GameTimeClockType::time_point time) { } virtual void OnTouchCancel(std::shared_ptr<UITouch> touch, GameTimeClockType::time_point time) { } virtual void OnTouchUp(std::shared_ptr<UITouch> touch, UICoordinateType x, UICoordinateType y, GameTimeClockType::time_point time) { } virtual bool OnPrimaryTouchSteal(std::shared_ptr<UITouch> touch, std::shared_ptr<UIObject> stealer) { return true; } virtual void OnPrimaryTouchHolderChanged(std::shared_ptr<UITouch> touch, std::shared_ptr<UIObject> primaryHolder) { } virtual void OnPrimaryTouchGiven(std::shared_ptr<UITouch> touch) { } virtual void OnPrimaryTouchLose(std::shared_ptr<UITouch> touch) { } }; } } #endif ======================= File: Engine/Common/Engine/Application/GameProcessAnchorObserver.h ======================= //////////////////////////////////////////////////////////////////////////////// // Application/GameProcessAnchorObserver.h (Leggiero - Engine) // // Observer Interfaces for Game Process Anchor //////////////////////////////////////////////////////////////////////////////// #ifndef __ENGINE__APPLICATION__GAME_PROCESS_ANCHOR_OBSERVER_H #define __ENGINE__APPLICATION__GAME_PROCESS_ANCHOR_OBSERVER_H // Leggiero.Basic #include <Basic/LeggieroBasic.h> namespace Leggiero { namespace Engine { namespace GameProcessAnchorObserver { // On Prepare Event Handler class IPrepareHandler { public: virtual void GameProcess_OnPrepare() = 0; }; // On Graphic Prepare Event Handler class IGraphicPrepareHandler { public: virtual void GameProcess_OnGraphicPrepare(bool isFirstGraphicPrepare) = 0; }; // On Before Frame Event Handler class IBeforeFrameHandler { public: virtual void GameProcess_OnBeforeFrame(GameFrameNumberType frameNumber, GameTimeClockType::time_point frameReferenceTime) = 0; }; // On After Frame Event Handler class IAfterFrameHandler { public: virtual void GameProcess_OnAfterFrame(GameFrameNumberType frameNumber) = 0; }; // On Graphic Shutdown Event Handler class IGraphicShutdownHandler { public: virtual void GameProcess_OnGraphicShutdown() = 0; }; // On Shutdown Event Handler class IShutdownHandler { public: virtual void GameProcess_OnShutdown() = 0; }; } } } #endif ======================= File: Engine/Modules/Crypto/Encrypt/RSAUtil.h ======================= <filename>Engine/Modules/Crypto/Encrypt/RSAUtil.h //////////////////////////////////////////////////////////////////////////////// // Encrypt/RSAUtil.h (Leggiero/Modules - Crypto) // // RSA Encryption Utility //////////////////////////////////////////////////////////////////////////////// #ifndef __LM_CRYPTO__ENCRYPT__RSA_UTIL_H #define __LM_CRYPTO__ENCRYPT__RSA_UTIL_H // Leggiero.Basic #include <Basic/LeggieroBasic.h> // Standrad Library #include <memory> #include <string> namespace Leggiero { namespace Crypto { namespace Encrypt { // RSA Encryption Class //note: only public key interfaces exists. don't use private key in client-side class RSA { public: // Assume PKCS#1 OAEP Padding static std::string EncryptWithPublicKey(const void *dataBuffer, size_t dataLength, const std::string &pemKey); static std::string EncryptWithPublicKey(const std::string &data, const std::string &pemKey); // Assume PKCS#1 Padding static std::string DecryptWithPublicKey(const void *dataBuffer, size_t dataLength, const std::string &pemKey); static std::string DecryptWithPublicKey(const std::string &data, const std::string &pemKey); }; } } } #endif ======================= File: Engine/Common/Utility/Math/Easing.h ======================= <gh_stars>10-100 //////////////////////////////////////////////////////////////////////////////// // Math/Easing.h (Leggiero - Utility) // // Additional Easing Function Defines //////////////////////////////////////////////////////////////////////////////// #ifndef __UTILITY__MATH__EASING_H #define __UTILITY__MATH__EASING_H // Standard Library #include <cmath> #include <limits> namespace Leggiero { namespace Utility { namespace Math { // Cubic Bezier Easing Class // This is an object because it uses precomputed table. class CubicBezierEasing { public: CubicBezierEasing(double p1x, double p1y, double p2x, double p2y); public: double Easy(double param); public: const double m_p1x; const double m_p1y; const double m_p2x; const double m_p2y; static constexpr size_t kSplineTableSize = 11; private: bool m_isLinearEasing; double m_sampleValues[kSplineTableSize]; }; // Easy as cubic-bezier. // This is slow! Consider to use CubicBezierEasing class in production. float EasyCubicBezier(float param, float p1x, float p1y, float p2x, float p2y); // Get linear parameter in an interval template <typename ValueT> inline ValueT ParameterInInterval(ValueT rawParam, ValueT intervalStart, ValueT intervalFinish) { if (intervalStart > intervalFinish) { // Invalid Interval return std::numeric_limits<ValueT>::quiet_NaN(); } if (rawParam <= intervalStart) { return static_cast<ValueT>(0.0); } if (rawParam >= intervalFinish) { return static_cast<ValueT>(1.0); } return (rawParam - intervalStart) / (intervalFinish - intervalStart); } // Smooth Fast-and-Go float EasySmoothBulgeFast(float param); // Smooth Slow-and-Go float EasySmoothBulgeSlow(float param); } } } #endif ======================= File: Engine/Common/Basic/_Internal/_CommonTypes.h ======================= //////////////////////////////////////////////////////////////////////////////// // _Internal/_CommonTypes.h (Leggiero - Basic) // * DO NOT directly include this header file outside of Basic project // // Definitions for common basic types //////////////////////////////////////////////////////////////////////////////// #ifndef __BASIC___COMMON_TYPES_H #define __BASIC___COMMON_TYPES_H // Standard Library #include <cstdint> #include <chrono> #include <limits> #include <string> // External Library #include <utfcpp/utf8.h> namespace Leggiero { // Standard clock to represent game time using GameTimeClockType = std::chrono::steady_clock; // Game data string type(UTF-8) using GameDataString = std::string; extern const GameDataString g_EmptyGameDataString; // Game Frame Number using GameFrameNumberType = int64_t; constexpr GameFrameNumberType kNoFrame = static_cast<GameFrameNumberType>(0); } #endif ======================= File: Engine/Modules/LUI/Prefab/UIPrefabPlaceProcessor.h ======================= <filename>Engine/Modules/LUI/Prefab/UIPrefabPlaceProcessor.h<gh_stars>10-100 //////////////////////////////////////////////////////////////////////////////// // Prefab/UIPrefabPlaceProcessor.h (Leggiero/Modules - LegacyUI) // // Processor interface for UI place holders //////////////////////////////////////////////////////////////////////////////// #ifndef __LM_LUI__PREFAB__UI_PREFAB_PLACE_PROCESSOR_H #define __LM_LUI__PREFAB__UI_PREFAB_PLACE_PROCESSOR_H // Leggiero.Basic #include <Basic/LeggieroBasic.h> // Standard Library #include <memory> #include <string> #include <unordered_map> // Leggiero.LegacyUI #include "UIObjectPrefab.h" #include "UITextObjectPrefab.h" #include "UIComponentPrefab.h" #include "../Description/UIDescriptionSourcedString.h" namespace Leggiero { namespace LUI { // Forward Declarations class UIManager; class UIObject; namespace Description { namespace Prefab { // Placeholder Processor class IUIPrefabPlaceProcessor { public: virtual ~IUIPrefabPlaceProcessor() { } public: virtual std::shared_ptr<UIObject> ProcessObjectPlaceholderFabrication(std::shared_ptr<UIManager> creatingManager, ObjectPlaceHolder::CreateKeyType creatingKey, std::unordered_map<std::string, GameDataString> &parameters, ComponentPostProcessCreatingContext &postProcessContext) { return nullptr; }; virtual std::shared_ptr<IUIComponent> ProcessComponentPlaceholderFabrication(std::shared_ptr<UIManager> creatingManager, std::shared_ptr<UIObject> ownerObject, ComponentPlaceHolder::CreateKeyType creatingKey, std::unordered_map<std::string, GameDataString> &parameters, ComponentPostProcessCreatingContext &postProcessingContext) { return nullptr; }; virtual GameDataString ProcessStringGeneration(const SourcedStringEntry::StringGeneratingKeyType &generateKey) { return ""; }; }; } } } } #endif ======================= File: Engine/Modules/Sound/Provider/OggSoundProvider.h ======================= <filename>Engine/Modules/Sound/Provider/OggSoundProvider.h //////////////////////////////////////////////////////////////////////////////// // Provider/OggSoundProvider.h (Leggiero/Modules - Sound) // // Sound provider for Ogg Vorbis format data //////////////////////////////////////////////////////////////////////////////// #ifndef __LM_SOUND__PROVIDER__OGG_SOUND_PROVIDER_H #define __LM_SOUND__PROVIDER__OGG_SOUND_PROVIDER_H // Leggiero.Basic #include <Basic/LeggieroBasic.h> // Standard Library #include <cstdio> #include <istream> #include <memory> #include <string> // External Library #include <vorbis/vorbisfile.h> // Leggiero.Utility #include <Utility/Threading/ManagedThreadPrimitives.h> // Leggiero.Sound #include "ISoundProvider.h" namespace Leggiero { namespace Sound { // Forward Declaration namespace _Internal { struct OGGRawMemoryBuffer; } // Ogg Vorbis Sound Data Provider class OggSoundProvider : public ISoundProvider { public: OggSoundProvider(FILE *source, bool needToClose = false); OggSoundProvider(const char *filePath); OggSoundProvider(const std::string &filePath); OggSoundProvider(std::istream *source); OggSoundProvider(std::shared_ptr<std::istream> source); OggSoundProvider(const void *memoryBuffer, size_t bufferSize); virtual ~OggSoundProvider(); protected: void _InitializeSoundData(); private: // Prevent Creating of NULL Sound Provider OggSoundProvider() { } public: // ISoundProvider virtual SampleFormat GetFormat() const override { return m_format; } virtual SamplingFrequencyType GetFrequency() const override { return m_frequency; } virtual size_t GetSampleLength() const override { return (size_t)m_lengthInSample; } virtual float GetLengthInSecond() const override { return (float)m_lengthInSecond; } virtual size_t FillSampleData(void *dataBuffer, size_t bufferSize, SampleNumberType startSample, SampleNumberType *outWrittenSamples = nullptr) override; public: bool IsValid() const { return m_isInitialized; } protected: bool m_isInitialized; SampleFormat m_format; SamplingFrequencyType m_frequency; int m_channelNumber; double m_lengthInSecond; ogg_int64_t m_lengthInSample; FILE *m_ownFileSource; std::shared_ptr<std::istream> m_sharedIStreamPtr; std::shared_ptr<_Internal::OGGRawMemoryBuffer> m_bufferSharedPtr; OggVorbis_File m_sourceVorbisFile; Utility::Threading::SafePthreadLock m_sourceFileMutex; int m_lastBitstream; SampleNumberType m_lastReadSamplePosition; }; } } #endif ======================= File: Engine/Platform/Platform.WinPC/WindowsUtility.h ======================= <reponame>LineGames/Leggiero //////////////////////////////////////////////////////////////////////////////// // WindowsUtility.h (Leggiero - Platform.WinPC) // // Windows Platform Utility Functions //////////////////////////////////////////////////////////////////////////////// #pragma once // Standard Library #include <vector> // Leggiero.Basic #include <Basic/LeggieroBasic.h> // Leggiero.Platform.WinPC #include "WindowsCommon.h" namespace Leggiero { namespace Platform { namespace Windows { namespace Utility { GameDataString TSTR_2_GameDataString(LPCTSTR sourceString); GameDataString WSTR_2_GameDataString(LPCWSTR sourceString); std::vector<wchar_t> GameDataString_2_WSTR(const GameDataString &sourceString); void PrintDebugString(const char *str); void PrintDebugString(LPCWSTR str); void PrintDebugStringFormat(const char *fmt,...); void PrintDebugStringFormat(const wchar_t *fmt,...); } } } } ======================= File: Engine/Platform/Platform.iOS/iOSPlatformApplication.h ======================= //////////////////////////////////////////////////////////////////////////////// // iOSPlatformApplication.h (Leggiero - Platform.iOS) // // Platform Application Object runs on iOS Platform //////////////////////////////////////////////////////////////////////////////// #ifndef __LP_IOS__IOS_PLATFORM_APPLICATION_H #define __LP_IOS__IOS_PLATFORM_APPLICATION_H // Standard Library #include <memory> #include <string> #include <unordered_set> // Leggiero.Basic #include <Basic/LeggieroBasic.h> // Leggiero.Engine #include <Engine/Application/IPlatformApplication.h> // Leggiero.Application #include <Application/AppPlatformType.h> #include <Application/DeviceCommonTypes.h> #include <Application/ApplicationComponent.h> #include <Application/IAppInformationProvider.h> #include <Application/IDeviceInformationProvider.h> #include <Application/IPlatformAppControl.h> #include <Application/SystemEventDispatcher.h> #include <Application/RawTouchEventDispatcher.h> namespace Leggiero { // Foraward Declaration class IGame; namespace Platform { namespace iOS { // Forward Declarations class IOSTextInputDialog; class IOSWebView; // Platform Application class IOSPlatformApplication : public IPlatformApplication , public Application::ApplicationComponent , public Application::IAppInformationProvider, public Application::IDeviceInformationProvider , public Application::IPlatformAppControl , public Application::SystemEventDispatcher, public Application::RawTouchEventDispatcher { public: IOSPlatformApplication(); virtual ~IOSPlatformApplication(); public: // Process Game Lifetime Events void InitializeGame(); void TerminateGame(); void InitializeGameGraphic(); void TerminateGameGraphic(); void DrawFrame(); // Set Application Meta-Data void SetScreenSize(int width, int height, bool isFirstSetting); void SetSafePadding(int left, int top, int right, int bottom); void SetApproximateScreenPPI(float approxXPPI, float approxYPPI); void SetIsTablet(bool isTablet); void SetSystemLocale(const std::string &systemLocaleString); public: // IPlatformApplication virtual Application::ApplicationComponent *GetApplicationComponent() override { return this; } virtual EngineComponent *GetApplicationEngineComponent() override { return GetApplicationComponent(); } public: // ApplicationComponent virtual Application::IAppInformationProvider &AppInformation() override { return *this; } virtual Application::IDeviceInformationProvider &DeviceInformation() override { return *this; } virtual Application::IPlatformAppControl &PlatformAppControl() override { return *this; } virtual Application::SystemEventDispatcher &SystemEventCenter() override { return *this; } virtual Application::RawTouchEventDispatcher &RawTouchEventCenter() override { return *this; } virtual Application::IAppTextInputController &TextInputController() override; virtual Application::IAppWebViewController &WebViewController() override; public: // IAppInformationProvider virtual Application::DeviceScreenCoordType GetPixelWidth() const override { return m_screenWidth; } virtual Application::DeviceScreenCoordType GetPixelHeight() const override { return m_screenHeight; } virtual Application::DeviceScreenPixelCoordType GetIntegerPixelWidth() const override { return m_screenPixelWidth; } virtual Application::DeviceScreenPixelCoordType GetIntegerPixelHeight() const override { return m_screenPixelHeight; } virtual Application::AppPlatformType GetPlatformType() const override { return Application::AppPlatformType::kAndroid; } virtual const char *GetSystemLocaleString() const override { return m_systemLocaleString.c_str(); } virtual std::string GetAppReferrer() override; public: // IDeviceInformationProvider virtual Application::DeviceScreenCoordType GetScreenPixelWidth() const override { return m_screenWidth; } virtual Application::DeviceScreenCoordType GetScreenPixelHeight() const override { return m_screenHeight; } virtual Application::DeviceScreenPixelCoordType GetScreenIntegerPixelWidth() const override { return m_screenPixelWidth; } virtual Application::DeviceScreenPixelCoordType GetScreenIntegerPixelHeight() const override { return m_screenPixelHeight; } virtual Application::DeviceScreenCoordType GetApproximateScreenXPPI() const override { return m_approxScreenXPPI; } virtual Application::DeviceScreenCoordType GetApproximateScreenYPPI() const override { return m_approxScreenYPPI; } virtual Utility::Math::BasicRect<Application::DeviceScreenCoordType> GetSafeArea() const override { return m_safeAreaRect; } virtual GameDataString GetDeviceName() const override; virtual bool IsTablet() const override { return m_isTablet; } public: // IPlatformAppControl // Set whether to prevent device sleep on idle virtual void SetNoSleepMode(bool isPreventSleep) override; public: // Process System Events void OnPause(); void OnResume(); void OnGoToBackground(); void OnReturnFromBackground(); void OnMemoryWarning(); void OnBackButtonPressed(); public: // Process Touch Events void OnTouchDown(Application::DeviceTouchIdType touchId, Application::DeviceScreenCoordType xPos, Application::DeviceScreenCoordType yPos, GameTimeClockType::time_point eventTime); void OnTouchMove(Application::DeviceTouchIdType touchId, Application::DeviceScreenCoordType xPos, Application::DeviceScreenCoordType yPos, GameTimeClockType::time_point eventTime); void OnTouchUp(Application::DeviceTouchIdType touchId, Application::DeviceScreenCoordType xPos, Application::DeviceScreenCoordType yPos, GameTimeClockType::time_point eventTime); void OnTouchCancel(Application::DeviceTouchIdType touchId, GameTimeClockType::time_point eventTime); void CancelAllTouch(); protected: std::shared_ptr<IGame> m_game; Application::DeviceScreenPixelCoordType m_screenPixelWidth; Application::DeviceScreenPixelCoordType m_screenPixelHeight; Application::DeviceScreenCoordType m_screenWidth; Application::DeviceScreenCoordType m_screenHeight; Application::DeviceScreenCoordType m_approxScreenXPPI; Application::DeviceScreenCoordType m_approxScreenYPPI; Utility::Math::BasicRect<Application::DeviceScreenCoordType> m_safeAreaRect; bool m_isTablet; std::string m_systemLocaleString; std::shared_ptr<IOSTextInputDialog> m_textInputDialogController; std::shared_ptr<IOSWebView> m_webViewController; std::unordered_set<Application::DeviceTouchIdType> m_downedTouches; }; } } } #endif ======================= File: Engine/Modules/HTTP/cURL/cURLAsyncHttpDownloadTask.h ======================= <reponame>LineGames/Leggiero //////////////////////////////////////////////////////////////////////////////// // cURL/cURLAsyncHttpDownloadTask.h (Leggiero/Modules - HTTP) // // libcurl and TaskManager based Async HTTP File Download Task //////////////////////////////////////////////////////////////////////////////// #ifndef __LM_HTTP__CURL__CURL_ASYNC_HTTP_DOWNLOAD_TASK_H #define __LM_HTTP__CURL__CURL_ASYNC_HTTP_DOWNLOAD_TASK_H // Leggiero.Basic #include <Basic/LeggieroBasic.h> // Standard Library #include <atomic> // Leggiero.HTTP #include "../Async/AsyncHttpDownloadTask.h" #include "../HttpUtility.h" namespace Leggiero { // Forward Declaration namespace Task { class TaskManagerComponent; } namespace HTTP { namespace cURL { // Forward Declaration namespace _Internal { class WritingState; } // libcurl based Async HTTP Download Task class CURLHTTPDownloadTask : public Async::HTTPDownloadTask { friend class _Internal::WritingState; public: CURLHTTPDownloadTask(const std::string &downloadFilePath, bool isBackgroundTask, const std::string &url, RequestMethod method, const POSTParameterMap &parameters, int connectTimeout); virtual ~CURLHTTPDownloadTask(); public: // ITask // Do Real Task Works virtual Task::TaskDoneResult Do() override; public: // IAsyncValueTask // Check whether the task have result value virtual bool HasValue() const override { Task::TaskState taskState = this->GetTaskState(); return (Utility::SyntacticSugar::HasFlag(taskState, Task::TaskState::kJobFinished) &&!Utility::SyntacticSugar::HasFlag(taskState, Task::TaskState::kHasError)); } // Get result value virtual HTTPRequestResult GetValue() override { return m_result; } public: // Async::HTTPDownloadTask // Get estimated file size. 0 if unavailable. virtual size_t GetEstimatedFileSize() override { return m_estimatedDownloadSize; } // Get currently downloaded data size virtual size_t GetDownloadedSize() override { return m_downloadedSize; } // Get progress value. If total estimated size is unavailable, always return 0.0. // Result value may in range [0.0, 1.0], but can exceed the range because of invalid estimation of size. isClipped can prevent it. virtual float GetEstimatedProgress(bool isClipped = true) override; // Request download stop virtual void RequestToCancelDownload() override { m_isCancelRequested.store(true); } // Check whether if the downloading finished by force before end of download. virtual bool IsCanceledDownload() override { return m_isCanceled.load(); } protected: const std::string m_downloadFilePath; const std::string m_requestURL; const RequestMethod m_requestMethod; const POSTParameterMap m_requestParameters; const int m_optionConnectTimeout; size_t m_estimatedDownloadSize; size_t m_downloadedSize; std::atomic_bool m_isCancelRequested; HTTPRequestResult m_result; std::atomic_bool m_isCanceled; public: static std::shared_ptr<CURLHTTPDownloadTask> StartHTTPDownloadAsync(Task::TaskManagerComponent *taskManager, const std::string &downloadFilePath, bool isBackgroundTask, const std::string &url, RequestMethod method = RequestMethod::kGet, const POSTParameterMap &parameters = kEmptyPOSTParameterMap, long connectTimeout = HTTP::Settings::GetHTTPRequestDefaultTimeoutInSec()); }; } } } #endif ======================= File: Engine/Modules/Task/GraphicTask/GraphicThreadWorker.h ======================= <filename>Engine/Modules/Task/GraphicTask/GraphicThreadWorker.h<gh_stars>10-100 //////////////////////////////////////////////////////////////////////////////// // GraphicTass/GraphicThreadWorker.h (Leggiero/Modules - Task) // // Thread Worker with Graphic Context //////////////////////////////////////////////////////////////////////////////// #ifndef __LM_TASK__GRAPHIC_TASK__GRAPHIC_THREAD_WORKER_H #define __LM_TASK__GRAPHIC_TASK__GRAPHIC_THREAD_WORKER_H // Leggiero.Basic #include <Basic/LeggieroBasic.h> // Standard Library #include <atomic> #include <memory> // Leggiero.Engine #include <Engine/Application/GameProcessAnchorObserver.h> // Leggiero.Task #include "../Processor/ThreadWorker.h" namespace Leggiero { // Forward Declarations namespace Engine { class GameProcessAnchor; } namespace Graphics { class IGLThreadContextInformation; } namespace Task { namespace GraphicTask { // Graphic Thread Worker class GraphicThreadWorker : public ThreadWorker , public Engine::GameProcessAnchorObserver::IGraphicPrepareHandler { public: GraphicThreadWorker(IThreadWorkerContext *pOwnerContext, Engine::GameProcessAnchor *gameAnchor); virtual ~GraphicThreadWorker(); protected: // ThreadWorker virtual bool _InitializeBeforeWork() override; virtual void _FinalizeAfterWork() override; virtual void _PostProcessAfterTask() override; virtual bool _LoopProcess() override; public: // IGraphicPrepareHandler virtual void GameProcess_OnGraphicPrepare(bool isFirstGraphicPrepare) override; protected: Engine::GameProcessAnchor *m_gameAnchor; bool m_isSubscribed; std::shared_ptr<Graphics::IGLThreadContextInformation> m_graphicsContext; std::atomic_bool m_checkAndRefreshRequested; }; } } } #endif ======================= File: Engine/Modules/FileSystem/_Internal/_AndroidBundleFileResourceComponent.h ======================= //////////////////////////////////////////////////////////////////////////////// // _Internal/_AndroidBundleFileResourceComponent.h (Leggiero/Modules - FileSystem) // // Android Platform's Bundled File Resources Component //////////////////////////////////////////////////////////////////////////////// #ifndef __LM_FILESYSTEM___INTERNAL__ANDROID_BUNDLE_FILE_RESOURCE_COMPONENT_H #define __LM_FILESYSTEM___INTERNAL__ANDROID_BUNDLE_FILE_RESOURCE_COMPONENT_H // Leggiero.Basic #include <Basic/LeggieroBasic.h> // Leggiero.FileSystem #include "../BundleFileResourceComponent.h" namespace Leggiero { namespace FileSystem { // Bundle File Resource Component class AndroidBundleFileResourceComponent : public BundleFileResourceComponent { public: AndroidBundleFileResourceComponent(); virtual ~AndroidBundleFileResourceComponent(); public: // BundleFileResourceComponent virtual bool IsBundleFileExists(const std::string &virtualPath) override; virtual size_t GetBundleFileLength(const std::string &virtualPath) override; virtual size_t ReadBundleFileData(const std::string &virtualPath, size_t offset, char *buffer, size_t bufferSize) override; virtual std::streamoff ReadBundleFileData(const std::string &virtualPath, std::streamoff offset, std::ostream &buffer) override; virtual bool IsDirectory(const std::string &virtualPath) override; virtual std::vector<std::string> ListSubDirectories(const std::string &virtualPath) override; virtual std::vector<std::string> ListFiles(const std::string &virtualPath) override; }; } } #endif ======================= File: Engine/Common/Engine/Module/EngineModuleException.h ======================= //////////////////////////////////////////////////////////////////////////////// // Module/EngineModuleException.h (Leggiero - Engine) // // Exceptions from Leggiero Engine Module System //////////////////////////////////////////////////////////////////////////////// #ifndef __ENGINE__MODULE__ENGINE_MODULE_EXCEPTION_H #define __ENGINE__MODULE__ENGINE_MODULE_EXCEPTION_H // Standard Library #include <exception> // Leggiero.Engine #include "EngineModuleId.h" namespace Leggiero { namespace ModuleSystem { // Exception due to cyclic dependency of engine modules class ModuleCyclicDependencyException : public std::exception { public: ModuleCyclicDependencyException() : ModuleCyclicDependencyException(EngineModuleIdType::kINVALID) { } ModuleCyclicDependencyException(EngineModuleIdType cyclicDetectedModule) : cyclicDetectedModule(cyclicDetectedModule) { } virtual ~ModuleCyclicDependencyException() throw() { } public: virtual const char *what() const throw() { return "Engine Modules have Cyclic Dependency"; } public: EngineModuleIdType cyclicDetectedModule; }; // Exception due to cyclic dependency of engine modules class ModuleMissingDependencyException : public std::exception { public: ModuleMissingDependencyException() : ModuleMissingDependencyException(EngineModuleIdType::kINVALID) { } ModuleMissingDependencyException(EngineModuleIdType notExistingModule) : missingModule(notExistingModule) { } virtual ~ModuleMissingDependencyException() throw() { } public: virtual const char *what() const throw() { return "Dependent Engine Module NOT Exists"; } public: EngineModuleIdType missingModule; }; } } #endif ======================= File: Engine/Modules/Application/SystemEventDispatcher.h ======================= //////////////////////////////////////////////////////////////////////////////// // SystemEventDispatcher.h (Leggiero/Modules - Application) // // System Event Dispatcher Sub-Component Base Class //////////////////////////////////////////////////////////////////////////////// #ifndef __LM_APPLICATION__SYSTEM_EVENT_DISPATCHER_H #define __LM_APPLICATION__SYSTEM_EVENT_DISPATCHER_H // Leggiero.Basic #include <Basic/LeggieroBasic.h> // Leggiero.Utility #include <Utility/Sugar/EventNotifier.h> namespace Leggiero { namespace Application { // Forward Declaration of Observer Interfaces class IApplicationEventObserver; class ISystemCommandEventObserver; class ISystemEventObserver; class IGraphicEventObserver; // System Event Dispatcher Base Class class SystemEventDispatcher { public: virtual ~SystemEventDispatcher() { } public: void RegisterApplicationEventObserver(IApplicationEventObserver *observer); void UnRegisterApplicationEventObserver(IApplicationEventObserver *observer); void RegisterCommandEventObserver(ISystemCommandEventObserver *observer); void UnRegisterCommandEventObserver(ISystemCommandEventObserver *observer); void RegisterSystemEventObserver(ISystemEventObserver *observer); void UnRegisterSystemEventObserver(ISystemEventObserver *observer); void RegisterGraphicEventObserver(IGraphicEventObserver *observer); void UnRegisterGraphicEventObserver(IGraphicEventObserver *observer); protected: Utility::DesignPattern::EventNotifier<IApplicationEventObserver *> m_applicationEventNotifier; Utility::DesignPattern::EventNotifier<ISystemCommandEventObserver *> m_commandEventNotifier; Utility::DesignPattern::EventNotifier<ISystemEventObserver *> m_systemEventNotifier; Utility::DesignPattern::EventNotifier<IGraphicEventObserver *> m_graphicEventNotifier; }; } } #endif ======================= File: Engine/Modules/Task/Processor/ITaskProcessor.h ======================= //////////////////////////////////////////////////////////////////////////////// // Processor/ITaskProcessor.h (Leggiero/Modules - Task) // // Interface for Task Processor Units //////////////////////////////////////////////////////////////////////////////// #ifndef __LM_TASK__PROCESSOR__I_TASK_PROCESSOR_H #define __LM_TASK__PROCESSOR__I_TASK_PROCESSOR_H // Leggiero.Basic #include <Basic/LeggieroBasic.h> // Leggiero.Task #include "../TaskTypes.h" namespace Leggiero { namespace Task { // Forward Declaration struct TaskExecutionEntry; // Interface of Task Processor Unit class ITaskProcessor { public: virtual ~ITaskProcessor() { } public: // Give job to processor virtual void GiveJob(TaskExecutionEntry *job) = 0; // Get task capability of the processor virtual TaskCapabilityType GetProcessorTaskCapability() { return TaskCapabilities::kGeneral; } // Is processor handle sleeps of its tasks? virtual bool IsManagingSleeps() { return false; } public: virtual void PrepareProcessorShutdown() { } }; } } #endif ======================= File: Engine/Modules/Graphics/Common/GLColor.h ======================= <filename>Engine/Modules/Graphics/Common/GLColor.h<gh_stars>10-100 //////////////////////////////////////////////////////////////////////////////// // Common/GLColor.h (Leggiero/Modules - Graphics) // // Provide Utilities for OpenGL Color //////////////////////////////////////////////////////////////////////////////// #ifndef __LM_GRAPHICS__COMMON__GL_COLOR_H #define __LM_GRAPHICS__COMMON__GL_COLOR_H // Leggiero.Basics #include <Basic/LeggieroBasic.h> // External Library #include <GLES3.h> namespace Leggiero { namespace Graphics { // Forward Declarations struct GLByteRGB; // Color represented as HSL Values // Each values have range [0.0, 1.0] struct HSLColor { public: float hue; float saturation; float lightness; public: HSLColor() : HSLColor(0.0f, 0.0f, 0.0f) { } HSLColor(float hue, float saturation, float lightness) : hue(hue), saturation(saturation), lightness(lightness) { } public: static HSLColor FromRGB(float r, float g, float b); static HSLColor FromRGB(const GLByteRGB &rgb); public: GLByteRGB ToRGB() const; void HueShift(float amount); void SaturationAdjust(float amount); void SaturationMultiply(float amount); void LightnessAdjust(float amount); void SetHue(float value); void SetSaturation(float value); void SetLightness(float value); }; // RGB Color by GLubyte struct GLByteRGB { public: GLubyte red; GLubyte green; GLubyte blue; public: GLByteRGB() : GLByteRGB(0, 0, 0) { } GLByteRGB(GLubyte red, GLubyte green, GLubyte blue) : red(red), green(green), blue(blue) { } GLByteRGB(int red, int green, int blue) : red((GLubyte)((red < 0)? 0 : ((red > 255)? 255 : red))) , green((GLubyte)((green < 0)? 0 : ((green > 255)? 255 : green))) , blue((GLubyte)((blue < 0)? 0 : ((blue > 255)? 255 : blue))) { } GLByteRGB(float red, float green, float blue) : red((GLubyte)((red < 0.0f)? 0.0f : ((red > 1.0f)? 255.0f : (GLubyte)(red * 255.0f)))) , green((GLubyte)((green < 0.0f)? 0.0f : ((green > 1.0f)? 255.0f : (GLubyte)(green * 255.0f)))) , blue((GLubyte)((blue < 0.0f)? 0.0f : ((blue > 1.0f)? 255.0f : (GLubyte)(blue * 255.0f)))) { } public: static const GLByteRGB kBlack; static const GLByteRGB kWhite; static const GLByteRGB kRed; static const GLByteRGB kGreen; static const GLByteRGB kBlue; public: static GLByteRGB Grey(GLubyte brightness); static GLByteRGB Grey(int brightness); static GLByteRGB Grey(float brightness); // Create a color based on a Color value in range [0.0, 1.0] // Same as HSV Color with S=100%, V=100%, for [0 Degree, 360 Degree] mapped from [0.0, 1.0] static GLByteRGB ChromaColor(float chroma); static GLByteRGB FromHSL(float h, float s, float l); static GLByteRGB FromHSL(const HSLColor &hsl); public: HSLColor ToHSL() const; public: bool operator ==(const GLByteRGB &rhs) const { return ((red == rhs.red) && (green == rhs.green) && (blue == rhs.blue)); } bool operator!=(const GLByteRGB &rhs) const { return!((*this) == rhs); } }; // ARGB Color by GLubyte struct GLByteARGB { public: GLubyte alpha; GLubyte red; GLubyte green; GLubyte blue; public: using ColorCodeType = uint32_t; public: GLByteARGB() : GLByteARGB(0, 0, 0, 0) { } GLByteARGB(GLubyte alpha, GLubyte red, GLubyte green, GLubyte blue) : alpha(alpha), red(red), green(green), blue(blue) { } GLByteARGB(int alpha, int red, int green, int blue) : alpha((GLubyte)((alpha < 0)? 0 : ((alpha > 255)? 255 : alpha))) , red((GLubyte)((red < 0)? 0 : ((red > 255)? 255 : red))) , green((GLubyte)((green < 0)? 0 : ((green > 255)? 255 : green))) , blue((GLubyte)((blue < 0)? 0 : ((blue > 255)? 255 : blue))) { } GLByteARGB(float alpha, float red, float green, float blue) : alpha((GLubyte)((alpha < 0.0f)? 0.0f : ((alpha > 1.0f)? 255.0f : (GLubyte)(alpha * 255.0f)))) , red((GLubyte)((red < 0.0f)? 0.0f : ((red > 1.0f)? 255.0f : (GLubyte)(red * 255.0f)))) , green((GLubyte)((green < 0.0f)? 0.0f : ((green > 1.0f)? 255.0f : (GLubyte)(green * 255.0f)))) , blue((GLubyte)((blue < 0.0f)? 0.0f : ((blue > 1.0f)? 255.0f : (GLubyte)(blue * 255.0f)))) { } GLByteARGB(const GLByteRGB &color, GLubyte alpha = (GLubyte)255) : alpha(alpha), red(color.red), green(color.green), blue(color.blue) { } public: ColorCodeType ToColorCodeARGB() const; ColorCodeType ToColorCodeRGBA() const; GLByteRGB ToGLByteRGB() const { return GLByteRGB(red, green, blue); } public: static const GLByteARGB kTransparent; static const GLByteARGB kBlack; static const GLByteARGB kWhite; static const GLByteARGB kRed; static const GLByteARGB kGreen; static const GLByteARGB kBlue; public: static GLByteARGB FromColorCodeARGB(ColorCodeType colorCode); static GLByteARGB FromColorCodeRGBA(ColorCodeType colorCode); static GLByteARGB Grey(GLubyte brightness, GLubyte alpha = (GLubyte)255); static GLByteARGB Grey(int brightness, int alpha = 255); static GLByteARGB Grey(float brightness, float alpha = 255.0f); // Create a color based on a Color value in range [0.0, 1.0] // Same as HSV Color with S=100%, V=100%, for [0 Degree, 360 Degree] mapped from [0.0, 1.0] static GLByteARGB ChromaColor(float chroma, float alpha = 255.0f); public: bool operator ==(const GLByteARGB &rhs) const { return ((red == rhs.red) && (green == rhs.green) && (blue == rhs.blue) && (alpha == rhs.alpha)); } bool operator!=(const GLByteARGB &rhs) const { return!((*this) == rhs); } }; } } #endif ======================= File: Engine/Modules/Sound/Provider/TestSoundProviders.h ======================= <reponame>LineGames/Leggiero<gh_stars>10-100 //////////////////////////////////////////////////////////////////////////////// // Provider/TestSoundProviders.h (Leggiero/Modules - Sound) // // Some example sound providers for testing purpose //////////////////////////////////////////////////////////////////////////////// #ifndef __LM_SOUND__PROVIDER__TEST_SOUND_PROVIDERS_H #define __LM_SOUND__PROVIDER__TEST_SOUND_PROVIDERS_H // Leggiero.Sound #include "ISoundProvider.h" namespace Leggiero { namespace Sound { // Sine Wave Sound Data Provider class SineWaveSoundProvider : public ISoundProvider { public: SineWaveSoundProvider(SampleFormat format, SamplingFrequencyType sampleFrequency, float length, float waveFrequency, float amplitude = 1.0f); virtual ~SineWaveSoundProvider(); protected: // Prevent Creating of NULL Sound Provider SineWaveSoundProvider() { } public: // ISoundProvider virtual SampleFormat GetFormat() const override { return m_format; } virtual SamplingFrequencyType GetFrequency() const override { return m_frequency; } virtual size_t GetSampleLength() const override { return (size_t)(m_lengthInSecond * (float)m_frequency); } virtual float GetLengthInSecond() const override { return m_lengthInSecond; } virtual size_t FillSampleData(void *dataBuffer, size_t bufferSize, SampleNumberType startSample, SampleNumberType *outWrittenSamples = nullptr) override; protected: float m_lengthInSecond; float m_waveFrequency; float m_waveAmplitude; SampleFormat m_format; SamplingFrequencyType m_frequency; void *m_bakedWave; size_t m_bakedPeriodLength; protected: void _BakePreSampledWave(); }; } } #endif ======================= File: Tools/ProjectCreator/Template/Project/Sources/App/Proj.WinPC/resource.h ======================= <reponame>LineGames/Leggiero<filename>Tools/ProjectCreator/Template/Project/Sources/App/Proj.WinPC/resource.h //{{NO_DEPENDENCIES}} // #define IDI_APPICON 201 // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 203 #define _APS_NEXT_COMMAND_VALUE 42001 #define _APS_NEXT_CONTROL_VALUE 2001 #define _APS_NEXT_SYMED_VALUE 202 #endif #endif ======================= File: Engine/Modules/FileSystem/_Internal/_WinPCBundleFileResourceComponent.h ======================= //////////////////////////////////////////////////////////////////////////////// // _Internal/_WinPCBundleFileResourceComponent.h (Leggiero/Modules - FileSystem) // // WinPC Platform's Bundled File Resources Component //////////////////////////////////////////////////////////////////////////////// #ifndef __LM_FILESYSTEM___INTERNAL__WINPC_BUNDLE_FILE_RESOURCE_COMPONENT_H #define __LM_FILESYSTEM___INTERNAL__WINPC_BUNDLE_FILE_RESOURCE_COMPONENT_H // Leggiero.Basic #include <Basic/LeggieroBasic.h> // Leggiero.FileSystem #include "../BundleFileResourceComponent.h" namespace Leggiero { namespace FileSystem { // Bundle File Resource Component class WinPCBundleFileResourceComponent : public BundleFileResourceComponent { public: WinPCBundleFileResourceComponent(); virtual ~WinPCBundleFileResourceComponent(); public: // EngineComponent // Initialize the Component virtual void InitializeComponent(Engine::GameProcessAnchor *gameAnchor) override; public: // BundleFileResourceComponent virtual bool IsBundleFileExists(const std::string &virtualPath) override; virtual size_t GetBundleFileLength(const std::string &virtualPath) override; virtual size_t ReadBundleFileData(const std::string &virtualPath, size_t offset, char *buffer, size_t bufferSize) override; virtual std::streamoff ReadBundleFileData(const std::string &virtualPath, std::streamoff offset, std::ostream &buffer) override; virtual bool IsDirectory(const std::string &virtualPath) override; virtual std::vector<std::string> ListSubDirectories(const std::string &virtualPath) override; virtual std::vector<std::string> ListFiles(const std::string &virtualPath) override; public: // NPO::INonPortableOptimization_BundleFileResource virtual bool NPO_IsEnable_BundleFileRealPath() const override { return true; } virtual std::string NPO_GetBundleFileRealPath(const std::string &virtualPath) override { return _GetBundleResourceFilePath(virtualPath); } protected: std::string _GetBundleResourceFilePath(const std::string &virtualPath) const; protected: std::string m_baseBundleRealPath; std::string m_platformOverrideBundleRealPath; }; } } #endif ======================= File: Engine/Modules/LUI/Common/UITransform.h ======================= <reponame>LineGames/Leggiero //////////////////////////////////////////////////////////////////////////////// // Common/UITransform.h (Leggiero/Modules - LegacyUI) // // 2D Transform that can applied to UI things //////////////////////////////////////////////////////////////////////////////// #ifndef __LM_LUI__COMMON__UI_TRANSFORM_H #define __LM_LUI__COMMON__UI_TRANSFORM_H // Standard Library #include <memory> // External Library #include <concurrentqueue/concurrentqueue.h> #define GLM_FORCE_RADIANS #include <glm/glm.hpp> // Leggiero.LegacyUI #include "UICommonTypes.h" namespace Leggiero { namespace LUI { // Common Interface for 2D Transform class IUITransform : public std::enable_shared_from_this<IUITransform> { public: virtual ~IUITransform() { } public: virtual UIVector2D ApplyTransform(UICoordinateType x, UICoordinateType y) = 0; virtual UIVector2D ApplyInverseTransform(UICoordinateType x, UICoordinateType y) = 0; public: virtual std::shared_ptr<IUITransform> Combine(std::shared_ptr<IUITransform> rhs); public: virtual bool _IsMatrixTransform() const { return false; } }; // Not-changing transform class IdentityTransform : public IUITransform { public: virtual ~IdentityTransform() { } public: virtual UIVector2D ApplyTransform(UICoordinateType x, UICoordinateType y) override { return UIVector2D(x, y); } virtual UIVector2D ApplyInverseTransform(UICoordinateType x, UICoordinateType y) override { return UIVector2D(x, y); } public: virtual std::shared_ptr<IUITransform> Combine(std::shared_ptr<IUITransform> rhs) override; public: // Pooled Transform Allocation static std::shared_ptr<IdentityTransform> AllocateTransform(); static void ReleaseTransform(std::shared_ptr<IdentityTransform> transformToRelease); protected: static moodycamel::ConcurrentQueue<std::shared_ptr<IdentityTransform> > ms_transformPool; }; // Offset transform class OffsetTransform : public IUITransform { public: OffsetTransform(UICoordinateType xOffset, UICoordinateType yOffset) : m_xOffset(xOffset), m_yOffset(yOffset) { } virtual ~OffsetTransform() { } public: virtual UIVector2D ApplyTransform(UICoordinateType x, UICoordinateType y) override { return UIVector2D(x + m_xOffset, y + m_yOffset); } virtual UIVector2D ApplyInverseTransform(UICoordinateType x, UICoordinateType y) override { return UIVector2D(x - m_xOffset, y - m_yOffset); } public: virtual std::shared_ptr<IUITransform> Combine(std::shared_ptr<IUITransform> rhs) override; public: UIVector2D GetOffset() const { return UIVector2D((UICoordinateType)m_xOffset, (UICoordinateType)m_yOffset); } UICoordinateType GetOffsetX() const { return (UICoordinateType)m_xOffset; } UICoordinateType GetOffsetY() const { return (UICoordinateType)m_yOffset; } void SetOffset(UICoordinateType xOffset, UICoordinateType yOffset) { m_xOffset = xOffset; m_yOffset = yOffset; } void SetOffsetX(UICoordinateType xOffset) { m_xOffset = xOffset; } void SetOffsetY(UICoordinateType yOffset) { m_yOffset = yOffset; } protected: UICoordinateType m_xOffset; UICoordinateType m_yOffset; public: // Pooled Transform Allocation static std::shared_ptr<OffsetTransform> AllocateTransform(UICoordinateType xOffset, UICoordinateType yOffset); static void ReleaseTransform(std::shared_ptr<OffsetTransform> transformToRelease); protected: static moodycamel::ConcurrentQueue<std::shared_ptr<OffsetTransform> > ms_transformPool; }; // Combine 2 transforms class UICombinedTransform : public IUITransform { public: UICombinedTransform(std::shared_ptr<IUITransform> pre, std::shared_ptr<IUITransform> post); virtual ~UICombinedTransform() { } public: virtual UIVector2D ApplyTransform(UICoordinateType x, UICoordinateType y) override; virtual UIVector2D ApplyInverseTransform(UICoordinateType x, UICoordinateType y) override; public: std::shared_ptr<IUITransform> GetPre() { return m_pre; } std::shared_ptr<IUITransform> GetPost() { return m_post; } protected: std::shared_ptr<IUITransform> m_pre; std::shared_ptr<IUITransform> m_post; public: // Pooled Transform Allocation static std::shared_ptr<UICombinedTransform> AllocateTransform(std::shared_ptr<IUITransform> pre, std::shared_ptr<IUITransform> post); static void ReleaseTransform(std::shared_ptr<UICombinedTransform> transformToRelease); protected: static moodycamel::ConcurrentQueue<std::shared_ptr<UICombinedTransform> > ms_transformPool; }; // Matrix based transform class UITransform : public IUITransform { public: UITransform(); UITransform(UITransform &rhs); UITransform(UITransform &&rhs); virtual ~UITransform(); public: // IUITransform virtual UIVector2D ApplyTransform(UICoordinateType x, UICoordinateType y) override; virtual UIVector2D ApplyInverseTransform(UICoordinateType x, UICoordinateType y) override; virtual std::shared_ptr<IUITransform> Combine(std::shared_ptr<IUITransform> rhs) override; public: UITransform operator*(UITransform &rhs); UITransform &operator=(UITransform &rhs); UITransform &operator*=(UITransform &rhs); UITransform operator*(UITransform &&rhs); UITransform &operator=(UITransform &&rhs); UITransform &operator*=(UITransform &&rhs); protected: virtual void _UpdateTransform(); virtual void _UpdateInverseTransform(); public: // IUITransform virtual bool _IsMatrixTransform() const override { return true; } protected: bool m_isTransformDirty; glm::mat3 m_transform; bool m_isInverseDirty; glm::mat3 m_inverseTransform; }; // Controllable parameter based UI transform class UIParameterTransform : public UITransform { public: UIParameterTransform(); virtual ~UIParameterTransform(); protected: // UITransform virtual void _UpdateTransform() override; public: UIVector2D GetTranslate() const { return UIVector2D((UICoordinateType)m_translate.x, (UICoordinateType)m_translate.y); } UICoordinateType GetTranslateX() const { return (UICoordinateType)m_translate.x; } UICoordinateType GetTranslateY() const { return (UICoordinateType)m_translate.y; } void SetTranslate(UICoordinateType x, UICoordinateType y) { if (m_translate.x!= (float)x || m_translate.y!= (float)y) { m_translate.x = (float)x; m_translate.y = (float)y; _Invalidate(); } } void SetTranslateX(UICoordinateType x) { if (m_translate.x!= (float)x) { m_translate.x = (float)x; _Invalidate(); } } void SetTranslateY(UICoordinateType y) { if (m_translate.y!= (float)y) { m_translate.y = (float)y; _Invalidate(); } } UIVector2D GetAnchor() const { return UIVector2D((UICoordinateType)m_anchor.x, (UICoordinateType)m_anchor.y); } UICoordinateType GetAnchorX() const { return (UICoordinateType)m_anchor.x; } UICoordinateType GetAnchorY() const { return (UICoordinateType)m_anchor.y; } void SetAnchor(UICoordinateType x, UICoordinateType y) { if (m_anchor.x!= (float)x || m_anchor.y!= (float)y) { m_anchor.x = (float)x; m_anchor.y = (float)y; _Invalidate(); } } void SetAnchorX(UICoordinateType x) { if (m_anchor.x!= (float)x) { m_anchor.x = (float)x; _Invalidate(); } } void SetAnchorY(UICoordinateType y) { if (m_anchor.y!= (float)y) { m_anchor.y = (float)y; _Invalidate(); } } float GetRotate() const { return m_rotate; } void SetRotate(float rotation) { if (m_rotate!= rotation) { m_rotate = rotation; _Invalidate(); } } void SetRotateInDegree(float rotationInDeg) { float rotationInRad = rotationInDeg * 0.017453278f; if (m_rotate!= rotationInRad) { m_rotate = rotationInRad; _Invalidate(); } } UIVector2D GetScale() const { return UIVector2D((UICoordinateType)m_scale.x, (UICoordinateType)m_scale.y); } UICoordinateType GetScaleX() const { return (UICoordinateType)m_scale.x; } UICoordinateType GetScaleY() const { return (UICoordinateType)m_scale.y; } void SetScale(UICoordinateType x, UICoordinateType y) { if (m_scale.x!= (float)x || m_scale.y!= (float)y) { m_scale.x = (float)x; m_scale.y = (float)y; _Invalidate(); } } void SetScaleX(UICoordinateType x) { if (m_scale.x!= (float)x) { m_scale.x = (float)x; _Invalidate(); } } void SetScaleY(UICoordinateType y) { if (m_scale.y!= (float)y) { m_scale.y = (float)y; _Invalidate(); } } UIVector2D GetSkew() const { return UIVector2D((UICoordinateType)m_skew.x, (UICoordinateType)m_skew.y); } UICoordinateType GetSkewX() const { return (UICoordinateType)m_skew.x; } UICoordinateType GetSkewY() const { return (UICoordinateType)m_skew.y; } void SetSkew(UICoordinateType x, UICoordinateType y) { if (m_skew.x!= (float)x || m_skew.y!= (float)y) { m_skew.x = (float)x; m_skew.y = (float)y; _Invalidate(); } } void SetSkewX(UICoordinateType x) { if (m_skew.x!= (float)x) { m_skew.x = (float)x; _Invalidate(); } } void SetSkewY(UICoordinateType y) { if (m_skew.y!= (float)y) { m_skew.y = (float)y; _Invalidate(); } } UIVector2D GetRoughPerspective() const { return UIVector2D((UICoordinateType)m_roughPerspective.x, (UICoordinateType)m_roughPerspective.y); } void SetRoughPerspective(UICoordinateType x, UICoordinateType y) { if (m_roughPerspective.x!= (float)x || m_roughPerspective.y!= (float)y) { m_roughPerspective.x = (float)x; m_roughPerspective.y = (float)y; _Invalidate(); } } protected: void _Invalidate() { m_isTransformDirty = true; m_isInverseDirty = true; } protected: glm::vec2 m_translate; glm::vec2 m_anchor; float m_rotate; glm::vec2 m_scale; glm::vec2 m_skew; // Rough pseudo-perspective transform // for optimization purpose. please use UIPerspectiveTransform or direct calculation to get accurate result glm::vec2 m_roughPerspective; }; // 2D Perspective Transform class UIPerspectiveTransform : public IUITransform { public: UIPerspectiveTransform(); UIPerspectiveTransform(const UIPerspectiveTransform &rhs); virtual ~UIPerspectiveTransform(); public: // IUITransform virtual UIVector2D ApplyTransform(UICoordinateType x, UICoordinateType y) override; virtual UIVector2D ApplyInverseTransform(UICoordinateType x, UICoordinateType y) override; public: UIPerspectiveTransform &operator=(const UIPerspectiveTransform &rhs); public: UIVector2D GetPerspective() const { return UIVector2D((UICoordinateType)m_perspective.x, (UICoordinateType)m_perspective.y); } UICoordinateType GetPerspectiveX() const { return (UICoordinateType)m_perspective.x; } UICoordinateType GetPerspectiveY() const { return (UICoordinateType)m_perspective.y; } void SetPerspective(UICoordinateType x, UICoordinateType y) { m_perspective.x = (float)x; m_perspective.y = (float)y; } void SetPerspectiveX(UICoordinateType x) { m_perspective.x = (float)x; } void SetPerspectiveY(UICoordinateType y) { m_perspective.y = (float)y; } UIVector2D GetPerspectiveFocus() const; UICoordinateType GetPerspectiveFocusX() const; UICoordinateType GetPerspectiveFocusY() const; void SetPerspectiveFocus(UICoordinateType x, UICoordinateType y); UIVector2D GetAnchor() const { return UIVector2D((UICoordinateType)m_anchor.x, (UICoordinateType)m_anchor.y); } UICoordinateType GetAnchorX() const { return (UICoordinateType)m_anchor.x; } UICoordinateType GetAnchorY() const { return (UICoordinateType)m_anchor.y; } void SetAnchor(UICoordinateType x, UICoordinateType y) { m_anchor.x = (float)x; m_anchor.y = (float)y; } void SetAnchorX(UICoordinateType x) { m_anchor.x = (float)x; } void SetAnchorY(UICoordinateType y) { m_anchor.y = (float)y; } protected: glm::vec2 m_perspective; glm::vec2 m_anchor; }; } } #endif ======================= File: Engine/Modules/LUI/Rendering/UIRenderingComponent.h ======================= <reponame>LineGames/Leggiero<filename>Engine/Modules/LUI/Rendering/UIRenderingComponent.h //////////////////////////////////////////////////////////////////////////////// // Rendering/UIRenderingComponent.h (Leggiero/Modules - LegacyUI) // // Renderable UI Component //////////////////////////////////////////////////////////////////////////////// #ifndef __LM_LUI__RENDERING__UI_RENDERING_COMPONENT_H #define __LM_LUI__RENDERING__UI_RENDERING_COMPONENT_H // Standard Library #include <memory> // Leggiero.LegacyUI #include "../Common/UICommonTypes.h" #include "../Component/IUIComponent.h" namespace Leggiero { namespace LUI { // Forward Declarations class UIRenderer; class IUITransform; class IUIClipping; // Renderable UI Component class UIRenderingComponent : public IUIComponent { public: UIRenderingComponent() { } virtual ~UIRenderingComponent() { } public: // IUIComponent virtual UIComponentType GetComponentType() const override { return UIComponentType::kRendering; } public: virtual void Render(const UIRenderer &renderer, IUITransform &effectiveTransform, const IUIClipping &effectiveClipping, float alpha) = 0; virtual UIElementSize GetVisualSize() { return UIElementSize(); } }; // Dummy rendering component: does not draw anything class DummyRenderingComponent : public UIRenderingComponent { public: DummyRenderingComponent() { } virtual ~DummyRenderingComponent() { } public: // IUIComponent virtual std::shared_ptr<IUIComponent> Clone(const UIObject &ownerObject) const override { return std::make_shared<DummyRenderingComponent>(); } public: // UIRenderingComponent virtual void Render(const UIRenderer &renderer, IUITransform &effectiveTransform, const IUIClipping &effectiveClipping, float alpha) override { } }; } } #endif ======================= File: Engine/Common/Engine/Module/EngineModuleId.h ======================= //////////////////////////////////////////////////////////////////////////////// // Module/EngineModuleId.h (Leggiero - Engine) // // Engine Module Id Definitions //////////////////////////////////////////////////////////////////////////////// #ifndef __ENGINE__MODULE__ENGINE_MODULE_ID_H #define __ENGINE__MODULE__ENGINE_MODULE_ID_H namespace Leggiero { // Engine Module Id Type enum class EngineModuleIdType { kINVALID = 0, kLog = 8, kHTTP = 51, kCrypto = 81, kGraphics = 200, kFont = 220, }; } #endif ======================= File: Engine/Modules/Sound/OpenALBackend/OpenALBufferedSoundPlayingContext.h ======================= <reponame>LineGames/Leggiero //////////////////////////////////////////////////////////////////////////////// // OpenALBackend/OpenALBufferedSoundPlayingContext.h (Leggiero/Modules - Sound) // // All data buffered Sound Playing Context in OpenAL Backend //////////////////////////////////////////////////////////////////////////////// #ifndef __LM_SOUND__OPENAL_BACKEND__OPENAL_BUFFERED_SOUND_PLAYING_CONTEXT_H #define __LM_SOUND__OPENAL_BACKEND__OPENAL_BUFFERED_SOUND_PLAYING_CONTEXT_H // Standard Library #include <atomic> #include <chrono> #include <memory> #include <vector> // External Library #include <OpenAL.h> // Leggiero.Utility #include <Utility/Object/PointerHolder.h> #include <Utility/Sugar/NonCopyable.h> #include <Utility/Threading/ManagedThreadPrimitives.h> // Leggiero.Sound #include "../Common/SoundTypes.h" #include "../Common/ISoundPlayingHandle.h" namespace Leggiero { namespace Sound { // Forward Declaration class ISoundProvider; namespace OpenAL { // Forward Declaration class OpenALSoundMixer; // Buffered Sound Playing Context class OpenALBufferedSoundPlayingContext : public ISoundPlayingHandle , public std::enable_shared_from_this<OpenALBufferedSoundPlayingContext> , private Utility::SyntacticSugar::NonCopyable { public: friend class OpenALSoundMixer; using MixerClass = OpenALSoundMixer; public: virtual ~OpenALBufferedSoundPlayingContext(); public: OpenALBufferedSoundPlayingContext(std::shared_ptr<ISoundProvider> soundProvider, std::shared_ptr<Utility::Object::PointerHolder> mixerHolder, ALuint source, ALuint buffer, bool isStartImmediately = true, float volume = 1.0f, bool isLooping = false, bool isPauseAfterFinish = false); private: OpenALBufferedSoundPlayingContext() = delete; public: virtual bool IsFinished() const override; virtual void Stop() override; virtual bool IsPaused() const override; virtual void Pause() override; virtual void Resume() override; virtual SampleNumberType GetCurrentPosition() override; virtual bool Seek(SampleNumberType samplePosition) override; virtual float GetVolume() const override { return m_volume; } virtual void SetVolume(float volume) override; public: void SetIsLooping(bool isLooping); bool IsLooping(); void Rewind(); void SetWillPauseAfterFinish(bool isPauseAfterFinish) { m_isPauseAfterFinish = isPauseAfterFinish; } bool IsWillPauseAfterFinish() const { return m_isPauseAfterFinish; } protected: void _Update(); void _PauseBySystem(); void _ResumeBySystem(); protected: void _FillBuffer(std::shared_ptr<ISoundProvider> &soundProvider); protected: bool m_isPlayFinished; Utility::Threading::SafePthreadLock m_pauseResumeCheckMutex; std::atomic_bool m_isPaused; std::atomic_bool m_isPausedBySystem; bool m_isPauseAfterFinish; std::atomic_bool m_isSourceReturned; ALuint m_source; ALuint m_buffer; size_t m_sampleSize; float m_volume; bool m_isVolumeChangeRequested; std::weak_ptr<Utility::Object::PointerHolder> m_mixerHolder; }; } } } #endif ======================= File: Engine/Common/Utility/Encoding/HexString.h ======================= //////////////////////////////////////////////////////////////////////////////// // Encoding/HexString.h (Leggiero - Utility) // // Binary - Hexadecimal string encoding utility //////////////////////////////////////////////////////////////////////////////// #ifndef __UTILITY__ENCODING__HEX_STRING_H #define __UTILITY__ENCODING__HEX_STRING_H // Leggiero.Basic #include <Basic/LeggieroBasic.h> // Standard Library #include <cstdint> #include <cstdio> #include <string> #include <vector> namespace Leggiero { namespace Utility { namespace Encoding { namespace HexString { std::string ToHexString(const std::string &binaryString, bool isCapital = false); std::string ToHexString(const void *dataBuffer, size_t dataLength, bool isCapital = false); size_t WriteHexString(const std::string &binaryString, char *buffer, size_t bufferLength, bool isCapital = false); size_t WriteHexString(const void *dataBuffer, size_t dataLength, char *buffer, size_t bufferLength, bool isCapital = false); size_t WriteHexString(const std::string &binaryString, std::vector<char> &buffer, bool isCapital = false); size_t WriteHexString(const void *dataBuffer, size_t dataLength, std::vector<char> &buffer, bool isCapital = false); std::string FromHexString(const std::string &hexString); std::string FromHexString(const char *stringBuffer, size_t stringLength); size_t ParseHexString(const std::string &hexString, void *buffer, size_t bufferLength); size_t ParseHexString(const char *stringBuffer, size_t stringLength, void *buffer, size_t bufferLength); size_t ParseHexString(const std::string &hexString, std::vector<uint8_t> &buffer); size_t ParseHexString(const char *stringBuffer, size_t stringLength, std::vector<uint8_t> &buffer); // Un-safe hex manipulation utilites class Unsafe { public: // Hope to faster than sprintf template <typename BufType> static void WriteOctetHex(BufType buf, size_t bufOffset, uint8_t hextData, bool isCapital) { switch (hextData) { case 0: buf[bufOffset] = '0'; buf[bufOffset + 1] = '0'; break; case 1: buf[bufOffset] = '0'; buf[bufOffset + 1] = '1'; break; case 2: buf[bufOffset] = '0'; buf[bufOffset + 1] = '2'; break; case 3: buf[bufOffset] = '0'; buf[bufOffset + 1] = '3'; break; case 4: buf[bufOffset] = '0'; buf[bufOffset + 1] = '4'; break; case 5: buf[bufOffset] = '0'; buf[bufOffset + 1] = '5'; break; case 6: buf[bufOffset] = '0'; buf[bufOffset + 1] = '6'; break; case 7: buf[bufOffset] = '0'; buf[bufOffset + 1] = '7'; break; case 8: buf[bufOffset] = '0'; buf[bufOffset + 1] = '8'; break; case 9: buf[bufOffset] = '0'; buf[bufOffset + 1] = '9'; break; case 10: buf[bufOffset] = '0'; buf[bufOffset + 1] = (isCapital? 'A' : 'a'); break; case 11: buf[bufOffset] = '0'; buf[bufOffset + 1] = (isCapital? 'B' : 'b'); break; case 12: buf[bufOffset] = '0'; buf[bufOffset + 1] = (isCapital? 'C' : 'c'); break; case 13: buf[bufOffset] = '0'; buf[bufOffset + 1] = (isCapital? 'D' : 'd'); break; case 14: buf[bufOffset] = '0'; buf[bufOffset + 1] = (isCapital? 'E' : 'e'); break; case 15: buf[bufOffset] = '0'; buf[bufOffset + 1] = (isCapital? 'F' : 'f'); break; case 16: buf[bufOffset] = '1'; buf[bufOffset + 1] = '0'; break; case 17: buf[bufOffset] = '1'; buf[bufOffset + 1] = '1'; break; case 18: buf[bufOffset] = '1'; buf[bufOffset + 1] = '2'; break; case 19: buf[bufOffset] = '1'; buf[bufOffset + 1] = '3'; break; case 20: buf[bufOffset] = '1'; buf[bufOffset + 1] = '4'; break; case 21: buf[bufOffset] = '1'; buf[bufOffset + 1] = '5'; break; case 22: buf[bufOffset] = '1'; buf[bufOffset + 1] = '6'; break; case 23: buf[bufOffset] = '1'; buf[bufOffset + 1] = '7'; break; case 24: buf[bufOffset] = '1'; buf[bufOffset + 1] = '8'; break; case 25: buf[bufOffset] = '1'; buf[bufOffset + 1] = '9'; break; case 26: buf[bufOffset] = '1'; buf[bufOffset + 1] = (isCapital? 'A' : 'a'); break; case 27: buf[bufOffset] = '1'; buf[bufOffset + 1] = (isCapital? 'B' : 'b'); break; case 28: buf[bufOffset] = '1'; buf[bufOffset + 1] = (isCapital? 'C' : 'c'); break; case 29: buf[bufOffset] = '1'; buf[bufOffset + 1] = (isCapital? 'D' : 'd'); break; case 30: buf[bufOffset] = '1'; buf[bufOffset + 1] = (isCapital? 'E' : 'e'); break; case 31: buf[bufOffset] = '1'; buf[bufOffset + 1] = (isCapital? 'F' : 'f'); break; case 32: buf[bufOffset] = '2'; buf[bufOffset + 1] = '0'; break; case 33: buf[bufOffset] = '2'; buf[bufOffset + 1] = '1'; break; case 34: buf[bufOffset] = '2'; buf[bufOffset + 1] = '2'; break; case 35: buf[bufOffset] = '2'; buf[bufOffset + 1] = '3'; break; case 36: buf[bufOffset] = '2'; buf[bufOffset + 1] = '4'; break; case 37: buf[bufOffset] = '2'; buf[bufOffset + 1] = '5'; break; case 38: buf[bufOffset] = '2'; buf[bufOffset + 1] = '6'; break; case 39: buf[bufOffset] = '2'; buf[bufOffset + 1] = '7'; break; case 40: buf[bufOffset] = '2'; buf[bufOffset + 1] = '8'; break; case 41: buf[bufOffset] = '2'; buf[bufOffset + 1] = '9'; break; case 42: buf[bufOffset] = '2'; buf[bufOffset + 1] = (isCapital? 'A' : 'a'); break; case 43: buf[bufOffset] = '2'; buf[bufOffset + 1] = (isCapital? 'B' : 'b'); break; case 44: buf[bufOffset] = '2'; buf[bufOffset + 1] = (isCapital? 'C' : 'c'); break; case 45: buf[bufOffset] = '2'; buf[bufOffset + 1] = (isCapital? 'D' : 'd'); break; case 46: buf[bufOffset] = '2'; buf[bufOffset + 1] = (isCapital? 'E' : 'e'); break; case 47: buf[bufOffset] = '2'; buf[bufOffset + 1] = (isCapital? 'F' : 'f'); break; case 48: buf[bufOffset] = '3'; buf[bufOffset + 1] = '0'; break; case 49: buf[bufOffset] = '3'; buf[bufOffset + 1] = '1'; break; case 50: buf[bufOffset] = '3'; buf[bufOffset + 1] = '2'; break; case 51: buf[bufOffset] = '3'; buf[bufOffset + 1] = '3'; break; case 52: buf[bufOffset] = '3'; buf[bufOffset + 1] = '4'; break; case 53: buf[bufOffset] = '3'; buf[bufOffset + 1] = '5'; break; case 54: buf[bufOffset] = '3'; buf[bufOffset + 1] = '6'; break; case 55: buf[bufOffset] = '3'; buf[bufOffset + 1] = '7'; break; case 56: buf[bufOffset] = '3'; buf[bufOffset + 1] = '8'; break; case 57: buf[bufOffset] = '3'; buf[bufOffset + 1] = '9'; break; case 58: buf[bufOffset] = '3'; buf[bufOffset + 1] = (isCapital? 'A' : 'a'); break; case 59: buf[bufOffset] = '3'; buf[bufOffset + 1] = (isCapital? 'B' : 'b'); break; case 60: buf[bufOffset] = '3'; buf[bufOffset + 1] = (isCapital? 'C' : 'c'); break; case 61: buf[bufOffset] = '3'; buf[bufOffset + 1] = (isCapital? 'D' : 'd'); break; case 62: buf[bufOffset] = '3'; buf[bufOffset + 1] = (isCapital? 'E' : 'e'); break; case 63: buf[bufOffset] = '3'; buf[bufOffset + 1] = (isCapital? 'F' : 'f'); break; case 64: buf[bufOffset] = '4'; buf[bufOffset + 1] = '0'; break; case 65: buf[bufOffset] = '4'; buf[bufOffset + 1] = '1'; break; case 66: buf[bufOffset] = '4'; buf[bufOffset + 1] = '2'; break; case 67: buf[bufOffset] = '4'; buf[bufOffset + 1] = '3'; break; case 68: buf[bufOffset] = '4'; buf[bufOffset + 1] = '4'; break; case 69: buf[bufOffset] = '4'; buf[bufOffset + 1] = '5'; break; case 70: buf[bufOffset] = '4'; buf[bufOffset + 1] = '6'; break; case 71: buf[bufOffset] = '4'; buf[bufOffset + 1] = '7'; break; case 72: buf[bufOffset] = '4'; buf[bufOffset + 1] = '8'; break; case 73: buf[bufOffset] = '4'; buf[bufOffset + 1] = '9'; break; case 74: buf[bufOffset] = '4'; buf[bufOffset + 1] = (isCapital? 'A' : 'a'); break; case 75: buf[bufOffset] = '4'; buf[bufOffset + 1] = (isCapital? 'B' : 'b'); break; case 76: buf[bufOffset] = '4'; buf[bufOffset + 1] = (isCapital? 'C' : 'c'); break; case 77: buf[bufOffset] = '4'; buf[bufOffset + 1] = (isCapital? 'D' : 'd'); break; case 78: buf[bufOffset] = '4'; buf[bufOffset + 1] = (isCapital? 'E' : 'e'); break; case 79: buf[bufOffset] = '4'; buf[bufOffset + 1] = (isCapital? 'F' : 'f'); break; case 80: buf[bufOffset] = '5'; buf[bufOffset + 1] = '0'; break; case 81: buf[bufOffset] = '5'; buf[bufOffset + 1] = '1'; break; case 82: buf[bufOffset] = '5'; buf[bufOffset + 1] = '2'; break; case 83: buf[bufOffset] = '5'; buf[bufOffset + 1] = '3'; break; case 84: buf[bufOffset] = '5'; buf[bufOffset + 1] = '4'; break; case 85: buf[bufOffset] = '5'; buf[bufOffset + 1] = '5'; break; case 86: buf[bufOffset] = '5'; buf[bufOffset + 1] = '6'; break; case 87: buf[bufOffset] = '5'; buf[bufOffset + 1] = '7'; break; case 88: buf[bufOffset] = '5'; buf[bufOffset + 1] = '8'; break; case 89: buf[bufOffset] = '5'; buf[bufOffset + 1] = '9'; break; case 90: buf[bufOffset] = '5'; buf[bufOffset + 1] = (isCapital? 'A' : 'a'); break; case 91: buf[bufOffset] = '5'; buf[bufOffset + 1] = (isCapital? 'B' : 'b'); break; case 92: buf[bufOffset] = '5'; buf[bufOffset + 1] = (isCapital? 'C' : 'c'); break; case 93: buf[bufOffset] = '5'; buf[bufOffset + 1] = (isCapital? 'D' : 'd'); break; case 94: buf[bufOffset] = '5'; buf[bufOffset + 1] = (isCapital? 'E' : 'e'); break; case 95: buf[bufOffset] = '5'; buf[bufOffset + 1] = (isCapital? 'F' : 'f'); break; case 96: buf[bufOffset] = '6'; buf[bufOffset + 1] = '0'; break; case 97: buf[bufOffset] = '6'; buf[bufOffset + 1] = '1'; break; case 98: buf[bufOffset] = '6'; buf[bufOffset + 1] = '2'; break; case 99: buf[bufOffset] = '6'; buf[bufOffset + 1] = '3'; break; case 100: buf[bufOffset] = '6'; buf[bufOffset + 1] = '4'; break; case 101: buf[bufOffset] = '6'; buf[bufOffset + 1] = '5'; break; case 102: buf[bufOffset] = '6'; buf[bufOffset + 1] = '6'; break; case 103: buf[bufOffset] = '6'; buf[bufOffset + 1] = '7'; break; case 104: buf[bufOffset] = '6'; buf[bufOffset + 1] = '8'; break; case 105: buf[bufOffset] = '6'; buf[bufOffset + 1] = '9'; break; case 106: buf[bufOffset] = '6'; buf[bufOffset + 1] = (isCapital? 'A' : 'a'); break; case 107: buf[bufOffset] = '6'; buf[bufOffset + 1] = (isCapital? 'B' : 'b'); break; case 108: buf[bufOffset] = '6'; buf[bufOffset + 1] = (isCapital? 'C' : 'c'); break; case 109: buf[bufOffset] = '6'; buf[bufOffset + 1] = (isCapital? 'D' : 'd'); break; case 110: buf[bufOffset] = '6'; buf[bufOffset + 1] = (isCapital? 'E' : 'e'); break; case 111: buf[bufOffset] = '6'; buf[bufOffset + 1] = (isCapital? 'F' : 'f'); break; case 112: buf[bufOffset] = '7'; buf[bufOffset + 1] = '0'; break; case 113: buf[bufOffset] = '7'; buf[bufOffset + 1] = '1'; break; case 114: buf[bufOffset] = '7'; buf[bufOffset + 1] = '2'; break; case 115: buf[bufOffset] = '7'; buf[bufOffset + 1] = '3'; break; case 116: buf[bufOffset] = '7'; buf[bufOffset + 1] = '4'; break; case 117: buf[bufOffset] = '7'; buf[bufOffset + 1] = '5'; break; case 118: buf[bufOffset] = '7'; buf[bufOffset + 1] = '6'; break; case 119: buf[bufOffset] = '7'; buf[bufOffset + 1] = '7'; break; case 120: buf[bufOffset] = '7'; buf[bufOffset + 1] = '8'; break; case 121: buf[bufOffset] = '7'; buf[bufOffset + 1] = '9'; break; case 122: buf[bufOffset] = '7'; buf[bufOffset + 1] = (isCapital? 'A' : 'a'); break; case 123: buf[bufOffset] = '7'; buf[bufOffset + 1] = (isCapital? 'B' : 'b'); break; case 124: buf[bufOffset] = '7'; buf[bufOffset + 1] = (isCapital? 'C' : 'c'); break; case 125: buf[bufOffset] = '7'; buf[bufOffset + 1] = (isCapital? 'D' : 'd'); break; case 126: buf[bufOffset] = '7'; buf[bufOffset + 1] = (isCapital? 'E' : 'e'); break; case 127: buf[bufOffset] = '7'; buf[bufOffset + 1] = (isCapital? 'F' : 'f'); break; case 128: buf[bufOffset] = '8'; buf[bufOffset + 1] = '0'; break; case 129: buf[bufOffset] = '8'; buf[bufOffset + 1] = '1'; break; case 130: buf[bufOffset] = '8'; buf[bufOffset + 1] = '2'; break; case 131: buf[bufOffset] = '8'; buf[bufOffset + 1] = '3'; break; case 132: buf[bufOffset] = '8'; buf[bufOffset + 1] = '4'; break; case 133: buf[bufOffset] = '8'; buf[bufOffset + 1] = '5'; break; case 134: buf[bufOffset] = '8'; buf[bufOffset + 1] = '6'; break; case 135: buf[bufOffset] = '8'; buf[bufOffset + 1] = '7'; break; case 136: buf[bufOffset] = '8'; buf[bufOffset + 1] = '8'; break; case 137: buf[bufOffset] = '8'; buf[bufOffset + 1] = '9'; break; case 138: buf[bufOffset] = '8'; buf[bufOffset + 1] = (isCapital? 'A' : 'a'); break; case 139: buf[bufOffset] = '8'; buf[bufOffset + 1] = (isCapital? 'B' : 'b'); break; case 140: buf[bufOffset] = '8'; buf[bufOffset + 1] = (isCapital? 'C' : 'c'); break; case 141: buf[bufOffset] = '8'; buf[bufOffset + 1] = (isCapital? 'D' : 'd'); break; case 142: buf[bufOffset] = '8'; buf[bufOffset + 1] = (isCapital? 'E' : 'e'); break; case 143: buf[bufOffset] = '8'; buf[bufOffset + 1] = (isCapital? 'F' : 'f'); break; case 144: buf[bufOffset] = '9'; buf[bufOffset + 1] = '0'; break; case 145: buf[bufOffset] = '9'; buf[bufOffset + 1] = '1'; break; case 146: buf[bufOffset] = '9'; buf[bufOffset + 1] = '2'; break; case 147: buf[bufOffset] = '9'; buf[bufOffset + 1] = '3'; break; case 148: buf[bufOffset] = '9'; buf[bufOffset + 1] = '4'; break; case 149: buf[bufOffset] = '9'; buf[bufOffset + 1] = '5'; break; case 150: buf[bufOffset] = '9'; buf[bufOffset + 1] = '6'; break; case 151: buf[bufOffset] = '9'; buf[bufOffset + 1] = '7'; break; case 152: buf[bufOffset] = '9'; buf[bufOffset + 1] = '8'; break; case 153: buf[bufOffset] = '9'; buf[bufOffset + 1] = '9'; break; case 154: buf[bufOffset] = '9'; buf[bufOffset + 1] = (isCapital? 'A' : 'a'); break; case 155: buf[bufOffset] = '9'; buf[bufOffset + 1] = (isCapital? 'B' : 'b'); break; case 156: buf[bufOffset] = '9'; buf[bufOffset + 1] = (isCapital? 'C' : 'c'); break; case 157: buf[bufOffset] = '9'; buf[bufOffset + 1] = (isCapital? 'D' : 'd'); break; case 158: buf[bufOffset] = '9'; buf[bufOffset + 1] = (isCapital? 'E' : 'e'); break; case 159: buf[bufOffset] = '9'; buf[bufOffset + 1] = (isCapital? 'F' : 'f'); break; case 160: buf[bufOffset] = (isCapital? 'A' : 'a'); buf[bufOffset + 1] = '0'; break; case 161: buf[bufOffset] = (isCapital? 'A' : 'a'); buf[bufOffset + 1] = '1'; break; case 162: buf[bufOffset] = (isCapital? 'A' : 'a'); buf[bufOffset + 1] = '2'; break; case 163: buf[bufOffset] = (isCapital? 'A' : 'a'); buf[bufOffset + 1] = '3'; break; case 164: buf[bufOffset] = (isCapital? 'A' : 'a'); buf[bufOffset + 1] = '4'; break; case 165: buf[bufOffset] = (isCapital? 'A' : 'a'); buf[bufOffset + 1] = '5'; break; case 166: buf[bufOffset] = (isCapital? 'A' : 'a'); buf[bufOffset + 1] = '6'; break; case 167: buf[bufOffset] = (isCapital? 'A' : 'a'); buf[bufOffset + 1] = '7'; break; case 168: buf[bufOffset] = (isCapital? 'A' : 'a'); buf[bufOffset + 1] = '8'; break; case 169: buf[bufOffset] = (isCapital? 'A' : 'a'); buf[bufOffset + 1] = '9'; break; case 170: buf[bufOffset] = (isCapital? 'A' : 'a'); buf[bufOffset + 1] = (isCapital? 'A' : 'a'); break; case 171: buf[bufOffset] = (isCapital? 'A' : 'a'); buf[bufOffset + 1] = (isCapital? 'B' : 'b'); break; case 172: buf[bufOffset] = (isCapital? 'A' : 'a'); buf[bufOffset + 1] = (isCapital? 'C' : 'c'); break; case 173: buf[bufOffset] = (isCapital? 'A' : 'a'); buf[bufOffset + 1] = (isCapital? 'D' : 'd'); break; case 174: buf[bufOffset] = (isCapital? 'A' : 'a'); buf[bufOffset + 1] = (isCapital? 'E' : 'e'); break; case 175: buf[bufOffset] = (isCapital? 'A' : 'a'); buf[bufOffset + 1] = (isCapital? 'F' : 'f'); break; case 176: buf[bufOffset] = (isCapital? 'B' : 'b'); buf[bufOffset + 1] = '0'; break; case 177: buf[bufOffset] = (isCapital? 'B' : 'b'); buf[bufOffset + 1] = '1'; break; case 178: buf[bufOffset] = (isCapital? 'B' : 'b'); buf[bufOffset + 1] = '2'; break; case 179: buf[bufOffset] = (isCapital? 'B' : 'b'); buf[bufOffset + 1] = '3'; break; case 180: buf[bufOffset] = (isCapital? 'B' : 'b'); buf[bufOffset + 1] = '4'; break; case 181: buf[bufOffset] = (isCapital? 'B' : 'b'); buf[bufOffset + 1] = '5'; break; case 182: buf[bufOffset] = (isCapital? 'B' : 'b'); buf[bufOffset + 1] = '6'; break; case 183: buf[bufOffset] = (isCapital? 'B' : 'b'); buf[bufOffset + 1] = '7'; break; case 184: buf[bufOffset] = (isCapital? 'B' : 'b'); buf[bufOffset + 1] = '8'; break; case 185: buf[bufOffset] = (isCapital? 'B' : 'b'); buf[bufOffset + 1] = '9'; break; case 186: buf[bufOffset] = (isCapital? 'B' : 'b'); buf[bufOffset + 1] = (isCapital? 'A' : 'a'); break; case 187: buf[bufOffset] = (isCapital? 'B' : 'b'); buf[bufOffset + 1] = (isCapital? 'B' : 'b'); break; case 188: buf[bufOffset] = (isCapital? 'B' : 'b'); buf[bufOffset + 1] = (isCapital? 'C' : 'c'); break; case 189: buf[bufOffset] = (isCapital? 'B' : 'b'); buf[bufOffset + 1] = (isCapital? 'D' : 'd'); break; case 190: buf[bufOffset] = (isCapital? 'B' : 'b'); buf[bufOffset + 1] = (isCapital? 'E' : 'e'); break; case 191: buf[bufOffset] = (isCapital? 'B' : 'b'); buf[bufOffset + 1] = (isCapital? 'F' : 'f'); break; case 192: buf[bufOffset] = (isCapital? 'C' : 'c'); buf[bufOffset + 1] = '0'; break; case 193: buf[bufOffset] = (isCapital? 'C' : 'c'); buf[bufOffset + 1] = '1'; break; case 194: buf[bufOffset] = (isCapital? 'C' : 'c'); buf[bufOffset + 1] = '2'; break; case 195: buf[bufOffset] = (isCapital? 'C' : 'c'); buf[bufOffset + 1] = '3'; break; case 196: buf[bufOffset] = (isCapital? 'C' : 'c'); buf[bufOffset + 1] = '4'; break; case 197: buf[bufOffset] = (isCapital? 'C' : 'c'); buf[bufOffset + 1] = '5'; break; case 198: buf[bufOffset] = (isCapital? 'C' : 'c'); buf[bufOffset + 1] = '6'; break; case 199: buf[bufOffset] = (isCapital? 'C' : 'c'); buf[bufOffset + 1] = '7'; break; case 200: buf[bufOffset] = (isCapital? 'C' : 'c'); buf[bufOffset + 1] = '8'; break; case 201: buf[bufOffset] = (isCapital? 'C' : 'c'); buf[bufOffset + 1] = '9'; break; case 202: buf[bufOffset] = (isCapital? 'C' : 'c'); buf[bufOffset + 1] = (isCapital? 'A' : 'a'); break; case 203: buf[bufOffset] = (isCapital? 'C' : 'c'); buf[bufOffset + 1] = (isCapital? 'B' : 'b'); break; case 204: buf[bufOffset] = (isCapital? 'C' : 'c'); buf[bufOffset + 1] = (isCapital? 'C' : 'c'); break; case 205: buf[bufOffset] = (isCapital? 'C' : 'c'); buf[bufOffset + 1] = (isCapital? 'D' : 'd'); break; case 206: buf[bufOffset] = (isCapital? 'C' : 'c'); buf[bufOffset + 1] = (isCapital? 'E' : 'e'); break; case 207: buf[bufOffset] = (isCapital? 'C' : 'c'); buf[bufOffset + 1] = (isCapital? 'F' : 'f'); break; case 208: buf[bufOffset] = (isCapital? 'D' : 'd'); buf[bufOffset + 1] = '0'; break; case 209: buf[bufOffset] = (isCapital? 'D' : 'd'); buf[bufOffset + 1] = '1'; break; case 210: buf[bufOffset] = (isCapital? 'D' : 'd'); buf[bufOffset + 1] = '2'; break; case 211: buf[bufOffset] = (isCapital? 'D' : 'd'); buf[bufOffset + 1] = '3'; break; case 212: buf[bufOffset] = (isCapital? 'D' : 'd'); buf[bufOffset + 1] = '4'; break; case 213: buf[bufOffset] = (isCapital? 'D' : 'd'); buf[bufOffset + 1] = '5'; break; case 214: buf[bufOffset] = (isCapital? 'D' : 'd'); buf[bufOffset + 1] = '6'; break; case 215: buf[bufOffset] = (isCapital? 'D' : 'd'); buf[bufOffset + 1] = '7'; break; case 216: buf[bufOffset] = (isCapital? 'D' : 'd'); buf[bufOffset + 1] = '8'; break; case 217: buf[bufOffset] = (isCapital? 'D' : 'd'); buf[bufOffset + 1] = '9'; break; case 218: buf[bufOffset] = (isCapital? 'D' : 'd'); buf[bufOffset + 1] = (isCapital? 'A' : 'a'); break; case 219: buf[bufOffset] = (isCapital? 'D' : 'd'); buf[bufOffset + 1] = (isCapital? 'B' : 'b'); break; case 220: buf[bufOffset] = (isCapital? 'D' : 'd'); buf[bufOffset + 1] = (isCapital? 'C' : 'c'); break; case 221: buf[bufOffset] = (isCapital? 'D' : 'd'); buf[bufOffset + 1] = (isCapital? 'D' : 'd'); break; case 222: buf[bufOffset] = (isCapital? 'D' : 'd'); buf[bufOffset + 1] = (isCapital? 'E' : 'e'); break; case 223: buf[bufOffset] = (isCapital? 'D' : 'd'); buf[bufOffset + 1] = (isCapital? 'F' : 'f'); break; case 224: buf[bufOffset] = (isCapital? 'E' : 'e'); buf[bufOffset + 1] = '0'; break; case 225: buf[bufOffset] = (isCapital? 'E' : 'e'); buf[bufOffset + 1] = '1'; break; case 226: buf[bufOffset] = (isCapital? 'E' : 'e'); buf[bufOffset + 1] = '2'; break; case 227: buf[bufOffset] = (isCapital? 'E' : 'e'); buf[bufOffset + 1] = '3'; break; case 228: buf[bufOffset] = (isCapital? 'E' : 'e'); buf[bufOffset + 1] = '4'; break; case 229: buf[bufOffset] = (isCapital? 'E' : 'e'); buf[bufOffset + 1] = '5'; break; case 230: buf[bufOffset] = (isCapital? 'E' : 'e'); buf[bufOffset + 1] = '6'; break; case 231: buf[bufOffset] = (isCapital? 'E' : 'e'); buf[bufOffset + 1] = '7'; break; case 232: buf[bufOffset] = (isCapital? 'E' : 'e'); buf[bufOffset + 1] = '8'; break; case 233: buf[bufOffset] = (isCapital? 'E' : 'e'); buf[bufOffset + 1] = '9'; break; case 234: buf[bufOffset] = (isCapital? 'E' : 'e'); buf[bufOffset + 1] = (isCapital? 'A' : 'a'); break; case 235: buf[bufOffset] = (isCapital? 'E' : 'e'); buf[bufOffset + 1] = (isCapital? 'B' : 'b'); break; case 236: buf[bufOffset] = (isCapital? 'E' : 'e'); buf[bufOffset + 1] = (isCapital? 'C' : 'c'); break; case 237: buf[bufOffset] = (isCapital? 'E' : 'e'); buf[bufOffset + 1] = (isCapital? 'D' : 'd'); break; case 238: buf[bufOffset] = (isCapital? 'E' : 'e'); buf[bufOffset + 1] = (isCapital? 'E' : 'e'); break; case 239: buf[bufOffset] = (isCapital? 'E' : 'e'); buf[bufOffset + 1] = (isCapital? 'F' : 'f'); break; case 240: buf[bufOffset] = (isCapital? 'F' : 'f'); buf[bufOffset + 1] = '0'; break; case 241: buf[bufOffset] = (isCapital? 'F' : 'f'); buf[bufOffset + 1] = '1'; break; case 242: buf[bufOffset] = (isCapital? 'F' : 'f'); buf[bufOffset + 1] = '2'; break; case 243: buf[bufOffset] = (isCapital? 'F' : 'f'); buf[bufOffset + 1] = '3'; break; case 244: buf[bufOffset] = (isCapital? 'F' : 'f'); buf[bufOffset + 1] = '4'; break; case 245: buf[bufOffset] = (isCapital? 'F' : 'f'); buf[bufOffset + 1] = '5'; break; case 246: buf[bufOffset] = (isCapital? 'F' : 'f'); buf[bufOffset + 1] = '6'; break; case 247: buf[bufOffset] = (isCapital? 'F' : 'f'); buf[bufOffset + 1] = '7'; break; case 248: buf[bufOffset] = (isCapital? 'F' : 'f'); buf[bufOffset + 1] = '8'; break; case 249: buf[bufOffset] = (isCapital? 'F' : 'f'); buf[bufOffset + 1] = '9'; break; case 250: buf[bufOffset] = (isCapital? 'F' : 'f'); buf[bufOffset + 1] = (isCapital? 'A' : 'a'); break; case 251: buf[bufOffset] = (isCapital? 'F' : 'f'); buf[bufOffset + 1] = (isCapital? 'B' : 'b'); break; case 252: buf[bufOffset] = (isCapital? 'F' : 'f'); buf[bufOffset + 1] = (isCapital? 'C' : 'c'); break; case 253: buf[bufOffset] = (isCapital? 'F' : 'f'); buf[bufOffset + 1] = (isCapital? 'D' : 'd'); break; case 254: buf[bufOffset] = (isCapital? 'F' : 'f'); buf[bufOffset + 1] = (isCapital? 'E' : 'e'); break; case 255: buf[bufOffset] = (isCapital? 'F' : 'f'); buf[bufOffset + 1] = (isCapital? 'F' : 'f'); break; } } template <typename BufType> static uint8_t ReadOctetHex(BufType buf, size_t bufOffset) { uint8_t res = 0; switch (buf[bufOffset]) { case '1': res += 0x10; break; case '2': res += 0x20; break; case '3': res += 0x30; break; case '4': res += 0x40; break; case '5': res += 0x50; break; case '6': res += 0x60; break; case '7': res += 0x70; break; case '8': res += 0x80; break; case '9': res += 0x90; break; case 'A': case 'a': res += 0xA0; break; case 'B': case 'b': res += 0xB0; break; case 'C': case 'c': res += 0xC0; break; case 'D': case 'd': res += 0xD0; break; case 'E': case 'e': res += 0xE0; break; case 'F': case 'f': res += 0xF0; break; } switch (buf[bufOffset + 1]) { case '1': res += 0x1; break; case '2': res += 0x2; break; case '3': res += 0x3; break; case '4': res += 0x4; break; case '5': res += 0x5; break; case '6': res += 0x6; break; case '7': res += 0x7; break; case '8': res += 0x8; break; case '9': res += 0x9; break; case 'A': case 'a': res += 0xA; break; case 'B': case 'b': res += 0xB; break; case 'C': case 'c': res += 0xC; break; case 'D': case 'd': res += 0xD; break; case 'E': case 'e': res += 0xE; break; case 'F': case 'f': res += 0xF; break; } return res; } }; template <size_t DATA_LENGTH> inline std::string GetFixedLengthHexString(const std::string &binaryString, bool isCapital = false) { char hexCString[DATA_LENGTH * 2 + 1]; for (size_t i = 0; i < DATA_LENGTH; ++i) { union { char source; uint8_t target; } a = { binaryString[i] }; Unsafe::WriteOctetHex(hexCString, i * 2, a.target, isCapital); } hexCString[DATA_LENGTH * 2] = '\0'; return hexCString; } template <size_t DATA_LENGTH> inline std::string GetFixedLengthHexString(const void *dataBuffer, bool isCapital = false) { char hexCString[DATA_LENGTH * 2 + 1]; const uint8_t *byteBuffer = (const uint8_t *)dataBuffer; for (size_t i = 0; i < DATA_LENGTH; ++i) { Unsafe::WriteOctetHex(hexCString, i * 2, byteBuffer[i], isCapital); } hexCString[DATA_LENGTH * 2] = '\0'; return hexCString; } } } } } #endif ======================= File: Engine/Modules/LUI/Rendering/UIRenderingUtility.h ======================= //////////////////////////////////////////////////////////////////////////////// // Rendering/UIRenderingUtility.h (Leggiero/Modules - LegacyUI) // // UI Rendering Utilites //////////////////////////////////////////////////////////////////////////////// #ifndef __LM_LUI__RENDERING__UI_RENDERING_UTILITY_H #define __LM_LUI__RENDERING__UI_RENDERING_UTILITY_H // Standard Library #include <memory> #include <vector> // External Library #include <glm/glm.hpp> // Leggiero.Graphics #include <Graphics/Common/GLColor.h> #include <Graphics/Texture/TextureSection.h> #include <Graphics/Shader/CommonGLVertexType.h> // Leggiero.LegacyUI #include "../Common/UICommonTypes.h" #include "UIClipping.h" namespace Leggiero { namespace LUI { namespace RenderingUtility { //------------------------------------------------------------------------------ template <typename VertexT> inline void PrepareRenderPolygon(const std::vector<VertexT> &vertexPolygon, const IUIClipping &clipping, std::vector<VertexT> &vertexBuffer, std::vector<GLushort> &indexBuffer) { std::vector<VertexT> clippedPolygon(clipping.ClipPolygon(vertexPolygon)); size_t startIndex = vertexBuffer.size(); vertexBuffer.insert(vertexBuffer.end(), clippedPolygon.begin(), clippedPolygon.end()); size_t vertexCount = clippedPolygon.size(); for (size_t i = 2; i < vertexCount; ++i) { indexBuffer.push_back((GLushort)(startIndex)); indexBuffer.push_back((GLushort)(startIndex + i - 1)); indexBuffer.push_back((GLushort)(startIndex + i)); } } //------------------------------------------------------------------------------ inline void PrepareRenderTextureRect(UIVector2D lt, UIVector2D rt, UIVector2D lb, UIVector2D rb, const Graphics::TextureRectSection &textureSection, const Graphics::GLByteARGB &color, const IUIClipping &clipping, bool isFlipHorizontal, bool isFlipVertical, bool isGridRounding, std::vector<Graphics::TextureColoredVertex> &vertexBuffer, std::vector<GLushort> &indexBuffer) { float leftU = textureSection.GetTexelLeft(); float rightU = textureSection.GetTexelRight(); float topV = textureSection.GetTexelTop(); float bottomV = textureSection.GetTexelBottom(); if (isFlipHorizontal) { float tmp = leftU; leftU = rightU; rightU = tmp; } if (isFlipVertical) { float tmp = topV; topV = bottomV; bottomV = tmp; } if (isGridRounding) { if (fabs(lt.x - rt.x) < kFloatEpsilon && fabs(lb.x - rb.x) < kFloatEpsilon) { lt.x = round(lt.x); rt.x = round(rt.x); lb.x = round(lb.x); rb.x = round(rb.x); } else if (fabs(lt.x - lb.x) < kFloatEpsilon && fabs(rt.x - rb.x) < kFloatEpsilon) { lt.x = round(lt.x); rt.x = round(rt.x); lb.x = round(lb.x); rb.x = round(rb.x); } if (fabs(lt.y - rt.y) < kFloatEpsilon && fabs(lb.y - rb.y) < kFloatEpsilon) { lt.y = round(lt.y); rt.y = round(rt.y); lb.y = round(lb.y); rb.y = round(rb.y); } else if (fabs(lt.y - lb.y) < kFloatEpsilon && fabs(rt.y - rb.y) < kFloatEpsilon) { lt.y = round(lt.y); rt.y = round(rt.y); lb.y = round(lb.y); rb.y = round(rb.y); } } std::vector<Graphics::TextureColoredVertex> polygon({ { { (float)lt.x, (float)lt.y, 0.0f, 1.0f },{ color.red, color.green, color.blue, color.alpha },{ leftU, topV } }, { { (float)rt.x, (float)rt.y, 0.0f, 1.0f },{ color.red, color.green, color.blue, color.alpha },{ rightU, topV } }, { { (float)rb.x, (float)rb.y, 0.0f, 1.0f },{ color.red, color.green, color.blue, color.alpha },{ rightU, bottomV } }, { { (float)lb.x, (float)lb.y, 0.0f, 1.0f },{ color.red, color.green, color.blue, color.alpha },{ leftU, bottomV } } }); PrepareRenderPolygon(polygon, clipping, vertexBuffer, indexBuffer); } //------------------------------------------------------------------------------ inline void PrepareRenderColoredRect(UIVector2D lt, UIVector2D rt, UIVector2D lb, UIVector2D rb, const Graphics::GLByteARGB &color, const IUIClipping &clipping, bool isGridRounding, std::vector<Graphics::ColoredVertex> &vertexBuffer, std::vector<GLushort> &indexBuffer) { if (isGridRounding) { if (fabs(lt.x - rt.x) < kFloatEpsilon && fabs(lb.x - rb.x) < kFloatEpsilon) { lt.x = round(lt.x); rt.x = round(rt.x); lb.x = round(lb.x); rb.x = round(rb.x); } else if (fabs(lt.x - lb.x) < kFloatEpsilon && fabs(rt.x - rb.x) < kFloatEpsilon) { lt.x = round(lt.x); rt.x = round(rt.x); lb.x
1,503
Headers() ]; }, function ($exception) { $response = $exception->getResponse(); $statusCode = $response->getStatusCode(); throw new ApiException( sprintf( '[%d] Error connecting to the API (%s)', $statusCode, $exception->getRequest()->getUri() ), $statusCode, $response->getHeaders(), $response->getBody() ); } ); } /** * Create request for operation 'taskWorkGetTaskWorkById' * * @param int $task_work_id Taskwork identifier (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Psr7\Request */ protected function taskWorkGetTaskWorkByIdRequest($task_work_id) { // verify the required parameter 'task_work_id' is set if ($task_work_id === null) { throw new \InvalidArgumentException( 'Missing the required parameter $task_work_id when calling taskWorkGetTaskWorkById' ); } $resourcePath = '/api/TaskWork/{taskWorkId}'; $formParams = []; $queryParams = []; $headerParams = []; $httpBody = ''; $multipart = false; // path params if ($task_work_id!== null) { $resourcePath = str_replace( '{'. 'taskWorkId'. '}', ObjectSerializer::toPathValue($task_work_id), $resourcePath ); } // body params $_tempBody = null; if ($multipart) { $headers = $this->headerSelector->selectHeadersForMultipart( ['application/json', 'text/json', 'application/xml', 'text/xml'] ); } else { $headers = $this->headerSelector->selectHeaders( ['application/json', 'text/json', 'application/xml', 'text/xml'], [] ); } // for model (json/xml) if (isset($_tempBody)) { // $_tempBody is the method argument, if present $httpBody = $_tempBody; // \stdClass has no __toString(), so we should encode it manually if ($httpBody instanceof \stdClass && $headers['Content-Type'] === 'application/json') { $httpBody = \GuzzleHttp\json_encode($httpBody); } } elseif (count($formParams) > 0) { if ($multipart) { $multipartContents = []; foreach ($formParams as $formParamName => $formParamValue) { $multipartContents[] = [ 'name' => $formParamName, 'contents' => $formParamValue ]; } // for HTTP post (form) $httpBody = new MultipartStream($multipartContents); } elseif ($headers['Content-Type'] === 'application/json') { $httpBody = \GuzzleHttp\json_encode($formParams); } else { // for HTTP post (form) $httpBody = \GuzzleHttp\Psr7\build_query($formParams); } } // this endpoint requires API key authentication $apiKey = $this->config->getApiKeyWithPrefix('Authorization'); if ($apiKey!== null) { $headers['Authorization'] = $apiKey; } $defaultHeaders = []; if ($this->config->getUserAgent()) { $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); } $headers = array_merge( $defaultHeaders, $headerParams, $headers ); $query = \GuzzleHttp\Psr7\build_query($queryParams); return new Request( 'GET', $this->config->getHost(). $resourcePath. ($query? "?{$query}" : ''), $headers, $httpBody ); } /** * Operation taskWorkGetTaskWorkForAutoAssign * * This call returns all autoassigned taskwork associated with a document * * @param int $docnumber Document identifier (required) * * @throws \Swagger\Client\ApiException on non-2xx response * @throws \InvalidArgumentException * @return \Swagger\Client\Model\TaskWorkDTO[] */ public function taskWorkGetTaskWorkForAutoAssign($docnumber) { list($response) = $this->taskWorkGetTaskWorkForAutoAssignWithHttpInfo($docnumber); return $response; } /** * Operation taskWorkGetTaskWorkForAutoAssignWithHttpInfo * * This call returns all autoassigned taskwork associated with a document * * @param int $docnumber Document identifier (required) * * @throws \Swagger\Client\ApiException on non-2xx response * @throws \InvalidArgumentException * @return array of \Swagger\Client\Model\TaskWorkDTO[], HTTP status code, HTTP response headers (array of strings) */ public function taskWorkGetTaskWorkForAutoAssignWithHttpInfo($docnumber) { $returnType = '\Swagger\Client\Model\TaskWorkDTO[]'; $request = $this->taskWorkGetTaskWorkForAutoAssignRequest($docnumber); try { $options = $this->createHttpClientOption(); try { $response = $this->client->send($request, $options); } catch (RequestException $e) { throw new ApiException( "[{$e->getCode()}] {$e->getMessage()}", $e->getCode(), $e->getResponse()? $e->getResponse()->getHeaders() : null, $e->getResponse()? $e->getResponse()->getBody()->getContents() : null ); } $statusCode = $response->getStatusCode(); if ($statusCode < 200 || $statusCode > 299) { throw new ApiException( sprintf( '[%d] Error connecting to the API (%s)', $statusCode, $request->getUri() ), $statusCode, $response->getHeaders(), $response->getBody() ); } $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer } else { $content = $responseBody->getContents(); if ($returnType!=='string') { $content = json_decode($content); } } return [ ObjectSerializer::deserialize($content, $returnType, []), $response->getStatusCode(), $response->getHeaders() ]; } catch (ApiException $e) { switch ($e->getCode()) { case 200: $data = ObjectSerializer::deserialize( $e->getResponseBody(), '\Swagger\Client\Model\TaskWorkDTO[]', $e->getResponseHeaders() ); $e->setResponseObject($data); break; } throw $e; } } /** * Operation taskWorkGetTaskWorkForAutoAssignAsync * * This call returns all autoassigned taskwork associated with a document * * @param int $docnumber Document identifier (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Promise\PromiseInterface */ public function taskWorkGetTaskWorkForAutoAssignAsync($docnumber) { return $this->taskWorkGetTaskWorkForAutoAssignAsyncWithHttpInfo($docnumber) ->then( function ($response) { return $response[0]; } ); } /** * Operation taskWorkGetTaskWorkForAutoAssignAsyncWithHttpInfo * * This call returns all autoassigned taskwork associated with a document * * @param int $docnumber Document identifier (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Promise\PromiseInterface */ public function taskWorkGetTaskWorkForAutoAssignAsyncWithHttpInfo($docnumber) { $returnType = '\Swagger\Client\Model\TaskWorkDTO[]'; $request = $this->taskWorkGetTaskWorkForAutoAssignRequest($docnumber); return $this->client ->sendAsync($request, $this->createHttpClientOption()) ->then( function ($response) use ($returnType) { $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer } else { $content = $responseBody->getContents(); if ($returnType!=='string') { $content = json_decode($content); } } return [ ObjectSerializer::deserialize($content, $returnType, []), $response->getStatusCode(), $response->getHeaders() ]; }, function ($exception) { $response = $exception->getResponse(); $statusCode = $response->getStatusCode(); throw new ApiException( sprintf( '[%d] Error connecting to the API (%s)', $statusCode, $exception->getRequest()->getUri() ), $statusCode, $response->getHeaders(), $response->getBody() ); } ); } /** * Create request for operation 'taskWorkGetTaskWorkForAutoAssign' * * @param int $docnumber Document identifier (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Psr7\Request */ protected function taskWorkGetTaskWorkForAutoAssignRequest($docnumber) { // verify the required parameter 'docnumber' is set if ($docnumber === null) { throw new \InvalidArgumentException( 'Missing the required parameter $docnumber when calling taskWorkGetTaskWorkForAutoAssign' ); } $resourcePath = '/api/TaskWork/autoassignlist/{docnumber}'; $formParams = []; $queryParams = []; $headerParams = []; $httpBody = ''; $multipart = false; // path params if ($docnumber!== null) { $resourcePath = str_replace( '{'. 'docnumber'. '}', ObjectSerializer::toPathValue($docnumber), $resourcePath ); } // body params $_tempBody = null; if ($multipart) { $headers = $this->headerSelector->selectHeadersForMultipart( ['application/json', 'text/json', 'application/xml', 'text/xml'] ); } else { $headers = $this->headerSelector->selectHeaders( ['application/json', 'text/json', 'application/xml', 'text/xml'], [] ); } // for model (json/xml) if (isset($_tempBody)) { // $_tempBody is the method argument, if present $httpBody = $_tempBody; // \stdClass has no __toString(), so we should encode it manually if ($httpBody instanceof \stdClass && $headers['Content-Type'] === 'application/json') { $httpBody = \GuzzleHttp\json_encode($httpBody); } } elseif (count($formParams) > 0) { if ($multipart) { $multipartContents = []; foreach ($formParams as $formParamName => $formParamValue) { $multipartContents[] = [ 'name' => $formParamName, 'contents' => $formParamValue ]; } // for HTTP post (form) $httpBody = new MultipartStream($multipartContents); } elseif ($headers['Content-Type'] === 'application/json') { $httpBody = \GuzzleHttp\json_encode($formParams); } else { // for HTTP post (form) $httpBody = \GuzzleHttp\Psr7\build_query($formParams); } } // this endpoint requires API key authentication $apiKey = $this->config->getApiKeyWithPrefix('Authorization'); if ($apiKey!== null) { $headers['Authorization'] = $apiKey; } $defaultHeaders = []; if ($this->config->getUserAgent()) { $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); } $headers = array_merge( $defaultHeaders, $headerParams, $headers ); $query = \GuzzleHttp\Psr7\build_query($queryParams); return new Request( 'GET', $this->config->getHost(). $resourcePath. ($query? "?{$query}" : ''), $headers, $httpBody ); } /** * Operation taskWorkGetTasks * * This call executes a task search and return taskwork active for the user and the given workflows ids (with all revisions) * * @param \Swagger\Client\Model\TaskWorkRequestDTO $request The request object that defines select parte and workflows ids, if workflows ids is null or empty returns all taskWork for the user (required) * * @throws \Swagger\Client\ApiException on non-2xx response * @throws \InvalidArgumentException * @return \Swagger\Client\Model\RowSearchResult[] */ public function taskWorkGetTasks($request) { list($response) = $this->taskWorkGetTasksWithHttpInfo($request); return $response; } /** * Operation taskWorkGetTasksWithHttpInfo * * This call executes a task search and return taskwork active for the user and the given workflows ids (with all revisions) * * @param \Swagger\Client\Model\TaskWorkRequestDTO $request The request object that defines select parte and workflows ids, if workflows ids is null or empty returns all taskWork for the user (required) * * @throws \Swagger\Client\ApiException on non-2xx response * @throws \InvalidArgumentException * @return array of \Swagger\Client\Model\RowSearchResult[], HTTP status code, HTTP response headers (array of strings) */ public function taskWorkGetTasksWithHttpInfo($request) { $returnType = '\Swagger\Client\Model\RowSearchResult[]'; $request = $this->taskWorkGetTasksRequest($request); try { $options = $this->createHttpClientOption(); try { $response = $this->client->send($request, $options); } catch (RequestException $e) { throw new ApiException( "[{$e->getCode()}] {$e->getMessage()}", $e->getCode(), $e->getResponse()? $e->getResponse()->getHeaders() : null, $e->getResponse()? $e->getResponse()->getBody()->getContents() : null ); } $statusCode = $response->getStatusCode(); if ($statusCode < 200 || $statusCode > 299) { throw new ApiException( sprintf( '[%d] Error connecting to the API (%s)', $statusCode, $request->getUri() ), $statusCode, $response->getHeaders(), $response->getBody() ); } $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer } else { $content = $responseBody->getContents(); if ($returnType!=='string') { $content = json_decode($content); } } return [ ObjectSerializer::deserialize($content, $returnType, []), $response->getStatusCode(), $response->getHeaders() ]; } catch (ApiException $e) { switch ($e->getCode()) { case 200: $data = ObjectSerializer::deserialize( $e->getResponseBody(), '\Swagger\Client\Model\RowSearchResult[]', $e->getResponseHeaders() ); $e->setResponseObject($data); break; } throw $e; } } /** * Operation taskWorkGetTasksAsync * * This call executes a task search and return taskwork active for the user and the given workflows ids (with all revisions) * * @param \Swagger\Client\Model\TaskWorkRequestDTO $request The request object that defines select parte and workflows ids, if workflows ids is null or empty returns all taskWork for the user (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Promise\PromiseInterface */ public function taskWorkGetTasksAsync($request) { return $this->taskWorkGetTasksAsyncWithHttpInfo($request) ->then( function ($response) { return $response[0]; } ); } /** * Operation taskWorkGetTasksAsyncWithHttpInfo * * This call executes a task search and return taskwork active for the user and the given workflows ids (with all revisions) * * @param \Swagger\Client\Model\TaskWorkRequestDTO $request The request object that defines select parte and workflows ids, if workflows ids is null or empty returns all taskWork for the user (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Promise\PromiseInterface */ public function taskWorkGetTasksAsyncWithHttpInfo($request) { $returnType = '\Swagger\Client\Model\RowSearchResult[]'; $request = $this->taskWorkGetTasksRequest($request); return $this->client ->sendAsync($request, $this->createHttpClientOption()) ->then( function ($response) use ($returnType) { $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer } else { $content = $responseBody->getContents(); if ($returnType!=='string') { $content = json_decode($content); } } return [ ObjectSerializer::deserialize($content, $returnType, []), $response->getStatusCode(), $response->getHeaders() ]; }, function ($exception) { $response = $exception->getResponse(); $statusCode = $response->getStatusCode(); throw new ApiException( sprintf( '[%d] Error connecting to the API (%s)', $statusCode, $exception->getRequest()->getUri() ), $statusCode, $response->getHeaders(), $response->getBody() ); } ); } /** * Create request for operation 'taskWorkGetTasks' * * @param \Swagger\Client\Model\TaskWorkRequestDTO $request The request object that defines select parte and workflows ids, if workflows ids is null or empty returns all taskWork for the user (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Psr7\Request */ protected function taskWorkGetTasksRequest($request) { // verify the required parameter'request' is set if ($request === null) { throw new \InvalidArgumentException( 'Missing the required parameter $request when calling taskWorkGetTasks' ); } $resourcePath = '/api/TaskWork'; $formParams = []; $queryParams = []; $headerParams = []; $httpBody = ''; $multipart = false; // body params $_tempBody = null; if (isset($request)) { $_tempBody = $request; } if ($multipart) { $headers = $this->headerSelector->selectHeadersForMultipart( ['application/json', 'text/json', 'application/xml', 'text/xml'] ); } else { $headers = $this->headerSelector->selectHeaders( ['application/json', 'text/json', 'application/xml', 'text/xml'], ['application/json', 'text/json', 'application/xml', 'text/xml', 'application/x-www-form-urlencoded'] ); } // for model (json/xml) if (isset($_tempBody)) { // $_tempBody is the method argument, if present $httpBody = $_tempBody; // \stdClass has no __toString(), so we should encode it manually if ($httpBody instanceof \stdClass && $headers['Content-Type'] === 'application/json') { $httpBody = \GuzzleHttp\json_encode($httpBody); } } elseif (count($formParams) > 0) { if ($multipart) { $multipartContents = []; foreach ($formParams as $formParamName => $formParamValue) { $multipartContents[] = [ 'name' => $formParamName, 'contents' => $formParamValue ]; } // for HTTP post (form) $httpBody = new MultipartStream($multipartContents); } elseif ($headers['Content-Type'] === 'application/json') { $httpBody = \GuzzleHttp\json_encode($formParams); } else { // for HTTP post (form) $httpBody = \GuzzleHttp\Psr7\build_query($formParams); } } // this endpoint requires API key authentication $apiKey = $this->config->getApiKeyWithPrefix('Authorization'); if ($apiKey!== null) { $headers['Authorization'] = $apiKey; } $defaultHeaders = []; if ($this->config->getUserAgent()) { $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); } $headers = array_merge( $defaultHeaders, $headerParams, $headers ); $query = \GuzzleHttp\Psr7\build_query($queryParams); return new Request( 'POST', $this->config->getHost(). $resourcePath. ($query? "?{$query}" : ''), $headers, $httpBody ); } /** * Operation taskWorkReassignTaskById * * This call reassigns a task to selected users * * @param int $taskworkid Taskwork identifier (required) * @param \Swagger\Client\Model\TaskWorkReassignRequest $reassign_request Information for re assign operation request (required) * * @throws \Swagger\Client\ApiException on non-2xx response * @throws \InvalidArgumentException * @return void */ public function taskWorkReassignTaskById($taskworkid, $reassign_request) { $this->taskWorkReassignTaskByIdWithHttpInfo($taskworkid, $reassign_request); } /** * Operation taskWorkReassignTaskByIdWithHttpInfo * * This call reassigns a task to selected users * * @param int $taskworkid Taskwork identifier (required) * @param \Swagger\Client\Model\TaskWorkReassignRequest $reassign_request Information for re assign operation request (required) * * @throws \Swagger\Client\ApiException on non-2xx response * @throws \InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ public function taskWorkReassignTaskByIdWithHttpInfo($taskworkid, $reassign_request) { $returnType = ''; $request = $this->taskWorkReassignTaskByIdRequest($taskworkid, $reassign_request); try { $options = $this->createHttpClientOption(); try { $response = $this->client->send($request, $options); } catch (RequestException $e) { throw new ApiException( "[{$e->getCode()}] {$e->getMessage()}", $e->getCode(), $e->getResponse()? $e->getResponse()->getHeaders() : null, $e->getResponse()? $e->getResponse()->getBody()->getContents() : null ); } $statusCode = $response->getStatusCode(); if ($statusCode < 200 || $statusCode > 299) { throw new ApiException( sprintf( '[%d] Error connecting to the API (%s)', $statusCode, $request->getUri() ), $statusCode, $response->getHeaders(), $response->getBody() ); } return [null, $statusCode, $response->getHeaders()]; } catch (ApiException $e) { switch ($e->getCode()) { } throw $e; } } /** * Operation taskWorkReassignTaskByIdAsync * * This call reassigns a task to selected users * * @param int $taskworkid Taskwork identifier (required) * @param \Swagger\Client\Model\TaskWorkReassignRequest $reassign_request Information for re assign operation request (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Promise\PromiseInterface */ public function taskWorkReassignTaskByIdAsync($taskworkid, $reassign_request) { return $this->taskWorkReassignTaskByIdAsyncWithHttpInfo($taskworkid, $reassign_request) ->then( function ($response) { return $response[0]; } ); } /** * Operation taskWorkReassignTaskByIdAsyncWithHttpInfo * * This call reassigns a task to selected users * * @param int $taskworkid Taskwork identifier (required) * @param \Swagger\Client\Model\TaskWorkReassignRequest $reassign_request Information for re assign operation request (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Promise\PromiseInterface */ public function taskWorkReassignTaskByIdAsyncWithHttpInfo($taskworkid, $reassign_request) { $returnType = ''; $request = $this->taskWorkReassignTaskByIdRequest($taskworkid, $reassign_request); return $this->client ->sendAsync($request, $this->createHttpClientOption()) ->then( function ($response) use ($returnType) { return [null, $response->getStatusCode(), $response->getHeaders()]; }, function ($exception) { $response = $exception->getResponse(); $statusCode = $response->getStatusCode(); throw new ApiException( sprintf( '[%d] Error connecting to the API (%s)', $statusCode, $exception->getRequest()->getUri() ), $statusCode, $response->getHeaders(), $response->getBody() ); } ); } /** * Create request for operation 'taskWorkReassignTaskById' * * @param int $taskworkid Taskwork identifier (required) * @param \Swagger\Client\Model\TaskWorkReassignRequest $reassign_request Information for re assign operation request (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Psr7\Request */ protected function taskWorkReassignTaskByIdRequest($taskworkid, $reassign_request) { // verify the required parameter 'taskworkid' is set if ($taskworkid === null) { throw new \InvalidArgumentException( 'Missing the required parameter $taskworkid when calling taskWorkReassignTaskById' ); } // verify the required parameter'reassign_request' is set if ($reassign_request === null) { throw new \InvalidArgumentException( 'Missing the required parameter $reassign_request when calling taskWorkReassignTaskById' ); } $resourcePath = '/api/TaskWork/reassign/{taskworkid}'; $formParams = []; $queryParams = []; $headerParams = []; $httpBody = ''; $multipart = false; // path params if ($taskworkid!== null) { $resourcePath = str_replace( '{'. 'taskworkid'. '}', ObjectSerializer::toPathValue($taskworkid), $resourcePath ); } // body params $_tempBody = null; if (isset($reassign_request)) { $_tempBody = $reassign_request; } if ($multipart) { $headers = $this->headerSelector->selectHeadersForMultipart( [] ); } else { $headers = $this->headerSelector->selectHeaders( [], ['application/json', 'text/json', 'application/xml', 'text/xml', 'application/x-www-form-urlencoded'] ); } // for model (json/xml) if (isset($_tempBody)) { // $_tempBody is the method argument, if present $httpBody = $_tempBody; // \stdClass has no __toString(), so we should encode it manually if ($httpBody instanceof \stdClass && $headers['Content-Type'] === 'application/json') { $httpBody = \GuzzleHttp\json_encode($httpBody); } } elseif (count($formParams) > 0) { if ($multipart) { $multipartContents = []; foreach ($formParams as $formParamName => $formParamValue) { $multipartContents[] = [ 'name' => $formParamName, 'contents' => $formParamValue ]; } // for HTTP post (form) $httpBody = new MultipartStream($multipartContents); } elseif ($headers['Content-Type'] === 'application/json') { $httpBody = \GuzzleHttp\json_encode($formParams); } else { // for HTTP post (form) $httpBody = \GuzzleHttp\Psr7\build_query($formParams); } } // this endpoint requires API key authentication $apiKey = $this->config->getApiKeyWithPrefix('Authorization'); if ($apiKey!== null) { $headers['Authorization'] = $apiKey; } $defaultHeaders = []; if ($this->config->getUserAgent()) { $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); } $headers = array_merge( $defaultHeaders, $headerParams, $headers ); $query = \GuzzleHttp\Psr7\build_query($queryParams); return new Request( 'POST', $this->config->getHost(). $resourcePath. ($query? "?{$query}" : ''), $headers, $httpBody ); } /** * Operation taskWorkReassignUsersTaskById * * This call reassigns a task to selected users * * @param int $taskworkid Taskwork identifier (required) * * @throws \Swagger\Client\ApiException on non-2xx response * @throws \InvalidArgumentException * @return \Swagger\Client\Model\UserCompleteDTO[] */ public function taskWorkReassignUsersTaskById($taskworkid) { list($response) = $this->taskWorkReassignUsersTaskByIdWithHttpInfo($taskworkid); return $response; } /** * Operation taskWorkReassignUsersTaskByIdWithHttpInfo * * This call reassigns a task to selected users * * @param int $taskworkid Taskwork identifier (required) * * @throws \Swagger\Client\ApiException on non-2xx response * @throws \InvalidArgumentException * @return array of \Swagger\Client\Model\UserCompleteDTO[], HTTP status code, HTTP response headers (array of strings) */ public function taskWorkReassignUsersTaskByIdWithHttpInfo($taskworkid) { $returnType = '\Swagger\Client\Model\UserCompleteDTO[]'; $request = $this->taskWorkReassignUsersTaskByIdRequest($taskworkid); try { $options = $this->createHttpClientOption(); try { $response = $this->client->send($request, $options); } catch (RequestException $e) { throw new ApiException( "[{$e->getCode()}] {$e->getMessage()}", $e->getCode(), $e->getResponse()? $e->getResponse()->getHeaders() : null, $e->getResponse()? $e->getResponse()->getBody()->getContents() : null ); } $statusCode = $response->getStatusCode(); if ($statusCode < 200 || $statusCode > 299) { throw new ApiException( sprintf( '[%d] Error connecting to the API (%s)', $statusCode, $request->getUri() ), $statusCode, $response->getHeaders(), $response->getBody() ); } $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer } else { $content = $responseBody->getContents(); if ($returnType!=='string') { $content = json_decode($content); } } return [ ObjectSerializer::deserialize($content, $returnType, []), $response->getStatusCode(), $response->getHeaders() ]; } catch (ApiException $e) { switch ($e->getCode()) { case 200: $data = ObjectSerializer::deserialize( $e->getResponseBody(), '\Swagger\Client\Model\UserCompleteDTO[]', $e->getResponseHeaders() ); $e->setResponseObject($data); break; } throw $e; } } /** * Operation taskWorkReassignUsersTaskByIdAsync * * This call reassigns a task to selected users * * @param int $taskworkid Taskwork identifier (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Promise\PromiseInterface */ public function taskWorkReassignUsersTaskByIdAsync($taskworkid) { return $this->taskWorkReassignUsersTaskByIdAsyncWithHttpInfo($taskworkid) ->then( function ($response) { return $response[0]; } ); } /** * Operation taskWorkReassignUsersTaskByIdAsyncWithHttpInfo * * This call reassigns a task to selected users * * @param int $taskworkid Taskwork identifier (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Promise\PromiseInterface */ public function taskWorkReassignUsersTaskByIdAsyncWithHttpInfo($taskworkid) { $returnType = '\Swagger\Client\Model\UserCompleteDTO[]'; $request = $this->taskWorkReassignUsersTaskByIdRequest($taskworkid); return $this->client ->sendAsync($request, $this->createHttpClientOption()) ->then( function ($response) use ($returnType) { $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer } else { $content = $responseBody->getContents(); if ($returnType!=='string') { $content = json_decode($content); } } return [ ObjectSerializer::deserialize($content, $returnType, []), $response->getStatusCode(), $response->getHeaders() ]; }, function ($exception) { $response = $exception->getResponse(); $statusCode = $response->getStatusCode(); throw new ApiException( sprintf( '[%d] Error connecting to the API (%s)', $statusCode, $exception->getRequest()->getUri() ), $statusCode, $response->getHeaders(), $response->getBody() ); } ); } /** * Create request for operation 'taskWorkReassignUsersTaskById' * * @param int $taskworkid Taskwork identifier (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Psr7\Request */ protected function taskWorkReassignUsersTaskByIdRequest($taskworkid) { // verify the required parameter 'taskworkid' is set if ($taskworkid === null) { throw new \InvalidArgumentException( 'Missing the required parameter $taskworkid when calling taskWorkReassignUsersTaskById' ); } $resourcePath = '/api/TaskWork/reassignusers/{taskworkid}'; $formParams = []; $queryParams = []; $headerParams = []; $httpBody = ''; $multipart = false; // path params if ($taskworkid!== null) { $resourcePath = str_replace( '{'. 'taskworkid'. '}', ObjectSerializer::toPathValue($taskworkid), $resourcePath ); } // body params $_tempBody = null; if ($multipart) { $headers = $this->headerSelector->selectHeadersForMultipart( ['application/json', 'text/json', 'application/xml', 'text/xml'] ); } else { $headers = $this->headerSelector->selectHeaders( ['application/json', 'text/json', 'application/xml', 'text/xml'], [] ); } // for model (json/xml) if (isset($_tempBody)) { // $_tempBody is the method argument, if present $httpBody = $_tempBody; // \stdClass has no __toString(), so we should encode it manually if ($httpBody instanceof \stdClass && $headers['Content-Type'] === 'application/json') { $httpBody = \GuzzleHttp\json_encode($httpBody); } } elseif (count($formParams) > 0) { if ($multipart) { $multipartContents = []; foreach ($formParams as $formParamName => $formParamValue) { $multipartContents[] = [ 'name' => $formParamName, 'contents' => $formParamValue ]; } // for HTTP post (form) $httpBody = new MultipartStream($multipartContents); } elseif ($headers['Content-Type'] === 'application/json') { $httpBody = \GuzzleHttp\json_encode($formParams); } else { // for HTTP post (form) $httpBody = \GuzzleHttp\Psr7\build_query($formParams); } } // this endpoint requires API key authentication $apiKey = $this->config->getApiKeyWithPrefix('Authorization'); if ($apiKey!== null) { $headers['Authorization'] = $apiKey; } $defaultHeaders = []; if ($this->config->getUserAgent()) { $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); } $headers = array_merge( $defaultHeaders, $headerParams, $headers ); $query = \GuzzleHttp\Psr7\build_query($queryParams); return new Request( 'GET', $this->config->getHost(). $resourcePath. ($query? "?{$query}" : ''), $headers, $httpBody ); } /** * Operation taskWorkSetProfileForTaskWorkBySelectionDocumentOperation * * This call adds a profile to process for a selection document taskwork operation * * @param int $task_work_id Taskwork identifie (required) * @param string $task_work_document_operation_id Id of the operation (required) * @param int[] $docnumbers List of document identifier to add (required) * * @throws \Swagger\Client\ApiException on non-2xx response * @throws \InvalidArgumentException * @return void */ public function taskWorkSetProfileForTaskWorkBySelectionDocumentOperation($task_work_id, $task_work_document_operation_id, $docnumbers) { $this->taskWorkSetProfileForTaskWorkBySelectionDocumentOperationWithHttpInfo($task_work_id, $task_work_document_operation_id, $docnumbers); } /** * Operation taskWorkSetProfileForTaskWorkBySelectionDocumentOperationWithHttpInfo * * This call adds a profile to process for a selection document taskwork operation * * @param int $task_work_id Taskwork identifie (required) * @param string $task_work_document_operation_id Id of the operation (required) * @param int[] $docnumbers List of document identifier to add (required) * * @throws \Swagger\Client\ApiException on non-2xx response * @throws \InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ public function taskWorkSetProfileForTaskWorkBySelectionDocumentOperationWithHttpInfo($task_work_id, $task_work_document_operation_id, $docnumbers) { $returnType = ''; $request = $this->taskWorkSetProfileForTaskWorkBySelectionDocumentOperationRequest($task_work_id, $task_work_document_operation_id, $docnumbers); try { $options = $this->createHttpClientOption(); try { $response = $this->client->send($request, $options); } catch (RequestException $e) { throw new ApiException( "[{$e->getCode()}] {$e->getMessage()}", $e->getCode(), $e->getResponse()? $e->getResponse()->getHeaders() : null, $e->getResponse()? $e->getResponse()->getBody()->getContents() : null ); } $statusCode = $response->getStatusCode(); if ($statusCode < 200 || $statusCode > 299) { throw new ApiException( sprintf( '[%d] Error connecting to the API (%s)', $statusCode, $request->getUri() ), $statusCode, $response->getHeaders(), $response->getBody() ); } return [null, $statusCode, $response->getHeaders()]; } catch (ApiException $e) { switch ($e->getCode()) { } throw $e; } } /** * Operation taskWorkSetProfileForTaskWorkBySelectionDocumentOperationAsync * * This call adds a profile to process for a selection document taskwork operation * * @param int $task_work_id Taskwork identifie (required) * @param string $task_work_document_operation_id Id of the operation (required) * @param int[] $docnumbers List of document identifier to add (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Promise\PromiseInterface */ public function taskWorkSetProfileForTaskWorkBySelectionDocumentOperationAsync($task_work_id, $task_work_document_operation_id, $docnumbers) { return $this->taskWorkSetProfileForTaskWorkBySelectionDocumentOperationAsyncWithHttpInfo($task_work_id, $task_work_document_operation_id, $docnumbers) ->then( function ($response) { return $response[0]; } ); } /** * Operation taskWorkSetProfileForTaskWorkBySelectionDocumentOperationAsyncWithHttpInfo * * This call adds a profile to process for a selection document taskwork operation * * @param int $task_work_id Taskwork identifie (required) * @param string $task_work_document_operation_id Id of the operation (required) * @param int[] $docnumbers List of document identifier to add (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Promise\PromiseInterface */ public function taskWorkSetProfileForTaskWorkBySelectionDocumentOperationAsyncWithHttpInfo($task_work_id, $task_work_document_operation_id, $docnumbers) { $returnType = ''; $request = $this->taskWorkSetProfileForTaskWorkBySelectionDocumentOperationRequest($task_work_id, $task_work_document_operation_id, $docnumbers); return $this->client ->sendAsync($request, $this->createHttpClientOption()) ->then( function ($response) use ($returnType) { return [null, $response->getStatusCode(), $response->getHeaders()]; }, function ($exception) { $response = $exception->getResponse(); $statusCode = $response->getStatusCode(); throw new ApiException( sprintf( '[%d] Error connecting to the API (%s)', $statusCode, $exception->getRequest()->getUri() ), $statusCode, $response->getHeaders(), $response->getBody() ); } ); } /** * Create request for operation 'taskWorkSetProfileForTaskWorkBySelectionDocumentOperation' * * @param int $task_work_id Taskwork identifie (required) * @param string $task_work_document_operation_id Id of the operation (required) * @param int[] $docnumbers List of document identifier to add (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Psr7\Request */ protected function taskWorkSetProfileForTaskWorkBySelectionDocumentOperationRequest($task_work_id, $task_work_document_operation_id, $docnumbers) { // verify the required parameter 'task_work_id' is set if ($task_work_id === null) { throw new \InvalidArgumentException( 'Missing the required parameter $task_work_id when calling taskWorkSetProfileForTaskWorkBySelectionDocumentOperation' ); } // verify the required parameter 'task_work_document_operation_id' is set if ($task_work_document_operation_id === null) { throw new \InvalidArgumentException( 'Missing the required parameter $task_work_document_operation_id when calling taskWorkSetProfileForTaskWorkBySelectionDocumentOperation' ); } // verify the required parameter 'docnumbers' is set if ($docnumbers === null) { throw new \InvalidArgumentException( 'Missing the required parameter $docnumbers when calling taskWorkSetProfileForTaskWorkBySelectionDocumentOperation' ); } $resourcePath = '/api/TaskWork/{taskWorkId}/documentsoperations/{taskWorkDocumentOperationId}/byselection'; $formParams = []; $queryParams = []; $headerParams = []; $httpBody = ''; $multipart = false; // path params if ($task_work_id!== null) { $resourcePath = str_replace( '{'. 'taskWorkId'. '}', ObjectSerializer::toPathValue($task_work_id), $resourcePath ); } // path params if ($task_work_document_operation_id!== null) { $resourcePath = str_replace( '{'. 'taskWorkDocumentOperationId'. '}', ObjectSerializer::toPathValue($task_work_document_operation_id), $resourcePath ); } // body params $_tempBody = null; if (isset($docnumbers)) { $_tempBody = $docnumbers; } if ($multipart) { $headers = $this->headerSelector->selectHeadersForMultipart( [] ); } else { $headers = $this->headerSelector->selectHeaders( [], ['application/json', 'text/json', 'application/xml', 'text/xml', 'application/x-www-form-urlencoded'] ); } // for model (json/xml) if (isset($_tempBody)) { // $_tempBody is the method argument, if present $httpBody = $_tempBody; // \stdClass has no __toString(), so we should encode it manually if ($httpBody instanceof \stdClass && $headers['Content-Type'] === 'application/json') { $httpBody = \GuzzleHttp\json_encode($httpBody); } } elseif (count($formParams) > 0) { if ($multipart) { $multipartContents = []; foreach ($formParams as $formParamName => $formParamValue) { $multipartContents[] = [ 'name' => $formParamName, 'contents' => $formParamValue ]; } // for HTTP post (form) $httpBody = new MultipartStream($multipartContents); } elseif ($headers['Content-Type'] === 'application/json') { $httpBody = \GuzzleHttp\json_encode($formParams); } else { // for HTTP post (form) $httpBody = \GuzzleHttp\Psr7\build_query($formParams); } } // this endpoint requires API key authentication $apiKey = $this->config->getApiKeyWithPrefix('Authorization'); if ($apiKey!== null) { $headers['Authorization'] = $apiKey; } $defaultHeaders = []; if ($this->config->getUserAgent()) { $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); } $headers = array_merge( $defaultHeaders, $headerParams, $headers ); $query = \GuzzleHttp\Psr7\build_query($queryParams); return new Request( 'PUT', $this->config->getHost(). $resourcePath. ($query? "?{$query}" : ''), $headers, $httpBody ); } /** * Operation taskWorkSetProfileForTaskWorkMaskDocumentOperation * * This call profiles a new document for a mask insert document taskwork operation * * @param int $task_work_id Taskwork identifie (required) * @param string $task_work_document_operation_id Id of the operation (required) * @param \Swagger\Client\Model\ProfileDTO $profile profile (optional) * * @throws \Swagger\Client\ApiException on non-2xx response * @throws \InvalidArgumentException * @return \Swagger\Client\Model\ProfileResultDTO */ public function taskWorkSetProfileForTaskWorkMaskDocumentOperation($task_work_id, $task_work_document_operation_id, $profile = null) { list($response) = $this->taskWorkSetProfileForTaskWorkMaskDocumentOperationWithHttpInfo($task_work_id, $task_work_document_operation_id, $profile); return $response; } /** * Operation taskWorkSetProfileForTaskWorkMaskDocumentOperationWithHttpInfo * * This call profiles a new document for a mask insert document taskwork operation * * @param int $task_work_id Taskwork identifie (required) * @param string $task_work_document_operation_id Id of the operation (required) * @param \Swagger\Client\Model\ProfileDTO $profile (optional) * * @throws \Swagger\Client\ApiException on non-2xx response * @throws \InvalidArgumentException * @return array of \Swagger\Client\Model\ProfileResultDTO, HTTP status code, HTTP response headers (array of strings) */ public function taskWorkSetProfileForTaskWorkMaskDocumentOperationWithHttpInfo($task_work_id, $task_work_document_operation_id, $profile = null) { $returnType = '\Swagger\Client\Model\ProfileResultDTO'; $request = $this->taskWorkSetProfileForTaskWorkMaskDocumentOperationRequest($task_work_id, $task_work_document_operation_id, $profile); try { $options = $this->createHttpClientOption(); try { $response = $this->client->send($request, $options); } catch (RequestException $e) { throw new ApiException( "[{$e->getCode()}] {$e->getMessage()}", $e->getCode(), $e->getResponse()? $e->getResponse()->getHeaders() : null, $e->getResponse()? $e->getResponse()->getBody()->getContents() : null ); } $statusCode = $response->getStatusCode(); if ($statusCode < 200 || $statusCode > 299) { throw new ApiException( sprintf( '[%d] Error connecting to the API (%s)', $statusCode, $request->getUri() ), $statusCode, $response->getHeaders(), $response->getBody() ); } $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer } else { $content = $responseBody->getContents(); if ($returnType!=='string') { $content = json_decode($content); } } return [ ObjectSerializer::deserialize($content, $returnType, []), $response->getStatusCode(), $response->getHeaders() ]; } catch (ApiException $e) { switch ($e->getCode()) { case 200: $data = ObjectSerializer::deserialize( $e->getResponseBody(), '\Swagger\Client\Model\ProfileResultDTO', $e->getResponseHeaders() ); $e->setResponseObject($data); break; } throw $e; } } /** * Operation taskWorkSetProfileForTaskWorkMaskDocumentOperationAsync * * This call profiles a new document for a mask insert document taskwork operation * * @param int $task_work_id Taskwork identifie (required) * @param string $task_work_document_operation_id Id of the operation (required) * @param \Swagger\Client\Model\ProfileDTO $profile (optional) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Promise\PromiseInterface */ public function taskWorkSetProfileForTaskWorkMaskDocumentOperationAsync($task_work_id, $task_work_document_operation_id, $profile = null) { return $this->taskWorkSetProfileForTaskWorkMaskDocumentOperationAsyncWithHttpInfo($task_work_id, $task_work_document_operation_id, $profile) ->then( function ($response) { return $response[0]; } ); } /** * Operation taskWorkSetProfileForTaskWorkMaskDocumentOperationAsyncWithHttpInfo * * This call profiles a new document for a mask insert document taskwork operation * * @param int $task_work_id Taskwork identifie (required) * @param string $task_work_document_operation_id Id of the operation (required) * @param \Swagger\Client\Model\ProfileDTO $profile (optional) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Promise\PromiseInterface */ public function taskWorkSetProfileForTaskWorkMaskDocumentOperationAsyncWithHttpInfo($task_work_id, $task_work_document_operation_id, $profile = null) { $returnType = '\Swagger\Client\Model\ProfileResultDTO'; $request = $this->taskWorkSetProfileForTaskWorkMaskDocumentOperationRequest($task_work_id, $task_work_document_operation_id, $profile); return $this->client ->sendAsync($request, $this->createHttpClientOption()) ->then( function ($response) use ($returnType) { $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer } else { $content = $responseBody->getContents(); if ($returnType!=='string') { $content = json_decode($content); } } return [ ObjectSerializer::deserialize($content, $returnType, []), $response->getStatusCode(), $response->getHeaders() ]; }, function ($exception) { $response = $exception->getResponse(); $statusCode = $response->getStatusCode(); throw new ApiException( sprintf( '[%d] Error connecting to the API (%s)', $statusCode, $exception->getRequest()->getUri() ), $statusCode, $response->getHeaders(), $response->getBody() ); } ); } /** * Create request for operation 'taskWorkSetProfileForTaskWorkMaskDocumentOperation' * * @param int $task_work_id Taskwork identifie (required) * @param string $task_work_document_operation_id Id of the operation (required) * @param \Swagger\Client\Model\ProfileDTO $profile (optional) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Psr7\Request */ protected function taskWorkSetProfileForTaskWorkMaskDocumentOperationRequest($task_work_id, $task_work_document_operation_id, $profile = null) { // verify the required parameter 'task_work_id' is set if ($task_work_id === null) { throw new \InvalidArgumentException( 'Missing the required parameter $task_work_id when calling taskWorkSetProfileForTaskWorkMaskDocumentOperation' ); } // verify the required parameter 'task_work_document_operation_id' is set if ($task_work_document_operation_id === null) { throw new \InvalidArgumentException( 'Missing the required parameter $task_work_document_operation_id when calling taskWorkSetProfileForTaskWorkMaskDocumentOperation' ); } $resourcePath = '/api/TaskWork/{taskWorkId}/documentsoperations/{taskWorkDocumentOperationId}/bymask'; $formParams = []; $queryParams = []; $headerParams = []; $httpBody = ''; $multipart = false; // path params if ($task_work_id!== null) { $resourcePath = str_replace( '{'. 'taskWorkId'. '}', ObjectSerializer::toPathValue($task_work_id), $resourcePath ); } // path params if ($task_work_document_operation_id!== null) { $resourcePath = str_replace( '{'. 'taskWorkDocumentOperationId'. '}', ObjectSerializer::toPathValue($task_work_document_operation_id), $resourcePath ); } // body params $_tempBody = null; if (isset($profile)) { $_tempBody = $profile; } if ($multipart) { $headers = $this->headerSelector->selectHeadersForMultipart( ['application/json', 'text/json', 'application/xml', 'text/xml'] ); } else { $headers = $this->headerSelector->selectHeaders( ['application/json', 'text/json', 'application/xml', 'text/xml'], [] ); } // for model (json/xml) if (isset($_tempBody)) { // $_tempBody is the method argument, if present $httpBody = $_tempBody; // \stdClass has no __toString(), so we should encode it manually if ($httpBody instanceof \stdClass && $headers['Content-Type'] === 'application/json') { $httpBody = \GuzzleHttp\json_encode($httpBody); } } elseif (count($formParams) > 0) { if ($multipart) { $multipartContents = []; foreach ($formParams as $formParamName => $formParamValue) { $multipartContents[] = [ 'name' => $formParamName, 'contents' => $formParamValue ]; } // for HTTP post (form) $httpBody = new MultipartStream($multipartContents); } elseif ($headers['Content-Type'] === 'application/json') { $httpBody = \GuzzleHttp\json_encode($formParams); } else { // for HTTP post (form) $httpBody = \GuzzleHttp\Psr7\build_query($formParams); } } // this endpoint requires API key authentication $apiKey = $this->config->getApiKeyWithPrefix('Authorization'); if ($apiKey!== null) { $headers['Authorization'] = $apiKey; } $defaultHeaders = []; if ($this->config->getUserAgent()) { $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); } $headers = array_merge( $defaultHeaders, $headerParams, $headers ); $query = \GuzzleHttp\Psr7\build_query($queryParams); return new Request( 'POST', $this->config->getHost(). $resourcePath. ($query? "?{$query}" : ''), $headers, $httpBody ); } /** * Operation taskWorkSetProfileForTaskWorkModelDocumentOperation * * This call profiles a new document for a model insert document taskwork operation * * @param int $task_work_id Taskwork identifie (required) * @param string $task_work_document_operation_id Id of the operation (required) * @param \Swagger\Client\Model\ProfileDTO $profile profile (optional) * * @throws \Swagger\Client\ApiException on non-2xx response * @throws \InvalidArgumentException * @return \Swagger\Client\Model\ProfileResultDTO */ public function taskWorkSetProfileForTaskWorkModelDocumentOperation($task_work_id, $task_work_document_operation_id, $profile = null) { list($response) = $this->taskWorkSetProfileForTaskWorkModelDocumentOperationWithHttpInfo($task_work_id, $task_work_document_operation_id, $profile); return $response; } /** * Operation taskWorkSetProfileForTaskWorkModelDocumentOperationWithHttpInfo * * This call profiles a new document for a model insert document taskwork operation * * @param int $task_work_id Taskwork identifie (required) * @param string $task_work_document_operation_id Id of the operation (required) * @param \Swagger\Client\Model\ProfileDTO $profile (optional) * * @throws \Swagger\Client\ApiException on non-2xx response * @throws \InvalidArgumentException * @return array of \Swagger\Client\Model\ProfileResultDTO, HTTP status code, HTTP response headers (array of strings) */ public function taskWorkSetProfileForTaskWorkModelDocumentOperationWithHttpInfo($task_work_id, $task_work_document_operation_id, $profile = null) { $returnType = '\Swagger\Client\Model\ProfileResultDTO'; $request = $this->taskWorkSetProfileForTaskWorkModelDocumentOperationRequest($task_work_id, $task_work_document_operation_id, $profile); try { $options = $this->createHttpClientOption(); try { $response = $this->client->send($request, $options); } catch (RequestException $e) { throw new ApiException( "[{$e->getCode()}] {$e->getMessage()}", $e->getCode(), $e->getResponse()? $e->getResponse()->getHeaders() : null, $e->getResponse()? $e->getResponse()->getBody()->getContents() : null ); } $statusCode = $response->getStatusCode(); if ($statusCode < 200 || $statusCode > 299) { throw new ApiException( sprintf( '[%d] Error connecting to the API (%s)', $statusCode, $request->getUri() ), $statusCode, $response->getHeaders(), $response->getBody() ); } $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer } else { $content = $responseBody->getContents(); if ($returnType!=='string') { $content = json_decode($content); } } return [ ObjectSerializer::deserialize($content, $returnType, []), $response->getStatusCode(), $response->getHeaders() ]; } catch (ApiException $e) { switch ($e->getCode()) { case 200: $data = ObjectSerializer::deserialize( $e->getResponseBody(), '\Swagger\Client\Model\ProfileResultDTO', $e->getResponseHeaders() ); $e->setResponseObject($data); break; } throw $e; } } /** * Operation taskWorkSetProfileForTaskWorkModelDocumentOperationAsync * * This call profiles a new document for a model insert document taskwork operation * * @param int $task_work_id Taskwork identifie (required) * @param string $task_work_document_operation_id Id of the operation (required) * @param \Swagger\Client\Model\ProfileDTO $profile (optional) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Promise\PromiseInterface */ public function taskWorkSetProfileForTaskWorkModelDocumentOperationAsync($task_work_id, $task_work_document_operation_id, $profile = null) { return $this->taskWorkSetProfileForTaskWorkModelDocumentOperationAsyncWithHttpInfo($task_work_id, $task_work_document_operation_id, $profile) ->then( function ($response) { return $response[0]; } ); } /** * Operation taskWorkSetProfileForTaskWorkModelDocumentOperationAsyncWithHttpInfo * * This call profiles a new document for a model insert document taskwork operation * * @param int $task_work_id Taskwork identifie (required) * @param string $task_work_document_operation_id Id of the operation (required) * @param \Swagger\Client\Model\ProfileDTO $profile (optional) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Promise\PromiseInterface */ public function taskWorkSetProfileForTaskWorkModelDocumentOperationAsyncWithHttpInfo($task_work_id, $task_work_document_operation_id, $profile = null) { $returnType = '\Swagger\Client\Model\ProfileResultDTO'; $request = $this->taskWorkSetProfileForTaskWorkModelDocumentOperationRequest($task_work_id, $task_work_document_operation_id, $profile); return $this->client ->sendAsync($request, $this->createHttpClientOption()) ->then( function ($response) use ($returnType) { $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer } else { $content = $responseBody->getContents(); if ($returnType!=='string') { $content = json_decode($content); } } return [ ObjectSerializer::deserialize($content, $returnType, []), $response->getStatusCode(), $response->getHeaders() ]; }, function ($exception) { $response = $exception->getResponse(); $statusCode = $response->getStatusCode(); throw new ApiException( sprintf( '[%d] Error connecting to the API (%s)', $statusCode, $exception->getRequest()->getUri() ), $statusCode, $response->getHeaders(), $response->getBody() ); } ); } /** * Create request for operation 'taskWorkSetProfileForTaskWorkModelDocumentOperation' * * @param int $task_work_id Taskwork identifie (required) * @param string $task_work_document_operation_id Id of the operation (required) * @param \Swagger\Client\Model\ProfileDTO $profile (optional) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Psr7\Request */ protected function taskWorkSetProfileForTaskWorkModelDocumentOperationRequest($task_work_id, $task_work_document_operation_id, $profile = null) { // verify the required parameter 'task_work_id' is set if ($task_work_id === null) { throw new \InvalidArgumentException( 'Missing the required parameter $task_work_id when calling taskWorkSetProfileForTaskWorkModelDocumentOperation' ); } // verify the required parameter 'task_work_document_operation_id' is set if ($task_work_document_operation_id === null) { throw new \InvalidArgumentException( 'Missing the required parameter $task_work_document_operation_id when calling taskWorkSetProfileForTaskWorkModelDocumentOperation' ); } $resourcePath = '/api/TaskWork/{taskWorkId}/documentsoperations/{taskWorkDocumentOperationId}/bymodel'; $formParams = []; $queryParams = []; $headerParams = []; $httpBody = ''; $multipart = false; // path params if ($task_work_id!== null) { $resourcePath = str_replace( '{'. 'taskWorkId'. '}', ObjectSerializer::toPathValue($task_work_id), $resourcePath ); } // path params if ($task_work_document_operation_id!== null) { $resourcePath = str_replace( '{'. 'taskWorkDocumentOperationId'. '}', ObjectSerializer::toPathValue($task_work_document_operation_id), $resourcePath ); } // body params $_tempBody = null; if (isset($profile)) { $_tempBody = $profile; } if ($multipart) { $headers = $this->headerSelector->selectHeadersForMultipart( ['application/json', 'text/json', 'application/xml', 'text/xml'] ); } else { $headers = $this->headerSelector->selectHeaders( ['application/json', 'text/json', 'application/xml', 'text/xml'], [] ); } // for model (json/xml) if (isset($_tempBody)) { // $_tempBody is the method argument, if present $httpBody = $_tempBody; // \stdClass has no __toString(), so we should encode it manually if ($httpBody instanceof \stdClass && $headers['Content-Type'] === 'application/json') { $httpBody = \GuzzleHttp\json_encode($httpBody); } } elseif (count($formParams) > 0) { if ($multipart) { $multipartContents = []; foreach ($formParams as $formParamName => $formParamValue) { $multipartContents[] = [ 'name' => $formParamName, 'contents' => $formParamValue ]; } // for HTTP post (form) $httpBody = new MultipartStream($multipartContents); } elseif ($headers['Content-Type'] === 'application/json') { $httpBody = \GuzzleHttp\json_encode($formParams); } else { // for HTTP post (form) $httpBody = \GuzzleHttp\Psr7\build_query($formParams); } } // this endpoint requires API key authentication $apiKey = $this->config->getApiKeyWithPrefix('Authorization'); if ($apiKey!== null) { $headers['Authorization'] = $apiKey; } $defaultHeaders = []; if ($this->config->getUserAgent()) { $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); } $headers = array_merge( $defaultHeaders, $headerParams, $headers ); $query = \GuzzleHttp\Psr7\build_query($queryParams); return new Request( 'POST', $this->config->getHost(). $resourcePath. ($query? "?{$query}" : ''), $headers, $httpBody ); } /** * Operation taskWorkSetProfileForTaskWorkStandardDocumentOperation * * This call profiles a new document for a standard insert document taskwork operation * * @param int $task_work_id Taskwork identifie (required) * @param string $task_work_document_operation_id Id of the operation (required) * @param \Swagger\Client\Model\ProfileDTO $profile profile (optional) * * @throws \Swagger\Client\ApiException on non-2xx response * @throws \InvalidArgumentException * @return \Swagger\Client\Model\ProfileResultDTO */ public function taskWorkSetProfileForTaskWorkStandardDocumentOperation($task_work_id, $task_work_document_operation_id, $profile = null) { list($response) = $this->taskWorkSetProfileForTaskWorkStandardDocumentOperationWithHttpInfo($task_work_id, $task_work_document_operation_id, $profile); return $response; } /** * Operation taskWorkSetProfileForTaskWorkStandardDocumentOperationWithHttpInfo * * This call profiles a new document for a standard insert document taskwork operation * * @param int $task_work_id Taskwork identifie (required) * @param string $task_work_document_operation_id Id of the operation (required) * @param \Swagger\Client\Model\ProfileDTO $profile (optional) * * @throws \Swagger\Client\ApiException on non-2xx response * @throws \InvalidArgumentException * @return array of \Swagger\Client\Model\ProfileResultDTO, HTTP status code, HTTP response headers (array of strings) */ public function taskWorkSetProfileForTaskWorkStandardDocumentOperationWithHttpInfo($task_work_id, $task_work_document_operation_id, $profile = null) { $returnType = '\Swagger\Client\Model\ProfileResultDTO'; $request = $this->taskWorkSetProfileForTaskWorkStandardDocumentOperationRequest($task_work_id, $task_work_document_operation_id, $profile); try { $options = $this->createHttpClientOption(); try { $response = $this->client->send($request, $options); } catch (RequestException $e) { throw new ApiException( "[{$e->getCode()}] {$e->getMessage()}", $e->getCode(), $e->getResponse()? $e->getResponse()->getHeaders() : null, $e->getResponse()? $e->getResponse()->getBody()->getContents() : null ); } $statusCode = $response->getStatusCode(); if ($statusCode < 200 || $statusCode > 299) { throw new ApiException( sprintf( '[%d] Error connecting to the API (%s)', $statusCode, $request->getUri() ), $statusCode, $response->getHeaders(), $response->getBody() ); } $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer } else { $content = $responseBody->getContents(); if ($returnType!=='string') { $content = json_decode($content); } } return [ ObjectSerializer::deserialize($content, $returnType, []), $response->getStatusCode(), $response->getHeaders() ]; } catch (ApiException $e) { switch ($e->getCode()) { case 200: $data = ObjectSerializer::deserialize( $e->getResponseBody(), '\Swagger\Client\Model\ProfileResultDTO', $e->getResponseHeaders() ); $e->setResponseObject($data); break; } throw $e; } } /** * Operation taskWorkSetProfileForTaskWorkStandardDocumentOperationAsync * * This call profiles a new document for a standard insert document taskwork operation * * @param int $task_work_id Taskwork identifie (required) * @param string $task_work_document_operation_id Id of the operation (required) * @param \Swagger\Client\Model\ProfileDTO $profile (optional) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Promise\PromiseInterface */ public function taskWorkSetProfileForTaskWorkStandardDocumentOperationAsync($task_work_id, $task_work_document_operation_id, $profile = null) { return $this->taskWorkSetProfileForTaskWorkStandardDocumentOperationAsyncWithHttpInfo($task_work_id, $task_work_document_operation_id, $profile) ->then( function ($response) { return $response[0]; } ); } /** * Operation taskWorkSetProfileForTaskWorkStandardDocumentOperationAsyncWithHttpInfo * * This call profiles a new document for a standard insert document taskwork operation * * @param int $task_work_id Taskwork identifie (required) * @param string $task_work_document_operation_id Id of the operation (required) * @param \Swagger\Client\Model\ProfileDTO $profile (optional) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Promise\PromiseInterface */ public function taskWorkSetProfileForTaskWorkStandardDocumentOperationAsyncWithHttpInfo($task_work_id, $task_work_document_operation_id, $profile = null) { $returnType = '\Swagger\Client\Model\ProfileResultDTO'; $request = $this->taskWorkSetProfileForTaskWorkStandardDocumentOperationRequest($task_work_id, $task_work_document_operation_id, $profile); return $this->client ->sendAsync($request, $this->createHttpClientOption()) ->then( function ($response) use ($returnType) { $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer } else { $content = $responseBody->getContents(); if ($returnType!=='string') { $content = json_decode($content); } } return [ ObjectSerializer::deserialize($content, $returnType, []), $response->getStatusCode(), $response->getHeaders() ]; }, function ($exception) { $response = $exception->getResponse(); $statusCode = $response->getStatusCode(); throw new ApiException( sprintf( '[%d] Error connecting to the API (%s)', $statusCode, $exception->getRequest()->getUri() ), $statusCode, $response->getHeaders(), $response->getBody() ); } ); } /** * Create request for operation 'taskWorkSetProfileForTaskWorkStandardDocumentOperation' * * @param int $task_work_id Taskwork identifie (required) * @param string $task_work_document_operation_id Id of the operation (required) * @param \Swagger\Client\Model\ProfileDTO $profile (optional) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Psr7\Request */ protected function taskWorkSetProfileForTaskWorkStandardDocumentOperationRequest($task_work_id, $task_work_document_operation_id, $profile = null) { // verify the required parameter 'task_work_id' is set if ($task_work_id === null) { throw new \InvalidArgumentException( 'Missing the required parameter $task_work_id when calling taskWorkSetProfileForTaskWorkStandardDocumentOperation' ); } // verify the required parameter 'task_work_document_operation_id' is set if ($task_work_document_operation_id === null) { throw new \InvalidArgumentException( 'Missing the required parameter $task_work_document_operation_id when calling taskWorkSetProfileForTaskWorkStandardDocumentOperation' ); } $resourcePath = '/api/TaskWork/{taskWorkId}/documentsoperations/{taskWorkDocumentOperationId}/bystandard'; $formParams = []; $queryParams = []; $headerParams = []; $httpBody = ''; $multipart = false; // path params if ($task_work_id!== null) { $resourcePath = str_replace( '{'. 'taskWorkId'. '}', ObjectSerializer::toPathValue($task_work_id), $resourcePath ); } // path params if ($task_work_document_operation_id!== null) { $resourcePath = str_replace( '{'. 'taskWorkDocumentOperationId'. '}', ObjectSerializer::toPathValue($task_work_document_operation_id), $resourcePath ); } // body params $_tempBody = null; if (isset($profile)) { $_tempBody = $profile; } if ($multipart) { $headers = $this->headerSelector->selectHeadersForMultipart( ['application/json', 'text/json', 'application/xml', 'text/xml'] ); } else { $headers = $this->headerSelector->selectHeaders( ['application/json', 'text/json', 'application/xml', 'text/xml'], [] ); } // for model (json/xml) if (isset($_tempBody)) { // $_tempBody is the method argument, if present $httpBody = $_tempBody; // \stdClass has no __toString(), so we should encode it manually if ($httpBody instanceof \stdClass && $headers['Content-Type'] === 'application/json') { $httpBody = \GuzzleHttp\json_encode($httpBody); } } elseif (count($formParams) > 0) { if ($multipart) { $multipartContents = []; foreach ($formParams as $formParamName => $formParamValue) { $multipartContents[] = [ 'name' => $formParamName, 'contents' => $formParamValue ]; } // for HTTP post (form) $httpBody = new MultipartStream($multipartContents); } elseif ($headers['Content-Type'] === 'application/json') { $httpBody = \GuzzleHttp\json_encode($formParams); } else { // for HTTP post (form) $httpBody = \GuzzleHttp\Psr7\build_query($formParams); } } // this endpoint requires API key authentication $apiKey = $this->config->getApiKeyWithPrefix('Authorization'); if ($apiKey!== null) { $headers['Authorization'] = $apiKey; } $defaultHeaders = []; if ($this->config->getUserAgent()) { $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); } $headers = array_merge( $defaultHeaders, $headerParams, $headers ); $query = \GuzzleHttp\Psr7\build_query($queryParams); return new Request( 'POST', $this->config->getHost(). $resourcePath. ($query? "?{$query}" : ''), $headers, $httpBody ); } /** * Operation taskWorkSetTaskPriority * * This call sets the tasks priority * * @param int[] $task_ids List of task identifier (required) * @param int $priority Priority (required) * * @throws \Swagger\Client\ApiException on non-2xx response * @throws \InvalidArgumentException * @return int */ public function taskWorkSetTaskPriority($task_ids, $priority) { list($response) = $this->taskWorkSetTaskPriorityWithHttpInfo($task_ids, $priority); return $response; } /** * Operation taskWorkSetTaskPriorityWithHttpInfo * * This call sets the tasks priority * * @param int[] $task_ids List of task identifier (required) * @param int $priority Priority (required) * * @throws \Swagger\Client\ApiException on non-2xx response * @throws \InvalidArgumentException * @return array of int, HTTP status code, HTTP response headers (array of strings) */ public function taskWorkSetTaskPriorityWithHttpInfo($task_ids, $priority) { $returnType = 'int'; $request = $this->taskWorkSetTaskPriorityRequest($task_ids, $priority); try { $options = $this->createHttpClientOption(); try { $response = $this->client->send($request, $options); } catch (RequestException $e) { throw new ApiException( "[{$e->getCode()}] {$e->getMessage()}", $e->getCode(), $e->getResponse()? $e->getResponse()->getHeaders() : null, $e->getResponse()? $e->getResponse()->getBody()->getContents() : null ); } $statusCode = $response->getStatusCode(); if ($statusCode < 200 || $statusCode > 299) { throw new ApiException( sprintf( '[%d] Error connecting to the API (%s)', $statusCode, $request->getUri() ), $statusCode, $response->getHeaders(), $response->getBody() ); } $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer } else { $content = $responseBody->getContents(); if ($returnType!=='string') { $content = json_decode($content); } } return [ ObjectSerializer::deserialize($content, $returnType, []), $response->getStatusCode(), $response->getHeaders() ]; } catch (ApiException $e) { switch ($e->getCode()) { case 200: $data = ObjectSerializer::deserialize( $e->getResponseBody(), 'int', $e->getResponseHeaders() ); $e->setResponseObject($data); break; } throw $e; } } /** * Operation taskWorkSetTaskPriorityAsync * * This call sets the tasks priority * * @param int[] $task_ids List of task identifier (required) * @param int $priority Priority (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Promise\PromiseInterface */ public function taskWorkSetTaskPriorityAsync($task_ids, $priority) { return $this->taskWorkSetTaskPriorityAsyncWithHttpInfo($task_ids, $priority) ->then( function ($response) { return $response[0]; } ); } /** * Operation taskWorkSetTaskPriorityAsyncWithHttpInfo * * This call sets the tasks priority * * @param int[] $task_ids List of task identifier (required) * @param int $priority Priority (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Promise\PromiseInterface */ public function taskWorkSetTaskPriorityAsyncWithHttpInfo($task_ids, $priority) { $returnType = 'int'; $request = $this->taskWorkSetTaskPriorityRequest($task_ids, $priority); return $this->client ->sendAsync($request, $this->createHttpClientOption()) ->then( function ($response) use ($returnType) { $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer } else { $content = $responseBody->getContents(); if ($returnType!=='string') { $content = json_decode($content); } } return [ ObjectSerializer::deserialize($content, $returnType, []), $response->getStatusCode(), $response->getHeaders() ]; }, function ($exception) { $response = $exception->getResponse(); $statusCode = $response->getStatusCode(); throw new ApiException( sprintf( '[%d] Error connecting to the API (%s)', $statusCode, $exception->getRequest()->getUri() ), $statusCode, $response->getHeaders(), $response->getBody() ); } ); } /** * Create request for operation 'taskWorkSetTaskPriority' * * @param int[] $task_ids List of task identifier (required) * @param int $priority Priority (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Psr7\Request */ protected function taskWorkSetTaskPriorityRequest($task_ids, $priority) { // verify the required parameter 'task_ids' is set if ($task_ids === null) { throw new \InvalidArgumentException( 'Missing the required parameter $task_ids when calling taskWorkSetTaskPriority' ); } // verify the required parameter 'priority' is set if ($priority === null) { throw new \InvalidArgumentException( 'Missing the required parameter $priority when calling taskWorkSetTaskPriority' ); } $resourcePath = '/api/TaskWork/priority/{priority}'; $formParams = []; $queryParams = []; $headerParams = []; $httpBody = ''; $multipart = false; // path params if ($priority!== null) { $resourcePath = str_replace( '{'. 'priority'. '}', ObjectSerializer::toPathValue($priority), $resourcePath ); } // body params $_tempBody = null; if (isset($task_ids)) { $_tempBody = $task_ids; } if ($multipart) { $headers = $this->headerSelector->selectHeadersForMultipart( ['application/json', 'text/json', 'application/xml', 'text/xml'] ); } else { $headers = $this->headerSelector->selectHeaders( ['application/json', 'text/json', 'application/xml', 'text/xml'], ['application/json', 'text/json', 'application/xml', 'text/xml', 'application/x-www-form-urlencoded'] ); } // for model (json/xml) if (isset($_tempBody)) { // $_tempBody is the method argument, if present $httpBody = $_tempBody; // \stdClass has no __toString(), so we should encode it manually if ($httpBody instanceof \stdClass && $headers['Content-Type'] === 'application/json') { $httpBody = \GuzzleHttp\json_encode($httpBody); } } elseif (count($formParams) > 0) { if ($multipart) { $multipartContents = []; foreach ($formParams as $formParamName => $formParamValue) { $multipartContents[] = [ 'name' => $formParamName, 'contents' => $formParamValue ]; } // for HTTP post (form) $httpBody = new MultipartStream($multipartContents); } elseif ($headers['Content-Type'] === 'application/json') { $httpBody = \GuzzleHttp\json_encode($formParams); } else { // for HTTP post (form) $httpBody = \GuzzleHttp\Psr7\build_query($formParams); } } // this endpoint requires API key authentication $apiKey = $this->config->getApiKeyWithPrefix('Authorization'); if ($apiKey!== null) { $headers['Authorization'] = $apiKey; } $defaultHeaders = []; if ($this->config->getUserAgent()) { $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); } $headers = array_merge( $defaultHeaders, $headerParams, $headers ); $query = \GuzzleHttp\Psr7\build_query($queryParams); return new Request( 'PUT', $this->config->getHost(). $resourcePath. ($query? "?{$query}" : ''), $headers, $httpBody ); } /** * Operation taskWorkSetTaskRead * * This call sets the task as read * * @param int[] $taskid Task Identifier (required) * * @throws \Swagger\Client\ApiException on non-2xx response * @throws \InvalidArgumentException * @return int */ public function taskWorkSetTaskRead($taskid) { list($response) = $this->taskWorkSetTaskReadWithHttpInfo($taskid); return $response; } /** * Operation taskWorkSetTaskReadWithHttpInfo * * This call sets the task as read * * @param int[] $taskid Task Identifier (required) * * @throws \Swagger\Client\ApiException on non-2xx response * @throws \InvalidArgumentException * @return array of int, HTTP status code, HTTP response headers (array of strings) */ public function taskWorkSetTaskReadWithHttpInfo($taskid) { $returnType = 'int'; $request = $this->taskWorkSetTaskReadRequest($taskid); try { $options = $this->createHttpClientOption(); try { $response = $this->client->send($request, $options); } catch (RequestException $e) { throw new ApiException( "[{$e->getCode()}] {$e->getMessage()}", $e->getCode(), $e->getResponse()? $e->getResponse()->getHeaders() : null, $e->getResponse()? $e->getResponse()->getBody()->getContents() : null ); } $statusCode = $response->getStatusCode(); if ($statusCode < 200 || $statusCode > 299) { throw new ApiException( sprintf( '[%d] Error connecting to the API (%s)', $statusCode, $request->getUri() ), $statusCode, $response->getHeaders(), $response->getBody() ); } $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer } else { $content = $responseBody->getContents(); if ($returnType!=='string') { $content = json_decode($content); } } return [ ObjectSerializer::deserialize($content, $returnType, []), $response->getStatusCode(), $response->getHeaders() ]; } catch (ApiException $e) { switch ($e->getCode()) { case 200: $data = ObjectSerializer::deserialize( $e->getResponseBody(), 'int', $e->getResponseHeaders() ); $e->setResponseObject($data); break; } throw $e; } } /** * Operation taskWorkSetTaskReadAsync * * This call sets the task as read * * @param int[] $taskid Task Identifier (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Promise\PromiseInterface */ public function taskWorkSetTaskReadAsync($taskid) { return $this->taskWorkSetTaskReadAsyncWithHttpInfo($taskid) ->then( function ($response) { return $response[0]; } ); } /** * Operation taskWorkSetTaskReadAsyncWithHttpInfo * * This call sets the task as read * * @param int[] $taskid Task Identifier (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Promise\PromiseInterface */ public function taskWorkSetTaskReadAsyncWithHttpInfo($taskid) { $returnType = 'int'; $request = $this->taskWorkSetTaskReadRequest($taskid); return $this->client ->sendAsync($request, $this->createHttpClientOption()) ->then( function ($response) use ($returnType) { $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer } else { $content = $responseBody->getContents(); if ($returnType!=='string') { $content = json_decode($content); } } return [ ObjectSerializer::deserialize($content, $returnType, []), $response->getStatusCode(), $response->getHeaders() ]; }, function ($exception) { $response = $exception->getResponse(); $statusCode = $response->getStatusCode(); throw new ApiException( sprintf( '[%d] Error connecting to the API (%s)', $statusCode, $exception->getRequest()->getUri() ), $statusCode, $response->getHeaders(), $response->getBody() ); } ); } /** * Create request for operation 'taskWorkSetTaskRead' * * @param int[] $taskid Task Identifier (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Psr7\Request */ protected function taskWorkSetTaskReadRequest($taskid) { // verify the required parameter 'taskid' is set if ($taskid === null) { throw new \InvalidArgumentException( 'Missing the required parameter $taskid when calling taskWorkSetTaskRead' ); } $resourcePath = '/api/TaskWork/read'; $formParams = []; $queryParams = []; $headerParams = []; $httpBody = ''; $multipart = false; // body params $_tempBody = null; if (isset($taskid)) { $_tempBody = $taskid; } if ($multipart) { $headers = $this->headerSelector->selectHeadersForMultipart( ['application/json', 'text/json', 'application/xml', 'text/xml'] ); } else { $headers = $this->headerSelector->selectHeaders( ['application/json', 'text/json', 'application/xml', 'text/xml'], ['application/json', 'text/json', 'application/xml', 'text/xml', 'application/x-www-form-urlencoded'] ); } // for model (json/xml) if (isset($_tempBody)) { // $_tempBody is the method argument, if present $httpBody = $_tempBody; // \stdClass has no __toString(), so we should encode it manually if ($httpBody instanceof \stdClass && $headers['Content-Type'] === 'application/json') { $httpBody = \GuzzleHttp\json_encode($httpBody); } } elseif (count($formParams) > 0) { if ($multipart) { $multipartContents = []; foreach ($formParams as $formParamName => $formParamValue) { $multipartContents[] = [ 'name' => $formParamName, 'contents' => $formParamValue ]; } // for HTTP post (form) $httpBody = new MultipartStream($multipartContents); } elseif ($headers['Content-Type'] === 'application/json') { $httpBody = \GuzzleHttp\json_encode($formParams); } else { // for HTTP post (form) $httpBody = \GuzzleHttp\Psr7\build_query($formParams); } } // this endpoint requires API key authentication $apiKey = $this->config->getApiKeyWithPrefix('Authorization'); if ($apiKey!== null) { $headers['Authorization'] = $apiKey; } $defaultHeaders = []; if ($this->config->getUserAgent()) { $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); } $headers = array_merge( $defaultHeaders, $headerParams, $headers ); $query = \GuzzleHttp\Psr7\build_query($queryParams); return new Request( 'PUT', $this->config->getHost(). $resourcePath. ($query? "?{$query}" : ''), $headers, $httpBody ); } /** * Operation taskWorkSetTaskUnRead * * This call sets the tasks as unread * * @param int[] $task_ids List of task identifier (required) * * @throws \Swagger\Client\ApiException on non-2xx response * @throws \InvalidArgumentException * @return int */ public function taskWorkSetTaskUnRead($task_ids) { list($response) = $this->taskWorkSetTaskUnReadWithHttpInfo($task_ids); return $response; } /** * Operation taskWorkSetTaskUnReadWithHttpInfo * * This call sets the tasks as unread * * @param int[] $task_ids List of task identifier (required) * * @throws \Swagger\Client\ApiException on non-2xx response * @throws \InvalidArgumentException * @return array of int, HTTP status code, HTTP response headers (array of strings) */ public function taskWorkSetTaskUnReadWithHttpInfo($task_ids) { $returnType = 'int'; $request = $this->taskWorkSetTaskUnReadRequest($task_ids); try { $options = $this->createHttpClientOption(); try { $response = $this->client->send($request, $options); } catch (RequestException $e) { throw new ApiException( "[{$e->getCode()}] {$e->getMessage()}", $e->getCode(), $e->getResponse()? $e->getResponse()->getHeaders() : null, $e->getResponse()? $e->getResponse()->getBody()->getContents() : null ); } $statusCode = $response->getStatusCode(); if ($statusCode < 200 || $statusCode > 299) { throw new ApiException( sprintf( '[%d] Error connecting to the API (%s)', $statusCode, $request->getUri() ), $statusCode, $response->getHeaders(), $response->getBody() ); } $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer } else { $content = $responseBody->getContents(); if ($returnType!=='string') { $content = json_decode($content); } } return [ ObjectSerializer::deserialize($content, $returnType, []), $response->getStatusCode(), $response->getHeaders() ]; } catch (ApiException $e) { switch ($e->getCode()) { case 200: $data = ObjectSerializer::deserialize( $e->getResponseBody(), 'int', $e->getResponseHeaders() ); $e->setResponseObject($data); break; } throw $e; } } /** * Operation taskWorkSetTaskUnReadAsync * * This call sets the tasks as unread * * @param int[] $task_ids List of task identifier (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Promise\PromiseInterface */ public function taskWorkSetTaskUnReadAsync($task_ids) { return $this->taskWorkSetTaskUnReadAsyncWithHttpInfo($task_ids) ->then( function ($response) { return $response[0]; } ); } /** * Operation taskWorkSetTaskUnReadAsyncWithHttpInfo * * This call sets the tasks as unread * * @param int[] $task_ids List of task identifier (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Promise\PromiseInterface */ public function taskWorkSetTaskUnReadAsyncWithHttpInfo($task_ids) { $returnType = 'int'; $request = $this->taskWorkSetTaskUnReadRequest($task_ids); return $this->client ->sendAsync($request, $this->createHttpClientOption()) ->then( function ($response) use ($returnType) { $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer } else { $content = $responseBody->getContents(); if ($returnType!=='string') { $content = json_decode($content); } } return [ ObjectSerializer::deserialize($content, $returnType, []), $response->getStatusCode(), $response->getHeaders() ]; }, function ($exception) { $response = $exception->getResponse(); $statusCode = $response->getStatusCode(); throw new ApiException( sprintf( '[%d] Error connecting to the API (%s)', $statusCode, $exception->getRequest()->getUri() ), $statusCode, $response->getHeaders(), $response->getBody() ); } ); } /** * Create request for operation 'taskWorkSetTaskUnRead' * * @param int[] $task_ids List of task identifier (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Psr7\Request */ protected function taskWorkSetTaskUnReadRequest($task_ids) { // verify the required parameter 'task_ids' is set if ($task_ids === null) { throw new \InvalidArgumentException( 'Missing the required parameter $task_ids when calling taskWorkSetTaskUnRead' ); } $resourcePath = '/api/TaskWork/unread'; $formParams = []; $queryParams = []; $headerParams = []; $httpBody = ''; $multipart = false; // body params $_tempBody = null; if (isset($task_ids)) { $_tempBody = $task_ids; } if ($multipart) { $headers = $this->headerSelector->selectHeadersForMultipart( ['application/json', 'text/json', 'application/xml', 'text/xml'] ); } else { $headers = $this->headerSelector->selectHeaders( ['application/json', 'text/json', 'application/xml', 'text/xml'], ['application/json', 'text/json', 'application/xml', 'text/xml', 'application/x-www-form-urlencoded'] ); } // for model (json/xml) if (isset($_tempBody)) { // $_tempBody is the method argument, if present $httpBody = $_tempBody; // \stdClass has no __toString(), so we should encode it manually if ($httpBody instanceof \stdClass && $headers['Content-Type'] === 'application/json') { $httpBody = \GuzzleHttp\json_encode($httpBody); } } elseif (count($formParams) > 0) { if ($multipart) { $multipartContents = []; foreach ($formParams as $formParamName => $formParamValue) { $multipartContents[] = [ 'name' => $formParamName, 'contents' => $formParamValue ]; } // for HTTP post (form) $httpBody = new MultipartStream($multipartContents); } elseif ($headers['Content-Type'] === 'application/json') { $httpBody = \GuzzleHttp\json_encode($formParams); } else { // for HTTP post (form) $httpBody = \GuzzleHttp\Psr7\build_query($formParams); } } // this endpoint requires API key authentication $apiKey = $this->config->getApiKeyWithPrefix('Authorization'); if ($apiKey!== null) { $headers['Authorization'] = $apiKey; } $defaultHeaders = []; if ($this->config->getUserAgent()) { $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); } $headers = array_merge( $defaultHeaders, $headerParams, $headers ); $query = \GuzzleHttp\Psr7\build_query($queryParams); return new Request( 'PUT', $this->config->getHost(). $resourcePath. ($query? "?{$query}" : ''), $headers, $httpBody ); } /** * Operation taskWorkTaskWorkTakeCharge * * This call takes charge of a taskwork * * @param int $task_work_id Taskwork identifier (required) * * @throws \Swagger\Client\ApiException on non-2xx response * @throws \InvalidArgumentException * @return void */ public function taskWorkTaskWorkTakeCharge($task_work_id) { $this->taskWorkTaskWorkTakeChargeWithHttpInfo($task_work_id); } /** * Operation taskWorkTaskWorkTakeChargeWithHttpInfo * * This call takes charge of a taskwork * * @param int $task_work_id Taskwork identifier (required) * * @throws \Swagger\Client\ApiException on non-2xx response * @throws \InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ public function taskWorkTaskWorkTakeChargeWithHttpInfo($task_work_id) { $returnType = ''; $request = $this->taskWorkTaskWorkTakeChargeRequest($task_work_id); try { $options = $this->createHttpClientOption(); try { $response = $this->client->send($request, $options); } catch (RequestException $e) { throw new ApiException( "[{$e->getCode()}] {$e->getMessage()}", $e->getCode(), $e->getResponse()? $e->getResponse()->getHeaders() : null, $e->getResponse()? $e->getResponse()->getBody()->getContents() : null ); } $statusCode = $response->getStatusCode(); if ($statusCode < 200 || $statusCode > 299) { throw new ApiException( sprintf( '[%d] Error connecting to the API (%s)', $statusCode, $request->getUri() ), $statusCode, $response->getHeaders(), $response->getBody() ); } return [null, $statusCode, $response->getHeaders()]; } catch (ApiException $e) { switch ($e->getCode()) { } throw $e; } } /** * Operation taskWorkTaskWorkTakeChargeAsync * * This call takes charge of a taskwork * * @param int $task_work_id Taskwork identifier (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Promise\PromiseInterface */ public function taskWorkTaskWorkTakeChargeAsync($task_work_id) { return $this->taskWorkTaskWorkTakeChargeAsyncWithHttpInfo($task_work_id) ->then( function ($response) { return $response[0]; } ); } /** * Operation taskWorkTaskWorkTakeChargeAsyncWithHttpInfo * * This call takes charge of a taskwork * * @param int $task_work_id Taskwork identifier (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Promise\PromiseInterface */ public function taskWorkTaskWorkTakeChargeAsyncWithHttpInfo($task_work_id) { $returnType = ''; $request = $this->taskWorkTaskWorkTakeChargeRequest($task_work_id); return $this->client ->sendAsync($request, $this->createHttpClientOption()) ->then( function ($response) use ($returnType) { return [null, $response->getStatusCode(), $response->getHeaders()]; }, function ($exception) { $response = $exception->getResponse(); $statusCode = $response->getStatusCode(); throw new ApiException( sprintf( '[%d] Error connecting to the API (%s)', $statusCode, $exception->getRequest()->getUri() ), $statusCode, $response->getHeaders(), $response->getBody() ); } ); } /** * Create request for operation 'taskWorkTaskWorkTakeCharge' * * @param int $task_work_id Taskwork identifier (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Psr7\Request */ protected function taskWorkTaskWorkTakeChargeRequest($task_work_id) { // verify the required parameter 'task_work_id' is set if ($task_work_id === null) { throw new \InvalidArgumentException( 'Missing the required parameter $task_work_id when calling taskWorkTaskWorkTakeCharge' ); } $resourcePath = '/api/TaskWork/{taskWorkId}/TakeCharge'; $formParams = []; $queryParams = []; $headerParams = []; $httpBody = ''; $multipart = false; // path params if ($task_work_id!== null) { $resourcePath = str_replace( '{'. 'taskWorkId'. '}', ObjectSerializer::toPathValue($task_work_id), $resourcePath ); } // body params $_tempBody = null; if ($multipart) { $headers = $this->headerSelector->selectHeadersForMultipart( [] ); } else { $headers = $this->headerSelector->selectHeaders( [], [] ); } // for model (json/xml) if (isset($_tempBody)) { // $_tempBody is the method argument, if present $httpBody = $_tempBody; // \stdClass has no __toString(), so we should encode it manually if ($httpBody instanceof \stdClass && $headers['Content-Type'] === 'application/json') { $httpBody = \GuzzleHttp\json_encode($httpBody); } } elseif (count($formParams) > 0) { if ($multipart) { $multipartContents = []; foreach ($formParams as $formParamName => $formParamValue) { $multipartContents[] = [ 'name' => $formParamName, 'contents' => $formParamValue ]; } // for HTTP post (form) $httpBody = new MultipartStream($multipartContents); } elseif ($headers['Content-Type'] === 'application/json') { $httpBody = \GuzzleHttp\json_encode($formParams); } else { // for HTTP post (form) $httpBody = \GuzzleHttp\Psr7\build_query($formParams); } } // this endpoint requires API key authentication $apiKey = $this->config->getApiKeyWithPrefix('Authorization'); if ($apiKey!== null) { $headers['Authorization'] = $apiKey; } $defaultHeaders = []; if ($this->config->getUserAgent()) { $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); } $headers = array_merge( $defaultHeaders, $headerParams, $headers ); $query = \GuzzleHttp\Psr7\build_query($queryParams); return new Request( 'PUT', $this->config->getHost(). $resourcePath. ($query? "?{$query}" : ''), $headers, $httpBody ); } /** * Create http client option * * @throws \RuntimeException on file opening failure * @return array of http client options */ protected function createHttpClientOption() { $options = []; if ($this->config->getDebug()) { $options[RequestOptions::DEBUG] = fopen($this->config->getDebugFile(), 'a'); if (!$options[RequestOptions::DEBUG]) { throw new \RuntimeException('Failed to open the debug file: '. $this->config->getDebugFile()); } } return $options; } } ======================= File: test/Model/TaskWorkDynamicJobOperationDTOTest.php ======================= <?php /** * TaskWorkDynamicJobOperationDTOTest * * PHP version 5 * * @category Class * @package Swagger\Client * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen */ /** * Abletech.Arxivar.Server.WebApi.Services * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * OpenAPI spec version: v1 * * Generated by: https://github.com/swagger-api/swagger-codegen.git * Swagger Codegen version: 2.3.1 */ /** * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen * Please update the test case below to test the model. */ namespace Swagger\Client; /** * TaskWorkDynamicJobOperationDTOTest Class Doc Comment * * @category Class */ // * @description Dynamic job operation /** * @package Swagger\Client * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen */ class TaskWorkDynamicJobOperationDTOTest extends \PHPUnit_Framework_TestCase { /** * Setup before running any test case */ public static function setUpBeforeClass() { } /** * Setup before running each test case */ public function setUp() { } /** * Clean up after running each test case */ public function tearDown() { } /** * Clean up after running all test cases */ public static function tearDownAfterClass() { } /** * Test "TaskWorkDynamicJobOperationDTO" */ public function testTaskWorkDynamicJobOperationDTO() { } /** * Test attribute "id" */ public function testPropertyId() { } /** * Test attribute "process_id" */ public function testPropertyProcessId() { } /** * Test attribute "task_work_id" */ public function testPropertyTaskWorkId() { } /** * Test attribute "dynamic_job" */ public function testPropertyDynamicJob() { } /** * Test attribute "outcome_value" */ public function testPropertyOutcomeValue() { } /** * Test attribute "execute_after" */ public function testPropertyExecuteAfter() { } /** * Test attribute "is_required" */ public function testPropertyIsRequired() { } /** * Test attribute "is_executed" */ public function testPropertyIsExecuted() { } } ======================= File: lib/Model/FindDTO.php ======================= <?php /** * FindDTO * * PHP version 5 * * @category Class * @package Swagger\Client * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen */ /** * Abletech.Arxivar.Server.WebApi.Services * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * OpenAPI spec version: v1 * * Generated by: https://github.com/swagger-api/swagger-codegen.git * Swagger Codegen version: 2.3.1 */ /** * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen * Do not edit the class manually. */ namespace Swagger\Client\Model; use \ArrayAccess; use \Swagger\Client\ObjectSerializer; /** * FindDTO Class Doc Comment * * @category Class * @description Class of find data * @package Swagger\Client * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen */ class FindDTO implements ModelInterface, ArrayAccess { const DISCRIMINATOR = null; /** * The original name of the model. * * @var string */ protected static $swaggerModelName = 'FindDTO'; /** * Array of property to type mappings. Used for (de)serialization * * @var string[] */ protected static $swaggerTypes = [ 'id' =>'string', 'description' =>'string', 'owner' => 'int', 'owner_description' =>'string', 'context' => 'int', 'show_fields' => 'bool', 'form_open' => 'bool', 'show_on_desktop' => 'bool', 'folder_id' => 'int', 'external_id' =>'string', 'table_name' =>'string', 'table_field_id' =>'string' ]; /** * Array of property to format mappings. Used for (de)serialization * * @var string[] */ protected static $swaggerFormats = [ 'id' => null, 'description' => null, 'owner' => 'int32', 'owner_description' => null, 'context' => 'int32', 'show_fields' => null, 'form_open' => null, 'show_on_desktop' => null, 'folder_id' => 'int32', 'external_id' => null, 'table_name' => null, 'table_field_id' => null ]; /** * Array of property to type mappings. Used for (de)serialization * * @return array */ public static function swaggerTypes() { return self::$swaggerTypes; } /** * Array of property to format mappings. Used for (de)serialization * * @return array */ public static function swaggerFormats() { return self::$swaggerFormats; } /** * Array of attributes where the key is the local name, * and the value is the original name * * @var string[] */ protected static $attributeMap = [ 'id' => 'id', 'description' => 'description', 'owner' => 'owner', 'owner_description' => 'ownerDescription', 'context' => 'context', 'show_fields' =>'showFields', 'form_open' => 'formOpen', 'show_on_desktop' =>'showOnDesktop', 'folder_id' => 'folderId', 'external_id' => 'externalId', 'table_name' => 'tableName', 'table_field_id' => 'tableFieldId' ]; /** * Array of attributes to setter functions (for deserialization of responses) * * @var string[] */ protected static $setters = [ 'id' =>'setId', 'description' =>'setDescription', 'owner' =>'setOwner', 'owner_description' =>'setOwnerDescription', 'context' =>'setContext', 'show_fields' =>'setShowFields', 'form_open' =>'setFormOpen', 'show_on_desktop' =>'setShowOnDesktop', 'folder_id' =>'setFolderId', 'external_id' =>'setExternalId', 'table_name' =>'setTableName', 'table_field_id' =>'setTableFieldId' ]; /** * Array of attributes to getter functions (for serialization of requests) * * @var string[] */ protected static $getters = [ 'id' => 'getId', 'description' => 'getDescription', 'owner' => 'getOwner', 'owner_description' => 'getOwnerDescription', 'context' => 'getContext', 'show_fields' => 'getShowFields', 'form_open' => 'getFormOpen', 'show_on_desktop' => 'getShowOnDesktop', 'folder_id' => 'getFolderId', 'external_id' => 'getExternalId', 'table_name' => 'getTableName', 'table_field_id' => 'getTableFieldId' ]; /** * Array of attributes where the key is the local name, * and the value is the original name * * @return array */ public static function attributeMap() { return self::$attributeMap; } /** * Array of attributes to setter functions (for deserialization of responses) * * @return array */ public static function setters() { return self::$setters; } /** * Array of attributes to getter functions (for serialization of requests) * * @return array */ public static function getters() { return self::$getters; } /** * The original name of the model. * * @return string */ public function getModelName() { return self::$swaggerModelName; } /** * Associative array for storing property values * * @var mixed[] */ protected $container = []; /** * Constructor * * @param mixed[] $data Associated array of property values * initializing the model */ public function __construct(array $data = null) { $this->container['id'] = isset($data['id'])? $data['id'] : null; $this->container['description'] = isset($data['description'])? $data['description'] : null; $this->container['owner'] = isset($data['owner'])? $data['owner'] : null; $this->container['owner_description'] = isset($data['owner_description'])? $data['owner_description'] : null; $this->container['context'] = isset($data['context'])? $data['context'] : null; $this->container['show_fields'] = isset($data['show_fields'])? $data['show_fields'] : null; $this->container['form_open'] = isset($data['form_open'])? $data['form_open'] : null; $this->container['show_on_desktop'] = isset($data['show_on_desktop'])? $data['show_on_desktop'] : null; $this->container['folder_id'] = isset($data['folder_id'])? $data['folder_id'] : null; $this->container['external_id'] = isset($data['external_id'])? $data['external_id'] : null; $this->container['table_name'] = isset($data['table_name'])? $data['table_name'] : null; $this->container['table_field_id'] = isset($data['table_field_id'])? $data['table_field_id'] : null; } /** * Show all the invalid properties with reasons. * * @return array invalid properties with reasons */ public function listInvalidProperties() { $invalidProperties = []; return $invalidProperties; } /** * Validate all the properties in the model * return true if all passed * * @return bool True if all properties are valid */ public function valid() { return true; } /** * Gets id * * @return string */ public function getId() { return $this->container['id']; } /** * Sets id * * @param string $id Identifier * * @return $this */ public function setId($id) { $this->container['id'] = $id; return $this; } /** * Gets description * * @return string */ public function getDescription() { return $this->container['description']; } /** * Sets description * * @param string $description Description * * @return $this */ public function setDescription($description) { $this->container['description'] = $description; return $this; } /** * Gets owner * * @return int */ public function getOwner() { return $this->container['owner']; } /** * Sets owner * * @param int $owner Author * * @return $this */ public function setOwner($owner) { $this->container['owner'] = $owner; return $this; } /** * Gets owner_description * * @return string */ public function getOwnerDescription() { return $this->container['owner_description']; } /** * Sets owner_description * * @param string $owner_description Author Description * * @return $this */ public function setOwnerDescription($owner_description) { $this->container['owner_description'] = $owner_description; return $this; } /** * Gets context * * @return int */ public function getContext() { return $this->container['context']; } /** * Sets context * * @param int $context Possible values: 0: Dm_Profile_Search 1: Dm_ElencoPratiche_Search 2: Dm_TaskWork_Search 3: Dm_UtentiBase_Search 4: Dm_Contatti_Search 5: ExternalData 6: Dm_Profile_Search_For_Fasciculation 7: Dm_Profile_Search_For_User_Default 8: Dm_Contatti_Search_For_User_Default * * @return $this */ public function setContext($context) { $this->container['context'] = $context; return $this; } /** * Gets show_fields * * @return bool */ public function getShowFields() { return $this->container['show_fields']; } /** * Sets show_fields * * @param bool $show_fields Show Fields * * @return $this */ public function setShowFields($show_fields) { $this->container['show_fields'] = $show_fields; return $this; } /** * Gets form_open * * @return bool */ public function getFormOpen() { return $this->container['form_open']; } /** * Sets form_open * * @param bool $form_open Open the Form * * @return $this */ public function setFormOpen($form_open) { $this->container['form_open'] = $form_open; return $this; } /** * Gets show_on_desktop * * @return bool */ public function getShowOnDesktop() { return $this->container['show_on_desktop']; } /** * Sets show_on_desktop * * @param bool $show_on_desktop Show on Desktop * * @return $this */ public function setShowOnDesktop($show_on_desktop) { $this->container['show_on_desktop'] = $show_on_desktop; return $this; } /** * Gets folder_id * * @return int */ public function getFolderId() { return $this->container['folder_id']; } /** * Sets folder_id * * @param int $folder_id Folder Identifier * * @return $this */ public function setFolderId($folder_id) { $this->container['folder_id'] = $folder_id; return $this; } /** * Gets external_id * * @return string */ public function getExternalId() { return $this->container['external_id']; } /** * Sets external_id * * @param string $external_id External Identifier * * @return $this */ public function setExternalId($external_id) { $this->container['external_id'] = $external_id; return $this; } /** * Gets table_name * * @return string */ public function getTableName() { return $this->container['table_name']; } /** * Sets table_name * * @param string $table_name Table Name * * @return $this */ public function setTableName($table_name) { $this->container['table_name'] = $table_name; return $this; } /** * Gets table_field_id * * @return string */ public function getTableFieldId() { return $this->container['table_field_id']; } /** * Sets table_field_id * * @param string $table_field_id Table Field Identifier * * @return $this */ public function setTableFieldId($table_field_id) { $this->container['table_field_id'] = $table_field_id; return $this; } /** * Returns true if offset exists. False otherwise. * * @param integer $offset Offset * * @return boolean */ public function offsetExists($offset) { return isset($this->container[$offset]); } /** * Gets offset. * * @param integer $offset Offset * * @return mixed */ public function offsetGet($offset) { return isset($this->container[$offset])? $this->container[$offset] : null; } /** * Sets value based on offset. * * @param integer $offset Offset * @param mixed $value Value to be set * * @return void */ public function offsetSet($offset, $value) { if (is_null($offset)) { $this->container[] = $value; } else { $this->container[$offset] = $value; } } /** * Unsets offset. * * @param integer $offset Offset * * @return void */ public function offsetUnset($offset) { unset($this->container[$offset]); } /** * Gets the string presentation of the object * * @return string */ public function __toString() { if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print return json_encode( ObjectSerializer::sanitizeForSerialization($this), JSON_PRETTY_PRINT ); } return json_encode(ObjectSerializer::sanitizeForSerialization($this)); } } ======================= File: test/Api/BarcodeApiTest.php ======================= <gh_stars>0 <?php /** * BarcodeApiTest * PHP version 5 * * @category Class * @package Swagger\Client * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen */ /** * Abletech.Arxivar.Server.WebApi.Services * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * OpenAPI spec version: v1 * * Generated by: https://github.com/swagger-api/swagger-codegen.git * Swagger Codegen version: 2.3.1 */ /** * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen * Please update the test case below to test the endpoint. */ namespace Swagger\Client; use \Swagger\Client\Configuration; use \Swagger\Client\ApiException; use \Swagger\Client\ObjectSerializer; /** * BarcodeApiTest Class Doc Comment * * @category Class * @package Swagger\Client * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen */ class BarcodeApiTest extends \PHPUnit_Framework_TestCase { /** * Setup before running any test cases */ public static function setUpBeforeClass() { } /** * Setup before running each test case */ public function setUp() { } /** * Clean up after running each test case */ public function tearDown() { } /** * Clean up after running all test cases */ public static function tearDownAfterClass() { } /** * Test case for barcodeGetBarcodeGraphicUserTemplate * * This call returns the barcode grapich user template. * */ public function testBarcodeGetBarcodeGraphicUserTemplate() { } /** * Test case for barcodeGetBarcodeUserSettings * * This call returns the barcode user default settings. * */ public function testBarcodeGetBarcodeUserSettings() { } /** * Test case for barcodeGetBarcodeUserTemplate * * This call returns the barcode user template by document type. * */ public function testBarcodeGetBarcodeUserTemplate() { } /** * Test case for barcodeGetDefaultTemplate * * This call returns the barcode default template by a printer family - ZEBRA_EPL2, - ZEBRA_ZPL2, - TOSHIBA_BSV4, - EPSON_ESC_POS. * */ public function testBarcodeGetDefaultTemplate() { } /** * Test case for barcodePrintArxBarcode * * This call executes the print of barcode in format Arxivar. * */ public function testBarcodePrintArxBarcode() { } /** * Test case for barcodePrintAttachmentByDocnumber * * This call executes the print of barcode for attachment of document. * */ public function testBarcodePrintAttachmentByDocnumber() { } /** * Test case for barcodePrintByDocnumber * * This call executes the print of barcode associated with a document. * */ public function testBarcodePrintByDocnumber() { } /** * Test case for barcodePrintByIdBarcode * * This call executes the print of barcode. * */ public function testBarcodePrintByIdBarcode() { } /** * Test case for barcodePrintRevisionByDocnumber * * This call executes the print of barcode for revision of document. * */ public function testBarcodePrintRevisionByDocnumber() { } /** * Test case for barcodeSetBarcodeGraphicUserTemplate * * This call sets the barcode graphic user template. * */ public function testBarcodeSetBarcodeGraphicUserTemplate() { } /** * Test case for barcodeSetBarcodeUserSettings * * This call sets the barcode user default settings. * */ public function testBarcodeSetBarcodeUserSettings() { } /** * Test case for barcodeSetBarcodeUserTemplate * * This call sets the barcode user template. * */ public function testBarcodeSetBarcodeUserTemplate() { } } ======================= File: lib/Model/SharingMailDTO.php ======================= <?php /** * SharingMailDTO * * PHP version 5 * * @category Class * @package Swagger\Client * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen */ /** * Abletech.Arxivar.Server.WebApi.Services * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * OpenAPI spec version: v1 * * Generated by: https://github.com/swagger-api/swagger-codegen.git * Swagger Codegen version: 2.3.1 */ /** * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen * Do not edit the class manually. */ namespace Swagger\Client\Model; use \ArrayAccess; use \Swagger\Client\ObjectSerializer; /** * SharingMailDTO Class Doc Comment * * @category Class * @package Swagger\Client * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen */ class SharingMailDTO implements ModelInterface, ArrayAccess { const DISCRIMINATOR = null; /** * The original name of the model. * * @var string */ protected static $swaggerModelName = 'SharingMailDTO'; /** * Array of property to type mappings. Used for (de)serialization * * @var string[] */ protected static $swaggerTypes = [ 'mail_subject' =>'string', 'mail_body_header' =>'string', 'mail_body_content' =>'string', 'mail_body_footer' =>'string', 'lang' =>'string' ]; /** * Array of property to format mappings. Used for (de)serialization * * @var string[] */ protected static $swaggerFormats = [ 'mail_subject' => null, 'mail_body_header' => null, 'mail_body_content' => null, 'mail_body_footer' => null, 'lang' => null ]; /** * Array of property to type mappings. Used for (de)serialization * * @return array */ public static function swaggerTypes() { return self::$swaggerTypes; } /** * Array of property to format mappings. Used for (de)serialization * * @return array */ public static function swaggerFormats() { return self::$swaggerFormats; } /** * Array of attributes where the key is the local name, * and the value is the original name * * @var string[] */ protected static $attributeMap = [ 'mail_subject' =>'mailSubject', 'mail_body_header' =>'mailBodyHeader', 'mail_body_content' =>'mailBodyContent', 'mail_body_footer' =>'mailBodyFooter', 'lang' => 'lang' ]; /** * Array of attributes to setter functions (for deserialization of responses) * * @var string[] */ protected static $setters = [ 'mail_subject' =>'setMailSubject', 'mail_body_header' =>'setMailBodyHeader', 'mail_body_content' =>'setMailBodyContent', 'mail_body_footer' =>'setMailBodyFooter', 'lang' =>'setLang' ]; /** * Array of attributes to getter functions (for serialization of requests) * * @var string[] */ protected static $getters = [ 'mail_subject' => 'getMailSubject', 'mail_body_header' => 'getMailBodyHeader', 'mail_body_content' => 'getMailBodyContent', 'mail_body_footer' => 'getMailBodyFooter', 'lang' => 'getLang' ]; /** * Array of attributes where the key is the local name, * and the value is the original name * * @return array */ public static function attributeMap() { return self::$attributeMap; } /** * Array of attributes to setter functions (for deserialization of responses) * * @return array */ public static function setters() { return self::$setters; } /** * Array of attributes to getter functions (for serialization of requests) * * @return array */ public static function getters() { return self::$getters; } /** * The original name of the model. * * @return string */ public function getModelName() { return self::$swaggerModelName; } /** * Associative array for storing property values * * @var mixed[] */ protected $container = []; /** * Constructor * * @param mixed[] $data Associated array of property values * initializing the model */ public function __construct(array $data = null) { $this->container['mail_subject'] = isset($data['mail_subject'])? $data['mail_subject'] : null; $this->container['mail_body_header'] = isset($data['mail_body_header'])? $data['mail_body_header'] : null; $this->container['mail_body_content'] = isset($data['mail_body_content'])? $data['mail_body_content'] : null; $this->container['mail_body_footer'] = isset($data['mail_body_footer'])? $data['mail_body_footer'] : null; $this->container['lang'] = isset($data['lang'])? $data['lang'] : null; } /** * Show all the invalid properties with reasons. * * @return array invalid properties with reasons */ public function listInvalidProperties() { $invalidProperties = []; return $invalidProperties; } /** * Validate all the properties in the model * return true if all passed * * @return bool True if all properties are valid */ public function valid() { return true; } /** * Gets mail_subject * * @return string */ public function getMailSubject() { return $this->container['mail_subject']; } /** * Sets mail_subject * * @param string $mail_subject Subject. * * @return $this */ public function setMailSubject($mail_subject) { $this->container['mail_subject'] = $mail_subject; return $this; } /** * Gets mail_body_header * * @return string */ public function getMailBodyHeader() { return $this->container['mail_body_header']; } /** * Sets mail_body_header * * @param string $mail_body_header Body Header. * * @return $this */ public function setMailBodyHeader($mail_body_header) { $this->container['mail_body_header'] = $mail_body_header; return $this; } /** * Gets mail_body_content * * @return string */ public function getMailBodyContent() { return $this->container['mail_body_content']; } /** * Sets mail_body_content * * @param string $mail_body_content Body Content. * * @return $this */ public function setMailBodyContent($mail_body_content) { $this->container['mail_body_content'] = $mail_body_content; return $this; } /** * Gets mail_body_footer * * @return string */ public function getMailBodyFooter() { return $this->container['mail_body_footer']; } /** * Sets mail_body_footer * * @param string $mail_body_footer Body Footer. * * @return $this */ public function setMailBodyFooter($mail_body_footer) { $this->container['mail_body_footer'] = $mail_body_footer; return $this; } /** * Gets lang * * @return string */ public function getLang() { return $this->container['lang']; } /** * Sets lang * * @param string $lang Lang code. * * @return $this */ public function setLang($lang) { $this->container['lang'] = $lang; return $this; } /** * Returns true if offset exists. False otherwise. * * @param integer $offset Offset * * @return boolean */ public function offsetExists($offset) { return isset($this->container[$offset]); } /** * Gets offset. * * @param integer $offset Offset * * @return mixed */ public function offsetGet($offset) { return isset($this->container[$offset])? $this->container[$offset] : null; } /** * Sets value based on offset. * * @param integer $offset Offset * @param mixed $value Value to be set * * @return void */ public function offsetSet($offset, $value) { if (is_null($offset)) { $this->container[] = $value; } else { $this->container[$offset] = $value; } } /** * Unsets offset. * * @param integer $offset Offset * * @return void */ public function offsetUnset($offset) { unset($this->container[$offset]); } /** * Gets the string presentation of the object * * @return string */ public function __toString() { if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print return json_encode( ObjectSerializer::sanitizeForSerialization($this), JSON_PRETTY_PRINT ); } return json_encode(ObjectSerializer::sanitizeForSerialization($this)); } } ======================= File: test/Api/MasksApiTest.php ======================= <?php /** * MasksApiTest * PHP version 5 * * @category Class * @package Swagger\Client * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen */ /** * Abletech.Arxivar.Server.WebApi.Services * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * OpenAPI spec version: v1 * * Generated by: https://github.com/swagger-api/swagger-codegen.git * Swagger Codegen version: 2.3.1 */ /** * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen * Please update the test case below to test the endpoint. */ namespace Swagger\Client; use \Swagger\Client\Configuration; use \Swagger\Client\ApiException; use \Swagger\Client\ObjectSerializer; /** * MasksApiTest Class Doc Comment * * @category Class * @package Swagger\Client * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen */ class MasksApiTest extends \PHPUnit_Framework_TestCase { /** * Setup before running any test cases */ public static function setUpBeforeClass() { } /** * Setup before running each test case */ public function setUp() { } /** * Clean up after running each test case */ public function tearDown() { } /** * Clean up after running all test cases */ public static function tearDownAfterClass() { } /** * Test case for masksCloneMask * * This call clones a mask. * */ public function testMasksCloneMask() { } /** * Test case for masksDelete * * This call deletes a mask. * */ public function testMasksDelete() { } /** * Test case for masksGetById * * This call returns a mask by its identifier. * */ public function testMasksGetById() { } /** * Test case for masksGetDocumentTypesByMaskId * * This call returns all possibile Document Types for a mask. * */ public function testMasksGetDocumentTypesByMaskId() { } /** * Test case for masksGetDocumentTypesByMaskIdOld * * This call returns all possibile Document Types for a mask. * */ public function testMasksGetDocumentTypesByMaskIdOld() { } /** * Test case for masksGetDocumentTypesTreeByMaskId * * This call returns all possibile Document Types for a mask (tree format). * */ public function testMasksGetDocumentTypesTreeByMaskId() { } /** * Test case for masksGetDocumentTypesTreeByMaskIdOld * * This call returns all possibile Document Types for a mask (tree format). * */ public function testMasksGetDocumentTypesTreeByMaskIdOld() { } /** * Test case for masksGetFieldsByClasse * * This call returns possibile fields by a Document Type. * */ public function testMasksGetFieldsByClasse() { } /** * Test case for masksGetList * * This call returns all masks. * */ public function testMasksGetList() { } /** * Test case for masksGetPermission * * This call returns the permissions for a mask. * */ public function testMasksGetPermission() { } /** * Test case for masksGetProfileForClasseBox * * This calls returns the profile schema for a mask associated to a class additional field. * */ public function testMasksGetProfileForClasseBox() { } /** * Test case for masksGetProfileSchemaByMaskId * * This call returns the profile schema by a mask. * */ public function testMasksGetProfileSchemaByMaskId() { } /** * Test case for masksGetRoot * * This call returns the root mask. * */ public function testMasksGetRoot() { } /** * Test case for masksInserMask * * This call inserts a new mask. * */ public function testMasksInserMask() { } /** * Test case for masksPost * * This call executes a new profiling. * */ public function testMasksPost() { } /** * Test case for masksSetPermission * * This call updates the permissions for a mask. * */ public function testMasksSetPermission() { } /** * Test case for masksUpdateMask * * This call updates a mask. * */ public function testMasksUpdateMask() { } } ======================= File: lib/Api/BufferApi.php ======================= <gh_stars>0 <?php /** * BufferApi * PHP version 5 * * @category Class * @package Swagger\Client * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen */ /** * Abletech.Arxivar.Server.WebApi.Services * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * OpenAPI spec version: v1 * * Generated by: https://github.com/swagger-api/swagger-codegen.git * Swagger Codegen version: 2.3.1 */ /** * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen * Do not edit the class manually. */ namespace Swagger\Client\Api; use GuzzleHttp\Client; use GuzzleHttp\ClientInterface; use GuzzleHttp\Exception\RequestException; use GuzzleHttp\Psr7\MultipartStream; use GuzzleHttp\Psr7\Request; use GuzzleHttp\RequestOptions; use Swagger\Client\ApiException; use Swagger\Client\Configuration; use Swagger\Client\HeaderSelector; use Swagger\Client\ObjectSerializer; /** * BufferApi Class Doc Comment * * @category Class * @package Swagger\Client * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen */ class BufferApi { /** * @var ClientInterface */ protected $client; /** * @var Configuration */ protected $config; /** * @param ClientInterface $client * @param Configuration $config * @param HeaderSelector $selector */ public function __construct( ClientInterface $client = null, Configuration $config = null, HeaderSelector $selector = null ) { $this->client = $client?: new Client(); $this->config = $config?: new Configuration(); $this->headerSelector = $selector?: new HeaderSelector(); } /** * @return Configuration */ public function getConfig() { return $this->config; } /** * Operation bufferDeleteByBufferId * * @param string $buffer_id buffer_id (required) * * @throws \Swagger\Client\ApiException on non-2xx response * @throws \InvalidArgumentException * @return bool */ public function bufferDeleteByBufferId($buffer_id) { list($response) = $this->bufferDeleteByBufferIdWithHttpInfo($buffer_id); return $response; } /** * Operation bufferDeleteByBufferIdWithHttpInfo * * @param string $buffer_id (required) * * @throws \Swagger\Client\ApiException on non-2xx response * @throws \InvalidArgumentException * @return array of bool, HTTP status code, HTTP response headers (array of strings) */ public function bufferDeleteByBufferIdWithHttpInfo($buffer_id) { $returnType = 'bool'; $request = $this->bufferDeleteByBufferIdRequest($buffer_id); try { $options = $this->createHttpClientOption(); try { $response = $this->client->send($request, $options); } catch (RequestException $e) { throw new ApiException( "[{$e->getCode()}] {$e->getMessage()}", $e->getCode(), $e->getResponse()? $e->getResponse()->getHeaders() : null, $e->getResponse()? $e->getResponse()->getBody()->getContents() : null ); } $statusCode = $response->getStatusCode(); if ($statusCode < 200 || $statusCode > 299) { throw new ApiException( sprintf( '[%d] Error connecting to the API (%s)', $statusCode, $request->getUri() ), $statusCode, $response->getHeaders(), $response->getBody() ); } $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer } else { $content = $responseBody->getContents(); if ($returnType!=='string') { $content = json_decode($content); } } return [ ObjectSerializer::deserialize($content, $returnType, []), $response->getStatusCode(), $response->getHeaders() ]; } catch (ApiException $e) { switch ($e->getCode()) { case 200: $data = ObjectSerializer::deserialize( $e->getResponseBody(), 'bool', $e->getResponseHeaders() ); $e->setResponseObject($data); break; } throw $e; } } /** * Operation bufferDeleteByBufferIdAsync * * * * @param string $buffer_id (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Promise\PromiseInterface */ public function bufferDeleteByBufferIdAsync($buffer_id) { return $this->bufferDeleteByBufferIdAsyncWithHttpInfo($buffer_id) ->then( function ($response) { return $response[0]; } ); } /** * Operation bufferDeleteByBufferIdAsyncWithHttpInfo * * * * @param string $buffer_id (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Promise\PromiseInterface */ public function bufferDeleteByBufferIdAsyncWithHttpInfo($buffer_id) { $returnType = 'bool'; $request = $this->bufferDeleteByBufferIdRequest($buffer_id); return $this->client ->sendAsync($request, $this->createHttpClientOption()) ->then( function ($response) use ($returnType) { $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer } else { $content = $responseBody->getContents(); if ($returnType!=='string') { $content = json_decode($content); } } return [ ObjectSerializer::deserialize($content, $returnType, []), $response->getStatusCode(), $response->getHeaders() ]; }, function ($exception) { $response = $exception->getResponse(); $statusCode = $response->getStatusCode(); throw new ApiException( sprintf( '[%d] Error connecting to the API (%s)', $statusCode, $exception->getRequest()->getUri() ), $statusCode, $response->getHeaders(), $response->getBody() ); } ); } /** * Create request for operation 'bufferDeleteByBufferId' * * @param string $buffer_id (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Psr7\Request */ protected function bufferDeleteByBufferIdRequest($buffer_id) { // verify the required parameter 'buffer_id' is set if ($buffer_id === null) { throw new \InvalidArgumentException( 'Missing the required parameter $buffer_id when calling bufferDeleteByBufferId' ); } $resourcePath = '/api/Buffer/{bufferId}'; $formParams = []; $queryParams = []; $headerParams = []; $httpBody = ''; $multipart = false; // path params if ($buffer_id!== null) { $resourcePath = str_replace( '{'. 'bufferId'. '}', ObjectSerializer::toPathValue($buffer_id), $resourcePath ); } // body params $_tempBody = null; if ($multipart) { $headers = $this->headerSelector->selectHeadersForMultipart( ['application/json', 'text/json', 'application/xml', 'text/xml'] ); } else { $headers = $this->headerSelector->selectHeaders( ['application/json', 'text/json', 'application/xml', 'text/xml'], [] ); } // for model (json/xml) if (isset($_tempBody)) { // $_tempBody is the method argument, if present $httpBody = $_tempBody; // \stdClass has no __toString(), so we should encode it manually if ($httpBody instanceof \stdClass && $headers['Content-Type'] === 'application/json') { $httpBody = \GuzzleHttp\json_encode($httpBody); } } elseif (count($formParams) > 0) { if ($multipart) { $multipartContents = []; foreach ($formParams as $formParamName => $formParamValue) { $multipartContents[] = [ 'name' => $formParamName, 'contents' => $formParamValue ]; } // for HTTP post (form) $httpBody = new MultipartStream($multipartContents); } elseif ($headers['Content-Type'] === 'application/json') { $httpBody = \GuzzleHttp\json_encode($formParams); } else { // for HTTP post (form) $httpBody = \GuzzleHttp\Psr7\build_query($formParams); } } // this endpoint requires API key authentication $apiKey = $this->config->getApiKeyWithPrefix('Authorization'); if ($apiKey!== null) { $headers['Authorization'] = $apiKey; } $defaultHeaders = []; if ($this->config->getUserAgent()) { $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); } $headers = array_merge( $defaultHeaders, $headerParams, $headers ); $query = \GuzzleHttp\Psr7\build_query($queryParams); return new Request( 'DELETE', $this->config->getHost(). $resourcePath. ($query? "?{$query}" : ''), $headers, $httpBody ); } /** * Operation bufferGetBufferElement * * This call returns the information about the buffer element * * @param string $id (required) * * @throws \Swagger\Client\ApiException on non-2xx response * @throws \InvalidArgumentException * @return \Swagger\Client\Model\BufferSimpleElement */ public function bufferGetBufferElement($id) { list($response) = $this->bufferGetBufferElementWithHttpInfo($id); return $response; } /** * Operation bufferGetBufferElementWithHttpInfo * * This call returns the information about the buffer element * * @param string $id (required) * * @throws \Swagger\Client\ApiException on non-2xx response * @throws \InvalidArgumentException * @return array of \Swagger\Client\Model\BufferSimpleElement, HTTP status code, HTTP response headers (array of strings) */ public function bufferGetBufferElementWithHttpInfo($id) { $returnType = '\Swagger\Client\Model\BufferSimpleElement'; $request = $this->bufferGetBufferElementRequest($id); try { $options = $this->createHttpClientOption(); try { $response = $this->client->send($request, $options); } catch (RequestException $e) { throw new ApiException( "[{$e->getCode()}] {$e->getMessage()}", $e->getCode(), $e->getResponse()? $e->getResponse()->getHeaders() : null, $e->getResponse()? $e->getResponse()->getBody()->getContents() : null ); } $statusCode = $response->getStatusCode(); if ($statusCode < 200 || $statusCode > 299) { throw new ApiException( sprintf( '[%d] Error connecting to the API (%s)', $statusCode, $request->getUri() ), $statusCode, $response->getHeaders(), $response->getBody() ); } $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer } else { $content = $responseBody->getContents(); if ($returnType!=='string') { $content = json_decode($content); } } return [ ObjectSerializer::deserialize($content, $returnType, []), $response->getStatusCode(), $response->getHeaders() ]; } catch (ApiException $e) { switch ($e->getCode()) { case 200: $data = ObjectSerializer::deserialize( $e->getResponseBody(), '\Swagger\Client\Model\BufferSimpleElement', $e->getResponseHeaders() ); $e->setResponseObject($data); break; } throw $e; } } /** * Operation bufferGetBufferElementAsync * * This call returns the information about the buffer element * * @param string $id (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Promise\PromiseInterface */ public function bufferGetBufferElementAsync($id) { return $this->bufferGetBufferElementAsyncWithHttpInfo($id) ->then( function ($response) { return $response[0]; } ); } /** * Operation bufferGetBufferElementAsyncWithHttpInfo * * This call returns the information about the buffer element * * @param string $id (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Promise\PromiseInterface */ public function bufferGetBufferElementAsyncWithHttpInfo($id) { $returnType = '\Swagger\Client\Model\BufferSimpleElement'; $request = $this->bufferGetBufferElementRequest($id); return $this->client ->sendAsync($request, $this->createHttpClientOption()) ->then( function ($response) use ($returnType) { $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer } else { $content = $responseBody->getContents(); if ($returnType!=='string') { $content = json_decode($content); } } return [ ObjectSerializer::deserialize($content, $returnType, []), $response->getStatusCode(), $response->getHeaders() ]; }, function ($exception) { $response = $exception->getResponse(); $statusCode = $response->getStatusCode(); throw new ApiException( sprintf( '[%d] Error connecting to the API (%s)', $statusCode, $exception->getRequest()->getUri() ), $statusCode, $response->getHeaders(), $response->getBody() ); } ); } /** * Create request for operation 'bufferGetBufferElement' * * @param string $id (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Psr7\Request */ protected function bufferGetBufferElementRequest($id) { // verify the required parameter 'id' is set if ($id === null) { throw new \InvalidArgumentException( 'Missing the required parameter $id when calling bufferGetBufferElement' ); } $resourcePath = '/api/Buffer/{id}'; $formParams = []; $queryParams = []; $headerParams = []; $httpBody = ''; $multipart = false; // path params if ($id!== null) { $resourcePath = str_replace( '{'. 'id'. '}', ObjectSerializer::toPathValue($id), $resourcePath ); } // body params $_tempBody = null; if ($multipart) { $headers = $this->headerSelector->selectHeadersForMultipart( ['application/json', 'text/json', 'application/xml', 'text/xml'] ); } else { $headers = $this->headerSelector->selectHeaders( ['application/json', 'text/json', 'application/xml', 'text/xml'], [] ); } // for model (json/xml) if (isset($_tempBody)) { // $_tempBody is the method argument, if present $httpBody = $_tempBody; // \stdClass has no __toString(), so we should encode it manually if ($httpBody instanceof \stdClass && $headers['Content-Type'] === 'application/json') { $httpBody = \GuzzleHttp\json_encode($httpBody); } } elseif (count($formParams) > 0) { if ($multipart) { $multipartContents = []; foreach ($formParams as $formParamName => $formParamValue) { $multipartContents[] = [ 'name' => $formParamName, 'contents' => $formParamValue ]; } // for HTTP post (form) $httpBody = new MultipartStream($multipartContents); } elseif ($headers['Content-Type'] === 'application/json') { $httpBody = \GuzzleHttp\json_encode($formParams); } else { // for HTTP post (form) $httpBody = \GuzzleHttp\Psr7\build_query($formParams); } } // this endpoint requires API key authentication $apiKey = $this->config->getApiKeyWithPrefix('Authorization'); if ($apiKey!== null) { $headers['Authorization'] = $apiKey; } $defaultHeaders = []; if ($this->config->getUserAgent()) { $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); } $headers = array_merge( $defaultHeaders, $headerParams, $headers ); $query = \GuzzleHttp\Psr7\build_query($queryParams); return new Request( 'GET', $this->config->getHost(). $resourcePath. ($query? "?{$query}" : ''), $headers, $httpBody ); } /** * Operation bufferGetFile * * This call returns the file of the buffer element * * @param string $id (required) * * @throws \Swagger\Client\ApiException on non-2xx response * @throws \InvalidArgumentException * @return \SplFileObject */ public function bufferGetFile($id) { list($response) = $this->bufferGetFileWithHttpInfo($id); return $response; } /** * Operation bufferGetFileWithHttpInfo * * This call returns the file of the buffer element * * @param string $id (required) * * @throws \Swagger\Client\ApiException on non-2xx response * @throws \InvalidArgumentException * @return array of \SplFileObject, HTTP status code, HTTP response headers (array of strings) */ public function bufferGetFileWithHttpInfo($id) { $returnType = '\SplFileObject'; $request = $this->bufferGetFileRequest($id); try { $options = $this->createHttpClientOption(); try { $response = $this->client->send($request, $options); } catch (RequestException $e) { throw new ApiException( "[{$e->getCode()}] {$e->getMessage()}", $e->getCode(), $e->getResponse()? $e->getResponse()->getHeaders() : null, $e->getResponse()? $e->getResponse()->getBody()->getContents() : null ); } $statusCode = $response->getStatusCode(); if ($statusCode < 200 || $statusCode > 299) { throw new ApiException( sprintf( '[%d] Error connecting to the API (%s)', $statusCode, $request->getUri() ), $statusCode, $response->getHeaders(), $response->getBody() ); } $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer } else { $content = $responseBody->getContents(); if ($returnType!=='string') { $content = json_decode($content); } } return [ ObjectSerializer::deserialize($content, $returnType, []), $response->getStatusCode(), $response->getHeaders() ]; } catch (ApiException $e) { switch ($e->getCode()) { case 200: $data = ObjectSerializer::deserialize( $e->getResponseBody(), '\SplFileObject', $e->getResponseHeaders() ); $e->setResponseObject($data); break; } throw $e; } } /** * Operation bufferGetFileAsync * * This call returns the file of the buffer element * * @param string $id (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Promise\PromiseInterface */ public function bufferGetFileAsync($id) { return $this->bufferGetFileAsyncWithHttpInfo($id) ->then( function ($response) { return $response[0]; } ); } /** * Operation bufferGetFileAsyncWithHttpInfo * * This call returns the file of the buffer element * * @param string $id (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Promise\PromiseInterface */ public function bufferGetFileAsyncWithHttpInfo($id) { $returnType = '\SplFileObject'; $request = $this->bufferGetFileRequest($id); return $this->client ->sendAsync($request, $this->createHttpClientOption()) ->then( function ($response) use ($returnType) { $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer } else { $content = $responseBody->getContents(); if ($returnType!=='string') { $content = json_decode($content); } } return [ ObjectSerializer::deserialize($content, $returnType, []), $response->getStatusCode(), $response->getHeaders() ]; }, function ($exception) { $response = $exception->getResponse(); $statusCode = $response->getStatusCode(); throw new ApiException( sprintf( '[%d] Error connecting to the API (%s)', $statusCode, $exception->getRequest()->getUri() ), $statusCode, $response->getHeaders(), $response->getBody() ); } ); } /** * Create request for operation 'bufferGetFile' * * @param string $id (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Psr7\Request */ protected function bufferGetFileRequest($id) { // verify the required parameter 'id' is set if ($id === null) { throw new \InvalidArgumentException( 'Missing the required parameter $id when calling bufferGetFile' ); } $resourcePath = '/api/Buffer/file/{id}'; $formParams = []; $queryParams = []; $headerParams = []; $httpBody = ''; $multipart = false; // path params if ($id!== null) { $resourcePath = str_replace( '{'. 'id'. '}', ObjectSerializer::toPathValue($id), $resourcePath ); } // body params $_tempBody = null; if ($multipart) { $headers = $this->headerSelector->selectHeadersForMultipart( ['application/octet-stream'] ); } else { $headers = $this->headerSelector->selectHeaders( ['application/octet-stream'], [] ); } // for model (json/xml) if (isset($_tempBody)) { // $_tempBody is the method argument, if present $httpBody = $_tempBody; // \stdClass has no __toString(), so we should encode it manually if ($httpBody instanceof \stdClass && $headers['Content-Type'] === 'application/json') { $httpBody = \GuzzleHttp\json_encode($httpBody); } } elseif (count($formParams) > 0) { if ($multipart) { $multipartContents = []; foreach ($formParams as $formParamName => $formParamValue) { $multipartContents[] = [ 'name' => $formParamName, 'contents' => $formParamValue ]; } // for HTTP post (form) $httpBody = new MultipartStream($multipartContents); } elseif ($headers['Content-Type'] === 'application/json') { $httpBody = \GuzzleHttp\json_encode($formParams); } else { // for HTTP post (form) $httpBody = \GuzzleHttp\Psr7\build_query($formParams); } } // this endpoint requires API key authentication $apiKey = $this->config->getApiKeyWithPrefix('Authorization'); if ($apiKey!== null) { $headers['Authorization'] = $apiKey; } $defaultHeaders = []; if ($this->config->getUserAgent()) { $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); } $headers = array_merge( $defaultHeaders, $headerParams, $headers ); $query = \GuzzleHttp\Psr7\build_query($queryParams); return new Request( 'GET', $this->config->getHost(). $resourcePath. ($query? "?{$query}" : ''), $headers, $httpBody ); } /** * Operation bufferGetForMonitoredFolder * * This call returns the list of the document in the buffer for the monitored folder * * * @throws \Swagger\Client\ApiException on non-2xx response * @throws \InvalidArgumentException * @return \Swagger\Client\Model\BufferSimpleElement[] */ public function bufferGetForMonitoredFolder() { list($response) = $this->bufferGetForMonitoredFolderWithHttpInfo(); return $response; } /** * Operation bufferGetForMonitoredFolderWithHttpInfo * * This call returns the list of the document in the buffer for the monitored folder * * * @throws \Swagger\Client\ApiException on non-2xx response * @throws \InvalidArgumentException * @return array of \Swagger\Client\Model\BufferSimpleElement[], HTTP status code, HTTP response headers (array of strings) */ public function bufferGetForMonitoredFolderWithHttpInfo() { $returnType = '\Swagger\Client\Model\BufferSimpleElement[]'; $request = $this->bufferGetForMonitoredFolderRequest(); try { $options = $this->createHttpClientOption(); try { $response = $this->client->send($request, $options); } catch (RequestException $e) { throw new ApiException( "[{$e->getCode()}] {$e->getMessage()}", $e->getCode(), $e->getResponse()? $e->getResponse()->getHeaders() : null, $e->getResponse()? $e->getResponse()->getBody()->getContents() : null ); } $statusCode = $response->getStatusCode(); if ($statusCode < 200 || $statusCode > 299) { throw new ApiException( sprintf( '[%d] Error connecting to the API (%s)', $statusCode, $request->getUri() ), $statusCode, $response->getHeaders(), $response->getBody() ); } $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer } else { $content = $responseBody->getContents(); if ($returnType!=='string') { $content = json_decode($content); } } return [ ObjectSerializer::deserialize($content, $returnType, []), $response->getStatusCode(), $response->getHeaders() ]; } catch (ApiException $e) { switch ($e->getCode()) { case 200: $data = ObjectSerializer::deserialize( $e->getResponseBody(), '\Swagger\Client\Model\BufferSimpleElement[]', $e->getResponseHeaders() ); $e->setResponseObject($data); break; } throw $e; } } /** * Operation bufferGetForMonitoredFolderAsync * * This call returns the list of the document in the buffer for the monitored folder * * * @throws \InvalidArgumentException * @return \GuzzleHttp\Promise\PromiseInterface */ public function bufferGetForMonitoredFolderAsync() { return $this->bufferGetForMonitoredFolderAsyncWithHttpInfo() ->then( function ($response) { return $response[0]; } ); } /** * Operation bufferGetForMonitoredFolderAsyncWithHttpInfo * * This call returns the list of the document in the buffer for the monitored folder * * * @throws \InvalidArgumentException * @return \GuzzleHttp\Promise\PromiseInterface */ public function bufferGetForMonitoredFolderAsyncWithHttpInfo() { $returnType = '\Swagger\Client\Model\BufferSimpleElement[]'; $request = $this->bufferGetForMonitoredFolderRequest(); return $this->client ->sendAsync($request, $this->createHttpClientOption()) ->then( function ($response) use ($returnType) { $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer } else { $content = $responseBody->getContents(); if ($returnType!=='string') { $content = json_decode($content); } } return [ ObjectSerializer::deserialize($content, $returnType, []), $response->getStatusCode(), $response->getHeaders() ]; }, function ($exception) { $response = $exception->getResponse(); $statusCode = $response->getStatusCode(); throw new ApiException( sprintf( '[%d] Error connecting to the API (%s)', $statusCode, $exception->getRequest()->getUri() ), $statusCode, $response->getHeaders(), $response->getBody() ); } ); } /** * Create request for operation 'bufferGetForMonitoredFolder' * * * @throws \InvalidArgumentException * @return \GuzzleHttp\Psr7\Request */ protected function bufferGetForMonitoredFolderRequest() { $resourcePath = '/api/Buffer/ForMonitoredFolder'; $formParams = []; $queryParams = []; $headerParams = []; $httpBody = ''; $multipart = false; // body params $_tempBody = null; if ($multipart) { $headers = $this->headerSelector->selectHeadersForMultipart( ['application/json', 'text/json', 'application/xml', 'text/xml'] ); } else { $headers = $this->headerSelector->selectHeaders( ['application/json', 'text/json', 'application/xml', 'text/xml'], [] ); } // for model (json/xml) if (isset($_tempBody)) { // $_tempBody is the method argument, if present $httpBody = $_tempBody; // \stdClass has no __toString(), so we should encode it manually if ($httpBody instanceof \stdClass && $headers['Content-Type'] === 'application/json') { $httpBody = \GuzzleHttp\json_encode($httpBody); } } elseif (count($formParams) > 0) { if ($multipart) { $multipartContents = []; foreach ($formParams as $formParamName => $formParamValue) { $multipartContents[] = [ 'name' => $formParamName, 'contents' => $formParamValue ]; } // for HTTP post (form) $httpBody = new MultipartStream($multipartContents); } elseif ($headers['Content-Type'] === 'application/json') { $httpBody = \GuzzleHttp\json_encode($formParams); } else { // for HTTP post (form) $httpBody = \GuzzleHttp\Psr7\build_query($formParams); } } // this endpoint requires API key authentication $apiKey = $this->config->getApiKeyWithPrefix('Authorization'); if ($apiKey!== null) { $headers['Authorization'] = $apiKey; } $defaultHeaders = []; if ($this->config->getUserAgent()) { $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); } $headers = array_merge( $defaultHeaders, $headerParams, $headers ); $query = \GuzzleHttp\Psr7\build_query($queryParams); return new Request( 'GET', $this->config->getHost(). $resourcePath. ($query? "?{$query}" : ''), $headers, $httpBody ); } /** * Operation bufferInsert * * This call allows to add a file to the buffer * * @param \SplFileObject $file The file (required) * * @throws \Swagger\Client\ApiException on non-2xx response * @throws \InvalidArgumentException * @return string[] */ public function bufferInsert($file) { list($response) = $this->bufferInsertWithHttpInfo($file); return $response; } /** * Operation bufferInsertWithHttpInfo * * This call allows to add a file to the buffer * * @param \SplFileObject $file The file (required) * * @throws \Swagger\Client\ApiException on non-2xx response * @throws \InvalidArgumentException * @return array of string[], HTTP status code, HTTP response headers (array of strings) */ public function bufferInsertWithHttpInfo($file) { $returnType ='string[]'; $request = $this->bufferInsertRequest($file); try { $options = $this->createHttpClientOption(); try { $response = $this->client->send($request, $options); } catch (RequestException $e) { throw new ApiException( "[{$e->getCode()}] {$e->getMessage()}", $e->getCode(), $e->getResponse()? $e->getResponse()->getHeaders() : null, $e->getResponse()? $e->getResponse()->getBody()->getContents() : null ); } $statusCode = $response->getStatusCode(); if ($statusCode < 200 || $statusCode > 299) { throw new ApiException( sprintf( '[%d] Error connecting to the API (%s)', $statusCode, $request->getUri() ), $statusCode, $response->getHeaders(), $response->getBody() ); } $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer } else { $content = $responseBody->getContents(); if ($returnType!=='string') { $content = json_decode($content); } } return [ ObjectSerializer::deserialize($content, $returnType, []), $response->getStatusCode(), $response->getHeaders() ]; } catch (ApiException $e) { switch ($e->getCode()) { case 200: $data = ObjectSerializer::deserialize( $e->getResponseBody(), 'string[]', $e->getResponseHeaders() ); $e->setResponseObject($data); break; } throw $e; } } /** * Operation bufferInsertAsync * * This call allows to add a file to the buffer * * @param \SplFileObject $file The file (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Promise\PromiseInterface */ public function bufferInsertAsync($file) { return $this->bufferInsertAsyncWithHttpInfo($file) ->then( function ($response) { return $response[0]; } ); } /** * Operation bufferInsertAsyncWithHttpInfo * * This call allows to add a file to the buffer * * @param \SplFileObject $file The file (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Promise\PromiseInterface */ public function bufferInsertAsyncWithHttpInfo($file) { $returnType ='string[]'; $request = $this->bufferInsertRequest($file); return $this->client ->sendAsync($request, $this->createHttpClientOption()) ->then( function ($response) use ($returnType) { $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer } else { $content = $responseBody->getContents(); if ($returnType!=='string') { $content = json_decode($content); } } return [ ObjectSerializer::deserialize($content, $returnType, []), $response->getStatusCode(), $response->getHeaders() ]; }, function ($exception) { $response = $exception->getResponse(); $statusCode = $response->getStatusCode(); throw new ApiException( sprintf( '[%d] Error connecting to the API (%s)', $statusCode, $exception->getRequest()->getUri() ), $statusCode, $response->getHeaders(), $response->getBody() ); } ); } /** * Create request for operation 'bufferInsert' * * @param \SplFileObject $file The file (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Psr7\Request */ protected function bufferInsertRequest($file) { // verify the required parameter 'file' is set if ($file === null) { throw new \InvalidArgumentException( 'Missing the required parameter $file when calling bufferInsert' ); } $resourcePath = '/api/Buffer/insert'; $formParams = []; $queryParams = []; $headerParams = []; $httpBody = ''; $multipart = false; // form params if ($file!== null) { $multipart = true; $formParams['file'] = \GuzzleHttp\Psr7\try_fopen(ObjectSerializer::toFormValue($file), 'rb'); } // body params $_tempBody = null; if ($multipart) { $headers = $this->headerSelector->selectHeadersForMultipart( ['application/json', 'text/json', 'application/xml', 'text/xml'] ); } else { $headers = $this->headerSelector->selectHeaders( ['application/json', 'text/json', 'application/xml', 'text/xml'], ['multipart/form-data'] ); } // for model (json/xml) if (isset($_tempBody)) { // $_tempBody is the method argument, if present $httpBody = $_tempBody; // \stdClass has no __toString(), so we should encode it manually if ($httpBody instanceof \stdClass && $headers['Content-Type'] === 'application/json') { $httpBody = \GuzzleHttp\json_encode($httpBody); } } elseif (count($formParams) > 0) { if ($multipart) { $multipartContents = []; foreach ($formParams as $formParamName => $formParamValue) { $multipartContents[] = [ 'name' => $formParamName, 'contents' => $formParamValue ]; } // for HTTP post (form) $httpBody = new MultipartStream($multipartContents); } elseif ($headers['Content-Type'] === 'application/json') { $httpBody = \GuzzleHttp\json_encode($formParams); } else { // for HTTP post (form) $httpBody = \GuzzleHttp\Psr7\build_query($formParams); } } // this endpoint requires API key authentication $apiKey = $this->config->getApiKeyWithPrefix('Authorization'); if ($apiKey!== null) { $headers['Authorization'] = $apiKey; } $defaultHeaders = []; if ($this->config->getUserAgent()) { $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); } $headers = array_merge( $defaultHeaders, $headerParams, $headers ); $query = \GuzzleHttp\Psr7\build_query($queryParams); return new Request( 'POST', $this->config->getHost(). $resourcePath. ($query? "?{$query}" : ''), $headers, $httpBody ); } /** * Operation bufferInsertAdvanced * * This call allows to add a file to the buffer * * @param int $element_type_enum Possible values: 0: DmBuffer 1: NextArchive 2: MonitoredFolder 3: ProcessDocThumbnail 4: CloneProfile 5: ReportExecuted (required) * @param string $description Description (required) * @param \SplFileObject $file The file (required) * * @throws \Swagger\Client\ApiException on non-2xx response * @throws \InvalidArgumentException * @return string[] */ public function bufferInsertAdvanced($element_type_enum, $description, $file) { list($response) = $this->bufferInsertAdvancedWithHttpInfo($element_type_enum, $description, $file); return $response; } /** * Operation bufferInsertAdvancedWithHttpInfo * * This call allows to add a file to the buffer * * @param int $element_type_enum Possible values: 0: DmBuffer 1: NextArchive 2: MonitoredFolder 3: ProcessDocThumbnail 4: CloneProfile 5: ReportExecuted (required) * @param string $description Description (required) * @param \SplFileObject $file The file (required) * * @throws \Swagger\Client\ApiException on non-2xx response * @throws \InvalidArgumentException * @return array of string[], HTTP status code, HTTP response headers (array of strings) */ public function bufferInsertAdvancedWithHttpInfo($element_type_enum, $description, $file) { $returnType ='string[]'; $request = $this->bufferInsertAdvancedRequest($element_type_enum, $description, $file); try { $options = $this->createHttpClientOption(); try { $response = $this->client->send($request, $options); } catch (RequestException $e) { throw new ApiException( "[{$e->getCode()}] {$e->getMessage()}", $e->getCode(), $e->getResponse()? $e->getResponse()->getHeaders() : null, $e->getResponse()? $e->getResponse()->getBody()->getContents() : null ); } $statusCode = $response->getStatusCode(); if ($statusCode < 200 || $statusCode > 299) { throw new ApiException( sprintf( '[%d] Error connecting to the API (%s)', $statusCode, $request->getUri() ), $statusCode, $response->getHeaders(), $response->getBody() ); } $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer } else { $content = $responseBody->getContents(); if ($returnType!=='string') { $content = json_decode($content); } } return [ ObjectSerializer::deserialize($content, $returnType, []), $response->getStatusCode(), $response->getHeaders() ]; } catch (ApiException $e) { switch ($e->getCode()) { case 200: $data = ObjectSerializer::deserialize( $e->getResponseBody(), 'string[]', $e->getResponseHeaders() ); $e->setResponseObject($data); break; } throw $e; } } /** * Operation bufferInsertAdvancedAsync * * This call allows to add a file to the buffer * * @param int $element_type_enum Possible values: 0: DmBuffer 1: NextArchive 2: MonitoredFolder 3: ProcessDocThumbnail 4: CloneProfile 5: ReportExecuted (required) * @param string $description Description (required) * @param \SplFileObject $file The file (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Promise\PromiseInterface */ public function bufferInsertAdvancedAsync($element_type_enum, $description, $file) { return $this->bufferInsertAdvancedAsyncWithHttpInfo($element_type_enum, $description, $file) ->then( function ($response) { return $response[0]; } ); } /** * Operation bufferInsertAdvancedAsyncWithHttpInfo * * This call allows to add a file to the buffer * * @param int $element_type_enum Possible values: 0: DmBuffer 1: NextArchive 2: MonitoredFolder 3: ProcessDocThumbnail 4: CloneProfile 5: ReportExecuted (required) * @param string $description Description (required) * @param \SplFileObject $file The file (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Promise\PromiseInterface */ public function bufferInsertAdvancedAsyncWithHttpInfo($element_type_enum, $description, $file) { $returnType ='string[]'; $request = $this->bufferInsertAdvancedRequest($element_type_enum, $description, $file); return $this->client ->sendAsync($request, $this->createHttpClientOption()) ->then( function ($response) use ($returnType) { $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer } else { $content = $responseBody->getContents(); if ($returnType!=='string') { $content = json_decode($content); } } return [ ObjectSerializer::deserialize($content, $returnType, []), $response->getStatusCode(), $response->getHeaders() ]; }, function ($exception) { $response = $exception->getResponse(); $statusCode = $response->getStatusCode(); throw new ApiException( sprintf( '[%d] Error connecting to the API (%s)', $statusCode, $exception->getRequest()->getUri() ), $statusCode, $response->getHeaders(), $response->getBody() ); } ); } /** * Create request for operation 'bufferInsertAdvanced' * * @param int $element_type_enum Possible values: 0: DmBuffer 1: NextArchive 2: MonitoredFolder 3: ProcessDocThumbnail 4: CloneProfile 5: ReportExecuted (required) * @param string $description Description (required) * @param \SplFileObject $file The file (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Psr7\Request */ protected function bufferInsertAdvancedRequest($element_type_enum, $description, $file) { // verify the required parameter 'element_type_enum' is set if ($element_type_enum === null) { throw new \InvalidArgumentException( 'Missing the required parameter $element_type_enum when calling bufferInsertAdvanced' ); } // verify the required parameter 'description' is set if ($description === null) { throw new \InvalidArgumentException( 'Missing the required parameter $description when calling bufferInsertAdvanced' ); } // verify the required parameter 'file' is set if ($file === null) { throw new \InvalidArgumentException( 'Missing the required parameter $file when calling bufferInsertAdvanced' ); } $resourcePath = '/api/Buffer/insert/{elementTypeEnum}/{description}'; $formParams = []; $queryParams = []; $headerParams = []; $httpBody = ''; $multipart = false; // path params if ($element_type_enum!== null) { $resourcePath = str_replace( '{'. 'elementTypeEnum'. '}', ObjectSerializer::toPathValue($element_type_enum), $resourcePath ); } // path params if ($description!== null) { $resourcePath = str_replace( '{'. 'description'. '}', ObjectSerializer::toPathValue($description), $resourcePath ); } // form params if ($file!== null) { $multipart = true; $formParams['file'] = \GuzzleHttp\Psr7\try_fopen(ObjectSerializer::toFormValue($file), 'rb'); } // body params $_tempBody = null; if ($multipart) { $headers = $this->headerSelector->selectHeadersForMultipart( ['application/json', 'text/json', 'application/xml', 'text/xml'] ); } else { $headers = $this->headerSelector->selectHeaders( ['application/json', 'text/json', 'application/xml', 'text/xml'], ['multipart/form-data'] ); } // for model (json/xml) if (isset($_tempBody)) { // $_tempBody is the method argument, if present $httpBody = $_tempBody; // \stdClass has no __toString(), so we should encode it manually if ($httpBody instanceof \stdClass && $headers['Content-Type'] === 'application/json') { $httpBody = \GuzzleHttp\json_encode($httpBody); } } elseif (count($formParams) > 0) { if ($multipart) { $multipartContents = []; foreach ($formParams as $formParamName => $formParamValue) { $multipartContents[] = [ 'name' => $formParamName, 'contents' => $formParamValue ]; } // for HTTP post (form) $httpBody = new MultipartStream($multipartContents); } elseif ($headers['Content-Type'] === 'application/json') { $httpBody = \GuzzleHttp\json_encode($formParams); } else { // for HTTP post (form) $httpBody = \GuzzleHttp\Psr7\build_query($formParams); } } // this endpoint requires API key authentication $apiKey = $this->config->getApiKeyWithPrefix('Authorization'); if ($apiKey!== null) { $headers['Authorization'] = $apiKey; } $defaultHeaders = []; if ($this->config->getUserAgent()) { $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); } $headers = array_merge( $defaultHeaders, $headerParams, $headers ); $query = \GuzzleHttp\Psr7\build_query($queryParams); return new Request( 'POST', $this->config->getHost(). $resourcePath. ($query? "?{$query}" : ''), $headers, $httpBody ); } /** * Operation bufferInsertAdvancedForMonitoredFolder * * This call allows to add a file to the buffer * * @param int $element_type_enum Possible values: 0: DmBuffer 1: NextArchive 2: MonitoredFolder 3: ProcessDocThumbnail 4: CloneProfile 5: ReportExecuted (required) * @param string $monitored_folder_id If the buffer is related to a monitored folder (required) * @param string $description Description (required) * @param \SplFileObject $file The file (required) * * @throws \Swagger\Client\ApiException on non-2xx response * @throws \InvalidArgumentException * @return string[] */ public function bufferInsertAdvancedForMonitoredFolder($element_type_enum, $monitored_folder_id, $description, $file) { list($response) = $this->bufferInsertAdvancedForMonitoredFolderWithHttpInfo($element_type_enum, $monitored_folder_id, $description, $file); return $response; } /** * Operation bufferInsertAdvancedForMonitoredFolderWithHttpInfo * * This call allows to add a file to the buffer * * @param int $element_type_enum Possible values: 0: DmBuffer 1: NextArchive 2: MonitoredFolder 3: ProcessDocThumbnail 4: CloneProfile 5: ReportExecuted (required) * @param string $monitored_folder_id If the buffer is related to a monitored folder (required) * @param string $description Description (required) * @param \SplFileObject $file The file (required) * * @throws \Swagger\Client\ApiException on non-2xx response * @throws \InvalidArgumentException * @return array of string[], HTTP status code, HTTP response headers (array of strings) */ public function bufferInsertAdvancedForMonitoredFolderWithHttpInfo($element_type_enum, $monitored_folder_id, $description, $file) { $returnType ='string[]'; $request = $this->bufferInsertAdvancedForMonitoredFolderRequest($element_type_enum, $monitored_folder_id, $description, $file); try { $options = $this->createHttpClientOption(); try { $response = $this->client->send($request, $options); } catch (RequestException $e) { throw new ApiException( "[{$e->getCode()}] {$e->getMessage()}", $e->getCode(), $e->getResponse()? $e->getResponse()->getHeaders() : null, $e->getResponse()? $e->getResponse()->getBody()->getContents() : null ); } $statusCode = $response->getStatusCode(); if ($statusCode < 200 || $statusCode > 299) { throw new ApiException( sprintf( '[%d] Error connecting to the API (%s)', $statusCode, $request->getUri() ), $statusCode, $response->getHeaders(), $response->getBody() ); } $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer } else { $content = $responseBody->getContents(); if ($returnType!=='string') { $content = json_decode($content); } } return [ ObjectSerializer::deserialize($content, $returnType, []), $response->getStatusCode(), $response->getHeaders() ]; } catch (ApiException $e) { switch ($e->getCode()) { case 200: $data = ObjectSerializer::deserialize( $e->getResponseBody(), 'string[]', $e->getResponseHeaders() ); $e->setResponseObject($data); break; } throw $e; } } /** * Operation bufferInsertAdvancedForMonitoredFolderAsync * * This call allows to add a file to the buffer * * @param int $element_type_enum Possible values: 0: DmBuffer 1: NextArchive 2: MonitoredFolder 3: ProcessDocThumbnail 4: CloneProfile 5: ReportExecuted (required) * @param string $monitored_folder_id If the buffer is related to a monitored folder (required) * @param string $description Description (required) * @param \SplFileObject $file The file (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Promise\PromiseInterface */ public function bufferInsertAdvancedForMonitoredFolderAsync($element_type_enum, $monitored_folder_id, $description, $file) { return $this->bufferInsertAdvancedForMonitoredFolderAsyncWithHttpInfo($element_type_enum, $monitored_folder_id, $description, $file) ->then( function ($response) { return $response[0]; } ); } /** * Operation bufferInsertAdvancedForMonitoredFolderAsyncWithHttpInfo * * This call allows to add a file to the buffer * * @param int $element_type_enum Possible values: 0: DmBuffer 1: NextArchive 2: MonitoredFolder 3: ProcessDocThumbnail 4: CloneProfile 5: ReportExecuted (required) * @param string $monitored_folder_id If the buffer is related to a monitored folder (required) * @param string $description Description (required) * @param \SplFileObject $file The file (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Promise\PromiseInterface */ public function bufferInsertAdvancedForMonitoredFolderAsyncWithHttpInfo($element_type_enum, $monitored_folder_id, $description, $file) { $returnType ='string[]'; $request = $this->bufferInsertAdvancedForMonitoredFolderRequest($element_type_enum, $monitored_folder_id, $description, $file); return $this->client ->sendAsync($request, $this->createHttpClientOption()) ->then( function ($response) use ($returnType) { $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer } else { $content = $responseBody->getContents(); if ($returnType!=='string') { $content = json_decode($content); } } return [ ObjectSerializer::deserialize($content, $returnType, []), $response->getStatusCode(), $response->getHeaders() ]; }, function ($exception) { $response = $exception->getResponse(); $statusCode = $response->getStatusCode(); throw new ApiException( sprintf( '[%d] Error connecting to the API (%s)', $statusCode, $exception->getRequest()->getUri() ), $statusCode, $response->getHeaders(), $response->getBody() ); } ); } /** * Create request for operation 'bufferInsertAdvancedForMonitoredFolder' * * @param int $element_type_enum Possible values: 0: DmBuffer 1: NextArchive 2: MonitoredFolder 3: ProcessDocThumbnail 4: CloneProfile 5: ReportExecuted (required) * @param string $monitored_folder_id If the buffer is related to a monitored folder (required) * @param string $description Description (required) * @param \SplFileObject $file The file (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Psr7\Request */ protected function bufferInsertAdvancedForMonitoredFolderRequest($element_type_enum, $monitored_folder_id, $description, $file) { // verify the required parameter 'element_type_enum' is set if ($element_type_enum === null) { throw new \InvalidArgumentException( 'Missing the required parameter $element_type_enum when calling bufferInsertAdvancedForMonitoredFolder' ); } // verify the required parameter'monitored_folder_id' is set if ($monitored_folder_id === null) { throw new \InvalidArgumentException( 'Missing the required parameter $monitored_folder_id when calling bufferInsertAdvancedForMonitoredFolder' ); } // verify the required parameter 'description' is set if ($description === null) { throw new \InvalidArgumentException( 'Missing the required parameter $description when calling bufferInsertAdvancedForMonitoredFolder' ); } // verify the required parameter 'file' is set if ($file === null) { throw new \InvalidArgumentException( 'Missing the required parameter $file when calling bufferInsertAdvancedForMonitoredFolder' ); } $resourcePath = '/api/Buffer/insertForMonitoredFolder/{elementTypeEnum}/{monitoredFolderId}/{description}'; $formParams = []; $queryParams = []; $headerParams = []; $httpBody = ''; $multipart = false; // path params if ($element_type_enum!== null) { $resourcePath = str_replace( '{'. 'elementTypeEnum'. '}', ObjectSerializer::toPathValue($element_type_enum), $resourcePath ); } // path params if ($monitored_folder_id!== null) { $resourcePath = str_replace( '{'.'monitoredFolderId'. '}', ObjectSerializer::toPathValue($monitored_folder_id), $resourcePath ); } // path params if ($description!== null) { $resourcePath = str_replace( '{'. 'description'. '}', ObjectSerializer::toPathValue($description), $resourcePath ); } // form params if ($file!== null) { $multipart = true; $formParams['file'] = \GuzzleHttp\Psr7\try_fopen(ObjectSerializer::toFormValue($file), 'rb'); } // body params $_tempBody = null; if ($multipart) { $headers = $this->headerSelector->selectHeadersForMultipart( ['application/json', 'text/json', 'application/xml', 'text/xml'] ); } else { $headers = $this->headerSelector->selectHeaders( ['application/json', 'text/json', 'application/xml', 'text/xml'], ['multipart/form-data'] ); } // for model (json/xml) if (isset($_tempBody)) { // $_tempBody is the method argument, if present $httpBody = $_tempBody; // \stdClass has no __toString(), so we should encode it manually if ($httpBody instanceof \stdClass && $headers['Content-Type'] === 'application/json') { $httpBody = \GuzzleHttp\json_encode($httpBody); } } elseif (count($formParams) > 0) { if ($multipart) { $multipartContents = []; foreach ($formParams as $formParamName => $formParamValue) { $multipartContents[] = [ 'name' => $formParamName, 'contents' => $formParamValue ]; } // for HTTP post (form) $httpBody = new MultipartStream($multipartContents); } elseif ($headers['Content-Type'] === 'application/json') { $httpBody = \GuzzleHttp\json_encode($formParams); } else { // for HTTP post (form) $httpBody = \GuzzleHttp\Psr7\build_query($formParams); } } // this endpoint requires API key authentication $apiKey = $this->config->getApiKeyWithPrefix('Authorization'); if ($apiKey!== null) { $headers['Authorization'] = $apiKey; } $defaultHeaders = []; if ($this->config->getUserAgent()) { $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); } $headers = array_merge( $defaultHeaders, $headerParams, $headers ); $query = \GuzzleHttp\Psr7\build_query($queryParams); return new Request( 'POST', $this->config->getHost(). $resourcePath. ($query? "?{$query}" : ''), $headers, $httpBody ); } /** * Create http client option * * @throws \RuntimeException on file opening failure * @return array of http client options */ protected function createHttpClientOption() { $options = []; if ($this->config->getDebug()) { $options[RequestOptions::DEBUG] = fopen($this->config->getDebugFile(), 'a'); if (!$options[RequestOptions::DEBUG]) { throw new \RuntimeException('Failed to open the debug file: '. $this->config->getDebugFile()); } } return $options; } } ======================= File: lib/Api/FoldersApi.php ======================= <?php /** * FoldersApi * PHP version 5 * * @category Class * @package Swagger\Client * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen */ /** * Abletech.Arxivar.Server.WebApi.Services * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * OpenAPI spec version: v1 * * Generated by: https://github.com/swagger-api/swagger-codegen.git * Swagger Codegen version: 2.3.1 */ /** * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen * Do not edit the class manually. */ namespace Swagger\Client\Api; use GuzzleHttp\Client; use GuzzleHttp\ClientInterface; use GuzzleHttp\Exception\RequestException; use GuzzleHttp\Psr7\MultipartStream; use GuzzleHttp\Psr7\Request; use GuzzleHttp\RequestOptions; use Swagger\Client\ApiException; use Swagger\Client\Configuration; use Swagger\Client\HeaderSelector; use Swagger\Client\ObjectSerializer; /** * FoldersApi Class Doc Comment * * @category Class * @package Swagger\Client * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen */ class FoldersApi { /** * @var ClientInterface */ protected $client; /** * @var Configuration */ protected $config; /** * @param ClientInterface $client * @param Configuration $config * @param HeaderSelector $selector */ public function __construct( ClientInterface $client = null, Configuration $config = null, HeaderSelector $selector = null ) { $this->client = $client?: new Client(); $this->config = $config?: new Configuration(); $this->headerSelector = $selector?: new HeaderSelector(); } /** * @return Configuration */ public function getConfig() { return $this->config; } /** * Operation foldersAutoinsertInFolderByDocnumber * * This method recalculate folder for profile * * @param int $docnumber The identifier of the profile (required) * * @throws \Swagger\Client\ApiException on non-2xx response * @throws \InvalidArgumentException * @return void */ public function foldersAutoinsertInFolderByDocnumber($docnumber) { $this->foldersAutoinsertInFolderByDocnumberWithHttpInfo($docnumber); } /** * Operation foldersAutoinsertInFolderByDocnumberWithHttpInfo * * This method recalculate folder for profile * * @param int $docnumber The identifier of the profile (required) * * @throws \Swagger\Client\ApiException on non-2xx response * @throws \InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ public function foldersAutoinsertInFolderByDocnumberWithHttpInfo($docnumber) { $returnType = ''; $request = $this->foldersAutoinsertInFolderByDocnumberRequest($docnumber); try { $options = $this->createHttpClientOption(); try { $response = $this->client->send($request, $options); } catch (RequestException $e) { throw new ApiException( "[{$e->getCode()}] {$e->getMessage()}", $e->getCode(), $e->getResponse()? $e->getResponse()->getHeaders() : null, $e->getResponse()? $e->getResponse()->getBody()->getContents() : null ); } $statusCode = $response->getStatusCode(); if ($statusCode < 200 || $statusCode > 299) { throw new ApiException( sprintf( '[%d] Error connecting to the API (%s)', $statusCode, $request->getUri() ), $statusCode, $response->getHeaders(), $response->getBody() ); } return [null, $statusCode, $response->getHeaders()]; } catch (ApiException $e) { switch ($e->getCode()) { } throw $e; } } /** * Operation foldersAutoinsertInFolderByDocnumberAsync * * This method recalculate folder for profile * * @param int $docnumber The identifier of the profile (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Promise\PromiseInterface */ public function foldersAutoinsertInFolderByDocnumberAsync($docnumber) { return $this->foldersAutoinsertInFolderByDocnumberAsyncWithHttpInfo($docnumber) ->then( function ($response) { return $response[0]; } ); } /** * Operation foldersAutoinsertInFolderByDocnumberAsyncWithHttpInfo * * This method recalculate folder for profile * * @param int $docnumber The identifier of the profile (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Promise\PromiseInterface */ public function foldersAutoinsertInFolderByDocnumberAsyncWithHttpInfo($docnumber) { $returnType = ''; $request = $this->foldersAutoinsertInFolderByDocnumberRequest($docnumber); return $this->client ->sendAsync($request, $this->createHttpClientOption()) ->then( function ($response) use ($returnType) { return [null, $response->getStatusCode(), $response->getHeaders()]; }, function ($exception) { $response = $exception->getResponse(); $statusCode = $response->getStatusCode(); throw new ApiException( sprintf( '[%d] Error connecting to the API (%s)', $statusCode, $exception->getRequest()->getUri() ), $statusCode, $response->getHeaders(), $response->getBody() ); } ); } /** * Create request for operation 'foldersAutoinsertInFolderByDocnumber' * * @param int $docnumber The identifier of the profile (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Psr7\Request */ protected function foldersAutoinsertInFolderByDocnumberRequest($docnumber) { // verify the required parameter 'docnumber' is set if ($docnumber === null) { throw new \InvalidArgumentException( 'Missing the required parameter $docnumber when calling foldersAutoinsertInFolderByDocnumber' ); } $resourcePath = '/api/Folders/{docnumber}/autoinsert'; $formParams = []; $queryParams = []; $headerParams = []; $httpBody = ''; $multipart = false; // path params if ($docnumber!== null) { $resourcePath = str_replace( '{'. 'docnumber'. '}', ObjectSerializer::toPathValue($docnumber), $resourcePath ); } // body params $_tempBody = null; if ($multipart) { $headers = $this->headerSelector->selectHeadersForMultipart( [] ); } else { $headers = $this->headerSelector->selectHeaders( [], [] ); } // for model (json/xml) if (isset($_tempBody)) { // $_tempBody is the method argument, if present $httpBody = $_tempBody; // \stdClass has no __toString(), so we should encode it manually if ($httpBody instanceof \stdClass && $headers['Content-Type'] === 'application/json') { $httpBody = \GuzzleHttp\json_encode($httpBody); } } elseif (count($formParams) > 0) { if ($multipart) { $multipartContents = []; foreach ($formParams as $formParamName => $formParamValue) { $multipartContents[] = [ 'name' => $formParamName, 'contents' => $formParamValue ]; } // for HTTP post (form) $httpBody = new MultipartStream($multipartContents); } elseif ($headers['Content-Type'] === 'application/json') { $httpBody = \GuzzleHttp\json_encode($formParams); } else { // for HTTP post (form) $httpBody = \GuzzleHttp\Psr7\build_query($formParams); } } // this endpoint requires API key authentication $apiKey = $this->config->getApiKeyWithPrefix('Authorization'); if ($apiKey!== null) { $headers['Authorization'] = $apiKey; } $defaultHeaders = []; if ($this->config->getUserAgent()) { $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); } $headers = array_merge( $defaultHeaders, $headerParams, $headers ); $query = \GuzzleHttp\Psr7\build_query($queryParams); return new Request( 'POST', $this->config->getHost(). $resourcePath. ($query? "?{$query}" : ''), $headers, $httpBody ); } /** * Operation foldersDelete * * This method allow to delete a folder * * @param int $id The identifier of the folder (required) * * @throws \Swagger\Client\ApiException on non-2xx response * @throws \InvalidArgumentException * @return void */ public function foldersDelete($id) { $this->foldersDeleteWithHttpInfo($id); } /** * Operation foldersDeleteWithHttpInfo * * This method allow to delete a folder * * @param int $id The identifier of the folder (required) * * @throws \Swagger\Client\ApiException on non-2xx response * @throws \InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ public function foldersDeleteWithHttpInfo($id) { $returnType = ''; $request = $this->foldersDeleteRequest($id); try { $options = $this->createHttpClientOption(); try { $response = $this->client->send($request, $options); } catch (RequestException $e) { throw new ApiException( "[{$e->getCode()}] {$e->getMessage()}", $e->getCode(), $e->getResponse()? $e->getResponse()->getHeaders() : null, $e->getResponse()? $e->getResponse()->getBody()->getContents() : null ); } $statusCode = $response->getStatusCode(); if ($statusCode < 200 || $statusCode > 299) { throw new ApiException( sprintf( '[%d] Error connecting to the API (%s)', $statusCode, $request->getUri() ), $statusCode, $response->getHeaders(), $response->getBody() ); } return [null, $statusCode, $response->getHeaders()]; } catch (ApiException $e) { switch ($e->getCode()) { } throw $e; } } /** * Operation foldersDeleteAsync * * This method allow to delete a folder * * @param int $id The identifier of the folder (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Promise\PromiseInterface */ public function foldersDeleteAsync($id) { return $this->foldersDeleteAsyncWithHttpInfo($id) ->then( function ($response) { return $response[0]; } ); } /** * Operation foldersDeleteAsyncWithHttpInfo * * This method allow to delete a folder * * @param int $id The identifier of the folder (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Promise\PromiseInterface */ public function foldersDeleteAsyncWithHttpInfo($id) { $returnType = ''; $request = $this->foldersDeleteRequest($id); return $this->client ->sendAsync($request, $this->createHttpClientOption()) ->then( function ($response) use ($returnType) { return [null, $response->getStatusCode(), $response->getHeaders()]; }, function ($exception) { $response = $exception->getResponse(); $statusCode = $response->getStatusCode(); throw new ApiException( sprintf( '[%d] Error connecting to the API (%s)', $statusCode, $exception->getRequest()->getUri() ), $statusCode, $response->getHeaders(), $response->getBody() ); } ); } /** * Create request for operation 'foldersDelete' * * @param int $id The identifier of the folder (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Psr7\Request */ protected function foldersDeleteRequest($id) { // verify the required parameter 'id' is set if ($id === null) { throw new \InvalidArgumentException( 'Missing the required parameter $id when calling foldersDelete' ); } $resourcePath = '/api/Folders/{id}'; $formParams = []; $queryParams = []; $headerParams = []; $httpBody = ''; $multipart = false; // path params if ($id!== null) { $resourcePath = str_replace( '{'. 'id'. '}', ObjectSerializer::toPathValue($id), $resourcePath ); } // body params $_tempBody = null; if ($multipart) { $headers = $this->headerSelector->selectHeadersForMultipart( [] ); } else { $headers = $this->headerSelector->selectHeaders( [], [] ); } // for model (json/xml) if (isset($_tempBody)) { // $_tempBody is the method argument, if present $httpBody = $_tempBody; // \stdClass has no __toString(), so we should encode it manually if ($httpBody instanceof \stdClass && $headers['Content-Type'] === 'application/json') { $httpBody = \GuzzleHttp\json_encode($httpBody); } } elseif (count($formParams) > 0) { if ($multipart) { $multipartContents = []; foreach ($formParams as $formParamName => $formParamValue) { $multipartContents[] = [ 'name' => $formParamName, 'contents' => $formParamValue ]; } // for HTTP post (form) $httpBody = new MultipartStream($multipartContents); } elseif ($headers['Content-Type'] === 'application/json') { $httpBody = \GuzzleHttp\json_encode($formParams); } else { // for HTTP post (form) $httpBody = \GuzzleHttp\Psr7\build_query($formParams); } } // this endpoint requires API key authentication $apiKey = $this->config->getApiKeyWithPrefix('Authorization'); if ($apiKey!== null) { $headers['Authorization'] = $apiKey; } $defaultHeaders = []; if ($this->config->getUserAgent()) { $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); } $headers = array_merge( $defaultHeaders, $headerParams, $headers ); $query = \GuzzleHttp\Psr7\build_query($queryParams); return new Request( 'DELETE', $this->config->getHost(). $resourcePath. ($query? "?{$query}" : ''), $headers, $httpBody ); } /** * Operation foldersDeleteArxDriveConfiguration * * This method delete the arxdrive configuration for the folder * * @param int $id The identifier of the configuration (required) * * @throws \Swagger\Client\ApiException on non-2xx response * @throws \InvalidArgumentException * @return void */ public function foldersDeleteArxDriveConfiguration($id) { $this->foldersDeleteArxDriveConfigurationWithHttpInfo($id); } /** * Operation foldersDeleteArxDriveConfigurationWithHttpInfo * * This method delete the arxdrive configuration for the folder * * @param int $id The identifier of the configuration (required) * * @throws \Swagger\Client\ApiException on non-2xx response * @throws \InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ public function foldersDeleteArxDriveConfigurationWithHttpInfo($id) { $returnType = ''; $request = $this->foldersDeleteArxDriveConfigurationRequest($id); try { $options = $this->createHttpClientOption(); try { $response = $this->client->send($request, $options); } catch (RequestException $e) { throw new ApiException( "[{$e->getCode()}] {$e->getMessage()}", $e->getCode(), $e->getResponse()? $e->getResponse()->getHeaders() : null, $e->getResponse()? $e->getResponse()->getBody()->getContents() : null ); } $statusCode = $response->getStatusCode(); if ($statusCode < 200 || $statusCode > 299) { throw new ApiException( sprintf( '[%d] Error connecting to the API (%s)', $statusCode, $request->getUri() ), $statusCode, $response->getHeaders(), $response->getBody() ); } return [null, $statusCode, $response->getHeaders()]; } catch (ApiException $e) { switch ($e->getCode()) { } throw $e; } } /** * Operation foldersDeleteArxDriveConfigurationAsync * * This method delete the arxdrive configuration for the folder * * @param int $id The identifier of the configuration (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Promise\PromiseInterface */ public function foldersDeleteArxDriveConfigurationAsync($id) { return $this->foldersDeleteArxDriveConfigurationAsyncWithHttpInfo($id) ->then( function ($response) { return $response[0]; } ); } /** * Operation foldersDeleteArxDriveConfigurationAsyncWithHttpInfo * * This method delete the arxdrive configuration for the folder * * @param int $id The identifier of the configuration (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Promise\PromiseInterface */ public function foldersDeleteArxDriveConfigurationAsyncWithHttpInfo($id) { $returnType = ''; $request = $this->foldersDeleteArxDriveConfigurationRequest($id); return $this->client ->sendAsync($request, $this->createHttpClientOption()) ->then( function ($response) use ($returnType) { return [null, $response->getStatusCode(), $response->getHeaders()]; }, function ($exception) { $response = $exception->getResponse(); $statusCode = $response->getStatusCode(); throw new ApiException( sprintf( '[%d] Error connecting to the API (%s)', $statusCode, $exception->getRequest()->getUri() ), $statusCode, $response->getHeaders(), $response->getBody() ); } ); } /** * Create request for operation 'foldersDeleteArxDriveConfiguration' * * @param int $id The identifier of the configuration (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Psr7\Request */ protected function foldersDeleteArxDriveConfigurationRequest($id) { // verify the required parameter 'id' is set if ($id === null) { throw new \InvalidArgumentException( 'Missing the required parameter $id when calling foldersDeleteArxDriveConfiguration' ); } $resourcePath = '/api/Folders/arxdriveinfo/{id}'; $formParams = []; $queryParams = []; $headerParams = []; $httpBody = ''; $multipart = false; // path params if ($id!== null) { $resourcePath = str_replace( '{'. 'id'. '}', ObjectSerializer::toPathValue($id), $resourcePath ); } // body params $_tempBody = null; if ($multipart) { $headers = $this->headerSelector->selectHeadersForMultipart( [] ); } else { $headers = $this->headerSelector->selectHeaders( [], [] ); } // for model (json/xml) if (isset($_tempBody)) { // $_tempBody is the method argument, if present $httpBody = $_tempBody; // \stdClass has no __toString(), so we should encode it manually if ($httpBody instanceof \stdClass && $headers['Content-Type'] === 'application/json') { $httpBody = \GuzzleHttp\json_encode($httpBody); } } elseif (count($formParams) > 0) { if ($multipart) { $multipartContents = []; foreach ($formParams as $formParamName => $formParamValue) { $multipartContents[] = [ 'name' => $formParamName, 'contents' => $formParamValue ]; } // for HTTP post (form) $httpBody = new MultipartStream($multipartContents); } elseif ($headers['Content-Type'] === 'application/json') { $httpBody = \GuzzleHttp\json_encode($formParams); } else { // for HTTP post (form) $httpBody = \GuzzleHttp\Psr7\build_query($formParams); } } // this endpoint requires API key authentication $apiKey = $this->config->getApiKeyWithPrefix('Authorization'); if ($apiKey!== null) { $headers['Authorization'] = $apiKey; } $defaultHeaders = []; if ($this->config->getUserAgent()) { $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); } $headers = array_merge( $defaultHeaders, $headerParams, $headers ); $query = \GuzzleHttp\Psr7\build_query($queryParams); return new Request( 'DELETE', $this->config->getHost(). $resourcePath. ($query? "?{$query}" : ''), $headers, $httpBody ); } /** * Operation foldersFindByDocnumber * * This method allows to find folders that contains docnumber * * @param int $docnumber The document identifier (required) * * @throws \Swagger\Client\ApiException on non-2xx response * @throws \InvalidArgumentException * @return \Swagger\Client\Model\FolderDTO[] */ public function foldersFindByDocnumber($docnumber) { list($response) = $this->foldersFindByDocnumberWithHttpInfo($docnumber); return $response; } /** * Operation foldersFindByDocnumberWithHttpInfo * * This method allows to find folders that contains docnumber * * @param int $docnumber The document identifier (required) * * @throws \Swagger\Client\ApiException on non-2xx response * @throws \InvalidArgumentException * @return array of \Swagger\Client\Model\FolderDTO[], HTTP status code, HTTP response headers (array of strings) */ public function foldersFindByDocnumberWithHttpInfo($docnumber) { $returnType = '\Swagger\Client\Model\FolderDTO[]'; $request = $this->foldersFindByDocnumberRequest($docnumber); try { $options = $this->createHttpClientOption(); try { $response = $this->client->send($request, $options); } catch (RequestException $e) { throw new ApiException( "[{$e->getCode()}] {$e->getMessage()}", $e->getCode(), $e->getResponse()? $e->getResponse()->getHeaders() : null, $e->getResponse()? $e->getResponse()->getBody()->getContents() : null ); } $statusCode = $response->getStatusCode(); if ($statusCode < 200 || $statusCode > 299) { throw new ApiException( sprintf( '[%d] Error connecting to the API (%s)', $statusCode, $request->getUri() ), $statusCode, $response->getHeaders(), $response->getBody() ); } $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer } else { $content = $responseBody->getContents(); if ($returnType!=='string') { $content = json_decode($content); } } return [ ObjectSerializer::deserialize($content, $returnType, []), $response->getStatusCode(), $response->getHeaders() ]; } catch (ApiException $e) { switch ($e->getCode()) { case 200: $data = ObjectSerializer::deserialize( $e->getResponseBody(), '\Swagger\Client\Model\FolderDTO[]', $e->getResponseHeaders() ); $e->setResponseObject($data); break; } throw $e; } } /** * Operation foldersFindByDocnumberAsync * * This method allows to find folders that contains docnumber * * @param int $docnumber The document identifier (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Promise\PromiseInterface */ public function foldersFindByDocnumberAsync($docnumber) { return $this->foldersFindByDocnumberAsyncWithHttpInfo($docnumber) ->then( function ($response) { return $response[0]; } ); } /** * Operation foldersFindByDocnumberAsyncWithHttpInfo * * This method allows to find folders that contains docnumber * * @param int $docnumber The document identifier (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Promise\PromiseInterface */ public function foldersFindByDocnumberAsyncWithHttpInfo($docnumber) { $returnType = '\Swagger\Client\Model\FolderDTO[]'; $request = $this->foldersFindByDocnumberRequest($docnumber); return $this->client ->sendAsync($request, $this->createHttpClientOption()) ->then( function ($response) use ($returnType) { $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer } else { $content = $responseBody->getContents(); if ($returnType!=='string') { $content = json_decode($content); } } return [ ObjectSerializer::deserialize($content, $returnType, []), $response->getStatusCode(), $response->getHeaders() ]; }, function ($exception) { $response = $exception->getResponse(); $statusCode = $response->getStatusCode(); throw new ApiException( sprintf( '[%d] Error connecting to the API (%s)', $statusCode, $exception->getRequest()->getUri() ), $statusCode, $response->getHeaders(), $response->getBody() ); } ); } /** * Create request for operation 'foldersFindByDocnumber' * * @param int $docnumber The document identifier (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Psr7\Request */ protected function foldersFindByDocnumberRequest($docnumber) { // verify the required parameter 'docnumber' is set if ($docnumber === null) { throw new \InvalidArgumentException( 'Missing the required parameter $docnumber when calling foldersFindByDocnumber' ); } $resourcePath = '/api/Folders/docnumber/{docnumber}'; $formParams = []; $queryParams = []; $headerParams = []; $httpBody = ''; $multipart = false; // path params if ($docnumber!== null) { $resourcePath = str_replace( '{'. 'docnumber'. '}', ObjectSerializer::toPathValue($docnumber), $resourcePath ); } // body params $_tempBody = null; if ($multipart) { $headers = $this->headerSelector->selectHeadersForMultipart( ['application/json', 'text/json', 'application/xml', 'text/xml'] ); } else { $headers = $this->headerSelector->selectHeaders( ['application/json', 'text/json', 'application/xml', 'text/xml'], [] ); } // for model (json/xml) if (isset($_tempBody)) { // $_tempBody is the method argument, if present $httpBody = $_tempBody; // \stdClass has no __toString(), so we should encode it manually if ($httpBody instanceof \stdClass && $headers['Content-Type'] === 'application/json') { $httpBody = \GuzzleHttp\json_encode($httpBody); } } elseif (count($formParams) > 0) { if ($multipart) { $multipartContents = []; foreach ($formParams as $formParamName => $formParamValue) { $multipartContents[] = [ 'name' => $formParamName, 'contents' => $formParamValue ]; } // for HTTP post (form) $httpBody = new MultipartStream($multipartContents); } elseif ($headers['Content-Type'] === 'application/json') { $httpBody = \GuzzleHttp\json_encode($formParams); } else { // for HTTP post (form) $httpBody = \GuzzleHttp\Psr7\build_query($formParams); } } // this endpoint requires API key authentication $apiKey = $this->config->getApiKeyWithPrefix('Authorization'); if ($apiKey!== null) { $headers['Authorization'] = $apiKey; } $defaultHeaders = []; if ($this->config->getUserAgent()) { $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); } $headers = array_merge( $defaultHeaders, $headerParams, $headers ); $query = \GuzzleHttp\Psr7\build_query($queryParams); return new Request( 'GET', $this->config->getHost(). $resourcePath. ($query? "?{$query}" : ''), $headers, $httpBody ); } /** * Operation foldersFindByName * * This method allows to find folders by their name * * @param string $name The name to search (required) * * @throws \Swagger\Client\ApiException on non-2xx response * @throws \InvalidArgumentException * @return \Swagger\Client\Model\FolderDTO[] */ public function foldersFindByName($name) { list($response) = $this->foldersFindByNameWithHttpInfo($name); return $response; } /** * Operation foldersFindByNameWithHttpInfo * * This method allows to find folders by their name * * @param string $name The name to search (required) * * @throws \Swagger\Client\ApiException on non-2xx response * @throws \InvalidArgumentException * @return array of \Swagger\Client\Model\FolderDTO[], HTTP status code, HTTP response headers (array of strings) */ public function foldersFindByNameWithHttpInfo($name) { $returnType = '\Swagger\Client\Model\FolderDTO[]'; $request = $this->foldersFindByNameRequest($name); try { $options = $this->createHttpClientOption(); try { $response = $this->client->send($request, $options); } catch (RequestException $e) { throw new ApiException( "[{$e->getCode()}] {$e->getMessage()}", $e->getCode(), $e->getResponse()? $e->getResponse()->getHeaders() : null, $e->getResponse()? $e->getResponse()->getBody()->getContents() : null ); } $statusCode = $response->getStatusCode(); if ($statusCode < 200 || $statusCode > 299) { throw new ApiException( sprintf( '[%d] Error connecting to the API (%s)', $statusCode, $request->getUri() ), $statusCode, $response->getHeaders(), $response->getBody() ); } $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer } else { $content = $responseBody->getContents(); if ($returnType!=='string') { $content = json_decode($content); } } return [ ObjectSerializer::deserialize($content, $returnType, []), $response->getStatusCode(), $response->getHeaders() ]; } catch (ApiException $e) { switch ($e->getCode()) { case 200: $data = ObjectSerializer::deserialize( $e->getResponseBody(), '\Swagger\Client\Model\FolderDTO[]', $e->getResponseHeaders() ); $e->setResponseObject($data); break; } throw $e; } } /** * Operation foldersFindByNameAsync * * This method allows to find folders by their name * * @param string $name The name to search (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Promise\PromiseInterface */ public function foldersFindByNameAsync($name) { return $this->foldersFindByNameAsyncWithHttpInfo($name) ->then( function ($response) { return $response[0]; } ); } /** * Operation foldersFindByNameAsyncWithHttpInfo * * This method allows to find folders by their name * * @param string $name The name to search (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Promise\PromiseInterface */ public function foldersFindByNameAsyncWithHttpInfo($name) { $returnType = '\Swagger\Client\Model\FolderDTO[]'; $request = $this->foldersFindByNameRequest($name); return $this->client ->sendAsync($request, $this->createHttpClientOption()) ->then( function ($response) use ($returnType) { $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer } else { $content = $responseBody->getContents(); if ($returnType!=='string') { $content = json_decode($content); } } return [ ObjectSerializer::deserialize($content, $returnType, []), $response->getStatusCode(), $response->getHeaders() ]; }, function ($exception) { $response = $exception->getResponse(); $statusCode = $response->getStatusCode(); throw new ApiException( sprintf( '[%d] Error connecting to the API (%s)', $statusCode, $exception->getRequest()->getUri() ), $statusCode, $response->getHeaders(), $response->getBody() ); } ); } /** * Create request for operation 'foldersFindByName' * * @param string $name The name to search (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Psr7\Request */ protected function foldersFindByNameRequest($name) { // verify the required parameter 'name' is set if ($name === null) { throw new \InvalidArgumentException( 'Missing the required parameter $name when calling foldersFindByName' ); } $resourcePath = '/api/Folders/find'; $formParams = []; $queryParams = []; $headerParams = []; $httpBody = ''; $multipart = false; // query params if ($name!== null) { $queryParams['name'] = ObjectSerializer::toQueryValue($name); } // body params $_tempBody = null; if ($multipart) { $headers = $this->headerSelector->selectHeadersForMultipart( ['application/json', 'text/json', 'application/xml', 'text/xml'] ); } else { $headers = $this->headerSelector->selectHeaders( ['application/json', 'text/json', 'application/xml', 'text/xml'], [] ); } // for model (json/xml) if (isset($_tempBody)) { // $_tempBody is the method argument, if present $httpBody = $_tempBody; // \stdClass has no __toString(), so we should encode it manually if ($httpBody instanceof \stdClass && $headers['Content-Type'] === 'application/json') { $httpBody = \GuzzleHttp\json_encode($httpBody); } } elseif (count($formParams) > 0) { if ($multipart) { $multipartContents = []; foreach ($formParams as $formParamName => $formParamValue) { $multipartContents[] = [ 'name' => $formParamName, 'contents' => $formParamValue ]; } // for HTTP post (form) $httpBody = new MultipartStream($multipartContents); } elseif ($headers['Content-Type'] === 'application/json') { $httpBody = \GuzzleHttp\json_encode($formParams); } else { // for HTTP post (form) $httpBody = \GuzzleHttp\Psr7\build_query($formParams); } } // this endpoint requires API key authentication $apiKey = $this->config->getApiKeyWithPrefix('Authorization'); if ($apiKey!== null) { $headers['Authorization'] = $apiKey; } $defaultHeaders = []; if ($this->config->getUserAgent()) { $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); } $headers = array_merge( $defaultHeaders, $headerParams, $headers ); $query = \GuzzleHttp\Psr7\build_query($queryParams); return new Request( 'GET', $this->config->getHost(). $resourcePath. ($query? "?{$query}" : ''), $headers, $httpBody ); } /** * Operation foldersFindByNameOld * * This method allows to find folders by their name * * @param string $name The name to search (required) * * @throws \Swagger\Client\ApiException on non-2xx response * @throws \InvalidArgumentException * @return \Swagger\Client\Model\FolderDTO[] */ public function foldersFindByNameOld($name) { list($response) = $this->foldersFindByNameOldWithHttpInfo($name); return $response; } /** * Operation foldersFindByNameOldWithHttpInfo * * This method allows to find folders by their name * * @param string $name The name to search (required) * * @throws \Swagger\Client\ApiException on non-2xx response * @throws \InvalidArgumentException * @return array of \Swagger\Client\Model\FolderDTO[], HTTP status code, HTTP response headers (array of strings) */ public function foldersFindByNameOldWithHttpInfo($name) { $returnType = '\Swagger\Client\Model\FolderDTO[]'; $request = $this->foldersFindByNameOldRequest($name); try { $options = $this->createHttpClientOption(); try { $response = $this->client->send($request, $options); } catch (RequestException $e) { throw new ApiException( "[{$e->getCode()}] {$e->getMessage()}", $e->getCode(), $e->getResponse()? $e->getResponse()->getHeaders() : null, $e->getResponse()? $e->getResponse()->getBody()->getContents() : null ); } $statusCode = $response->getStatusCode(); if ($statusCode < 200 || $statusCode > 299) { throw new ApiException( sprintf( '[%d] Error connecting to the API (%s)', $statusCode, $request->getUri() ), $statusCode, $response->getHeaders(), $response->getBody() ); } $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer } else { $content = $responseBody->getContents(); if ($returnType!=='string') { $content = json_decode($content); } } return [ ObjectSerializer::deserialize($content, $returnType, []), $response->getStatusCode(), $response->getHeaders() ]; } catch (ApiException $e) { switch ($e->getCode()) { case 200: $data = ObjectSerializer::deserialize( $e->getResponseBody(), '\Swagger\Client\Model\FolderDTO[]', $e->getResponseHeaders() ); $e->setResponseObject($data); break; } throw $e; } } /** * Operation foldersFindByNameOldAsync * * This method allows to find folders by their name * * @param string $name The name to search (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Promise\PromiseInterface */ public function foldersFindByNameOldAsync($name) { return $this->foldersFindByNameOldAsyncWithHttpInfo($name) ->then( function ($response) { return $response[0]; } ); } /** * Operation foldersFindByNameOldAsyncWithHttpInfo * * This method allows to find folders by their name * * @param string $name The name to search (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Promise\PromiseInterface */ public function foldersFindByNameOldAsyncWithHttpInfo($name) { $returnType = '\Swagger\Client\Model\FolderDTO[]'; $request = $this->foldersFindByNameOldRequest($name); return $this->client ->sendAsync($request, $this->createHttpClientOption()) ->then( function ($response) use ($returnType) { $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer } else { $content = $responseBody->getContents(); if ($returnType!=='string') { $content = json_decode($content); } } return [ ObjectSerializer::deserialize($content, $returnType, []), $response->getStatusCode(), $response->getHeaders() ]; }, function ($exception) { $response = $exception->getResponse(); $statusCode = $response->getStatusCode(); throw new ApiException( sprintf( '[%d] Error connecting to the API (%s)', $statusCode, $exception->getRequest()->getUri() ), $statusCode, $response->getHeaders(), $response->getBody() ); } ); } /** * Create request for operation 'foldersFindByNameOld' * * @param string $name The name to search (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Psr7\Request */ protected function foldersFindByNameOldRequest($name) { // verify the required parameter 'name' is set if ($name === null) { throw new \InvalidArgumentException( 'Missing the required parameter $name when calling foldersFindByNameOld' ); } $resourcePath = '/api/Folders/find/{name}'; $formParams = []; $queryParams = []; $headerParams = []; $httpBody = ''; $multipart = false; // path params if ($name!== null) { $resourcePath = str_replace( '{'. 'name'. '}', ObjectSerializer::toPathValue($name), $resourcePath ); } // body params $_tempBody = null; if ($multipart) { $headers = $this->headerSelector->selectHeadersForMultipart( ['application/json', 'text/json', 'application/xml', 'text/xml'] ); } else { $headers = $this->headerSelector->selectHeaders( ['application/json', 'text/json', 'application/xml', 'text/xml'], [] ); } // for model (json/xml) if (isset($_tempBody)) { // $_tempBody is the method argument, if present $httpBody = $_tempBody; // \stdClass has no __toString(), so we should encode it manually if ($httpBody instanceof \stdClass && $headers['Content-Type'] === 'application/json') { $httpBody = \GuzzleHttp\json_encode($httpBody); } } elseif (count($formParams) > 0) { if ($multipart) { $multipartContents = []; foreach ($formParams as $formParamName => $formParamValue) { $multipartContents[] = [ 'name' => $formParamName, 'contents' => $formParamValue ]; } // for HTTP post (form) $httpBody = new MultipartStream($multipartContents); } elseif ($headers['Content-Type'] === 'application/json') { $httpBody = \GuzzleHttp\json_encode($formParams); } else { // for HTTP post (form) $httpBody = \GuzzleHttp\Psr7\build_query($formParams); } } // this endpoint requires API key authentication $apiKey = $this->config->getApiKeyWithPrefix('Authorization'); if ($apiKey!== null) { $headers['Authorization'] = $apiKey; } $defaultHeaders = []; if ($this->config->getUserAgent()) { $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); } $headers = array_merge( $defaultHeaders, $headerParams, $headers ); $query = \GuzzleHttp\Psr7\build_query($queryParams); return new Request( 'GET', $this->config->getHost(). $resourcePath. ($query? "?{$query}" : ''), $headers, $httpBody ); } /** * Operation foldersFindInFolderByName * * This method allows to find folders by their parent and name * * @param int $id The identifier for root folder (required) * @param string $name The name to search (required) * * @throws \Swagger\Client\ApiException on non-2xx response * @throws \InvalidArgumentException * @return \Swagger\Client\Model\FolderDTO[] */ public function foldersFindInFolderByName($id, $name) { list($response) = $this->foldersFindInFolderByNameWithHttpInfo($id, $name); return $response; } /** * Operation foldersFindInFolderByNameWithHttpInfo * * This method allows to find folders by their parent and name * * @param int $id The identifier for root folder (required) * @param string $name The name to search (required) * * @throws \Swagger\Client\ApiException on non-2xx response * @throws \InvalidArgumentException * @return array of \Swagger\Client\Model\FolderDTO[], HTTP status code, HTTP response headers (array of strings) */ public function foldersFindInFolderByNameWithHttpInfo($id, $name) { $returnType = '\Swagger\Client\Model\FolderDTO[]'; $request = $this->foldersFindInFolderByNameRequest($id, $name); try { $options = $this->createHttpClientOption(); try { $response = $this->client->send($request, $options); } catch (RequestException $e) { throw new ApiException( "[{$e->getCode()}] {$e->getMessage()}", $e->getCode(), $e->getResponse()? $e->getResponse()->getHeaders() : null, $e->getResponse()? $e->getResponse()->getBody()->getContents() : null ); } $statusCode = $response->getStatusCode(); if ($statusCode < 200 || $statusCode > 299) { throw new ApiException( sprintf( '[%d] Error connecting to the API (%s)', $statusCode, $request->getUri() ), $statusCode, $response->getHeaders(), $response->getBody() ); } $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer } else { $content = $responseBody->getContents(); if ($returnType!=='string') { $content = json_decode($content); } } return [ ObjectSerializer::deserialize($content, $returnType, []), $response->getStatusCode(), $response->getHeaders() ]; } catch (ApiException $e) { switch ($e->getCode()) { case 200: $data = ObjectSerializer::deserialize( $e->getResponseBody(), '\Swagger\Client\Model\FolderDTO[]', $e->getResponseHeaders() ); $e->setResponseObject($data); break; } throw $e; } } /** * Operation foldersFindInFolderByNameAsync * * This method allows to find folders by their parent and name * * @param int $id The identifier for root folder (required) * @param string $name The name to search (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Promise\PromiseInterface */ public function foldersFindInFolderByNameAsync($id, $name) { return $this->foldersFindInFolderByNameAsyncWithHttpInfo($id, $name) ->then( function ($response) { return $response[0]; } ); } /** * Operation foldersFindInFolderByNameAsyncWithHttpInfo * * This method allows to find folders by their parent and name * * @param int $id The identifier for root folder (required) * @param string $name The name to search (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Promise\PromiseInterface */ public function foldersFindInFolderByNameAsyncWithHttpInfo($id, $name) { $returnType = '\Swagger\Client\Model\FolderDTO[]'; $request = $this->foldersFindInFolderByNameRequest($id, $name); return $this->client ->sendAsync($request, $this->createHttpClientOption()) ->then( function ($response) use ($returnType) { $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer } else { $content = $responseBody->getContents(); if ($returnType!=='string') { $content = json_decode($content); } } return [ ObjectSerializer::deserialize($content, $returnType, []), $response->getStatusCode(), $response->getHeaders() ]; }, function ($exception) { $response = $exception->getResponse(); $statusCode = $response->getStatusCode(); throw new ApiException( sprintf( '[%d] Error connecting to the API (%s)', $statusCode, $exception->getRequest()->getUri() ), $statusCode, $response->getHeaders(), $response->getBody() ); } ); } /** * Create request for operation 'foldersFindInFolderByName' * * @param int $id The identifier for root folder (required) * @param string $name The name to search (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Psr7\Request */ protected function foldersFindInFolderByNameRequest($id, $name) { // verify the required parameter 'id' is set if ($id === null) { throw new \InvalidArgumentException( 'Missing the required parameter $id when calling foldersFindInFolderByName' ); } // verify the required parameter 'name' is set if ($name === null) { throw new \InvalidArgumentException( 'Missing the required parameter $name when calling foldersFindInFolderByName' ); } $resourcePath = '/api/Folders/{id}/name/{name}'; $formParams = []; $queryParams = []; $headerParams = []; $httpBody = ''; $multipart = false; // path params if ($id!== null) { $resourcePath = str_replace( '{'. 'id'. '}', ObjectSerializer::toPathValue($id), $resourcePath ); } // path params if ($name!== null) { $resourcePath = str_replace( '{'. 'name'. '}', ObjectSerializer::toPathValue($name), $resourcePath ); } // body params $_tempBody = null; if ($multipart) { $headers = $this->headerSelector->selectHeadersForMultipart( ['application/json', 'text/json', 'application/xml', 'text/xml'] ); } else { $headers = $this->headerSelector->selectHeaders( ['application/json', 'text/json', 'application/xml', 'text/xml'], [] ); } // for model (json/xml) if (isset($_tempBody)) { // $_tempBody is the method argument, if present $httpBody = $_tempBody; // \stdClass has no __toString(), so we should encode it manually if ($httpBody instanceof \stdClass && $headers['Content-Type'] === 'application/json') { $httpBody = \GuzzleHttp\json_encode($httpBody); } } elseif (count($formParams) > 0) { if ($multipart) { $multipartContents = []; foreach ($formParams as $formParamName => $formParamValue) { $multipartContents[] = [ 'name' => $formParamName, 'contents' => $formParamValue ]; } // for HTTP post (form) $httpBody = new MultipartStream($multipartContents); } elseif ($headers['Content-Type'] === 'application/json') { $httpBody = \GuzzleHttp\json_encode($formParams); } else { // for HTTP post (form) $httpBody = \GuzzleHttp\Psr7\build_query($formParams); } } // this endpoint requires API key authentication $apiKey = $this->config->getApiKeyWithPrefix('Authorization'); if ($apiKey!== null) { $headers['Authorization'] = $apiKey; } $defaultHeaders = []; if ($this->config->getUserAgent()) { $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); } $headers = array_merge( $defaultHeaders, $headerParams, $headers ); $query = \GuzzleHttp\Psr7\build_query($queryParams); return new Request( 'GET', $this->config->getHost(). $resourcePath. ($query? "?{$query}" : ''), $headers, $httpBody ); } /** * Operation foldersGetArchiveInfo * * This method returns the profile configuration for a folder * * @param int $id The identifier of the folder (required) * * @throws \Swagger\Client\ApiException on non-2xx response * @throws \InvalidArgumentException * @return \Swagger\Client\Model\FolderArchiveModeInfo */ public function foldersGetArchiveInfo($id) { list($response) = $this->foldersGetArchiveInfoWithHttpInfo($id); return $response; } /** * Operation foldersGetArchiveInfoWithHttpInfo * * This method returns the profile configuration for a folder * * @param int $id The identifier of the folder (required) * * @throws \Swagger\Client\ApiException on non-2xx response * @throws \InvalidArgumentException * @return array of \Swagger\Client\Model\FolderArchiveModeInfo, HTTP status code, HTTP response headers (array of strings) */ public function foldersGetArchiveInfoWithHttpInfo($id) { $returnType = '\Swagger\Client\Model\FolderArchiveModeInfo'; $request = $this->foldersGetArchiveInfoRequest($id); try { $options = $this->createHttpClientOption(); try { $response = $this->client->send($request, $options); } catch (RequestException $e) { throw new ApiException( "[{$e->getCode()}] {$e->getMessage()}", $e->getCode(), $e->getResponse()? $e->getResponse()->getHeaders() : null, $e->getResponse()? $e->getResponse()->getBody()->getContents() : null ); } $statusCode = $response->getStatusCode(); if ($statusCode < 200 || $statusCode > 299) { throw new ApiException( sprintf( '[%d] Error connecting to the API (%s)', $statusCode, $request->getUri() ), $statusCode, $response->getHeaders(), $response->getBody() ); } $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer } else { $content = $responseBody->getContents(); if ($returnType!=='string') { $content = json_decode($content); } } return [ ObjectSerializer::deserialize($content, $returnType, []), $response->getStatusCode(), $response->getHeaders() ]; } catch (ApiException $e) { switch ($e->getCode()) { case 200: $data = ObjectSerializer::deserialize( $e->getResponseBody(), '\Swagger\Client\Model\FolderArchiveModeInfo', $e->getResponseHeaders() ); $e->setResponseObject($data); break; } throw $e; } } /** * Operation foldersGetArchiveInfoAsync * * This method returns the profile configuration for a folder * * @param int $id The identifier of the folder (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Promise\PromiseInterface */ public function foldersGetArchiveInfoAsync($id) { return $this->foldersGetArchiveInfoAsyncWithHttpInfo($id) ->then( function ($response) { return $response[0]; } ); } /** * Operation foldersGetArchiveInfoAsyncWithHttpInfo * * This method returns the profile configuration for a folder * * @param int $id The identifier of the folder (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Promise\PromiseInterface */ public function foldersGetArchiveInfoAsyncWithHttpInfo($id) { $returnType = '\Swagger\Client\Model\FolderArchiveModeInfo'; $request = $this->foldersGetArchiveInfoRequest($id); return $this->client ->sendAsync($request, $this->createHttpClientOption()) ->then( function ($response) use ($returnType) { $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer } else { $content = $responseBody->getContents(); if ($returnType!=='string') { $content = json_decode($content); } } return [ ObjectSerializer::deserialize($content, $returnType, []), $response->getStatusCode(), $response->getHeaders() ]; }, function ($exception) { $response = $exception->getResponse(); $statusCode = $response->getStatusCode(); throw new ApiException( sprintf( '[%d] Error connecting to the API (%s)', $statusCode, $exception->getRequest()->getUri() ), $statusCode, $response->getHeaders(), $response->getBody() ); } ); } /** * Create request for operation 'foldersGetArchiveInfo' * * @param int $id The identifier of the folder (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Psr7\Request */ protected function foldersGetArchiveInfoRequest($id) { // verify the required parameter 'id' is set if ($id === null) { throw new \InvalidArgumentException( 'Missing the required parameter $id when calling foldersGetArchiveInfo' ); } $resourcePath = '/api/Folders/{id}/archiveinfo'; $formParams = []; $queryParams = []; $headerParams = []; $httpBody = ''; $multipart = false; // path params if ($id!== null) { $resourcePath = str_replace( '{'. 'id'. '}', ObjectSerializer::toPathValue($id), $resourcePath ); } // body params $_tempBody = null; if ($multipart) { $headers = $this->headerSelector->selectHeadersForMultipart( ['application/json', 'text/json', 'application/xml', 'text/xml'] ); } else { $headers = $this->headerSelector->selectHeaders( ['application/json', 'text/json', 'application/xml', 'text/xml'], [] ); } // for model (json/xml) if (isset($_tempBody)) { // $_tempBody is the method argument, if present $httpBody = $_tempBody; // \stdClass has no __toString(), so we should encode it manually if ($httpBody instanceof \stdClass && $headers['Content-Type'] === 'application/json') { $httpBody = \GuzzleHttp\json_encode($httpBody); } } elseif (count($formParams) > 0) { if ($multipart) { $multipartContents = []; foreach ($formParams as $formParamName => $formParamValue) { $multipartContents[] = [ 'name' => $formParamName, 'contents' => $formParamValue ]; } // for HTTP post (form) $httpBody = new MultipartStream($multipartContents); } elseif ($headers['Content-Type'] === 'application/json') { $httpBody = \GuzzleHttp\json_encode($formParams); } else { // for HTTP post (form) $httpBody = \GuzzleHttp\Psr7\build_query($formParams); } } // this endpoint requires API key authentication $apiKey = $this->config->getApiKeyWithPrefix('Authorization'); if ($apiKey!== null) { $headers['Authorization'] = $apiKey; } $defaultHeaders = []; if ($this->config->getUserAgent()) { $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); } $headers = array_merge( $defaultHeaders, $headerParams, $headers ); $query = \GuzzleHttp\Psr7\build_query($queryParams); return new Request( 'GET', $this->config->getHost(). $resourcePath. ($query? "?{$query}" : ''), $headers, $httpBody ); } /** * Operation foldersGetArxDriveConfiguration * * This method returns the ArxDrive configuration for the folder * * @param int $id The identifier of the folder (required) * * @throws \Swagger\Client\ApiException on non-2xx response * @throws \InvalidArgumentException * @return \Swagger\Client\Model\ArxDriveFolderModeInfo */ public function foldersGetArxDriveConfiguration($id) { list($response) = $this->foldersGetArxDriveConfigurationWithHttpInfo($id); return $response; } /** * Operation foldersGetArxDriveConfigurationWithHttpInfo * * This method returns the ArxDrive configuration for the folder * * @param int $id The identifier of the folder (required) * * @throws \Swagger\Client\ApiException on non-2xx response * @throws \InvalidArgumentException * @return array of \Swagger\Client\Model\ArxDriveFolderModeInfo, HTTP status code, HTTP response headers (array of strings) */ public function foldersGetArxDriveConfigurationWithHttpInfo($id) { $returnType = '\Swagger\Client\Model\ArxDriveFolderModeInfo'; $request = $this->foldersGetArxDriveConfigurationRequest($id); try { $options = $this->createHttpClientOption(); try { $response = $this->client->send($request, $options); } catch (RequestException $e) { throw new ApiException( "[{$e->getCode()}] {$e->getMessage()}", $e->getCode(), $e->getResponse()? $e->getResponse()->getHeaders() : null, $e->getResponse()? $e->getResponse()->getBody()->getContents() : null ); } $statusCode = $response->getStatusCode(); if ($statusCode < 200 || $statusCode > 299) { throw new ApiException( sprintf( '[%d] Error connecting to the API (%s)', $statusCode, $request->getUri() ), $statusCode, $response->getHeaders(), $response->getBody() ); } $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer } else { $content = $responseBody->getContents(); if ($returnType!=='string') { $content = json_decode($content); } } return [ ObjectSerializer::deserialize($content, $returnType, []), $response->getStatusCode(), $response->getHeaders() ]; } catch (ApiException $e) { switch ($e->getCode()) { case 200: $data = ObjectSerializer::deserialize( $e->getResponseBody(), '\Swagger\Client\Model\ArxDriveFolderModeInfo', $e->getResponseHeaders() ); $e->setResponseObject($data); break; } throw $e; } } /** * Operation foldersGetArxDriveConfigurationAsync * * This method returns the ArxDrive configuration for the folder * * @param int $id The identifier of the folder (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Promise\PromiseInterface */ public function foldersGetArxDriveConfigurationAsync($id) { return $this->foldersGetArxDriveConfigurationAsyncWithHttpInfo($id) ->then( function ($response) { return $response[0]; } ); } /** * Operation foldersGetArxDriveConfigurationAsyncWithHttpInfo * * This method returns the ArxDrive configuration for the folder * * @param int $id The identifier of the folder (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Promise\PromiseInterface */ public function foldersGetArxDriveConfigurationAsyncWithHttpInfo($id) { $returnType = '\Swagger\Client\Model\ArxDriveFolderModeInfo'; $request = $this->foldersGetArxDriveConfigurationRequest($id); return $this->client ->sendAsync($request, $this->createHttpClientOption()) ->then( function ($response) use ($returnType) { $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer } else { $content = $responseBody->getContents(); if ($returnType!=='string') { $content = json_decode($content); } } return [ ObjectSerializer::deserialize($content, $returnType, []), $response->getStatusCode(), $response->getHeaders() ]; }, function ($exception) { $response = $exception->getResponse(); $statusCode = $response->getStatusCode(); throw new ApiException( sprintf( '[%d] Error connecting to the API (%s)', $statusCode, $exception->getRequest()->getUri() ), $statusCode, $response->getHeaders(), $response->getBody() ); } ); } /** * Create request for operation 'foldersGetArxDriveConfiguration' * * @param int $id The identifier of the folder (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Psr7\Request */ protected function foldersGetArxDriveConfigurationRequest($id) { // verify the required parameter 'id' is set if ($id === null) { throw new \InvalidArgumentException( 'Missing the required parameter $id when calling foldersGetArxDriveConfiguration' ); } $resourcePath = '/api/Folders/{id}/arxdriveinfo'; $formParams = []; $queryParams = []; $headerParams = []; $httpBody = ''; $multipart = false; // path params if ($id!== null) { $resourcePath = str_replace( '{'. 'id'. '}', ObjectSerializer::toPathValue($id), $resourcePath ); } // body params $_tempBody = null; if ($multipart) { $headers = $this->headerSelector->selectHeadersForMultipart( ['application/json', 'text/json', 'application/xml', 'text/xml'] ); } else { $headers = $this->headerSelector->selectHeaders( ['application/json', 'text/json', 'application/xml', 'text/xml'], [] ); } // for model (json/xml) if (isset($_tempBody)) { // $_tempBody is the method argument, if present $httpBody = $_tempBody; // \stdClass has no __toString(), so we should encode it manually if ($httpBody instanceof \stdClass && $headers['Content-Type'] === 'application/json') { $httpBody = \GuzzleHttp\json_encode($httpBody); } } elseif (count($formParams) > 0) { if ($multipart) { $multipartContents = []; foreach ($formParams as $formParamName => $formParamValue) { $multipartContents[] = [ 'name' => $formParamName, 'contents' => $formParamValue ]; } // for HTTP post (form) $httpBody = new MultipartStream($multipartContents); } elseif ($headers['Content-Type'] === 'application/json') { $httpBody = \GuzzleHttp\json_encode($formParams); } else { // for HTTP post (form) $httpBody = \GuzzleHttp\Psr7\build_query($formParams); } } // this endpoint requires API key authentication $apiKey = $this->config->getApiKeyWithPrefix('Authorization'); if ($apiKey!== null) { $headers['Authorization'] = $apiKey; } $defaultHeaders = []; if ($this->config->getUserAgent()) { $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); } $headers = array_merge( $defaultHeaders, $headerParams, $headers ); $query = \GuzzleHttp\Psr7\build_query($queryParams); return new Request( 'GET', $this->config->getHost(). $resourcePath. ($query? "?{$query}" : ''), $headers, $httpBody ); } /** * Operation foldersGetById * * This method return the folders contained in specified folder * * @param int $id The identifier of the folder (required) * * @throws \Swagger\Client\ApiException on non-2xx response * @throws \InvalidArgumentException * @return \Swagger\Client\Model\FolderDTO */ public function foldersGetById($id) { list($response) = $this->foldersGetByIdWithHttpInfo($id); return $response; } /** * Operation foldersGetByIdWithHttpInfo * * This method return the folders contained in specified folder * * @param int $id The identifier of the folder (required) * * @throws \Swagger\Client\ApiException on non-2xx response * @throws \InvalidArgumentException * @return array of \Swagger\Client\Model\FolderDTO, HTTP status code, HTTP response headers (array of strings) */ public function foldersGetByIdWithHttpInfo($id) { $returnType = '\Swagger\Client\Model\FolderDTO'; $request = $this->foldersGetByIdRequest($id); try { $options = $this->createHttpClientOption(); try { $response = $this->client->send($request, $options); } catch (RequestException $e) { throw new ApiException( "[{$e->getCode()}] {$e->getMessage()}", $e->getCode(), $e->getResponse()? $e->getResponse()->getHeaders() : null, $e->getResponse()? $e->getResponse()->getBody()->getContents() : null ); } $statusCode = $response->getStatusCode(); if ($statusCode < 200 || $statusCode > 299) { throw new ApiException( sprintf( '[%d] Error connecting to the API (%s)', $statusCode, $request->getUri() ), $statusCode, $response->getHeaders(), $response->getBody() ); } $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer } else { $content = $responseBody->getContents(); if ($returnType!=='string') { $content = json_decode($content); } } return [ ObjectSerializer::deserialize($content, $returnType, []), $response->getStatusCode(), $response->getHeaders() ]; } catch (ApiException $e) { switch ($e->getCode()) { case 200: $data = ObjectSerializer::deserialize( $e->getResponseBody(), '\Swagger\Client\Model\FolderDTO', $e->getResponseHeaders() ); $e->setResponseObject($data); break; } throw $e; } } /** * Operation foldersGetByIdAsync * * This method return the folders contained in specified folder * * @param int $id The identifier of the folder (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Promise\PromiseInterface */ public function foldersGetByIdAsync($id) { return $this->foldersGetByIdAsyncWithHttpInfo($id) ->then( function ($response) { return $response[0]; } ); } /** * Operation foldersGetByIdAsyncWithHttpInfo * * This method return the folders contained in specified folder * * @param int $id The identifier of the folder (required) * * @throws \InvalidArgumentException * @return \GuzzleHttp\Promise\PromiseInterface */ public function foldersGetByIdAsyncWithHttpInfo($id) { $returnType = '\Swagger\Client\Model\FolderDTO'; $request = $this->foldersGetByIdRequest($id); return $this->client ->sendAsync($request, $this->createHttpClientOption()) ->then( function ($response) use ($returnType) { $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer } else { $content = $responseBody->getContents(); if ($returnType!=='string') { $content = json_decode($content); } } return [ ObjectSerializer::deserialize($content, $returnType, []), $response->getStatusCode(), $response->getHeaders() ]; }, function ($exception) { $response = $exception->getResponse(); $statusCode = $response->getStatusCode(); throw new ApiException( sprintf( '[%d] Error connecting to the API (%s)',
1,504
Repo: Ghabry/mv-plugins ======================= File: OrangeLighting/OrangeLightingEventLight.js ======================= /*============================================================================= * Orange Lighting - Event Light * By Hudell - www.hudell.com * OrangeLightingEventLight.js * Version: 1.1 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Event Lights <OrangeLightingEventLight> * @author Hudell * * @param eventRadius * @desc The size of the light globe around the event by default * @default 40 * * @param eventColor * @desc The color of the light around the event by default * @default #FFFFFF * * @param eventFlicker * @desc Should the plugin flick the light around the event by default? * @default false * * @help * ============================================================================ * Hudell's Plugins * ============================================================================ * * Check out my website: * http://hudell.com * * ============================================================================ * Notetags * ============================================================================ * * <light> * This notetag will enable a light globe around the event * * <light_radius:40> * This notetag will let you configure the radius of the light globe * * <light_color:#FFFFFF> * This notetag will let you configure the color of the light globe * * <light_flickle:true> * This notetag will let you configure if the light globle should flickle * * <flashlight> * This notetag will activate a flashlight on the event * * ============================================================================ * Script Calls * ============================================================================ * * this.enableLight(); * This script call will enable a light globe around the event * * this.disableLight(); * This script call will disable all light effects on the event * * this.enableFlashlight(); * This script call will activate a flashlight on the event * * this.disableFlashlight(); * This script call will deactivate the flashlight on the event, but keep other effects active. * * this.enableEventLight(eventId); * This script call will enable a light globe around the event * * this.disableEventLight(eventId); * This script call will disable all light effects on the event * * this.enableEventFlashlight(eventId); * This script call will activate a flashlight on the event * * this.disableEventFlashlight(eventId); * This script call will deactivate the flashlight on the event, but keep other effects active. * *=============================================================================*/ if (!Hudell ||!Hudell.OrangeLighting) { throw new Error("Couldn't find Hudell's OrangeLighting plugin. Please add it before this add-on."); } (function(lightSystem) { "use strict"; lightSystem.addOns.EventLight = {}; (function(eventLight){ var parameters = $plugins.filter(function(plugin) { return plugin.description.contains('<OrangeLightingEventLight>'); }); if (parameters.length === 0) { throw new Error("Couldn't find Hudell's OrangeLightingEventLight parameters."); } eventLight.Parameters = parameters[0].parameters; eventLight.Param = {}; eventLight.Param.eventRadius = Number(eventLight.Parameters.eventRadius || 40); eventLight.Param.eventColor = eventLight.Parameters.eventColor || '#FFFFFF'; eventLight.Param.eventFlicker = (eventLight.Parameters.eventFlicker || "false").toUpperCase() === "TRUE"; eventLight.getEventPosition = function(event) { return lightSystem.getCharacterPosition(event); }; //Refreshes the event's light eventLight.refresh = function() { var events = $gameMap._events.filter(function(event){ return!!event &&!!event.orangeLight; }); if (events.length === 0) return; var canvas = this._maskBitmap.canvas; var ctx = canvas.getContext("2d"); ctx.globalCompositeOperation = 'lighter'; for (var i = 0; i < events.length; i++) { var eventData = events[i]; var positions = lightSystem.getCharacterPosition(eventData); var radius = eventData.orangeLight.radius || eventLight.Param.eventRadius; var color = eventData.orangeLight.color || eventLight.Param.eventColor; var flicker = eventData.orangeLight.flicker || eventLight.Param.eventFlicker; var flashlight = eventData.orangeLight.flashlight || false; if (flashlight) { this._maskBitmap.makeFlashlightEffect(positions[0], positions[1], 0, radius, color, 'black', positions[2]); } else { if (radius < 100) { this._maskBitmap.radialgradientFillRect(positions[0], positions[1], 0, radius, '#999999', 'black', flicker); } else { this._maskBitmap.radialgradientFillRect(positions[0], positions[1], 20, radius, color, 'black', flicker); } } } ctx.globalCompositeOperation ='source-over'; }; eventLight.update = function(){ }; lightSystem.on('afterRefreshMask', eventLight.refresh); lightSystem.on('updateMask', eventLight.update); (function($){ $.enableEventLight = function(eventId, flashlight, radius, color, flicker) { if (eventId > 0) { var eventData = $gameMap.event(eventId); if (eventData) { eventData.enableLight(flashlight, radius, color, flicker); } } }; $.disableEventLight = function(eventId) { if (eventId > 0) { var eventData = $gameMap.event(eventId); if (eventData) { eventData.disableLight(); } } }; $.enableEventFlashlight = function(eventId) { this.enableEventLight(eventId, true); }; $.disableEventFlashlight = function(eventId) { this.enableEventLight(eventId, false); }; $.enableLight = function(flashlight, radius, color, flicker) { this.enableEventLight(this._eventId, flashlight, radius, color, flicker); }; $.disableLight = function() { this.disableEventLight(this._eventId); }; $.enableFlashlight = function() { this.enableEventLight(this._eventId, true); }; $.disableFlashlight = function() { this.enableEventLight(this._eventId, false); }; })(Game_Interpreter.prototype); (function($) { $.enableLight = function(flashlight, radius, color, flicker) { this.orangeLight = { flashlight : flashlight, radius : radius, color : color, flicker : flicker }; lightSystem.dirty = true; }; $.disableLight = function() { this.orangeLight = undefined; lightSystem.dirty = true; }; $.enableFlashlight = function() { this.enableLight(true); }; $.disableFlashlight = function() { this.enableLight(false); }; eventLight.Game_Event_prototype_update = $.update; $.update = function(sceneActive) { var oldD = this._direction; var oldX = this._x; var oldY = this._y; eventLight.Game_Event_prototype_update.call(this, sceneActive); if (!this.orangeLight) return; if (this.isMoving() || oldD!== this._direction || oldX!== this._x || oldY!== this._y) { lightSystem.dirty = true; } }; $.checkNoteTags = function(){ if (!this.event().meta) return; var orangeLight = { flashlight : false, flicker : eventLight.Param.eventFlicker, radius : eventLight.Param.eventRadius, color : eventLight.Param.eventColor }; var add = false; if (this.event().meta.light_radius!== undefined) { add = true; orangeLight.radius = this.event().meta.light_radius; } if (this.event().meta.light_color!== undefined) { add = true; orangeLight.color = this.event().meta.light_color; } if (this.event().meta.light_flickle!== undefined) { add = true; orangeLight.flicker = this.event().meta.light_flickle; } if (this.event().meta.light_flickler!== undefined) { add = true; orangeLight.flicker = this.event().meta.light_flickler; } if (this.event().meta.light_flicker!== undefined) { add = true; orangeLight.flicker = this.event().meta.light_flicker; } if (this.event().meta.light) { add = true; } if (this.event().meta.flashlight) { add = true; orangeLight.flashlight = true; } if (add) { this.orangeLight = orangeLight; } else { this.orangeLight = undefined; } }; eventLight.Game_Event_prototype_initialize = $.initialize; $.initialize = function(mapId, eventId) { eventLight.Game_Event_prototype_initialize.call(this, mapId, eventId); this.checkNoteTags(); }; })(Game_Event.prototype); })(lightSystem.addOns.EventLight); })(Hudell.OrangeLighting); Imported["OrangeLighting.EventLight"] = 1.1; ======================= File: OrangeChangeSaveFileName.js ======================= <gh_stars>10-100 /*============================================================================= * Orange - Change Save File Name * By Hudell - www.hudell.com * OrangeChangeSaveFileName.js * Version: 1.0 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc This plugin will help you change the base name of the save files * @author Hudell * * @param localFilePattern * @desc The pattern for the local file name. Include '%1' on the position where you want the number of the save file to be. * @default file%1.rpgsave * * @param webStorageKeyPattern * @desc The pattern for web storage key name. Include '%1' on the position where you want the number of the save file to be. * @default RPG File%1 * * @help * ============================================================================ * Latest Version * ============================================================================ * * Get the latest version of this script on http://link.hudell.com/savefilename * *=============================================================================*/ var Imported = Imported || {}; var OrangeChangeSaveFileName = OrangeChangeSaveFileName || {}; (function($) { "use strict"; $.Parameters = PluginManager.parameters('OrangeChangeSaveFileName'); // If a new localFilePattern was defined, alias the localFilePath method // from the StorageManager and use the new pattern if ($.Parameters["localFilePattern"]!== undefined) { var saveFilePattern = $.Parameters["localFilePattern"] || "file%1.rpgsave"; var oldStorageManager_localFilePath = StorageManager.localFilePath; StorageManager.localFilePath = function(savefileId) { if (savefileId <= 0) { return oldStorageManager_localFilePath.call(this, savefileId); } var name = saveFilePattern.format(savefileId); return this.localFileDirectoryPath() + name; }; } // If a new webStorageKeyPattern was defined, alias the webStorageKey method // from the StorageManager and use the new pattern if ($.Parameters["webStorageKeyPattern"]!== undefined) { var webStorageKeyPattern = $.Parameters["webStorageKeyPattern"] || "RPG File%1"; var oldStorageManager_webStorageKey = StorageManager.webStorageKey; StorageManager.webStorageKey = function(savefileId) { if (savefileId <= 0) { return oldStorageManager_webStorageKey.call(this, savefileId); } return webStorageKeyPattern.format(savefileId); }; } })(OrangeChangeSaveFileName); Imported["OrangeChangeSaveFileName"] = 1; ======================= File: OrangeTimeSystem/OrangeTimeSystemVariables.js ======================= <filename>OrangeTimeSystem/OrangeTimeSystemVariables.js /*============================================================================= * Orange - Time System Variables * By Hudell - www.hudell.com * OrangeTimeSystemVariables.js * Version: 1.4 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Exports Orange Time System data to variables * * @author Hudell * * @param secondVariable * @desc The number of the variable where you want to store the seconds * @default 0 * * @param minuteVariable * @desc The number of the variable where you want to store the minutes * @default 0 * * @param hourVariable * @desc The number of the variable where you want to store the hours * @default 0 * * @param dayVariable * @desc The number of the variable where you want to store the days * @default 0 * * @param monthVariable * @desc The number of the variable where you want to store the months * @default 0 * * @param yearVariable * @desc The number of the variable where you want to store the years * @default 0 * * @param weekDayVariable * @desc The number of the variable where you want to store the week day * @default 0 * * @param dayPeriodVariable * @desc The number of the variable where you want to store the day period * @default 0 * * @param monthNameVariable * @desc The number of the variable where you want to store the name of the month * @default 0 * * @param monthShortNameVariable * @desc The number of the variable where you want to store the short name of the month * @default 0 * * @param dayNameVariable * @desc The number of the variable where you want to store the name of the day * @default 0 * * @param dayShortNameVariable * @desc The number of the variable where you want to store the short name of the day * @default 0 * * @help * ============================================================================ * Latest Version * ============================================================================ * * Get the latest version of this script on * http://link.hudell.com/time-system-variables * *=============================================================================*/ var Imported = Imported || {}; var OrangeTimeSystemVariables = OrangeTimeSystemVariables || {}; if (Imported["OrangeTimeSystem"] === undefined) { console.log('Download MVCommons: http://link.hudell.com/time-system'); throw new Error("This library requires the OrangeTimeSystem!"); } (function($) { "use strict"; $.Parameters = PluginManager.parameters('OrangeTimeSystemVariables'); $.Param = $.Param || {}; $.Param.secondVariable = Number($.Parameters.secondVariable || 0); $.Param.minuteVariable = Number($.Parameters.minuteVariable || 0); $.Param.hourVariable = Number($.Parameters.hourVariable || 0); $.Param.dayVariable = Number($.Parameters.dayVariable || 0); $.Param.monthVariable = Number($.Parameters.monthVariable || 0); $.Param.yearVariable = Number($.Parameters.yearVariable || 0); $.Param.weekDayVariable = Number($.Parameters.weekDayVariable || 0); $.Param.dayPeriodVariable = Number($.Parameters.dayPeriodVariable || 0); $.Param.monthNameVariable = Number($.Parameters.monthNameVariable || 0); $.Param.monthShortNameVariable = Number($.Parameters.monthShortNameVariable || 0); $.Param.dayNameVariable = Number($.Parameters.dayNameVariable || 0); $.Param.dayShortNameVariable = Number($.Parameters.dayShortNameVariable || 0); $.configureVariables = function() { if ($gameVariables === undefined || $gameVariables === null) return; if ($.Param.secondVariable!== undefined && $.Param.secondVariable > 0) { $gameVariables.setValue($.Param.secondVariable, OrangeTimeSystem.seconds); } if ($.Param.minuteVariable!== undefined && $.Param.minuteVariable > 0) { $gameVariables.setValue($.Param.minuteVariable, OrangeTimeSystem.minute); } if ($.Param.hourVariable!== undefined && $.Param.hourVariable > 0) { $gameVariables.setValue($.Param.hourVariable, OrangeTimeSystem.hour); } if ($.Param.dayVariable!== undefined && $.Param.dayVariable > 0) { $gameVariables.setValue($.Param.dayVariable, OrangeTimeSystem.day); } if ($.Param.monthVariable!== undefined && $.Param.monthVariable > 0) { $gameVariables.setValue($.Param.monthVariable, OrangeTimeSystem.month); } if ($.Param.yearVariable!== undefined && $.Param.yearVariable > 0) { $gameVariables.setValue($.Param.yearVariable, OrangeTimeSystem.year); } if ($.Param.weekDayVariable!== undefined && $.Param.weekDayVariable > 0) { $gameVariables.setValue($.Param.weekDayVariable, OrangeTimeSystem.weekDay); } if ($.Param.dayPeriodVariable!== undefined && $.Param.dayPeriodVariable > 0) { $gameVariables.setValue($.Param.dayPeriodVariable, OrangeTimeSystem.dayPeriod); } if ($.Param.monthNameVariable!== undefined && $.Param.monthNameVariable > 0) { $gameVariables.setValue($.Param.monthNameVariable, OrangeTimeSystem.monthName); } if ($.Param.monthShortNameVariable!== undefined && $.Param.monthShortNameVariable > 0) { $gameVariables.setValue($.Param.monthShortNameVariable, OrangeTimeSystem.monthShortName); } if ($.Param.dayNameVariable!== undefined && $.Param.dayNameVariable > 0) { $gameVariables.setValue($.Param.dayNameVariable, OrangeTimeSystem.dayName); } if ($.Param.dayShortNameVariable!== undefined && $.Param.dayShortNameVariable > 0) { $gameVariables.setValue($.Param.dayShortNameVariable, OrangeTimeSystem.dayShortName); } }; var oldGameVariablesSetValue = Game_Variables.prototype.setValue; Game_Variables.prototype.setValue = function(variableId, value) { oldGameVariablesSetValue.apply(this, arguments); var changed = false; if (variableId == $.Param.secondVariable) { OrangeTimeSystem.seconds = value; changed = true; } if (variableId == $.Param.minuteVariable) { OrangeTimeSystem.minute = value; changed = true; } if (variableId == $.Param.hourVariable) { OrangeTimeSystem.hour = value; changed = true; } if (variableId == $.Param.dayVariable) { OrangeTimeSystem.day = value; changed = true; } if (variableId == $.Param.monthVariable) { OrangeTimeSystem.month = value; changed = true; } if (variableId == $.Param.yearVariable) { OrangeTimeSystem.year = value; changed = true; } if (changed) { OrangeTimeSystem.updateTime(); } }; // Updates the variables every in-game second OrangeTimeSystem.on('changeTime', $.configureVariables); })(OrangeTimeSystemVariables); Imported.OrangeTimeSystemVariables = 1.4; ======================= File: OrangeHud/OrangeHudVariablePicture.js ======================= <gh_stars>10-100 /*============================================================================= * Orange - Variable Picture HUD * By HUDell - www.hudell.com * OrangeHudVariablePicture.js * Version: 1.6 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc OrangeHudVariablePicture 1.5.1 - Adds a new Variable Picture to Orange Hud * @author Hudell * * @param GroupName * @desc The name of the HUD group where this line should be displayed * @default main * * @param Pattern * @desc The pattern of the picture file name that will be drawn * @default %1 * * @param VariableId * @desc The number of the variable that will be used to control this picture. * @default 1 * * @param SwitchId * @desc Set this to a switch number to use it to control the visibility of this line * @default 0 * * @param X * @desc The X position of the variable line inside the HUD * @default * * @param Y * @desc The Y position of the variable line inside the HUD * @default * * @param ScriptPattern * @desc A script call to be used to decide the filename of the picture instead of the pattern * @default * * @param VariableX * @desc The number of the variable that holds the X position of the picture inside the HUD * @default 0 * * @param VariableY * @desc The number of the variable that holds the Y position of the picture inside the HUD * @default 0 * * @param CommonEventId * @desc Number of a common event to call if the player clicks on this picture * @default * * @help * ============================================================================ * My Blog: * ============================================================================ * http://hudell.com * */ var Imported = Imported || {}; if (Imported["OrangeHud"] === undefined) { throw new Error("Please add OrangeHud before OrangeHudVariablePicture!"); } if (Imported["OrangeHud"] < 1.7) { throw new Error("Please update OrangeHud!"); } var OrangeHudVariablePicture = OrangeHudVariablePicture || {}; if (Imported["OrangeHudVariablePicture"] === undefined) { OrangeHudVariablePicture.validateParams = function(paramsLine) { paramsLine.GroupName = paramsLine.GroupName || "main"; if (paramsLine.ScriptPattern!== undefined && paramsLine.ScriptPattern.trim() === "") { paramsLine.ScriptPattern = undefined; } if (paramsLine.Pattern === undefined) { paramsLine.Pattern = "%1"; } else if (paramsLine.Pattern.trim() === "") { paramsLine.Pattern = ""; } paramsLine.VariableId = Number(paramsLine.VariableId || 0); paramsLine.X = Number(paramsLine.X || 0); paramsLine.Y = Number(paramsLine.Y || 0); paramsLine.VariableX = Number(paramsLine.VariableX || 0); paramsLine.VariableY = Number(paramsLine.VariableY || 0); paramsLine.CommonEventId = Number(paramsLine.CommonEventId || 0); paramsLine.SwitchId = Number(paramsLine.SwitchId || 0); if (paramsLine.CommonEventId > 0) { var key = OrangeHudVariablePicture.getKey(paramsLine); this.images = this.images || {}; this.images[key] = this.images[key] || {}; var alias = TouchInput._onMouseDown; var me = this; TouchInput._onMouseDown = function(event) { if (paramsLine.SwitchId > 0) { if (!$gameSwitches.value(paramsLine.SwitchId)) { return; } } var x = Graphics.pageToCanvasX(event.pageX); var y = Graphics.pageToCanvasY(event.pageY); var width = me.images[key].width; var height = me.images[key].height; if (width!== undefined && height!== undefined) { var imageX = me.realX(paramsLine) + OrangeHud.Param.HudX + OrangeHud.Param.WindowMargin + OrangeHud.Param.WindowPadding; var imageY = me.realY(paramsLine) + OrangeHud.Param.HudY + OrangeHud.Param.WindowMargin + OrangeHud.Param.WindowPadding; if (x >= imageX && y >= imageY) { if (x <= imageX + width && y <= imageY + height) { $gameTemp.reserveCommonEvent(paramsLine.CommonEventId); return; } } } // If the click wasn't triggered, call the alias to keep the mouseDown event happening alias.call(this, event); }; } }; OrangeHudVariablePicture.realX = function(variableData) { var x = variableData.X; if (variableData.VariableX > 0) { x = $gameVariables.value(variableData.VariableX); } return x; }; OrangeHudVariablePicture.realY = function(variableData) { var y = variableData.Y; if (variableData.VariableY > 0) { y = $gameVariables.value(variableData.VariableY); } return y; }; OrangeHudVariablePicture.drawLine = function(hudWindow, variableData) { if (variableData.SwitchId > 0) { if (!$gameSwitches.value(variableData.SwitchId)) { return; } } var filename = this.getFileName(variableData); x = this.realX(variableData); y = this.realY(variableData); var bitmap = ImageManager.loadPicture(filename); bitmap.addLoadListener(function(){ OrangeHud.setDirty(); }); var key = OrangeHudVariablePicture.getKey(variableData); this.images = this.images || {}; this.images[key] = this.images[key] || {}; this.images[key].width = bitmap._canvas.width; this.images[key].height = bitmap._canvas.height; this.drawPicture(hudWindow, filename, x, y, variableData); }; OrangeHudVariablePicture.drawPicture = function(hudWindow, filename, x, y, variableData) { hudWindow.drawPicture(filename, x, y); }; OrangeHudVariablePicture.getValue = function(variableData) { if (variableData.VariableId > 0) { return $gameVariables.value(variableData.VariableId); } else { return 0; } }; OrangeHudVariablePicture.getFileName = function(variableData) { var pattern = variableData.Pattern; if (variableData.ScriptPattern!== undefined) { pattern = Function("return " + variableData.ScriptPattern)(); } var varValue = ''; if (variableData.VariableId > 0) { varValue = Number($gameVariables.value(variableData.VariableId)); } return pattern.format(varValue); }; OrangeHudVariablePicture.getKey = function(variableData) { return variableData.VariableId; }; OrangeHud.registerLineType('OrangeHudVariablePicture', OrangeHudVariablePicture); Imported["OrangeHudVariablePicture"] = 1.6; } ======================= File: OrangeEventManager/OrangeEventManager.js ======================= /*============================================================================= * Orange - Event Manager * By Hudell - www.hudell.com * OrangeEventManager.js * Version: 1.2 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Provides an event listener interface to any plugin * * @author Hudell * * @help * ============================================================================ * Latest Version * ============================================================================ * * Get the latest version of this script on * http://link.hudell.com/event-manager * *=============================================================================*/ var Imported = Imported || {}; var OrangeEventManager = OrangeEventManager || {}; (function($) { "use strict"; $._events = []; var oldGameTemp_initialize = Game_Temp.prototype.initialize; Game_Temp.prototype.initialize = function() { oldGameTemp_initialize.call(this); this._orangeCommonEvents = []; }; Game_Temp.prototype.reserveOrangeCommonEvent = function(commonEventId) { if (commonEventId > 0) { this._orangeCommonEvents = this._orangeCommonEvents || []; this._orangeCommonEvents.push(commonEventId); } }; var oldGameInterpreter_setupReservedCommonEvent = Game_Interpreter.prototype.setupReservedCommonEvent; Game_Interpreter.prototype.setupReservedCommonEvent = function() { if (!$gameTemp) return false; var result = oldGameInterpreter_setupReservedCommonEvent.call(this); if (result) return result; if (!$gameTemp._orangeCommonEvents) return result; if ($gameTemp._orangeCommonEvents.length > 0) { var commonEventId = $gameTemp._orangeCommonEvents.shift(); var commonEvent = $dataCommonEvents[commonEventId]; this.setup(commonEvent.list); return true; } return result; }; $.on = function(eventName, callback) { if (this._events[eventName] === undefined) this._events[eventName] = []; this._events[eventName].push(callback); }; $.un = function(eventName, callback) { if (this._events[eventName] === undefined) return; for (var i = 0; i < this._events[eventName].length; i++) { if (this._events[eventName][i] == callback) { this._events[eventName][i] = undefined; return; } } }; $.executeCallback = function(callback) { if (typeof(callback) == "function") { return callback.call(this); } if (typeof(callback) == "number") { $gameTemp.reserveOrangeCommonEvent(callback); return true; } if (typeof(callback) == "string") { var id = parseInt(callback, 10); if (parseInt(callback, 10) == callback.trim()) { $gameTemp.reserveOrangeCommonEvent(parseInt(callback, 10)); return true; } else if (callback.substr(0, 2) == 'SS') { //Self Switch var selfSwitchData = callback.split(','); var usedData = [0, 0, 'A', 'TRUE']; for (var i = 0; i < selfSwitchData.length; i++) { if (usedData.length > i) { usedData[i] = selfSwitchData[i]; } } var mapId = parseInt(usedData[0].substr(2), 10); var eventId = parseInt(usedData[1], 10); var switchName = usedData[2].toUpperCase(); var switchValue = usedData[3].toUpperCase(); var key = [mapId, eventId, switchName]; if (!!$gameSelfSwitches) { if (switchValue == 'TOGGLE') { switchValue =!$gameSelfSwitches.value(key); } else if (switchValue === 'FALSE' || switchValue === 'OFF') { switchValue = false; } else { switchValue = true; } $gameSelfSwitches.setValue(key, switchValue); return true; } else { return false; } } else if (callback.substr(0, 1) == 'S') { //Switch var data = callback.split(','); var value = 'TRUE'; if (data.length >= 2) { value = data[1].toUpperCase(); } id = parseInt(data[0].substr(1)); if (!!$gameSwitches) { if (value == 'TOGGLE') { value =!$gameSwitches.value(id); } else if (value === 'FALSE' || value === 'OFF') { value = false; } else { value = true; } $gameSwitches.setValue(id, value); return true; } else { return false; } } return eval(callback); } console.error("Unknown callback type: ", callback); return undefined; }; $.runEvent = function(eventName) { if (this._events[eventName] === undefined) return; for (var i = 0; i < this._events[eventName].length; i++) { var callback = this._events[eventName][i]; if (this.executeCallback(callback) === false) { break; } } }; })(OrangeEventManager); Imported.OrangeEventManager = 1.2; ======================= File: OrangeNoteTagToSwitch.js ======================= /*============================================================================= * Orange - Notetag to Switch * By Hudell - www.hudell.com * OrangeNoteTagToSwitch.js * Version: 1.2 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Allow you to automatically turn on a switch everytime a notetag is found on a map - OrangeNoteTagToSwitch * @author Hudell * * @param switchId * @desc The number of the switch to activate when the notetag is found * @default 0 * * @param notetag * @desc The name of the notetag to look for on the maps notes * @default 0 * * @param noteList * @desc Configure several notes with a single plugin using this param * @default * * @help * Add the <notetag> on the notes of the maps that you want to tag. * * This plugin can be added multiple times to the same project * (just make a copy of the file and add it) * * ============================================================================ * Latest Version * ============================================================================ * * Get the latest version of this script on * http://hudell.com * *=============================================================================*/ var Imported = Imported || {}; if (Imported["OrangeNoteTagToSwitch"] === undefined) { (function() { "use strict"; var getProp = undefined; if (Imported["MVCommons"]!== undefined) { getProp = MVC.getProp; } else { getProp = function (meta, propName){ if (meta === undefined) return undefined; if (meta[propName]!== undefined) return meta[propName]; for (var key in meta) { if (key.toLowerCase() == propName.toLowerCase()) { return meta[key]; } } return undefined; }; } var paramList = []; function updateParamList(){ for (var i = 0; i < $plugins.length; i++) { if ($plugins[i].description.indexOf('OrangeNoteTagToSwitch') >= 0) { var switchId = Number($plugins[i].parameters['switchId'] || 0); var notetagName = $plugins[i].parameters['notetag'] || ''; if (switchId > 0 && notetagName.trim().length > 0) { paramList.push({ switchId : switchId, notetagName : notetagName }); } var list = $plugins[i].parameters['noteList']; if (list!== undefined) { var re = /<([^<>:]+):([^>]*)>/g; while(true) { var match = re.exec(list); if (match) { notetagName = match[1]; switchId = Number(match[2] || 0); if (switchId > 0 && notetagName.trim().length > 0) { paramList.push({ switchId : switchId, notetagName : notetagName }); } } else { break; } } } } } } updateParamList(); if (paramList.length > 0) { var updateSwitchList = function() { if (SceneManager._scene instanceof Scene_Map) { for (var i = 0; i < paramList.length; i++) { var value = undefined; if ($gameMap._interpreter.isRunning() && $gameMap._interpreter._eventId > 0) { var eventData = $dataMap.events[$gameMap._interpreter._eventId]; if (eventData) { value = getProp(eventData.meta, paramList[i].notetagName); } } if (value === undefined) { value = getProp($dataMap.meta, paramList[i].notetagName) === true; } $gameSwitches.setValue(paramList[i].switchId, value); } } }; var oldGameInterpreter_setup = Game_Interpreter.prototype.setup; Game_Interpreter.prototype.setup = function(list, eventId) { oldGameInterpreter_setup.call(this, list, eventId); updateSwitchList(); }; var oldGameInterpreter_terminate = Game_Interpreter.prototype.terminate; Game_Interpreter.prototype.terminate = function(list, eventId) { oldGameInterpreter_terminate.call(this, list, eventId); updateSwitchList(); }; var oldGamePlayer_performTransfer = Game_Player.prototype.performTransfer; Game_Player.prototype.performTransfer = function() { var shouldUpdateSwitchList = this.isTransferring(); oldGamePlayer_performTransfer.call(this); if (shouldUpdateSwitchList) { updateSwitchList(); } }; } })(); Imported["OrangeNoteTagToSwitch"] = 1.2; } ======================= File: OrangeHud/OrangeHudClock.js ======================= /*============================================================================= * Orange - Clock HUD * By HUDell - www.hudell.com * OrangeHudClock.js * Version: 1.5 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Adds a new Variable to Orange Hud * @author Hudell * * @param GroupName * @desc The name of the HUD group where this line should be displayed * @default main * * @param Pattern * @desc The pattern of the line that will be drawn * @default %1:%2:%3 * * @param VariableHour * @desc The number of the variable that holds the Hour value. * @default 0 * * @param VariableMinute * @desc The number of the variable that holds the Minute value. * @default 0 * * @param VariableSecond * @desc The number of the variable that holds the Second value. * @default 0 * * @param SwitchId * @desc Set this to a switch number to use it to control the visibility of this line * @default 0 * * @param X * @desc The X position of the variable line inside the HUD * @default * * @param Y * @desc The Y position of the variable line inside the HUD * @default * * @param FontFace * @desc The font face to use. Leave empty to use the HUD default * @default * * @param FontSize * @desc The font size to use. Leave empty to use the HUD default * @default * * @param FontColor * @desc The font color to use. Leave empty to use the HUD default * @default * * @param FontItalic * @desc Should use italic? Leave empty to use the HUD default * @default * * @param ScriptPattern * @desc A script call to be used instead of the Pattern * @default * * @help * ============================================================================ * My Blog: * ============================================================================ * http://hudell.com * */ var Imported = Imported || {}; if (Imported["OrangeHud"] === undefined) { throw new Error("Please add OrangeHud before OrangeHudClock!"); } var OrangeHudClock = OrangeHudClock || {}; if (Imported["OrangeHudClock"] === undefined) { OrangeHudClock.validateParams = function(line) { line.GroupName = line.GroupName || "main"; if (line.ScriptPattern!== undefined && line.ScriptPattern.trim() === "") { line.ScriptPattern = undefined; } if (line.Pattern === undefined) { line.Pattern = "%1:%2:%3"; } else if (line.Pattern.trim() === "") { line.Pattern = ""; } line.VariableHour = Number(line.VariableHour || 0); line.VariableMinute = Number(line.VariableMinute || 0); line.VariableSecond = Number(line.VariableSecond || 0); if (line.FontFace === undefined || line.FontFace.trim() === "") { line.FontFace = OrangeHud.Param.DefaultFontFace; } if (line.FontColor === undefined || line.FontColor.trim() === "") { line.FontColor = OrangeHud.Param.DefaultFontColor; } line.FontSize = Number(line.FontSize || OrangeHud.Param.DefaultFontSize); line.X = Number(line.X || 0); line.Y = Number(line.Y || 0); if (line.FontItalic === undefined || line.FontItalic.trim() === "") { line.FontItalic = OrangeHud.Param.DefaultFontItalic; } else { line.FontItalic = line.FontItalic == "true"; } line.SwitchId = Number(line.SwitchId || 0); }; OrangeHudClock.drawLine = function(window, variableData) { if (variableData.SwitchId > 0) { if (!$gameSwitches.value(variableData.SwitchId)) { return; } } var line = this.getValue(variableData); window.contents.fontFace = variableData.FontFace; window.contents.fontSize = variableData.FontSize; window.contents.fontItalic = variableData.FontItalic; window.changeTextColor(variableData.FontColor); window.drawTextEx(line, variableData.X, variableData.Y); window.resetFontSettings(); }; OrangeHudClock.getValue = function(variableData) { var pattern = variableData.Pattern; if (variableData.ScriptPattern!== undefined) { pattern = Function("return " + variableData.ScriptPattern)(); } var hour = ''; var minute = ''; var second = ''; if (variableData.VariableHour > 0) { hour = Number($gameVariables.value(variableData.VariableHour)).padZero(2); } if (variableData.VariableMinute > 0) { minute = Number($gameVariables.value(variableData.VariableMinute)).padZero(2); } if (variableData.VariableSecond > 0) { second = Number($gameVariables.value(variableData.VariableSecond)).padZero(2); } return pattern.format(hour, minute, second); }; OrangeHudClock.getKey = function(variableData) { return variableData.VariableHour + ',' + variableData.VariableMinute + ',' + variableData.VariableSecond; }; OrangeHud.registerLineType('OrangeHudClock', OrangeHudClock); Imported["OrangeHudClock"] = 1.5; } ======================= File: OrangeDisableRefresh.js ======================= /*============================================================================= * Orange - DisableRefresh * By Hudell - www.hudell.com * OrangeDisableRefresh.js * Version: 1.0 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Disables F5 Refresh <OrangeDisableRefresh> * @author Hudell * * @help * ============================================================================ * Hudell's Plugins * ============================================================================ * * Check out my website: * http://hudell.com * *=============================================================================*/ var Imported = Imported || {}; var Hudell = Hudell || {}; Hudell.OrangeDisableRefresh = Hudell.OrangeDisableRefresh || {}; (function($) { $.oldSceneManager_onKeyDown = SceneManager.onKeyDown; SceneManager.onKeyDown = function(event) { if (event.keyCode == 116) return; $.oldSceneManager_onKeyDown.call(this, event); }; })(Hudell.OrangeDisableRefresh); OrangeDisableRefresh = Hudell.OrangeDisableRefresh; Imported.OrangeDisableRefresh = 1.0; ======================= File: OrangeEventHitboxes.js ======================= <reponame>Ghabry/mv-plugins /*============================================================================= * Orange - Event Hitboxes * By Hudell - www.hudell.com * OrangeEventHitboxes.js * Version: 1.1 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Allows the configuration of custom hitboxes for events * @author Hudell * @help * ============================================================================ * Instructions * ============================================================================ * This plugin REQUIRES MVCommons: http://link.hudell.com/mvcommons * * There are 4 tags that can be used to configure the event hitboxes: * <hitboxX:0> * <hitboxY:0> * <hitboxWidth:1> * <hitboxHeight:1> * * The hitboxX and hitboxY tags are used to relocate the top left position of * the hitbox. The default value is 0 * The hitboxWidth and hitboxHeight tags are used to resize the hitbox. The * default value is 1. * * All values are on tiles. If you change hitboxX to -1: * <hitboxX:-1> * then the hitbox will start one tile to left of where it would usually start * * Those tags can be added to the event notes. If you want a different * size for a specific page, you can add those tags on a comment on that page * and the plugin will understand that it should use that configuration * for that specific page. * * ============================================================================ * Latest Version * ============================================================================ * * Get the latest version of this script on http://link.hudell.com/event-hitboxes * */ var Imported = Imported || {}; if (Imported.MVCommons === undefined) { var MVC = MVC || {}; (function($){ $.defaultGetter = function(name) { return function () { return this['_' + name]; }; }; $.defaultSetter = function(name) { return function (value) { var prop = '_' + name; if ((!this[prop]) || this[prop]!== value) { this[prop] = value; if (this._refresh) { this._refresh(); } } }; }; $.accessor = function(value, name /*, setter, getter */) { Object.defineProperty(value, name, { get: arguments.length > 3? arguments[3] : $.defaultGetter(name), set: arguments.length > 2? arguments[2] : $.defaultSetter(name), configurable: true });}; $.reader = function(obj, name /*, getter */) { Object.defineProperty(obj, name, { get: arguments.length > 2? arguments[2] : defaultGetter(name), configurable: true }); }; $.getProp = function(meta, propName){ if (meta === undefined) return undefined; if (meta[propName]!== undefined) return meta[propName]; for (var key in meta) { if (key.toLowerCase() == propName.toLowerCase()) { return meta[key]; } } return undefined; }; $.extractEventMeta = function(event) { var the_event = event; if (the_event instanceof Game_Event) { the_event = event.event(); } var pages = the_event.pages; if (pages === undefined) return; var re = /<([^<>:]+)(:?)([^>]*)>/g; for (var i = 0; i < pages.length; i++) { var page = pages[i]; page.meta = page.meta || {}; for (var j = 0; j < page.list.length; j++) { var command = page.list[j]; if (command.code!== 108 && command.code!== 408) continue; for (;;) { var match = re.exec(command.parameters[0]); if (match) { if (match[2] === ':') { page.meta[match[1]] = match[3]; } else { page.meta[match[1]] = true; } } else { break; } } } } }; })(MVC); Number.prototype.fix = function() { return parseFloat(this.toPrecision(12)); }; Number.prototype.floor = function() { return Math.floor(this.fix()); }; } var OrangeEventHitboxes = OrangeEventHitboxes || {}; (function($) { "use strict"; // Creates an accessor for the hitboxX property, // It's value is read from the notetags and then cached. It can also be changed // manually. Default is 0. MVC.accessor(Game_Event.prototype, 'hitboxX', function(value) { this._hitboxX = value; this._canClearHitboxX = false; }, function() { if (this._hitboxX === undefined) { var size = this.findNoteTagValue('hitboxX'); if (size!== undefined) { size = parseInt(size, 10); } if (typeof(size) == "number") { this._hitboxX = size; } else { this._hitboxX = 0; } this._canClearHitboxX = true; } return this._hitboxX; }); // Creates an accessor for the hitboxY property, // It's value is read from the notetags and then cached. It can also be changed // manually. Default is 0. MVC.accessor(Game_Event.prototype, 'hitboxY', function(value) { this._hitboxY = value; this._canClearHitboxY = false; }, function() { if (this._hitboxY === undefined) { var size = this.findNoteTagValue('hitboxY'); if (size!== undefined) { size = parseInt(size, 10); } if (typeof(size) == "number") { this._hitboxY = size; } else { this._hitboxY = 0; } this._canClearHitboxY = true; } return this._hitboxY; }); // Creates an accessor for the hitboxWidth property, // It's value is read from the notetags and then cached. It can also be changed // manually. Default is 1. MVC.accessor(Game_Event.prototype, 'hitboxWidth', function(value) { this._hitboxWidth = value; this._canClearHitboxWidth = false; }, function() { if (this._hitboxWidth === undefined) { var size = this.findNoteTagValue('hitboxWidth'); if (size!== undefined) { size = parseInt(size, 10); } if (typeof(size) == "number") { this._hitboxWidth = size; } else { this._hitboxWidth = 1; } this._canClearHitboxWidth = true; } return this._hitboxWidth; }); // Creates an accessor for the hitboxHeight property, // It's value is read from the notetags and then cached. It can also be changed // manually. Default is 1. MVC.accessor(Game_Event.prototype, 'hitboxHeight', function(value) { this._hitboxHeight = value; this._canClearHitboxHeight = false; }, function() { if (this._hitboxHeight === undefined) { var size = this.findNoteTagValue('hitboxHeight'); if (size!== undefined) { size = parseInt(size, 10); } if (typeof(size) == "number") { this._hitboxHeight = size; } else { this._hitboxHeight = 1; } this._canClearHitboxHeight = true; } return this._hitboxHeight; }); // Quick reader for the left position of the hitbox MVC.reader(Game_Event.prototype, 'left', function() { return (this._x + this.hitboxX).fix(); }); // Quick reader for the top position of the hitbox MVC.reader(Game_Event.prototype, 'top', function() { return (this._y + this.hitboxY).fix(); }); // Quick reader for the right position of the hitbox MVC.reader(Game_Event.prototype, 'right', function() { return (this.left + this.hitboxWidth).fix(); }); // Quick reader for the bottom position of the hitbox MVC.reader(Game_Event.prototype, 'bottom', function() { return (this.top + this.hitboxHeight).fix(); }); // Adds a method that searches for a notetag value on all comments of the page Game_Event.prototype.findNoteTagValue = function(notetag) { var page = this.page(); if (page === undefined) return false; if (page.meta === undefined) { MVC.extractEventMeta(this); } var result; if (page.meta!== undefined) { result = MVC.getProp(page.meta, notetag); } if (result === undefined) { return MVC.getProp(this.event().meta, notetag); } else { return result; } }; // Adds a method that checks if the event is using the default hitbox, // in which case some methods don't need to be changed. Game_Event.prototype.isUsingDefaultHitbox = function() { return (this.hitboxX === 0 && this.hitboxY === 0 && this.hitboxWidth === 1 && this.hitboxHeight === 1); }; // Alias the method pos of the Game_Event class to check if the event // is on a specified position. If the event hitbox wasn't changed, the old // method is run instead. var oldGameEvent_pos = Game_Event.prototype.pos; Game_Event.prototype.pos = function(x, y) { if (this.isUsingDefaultHitbox()) { return oldGameEvent_pos.call(this, x, y); } else { return (x >= this.left && x < this.right && y >= this.top && y < this.bottom); } }; // Alias the setupPage method from the Game_Event class to clear the // hitbox cache (because the event can use a different cache for each page) var oldGameEvent_setupPage = Game_Event.prototype.setupPage; Game_Event.prototype.setupPage = function() { oldGameEvent_setupPage.call(this); if (this._canClearHitboxX === true) this._hitboxX = undefined; if (this._canClearHitboxY === true) this._hitboxY = undefined; if (this._canClearHitboxHeight === true) this._hitboxHeight = undefined; if (this._canClearHitboxWidth === true) this._hitboxWidth = undefined; }; })(OrangeEventHitboxes); Imported.OrangeEventHitboxes = 1.1; ======================= File: OrangePathfinding.js ======================= /*============================================================================= * Orange - Pathfinding * By Hudell - www.hudell.com * OrangePathfinding.js * Version: 1.0.1 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Faster Pathfinding for Rpg Maker MV <OrangePathfinding> * @author Hudell * * @param searchLimit * @desc The higher this number, the smarter (and slower) the pathfinding will be * @default 12 * * @help * ============================================================================ * Hudell's Plugins * ============================================================================ * * Check out my website: * http://hudell.com * *=============================================================================*/ var Imported = Imported || {}; var Hudell = Hudell || {}; Hudell.OrangePathfinding = Hudell.OrangePathfinding || {}; if (Imported["SuperOrangeMovement"]!== undefined || Imported["SuperOrangeMovementEx"]!== undefined) { throw new Error("You don't need OrangePathfinding if you're using Super Orange Movement."); } (function($) { "use strict"; var parameters = $plugins.filter(function(plugin) { return plugin.description.contains('<OrangePathfinding>'); }); if (parameters.length === 0) { throw new Error("Couldn't find Hudell's OrangePathfinding parameters."); } $.Parameters = parameters[0].parameters; $.Param = {}; $.Param.searchLimit = Number($.Parameters.searchLimit || 12); Game_Character.prototype.getDirectionNode = function(start, goalX, goalY) { var searchLimit = this.searchLimit(); var mapWidth = $gameMap.width(); var nodeList = []; var openList = []; var closedList = []; var best = start; if (this.x === goalX && this.y === goalY) { return undefined; } nodeList.push(start); openList.push(start.y * mapWidth + start.x); while (nodeList.length > 0) { var bestIndex = 0; for (var i = 0; i < nodeList.length; i++) { if (nodeList[i].f < nodeList[bestIndex].f) { bestIndex = i; } } var current = nodeList[bestIndex]; var x1 = current.x; var y1 = current.y; var pos1 = y1 * mapWidth + x1; var g1 = current.g; nodeList.splice(bestIndex, 1); openList.splice(openList.indexOf(pos1), 1); closedList.push(pos1); if (current.x === goalX && current.y === goalY) { best = current; break; } if (g1 >= searchLimit) { continue; } for (var j = 0; j < 4; j++) { var direction = 2 + j * 2; var x2 = $gameMap.roundXWithDirection(x1, direction); var y2 = $gameMap.roundYWithDirection(y1, direction); var pos2 = y2 * mapWidth + x2; if (closedList.contains(pos2)) { continue; } if (!this.canPass(x1, y1, direction) && (x2!== goalX || y2!== goalY)) { continue; } var g2 = g1 + 1; var index2 = openList.indexOf(pos2); if (index2 < 0 || g2 < nodeList[index2].g) { var neighbor; if (index2 >= 0) { neighbor = nodeList[index2]; } else { neighbor = {}; nodeList.push(neighbor); openList.push(pos2); } neighbor.parent = current; neighbor.x = x2; neighbor.y = y2; neighbor.g = g2; neighbor.f = g2 + $gameMap.distance(x2, y2, goalX, goalY); if (!best || neighbor.f - neighbor.g < best.f - best.g) { best = neighbor; } } } } return best; }; Game_Character.prototype.clearCachedNode = function() { this.setCachedNode(); }; Game_Character.prototype.setCachedNode = function(node, goalX, goalY) { this._cachedNode = node; this._cachedGoalX = goalX; this._cachedGoalY = goalY; }; Game_Character.prototype.findDirectionTo = function(goalX, goalY) { if (this.x === goalX && this.y === goalY) { return 0; } if (this._cachedGoalX!== goalX || this._cachedGoalY!== goalY) { this.clearCachedNode(); } var node = this._cachedNode; var start = {}; start.parent = null; start.x = this.x; start.y = this.y; start.g = 0; start.f = $gameMap.distance(start.x, start.y, goalX, goalY); var canRetry = true; if (node === undefined) { node = this.getDirectionNode(start, goalX, goalY); this.setCachedNode(node, goalX, goalY); if (node === undefined) { return 0; } canRetry = false; } if (node.x!== start.x || node.y!== start.y) { while (node.parent && (node.parent.x!== start.x || node.parent.y!== start.y)) { node = node.parent; } if (!node.parent) { this.clearCachedNode(); if (canRetry) { node = this.getDirectionNode(start, goalX, goalY); this.setCachedNode(node, goalX, goalY); if (node === undefined) { return 0; } } } } var deltaX1 = $gameMap.deltaX(node.x, start.x); var deltaY1 = $gameMap.deltaY(node.y, start.y); if (deltaY1 > 0) { return 2; } else if (deltaX1 < 0) { return 4; } else if (deltaX1 > 0) { return 6; } else if (deltaY1 < 0) { return 8; } var deltaX2 = this.deltaXFrom(goalX); var deltaY2 = this.deltaYFrom(goalY); var direction = 0; if (Math.abs(deltaX2) > Math.abs(deltaY2)) { direction = deltaX2 > 0? 4 : 6; } else if (deltaY2!== 0) { direction = deltaY2 > 0? 8 : 2; } if (direction > 0) { if (!this.canPass(this._x, this._y, direction)) { this.clearCachedNode(); direction = 0; } } return direction; }; Game_Character.prototype.searchLimit = function() { return $.Param.searchLimit; }; })(Hudell.OrangePathfinding); Imported["OrangePathfinding"] = 1.0; ======================= File: OrangeHud/OrangeHudActorGauge.js ======================= /*============================================================================= * Orange - Actor Gauge HUD * By HUDell - www.hudell.com * OrangeHudActorGauge.js * Version: 1.0 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc OrangeHudActorGauge 1.2 - Adds a new Gauge to Orange Hud * @author Hudell * * @param GroupName * @desc The name of the HUD group where this line should be displayed * @default main * * @param ActorIndex * @desc The index of the actor in the party. If the index is invalid, nothing will be shown * @default 0 * * @param ValueExpression * @desc The expression for the the value. Click the help button for more info. * @default <hp> * * @param MaxValueExpression * @desc The expression for the the max value. Click the help button for more info. * @default <mhp> * * @param ScriptValue * @desc A script to run to get the current value of the gauge. * @default * * @param ScriptMaxValue * @desc A script to run to get the max value of the gauge. * @default * * @param SwitchId * @desc Set this to a switch number to use it to control the visibility of this line * @default 0 * * @param X * @desc The X position of the gauge inside the HUD * @default * * @param Y * @desc The Y position of the gauge inside the HUD * @default * * @param Width * @desc The width of the Gauge * @default 100 * * @param Direction * @desc The direction in which the gauge is filled * @default right * * @param Height * @desc The height of the Gauge * @default 6 * * @param VariableX * @desc The number of the variable that holds the X position of the picture inside the HUD * @default 0 * * @param VariableY * @desc The number of the variable that holds the Y position of the picture inside the HUD * @default 0 * * @param GaugeColor1 * @desc The color (or color ID) to use on the gauge * @default 20 * * @param GaugeColor2 * @desc The color (or color ID) to use on the gauge * @default 21 * * @param AllowOverflow * @desc Set this to true if you want the gauge bar to overflow when the value is too high * @default false * * @param AutoRefresh * @desc Set this to false to disable automatic refresh of the gauge * @default true * * @help * ============================================================================ * My Blog: * ============================================================================ * http://hudell.com * ============================================================================ * Valid variables: * ============================================================================ * <hp> * <mp> * <tp> * <mhp> * <mmp> * <atk> * <def> * <mat> * <mdf> * <agi> * <luk> * <hit> * <eva> * <cri> * <cev> * <mev> * <mrf> * <cnt> * <hrg> * <mrg> * <trg> * <tgr> * <grd> * <rec> * <pha> * <mcr> * <tcr> * <pdr> * <mdr> * <fdr> * <exr> * <level> * <maxlevel> * */ var Imported = Imported || {}; if (Imported.OrangeHud === undefined) { throw new Error("Please add OrangeHud before OrangeHudActorGauge!"); } if (Imported.OrangeHud < 1.7) { throw new Error("Please update OrangeHud!"); } var OrangeHudActorGauge = OrangeHudActorGauge || {}; if (Imported.OrangeHudActorGauge === undefined) { OrangeHudActorGauge.validateParams = function(paramsLine) { paramsLine.GroupName = paramsLine.GroupName || "main"; paramsLine.ValueExpression = paramsLine.ValueExpression || ""; paramsLine.MaxValueExpression = paramsLine.MaxValueExpression || ""; paramsLine.X = Number(paramsLine.X || 0); paramsLine.Y = Number(paramsLine.Y || 0); paramsLine.Width = Number(paramsLine.Width || 0); paramsLine.Height = Number(paramsLine.Height || 0); paramsLine.VariableX = Number(paramsLine.VariableX || 0); paramsLine.VariableY = Number(paramsLine.VariableY || 0); paramsLine.SwitchId = Number(paramsLine.SwitchId || 0); if (!paramsLine.Direction) { paramsLine.Direction = 'right'; } else { paramsLine.Direction = paramsLine.Direction.toLowerCase().trim(); if (paramsLine.Direction!== 'left' && paramsLine.Direction!== 'up' && paramsLine.Direction!== 'down') { paramsLine.Direction = 'right'; } } if (paramsLine.ScriptValue!== undefined && paramsLine.ScriptValue.trim() === "") { paramsLine.ScriptValue = undefined; } else { paramsLine.ScriptValue = Function("return " + paramsLine.ScriptValue); // jshint ignore:line } if (paramsLine.ScriptMaxValue!== undefined && paramsLine.ScriptMaxValue.trim() === "") { paramsLine.ScriptMaxValue = undefined; } else { paramsLine.ScriptMaxValue = Function("return " + paramsLine.ScriptMaxValue); //jshint ignore:line } paramsLine.AllowOverflow = paramsLine.AllowOverflow === "true"; paramsLine.AutoRefresh = paramsLine.AutoRefresh!== "false"; if (!paramsLine.GaugeColor1) { paramsLine.GaugeColor1 = 20; } else if (parseInt(paramsLine.GaugeColor1, 10) == paramsLine.GaugeColor1) { paramsLine.GaugeColor1 = parseInt(paramsLine.GaugeColor1, 10); } if (!paramsLine.GaugeColor2) { paramsLine.GaugeColor2 = 21; } else if (parseInt(paramsLine.GaugeColor2, 10) == paramsLine.GaugeColor2) { paramsLine.GaugeColor2 = parseInt(paramsLine.GaugeColor2, 10); } }; OrangeHudActorGauge.realX = function(variableData) { var x = variableData.X; if (variableData.VariableX > 0) { x = $gameVariables.value(variableData.VariableX); } return x; }; OrangeHudActorGauge.realY = function(variableData) { var y = variableData.Y; if (variableData.VariableY > 0) { y = $gameVariables.value(variableData.VariableY); } return y; }; OrangeHudActorGauge.drawLine = function(hudWindow, variableData) { if (variableData.SwitchId > 0) { if (!$gameSwitches.value(variableData.SwitchId)) { return; } } this.drawGauge(hudWindow, variableData); }; OrangeHudActorGauge.getRealColor = function(hudWindow, color) { if (typeof(color) == "number") { return hudWindow.textColor(color); } else { return color; } }; OrangeHudActorGauge.drawGauge = function(hudWindow, variableData) { var x = this.realX(variableData); var y = this.realY(variableData); var color1 = this.getRealColor(hudWindow, variableData.GaugeColor1); var color2 = this.getRealColor(hudWindow, variableData.GaugeColor2); var value = this.getCurrentValue(variableData); var maxValue = this.getMaxValue(variableData); var rate; var width = variableData.Width; var height = variableData.Height; if (maxValue > 0) { rate = parseFloat((value / maxValue).toPrecision(12)); } else { rate = 0; } if (isNaN(rate)) { rate = 0; } if (!variableData.AllowOverflow) { rate = rate.clamp(0, 1); } if (width > 0 && height > 0) { var fillW; var fillH; var fillX = x; var gaugeY = y; var fillY = gaugeY; if (variableData.Direction === 'left' || variableData.Direction === 'right') { fillW = Math.floor(width * rate); fillH = height; if (variableData.Direction === 'left') { fillX = fillX + width - fillW; } } else { fillW = width; fillH = Math.floor(height * rate); if (variableData.Direction == 'up') { fillY = fillY + height - fillH; } } hudWindow.contents.fillRect(x, gaugeY, width, height, hudWindow.gaugeBackColor()); hudWindow.contents.gradientFillRect(fillX, fillY, fillW, fillH, color1, color2); } }; OrangeHudActorGauge.getValue = function(variableData) { if (variableData.AutoRefresh) { return this.getCurrentValue(variableData) +'/'+ this.getMaxValue(variableData); } else { return 0; } }; OrangeHudActorGauge.getCurrentValue = function(variableData) { if (variableData.ScriptValue!== undefined) { if (typeof(variableData.ScriptValue) == "function") { return parseFloat(variableData.ScriptValue()); } else { return parseFloat(Function("return " + variableData.ScriptValue)()); //jshint ignore:line } } else { return OrangeHudActorGauge.getActorValue(variableData, variableData.ValueExpression); } }; OrangeHudActorGauge.getActorValue = function(variableData, expression) { var members = $gameParty.members(); if (members.length > variableData.ActorIndex) { var actorData = members[variableData.ActorIndex]; expression = expression.replace(/<hp>/gi, actorData.hp); expression = expression.replace(/<mp>/gi, actorData.mp); expression = expression.replace(/<tp>/gi, actorData.tp); expression = expression.replace(/<mhp>/gi, actorData.mhp); expression = expression.replace(/<mmp>/gi, actorData.mmp); expression = expression.replace(/<atk>/gi, actorData.atk); expression = expression.replace(/<def>/gi, actorData.def); expression = expression.replace(/<mat>/gi, actorData.mat); expression = expression.replace(/<mdf>/gi, actorData.mdf); expression = expression.replace(/<agi>/gi, actorData.agi); expression = expression.replace(/<luk>/gi, actorData.luk); expression = expression.replace(/<hit>/gi, actorData.hit); expression = expression.replace(/<eva>/gi, actorData.eva); expression = expression.replace(/<cri>/gi, actorData.cri); expression = expression.replace(/<cev>/gi, actorData.cev); expression = expression.replace(/<mev>/gi, actorData.mev); expression = expression.replace(/<mrf>/gi, actorData.mrf); expression = expression.replace(/<cnt>/gi, actorData.cnt); expression = expression.replace(/<hrg>/gi, actorData.hrg); expression = expression.replace(/<mrg>/gi, actorData.mrg); expression = expression.replace(/<trg>/gi, actorData.trg); expression = expression.replace(/<tgr>/gi, actorData.tgr); expression = expression.replace(/<grd>/gi, actorData.grd); expression = expression.replace(/<rec>/gi, actorData.rec); expression = expression.replace(/<pha>/gi, actorData.pha); expression = expression.replace(/<mcr>/gi, actorData.mcr); expression = expression.replace(/<tcr>/gi, actorData.tcr); expression = expression.replace(/<pdr>/gi, actorData.pdr); expression = expression.replace(/<mdr>/gi, actorData.mdr); expression = expression.replace(/<fdr>/gi, actorData.fdr); expression = expression.replace(/<exr>/gi, actorData.exr); expression = expression.replace(/<level>/gi, actorData.level); expression = expression.replace(/<maxlevel>/gi, actorData.maxLevel()); expression = expression.replace(/<exp>/gi, actorData.currentExp()); try { return parseFloat(Function("return " + expression)()); //jshint ignore:line } catch(e) { console.error(e); return 0; } } else { return 0; } }; OrangeHudActorGauge.getMaxValue = function(variableData) { if (variableData.ScriptMaxValue!== undefined) { if (typeof(variableData.ScriptMaxValue) == "function") { return parseFloat(variableData.ScriptMaxValue()); } else { return parseFloat(Function("return " + variableData.ScriptMaxValue)()); //jshint ignore:line } } else { return OrangeHudActorGauge.getActorValue(variableData, variableData.MaxValueExpression); } }; OrangeHudActorGauge.getKey = function(variableData) { return variableData.ValueVariableId; }; OrangeHud.registerLineType('OrangeHudActorGauge', OrangeHudActorGauge); Imported.OrangeHudActorGauge = 1.0; } ======================= File: OrangeCircularJson.js ======================= <gh_stars>10-100 /*============================================================================= * Orange - CircularJSON * By Hudell - www.hudell.com * OrangeCircularJSON.js * Version: 1.0.1 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Fixes Circular References on JSON serialization <OrangeCircularJSON> * @author Hudell * * @help * ============================================================================ * Hudell's Plugins * ============================================================================ * * Check out my website: * http://hudell.com * * This plugin uses the CircularJSON module by WebRelection: * https://github.com/WebReflection/circular-json * *=============================================================================*/ var Imported = Imported || {}; var Hudell = Hudell || {}; Hudell.OrangeCircularJSON = Hudell.OrangeCircularJSON || {}; (function($) { var oldJsonExStringify = JsonEx.stringify; var oldJsonExParse = JsonEx.parse; //CircularJSON, by WebReflection (https://github.com/WebReflection/circular-json) // Modified to include the functionality of JsonEx._encode and JsonEx._decode, from MV's lib. /*! Copyright (C) 2013 by WebReflection Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ var CircularJSON = (function(JSON, RegExp){ var // should be a not so common char // possibly one JSON does not encode // possibly one encodeURIComponent does not encode // right now this char is '~' but this might change in the future specialChar = '~', safeSpecialChar = '\\x' + ( '0' + specialChar.charCodeAt(0).toString(16) ).slice(-2), escapedSafeSpecialChar = '\\' + safeSpecialChar, specialCharRG = new RegExp(safeSpecialChar, 'g'), safeSpecialCharRG = new RegExp(escapedSafeSpecialChar, 'g'), safeStartWithSpecialCharRG = new RegExp('(?:^|([^\\\\]))' + escapedSafeSpecialChar), indexOf = [].indexOf || function(v){ for(var i=this.length;i--&&this[i]!==v;); return i; }, $String = String // there's no way to drop warnings in JSHint // about new String... well, I need that here! // faked, and happy linter! ; function generateReplacer(value, replacer, resolve) { var path = [], all = [value], seen = [value], mapp = [resolve? specialChar : '[Circular]'], last = value, lvl = 1, i ; return function(key, value) { // the replacer has rights to decide // if a new object should be returned // or if there's some key to drop // let's call it here rather than "too late" if (replacer) value = replacer.call(this, key, value); var type = Object.prototype.toString.call(value); if (type === '[object Object]' || type === '[object Array]') { var constructorName = JsonEx._getConstructorName(value); if (constructorName!== 'Object' && constructorName!== 'Array') { value['@'] = constructorName; } } // did you know? Safari passes keys as integers for arrays // which means if (key) when key === 0 won't pass the check if (key!== '') { if (last!== this) { i = lvl - indexOf.call(all, this) - 1; lvl -= i; all.splice(lvl, all.length); path.splice(lvl - 1, path.length); last = this; } // console.log(lvl, key, path); if (typeof value === 'object' && value) { // if object isn't referring to parent object, add to the // object path stack. Otherwise it is already there. if (indexOf.call(all, value) < 0) { all.push(last = value); } lvl = all.length; i = indexOf.call(seen, value); if (i < 0) { i = seen.push(value) - 1; if (resolve) { // key cannot contain specialChar but could be not a string path.push(('' + key).replace(specialCharRG, safeSpecialChar)); mapp[i] = specialChar + path.join(specialChar); } else { mapp[i] = mapp[0]; } } else { value = mapp[i]; } } else { if (typeof value ==='string' && resolve) { // ensure no special char involved on deserialization // in this case only first char is important // no need to replace all value (better performance) value = value.replace(safeSpecialChar, escapedSafeSpecialChar) .replace(specialChar, safeSpecialChar); } } } return value; }; } function retrieveFromPath(current, keys) { for(var i = 0, length = keys.length; i < length; current = current[ // keys should be normalized back here keys[i++].replace(safeSpecialCharRG, specialChar) ]); return current; } function generateReviver(reviver) { return function(key, value) { var isString = typeof value ==='string'; if (isString && value.charAt(0) === specialChar) { return new $String(value.slice(1)); } if (key === '') value = regenerate(value, value, {}); // again, only one needed, do not use the RegExp for this replacement // only keys need the RegExp if (isString) value = value.replace(safeStartWithSpecialCharRG, '$1' + specialChar) .replace(escapedSafeSpecialChar, safeSpecialChar); return reviver? reviver.call(this, key, value) : value; }; } function regenerateArray(root, current, retrieve) { for (var i = 0, length = current.length; i < length; i++) { current[i] = regenerate(root, current[i], retrieve); } return current; } function regenerateObject(root, current, retrieve) { for (var key in current) { if (current.hasOwnProperty(key)) { current[key] = regenerate(root, current[key], retrieve); } } var type = Object.prototype.toString.call(current); if (type === '[object Object]' || type === '[object Array]') { if (current['@']) { var constructor = window[current['@']]; if (constructor) { current = JsonEx._resetPrototype(current, constructor.prototype); } } } return current; } function regenerate(root, current, retrieve) { return current instanceof Array? // fast Array reconstruction regenerateArray(root, current, retrieve) : ( current instanceof $String? ( // root is an empty string current.length? ( retrieve.hasOwnProperty(current)? retrieve[current] : retrieve[current] = retrieveFromPath( root, current.split(specialChar) ) ) : root ) : ( current instanceof Object? // dedicated Object parser regenerateObject(root, current, retrieve) : // value as it is current ) ) ; } function stringifyRecursion(value, replacer, space, doNotResolve) { return JSON.stringify(value, generateReplacer(value, replacer,!doNotResolve), space); } function parseRecursion(text, reviver) { return JSON.parse(text, generateReviver(reviver)); } return { stringify: stringifyRecursion, parse: parseRecursion }; }(JSON, RegExp)); JsonEx.stringify = function(object) { return CircularJSON.stringify(object); }; JsonEx.parse = function(json) { return CircularJSON.parse(json); }; $.oldJsonExParse = oldJsonExParse; $.oldJsonExStringify = oldJsonExStringify; $.CircularJSON = CircularJSON; })(Hudell.OrangeCircularJSON); OrangeCircularJSON = Hudell.OrangeCircularJSON; Imported.OrangeCircularJSON = 1.0; ======================= File: OrangeHud/OrangeHudGroup.js ======================= /*============================================================================= * Orange - HUD Group * By HUDell - www.hudell.com * OrangeHudGroup.js * Version: 1.0 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc v1.0 - Adds a new group of lines to create a different hud * @author Hudell * * @param GroupName * @desc The name of this HUD group. Don't use special characters. * @default group * * @param DefaultFontFace * @desc The font face to use by default * @default Verdana * * @param DefaultFontSize * @desc The font size to use by default * @default 18 * * @param DefaultFontColor * @desc The font color to use by default * @default #FFFFFF * * @param DefaultFontItalic * @desc Should use italic by default? * @default false * * @param HudWidth * @desc The width of the hud. 0 == 100% * @default 0 * * @param HudHeight * @desc The height of the hud. 0 == 100% * @default 0 * * @param HudX * @desc The X position of the hud * @default 0 * * @param HudY * @desc The Y position of the hud * @default 0 * * @param HudOpacity * @desc The Opacity of the hud * @default 0 * * @param SwitchId * @desc Number of a switch to hide / show the hud * @default 0 * * @param WindowMargin * @desc The number of pixels to use on the margin of the hud window * @default 4 * * @param WindowPadding * @desc The number of pixels to use on the padding of the hud window * @default 18 * * @param AutoRefresh * @desc Set this to false to disable automatic refresh of the HUD * @default true * * @param ShowUnderTintLayer * @desc Set this to true to hide the HUD under tint and face effects * @default false * * * @help * ============================================================================ * My Blog: * ============================================================================ * http://hudell.com * */ ======================= File: OrangeTimeSystem/OrangeDayAndNight.js ======================= <gh_stars>10-100 /*============================================================================= * Orange - Day and Night * By Hudell - www.hudell.com * OrangeDayAndNight.js * Version: 1.3 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Tints the screen to show the time passing * * @author Hudell * * @param morningTint * @desc Red, Green, Blue and Gray values to use in the morning, comma separated * @default -34, -17, 10, 68 * * @param middayTint * @desc Red, Green, Blue and Gray values to use during the day, comma separated * @default 0, 0, 0, 0 * * @param eveningTint * @desc Red, Green, Blue and Gray values to use in the evening, comma separated * @default 17, -34, -68, 17 * * @param nightTint * @desc Red, Green, Blue and Gray values to use at night, comma separated * @default -102, -85, 0, 170 * * @param tintSpeed * @desc how many frames should the tint effect take to complete? * @default 300 * * @help * Use the following plugin command to update the screen tint immediatelly: * * update screen tint * * You can specify the duration of the tint effect this way: * * update screen tint in 20 frames * * */ var Imported = Imported || {}; if (Imported["OrangeTimeSystem"] === undefined) { console.log('Download OrangeTimeSystem: http://link.hudell.com/time-system'); throw new Error("This library requires the OrangeTimeSystem!"); } var OrangeDayAndNight = OrangeDayAndNight || MVC.shallowClone(OrangeEventManager); (function($) { "use strict"; $.Parameters = PluginManager.parameters('OrangeDayAndNight'); $.Param = $.Param || {}; $.Param.morningTint = $.Parameters['morningTint'] || "-34, -17, 10, 68"; $.Param.middayTint = $.Parameters['middayTint'] || "0, 0, 0, 0"; $.Param.eveningTint = $.Parameters['eveningTint'] || "17, -34, -68, 17"; $.Param.nightTint = $.Parameters['nightTint'] || "-102, -85, 0, 170"; $.Param.tintSpeed = Number($.Parameters['tintSpeed'] || 0); $.canTintScreen = function() { return!OrangeTimeSystem.inside; }; $.onDayPeriodChange = function(){ $.updateTint($.Param.tintSpeed); }; $.updateTint = function(speed) { var dataStr = ""; var data = [0, 0, 0, 0]; if ($.canTintScreen()) { switch(OrangeTimeSystem.dayPeriod) { case 1 : dataStr = $.Param.morningTint; break; case 2 : dataStr = $.Param.middayTint; break; case 3 : dataStr = $.Param.eveningTint; break; case 4 : dataStr = $.Param.nightTint; break; default : return; } data = dataStr.split(','); } if (data.length > 0) { data[0] = parseInt(data[0], 10); } else { data.push(0); } if (data.length > 1) { data[1] = parseInt(data[1], 10); } else { data.push(0); } if (data.length > 2) { data[2] = parseInt(data[2], 10); } else { data.push(0); } if (data.length > 3) { data[3] = parseInt(data[3], 10); } else { data.push(0); } $gameScreen.startTint(data, speed); }; OrangeTimeSystem.on('changeDayPeriod', $.onDayPeriodChange); var oldGamePlayer_performTransfer = Game_Player.prototype.performTransfer; Game_Player.prototype.performTransfer = function() { oldGamePlayer_performTransfer.call(this); $.updateTint(1); }; var oldGameInterpreter_pluginCommand = Game_Interpreter.prototype.pluginCommand; Game_Interpreter.prototype.pluginCommand = function(command, args) { oldGameInterpreter_pluginCommand.call(this, command, args); if (command.toUpperCase() == 'UPDATE') { if (args.length >= 2 && args[0].toUpperCase() == 'SCREEN' && args[1].toUpperCase() == 'TINT') { var speed = 0; if (args.length >= 4 && args[2].toUpperCase() == 'IN') { speed = parseInt(args[3], 10); } $.updateTint(speed); } } }; })(OrangeDayAndNight); Imported["OrangeDayAndNight"] = 1.3; ======================= File: OrangeHud/OrangeHudFacePicture.js ======================= /*============================================================================= * Orange - Face Picture HUD * By HUDell - www.hudell.com * OrangeHudFacePicture.js * Version: 1.3.1 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Draws a character's face on the OrangeHud * @author Hudell * * @param GroupName * @desc The name of the HUD group where this line should be displayed * @default main * * @param ActorIndex * @desc The index of the actor in the party. If the index is invalid, nothing will be shown * @default 0 * * @param SwitchId * @desc Set this to a switch number to use it to control the visibility of this line * @default 0 * * @param X * @desc The X position of the variable line inside the HUD * @default * * @param Y * @desc The Y position of the variable line inside the HUD * @default * * @param VariableX * @desc The number of the variable that holds the X position of the picture inside the HUD * @default 0 * * @param VariableY * @desc The number of the variable that holds the Y position of the picture inside the HUD * @default 0 * * @help * ============================================================================ * My Blog: * ============================================================================ * http://hudell.com * */ var Imported = Imported || {}; if (Imported["OrangeHud"] === undefined) { throw new Error("Please add OrangeHud before OrangeHudFacePicture!"); } if (Imported["OrangeHud"] < 1.7) { throw new Error("Please update OrangeHud!"); } var OrangeHudFacePicture = OrangeHudFacePicture || {}; if (Imported["OrangeHudFacePicture"] === undefined) { OrangeHudFacePicture.validateParams = function(paramsLine) { paramsLine.GroupName = paramsLine.GroupName || "main"; paramsLine.ActorIndex = Number(paramsLine.ActorIndex || 0); paramsLine.X = Number(paramsLine.X || 0); paramsLine.Y = Number(paramsLine.Y || 0); paramsLine.VariableX = Number(paramsLine.VariableX || 0); paramsLine.VariableY = Number(paramsLine.VariableY || 0); paramsLine.SwitchId = Number(paramsLine.SwitchId || 0); }; OrangeHudFacePicture.realX = function(variableData) { var x = variableData.X; if (variableData.VariableX > 0) { x = $gameVariables.value(variableData.VariableX); } return x; }; OrangeHudFacePicture.realY = function(variableData) { var y = variableData.Y; if (variableData.VariableY > 0) { y = $gameVariables.value(variableData.VariableY); } return y; }; OrangeHudFacePicture.drawLine = function(hudWindow, variableData) { if (variableData.SwitchId > 0) { if (!$gameSwitches.value(variableData.SwitchId)) { return; } } var fileData = this.getValue(variableData); if (fileData!== false) { x = this.realX(variableData); y = this.realY(variableData); var bitmap = ImageManager.loadFace(fileData[0]); bitmap.addLoadListener(function(){ OrangeHud.setDirty(); }); hudWindow.drawFace(fileData[0], fileData[1], x, y); } }; OrangeHudFacePicture.drawPicture = function(hudWindow, filename, x, y, variableData) { hudWindow.drawPicture(filename, x, y); }; OrangeHudFacePicture.getValue = function(variableData) { if (variableData.ActorIndex >= 0) { var members = $gameParty.members(); if (variableData.ActorIndex < members.length) { var faceName = members[variableData.ActorIndex]._faceName; var faceIndex = members[variableData.ActorIndex]._faceIndex; return [faceName, faceIndex]; } } return false; }; OrangeHudFacePicture.getKey = function(variableData) { return variableData.ActorIndex; }; OrangeHud.registerLineType('OrangeHudFacePicture', OrangeHudFacePicture); Imported["OrangeHudFacePicture"] = 1.3; } ======================= File: OrangeMovement/OrangeAutoAvoidObstacles.js ======================= <reponame>Ghabry/mv-plugins<gh_stars>10-100 /*============================================================================= * Orange - Auto Avoid Obstacles * By Hudell - www.hudell.com * OrangeAutoAvoidObstacles.js * Version: 1.0 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Makes the player automatically Avoid small obstacles, by walking around them * * @param AvoidEvents * @desc Set this to false if you don't want the player to avoid events. * @default true * * @param OnlyWhenDashing * @desc Set this to true to only avoid obstacles when the player is dashing. * @default false * * @param DashingDelay * @desc Makes the character wait a little before trying to avoid an obstacle when dashing. Set this to a number of frames. * @default 0 * * @param WalkingDelay * @desc Makes the character wait a little before trying to avoid an obstacle when walking. Set this to a number of frames. * @default 0 * * @param MaxOffset * @desc The max distance (in tiles) that the character is allowed to walk in a different direction to avoid an obstacle. * @default 0.75 * * @param RetainDirection * @desc If true, the character won't face the other direction when walking around an object. * @default true * * @author Hudell * * @help * ============================================================================ * Latest Version * ============================================================================ * * Get the latest version of this script on http://link.hudell.com/auto-avoid * *=============================================================================*/ var Imported = Imported || {}; if (Imported['MVCommons'] === undefined) { console.log('Download MVCommons: http://link.hudell.com/mvcommons'); throw new Error("This library needs MVCommons to work properly!"); } if (Imported['SuperOrangeMovement'] === undefined) { console.log('Download SuperOrangeMovement: http://link.hudell.com/super-orange-movement'); throw new Error("This library needs SuperOrangeMovement to work properly!"); } var OrangeAutoAvoidObstacles = OrangeAutoAvoidObstacles || {}; (function($) { "use strict"; $.Parameters = PluginManager.parameters('OrangeAutoAvoidObstacles'); $.Param = $.Param || {}; $.Param.AvoidEvents = $.Param["AvoidEvents"]!== "false"; $.Param.OnlyWhenDashing = $.Param["OnlyWhenDashing"] === "true"; $.Param.DashingDelay = Number($.Param["DashingDelay"] || 0); $.Param.WalkingDelay = Number($.Param["WalkingDelay"] || 0); $.Param.MaxOffset = Number($.Param["MaxOffset"] || 0.75); $.Param.RetainDirection = $.Param["RetainDirection"]!== "false"; var avoidObstaclesDelay = 0; // Every time the player succesfully moves, reset the delay var oldGamePlayer_onBeforeMove = Game_Player.prototype.onBeforeMove; Game_Player.prototype.onBeforeMove = function() { if (this.isDashing()) { avoidObstaclesDelay = $.Param.DashingDelay; } else { avoidObstaclesDelay = $.Param.WalkingDelay; } if (oldGamePlayer_onBeforeMove!== undefined) { oldGamePlayer_onBeforeMove.call(this); } }; var oldGamePlayer_trySavingFailedMovement = Game_Player.prototype.trySavingFailedMovement; Game_Player.prototype.trySavingFailedMovement = function(direction) { if (oldGamePlayer_trySavingFailedMovement!== undefined) { if (oldGamePlayer_trySavingFailedMovement.call(this, direction)) { return true; } } if (avoidObstaclesDelay > 0) { avoidObstaclesDelay--; } if ($.Param.OnlyWhenDashing === true) { if (!this.isDashing()) { return false; } } if ($.Param.AvoidEvents!== true) { if (this.isTilesetPassable(this._x, this._y, direction)) { var x2 = $gameMap.roundFractionXWithDirection(this._x, direction, this.myStepSize()); var y2 = $gameMap.roundFractionYWithDirection(this._y, direction, this.myStepSize()); if (this.isCollidedWithCharacters(x2, y2)) { return false; } } } if (this.tryToAvoid(direction, $.Param.MaxOffset)) { return true; } return false; }; Game_Player.prototype.tryToAvoid = function(direction, maxOffset) { if (avoidObstaclesDelay > 0) { return false; } var previousOffset = 0; var offset = this.myStepSize(); var tryDirection = function(xOffset, yOffset, movementDirection, faceDirection) { // Test if the player would be able to move on the faceDirection if they were at the offset position. If they could, then move towards that position for now. if (this.canPass((this._x + xOffset).fix(), (this._y + yOffset).fix(), faceDirection)) { this.executeMove(movementDirection); if ($.Param.RetainDirection) { this.setDirection(faceDirection); } return true; } return false; }; if (direction == Direction.LEFT || direction == Direction.RIGHT) { // If the player can't walk horizontally on the current position, but would be able to walk if he were a little higher or lower then move vertically instead // on the next iterations it will keep trying to move horizontaly again and it will eventually work before the offset is reached var downEnabled = true; var upEnabled = true; while (offset <= maxOffset) { if (downEnabled) { if (!this.canPass(this._x, (this._y + previousOffset).fix(), Direction.DOWN)) { downEnabled = false; } } if (upEnabled) { if (!this.canPass(this._x, (this._y - previousOffset).fix(), Direction.UP)) { upEnabled = false; } } if (downEnabled === true && tryDirection.call(this, 0, offset, Direction.DOWN, direction)) { return true; } if (upEnabled === true && tryDirection.call(this, 0, -offset, Direction.UP, direction)) { return true; } previousOffset = offset; offset += this.myStepSize(); } } else if (direction == Direction.UP || direction == Direction.DOWN) { // If the player can't walk vertically on the current position, but would be able to walk if he were a little left or right then move horizontally instead // on the next iterations it will keep trying to move vertically again and it will eventually work before the offset is reached var leftEnabled = true; var rightEnabled = true; while (offset <= maxOffset) { if (leftEnabled) { if (!this.canPass((this._x - previousOffset).fix(), this._y, Direction.LEFT)) { leftEnabled = false; } } if (rightEnabled) { if (!this.canPass((this._x + previousOffset).fix(), this._y, Direction.RIGHT)) { rightEnabled = false; } } if (rightEnabled === true && tryDirection.call(this, offset, 0, Direction.RIGHT, direction)) { return true; } if (leftEnabled === true && tryDirection.call(this, -offset, 0, Direction.LEFT, direction)) { return true; } previousOffset = offset; offset += this.myStepSize(); } } return false; }; })(OrangeAutoAvoidObstacles); PluginManager.register("OrangeAutoAvoidObstacles", "1.0.0", "Will make the player avoid small obstacles automatically", { email: "<EMAIL>", name: "Hudell", website: "http://www.hudell.com" }, "2015-10-21"); ======================= File: OrangeLighting/OrangeLighting.js ======================= /*============================================================================= * Orange - Lighting * By Hudell - www.hudell.com * OrangeLighting.js * Version: 1.4 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Lighting system <OrangeLighting> * @author Hudell * * @param lightMaskSwitch * @desc When this switch is on, the lighting system will be activated * @default 0 * * @param opacityVariable * @desc The variable that defines the opacity of the black mask. If none is defined, the opacity will be 255. * @default 0 * * @param tintSpeed * @desc The speed in which the color will change. (4 = black to white in 1 second, 255 = instant) * @default 0.3 * * @param defaultMaskColor * @desc The default mask color * @default black * * @help * ============================================================================ * Hudell's Plugins * ============================================================================ * * Check out my website: * http://hudell.com * *=============================================================================*/ var Imported = Imported || {}; var Hudell = Hudell || {}; Hudell.OrangeLighting = Hudell.OrangeLighting || {}; (function(namespace) { "use strict"; namespace.addOns = {}; namespace._listeners = {}; var parameters = $plugins.filter(function(plugin) { return plugin.description.contains('<OrangeLighting>'); }); if (parameters.length === 0) { throw new Error("Couldn't find Hudell's OrangeLighting parameters."); } namespace.Parameters = parameters[0].parameters; namespace.Param = {}; namespace.Param.lightMaskSwitch = Number(namespace.Parameters.lightMaskSwitch || 0); namespace.Param.opacityVariable = Number(namespace.Parameters.opacityVariable || 0); namespace.Param.tintSpeed = Number(namespace.Parameters.tintSpeed || 0.3); namespace.Param.defaultMaskColor = namespace.Parameters.defaultMaskColor || "black"; namespace.enabled = true; Object.defineProperties(namespace, { dirty: { get: function() { return this._dirty; }, set: function(value) { this._dirty = value; }, configurable: true } }); namespace.isActive = function() { return this.enabled; }; function OrangeLightmask() { this.initialize.apply(this, arguments); } namespace.shouldShowLightMask = function(){ return namespace.Param.lightMaskSwitch === 0 || $gameSwitches.value(namespace.Param.lightMaskSwitch); }; namespace.on = function(eventName, callback) { if (this._listeners[eventName] === undefined) this._listeners[eventName] = []; this._listeners[eventName].push(callback); }; namespace.un = function(eventName, callback) { if (this._listeners[eventName] === undefined) return; for (var i = 0; i < this._listeners[eventName].length; i++) { if (this._listeners[eventName][i] == callback) { this._listeners[eventName][i] = undefined; return; } } }; namespace.runEvent = function(eventName, scope) { if (this._listeners[eventName] === undefined) return; if (scope === undefined) scope = this; for (var i = 0; i < this._listeners[eventName].length; i++) { var callback = this._listeners[eventName][i]; callback.call(scope); } }; namespace.Lightmask = OrangeLightmask; namespace.Lightmask.prototype = Object.create(PIXI.DisplayObjectContainer.prototype); namespace.Lightmask.prototype.constructor = namespace.Lightmask; //Copied from http://stackoverflow.com/questions/1573053/javascript-function-to-convert-color-names-to-hex-codes namespace.colorNameToHex = function(color) { if (color.charAt('0') == '#') return color; var colors = {"aliceblue":"#f0f8ff","antiquewhite":"#faebd7","aqua":"#00ffff","aquamarine":"#7fffd4","azure":"#f0ffff", "beige":"#f5f5dc","bisque":"#ffe4c4","black":"#000000","blanchedalmond":"#ffebcd","blue":"#0000ff","blueviolet":"#8a2be2","brown":"#a52a2a","burlywood":"#deb887", "cadetblue":"#5f9ea0","chartreuse":"#7fff00","chocolate":"#d2691e","coral":"#ff7f50","cornflowerblue":"#6495ed","cornsilk":"#fff8dc","crimson":"#dc143c","cyan":"#00ffff", "darkblue":"#00008b","darkcyan":"#008b8b","darkgoldenrod":"#b8860b","darkgray":"#a9a9a9","darkgreen":"#006400","darkkhaki":"#bdb76b","darkmagenta":"#8b008b","darkolivegreen":"#556b2f", "darkorange":"#ff8c00","darkorchid":"#9932cc","darkred":"#8b0000","darksalmon":"#e9967a","darkseagreen":"#8fbc8f","darkslateblue":"#483d8b","darkslategray":"#2f4f4f","darkturquoise":"#00ced1", "darkviolet":"#9400d3","deeppink":"#ff1493","deepskyblue":"#00bfff","dimgray":"#696969","dodgerblue":"#1e90ff", "firebrick":"#b22222","floralwhite":"#fffaf0","forestgreen":"#228b22","fuchsia":"#ff00ff", "gainsboro":"#dcdcdc","ghostwhite":"#f8f8ff","gold":"#ffd700","goldenrod":"#daa520","gray":"#808080","green":"#008000","greenyellow":"#adff2f", "honeydew":"#f0fff0","hotpink":"#ff69b4", "indianred ":"#cd5c5c","indigo":"#4b0082","ivory":"#fffff0","khaki":"#f0e68c", "lavender":"#e6e6fa","lavenderblush":"#fff0f5","lawngreen":"#7cfc00","lemonchiffon":"#fffacd","lightblue":"#add8e6","lightcoral":"#f08080","lightcyan":"#e0ffff","lightgoldenrodyellow":"#fafad2", "lightgrey":"#d3d3d3","lightgreen":"#90ee90","lightpink":"#ffb6c1","lightsalmon":"#ffa07a","lightseagreen":"#20b2aa","lightskyblue":"#87cefa","lightslategray":"#778899","lightsteelblue":"#b0c4de", "lightyellow":"#ffffe0","lime":"#00ff00","limegreen":"#32cd32","linen":"#faf0e6", "magenta":"#ff00ff","maroon":"#800000","mediumaquamarine":"#66cdaa","mediumblue":"#0000cd","mediumorchid":"#ba55d3","mediumpurple":"#9370d8","mediumseagreen":"#3cb371","mediumslateblue":"#7b68ee", "mediumspringgreen":"#00fa9a","mediumturquoise":"#48d1cc","mediumvioletred":"#c71585","midnightblue":"#191970","mintcream":"#f5fffa","mistyrose":"#ffe4e1","moccasin":"#ffe4b5", "navajowhite":"#ffdead","navy":"#000080", "oldlace":"#fdf5e6","olive":"#808000","olivedrab":"#6b8e23","orange":"#ffa500","orangered":"#ff4500","orchid":"#da70d6", "palegoldenrod":"#eee8aa","palegreen":"#98fb98","paleturquoise":"#afeeee","palevioletred":"#d87093","papayawhip":"#ffefd5","peachpuff":"#ffdab9","peru":"#cd853f","pink":"#ffc0cb","plum":"#dda0dd","powderblue":"#b0e0e6","purple":"#800080", "red":"#ff0000","rosybrown":"#bc8f8f","royalblue":"#4169e1", "saddlebrown":"#8b4513","salmon":"#fa8072","sandybrown":"#f4a460","seagreen":"#2e8b57","seashell":"#fff5ee","sienna":"#a0522d","silver":"#c0c0c0","skyblue":"#87ceeb","slateblue":"#6a5acd","slategray":"#708090","snow":"#fffafa","springgreen":"#00ff7f","steelblue":"#4682b4", "tan":"#d2b48c","teal":"#008080","thistle":"#d8bfd8","tomato":"#ff6347","turquoise":"#40e0d0", "violet":"#ee82ee", "wheat":"#f5deb3","white":"#ffffff","whitesmoke":"#f5f5f5", "yellow":"#ffff00","yellowgreen":"#9acd32"}; if (typeof colors[color.toLowerCase()]!= 'undefined') return colors[color.toLowerCase()]; return false; }; namespace.hexToRgb = function(hex) { var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); return result? { red : parseInt(result[1], 16), green : parseInt(result[2], 16), blue : parseInt(result[3], 16) } : null; }; namespace.getCharacterPosition = function(character) { var pw = $gameMap.tileWidth(); var ph = $gameMap.tileHeight(); var dx = $gameMap.displayX(); var dy = $gameMap.displayY(); var px = character._realX; var py = character._realY; var pd = character._direction; var x1 = (pw / 2) + ((px - dx) * pw); var y1 = (ph / 2) + ((py - dy) * ph); return [x1, y1, pd]; }; (function($) { Object.defineProperties($, { width: { get: function() { return this._width; }, configurable: true }, height: { get: function() { return this._height; }, configurable: true }, sprites: { get: function() { return this._sprites; }, configurable: true }, currentMapId: { get: function() { return this._currentMapId; }, set: function(value) { this._currentMapId = value; }, configurable: true }, currentDisplayX: { get: function() { return this._currentDisplayX; }, set: function(value) { this._currentDisplayX = value; }, configurable: true }, currentDisplayY: { get: function() { return this._currentDisplayY; }, set: function(value) { this._currentDisplayY = value; }, configurable: true } }); $.initialize = function() { PIXI.DisplayObjectContainer.call(this); this._width = Graphics.width; this._height = Graphics.height; this._sprites = []; this.createMaskBitmap(); }; $.update = function() { this.updateMask(); }; $.createMaskBitmap = function() { this._maskBitmap = new Bitmap(Graphics.width, Graphics.height); }; $.maskColor = function() { return namespace.Param.defaultMaskColor; }; $.walkColor = function(newRGB, currentRGB, colorName, tintSpeed) { if (newRGB[colorName] < currentRGB[colorName]) { currentRGB[colorName] = currentRGB[colorName] - tintSpeed; if (newRGB[colorName] > currentRGB[colorName]) { currentRGB[colorName] = newRGB[colorName]; } } else if(newRGB[colorName] > currentRGB[colorName]) { currentRGB[colorName] = currentRGB[colorName] + tintSpeed; if (newRGB[colorName] < currentRGB[colorName]) { currentRGB[colorName] = newRGB[colorName]; } } newRGB[colorName] = newRGB[colorName].clamp(0, 255); }; $.refreshMaskColor = function() { var destinationColor = $.maskColor(); var newColor = destinationColor; if (namespace._lastMaskColor!== undefined && destinationColor!== namespace._lastMaskColor) { var currentColor = namespace._lastMaskColor; var currentRGB = namespace._currentRGB; if (!!currentRGB || currentColor.charAt(0) == '#') { newColor = namespace.colorNameToHex(destinationColor); if (newColor === false) { newColor = destinationColor; } if (currentRGB === undefined) { currentRGB = namespace.hexToRgb(currentColor); } var newRGB = namespace.hexToRgb(newColor); this.walkColor(newRGB, currentRGB,'red', namespace.Param.tintSpeed); this.walkColor(newRGB, currentRGB, 'green', namespace.Param.tintSpeed); this.walkColor(newRGB, currentRGB, 'blue', namespace.Param.tintSpeed); newColor = '#' + ((1 << 24) + (Math.floor(currentRGB.red) << 16) + (Math.floor(currentRGB.green) << 8) + Math.floor(currentRGB.blue)).toString(16).slice(1); namespace._currentRGB = currentRGB; } } else { namespace._currentRGB = undefined; } namespace._lastMaskColor = newColor; }; $.refreshMask = function() { namespace.runEvent('beforeRefreshMask', this); this.popAllSprites(); if (namespace.isActive()) { namespace._showing = namespace.shouldShowLightMask(); if (namespace._showing) { namespace.runEvent('refreshMask', this); var backOpacity = 255; if (namespace.Param.opacityVariable > 0) { backOpacity = $gameVariables.value(namespace.Param.opacityVariable).clamp(0, 255); } //calculates what will be the new mask color this.refreshMaskColor(); namespace.runEvent('refreshMaskColor', this); namespace._lastOpacity = backOpacity; // Adds the mask sprite this.addSprite(0, 0, this._maskBitmap, backOpacity); this._maskBitmap.fillRect(0, 0, Graphics.width, Graphics.height, namespace._lastMaskColor); namespace.runEvent('afterRefreshMask', this); } } }; $.updateMask = function() { if (!namespace.isActive()){ if (this._sprites.length > 0) { namespace.dirty = true; } return; } var newId = 0; var newDisplayX = 0; var newDisplayY = 0; if ($gameMap!== undefined && $gameMap!== null) { newId = $gameMap._mapId; newDisplayX = $gameMap._displayX; newDisplayY = $gameMap._displayY; } if (newId!== this.currentMapId || newDisplayY!== this.currentDisplayY || newDisplayX || this.currentDisplayX) { namespace.dirty = true; } if (namespace.shouldShowLightMask()!== namespace._showing) { namespace.dirty = true; } if (namespace._lastMaskColor!== $.maskColor()) { namespace.dirty = true; } // if (namespace.Param.opacityVariable > 0) { // var backOpacity = $gameVariables.value(namespace.Param.opacityVariable).clamp(0, 255); // if (backOpacity!== namespace._lastOpacity) { // namespace.dirty = true; // } // } namespace.runEvent('updateMask', this); if (namespace.dirty) { this.refreshMask(); namespace.dirty = false; this.currentMapId = newId; this.currentDisplayX = newDisplayX; this.currentDisplayY = newDisplayY; } }; $.addSprite = function(x, y, bitmap, opacity, blendMode, rotation, anchorX, anchorY) { if (opacity === undefined) opacity = 255; if (blendMode === undefined) blendMode = 2; if (rotation === undefined) rotation = 0; if (anchorX === undefined) anchorX = 0; if (anchorY === undefined) anchorY = 0; var sprite = new Sprite(this.viewport); sprite.bitmap = bitmap; sprite.opacity = opacity; sprite.blendMode = blendMode; sprite.x = x; sprite.y = y; this._sprites.push(sprite); this.addChild(sprite); sprite.rotation = rotation; sprite.ax = anchorX; sprite.ay = anchorY; sprite.opacity = opacity; return sprite; }; $.popSprite = function() { var sprite = this._sprites.pop(); if (sprite) { this.removeChild(sprite); } return sprite; }; $.popAllSprites = function() { var sprite; while (this._sprites.length > 0) { sprite = this._sprites.pop(); if (sprite) { this.removeChild(sprite); } } }; })(namespace.Lightmask.prototype); (function($) { $.createLightmask = function() { this._lightmask = new namespace.Lightmask(); this.addChild(this._lightmask); }; // Creates the Lightmask before the weather layer namespace.Spriteset_Map_prototype_createWeather = $.createWeather; $.createWeather = function() { this.createLightmask(); namespace.Spriteset_Map_prototype_createWeather.call(this); }; })(Spriteset_Map.prototype); (function($){ $.radialgradientFillRect = function (x, y, startRadius, endRadius, color1, color2, flicker) { var context = this._context; var grad; var wait = Math.floor((Math.random() * 8) + 1); if (flicker === true && wait == 1) { var gradRnd = Math.floor((Math.random() * 7) + 1); var colorRnd = Math.floor((Math.random() * 10) - 5); var red = namespace.hexToRgb(color1).red; var green = namespace.hexToRgb(color1).green; var blue = namespace.hexToRgb(color1).blue; green = (green + colorRnd).clamp(0, 255); color1 = '#' + ((1 << 24) + (red << 16) + (green << 8) + blue).toString(16).slice(1); endRadius -= gradRnd; } grad = context.createRadialGradient(x, y, startRadius, x, y, endRadius); grad.addColorStop(0, color1); grad.addColorStop(1, color2); context.save(); context.fillStyle = grad; context.fillRect(x - endRadius, y - endRadius, endRadius * 2, endRadius * 2); context.restore(); this._setDirty(); }; $.makeFlashlightEffect = function(x, y, startRadius, endRadius, color1, color2, direction) { var context = this._context; var grad; context.save(); grad = context.createRadialGradient(x, y, startRadius, x, y, endRadius); grad.addColorStop(0, '#999999'); grad.addColorStop(1, color2); context.fillStyle = grad; context.fillRect(x - endRadius, y - endRadius, endRadius * 2, endRadius * 2); for (var cone = 0; cone < 8; cone++) { startRadius = cone * 2; endRadius = cone * 12; switch(direction) { case 6 : x += cone * 6; break; case 4 : x -= cone * 6; break; case 2 : y += cone * 6; break; case 8 : y -= cone * 6; break; default : break; } grad = context.createRadialGradient(x, y, startRadius, x, y, endRadius); grad.addColorStop(0, color1); grad.addColorStop(1, color2); context.fillStyle = grad; context.fillRect(x - endRadius, y - endRadius, endRadius * 2, endRadius * 2); } context.restore(); this._setDirty(); }; })(Bitmap.prototype); namespace.clear = function() { this._currentRGB = undefined; this._lastMaskColor = undefined; this._lastOpacity = undefined; }; namespace.oldGameMap_setup = Game_Map.prototype.setup; Game_Map.prototype.setup = function(mapId) { namespace.oldGameMap_setup.call(this, mapId); namespace.clear(); }; })(Hudell.OrangeLighting); OrangeLighting = Hudell.OrangeLighting; Imported.OrangeLighting = 1.4; ======================= File: OrangeTriggerBlockedTouchEvents.js ======================= <filename>OrangeTriggerBlockedTouchEvents.js /*============================================================================= * Orange - Trigger Blocked Touch Events * By Hudell - www.hudell.com * OrangeTriggerBlockedTouchEvents.js * Version: 1.0 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc This plugin will trigger onTouch events on normal priority if the player tries to walk into them * @author Hudell * * * @help * ============================================================================ * Latest Version * ============================================================================ * * Get the latest version of this script on * http://link.hudell.com/trigger-blocked-touch-events * *=============================================================================*/ var Imported = Imported || {}; var OrangeTriggerBlockedTouchEvents = OrangeTriggerBlockedTouchEvents || {}; (function($) { "use strict"; // alias the updateNonmoving method from the Game_Player class to check // if there's any event to trigger var oldGamePlayer_updateNonmoving = Game_Player.prototype.updateNonmoving; Game_Player.prototype.updateNonmoving = function(wasMoving) { oldGamePlayer_updateNonmoving.call(this, wasMoving); // If the player was moving or it's pressing an arrow key if (wasMoving || Input.dir4!== 0) { // Doesn't trigger anything if there's already something running if (!$gameMap.isEventRunning()) { // Makes sure the player is blocked before checking the events if (!this.isMapPassable(this._x, this._y, this.direction)) { this.checkEventTriggerThere([1]); // Setups the starting event if there's any. if ($gameMap.setupStartingEvent()) { return; } } } } }; })(OrangeTriggerBlockedTouchEvents); // If MVCommons is imported, register the plugin with it's PluginManager. if (Imported['MVCommons']!== undefined) { PluginManager.register("OrangeTriggerBlockedTouchEvents", "1.0.0", "Will trigger onTouch events on normal priority if the player tries to walk into them", { email: "<EMAIL>", name: "Hudell", website: "http://www.hudell.<EMAIL>" }, "2015-10-21"); } else { Imported["OrangeTriggerBlockedTouchEvents"] = true; } ======================= File: OrangeDisableMouseMovement.js ======================= /*============================================================================= * Orange - Disable Mouse Movement * By Hudell - www.hudell.com * OrangeDisableMouseMovement.js * Version: 1.0 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc This plugin will disable the player movement with the use of the mouse * @author Hudell * * @help * ============================================================================ * Latest Version * ============================================================================ * * Get the latest version of this script on * http://link.hudell.com/disable-mouse-movement * *=============================================================================*/ Game_Temp.prototype.setDestination = function(x, y) {}; var Imported = Imported || {}; Imported["OrangeDisableMouseMovement"] = true; ======================= File: PluginTemplate.js ======================= <reponame>Ghabry/mv-plugins<gh_stars>10-100 /*============================================================================= * Orange - PluginName * By Hudell - www.hudell.com * OrangePluginName.js * Version: 1.0 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Plugin Description <OrangePluginName> * @author Hudell * * @param paramName * @desc Description * @default 0 * * @help * ============================================================================ * Hudell's Plugins * ============================================================================ * * Check out my website: * http://hudell.com * *=============================================================================*/ var Imported = Imported || {}; var Hudell = Hudell || {}; Hudell.OrangePluginName = Hudell.OrangePluginName || {}; (function($) { "use strict"; var parameters = $plugins.filter(function(plugin) { return plugin.description.contains('<OrangePluginName>'); }); if (parameters.length === 0) { throw new Error("Couldn't find Hudell's OrangePluginName parameters."); } $.Parameters = parameters[0].parameters; $.Param = {}; // Param validation //$.Param.paramName = Number($.Parameters.paramName || 0); // Code goes here })(Hudell.OrangePluginName); OrangePluginName = Hudell.OrangePluginName; Imported.OrangePluginName = 1.0; ======================= File: OrangeOverlay.js ======================= <reponame>Ghabry/mv-plugins /*============================================================================= * Orange - Overlay * By Hudell - www.hudell.com * OrangeOverlay.js * Version: 1.1.2 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc v1.1.2 - Adds overlay images to the map <OrangeOverlay> * @author Hudell * * @param Organized Folders * @desc Use different folders for each type of parallax * @default false * * @param Parallax Layer Filename * @desc * @default par * * @param Ground Layer Filename * @desc * @default ground * * @param Light Layer Filename * @desc * @default light * * @param Shadow Layer Filename * @desc * @default shadow * * @param Light Opacity * @desc * @default 185 * * @param Quick Start * @desc * @default true * * @param Bush Region ID * @desc * @default 7 * * @param Fog Switch ID * @desc * @default 1 * * @param Light Switch ID * @desc * @default 2 * * @param Parallax Switch ID * @desc * @default 3 * * @param Shadow Switch ID * @desc * @default 4 * * @help * ============================================================================ * Hudell's Plugins * ============================================================================ * * Check out my website: * http://hudell.com * * ============================================================================ * Instructions * ============================================================================ * * You can use this plugin to add overlay images to your maps * You can keep the images either on the img/parallaxes folder * Or (if you set the Organized Folders param to true) on separate folders like this: * * img/overlays/grounds * img/overlays/pars * img/overlays/shadows * img/overlays/lights * img/overlays/fogs * * All image filenames must end with the number of the map that they are used on * * Map notetags: * * <all> : Display all overlays * <ground> : Display ground overlay * <par> : Display parallax overlay * <light> : Display light overlay * <shadow> : Display shadow overlay * <fogName:filename> : Display the specified fog image * <fogOpacity:number> : Change the opacity level of the fog image (0 to 255) * <fogBlend:number> : Changes the blend type of the fog image * <fogDuration:number> : Changes the duration of the opacity transition * <xMove:number> : Changes the horizontal speed of the fog * <yMove:number> : Changes the vertical speed of the fog * * You can use variables numbers on the notetags by adding a $ symbol before the value * * ============================================================================ * Plugin Commands * ============================================================================ * ---------------------------------------------------------------------------- * Overlay layertype filename * ---------------------------------------------------------------------------- * Possible layer types: ground, light, shadow, par * * ---------------------------------------------------------------------------- * Overlay fog filename opacity xMove yMove blendmode duration * ---------------------------------------------------------------------------- * Changes the fog params to the ones specified in this command. * Blendmode and duration are optional * Examples: * Overlay fog fog1 100 10 0 0 20 * This will display the file fo1 with opacity 100 and move horizontally 10px * at a time, with a transition of 20 frames * * ---------------------------------------------------------------------------- * Overlay fadeout duration * ---------------------------------------------------------------------------- * Do a fadeout effect on the current fog * * ---------------------------------------------------------------------------- * Overlay addfog filename ID Opacity xMove yMove BlendType Z * ---------------------------------------------------------------------------- * Adds an extra fog layer. BlendType and Z values are optional * * ---------------------------------------------------------------------------- * Overlay removefog ID * ---------------------------------------------------------------------------- * Removes an extra fog that was added with the addfog command * * ============================================================================ * Changelog * ============================================================================ * Version 1.1.2: * Fixed several small issues with the opacity *=============================================================================*/ var Imported = Imported || {}; var Hudell = Hudell || {}; Hudell.OrangeOverlay = Hudell.OrangeOverlay || {}; (function($) { "use strict"; var parameters = $plugins.filter(function(plugin) { return plugin.description.contains('<OrangeOverlay>'); }); if (parameters.length === 0) { throw new Error("Couldn't find Hudell's OrangeOverlay parameters."); } $.Parameters = parameters[0].parameters; $.Param = {}; $.Param.organizedFolders = $.Parameters["Organized Folders"] == 'true'; $.Param.parallaxLayerFileName = $.Parameters["Parallax Layer Filename"] || 'par'; $.Param.groundLayerFileName = $.Parameters["Ground Layer Filename"] || 'ground'; $.Param.lightLayerFileName = $.Parameters["Light Layer Filename"] || 'light'; $.Param.shadowLayerFileName = $.Parameters["Shadow Layer Filename"] ||'shadow'; $.Param.lightOpacity = Number($.Parameters["Light Opacity"] || 185); $.Param.quickStart = $.Parameters["Quick Start"]!= 'false'; $.Param.bushRegionId = Number($.Parameters["Bush Region ID"] || 7); $.Param.fogSwitchId = Number($.Parameters["Fog Switch ID"] || 1); $.Param.lightSwitchId = Number($.Parameters["Light Switch ID"] || 2); $.Param.parallaxSwitchId = Number($.Parameters["Parallax Switch ID"] || 3); $.Param.shadowSwitchId = Number($.Parameters["Shadow Switch ID"] || 4); $.clearParams = function() { $.fogFileNameCommand = ''; $.fogOpacityCommand = 0; $.fogMoveXCommand = 0; $.fogMoveYCommand = 0; $.fodBlendCommand = 0; $.fogDurationCommand = 0; $.overlayFadeOut = false; $.fogFadeOut = 1; $.fogFileName = ''; $.fogOpacity = 255; $.fogMoveX = 0; $.fogMoveY = 0; $.fogBlendMode = 0; $.fogDuration = 1; $.updateFog = false; $.updateLight = false; $.lightName = ''; $.updateShadow = false; $.shadowName = ''; $.updateParallax = false; $.parallaxName = ''; $.updateGround = false; $.groundName = ''; $.newFogToCreate = false; $.newFogName = ''; $.newFogId = ''; $.newFogOpacity = 0; $.newFogZ = 22; $.newFogBlend = 0; $.newFogXMove = 0; $.newFogYMove = 0; $.fogToRemove = 0; $.defOpacity = 0; $.defDuration = 1; $.defTransition = 0; $.fogNewX = 0; $.fogNewY = 0; }; $.clearParams(); var oldDataManager_setupNewGame = DataManager.setupNewGame; DataManager.setupNewGame = function() { oldDataManager_setupNewGame.call(this); if ($.Param.quickStart) { if ($.Param.fogSwitchId > 0) { $gameSwitches.setValue($.Param.fogSwitchId, true); } if ($.Param.lightSwitchId > 0) { $gameSwitches.setValue($.Param.lightSwitchId, true); } if ($.Param.parallaxSwitchId > 0) { $gameSwitches.setValue($.Param.parallaxSwitchId, true); } if ($.Param.shadowSwitchId > 0) { $gameSwitches.setValue($.Param.shadowSwitchId, true); } } }; var oldSpritesetMap_createLowerLayer = Spriteset_Map.prototype.createLowerLayer; Spriteset_Map.prototype.createLowerLayer = function() { $.clearParams(); this._fogList = []; oldSpritesetMap_createLowerLayer.call(this); }; Spriteset_Map.prototype.loadBitmap = function(folderName, fileName) { if ($.Param.organizedFolders) { return ImageManager.loadBitmap('img/overlays/' + folderName + '/', fileName); } return ImageManager.loadParallax(fileName); }; Spriteset_Map.prototype.createLayer = function(folderName, fileNamePrefix, tagName, zValue, switchId, maxOpacity) { if (!$dataMap) return null; if (!$dataMap.meta) return null; if (!$dataMap.meta[tagName] &&!$dataMap.meta.all) { return null; } if (maxOpacity === undefined) maxOpacity = 255; var layer = new Sprite(); layer.bitmap = this.loadBitmap(folderName, fileNamePrefix + $gameMap._mapId); layer.z = zValue; this._tilemap.addChild(layer); if (switchId > 0) { layer.opacity = $gameSwitches.value(switchId)? maxOpacity : 0; } return layer; }; Spriteset_Map.prototype.createGroundLayer = function() { this._groundLayer = this.createLayer('grounds', $.Param.groundLayerFileName, 'ground', 1, 0); }; Spriteset_Map.prototype.createParallaxLayer = function() { this._parallaxLayer = this.createLayer('pars', $.Param.parallaxLayerFileName, 'par', 20, $.Param.parallaxSwitchId); }; Spriteset_Map.prototype.createShadowLayer = function() { this._shadowLayer = this.createLayer('shadows', $.Param.shadowLayerFileName,'shadow', 21, $.Param.shadowSwitchId); }; Spriteset_Map.prototype.getOverlayVariable = function(variableName) { if (!$dataMap) return false; if (!$dataMap.meta) return false; if ($dataMap.meta[variableName] === undefined) return false; var value = $dataMap.meta[variableName].trim(); if (value[0] == '$') { value = value.slice(1); var variableId = parseInt(value, 10); if (!isNaN(variableId) && variableId > 0) { return $gameVariables.value(variableId); } } return value; }; Spriteset_Map.prototype.createFogItem = function(id, fileName, xMove, yMove, opacity, blend, z) { if (!this._fogList[id]) { var data = {}; data.bitmap = this.loadBitmap('fogs', fileName); if (!data.bitmap) return; data.sprite = new TilingSprite(); data.sprite.bitmap = data.bitmap; data.sprite.width = Graphics.width; data.sprite.height = Graphics.height; data.sprite.opacity = opacity; data.sprite.blendMode = blend; data.sprite.z = z; data.newX = 0; data.newY = 0; data.xMove = xMove; data.yMove = yMove; this._fogList[id] = data; this._tilemap.addChild(data.sprite); } $.newFogToCreate = false; }; Spriteset_Map.prototype.createFogLayer = function() { $.fogFileName = this.getOverlayVariable('fogName'); $.fogOpacity = parseInt(this.getOverlayVariable('fogOpacity'), 10) || 255; $.fogMoveX = parseFloat(this.getOverlayVariable('xMove'), 10) || 0; $.fogMoveY = parseFloat(this.getOverlayVariable('yMove'), 10) || 0; $.fogBlendMode = parseInt(this.getOverlayVariable('fogBlend'), 10) || 0; $.fogDuration = parseInt(this.getOverlayVariable('fogDuration'), 10) || 1; if (!$.fogFileName &&!$.fogFileNameCommand) return; var fileName = $.fogFileName; if (!!$.fogFileNameCommand && $.fogFileNameCommand!== '') { fileName = $.fogFileNameCommand; } var bitmap = this.loadBitmap('fogs', fileName); if (!bitmap) return; var layer = new TilingSprite(); layer.bitmap = bitmap; layer.width = Graphics.width; layer.height = Graphics.height; layer.blendMode = $.fogBlendMode; layer.opacity = 0; layer.origin.x = $gameMap.displayX() * $gameMap.tileWidth(); layer.origin.y = $gameMap.displayY() * $gameMap.tileHeight(); layer.z = 22; $.fogNewX = 0; $.fogNewY = 0; this._tilemap.addChild(layer); this._fogLayer = layer; $.updateFog = false; }; Spriteset_Map.prototype.createLightLayer = function() { this._lightLayer = this.createLayer('lights', $.Param.lightLayerFileName, 'light', 23, $.Param.lightSwitchId, $.Param.lightOpacity); if (!!this._lightLayer) { this._lightLayer.blendMode = 1; } }; var oldSpritesetMap_createCharacters = Spriteset_Map.prototype.createCharacters; Spriteset_Map.prototype.createCharacters = function() { this.createGroundLayer(); oldSpritesetMap_createCharacters.call(this); this.createParallaxLayer(); this.createShadowLayer(); this.createFogLayer(); this.createLightLayer(); }; Spriteset_Map.prototype.updateLayer = function(layerName, update, folderName, fileNamePrefix, tagName, zValue, switchId, maxOpacity, opacityChange) { if (maxOpacity === undefined) maxOpacity = 255; if (opacityChange === undefined) opacityChange = 10; var layer = this[layerName]; if (!layer) { layer = this.createLayer(folderName, fileNamePrefix, tagName, zValue, switchId, maxOpacity); update = false; } if (!!layer) { layer.x = $gameMap.displayX() * (0 - $gameMap.tileWidth()); layer.y = $gameMap.displayY() * (0 - $gameMap.tileHeight()); if (switchId > 0) { if ($gameSwitches.value(switchId)) { if (layer.opacity < maxOpacity) { layer.opacity += opacityChange; } if (layer.opacity > maxOpacity) { layer.opacity = maxOpacity; } } else { if (layer.opacity > 0) { layer.opacity -= opacityChange; } if (layer.opacity < 0) { layer.opacity = 0; } } } if (update) { layer.bitmap = this.loadBitmap(folderName, fileNamePrefix + $gameMap._mapId); } this[layerName] = layer; } }; Spriteset_Map.prototype.updateGroundLayer = function() { this.updateLayer('_groundLayer', $.updateGround, 'grounds', $.Param.groundLayerFileName, 'ground', 1, 0); $.updateGround = false; }; Spriteset_Map.prototype.updateParallaxLayer = function() { this.updateLayer('_parallaxLayer', $.updateParallax, 'pars', $.Param.parallaxLayerFileName, 'par', 20, $.Param.parallaxSwitchId); $.updateParallax = false; }; Spriteset_Map.prototype.updateShadowLayer = function() { this.updateLayer('_shadowLayer', $.updateShadow,'shadows', $.Param.shadowLayerFileName,'shadow', 21, $.Param.shadowSwitchId); $.updateShadow = false; }; Spriteset_Map.prototype.updateFogItem = function(id) { var data = this._fogList[id]; if (!data) return; data.newX += data.xMove; data.newY += data.yMove; data.sprite.origin.x = $gameMap.displayX() * $gameMap.tileWidth() - data.newX; data.sprite.origin.y = $gameMap.displayY() * $gameMap.tileHeight() - data.newY; }; Spriteset_Map.prototype.removeFogItem = function(id) { if (!this._fogList[id]) return; delete this._fogList[id]; }; Spriteset_Map.prototype.updateFogLayer = function() { if (!this._fogLayer) { this.createFogLayer(); if (!this._fogLayer) { return; } } var newOpacity; this._fogLayer.blendMode = $.fodBlendCommand === 0? 0 : 1; if ($.fogMoveXCommand!== 0) { $.fogNewX += $.fogMoveXCommand; } else { $.fogNewX += $.fogMoveX; } if ($.fogMoveYCommand!== 0) { $.fogNewY += $.fogMoveYCommand; } else { $.fogNewY += $.fogMoveY; } this._fogLayer.origin.x = $gameMap.displayX() * $gameMap.tileWidth() - $.fogNewX; this._fogLayer.origin.y = $gameMap.displayY() * $gameMap.tileHeight() - $.fogNewY; if ($.Param.fogSwitchId > 0 && $gameSwitches.value($.Param.fogSwitchId)) { if ($.fogOpacityCommand!== 0) { $.defOpacity = $.fogOpacityCommand; } else { $.defOpacity = $.fogOpacity; } if ($.fogDurationCommand!== 0) { $.defDuration = $.fogDurationCommand; } else { $.defDuration = $.fogDuration; } $.defTransition = $.defOpacity / $.defDuration; } else if (this._fogLayer.opacity > 0) { newOpacity = this._fogLayer.opacity - 10; if (newOpacity < 0) newOpacity = 0; this._fogLayer.opacity = newOpacity; } if ($.overlayFadeOut) { $.defTransition = $.defOpacity / $.fogFadeOut; if (this._fogLayer.opacity > 0) { newOpacity = this._fogLayer.opacity - $.defTransition; if (newOpacity < 0) newOpacity = 0; this._fogLayer.opacity = newOpacity; } else { $.overlayFadeOut = false; $.fogOpacityCommand = 0; $.defOpacity = 0; if ($.Param.fogSwitchId > 0) { $gameSwitches.setValue($.Param.fogSwitchId, false); } } } else if (this._fogLayer.opacity < $.defOpacity) { newOpacity = this._fogLayer.opacity + $.defTransition; if (newOpacity > $.defOpacity) newOpacity = $.defOpacity; this._fogLayer.opacity = newOpacity; } if ($.updateFog &&!!$.fogFileNameCommand && $.fogFileNameCommand!== '') { this._fogLayer.bitmap = this.loadBitmap('fogs', $.fogFileNameCommand); $.updateFog = false; } }; Spriteset_Map.prototype.updateLightLayer = function() { this.updateLayer('_lightLayer', $.updateLight, 'lights', $.Param.lightLayerFileName, 'light', 23, $.Param.lightSwitchId, $.Param.lightOpacity, 1); $.updateLight = false; }; var oldSpritesetMap_updateTilemap = Spriteset_Map.prototype.updateTilemap; Spriteset_Map.prototype.updateTilemap = function() { this.updateGroundLayer(); this.updateParallaxLayer(); this.updateShadowLayer(); this.updateFogLayer(); this.updateLightLayer(); oldSpritesetMap_updateTilemap.call(this); var len = this._fogList.length; if (len > 0) { for (var i = 0; i < len; i++) { if (!!this._fogList[i]) { this.updateFogItem(i); } } } if ($.newFogToCreate) { this.createFogItem($.newFogId, $.newFogName, $.newFogXMove, $.newFogYMove, $.newFogOpacity, $.newFogBlend, $.newFogZ); $.newFogToCreate = false; } if ($.fogToRemove > 0) { this.removeFogItem($.fogToRemove); $.fogToRemove = 0; } }; Game_Interpreter.prototype.overlayPluginCommand = function(args) { if (args.length < 2) return; switch(args[0].toLowerCase()) { case 'fog' : if (args.length < 5) return; if (!!args[1] &&!!args[2] &&!!args[3] &&!!args[4]) { $.updateFog = true; $.fogFileNameCommand = args[1]; $.fogOpacityCommand = parseInt(args[2], 10); $.fogMoveXCommand = parseFloat(args[3], 10); $.fogMoveYCommand = parseFloat(args[4], 10); if (args.length > 5 &&!!args[5]) { $.fodBlendCommand = parseInt(args[5], 10); } if (args.length > 6 &&!!args[6]) { $.fogDurationCommand = parseInt(args[6], 10); } } break; case 'fadeout' : if (!!args[1]) { $.overlayFadeOut = true; $.fogFadeOut = parseInt(args[1], 10); } break; case 'light' : if (!!args[1]) { $.updateLight = true; $.lightName = args[1]; } break; case'shadow' : if (!!args[1]) { $.updateShadow = true; $.shadowName = args[1]; } break; case 'par' : if (!!args[1]) { $.updateParallax = true; $.parallaxName = args[1]; } break; case 'ground' : if (!!args[1]) { $.updateGround = true; $.groundName = args[1]; } break; case 'addfog' : if (args.length < 6) return; if (!args[1]) return; $.newFogToCreate = true; $.newFogName = args[1]; $.newFogId = parseInt(args[2], 10); $.newFogOpacity = parseInt(args[3], 10); $.newFogXMove = parseFloat(args[4], 10); $.newFogYMove = parseFloat(args[5], 10); if (args.length > 6) { $.newFogBlend = parseInt(args[6], 10); } else { $.newFogBlend = 0; } if (args.length > 7) { $.newFogZ = parseInt(args[7], 10); } else { $.newFogZ = 22; } break; case'removefog' : $.fogToRemove = parseInt(args[1], 10); break; default : console.log('unknown command: ', args[0]); break; } }; var oldGameInterpreter_pluginCommand = Game_Interpreter.prototype.pluginCommand; Game_Interpreter.prototype.pluginCommand = function (command, args) { if (command.toLowerCase() == 'overlay') { this.overlayPluginCommand(args); return; } oldGameInterpreter_pluginCommand.apply(this, arguments); }; if ($.Param.bushRegionId > 0) { var oldIsBush = Game_Map.prototype.isBush; Game_Map.prototype.isBush = function(x, y) { if (oldIsBush.call(this, x, y) === true) return true; if (this.isValid(x, y)) { return $gameMap.regionId(x, y) == $.Param.bushRegionId; } return false; }; } if (!!Utils.RPGMAKER_VERSION && Utils.RPGMAKER_VERSION == "1.2.0") { TilingSprite.prototype.generateTilingTexture = function(arg) { PIXI.TilingSprite.prototype.generateTilingTexture.call(this, arg); // Purge from Pixi's Cache if (Graphics.isWebGL()) { if (!!this.tilingTexture && this.tilingTexture.canvasBuffer) { PIXI.Texture.removeTextureFromCache(this.tilingTexture.canvasBuffer.canvas._pixiId); } } }; } var oldSpriteCharacter_startBallon = Sprite_Character.prototype.startBalloon; Sprite_Character.prototype.startBalloon = function() { oldSpriteCharacter_startBallon.call(this); if (!!this._balloonSprite) { this._balloonSprite.z = 30; } }; var oldSpriteAnimation_initMembers = Sprite_Animation.prototype.initMembers; Sprite_Animation.prototype.initMembers = function() { oldSpriteAnimation_initMembers.apply(this, arguments); this.z = 30; }; })(Hudell.OrangeOverlay); OrangeOverlay = Hudell.OrangeOverlay; Imported.OrangeOverlay = 1.1; ======================= File: OrangeLighting/OrangeLightingPlayerLight.js ======================= /*============================================================================= * Orange Lighting - Player Light * By Hudell - www.hudell.com * OrangeLightingPlayerLight.js * Version: 1.0.1 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Player Lights <OrangeLightingPlayerLight> * @author Hudell * * @param playerRadius * @desc The size of the light globe around the player * @default 40 * * @param playerColor * @desc The color of the light around the player * @default #FFFFFF * * @param playerFlicker * @desc Should the plugin flick the light around the player? * @default false * * @param flashlightSwitch * @desc When this switch is on, a flashlight will be added to the player. * @default 0 * * * @help * ============================================================================ * Hudell's Plugins * ============================================================================ * * Check out my website: * http://hudell.com * *=============================================================================*/ if (!Hudell ||!Hudell.OrangeLighting) { throw new Error("Couldn't find Hudell's OrangeLighting plugin. Please add it before this add-on."); } (function(lightSystem) { "use strict"; lightSystem.addOns.PlayerLight = {}; (function(playerLight){ var parameters = $plugins.filter(function(plugin) { return plugin.description.contains('<OrangeLightingPlayerLight>'); }); if (parameters.length === 0) { throw new Error("Couldn't find Hudell's OrangeLightingPlayerLight parameters."); } playerLight.Parameters = parameters[0].parameters; playerLight.Param = {}; playerLight.Param.playerRadius = Number(playerLight.Parameters.playerRadius || 40); playerLight.Param.playerColor = playerLight.Parameters.playerColor || '#FFFFFF'; playerLight.Param.playerFlicker = (playerLight.Parameters.playerFlicker || "false").toUpperCase() === "TRUE"; playerLight.Param.flashlightSwitch = Number(playerLight.Parameters.flashlightSwitch || 0); playerLight.enabled = true; playerLight.shouldShowFlashlight = function(){ return playerLight.Param.flashlightSwitch > 0 && $gameSwitches.value(playerLight.Param.flashlightSwitch); }; playerLight.getPlayerPosition = function() { return lightSystem.getCharacterPosition($gamePlayer); }; //Refreshes the player's light playerLight.refresh = function() { if (!playerLight.enabled) return; lightSystem._showingFlashlight = playerLight.shouldShowFlashlight(); var canvas = this._maskBitmap.canvas; var ctx = canvas.getContext("2d"); ctx.globalCompositeOperation = 'lighter'; var positions = playerLight.getPlayerPosition(); if (playerLight.shouldShowFlashlight()) { this._maskBitmap.makeFlashlightEffect(positions[0], positions[1], 0, playerLight.Param.playerRadius, playerLight.Param.playerColor, 'black', positions[2]); } else { if (playerLight.Param.playerRadius < 100) { this._maskBitmap.radialgradientFillRect(positions[0], positions[1], 0, playerLight.Param.playerRadius, '#999999', 'black', playerLight.Param.playerFlicker); } else { this._maskBitmap.radialgradientFillRect(positions[0], positions[1], 20, playerLight.Param.playerRadius, playerLight.Param.playerColor, 'black', playerLight.Param.playerFlicker); } } ctx.globalCompositeOperation ='source-over'; }; playerLight.update = function(){ if (!playerLight.enabled) return; if (playerLight.shouldShowFlashlight()!== lightSystem._showingFlashlight) { lightSystem.dirty = true; } if (playerLight.Param.playerFlicker &&!playerLight.shouldShowFlashlight()) { lightSystem.dirty = true; } }; lightSystem.on('afterRefreshMask', playerLight.refresh); lightSystem.on('updateMask', playerLight.update); (function($) { playerLight.Game_Player_prototype_update = $.update; $.update = function(sceneActive) { var oldD = this._direction; var oldX = this._x; var oldY = this._y; playerLight.Game_Player_prototype_update.call(this, sceneActive); if (this.isMoving() || oldD!== this._direction || oldX!== this._x || oldY!== this._y) { lightSystem.dirty = true; } }; })(Game_Player.prototype); })(lightSystem.addOns.PlayerLight); })(Hudell.OrangeLighting); Imported["OrangeLighting.PlayerLight"] = 1.0; ======================= File: OrangeMapChangeEvent.js ======================= <gh_stars>10-100 /*============================================================================= * Orange - Map Change Event * By Hudell - www.hudell.com * OrangeMapChangeEvent.js * Version: 1.0 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Will let you call a common event everytime the player is transfered to a new map * * @author Hudell * * @param commonEventId * @desc The number of the common event to call * @default 0 * * @help * ============================================================================ * Latest Version * ============================================================================ * * Get the latest version of this script on * http://link.hudell.com/map-change-event * *=============================================================================*/ var Imported = Imported || {}; var OrangeMapChangeEvent = OrangeMapChangeEvent || {}; (function($) { "use strict"; $.Parameters = PluginManager.parameters('OrangeMapChangeEvent'); $.Param = $.Param || {}; $.Param.commonEventId = Number($.Parameters['commonEventId'] || 0); var oldGamePlayer_performTransfer = Game_Player.prototype.performTransfer; Game_Player.prototype.performTransfer = function() { if (this.isTransferring()) { if ($.Param.commonEventId!== undefined && $.Param.commonEventId > 0) { $gameTemp.reserveCommonEvent($.Param.commonEventId); } } oldGamePlayer_performTransfer.call(this); }; })(OrangeMapChangeEvent); if (Imported['MVCommons']!== undefined) { PluginManager.register("OrangeMapChangeEvent", "1.0.0", "Will let you call a common event everytime the player is transfered to a new map", { email: "<EMAIL>", name: "Hudell", website: "http://www.hudell.com" }, "2015-10-19"); } else { Imported["OrangeMapChangeEvent"] = true; } ======================= File: OrangeInstantTriggerMouseEvents.js ======================= <reponame>Ghabry/mv-plugins<gh_stars>10-100 /*============================================================================= * Orange - Instant Trigger Mouse Events * By Hudell - www.hudell.com * OrangeInstantTriggerMouseEvents.js * Version: 1.0 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc This plugin will trigger events instantly when you click on them * @author Hudell * * @help * ============================================================================ * Latest Version * ============================================================================ * * Get the latest version of this script on * http://link.hudell.com/trigger-mouse-events * *=============================================================================*/ var Imported = Imported || {}; var OrangeInstantTriggerMouseEvents = OrangeInstantTriggerMouseEvents || {}; (function($) { "use strict"; Scene_Map.prototype.tryTriggeringEvent = function() { if ($gameMap.isAnyEventStarting() || $gameMap.isEventRunning() ||!$gamePlayer.canStartLocalEvents()) { return false; } if (TouchInput.isTriggered() || this._touchCount > 0) { if (TouchInput.isPressed()) { if (this._touchCount === 0 || this._touchCount >= 15) { var x = $gameMap.canvasToMapX(TouchInput.x); var y = $gameMap.canvasToMapY(TouchInput.y); var events = $gameMap.eventsXy(x, y); if (events.length === 0) { return false; } for (var i = 0; i < events.length; i++) { if (events[i].isTriggerIn([0])) { events[i].start(); return true; } } } } } return false; }; var oldSceneMap_processMapTouch = Scene_Map.prototype.processMapTouch; Scene_Map.prototype.processMapTouch = function() { if (!this.tryTriggeringEvent()) { oldSceneMap_processMapTouch.call(this); } }; })(OrangeInstantTriggerMouseEvents); // If MVCommons is imported, register the plugin with it's PluginManager. if (Imported['MVCommons']!== undefined) { PluginManager.register("OrangeInstantTriggerMouseEvents", "1.0.0", "This plugin will trigger events instantly when you click on them", { email: "<EMAIL>", name: "Hudell", website: "http://www.hudell.com" }, "2015-10-22"); } else { Imported["OrangeInstantTriggerMouseEvents"] = true; } ======================= File: OrangeAutoSave.js ======================= /*============================================================================= * Orange - AutoSave * By Hudell - www.hudell.com * OrangeAutoSave.js * Version: 1.1.1 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Automatically save the game on map change <OrangeAutoSave> * @author Hudell * * @param saveSlot * @desc Set this to the number of the slot where the plugin should save * @default 1 * * @param saveOnPluginTransfer * @desc save game automatically on any kind of player transfer * @default false * * @param saveOnTransferCommand * @desc save game automatically when the "transfer player" command is used * @default true * * @param autoSaveSlot * @desc Instead of using the saveSlot param, the plugin will pick the last used slot * @default false * * @help * ============================================================================ * Hudell's Plugins * ============================================================================ * * Check out my website: * http://hudell.com * * ============================================================================ * * You only need to enable saveOnPluginTransfer if you have other plugins * that transfer the player and you want the game to be saved on those * transfers too. * * When you enable it, this plugin will have to change the "new game" and * "load game" commands to make sure the game isn't autosaved by them too. * * ============================================================================ * * You can trigger an auto save with the following script call: * * DataManager.autoSave(); * *=============================================================================*/ var Imported = Imported || {}; var Hudell = Hudell || {}; Hudell.OrangeAutoSave = Hudell.OrangeAutoSave || {}; (function($) { "use strict"; var parameters = $plugins.filter(function(plugin) { return plugin.description.contains('<OrangeAutoSave>'); }); if (parameters.length === 0) { throw new Error("Couldn't find Hudell's OrangeAutoSave parameters."); } $.Parameters = parameters[0].parameters; $.Param = {}; $.enabled = true; $.skipCalls = 0; // Param validation if ($.Parameters.saveSlot!== "false") { $.Param.saveSlot = Number($.Parameters.saveSlot || 1); } else { $.Param.saveSlot = 99; } $.Param.saveOnPluginTransfer = ($.Parameters.saveOnPluginTransfer || "").toLowerCase() === "true"; $.Param.saveOnTransferCommand = ($.Parameters.saveOnTransferCommand || "").toLowerCase()!== "false"; $.Param.autoSaveSlot = ($.Parameters.autoSaveSlot || "").toLowerCase()!== "false"; $.Param.currentSaveSlot = $.Param.saveSlot; // Code $.getSaveSlot = function() { return $.Param.currentSaveSlot; }; $.skipNextCall = function() { $.skipCalls++; }; $.doAutoSave = function() { $gameSystem.onBeforeSave(); DataManager.saveGameWithoutRescue($.getSaveSlot()); }; //Only change the performTransfer method if it's activated through params if ($.Param.saveOnPluginTransfer) { $.oldGamePlayer_performTransfer = Game_Player.prototype.performTransfer; Game_Player.prototype.performTransfer = function() { $.oldGamePlayer_performTransfer.call(this); if ($.skipCalls > 0) { $.skipCalls--; return; } if (this._newMapId > 0) { if ($.enabled) { $.doAutoSave(); } } }; //Changes setupNewGame so that the initial player transfer doesn't trigger an auto save $.oldDataManager_setupNewGame = DataManager.setupNewGame; DataManager.setupNewGame = function() { $.skipNextCall(); $.oldDataManager_setupNewGame.call(this); }; //Changes reloadMapIfUpdated so that loading a game doesn't trigger an auto save $.oldSceneLoad_reloadMapIfUpdated = Scene_Load.prototype.reloadMapIfUpdated; Scene_Load.prototype.reloadMapIfUpdated = function() { if ($gameSystem.versionId()!== $dataSystem.versionId) { $.skipNextCall(); } $.oldSceneLoad_reloadMapIfUpdated.call(this); }; //Only change the command if the performTransfer is disabled and the transfer command is enabled } else if ($.Param.saveOnTransferCommand) { $.oldGameInterpreter_command201 = Game_Interpreter.prototype.command201; Game_Interpreter.prototype.command201 = function() { $.oldGameInterpreter_command201.call(this); if ($gamePlayer.isTransferring() && $.enabled) { $.doAutoSave(); } }; } if ($.Param.autoSaveSlot) { var oldDataManager_saveGameWithoutRescue = DataManager.saveGameWithoutRescue; DataManager.saveGameWithoutRescue = function(savefileId) { oldDataManager_saveGameWithoutRescue.call(this, savefileId); $.Param.currentSaveSlot = savefileId; }; var oldDataManager_loadGameWithoutRescue = DataManager.loadGameWithoutRescue; DataManager.loadGameWithoutRescue = function(savefileId) { oldDataManager_loadGameWithoutRescue.call(this, savefileId); $.Param.currentSaveSlot = savefileId; }; var autoSaveSlot_setupNewGame = DataManager.setupNewGame; DataManager.setupNewGame = function() { autoSaveSlot_setupNewGame.call(this); $.Param.currentSaveSlot = $.Param.saveSlot; }; } DataManager.autoSave = $.doAutoSave; })(Hudell.OrangeAutoSave); Imported.OrangeAutoSave = 1.1; ======================= File: OrangeMoveCharacterTo.js ======================= /*============================================================================= * Orange - Move Character To * By Hudell - www.hudell.com * OrangeMoveCharacterTo.js * Version: 1.3 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc This plugin adds a script call and a plugin command you can use to move the player or an event to a specific position. * @author Hudell * * @param failedMovementDelay * @desc How many frames should the characters wait before trying to move again after failing to move once. * @default 30 * * @help * Plugin Commands Examples: * move event 10 to position 15 20 and face left * move player to event 5 * move event 7 to player and follow * clear player path * clear event 7 path * * Script calls (can be used inside move routes): * this.setDestination(x, y, d); * this.setCharacterDestination(eventId, follow) * * Example: * this.setDestination(15, 20, 2); * this.setCharacterDestination(10, true); * * Direction numbers are the RPG Maker default: * left = 4 * right = 6 * top = 8 * down = 2 * * ============================================================================ * Latest Version * ============================================================================ * * Get the latest version of this script on * http://link.hudell.com/move-character-to * *=============================================================================*/ var Imported = Imported || {}; var OrangeMoveCharacterTo = OrangeMoveCharacterTo || {}; (function($) { "use strict"; var parameters = PluginManager.parameters('OrangeMoveCharacterTo') || {}; var failedMovementDelay = Number(parameters.failedMovementDelay || 30); Game_Interpreter.prototype.checkOldOrangeMoveToFormat = function(command, args) { if (command.toUpperCase() === 'ORANGEMOVETO') { var character = this.character(parseInt(args[0], 10)); if (args.length > 2) { var x = parseFloat(args[1]); var y = parseFloat(args[2]); var d = 0; if (args.length > 3) { switch(args[3].toUpperCase()) { case 'LEFT' : d = 4; break; case 'RIGHT' : d = 6; break; case 'UP' : d = 8; break; case 'DOWN' : d = 2; break; default : d = parseInt(args[3], 10); break; } } character.setDestination(x, y, d); } else { character.clearDestination(); } } }; Game_Interpreter.prototype.checkOrangeClearPathCommand = function(command, args) { if (command.toUpperCase()!== 'CLEAR') return; if (args.length < 2) return; var nextIndex = 0; var eventId = undefined; if (args[0].toUpperCase() === 'EVENT') { eventId = parseInt(args[1], 10); nextIndex = 2; } else if (args[0].toUpperCase() === 'PLAYER') { eventId = -1; nextIndex = 1; } else if (args[0].toUpperCase() === 'THIS' && args[1].toUpperCase() === 'EVENT') { eventId = 0; nextIndex = 2; } if (args.length > nextIndex && args[nextIndex].toUpperCase() === 'PATH') { var character = this.character(eventId); if (character!== undefined && character!== null) { character.clearDestination(); } } }; Game_Interpreter.prototype.checkNewOrangeMoveToFormat = function(command, args) { if (command.toUpperCase()!== 'MOVE') return; if (args.length <= 4) return; var eventId = undefined; var newEventId = undefined; var newX = undefined; var newY = undefined; var nextIndex = 0; var follow = false; var direction = 0; if (args[0].toUpperCase() === 'EVENT') { eventId = parseInt(args[1], 10); nextIndex = 2; } else if (args[0].toUpperCase() === 'PLAYER') { eventId = -1; nextIndex = 1; } else if (args[0].toUpperCase === 'THIS' && args[1].toUpperCase() === 'EVENT') { eventId = 0; nextIndex = 2; } else { return; } if (args[nextIndex].toUpperCase()!== 'TO') return; nextIndex++; if (args.length <= nextIndex) return; if (args[nextIndex].toUpperCase() === 'EVENT') { nextIndex++; if (args.length <= nextIndex) return; newEventId = parseInt(args[nextIndex], 10); nextIndex++; } else if (args[nextIndex].toUpperCase() === 'PLAYER') { newEventId = -1; nextIndex++; } else if (args[nextIndex].toUpperCase() === 'POSITION') { if (args.length <= nextIndex + 2) return; newX = parseFloat(args[nextIndex + 1]); newY = parseFloat(args[nextIndex + 2]); nextIndex += 3; } if (args.length > nextIndex +1) { if (args[nextIndex].toUpperCase() === 'AND') { nextIndex++; if (args[nextIndex].toUpperCase() === 'FOLLOW') { follow = true; nextIndex++; } else if (args[nextIndex].toUpperCase() === 'FACE' || args[nextIndex].toUpperCase() === 'TURN') { nextIndex++; if (args.length > nextIndex) { if (args[nextIndex].toUpperCase() === 'LEFT') { direction = 4; } else if (args[nextIndex].toUpperCase() === 'RIGHT') { direction = 6; } else if (args[nextIndex].toUpperCase() === 'UP') { direction = 8; } else if (args[nextIndex].toUpperCase() === 'DOWN') { direction = 2; } else { direction = parseInt(args[nextIndex], 10); } nextIndex++; } } } } var character = this.character(eventId); if (newEventId!== undefined) { var newCharacter = this.character(newEventId); if (newCharacter === undefined || newCharacter === null) return; character.setCharacterDestination(newCharacter, follow); } else { character.setDestination(newX, newY, direction); } }; var oldGameInterpreter_pluginCommand = Game_Interpreter.prototype.pluginCommand; Game_Interpreter.prototype.pluginCommand = function(command, args) { oldGameInterpreter_pluginCommand.call(this, command, args); this.checkOldOrangeMoveToFormat.call(this, command, args); this.checkNewOrangeMoveToFormat.call(this, command, args); this.checkOrangeClearPathCommand.call(this, command, args); }; var oldGameCharacterBase_updateStop = Game_CharacterBase.prototype.updateStop; Game_CharacterBase.prototype.updateStop = function() { var direction = undefined; var distance = undefined; if (this._orangeMovementDelay!== undefined && this._orangeMovementDelay > 0) { this._orangeMovementDelay--; return; } if (this._xDestination!== undefined && this._yDestination!== undefined) { if (this._xDestination == this._x && this._yDestination == this._y) { // If the character reached the destination, check if there's a direction to face if (this._dDestination!== undefined && this._dDestination!== 0) { if (this.isMoving()) { return; } this._direction = this._dDestination; } this.clearDestination(); } if (this._xDestination!== undefined) { if (!this.isMoving()) { var xDistance = this._x - this._xDestination; var yDistance = this._y - this._yDestination; // Check if there's any additional partial tile to walk if (Math.abs(xDistance) < 1 && Math.abs(yDistance) < 1) { if (xDistance < 0) { this._direction = 6; this._x = this._xDestination; return; } else if (yDistance < 0) { this._direction = 2; this._y = this._yDestination; return; } else if (xDistance > 0) { this._direction = 4; this._x = this._xDestination; return; } else if (yDistance > 0) { this._y = this._yDestination; this._direction = 8; return; } } else { //Check if there's any partial position to fix before start walking if (this._x - Math.floor(this._x) || this._y - Math.floor(this._y)) { if (this._xDestination > this._x) { this._direction = 6; this._x = Math.ceil(this._x); } else { this._direction = 4; this._x = Math.floor(this._x); } if (this._yDestination > this._y) { this._direction = 2; this._y = Math.ceil(this._y); } else { this._direction = 8; this._y = Math.floor(this._y); } return; } } direction = this.findDirectionTo(Math.floor(this._xDestination), Math.floor(this._yDestination)); if (direction > 0) { this.moveStraight(direction); if (!this.isMovementSucceeded()) { this._orangeMovementDelay = failedMovementDelay; } return; } } } } if (this._destinationCharacter!== undefined) { if (this._destinationCharacter._x === this._x && this._destinationCharacter._y == this._y) { //If the stalker reached the character, check if it needs to keep following it if (this._followCharacter!== true) { this.clearDestination(); } else { return; } } if (this._destinationCharacter!== undefined) { if (!this.isMoving()) { direction = this.findDirectionTo(this._destinationCharacter._x, this._destinationCharacter._y); if (direction > 0) { this.moveStraight(direction); if (!this.isMovementSucceeded()) { //If failed to move, and it's not set to follow the character and distance is less than 1 tile, stop moving. if (this._followCharacter!== true) { distance = Math.abs(this._x - this._destinationCharacter._x) + Math.abs(this._y - this._destinationCharacter._y); if (distance <= 1) { this.clearDestination(); return; } } this._orangeMovementDelay = failedMovementDelay; } return; } } } } oldGameCharacterBase_updateStop.call(this); }; // Change the advanceMoveRouteIndex to only advance the index when the character reach the destination. var oldGameCharacter_advanceMoveRouteIndex = Game_Character.prototype.advanceMoveRouteIndex; Game_Character.prototype.advanceMoveRouteIndex = function() { if (this._xDestination === undefined && this._yDestination === undefined && this._destinationCharacter === undefined) { oldGameCharacter_advanceMoveRouteIndex.call(this); } }; // Clears the destination automatically if a new move route is set var oldGameCharacter_setMoveRoute = Game_Character.prototype.setMoveRoute; Game_Character.prototype.setMoveRoute = function(moveRoute) { this.clearDestination(); oldGameCharacter_setMoveRoute.call(this, moveRoute); }; Game_CharacterBase.prototype.setDestination = function(x, y, d) { if (this._x!= x || this._y!= y || this.isMoving()) { this._xDestination = x; this._yDestination = y; if (d!== undefined) { this._dDestination = d; } } else if (d!== undefined && d!== 0) { this._direction = d; } }; Game_CharacterBase.prototype.setCharacterDestination = function(character, follow) { if (follow === undefined) follow = false; if (typeof(character) == "number") { character = $gameMap._interpreter.character(character); } if (character === undefined) return; if (follow === true) { this._destinationCharacter = character; this._followCharacter = true; } else { if (this._x!= character._x || this._y!= character._y || this.isMoving()) { this._destinationCharacter = character; this._followCharacter = false; } } }; //Updates Game_Temp.prototype.setDestination to only be executed when the player has no destination set on itself var oldGameTemp_setDestination = Game_Temp.prototype.setDestination; Game_Temp.prototype.setDestination = function(x, y) { if ($gamePlayer._xDestination === undefined && $gamePlayer._destinationCharacter === undefined && $gamePlayer._yDestination === undefined) { oldGameTemp_setDestination.call(this, x, y); } }; Game_CharacterBase.prototype.clearDestination = function() { this._xDestination = undefined; this._yDestination = undefined; this._dDestination = undefined; this._destinationCharacter = undefined; this._followCharacter = false; }; Game_Interpreter.prototype.waitForEventMovement = function(eventId) { this._waitingForEventMovement = eventId; if (!!this._waitingForEventMovement) { this._waitMode = 'eventMovement'; } }; var oldGameInterpreter_updateWaitMode = Game_Interpreter.prototype.updateWaitMode; Game_Interpreter.prototype.updateWaitMode = function() { if (this._waitMode == 'eventMovement') { if (!!this._waitingForEventMovement) { var eventId = this._waitingForEventMovement; var event = this.character(eventId); if (event.isMoving() || event.isJumping() || event.isBalloonPlaying()) { return true; } if (event._xDestination!== undefined && event._yDestination!== undefined) { return true; } } this._waitMode = ''; } return oldGameInterpreter_updateWaitMode.apply(this, arguments); }; })(OrangeMoveCharacterTo); Imported['OrangeMoveCharacterTo'] = 1.3; ======================= File: OrangeHud/OrangeHudVariableIcon.js ======================= <filename>OrangeHud/OrangeHudVariableIcon.js /*============================================================================= * Orange - Variable Icon HUD * By HUDell - www.hudell.com * OrangeHudVariableIcon.js * Version: 1.1 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Adds a new Variable Icon to Orange Hud * @author Hudell * * @param GroupName * @desc The name of the HUD group where this line should be displayed * @default main * * @param VariableId * @desc The number of the variable that will be used to control this Icon. * @default 1 * * @param SwitchId * @desc Set this to a switch number to use it to control the visibility of this line * @default 0 * * @param X * @desc The X position of the variable line inside the HUD * @default * * @param Y * @desc The Y position of the variable line inside the HUD * @default * * @param VariableX * @desc The number of the variable that holds the X position of the Icon inside the HUD * @default 0 * * @param VariableY * @desc The number of the variable that holds the Y position of the Icon inside the HUD * @default 0 * * @help * ============================================================================ * My Blog: * ============================================================================ * http://hudell.com * */ var Imported = Imported || {}; if (Imported["OrangeHud"] === undefined) { throw new Error("Please add OrangeHud before OrangeHudVariableIcon!"); } var OrangeHudVariableIcon = OrangeHudVariableIcon || {}; if (Imported["OrangeHudVariableIcon"] === undefined) { OrangeHudVariableIcon.validateParams = function(paramsLine) { paramsLine.GroupName = paramsLine.GroupName || "main"; paramsLine.VariableId = Number(paramsLine.VariableId || 0); paramsLine.X = Number(paramsLine.X || 0); paramsLine.Y = Number(paramsLine.Y || 0); paramsLine.VariableX = Number(paramsLine.VariableX || 0); paramsLine.VariableY = Number(paramsLine.VariableY || 0); paramsLine.SwitchId = Number(paramsLine.SwitchId || 0); }; OrangeHudVariableIcon.realX = function(variableData) { var x = variableData.X; if (variableData.VariableX > 0) { x = $gameVariables.value(variableData.VariableX); } return x; }; OrangeHudVariableIcon.realY = function(variableData) { var y = variableData.Y; if (variableData.VariableY > 0) { y = $gameVariables.value(variableData.VariableY); } return y; }; OrangeHudVariableIcon.drawLine = function(hudWindow, variableData) { if (variableData.SwitchId > 0) { if (!$gameSwitches.value(variableData.SwitchId)) { return; } } var iconindex = this.getIconIndex(variableData); x = this.realX(variableData); y = this.realY(variableData); if (iconindex >= 0) { this.drawIcon(hudWindow, iconindex, x, y, variableData); } }; OrangeHudVariableIcon.drawIcon = function(hudWindow, iconindex, x, y, variableData) { hudWindow.drawIcon(iconindex, x, y); }; OrangeHudVariableIcon.getValue = function(variableData) { if (variableData.VariableId > 0) { return $gameVariables.value(variableData.VariableId); } else { return 0; } }; OrangeHudVariableIcon.getIconIndex = function(variableData) { var varValue = -1; if (variableData.VariableId > 0) { varValue = Number($gameVariables.value(variableData.VariableId)); } return varValue; }; OrangeHudVariableIcon.getKey = function(variableData) { return variableData.VariableId; }; OrangeHud.registerLineType('OrangeHudVariableIcon', OrangeHudVariableIcon); Imported["OrangeHudVariableIcon"] = 1.1; } ======================= File: OrangeHud/OrangeHudActorStatus.js ======================= <gh_stars>10-100 /*============================================================================= * Orange - Actor Status HUD * By HUDell - www.hudell.com * OrangeHudActorStatus.js * Version: 1.5.2 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Adds a new line to Orange Hud to display an actor's status * @author Hudell * * @param GroupName * @desc The name of the HUD group where this line should be displayed * @default main * * @param Pattern * @desc The pattern of the line that will be drawn. Click the help button for more info. * @default <hp> / <mhp> * * @param ActorIndex * @desc The index of the actor in the party. If the index is invalid, nothing will be shown * @default 0 * * @param SwitchId * @desc Set this to a switch number to use it to control the visibility of this line * @default 0 * * @param X * @desc The X position of the variable line inside the HUD * @default * * @param Y * @desc The Y position of the variable line inside the HUD * @default * * @param FontFace * @desc The font face to use. Leave empty to use the HUD default * @default * * @param FontSize * @desc The font size to use. Leave empty to use the HUD default * @default * * @param FontColor * @desc The font color to use. Leave empty to use the HUD default * @default * * @param FontItalic * @desc Should use italic? Leave empty to use the HUD default * @default * * @param ScriptPattern * @desc A script call to be used instead of the Pattern * @default * * @help * ============================================================================ * My Blog: * ============================================================================ * http://hudell.com * ============================================================================ * Valid variables: * ============================================================================ * <hp> * <mp> * <tp> * <mhp> * <mmp> * <atk> * <def> * <mat> * <mdf> * <agi> * <luk> * <hit> * <eva> * <cri> * <cev> * <mev> * <mrf> * <cnt> * <hrg> * <mrg> * <trg> * <tgr> * <grd> * <rec> * <pha> * <mcr> * <tcr> * <pdr> * <mdr> * <fdr> * <exr> * <level> * <maxlevel> * */ var Imported = Imported || {}; if (Imported["OrangeHud"] === undefined) { throw new Error("Please add OrangeHud before OrangeHudActorStatus!"); } var OrangeHudActorStatusLine = OrangeHudActorStatusLine || {}; if (Imported["OrangeHudActorStatus"] === undefined) { OrangeHudActorStatusLine.validateParams = function(line) { line.GroupName = line.GroupName || "main"; if (line.ScriptPattern!== undefined && line.ScriptPattern.trim() === "") { line.ScriptPattern = undefined; } if (line.Pattern === undefined) { line.Pattern = "<hp> / <mhp>"; } else if (line.Pattern.trim() === "") { line.Pattern = ""; } line.ActorIndex = Number(line.ActorIndex || 0); if (line.FontFace === undefined || line.FontFace.trim() === "") { line.FontFace = OrangeHud.Param.DefaultFontFace; } if (line.FontColor === undefined || line.FontColor.trim() === "") { line.FontColor = OrangeHud.Param.DefaultFontColor; } line.FontSize = Number(line.FontSize || OrangeHud.Param.DefaultFontSize); line.X = Number(line.X || 0); line.Y = Number(line.Y || 0); if (line.FontItalic === undefined || line.FontItalic.trim() === "") { line.FontItalic = OrangeHud.Param.DefaultFontItalic; } else { line.FontItalic = line.FontItalic == "true"; } line.SwitchId = Number(line.SwitchId || 0); }; OrangeHudActorStatusLine.drawLine = function(window, variableData) { if (variableData.SwitchId > 0) { if (!$gameSwitches.value(variableData.SwitchId)) { return; } } var line = this.getLine(variableData); window.contents.fontFace = variableData.FontFace; window.contents.fontSize = variableData.FontSize; window.contents.fontItalic = variableData.FontItalic; window.changeTextColor(variableData.FontColor); window.drawTextEx(line, variableData.X, variableData.Y); window.resetFontSettings(); }; OrangeHudActorStatusLine.getLine = function(variableData) { var pattern = variableData.Pattern; if (variableData.ScriptPattern!== undefined) { pattern = Function("return " + variableData.ScriptPattern)(); } var members = $gameParty.members(); if (members.length > variableData.ActorIndex) { var line = pattern; var actorData = members[variableData.ActorIndex]; line = line.replace(/\<hp\>/gi, actorData.hp); line = line.replace(/\<mp\>/gi, actorData.mp); line = line.replace(/\<tp\>/gi, actorData.tp); line = line.replace(/\<mhp\>/gi, actorData.mhp); line = line.replace(/\<mmp\>/gi, actorData.mmp); line = line.replace(/\<atk\>/gi, actorData.atk); line = line.replace(/\<def\>/gi, actorData.def); line = line.replace(/\<mat\>/gi, actorData.mat); line = line.replace(/\<mdf\>/gi, actorData.mdf); line = line.replace(/\<agi\>/gi, actorData.agi); line = line.replace(/\<luk\>/gi, actorData.luk); line = line.replace(/\<hit\>/gi, actorData.hit); line = line.replace(/\<eva\>/gi, actorData.eva); line = line.replace(/\<cri\>/gi, actorData.cri); line = line.replace(/\<cev\>/gi, actorData.cev); line = line.replace(/\<mev\>/gi, actorData.mev); line = line.replace(/\<mrf\>/gi, actorData.mrf); line = line.replace(/\<cnt\>/gi, actorData.cnt); line = line.replace(/\<hrg\>/gi, actorData.hrg); line = line.replace(/\<mrg\>/gi, actorData.mrg); line = line.replace(/\<trg\>/gi, actorData.trg); line = line.replace(/\<tgr\>/gi, actorData.tgr); line = line.replace(/\<grd\>/gi, actorData.grd); line = line.replace(/\<rec\>/gi, actorData.rec); line = line.replace(/\<pha\>/gi, actorData.pha); line = line.replace(/\<mcr\>/gi, actorData.mcr); line = line.replace(/\<tcr\>/gi, actorData.tcr); line = line.replace(/\<pdr\>/gi, actorData.pdr); line = line.replace(/\<mdr\>/gi, actorData.mdr); line = line.replace(/\<fdr\>/gi, actorData.fdr); line = line.replace(/\<exr\>/gi, actorData.exr); line = line.replace(/\<level\>/gi, actorData.level); line = line.replace(/\<maxlevel\>/gi, actorData.maxLevel()); line = line.replace(/\<exp\>/gi, actorData.currentExp()); return line; } else { return ''; } }; OrangeHudActorStatusLine.getValue = function(variableData) { return this.getLine(variableData); }; OrangeHudActorStatusLine.getKey = function(variableData) { return 'actor' + variableData.ActorIndex; }; OrangeHud.registerLineType('OrangeHudActorStatus', OrangeHudActorStatusLine); Imported.OrangeHudActorStatus = 1.5; } ======================= File: OrangeInstantMouseMovement.js ======================= /*============================================================================= * Orange - Instant Mouse Movement * By Hudell - www.hudell.com * OrangeInstantMouseMovement.js * Version: 1.0 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc This plugin will instantly teleport the player to the clicked position * @author Hudell * * @help * ============================================================================ * Latest Version * ============================================================================ * * Get the latest version of this script on * http://link.hudell.com/instant-mouse-movement * *=============================================================================*/ /*:pt-br * @plugindesc Este plugin vai teletransportar o jogador instantaneamente para a posição clicada * @author Hudell * * @help * ============================================================================ * Última Versão * ============================================================================ * * Baixe a última versão deste script em * http://link.hudell.com/instant-mouse-movement * *=============================================================================*/ Game_Temp.prototype.setDestination = function(x, y) { $gamePlayer.setPosition(x, y); }; var Imported = Imported || {}; // If MVCommons is imported, register the plugin with it's PluginManager. if (Imported['MVCommons']!== undefined) { PluginManager.register("OrangeInstantMouseMovement", "1.0.0", "This plugin will instantly teleport the player to the clicked position", { email: "<EMAIL>", name: "Hudell", website: "http://www.hudell.com" }, "2015-10-24"); } else { Imported["OrangeInstantMouseMovement"] = true; } ======================= File: OrangeAntiLag.js ======================= <filename>OrangeAntiLag.js /*============================================================================= * Orange - Anti Lag * By Hudell - www.hudell.com * OrangeAntiLag.js * Version: 1.0 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Improves part of RM code to reduce lag * @author Hudell */ var Imported = Imported || {}; var OrangeAntiLag = OrangeAntiLag || {}; (function($) { "use strict"; // Replaces the original refreshTileEvents to filter the _events array directly Game_Map.prototype.refreshTileEvents = function() { this.tileEvents = this._events.filter(function(event) { return!!event && event.isTile(); }); }; // Replaces the original eventsXy to filter the _events array directly Game_Map.prototype.eventsXy = function(x, y) { return this._events.filter(function(event) { return!!event && event.pos(x, y); }); }; // Replaces the original eventsXyNt to filter the _events array directly Game_Map.prototype.eventsXyNt = function(x, y) { return this._events.filter(function(event) { return!!event && event.posNt(x, y); }); }; // Make Tilemap class sort sprites only when needed Game_Temp.prototype.canSortTileMapChildren = function() { return!!this._zOrderChanged; }; Game_Temp.prototype.markZOrderChanged = function() { this._zOrderChanged = true; }; Game_Temp.prototype.clearZOrderChanged = function() { this._zOrderChanged = false; }; var oldGameTempInitialize = Game_Temp.prototype.initialize; Game_Temp.prototype.initialize = function() { oldGameTempInitialize.call(this); this._zOrderChanged = false; }; var oldTileMapSortChildren = Tilemap.prototype._sortChildren; Tilemap.prototype._sortChildren = function() { if ($gameTemp.canSortTileMapChildren()) { oldTileMapSortChildren.call(this); $gameTemp.clearZOrderChanged(); } }; var oldSpriteCharacterUpdatePosition = Sprite_Character.prototype.updatePosition; Sprite_Character.prototype.updatePosition = function() { if (this.z!== this._character.screenZ() || this.y!== this._character.screenY()) { $gameTemp.markZOrderChanged(); } oldSpriteCharacterUpdatePosition.call(this); }; Window.prototype._refreshBack = function() { var m = this._margin; var w = this._width - m * 2; var h = this._height - m * 2; var bitmap = this._windowBackSprite.bitmap; if (!bitmap) { bitmap = new Bitmap(w, h); } else if (bitmap.width!== w || bitmap.height!== h) { bitmap.resize(w, h); } this._windowBackSprite.bitmap = bitmap; this._windowBackSprite.setFrame(0, 0, w, h); this._windowBackSprite.move(m, m); if (w > 0 && h > 0 && this._windowskin) { var p = 96; bitmap.bltImage(this._windowskin, 0, 0, p, p, 0, 0, w, h); for (var y = 0; y < h; y += p) { for (var x = 0; x < w; x += p) { bitmap.bltImage(this._windowskin, 0, p, p, p, x, y, p, p); } } var tone = this._colorTone; bitmap.adjustTone(tone[0], tone[1], tone[2]); } }; Window.prototype._refreshFrame = function() { var w = this._width; var h = this._height; var m = 24; var bitmap = this._windowFrameSprite.bitmap; if (!bitmap) { bitmap = new Bitmap(w, h); } else if (bitmap.width!= w || bitmap.height!= h) { bitmap.resize(w, h); } this._windowFrameSprite.bitmap = bitmap; this._windowFrameSprite.setFrame(0, 0, w, h); if (w > 0 && h > 0 && this._windowskin) { var skin = this._windowskin; var p = 96; var q = 96; bitmap.bltImage(skin, p+m, 0+0, p-m*2, m, m, 0, w-m*2, m); bitmap.bltImage(skin, p+m, 0+q-m, p-m*2, m, m, h-m, w-m*2, m); bitmap.bltImage(skin, p+0, 0+m, m, p-m*2, 0, m, m, h-m*2); bitmap.bltImage(skin, p+q-m, 0+m, m, p-m*2, w-m, m, m, h-m*2); bitmap.bltImage(skin, p+0, 0+0, m, m, 0, 0, m, m); bitmap.bltImage(skin, p+q-m, 0+0, m, m, w-m, 0, m, m); bitmap.bltImage(skin, p+0, 0+q-m, m, m, 0, h-m, m, m); bitmap.bltImage(skin, p+q-m, 0+q-m, m, m, w-m, h-m, m, m); } }; Window.prototype._refreshCursor = function() { var pad = this._padding; var x = this._cursorRect.x + pad - this.origin.x; var y = this._cursorRect.y + pad - this.origin.y; var w = this._cursorRect.width; var h = this._cursorRect.height; var m = 4; var x2 = Math.max(x, pad); var y2 = Math.max(y, pad); var ox = x - x2; var oy = y - y2; var w2 = Math.min(w, this._width - pad - x2); var h2 = Math.min(h, this._height - pad - y2); var bitmap = this._windowCursorSprite.bitmap; if (!bitmap) { bitmap = new Bitmap(w2, h2); } else if (bitmap.width!== w2 || bitmap.height!== h2) { bitmap.resize(w2, h2); } this._windowCursorSprite.bitmap = bitmap; this._windowCursorSprite.setFrame(0, 0, w2, h2); this._windowCursorSprite.move(x2, y2); if (w > 0 && h > 0 && this._windowskin) { var skin = this._windowskin; var p = 96; var q = 48; bitmap.bltImage(skin, p+m, p+m, q-m*2, q-m*2, ox+m, oy+m, w-m*2, h-m*2); bitmap.bltImage(skin, p+m, p+0, q-m*2, m, ox+m, oy+0, w-m*2, m); bitmap.bltImage(skin, p+m, p+q-m, q-m*2, m, ox+m, oy+h-m, w-m*2, m); bitmap.bltImage(skin, p+0, p+m, m, q-m*2, ox+0, oy+m, m, h-m*2); bitmap.bltImage(skin, p+q-m, p+m, m, q-m*2, ox+w-m, oy+m, m, h-m*2); bitmap.bltImage(skin, p+0, p+0, m, m, ox+0, oy+0, m, m); bitmap.bltImage(skin, p+q-m, p+0, m, m, ox+w-m, oy+0, m, m); bitmap.bltImage(skin, p+0, p+q-m, m, m, ox+0, oy+h-m, m, m); bitmap.bltImage(skin, p+q-m, p+q-m, m, m, ox+w-m, oy+h-m, m, m); } }; Window_Base.prototype.createContents = function() { var w = this.contentsWidth(); var h = this.contentsHeight(); if (!this.contents) { this.contents = new Bitmap(w, h); } else if (this.contents.width!= w || this.contents.height!= h) { this.contents.resize(w, h); this.contents.clear(); } else { this.contents.clear(); } this.resetFontSettings(); }; var uniqueMessageWindow = false; Scene_Map.prototype.createMessageWindow = function() { if (uniqueMessageWindow) { this._messageWindow = uniqueMessageWindow; this._messageWindow.openness = 0; this._messageWindow.initMembers(); // this._messageWindow.updatePlacement(); } else { this._messageWindow = new Window_Message(); uniqueMessageWindow = this._messageWindow; } this.addWindow(this._messageWindow); this._messageWindow.subWindows().forEach(function(window) { this.addWindow(window); }, this); }; var uniqueScrollTextWindow = false; Scene_Map.prototype.createScrollTextWindow = function() { if (uniqueScrollTextWindow) { this._scrollTextWindow = uniqueScrollTextWindow; this._scrollTextWindow.opacity = 0; this._scrollTextWindow.hide(); this._scrollTextWindow._text = ''; this._scrollTextWindow._allTextHeight = 0; } else { this._scrollTextWindow = new Window_ScrollText(); uniqueScrollTextWindow = this._scrollTextWindow; } this.addWindow(this._scrollTextWindow); }; var uniqueMapNameWindow = false; Scene_Map.prototype.createMapNameWindow = function() { if (uniqueMapNameWindow) { this._mapNameWindow = uniqueMapNameWindow; this._mapNameWindow.opacity = 0; this._mapNameWindow.contentsOpacity = 0; this._mapNameWindow._showCount = 0; this._mapNameWindow.refresh(); } else { this._mapNameWindow = new Window_MapName(); uniqueMapNameWindow = this._mapNameWindow; } this.addChild(this._mapNameWindow); }; var uniqueDestinationSprite = false; Spriteset_Map.prototype.createDestination = function() { if (uniqueDestinationSprite) { this._destinationSprite = uniqueDestinationSprite; this._destinationSprite._frameCount = 0; } else { this._destinationSprite = new Sprite_Destination(); uniqueDestinationSprite = this._destinationSprite; } this._destinationSprite.z = 9; this._tilemap.addChild(this._destinationSprite); }; var uniqueTimerSprite = false; Spriteset_Base.prototype.createTimer = function() { if (uniqueTimerSprite) { this._timerSprite = uniqueTimerSprite; this._timerSprite._seconds = 0; this._timerSprite.update(); } else { this._timerSprite = new Sprite_Timer(); uniqueTimerSprite = this._timerSprite; } this.addChild(this._timerSprite); }; var uniqueWeather = false; Spriteset_Map.prototype.createWeather = function() { if (uniqueWeather) { this._weather = uniqueWeather; this._weather.power = 0; this._weather.type = 'none'; this._weather.origin = new Point(); } else { this._weather = new Weather(); uniqueWeather = this._weather; } this.addChild(this._weather); }; })(OrangeAntiLag); Imported.OrangeAntiLag = true; ======================= File: OrangeTimeSystem/OrangeWeather.js ======================= <filename>OrangeTimeSystem/OrangeWeather.js /*============================================================================= * Orange - Weather * By Hudell - www.hudell.com * OrangeWeather.js * Version: 1.0.1 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Adds weather effects to your game * * @author Hudell *============================================================================= * * @param weatherSpeed * @desc How many frames does it take for the weather effect to change completely * @default 60 * * @param changeWeatherStrengthAlongTheDay * @desc If true, the weather effect strength may change during the day * @default true * * @param rainChance * @desc A number between 0 and 100 identifying the chances of raining * @default 0 * * @param rainChanceByMonth * @desc You can set a different rain chance for each month, in the format <monthNumber: chance>. Example: <1: 20> <12:15> * @default * * @param maxRainStrength * @desc A number between 1 and 9 identifying the max strength of rain. * @default 9 * * @param minRainStrength * @desc A number between 1 and 9 identifying the min strength of rain. * @default 1 * * @param rainStrengthByMonth * @desc You can set a different strength range for each month, in the format <monthNumber: minStrength,maxStrength>. Example: <1: 1,5> <12: 3,9> * @default * * @param snowChance * @desc A number between 0 and 100 identifying the chances of snowing * @default 0 * * @param snowChanceByMonth * @desc You can set a different snow chance for each month, in the format <monthNumber: chance>. Example: <1: 20> <12:15> * @default * * @param maxSnowStrength * @desc A number between 1 and 9 identifying the max strength of snow. * @default 9 * * @param minSnowStrength * @desc A number between 1 and 9 identifying the min strength of snow. * @default 1 * * @param snowStrengthByMonth * @desc You can set a different strength range for each month, in the format <monthNumber: minStrength,maxStrength>. Example: <1: 1,5> <12: 3,9> * @default * * @param stormChance * @desc A number between 0 and 100 identifying the chances of storming * @default 0 * * @param stormChanceByMonth * @desc You can set a different storm chance for each month, in the format <monthNumber: chance>. Example: <1: 20> <12:15> * @default * * @param maxStormStrength * @desc A number between 1 and 9 identifying the max strength of storm. * @default 9 * * @param minStormStrength * @desc A number between 1 and 9 identifying the min strength of storm. * @default 1 * * @param stormStrengthByMonth * @desc You can set a different strength range for each month, in the format <monthNumber: minStrength,maxStrength>. Example: <1: 1,5> <12: 3,9> * @default * * @param playDefaultWeatherEffects * @desc set this to false if you want to use your own weather effects through common events * @default true * * @param rainCommonEvent * @desc the common event to run when it starts raining * @default 0 * * @param snowCommonEvent * @desc the common event to run when it starts snowing * @default 0 * * @param stormCommonEvent * @desc the common event to run when a storm starts * @default 0 * * @param normalWeatherCommonEvent * @desc the common event to run when the weather goes back to sunny * @default 0 * */ var Imported = Imported || {}; if (Imported["OrangeTimeSystem"] === undefined) { console.log('Download OrangeTimeSystem: http://link.hudell.com/time-system'); throw new Error("This library requires the OrangeTimeSystem!"); } var OrangeWeather = OrangeWeather || MVC.shallowClone(OrangeEventManager); (function($) { "use strict"; $.WeatherTypes = { NORMAL : 0, RAIN : 1, SNOW : 2, STORM : 3 }; $.Parameters = PluginManager.parameters('OrangeWeather'); $.Param = $.Param || {}; $.Param.weatherSpeed = Number($.Parameters.weatherSpeed || 60); $.Param.changeWeatherStrengthAlongTheDay = $.Parameters.changeWeatherStrengthAlongTheDay!= "false"; $.Param.normalWeatherCommonEvent = Number($.Parameters.normalWeatherCommonEvent || 0); $.Param.playDefaultWeatherEffects = $.Parameters.playDefaultWeatherEffects!= "false"; $.Param.rainChance = Number($.Parameters.rainChance || 0); $.Param.maxRainStrength = Number($.Parameters.maxRainStrength || 0); $.Param.minRainStrength = Number($.Parameters.minRainStrength || 0); $.Param.rainCommonEvent = Number($.Parameters.rainCommonEvent || 0); $.Param.snowChance = Number($.Parameters.snowChance || 0); $.Param.maxSnowStrength = Number($.Parameters.maxSnowStrength || 0); $.Param.minSnowStrength = Number($.Parameters.minSnowStrength || 0); $.Param.snowCommonEvent = Number($.Parameters.snowCommonEvent || 0); $.Param.stormChance = Number($.Parameters.stormChance || 0); $.Param.maxStormStrength = Number($.Parameters.maxStormStrength || 0); $.Param.minStormStrength = Number($.Parameters.minStormStrength || 0); $.Param.stormCommonEvent = Number($.Parameters.stormCommonEvent || 0); var rainChanceByMonth = ($.Parameters.rainChanceByMonth || "").trim(); var rainChanceByMonthObj = { note : rainChanceByMonth, meta : {}}; DataManager.extractMetadata(rainChanceByMonthObj); var rainStrengthByMonth = ($.Parameters.rainStrengthByMonth || "").trim(); var rainStrengthByMonthObj = { note : rainStrengthByMonth, meta : {} }; DataManager.extractMetadata(rainStrengthByMonthObj); var snowChanceByMonth = ($.Parameters.snowChanceByMonth || "").trim(); var snowChanceByMonthObj = { note : snowChanceByMonth, meta : {}}; DataManager.extractMetadata(snowChanceByMonthObj); var snowStrengthByMonth = ($.Parameters.snowStrengthByMonth || "").trim(); var snowStrengthByMonthObj = { note : snowStrengthByMonth, meta : {} }; DataManager.extractMetadata(snowStrengthByMonthObj); var stormChanceByMonth = ($.Parameters.stormChanceByMonth || "").trim(); var stormChanceByMonthObj = { note : stormChanceByMonth, meta : {}}; DataManager.extractMetadata(stormChanceByMonthObj); var stormStrengthByMonth = ($.Parameters.stormStrengthByMonth || "").trim(); var stormStrengthByMonthObj = { note : stormStrengthByMonth, meta : {} }; DataManager.extractMetadata(stormStrengthByMonthObj); var i; var monthIndex; $.Param.rainChanceByMonth = [undefined]; $.Param.rainStrengthByMonth = [undefined]; $.Param.snowChanceByMonth = [undefined]; $.Param.snowStrengthByMonth = [undefined]; $.Param.stormChanceByMonth = [undefined]; $.Param.stormStrengthByMonth = [undefined]; for (i=0; i < OrangeTimeSystem.Param.yearLength; i++) { $.Param.rainChanceByMonth.push($.Param.rainChance); $.Param.snowChanceByMonth.push($.Param.snowChance); $.Param.stormChanceByMonth.push($.Param.stormChance); $.Param.rainStrengthByMonth.push({ max :$.Param.maxRainStrength, min :$.Param.minRainStrength }); $.Param.snowStrengthByMonth.push({ max :$.Param.maxSnowStrength, min :$.Param.minSnowStrength }); $.Param.stormStrengthByMonth.push({ max :$.Param.maxStormStrength, min :$.Param.minStormStrength }); } for (monthIndex in rainChanceByMonthObj.meta) { $.Param.rainChanceByMonth[monthIndex] = parseInt(rainChanceByMonthObj.meta[monthIndex], 10); } for (monthIndex in snowChanceByMonthObj.meta) { $.Param.snowChanceByMonth[monthIndex] = parseInt(snowChanceByMonthObj.meta[monthIndex], 10); } for (monthIndex in stormChanceByMonthObj.meta) { $.Param.stormChanceByMonth[monthIndex] = parseInt(stormChanceByMonthObj.meta[monthIndex], 10); } var str, data, min, max; for (monthIndex in rainStrengthByMonthObj.meta) { str = rainStrengthByMonthObj.meta[monthIndex]; data = str.split(','); min = $.Param.minRainStrength; max = $.Param.maxRainStrength; if (data.length > 1) { min = parseInt(data[0], 10); max = parseInt(data[1], 10); } else if (data.length > 0) { max = parseInt(data[0], 10); } $.Param.rainStrengthByMonth[monthIndex] = { min : min, max : max }; } for (monthIndex in snowStrengthByMonthObj.meta) { str = snowStrengthByMonthObj.meta[monthIndex]; data = str.split(','); min = $.Param.minSnowStrength; max = $.Param.maxSnowStrength; if (data.length > 1) { min = parseInt(data[0], 10); max = parseInt(data[1], 10); } else if (data.length > 0) { max = parseInt(data[0], 10); } $.Param.snowStrengthByMonth[monthIndex] = { min : min, max : max }; } for (monthIndex in stormStrengthByMonthObj.meta) { str = stormStrengthByMonthObj.meta[monthIndex]; data = str.split(','); min = $.Param.minStormStrength; max = $.Param.maxStormStrength; if (data.length > 1) { min = parseInt(data[0], 10); max = parseInt(data[1], 10); } else if (data.length > 0) { max = parseInt(data[0], 10); } $.Param.stormStrengthByMonth[monthIndex] = { min : min, max : max }; } MVC.accessor($, 'weather'); MVC.accessor($, 'weatherPower'); MVC.accessor($, 'nextDayWeather'); MVC.reader($, 'rainChance', function(){ return $.Param.rainChanceByMonth[OrangeTimeSystem.month]; }); MVC.reader($,'maxRainStrength', function(){ return $.Param.rainStrengthByMonth[OrangeTimeSystem.month].max; }); MVC.reader($,'minRainStrength', function(){ return $.Param.rainStrengthByMonth[OrangeTimeSystem.month].min; }); MVC.reader($,'snowChance', function(){ return $.Param.snowChanceByMonth[OrangeTimeSystem.month]; }); MVC.reader($,'maxSnowStrength', function(){ return $.Param.snowStrengthByMonth[OrangeTimeSystem.month].max; }); MVC.reader($,'minSnowStrength', function(){ return $.Param.snowStrengthByMonth[OrangeTimeSystem.month].min; }); MVC.reader($,'stormChance', function(){ return $.Param.stormChanceByMonth[OrangeTimeSystem.month]; }); MVC.reader($,'maxStormStrength', function(){ return $.Param.stormStrengthByMonth[OrangeTimeSystem.month].max; }); MVC.reader($,'minStormStrength', function(){ return $.Param.stormStrengthByMonth[OrangeTimeSystem.month].min; }); MVC.reader($,'maxWeatherStrength', function(){ switch (this.weather) { case $.WeatherTypes.RAIN : return $.Param.rainStrengthByMonth[OrangeTimeSystem.month].max; case $.WeatherTypes.SNOW : return $.Param.snowStrengthByMonth[OrangeTimeSystem.month].max; case $.WeatherTypes.STORM : return $.Param.stormStrengthByMonth[OrangeTimeSystem.month].max; default : return 0; } }); MVC.reader($,'minWeatherStrength', function(){ switch (this.weather) { case $.WeatherTypes.RAIN : return $.Param.rainStrengthByMonth[OrangeTimeSystem.month].min; case $.WeatherTypes.SNOW : return $.Param.snowStrengthByMonth[OrangeTimeSystem.month].min; case $.WeatherTypes.STORM : return $.Param.stormStrengthByMonth[OrangeTimeSystem.month].min; default : return 0; } }); MVC.reader($, 'tomorrowRainChance', function(){ var dateObj = OrangeTimeSystem.getTomorrow(); return $.Param.rainChanceByMonth[dateObj.month]; }); MVC.reader($, 'tomorrowSnowChance', function(){ var dateObj = OrangeTimeSystem.getTomorrow(); return $.Param.snowChanceByMonth[dateObj.month]; }); MVC.reader($, 'tomorrowStormChance', function(){ var dateObj = OrangeTimeSystem.getTomorrow(); return $.Param.stormChanceByMonth[dateObj.month]; }); $.weather = 0; $.weatherPower = 0; $.nextDayWeather = 0; $.canUpdateWeather = function() { return!OrangeTimeSystem.inside; }; $.onMinuteChange = function(){ // Randomly change the strength of the weather effect about once an hour if (Math.random() * 100 < Math.ceil(100 / OrangeTimeSystem.Param.hourLength)) { this.randomizePower(); } }; $.pickNextDayWeather = function(){ var rainChance = this.tomorrowRainChance; if (Math.random() * 100 < rainChance) { this.nextDayWeather = this.WeatherTypes.RAIN; return; } var snowChance = this.tomorrowSnowChance; if (Math.random() * 100 < snowChance) { this.nextDayWeather = this.WeatherTypes.SNOW; return; } var stormChance = this.tomorrowStormChance; if (Math.random() * 100 < stormChance) { this.nextDayWeather = this.WeatherTypes.STORM; return; } this.nextDayWeather = this.WeatherTypes.NORMAL; }; $.onDayChange = function(){ this.weather = this.nextDayWeather; this.pickNextDayWeather(); this.updateWeather($.Param.weatherSpeed); }; $.randomizePower = function(){ var maxWeatherStrength = this.maxWeatherStrength; var minWeatherStrength = this.minWeatherStrength; var diff = maxWeatherStrength - minWeatherStrength + 1; var strength = Math.floor(Math.random() * diff) + minWeatherStrength; this.weatherPower = strength; }; $.startRaining = function(strength, speed) { if ($gameScreen === undefined || $gameScreen === null) return; $.runEvent('startRaining'); if ($.Param.rainCommonEvent > 0) { $gameTemp.reserveCommonEvent($.Param.rainCommonEvent); } if ($.Param.playDefaultWeatherEffects) { $gameScreen.changeWeather('rain', strength, speed); } }; $.startSnowing = function(strength, speed) { if ($gameScreen === undefined || $gameScreen === null) return; $.runEvent('startSnowing'); if ($.Param.snowCommonEvent > 0) { $gameTemp.reserveCommonEvent($.Param.snowCommonEvent); } if ($.Param.playDefaultWeatherEffects) { $gameScreen.changeWeather('snow', strength, speed); } }; $.startStorm = function(strength, speed) { if ($gameScreen === undefined || $gameScreen === null) return; $.runEvent('startStorm'); if ($.Param.stormCommonEvent > 0) { $gameTemp.reserveCommonEvent($.Param.stormCommonEvent); } if ($.Param.playDefaultWeatherEffects) { $gameScreen.changeWeather('storm', strength, speed); } }; $.resetWeather = function(speed) { if ($gameScreen === undefined || $gameScreen === null) return; $.runEvent('normalWeather'); if ($.Param.normalWeatherCommonEvent > 0) { $gameTemp.reserveCommonEvent($.Param.normalWeatherCommonEvent); } if ($.Param.playDefaultWeatherEffects) { $gameScreen.changeWeather('none', 0, speed); } }; $.updateWeather = function(speed) { var type = 0; if (this.canUpdateWeather()) { type = this.weather; if (type > 0 && this.weatherPower === 0) { this.randomizePower(); } } switch(type) { case this.WeatherTypes.RAIN : this.startRaining(this.weatherPower, speed); break; case this.WeatherTypes.SNOW : this.startSnowing(this.weatherPower, speed); break; case this.WeatherTypes.STORM : this.startStorm(this.weatherPower, speed); break; default : this.resetWeather(speed); this.weatherPower = 0; break; } }; if ($.Param.changeWeatherStrengthAlongTheDay) { OrangeTimeSystem.on('changeMinute', function(){ $.onMinuteChange.call($); }); } OrangeTimeSystem.on('changeDay', function(){ $.onDayChange.call($); }); var oldGamePlayer_performTransfer = Game_Player.prototype.performTransfer; Game_Player.prototype.performTransfer = function() { oldGamePlayer_performTransfer.call(this); $.updateWeather(1); }; })(OrangeWeather); Imported["OrangeWeather"] = 1; ======================= File: OrangeRegionNames.js ======================= <gh_stars>10-100 /*============================================================================= * Orange - RegionNames * By Hudell - www.hudell.com * OrangeRegionNames.js * Version: 1.0 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Displays the name of the region the player is currently walking on <OrangeRegionNames> * @author Hudell * * @param 1 * @desc The name of the region 1 * @default * * @param 2 * @desc The name of the region 2 * @default * * @param 3 * @desc The name of the region 3 * @default * * @param 4 * @desc The name of the region 4 * @default * * @param 5 * @desc The name of the region 5 * @default * * @param 6 * @desc The name of the region 6 * @default * * @param 7 * @desc The name of the region 7 * @default * * @param 8 * @desc The name of the region 8 * @default * * @param 9 * @desc The name of the region 9 * @default * * @param 10 * @desc The name of the region 10 * @default * * @param 11 * @desc The name of the region 11 * @default * * @param 12 * @desc The name of the region 12 * @default * * @param 13 * @desc The name of the region 13 * @default * * @param 14 * @desc The name of the region 14 * @default * * @param 15 * @desc The name of the region 15 * @default * * @param 16 * @desc The name of the region 16 * @default * * @param 17 * @desc The name of the region 17 * @default * * @param 18 * @desc The name of the region 18 * @default * * @param 19 * @desc The name of the region 19 * @default * * @param 20 * @desc The name of the region 20 * @default * * @param 21 * @desc The name of the region 21 * @default * * @param 22 * @desc The name of the region 22 * @default * * @param 23 * @desc The name of the region 23 * @default * * @param 24 * @desc The name of the region 24 * @default * * @param 25 * @desc The name of the region 25 * @default * * @param 26 * @desc The name of the region 26 * @default * * @param 27 * @desc The name of the region 27 * @default * * @param 28 * @desc The name of the region 28 * @default * * @param 29 * @desc The name of the region 29 * @default * * @param 30 * @desc The name of the region 30 * @default * * @param 31 * @desc The name of the region 31 * @default * * @param 32 * @desc The name of the region 32 * @default * * @param 33 * @desc The name of the region 33 * @default * * @param 34 * @desc The name of the region 34 * @default * * @param 35 * @desc The name of the region 35 * @default * * @param 36 * @desc The name of the region 36 * @default * * @param 37 * @desc The name of the region 37 * @default * * @param 38 * @desc The name of the region 38 * @default * * @param 39 * @desc The name of the region 39 * @default * * @param 40 * @desc The name of the region 40 * @default * * @param 41 * @desc The name of the region 41 * @default * * @param 42 * @desc The name of the region 42 * @default * * @param 43 * @desc The name of the region 43 * @default * * @param 44 * @desc The name of the region 44 * @default * * @param 45 * @desc The name of the region 45 * @default * * @param 46 * @desc The name of the region 46 * @default * * @param 47 * @desc The name of the region 47 * @default * * @param 48 * @desc The name of the region 48 * @default * * @param 49 * @desc The name of the region 49 * @default * * @param 50 * @desc The name of the region 50 * @default * * @param 51 * @desc The name of the region 51 * @default * * @param 52 * @desc The name of the region 52 * @default * * @param 53 * @desc The name of the region 53 * @default * * @param 54 * @desc The name of the region 54 * @default * * @param 55 * @desc The name of the region 55 * @default * * @param 56 * @desc The name of the region 56 * @default * * @param 57 * @desc The name of the region 57 * @default * * @param 58 * @desc The name of the region 58 * @default * * @param 59 * @desc The name of the region 59 * @default * * @param 60 * @desc The name of the region 60 * @default * * @param 61 * @desc The name of the region 61 * @default * * @param 62 * @desc The name of the region 62 * @default * * @param 63 * @desc The name of the region 63 * @default * * @param 64 * @desc The name of the region 64 * @default * * @param 65 * @desc The name of the region 65 * @default * * @param 66 * @desc The name of the region 66 * @default * * @param 67 * @desc The name of the region 67 * @default * * @param 68 * @desc The name of the region 68 * @default * * @param 69 * @desc The name of the region 69 * @default * * @param 70 * @desc The name of the region 70 * @default * * @param 71 * @desc The name of the region 71 * @default * * @param 72 * @desc The name of the region 72 * @default * * @param 73 * @desc The name of the region 73 * @default * * @param 74 * @desc The name of the region 74 * @default * * @param 75 * @desc The name of the region 75 * @default * * @param 76 * @desc The name of the region 76 * @default * * @param 77 * @desc The name of the region 77 * @default * * @param 78 * @desc The name of the region 78 * @default * * @param 79 * @desc The name of the region 79 * @default * * @param 80 * @desc The name of the region 80 * @default * * @param 81 * @desc The name of the region 81 * @default * * @param 82 * @desc The name of the region 82 * @default * * @param 83 * @desc The name of the region 83 * @default * * @param 84 * @desc The name of the region 84 * @default * * @param 85 * @desc The name of the region 85 * @default * * @param 86 * @desc The name of the region 86 * @default * * @param 87 * @desc The name of the region 87 * @default * * @param 88 * @desc The name of the region 88 * @default * * @param 89 * @desc The name of the region 89 * @default * * @param 90 * @desc The name of the region 90 * @default * * @param 91 * @desc The name of the region 91 * @default * * @param 92 * @desc The name of the region 92 * @default * * @param 93 * @desc The name of the region 93 * @default * * @param 94 * @desc The name of the region 94 * @default * * @param 95 * @desc The name of the region 95 * @default * * @param 96 * @desc The name of the region 96 * @default * * @param 97 * @desc The name of the region 97 * @default * * @param 98 * @desc The name of the region 98 * @default * * @param 99 * @desc The name of the region 99 * @default * * @param 00 * @desc The name of the region 00 * @default * * @param 101 * @desc The name of the region 101 * @default * * @param 102 * @desc The name of the region 102 * @default * * @param 103 * @desc The name of the region 103 * @default * * @param 104 * @desc The name of the region 104 * @default * * @param 105 * @desc The name of the region 105 * @default * * @param 106 * @desc The name of the region 106 * @default * * @param 107 * @desc The name of the region 107 * @default * * @param 108 * @desc The name of the region 108 * @default * * @param 109 * @desc The name of the region 109 * @default * * @param 110 * @desc The name of the region 110 * @default * * @param 111 * @desc The name of the region 111 * @default * * @param 112 * @desc The name of the region 112 * @default * * @param 113 * @desc The name of the region 113 * @default * * @param 114 * @desc The name of the region 114 * @default * * @param 115 * @desc The name of the region 115 * @default * * @param 116 * @desc The name of the region 116 * @default * * @param 117 * @desc The name of the region 117 * @default * * @param 118 * @desc The name of the region 118 * @default * * @param 119 * @desc The name of the region 119 * @default * * @param 120 * @desc The name of the region 120 * @default * * @param 121 * @desc The name of the region 121 * @default * * @param 122 * @desc The name of the region 122 * @default * * @param 123 * @desc The name of the region 123 * @default * * @param 124 * @desc The name of the region 124 * @default * * @param 125 * @desc The name of the region 125 * @default * * @param 126 * @desc The name of the region 126 * @default * * @param 127 * @desc The name of the region 127 * @default * * @param 128 * @desc The name of the region 128 * @default * * @param 129 * @desc The name of the region 129 * @default * * @param 130 * @desc The name of the region 130 * @default * * @param 131 * @desc The name of the region 131 * @default * * @param 132 * @desc The name of the region 132 * @default * * @param 133 * @desc The name of the region 133 * @default * * @param 134 * @desc The name of the region 134 * @default * * @param 135 * @desc The name of the region 135 * @default * * @param 136 * @desc The name of the region 136 * @default * * @param 137 * @desc The name of the region 137 * @default * * @param 138 * @desc The name of the region 138 * @default * * @param 139 * @desc The name of the region 139 * @default * * @param 140 * @desc The name of the region 140 * @default * * @param 141 * @desc The name of the region 141 * @default * * @param 142 * @desc The name of the region 142 * @default * * @param 143 * @desc The name of the region 143 * @default * * @param 144 * @desc The name of the region 144 * @default * * @param 145 * @desc The name of the region 145 * @default * * @param 146 * @desc The name of the region 146 * @default * * @param 147 * @desc The name of the region 147 * @default * * @param 148 * @desc The name of the region 148 * @default * * @param 149 * @desc The name of the region 149 * @default * * @param 150 * @desc The name of the region 150 * @default * * @param 151 * @desc The name of the region 151 * @default * * @param 152 * @desc The name of the region 152 * @default * * @param 153 * @desc The name of the region 153 * @default * * @param 154 * @desc The name of the region 154 * @default * * @param 155 * @desc The name of the region 155 * @default * * @param 156 * @desc The name of the region 156 * @default * * @param 157 * @desc The name of the region 157 * @default * * @param 158 * @desc The name of the region 158 * @default * * @param 159 * @desc The name of the region 159 * @default * * @param 160 * @desc The name of the region 160 * @default * * @param 161 * @desc The name of the region 161 * @default * * @param 162 * @desc The name of the region 162 * @default * * @param 163 * @desc The name of the region 163 * @default * * @param 164 * @desc The name of the region 164 * @default * * @param 165 * @desc The name of the region 165 * @default * * @param 166 * @desc The name of the region 166 * @default * * @param 167 * @desc The name of the region 167 * @default * * @param 168 * @desc The name of the region 168 * @default * * @param 169 * @desc The name of the region 169 * @default * * @param 170 * @desc The name of the region 170 * @default * * @param 171 * @desc The name of the region 171 * @default * * @param 172 * @desc The name of the region 172 * @default * * @param 173 * @desc The name of the region 173 * @default * * @param 174 * @desc The name of the region 174 * @default * * @param 175 * @desc The name of the region 175 * @default * * @param 176 * @desc The name of the region 176 * @default * * @param 177 * @desc The name of the region 177 * @default * * @param 178 * @desc The name of the region 178 * @default * * @param 179 * @desc The name of the region 179 * @default * * @param 180 * @desc The name of the region 180 * @default * * @param 181 * @desc The name of the region 181 * @default * * @param 182 * @desc The name of the region 182 * @default * * @param 183 * @desc The name of the region 183 * @default * * @param 184 * @desc The name of the region 184 * @default * * @param 185 * @desc The name of the region 185 * @default * * @param 186 * @desc The name of the region 186 * @default * * @param 187 * @desc The name of the region 187 * @default * * @param 188 * @desc The name of the region 188 * @default * * @param 189 * @desc The name of the region 189 * @default * * @param 190 * @desc The name of the region 190 * @default * * @param 191 * @desc The name of the region 191 * @default * * @param 192 * @desc The name of the region 192 * @default * * @param 193 * @desc The name of the region 193 * @default * * @param 194 * @desc The name of the region 194 * @default * * @param 195 * @desc The name of the region 195 * @default * * @param 196 * @desc The name of the region 196 * @default * * @param 197 * @desc The name of the region 197 * @default * * @param 198 * @desc The name of the region 198 * @default * * @param 199 * @desc The name of the region 199 * @default * * @param 200 * @desc The name of the region 200 * @default * * @param 201 * @desc The name of the region 201 * @default * * @param 202 * @desc The name of the region 202 * @default * * @param 203 * @desc The name of the region 203 * @default * * @param 204 * @desc The name of the region 204 * @default * * @param 205 * @desc The name of the region 205 * @default * * @param 206 * @desc The name of the region 206 * @default * * @param 207 * @desc The name of the region 207 * @default * * @param 208 * @desc The name of the region 208 * @default * * @param 209 * @desc The name of the region 209 * @default * * @param 210 * @desc The name of the region 210 * @default * * @param 211 * @desc The name of the region 211 * @default * * @param 212 * @desc The name of the region 212 * @default * * @param 213 * @desc The name of the region 213 * @default * * @param 214 * @desc The name of the region 214 * @default * * @param 215 * @desc The name of the region 215 * @default * * @param 216 * @desc The name of the region 216 * @default * * @param 217 * @desc The name of the region 217 * @default * * @param 218 * @desc The name of the region 218 * @default * * @param 219 * @desc The name of the region 219 * @default * * @param 220 * @desc The name of the region 220 * @default * * @param 221 * @desc The name of the region 221 * @default * * @param 222 * @desc The name of the region 222 * @default * * @param 223 * @desc The name of the region 223 * @default * * @param 224 * @desc The name of the region 224 * @default * * @param 225 * @desc The name of the region 225 * @default * * @param 226 * @desc The name of the region 226 * @default * * @param 227 * @desc The name of the region 227 * @default * * @param 228 * @desc The name of the region 228 * @default * * @param 229 * @desc The name of the region 229 * @default * * @param 230 * @desc The name of the region 230 * @default * * @param 231 * @desc The name of the region 231 * @default * * @param 232 * @desc The name of the region 232 * @default * * @param 233 * @desc The name of the region 233 * @default * * @param 234 * @desc The name of the region 234 * @default * * @param 235 * @desc The name of the region 235 * @default * * @param 236 * @desc The name of the region 236 * @default * * @param 237 * @desc The name of the region 237 * @default * * @param 238 * @desc The name of the region 238 * @default * * @param 239 * @desc The name of the region 239 * @default * * @param 240 * @desc The name of the region 240 * @default * * @param 241 * @desc The name of the region 241 * @default * * @param 242 * @desc The name of the region 242 * @default * * @param 243 * @desc The name of the region 243 * @default * * @param 244 * @desc The name of the region 244 * @default * * @param 245 * @desc The name of the region 245 * @default * * @param 246 * @desc The name of the region 246 * @default * * @param 247 * @desc The name of the region 247 * @default * * @param 248 * @desc The name of the region 248 * @default * * @param 249 * @desc The name of the region 249 * @default * * @param 250 * @desc The name of the region 250 * @default * * @param 251 * @desc The name of the region 251 * @default * * @param 252 * @desc The name of the region 252 * @default * * @param 253 * @desc The name of the region 253 * @default * * @param 254 * @desc The name of the region 254 * @default * * @param 255 * @desc The name of the region 255 * @default * * @help * ============================================================================ * Hudell's Plugins * ============================================================================ * * Check out my website: * http://hudell.com * *=============================================================================*/ var Imported = Imported || {}; var Hudell = Hudell || {}; Hudell.OrangeRegionNames = Hudell.OrangeRegionNames || {}; function Window_RegionName() { this.initialize.apply(this, arguments); } Window_RegionName.prototype = Object.create(Window_MapName.prototype); Window_RegionName.prototype.constructor = Window_RegionName; (function($) { "use strict"; var parameters = $plugins.filter(function(plugin) { return plugin.description.contains('<OrangeRegionNames>'); }); if (parameters.length === 0) { throw new Error("Couldn't find Hudell's OrangeRegionNames parameters."); } $.Parameters = parameters[0].parameters; $.RegionNames = {}; for (var i = 1; i <= 255; i++) { $.RegionNames[i] = $.Parameters[i] || ""; } $.getRegionName = function(regionId) { return ($.RegionNames[regionId] || "").trim(); }; Window_RegionName.prototype.refresh = function() { this.contents.clear(); var regionId = this._currentRegionId || 0; // var regionId = $gameMap.regionId($gamePlayer._x, $gamePlayer._y); if (regionId > 0) { var regionName = $.getRegionName(regionId); if (regionName) { var width = this.contentsWidth(); this.drawBackground(0, 0, width, this.lineHeight()); this.drawText(regionName, 0, 0, width, 'center'); } } }; Window_RegionName.prototype.update = function() { var regionId = $gameMap.regionId($gamePlayer._x, $gamePlayer._y); if (regionId!== this._currentRegionId) { this._currentRegionId = regionId; this.open(); } else { Window_MapName.prototype.update.call(this); } }; Scene_Map.prototype.createRegionNameWindow = function(){ this._regionNameWindow = new Window_RegionName(); this.addChild(this._regionNameWindow); }; $.oldSceneMap_createMapNameWindow = Scene_Map.prototype.createMapNameWindow; Scene_Map.prototype.createMapNameWindow = function() { $.oldSceneMap_createMapNameWindow.call(this); this.createRegionNameWindow.call(this); }; $.oldSceneMap_updateTransferPlayer = Scene_Map.prototype.updateTransferPlayer; Scene_Map.prototype.updateTransferPlayer = function() { if ($gamePlayer.isTransferring()) { this._regionNameWindow.close(); } $.oldSceneMap_updateTransferPlayer.call(this); this._regionNameWindow.update(); }; $.oldSceneMap_callMenu = Scene_Map.prototype.callMenu; Scene_Map.prototype.callMenu = function() { $.oldSceneMap_callMenu.call(this); this._regionNameWindow.hide(); }; $.oldSceneMap_launchBattle = Scene_Map.prototype.launchBattle; Scene_Map.prototype.launchBattle = function() { $.oldSceneMap_launchBattle.call(this); this._regionNameWindow.hide(); }; $.oldSceneMap_stop = Scene_Map.prototype.stop; Scene_Map.prototype.stop = function() { this._regionNameWindow.close(); $.oldSceneMap_stop.call(this); }; })(Hudell.OrangeRegionNames); OrangeRegionNames = Hudell.OrangeRegionNames; Imported["OrangeRegionNames"] = 1.0; ======================= File: OrangeSteamCloud.js ======================= /*============================================================================= * Orange - SteamCloud * By Hudell - www.hudell.com * OrangeSteamCloud.js * Version: 1.0 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Steam Cloud Integration <OrangeSteamCloud> * @author Hudell * * @help * ============================================================================ * Hudell's Plugins * ============================================================================ * * Check out my website to learn how to use this plugin: * http://hudell.com * *=============================================================================*/ var Imported = Imported || {}; var Hudell = Hudell || {}; Hudell.OrangeSteamCloud = Hudell.OrangeSteamCloud || {}; (function($) { "use strict"; if (!Utils.isNwjs()) return; if (Imported.OrangeGreenworks === undefined || isNaN(Imported.OrangeGreenworks) || Imported.OrangeGreenworks < 1.1) { console.error('OrangeGreenworks not found.'); return; } if (!OrangeGreenworks.initialized) { console.error('OrangeGreenworks not initialized'); return; } var g = OrangeGreenworks.greenworks; if (!g) { console.error('Unable to find OrangeGreenworks internal component.'); return; } $.syncAllSaves = function() { if (!g.isSteamRunning()) return; if (!g.isCloudEnabled()) return; if (!g.isCloudEnabledForUser()) return; g.readTextFromFile('globalInfo', function(json){ var localJson; try { localJson = StorageManager.load(0); } catch (e) { console.error(e); localJson = ''; } if (json == localJson) return; var globalInfo; var localGlobalInfo; try { globalInfo = JSON.parse(json); } catch(e) { globalInfo = {}; } try { localGlobalInfo = JSON.parse(localJson); } catch(e) { localGlobalInfo = {}; } for (var i = 1; i <= DataManager.maxSavefiles(); i++) { var remoteData = globalInfo[i]; var localData = localGlobalInfo[i]; if (!remoteData) continue; if (!!localData) { if (localData.timestamp >= remoteData.timestamp) continue; } $.downloadFile(i, remoteData); } }, function(msg){ console.log('Global Info download failed. Error message:', msg); }); }; $.saveFile = function(fileName, fileContent) { if (!g.isSteamRunning()) return; if (!g.isCloudEnabled()) return; if (!g.isCloudEnabledForUser()) return; g.saveTextToFile(fileName, fileContent, function(){ console.log('Save file uploaded successfully', arguments); }, function(){ console.error('Failed to upload save file:', arguments); }); }; $.updateLocalGlobalInfo = function(savefileId, header) { var globalInfo = DataManager.loadGlobalInfo() || []; globalInfo[savefileId] = header; $.saveLocally(0, JSON.stringify(globalInfo)); }; $.saveLocally = function(savefileId, json) { if (StorageManager.isLocalMode()) { StorageManager.saveToLocalFile(savefileId, json); } else { StorageManager.saveToWebStorage(savefileId, json); } }; $.downloadFile = function(savefileId, header) { if (!g.isSteamRunning()) return; if (!g.isCloudEnabled()) return; if (!g.isCloudEnabledForUser()) return; if (savefileId > 0) { g.readTextFromFile('save_' + savefileId, function(fileContent){ try { //Make sure the data is parse-able before saving it. var data = JSON.parse(fileContent); $.saveLocally(savefileId, fileContent); $.updateLocalGlobalInfo(savefileId, header); } catch(e) { console.error('Failed to save downloaded file'+ savefileId, e); } }, function(msg){ console.error('Failed to download save file'+ savefileId, msg); }); } else { if (savefileId == -1) { //jshint ignore:line g.readTextFromFile('config', function(fileContent){ $.saveLocally(-1, fileContent); ConfigManager.load(); }, function(msg){ console.error('Failed to download config from cloud.', msg); }); } } }; $._oldDataManager_makeSavefileInfo = DataManager.makeSavefileInfo; DataManager.makeSavefileInfo = function() { var info = $._oldDataManager_makeSavefileInfo.call(this); info.timestamp = new Date().getTime(); return info; }; $._oldStorageManager_save = StorageManager.save; StorageManager.save = function(savefileId, json) { $._oldStorageManager_save.call(this, savefileId, json); if (savefileId == 0) { //jshint ignore:line $.saveFile('globalInfo', json); } else if (savefileId == -1) { $.saveFile('config', json); } else { $.saveFile('save_' + savefileId, json); } }; $._oldDataManager_saveGlobalInfo = DataManager.saveGlobalInfo; DataManager.saveGlobalInfo = function(info) { info.timestamp = new Date().getTime(); $._oldDataManager_saveGlobalInfo.call(this, info); }; $.downloadFile(-1); $.syncAllSaves(); })(Hudell.OrangeSteamCloud); OrangeSteamCloud = Hudell.OrangeSteamCloud; Imported.OrangeSteamCloud = 1.0; ======================= File: OrangeOnLoadEvent.js ======================= /*============================================================================= * Orange - On Load Event * By Hudell - www.hudell.com * OrangeOnLoadEvent.js * Version: 1.0 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Will let you call a common event immediately after a load game * * @author Hudell * * @param commonEventId * @desc The number of the common event to call * @default 0 * * @help * ============================================================================ * Latest Version * ============================================================================ * * Get the latest version of this script on http://link.hudell.com/on-load-event * *=============================================================================*/ var Imported = Imported || {}; var OrangeOnLoadEvent = OrangeOnLoadEvent || {}; (function($) { "use strict"; $.Parameters = PluginManager.parameters('OrangeOnLoadEvent'); $.Param = $.Param || {}; $.Param.commonEventId = Number($.Parameters['commonEventId'] || 0); var oldGameSystem_onAfterLoad = Game_System.prototype.onAfterLoad; Game_System.prototype.onAfterLoad = function() { oldGameSystem_onAfterLoad.call(this); if ($.Param.commonEventId!== undefined && $.Param.commonEventId > 0) { $gameTemp.reserveCommonEvent($.Param.commonEventId); } }; })(OrangeOnLoadEvent); if (Imported['MVCommons']!== undefined) { PluginManager.register("OrangeOnLoadEvent", "1.0.0", "Will let you call a common event immediately after a load game", { email: "<EMAIL>", name: "Hudell", website: "http://www.hudell.com" }, "2015-10-19"); } else { Imported["OrangeOnLoadEvent"] = true; } ======================= File: OrangeLighting/OrangeTimeSystemLighting.js ======================= /*============================================================================= * Orange Lighting - Time System Lights * By Hudell - www.hudell.com * OrangeTimeSystemLighting.js * Version: 1.0 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Time System Lights <OrangeTimeSystemLighting> * @author Hudell * * @param hourColors * @desc A different color mask for each hour of the day. Requires OrangeTimeSystem. * @default #000000, #000000, #000000, #000000, #000000, #111111, #111111, #666666, #AAAAAA, #EEEEEE, #FFFFFF, #FFFFFF, #FFFFFF, #FFFFFF, #FFFFFF, #FFFFFF, #FFFFFF, #FFFFFF, #EEEEEE, #AAAAAA, #776666, #441111, #000000, #000000, #000000 * * @param insideBuildingsHourColor * @desc A different color mask to use inside buildings, for each hour of the day. Requires OrangeTimeSystem. * @default #FFFFFF * * @help * ============================================================================ * Hudell's Plugins * ============================================================================ * * Check out my website: * http://hudell.com * *=============================================================================*/ if (!Hudell ||!Hudell.OrangeLighting) { throw new Error("Couldn't find Hudell's OrangeLighting plugin. Please add it before this add-on."); } if (!OrangeTimeSystem) { throw new Error("Couldn't find Hudell's OrangeTimeSystem plugin. Please add it before this add-on."); } (function(lightSystem) { "use strict"; lightSystem.addOns.TimeSystemLights = {}; (function(timeSystemLights){ var parameters = $plugins.filter(function(plugin) { return plugin.description.contains('<OrangeTimeSystemLighting>'); }); if (parameters.length === 0) { throw new Error("Couldn't find Hudell's OrangeTimeSystemLighting parameters."); } timeSystemLights.Parameters = parameters[0].parameters; timeSystemLights.Param = {}; timeSystemLights.Param.hourColors = (timeSystemLights.Parameters.hourColors || "").split(","); timeSystemLights.Param.insideBuildingsHourColor = (timeSystemLights.Parameters.insideBuildingsHourColor || "").split(","); (function(){ for (var i = 0; i < timeSystemLights.Param.hourColors.length; i++) { timeSystemLights.Param.hourColors[i] = timeSystemLights.Param.hourColors[i].trim(); } for (i = 0; i < timeSystemLights.Param.insideBuildingsHourColor.length; i++) { timeSystemLights.Param.insideBuildingsHourColor[i] = timeSystemLights.Param.insideBuildingsHourColor[i].trim(); } if (timeSystemLights.Param.hourColors.length === 0){ timeSystemLights.Param.hourColors.push('black'); } if (timeSystemLights.Param.insideBuildingsHourColor.length === 0){ timeSystemLights.Param.insideBuildingsHourColor.push('#FFFFFF'); } })(); (function($) { timeSystemLights.oldMaskColor = $.maskColor; $.maskColor = function() { var hour = OrangeTimeSystem.hour; if (OrangeTimeSystem.inside) { return timeSystemLights.Param.insideBuildingsHourColor[hour % timeSystemLights.Param.insideBuildingsHourColor.length]; } else { return timeSystemLights.Param.hourColors[hour % timeSystemLights.Param.hourColors.length]; } }; })(lightSystem.Lightmask.prototype); })(lightSystem.addOns.TimeSystemLights); })(Hudell.OrangeLighting); Imported["OrangeLighting.TimeSystemLights"] = 1.0; ======================= File: OrangeHud/OrangeHudDate.js ======================= /*============================================================================= * Orange - Date HUD * By HUDell - www.hudell.com * OrangeHudDate.js * Version: 1.5 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Adds a new Variable to Orange Hud * @author Hudell * * @param GroupName * @desc The name of the HUD group where this line should be displayed * @default main * * @param Pattern * @desc The pattern of the line that will be drawn * @default %1/%2/%3 * * @param VariableDay * @desc The number of the variable that holds the Day value. * @default 0 * * @param VariableMonth * @desc The number of the variable that holds the Month value. * @default 0 * * @param VariableYear * @desc The number of the variable that holds the Year value. * @default 0 * * @param YearDigits * @desc The number of digits to display on the year number. * @default 4 * * @param SwitchId * @desc Set this to a switch number to use it to control the visibility of this line * @default 0 * * @param X * @desc The X position of the variable line inside the HUD * @default * * @param Y * @desc The Y position of the variable line inside the HUD * @default * * @param FontFace * @desc The font face to use. Leave empty to use the HUD default * @default * * @param FontSize * @desc The font size to use. Leave empty to use the HUD default * @default * * @param FontColor * @desc The font color to use. Leave empty to use the HUD default * @default * * @param FontItalic * @desc Should use italic? Leave empty to use the HUD default * @default * * @param ScriptPattern * @desc A script call to be used instead of the Pattern * @default * * @help * ============================================================================ * My Blog: * ============================================================================ * http://hudell.com * */ var Imported = Imported || {}; if (Imported["OrangeHud"] === undefined) { throw new Error("Please add OrangeHud before OrangeHudDate!"); } var OrangeHudDate = OrangeHudDate || {}; if (Imported["OrangeHudDate"] === undefined) { OrangeHudDate.validateParams = function(line) { line.GroupName = line.GroupName || "main"; if (line.ScriptPattern!== undefined && line.ScriptPattern.trim() === "") { line.ScriptPattern = undefined; } if (line.Pattern === undefined) { line.Pattern = "%1/%2/%3"; } else if (line.Pattern.trim() === "") { line.Pattern = ""; } line.VariableDay = Number(line.VariableDay || 0); line.VariableMonth = Number(line.VariableMonth || 0); line.VariableYear = Number(line.VariableYear || 0); line.YearDigits = Number(line.YearDigits || 4); if (line.FontFace === undefined || line.FontFace.trim() === "") { line.FontFace = OrangeHud.Param.DefaultFontFace; } if (line.FontColor === undefined || line.FontColor.trim() === "") { line.FontColor = OrangeHud.Param.DefaultFontColor; } line.FontSize = Number(line.FontSize || OrangeHud.Param.DefaultFontSize); line.X = Number(line.X || 0); line.Y = Number(line.Y || 0); if (line.FontItalic === undefined || line.FontItalic.trim() === "") { line.FontItalic = OrangeHud.Param.DefaultFontItalic; } else { line.FontItalic = line.FontItalic == "true"; } line.SwitchId = Number(line.SwitchId || 0); }; OrangeHudDate.drawLine = function(window, variableData) { if (variableData.SwitchId > 0) { if (!$gameSwitches.value(variableData.SwitchId)) { return; } } var line = this.getValue(variableData); window.contents.fontFace = variableData.FontFace; window.contents.fontSize = variableData.FontSize; window.contents.fontItalic = variableData.FontItalic; window.changeTextColor(variableData.FontColor); window.drawTextEx(line, variableData.X, variableData.Y); window.resetFontSettings(); }; OrangeHudDate.getValue = function(variableData) { var pattern = variableData.Pattern; if (variableData.ScriptPattern!== undefined) { pattern = Function("return " + variableData.ScriptPattern)(); } var day = ''; var month = ''; var year = ''; if (variableData.VariableDay > 0) { day = $gameVariables.value(variableData.VariableDay); if (typeof(day) == "number" || parseInt(day, 10) == day) { day = Number(day).padZero(2); } } if (variableData.VariableMonth > 0) { month = $gameVariables.value(variableData.VariableMonth); if (typeof(month) == "number" || parseInt(month, 10) == month) { month = Number(month).padZero(2); } } if (variableData.VariableYear > 0) { year = Number($gameVariables.value(variableData.VariableYear)).padZero(variableData.YearDigits); } return pattern.format(day, month, year); }; OrangeHudDate.getKey = function(variableData) { return variableData.VariableYear + ',' + variableData.VariableMonth + ',' + variableData.VariableDay; }; OrangeHud.registerLineType('OrangeHudDate', OrangeHudDate); Imported["OrangeHudDate"] = 1.5; } ======================= File: OrangeGreenworks.js ======================= <reponame>Ghabry/mv-plugins /*============================================================================= * Orange - Greenworks * By Hudell - www.hudell.com * OrangeGreenworks.js * Version: 1.2 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Steamworks Integration <OrangeGreenworks> * @author Hudell * * @help * ============================================================================ * Hudell's Plugins * ============================================================================ * * Check out my website to learn how to use this plugin: * http://hudell.com/blog/orangegreenworks/ * *=============================================================================*/ var Imported = Imported || {}; var Hudell = Hudell || {}; Hudell.OrangeGreenworks = Hudell.OrangeGreenworks || {}; (function($) { "use strict"; $.getScreenName = function() { return 'Play Test'; }; $.getUILanguage = function() { return 'english'; }; $.getGameLanguage = function() { return 'english'; }; $.activateAchievement = function(achievementName) { console.log('Activate achievement ', achievementName); }; $.getAchievement = function(achievementName) { return false; }; $.clearAchievement = function(achievementName) { console.log('Clear achievement ', achievementName); }; $.getNumberOfAchievements = function() { return 0; }; $.isSteamRunning = function() { return false; }; $.activateGameOverlay = function(option) { }; $.isGameOverlayEnabled = function() { return false; }; $.activateGameOverlayToWebPage = function(url) { console.log('Open URL'); }; $.getDLCCount = function() { return 0; }; $.isDLCInstalled = function(dlcAppId) { return false; }; $.installDLC = function(dlcAppId) { }; $.uninstallDLC = function(dlcAppId) { }; $.getStatInt = function(name) { return 0; }; $.getStatFloat = function(name) { return 0; }; $.setStat = function(name, value) { console.log('Change Stat', name, value); return false; }; $.storeStats = function() { console.log('Store Stats'); return false; }; $.isSubscribedApp = function(appId) { return false; }; if (Utils.isNwjs()) { $.initialized = false; try { $.greenworks = require('./greenworks'); } catch(e) { $.greenworks = false; console.log('Greenworks failed to load. Make sure you copied all files from the Steamworks SDK to the right folders;'); console.log('http://hudell.com/blog/orange-greenworks'); console.error(e); } if (!!$.greenworks) { $.initialized = $.greenworks.initAPI(); if (!$.initialized) { console.log('Greenworks failed to initialize.'); return; } $.steamId = $.greenworks.getSteamId(); console.log('Steam User: ', $.steamId.screenName); $.getScreenName = function() { return $.steamId.screenName; }; $.getUILanguage = function() { return $.greenworks.getCurrentUILanguage(); }; $.getGameLanguage = function() { return $.greenworks.getCurrentGameLanguage(); }; $.isSteamRunning = function() { return $.greenworks.isSteamRunning(); }; $._storeStatsSuccess = function(){ console.log('Stored Stats Successfully', arguments); }; $._storeStatsError = function(){ console.log('Failed to Store Stats', arguments); }; $._achievementSuccess = function(){ console.log('Achievement activated', arguments); }; $._achievementError = function(){ console.log('Achievement activation error', arguments); }; $._clearAchievementSuccess = function(){ console.log('Successfully Cleared Achievement', arguments); }; $._clearAchievementError = function(){ console.log('Failed to Clear Achievement', arguments); }; $._getAchievementSuccess = function(){ }; $._getAchievementError = function(){ console.log('Failed to check Achievement', arguments); }; $.activateAchievement = function(achievementName) { if (!achievementName) { console.log('Achievement name not provided.'); return; } if (!$.isSteamRunning()) { console.log('Steam isn\'t running'); return; } $.greenworks.activateAchievement(achievementName, $._achievementSuccess, $._achievementError); }; $.getAchievement = function(achievementName) { if (!achievementName) { console.log('Achievement name not provided.'); return false; } if (!$.isSteamRunning()) { console.log('Steam isn\'t running'); return false; } return $.greenworks.getAchievement(achievementName, $._getAchievementSuccess, $._getAchievementError); }; $.clearAchievement = function(achievementName) { if (!achievementName) { console.log('Achievement name not provided.'); return false; } if (!$.isSteamRunning()) { console.log('Steam isn\'t running'); return false; } $.greenworks.clearAchievement(achievementName, $._clearAchievementSuccess, $._clearAchievementError); }; $.getNumberOfAchievements = function() { if (!$.isSteamRunning()) { console.log('Steam isn\'t running'); return false; } return $.greenworks.getNumberOfAchievements(); }; $.activateGameOverlay = function(option) { if (!$.isSteamRunning()) { console.log('Steam isn\'t running'); return false; } $.greenworks.activateGameOverlay(option); }; $.isGameOverlayEnabled = function() { if (!$.isSteamRunning()) { console.log('Steam isn\'t running'); return false; } return $.greenworks.isGameOverlayEnabled(); }; $.activateGameOverlayToWebPage = function(url) { if (!$.isSteamRunning()) { console.log('Steam isn\'t running'); return false; } $.greenworks.activateGameOverlayToWebPage(url); }; $.isSubscribedApp = function(appId) { if (!$.isSteamRunning()) { console.log('Steam isn\'t running'); return false; } return $.greenworks.isSubscribedApp(appId); }; $.getDLCCount = function() { if (!$.isSteamRunning()) { console.log('Steam isn\'t running'); return 0; } return $.greenworks.getDLCCount(); }; $.isDLCInstalled = function(dlcAppId) { if (!$.isSteamRunning()) { console.log('Steam isn\'t running'); return false; } return $.greenworks.isDLCInstalled(dlcAppId); }; $.installDLC = function(dlcAppId) { if (!$.isSteamRunning()) { console.log('Steam isn\'t running'); return false; } $.greenworks.installDLC(dlcAppId); }; $.uninstallDLC = function(dlcAppId) { if (!$.isSteamRunning()) { console.log('Steam isn\'t running'); return false; } $.greenworks.uninstallDLC(dlcAppId); }; $.getStatInt = function(name) { if (!$.isSteamRunning()) { console.log('Steam isn\'t running'); return 0; } return $.greenworks.getStatInt(name); }; $.getStatFloat = function(name) { if (!$.isSteamRunning()) { console.log('Steam isn\'t running'); return 0; } return $.greenworks.getStatFloat(name); }; $.setStat = function(name, value) { if (!$.isSteamRunning()) { console.log('Steam isn\'t running'); return false; } return $.greenworks.setStat(name, value); }; $.storeStats = function() { if (!$.isSteamRunning()) { console.log('Steam isn\'t running'); return false; } return $.greenworks.setStat($._storeStatsSuccess, $._storeStatsError); }; $.getFriendCount = function() { return $.greenworks.getFriendCount($.greenworks.FriendFlags.Immediate); }; $.isCloudEnabled = function() { return $.greenworks.isCloudEnabled(); }; $.isCloudEnabledForUser = function() { return $.greenworks.isCloudEnabledForUser(); }; } } })(Hudell.OrangeGreenworks); OrangeGreenworks = Hudell.OrangeGreenworks; Imported.OrangeGreenworks = 1.2; ======================= File: OrangeTimeSystem/OrangeTimeSystemEvents.js ======================= /*============================================================================= * Orange - Time System Events * By Hudell - www.hudell.com * OrangeTimeSystemEvents.js * Version: 1.3 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Allow you to configure common events to be called when the time system changes * * @author Hudell *============================================================================= * * @param onChangeSecond * @desc The number of the common event to call when the second change * @default 0 * * @param onChangeMinute * @desc The number of the common event to call when the minute change * @default 0 * * @param onChangeHour * @desc The number of the common event to call when the hour change * @default 0 * * @param onChangeDay * @desc The number of the common event to call when the day change * @default 0 * * @param onChangeMonth * @desc The number of the common event to call when the month change * @default 0 * * @param onChangeYear * @desc The number of the common event to call when the year change * @default 0 * * @param onChangeDayPeriod * @desc The number of the common event to call when the day period change * @default 0 * * @param onChangeTime * @desc The number of the common event to call when the time changes * @default 0 * * @param onNightPeriod * @desc The number of the common event to call when the night starts * @default 0 * * @param onEarlyMorningPeriod * @desc The number of the common event to call when the night ends * @default 0 * * @param onDayPeriod * @desc The number of the common event to call when the sun rises * @default 0 * * @param onEveningPeriod * @desc The number of the common event to call when the sun starts to set * @default 0 * * @help * ============================================================================ * Latest Version * ============================================================================ * * Get the latest version of this script on * http://link.hudell.com/time-system-events * *=============================================================================*/ var Imported = Imported || {}; if (Imported["OrangeTimeSystem"] === undefined) { console.log('Download OrangeTimeSystem: http://link.hudell.com/time-system'); throw new Error("This library requires the OrangeTimeSystem!"); } var OrangeTimeSystemEvents = OrangeTimeSystemEvents || MVC.shallowClone(OrangeEventManager); (function($) { "use strict"; $.Parameters = PluginManager.parameters('OrangeTimeSystemEvents'); $.Param = $.Param || {}; $.Param.onChangeDay = Number($.Parameters['onChangeDay'] || 0); $.Param.onChangeMonth = Number($.Parameters['onChangeMonth'] || 0); $.Param.onChangeYear = Number($.Parameters['onChangeYear'] || 0); $.Param.onChangeHour = Number($.Parameters['onChangeHour'] || 0); $.Param.onChangeMinute = Number($.Parameters['onChangeMinute'] || 0); $.Param.onChangeSecond = Number($.Parameters['onChangeSecond'] || 0); $.Param.onChangeDayPeriod = Number($.Parameters['onChangeDayPeriod'] || 0); $.Param.onChangeTime = Number($.Parameters['onChangeTime'] || 0); $.Param.onNightPeriod = Number($.Parameters['onNightPeriod'] || 0); $.Param.onEarlyMorningPeriod = Number($.Parameters['onEarlyMorningPeriod'] || 0); $.Param.onDayPeriod = Number($.Parameters['onDayPeriod'] || 0); $.Param.onEveningPeriod = Number($.Parameters['onEveningPeriod'] || 0); $.onChangeDay = function() { if ($.Param.onChangeDay!== undefined && $.Param.onChangeDay > 0) { this.executeCallback($.Param.onChangeDay); } }; $.onChangeMonth = function() { if ($.Param.onChangeMonth!== undefined && $.Param.onChangeMonth > 0) { this.executeCallback($.Param.onChangeMonth); } }; $.onChangeYear = function() { if ($.Param.onChangeYear!== undefined && $.Param.onChangeYear > 0) { this.executeCallback($.Param.onChangeYear); } }; $.onChangeHour = function() { if ($.Param.onChangeHour!== undefined && $.Param.onChangeHour > 0) { this.executeCallback($.Param.onChangeHour); } }; $.onChangeMinute = function() { if ($.Param.onChangeMinute!== undefined && $.Param.onChangeMinute > 0) { this.executeCallback($.Param.onChangeMinute); } }; $.onChangeSecond = function() { if ($.Param.onChangeSecond!== undefined && $.Param.onChangeSecond > 0) { this.executeCallback($.Param.onChangeSecond); } }; $.onChangeDayPeriod = function() { if ($.Param.onChangeDayPeriod!== undefined && $.Param.onChangeDayPeriod > 0) { this.executeCallback($.Param.onChangeDayPeriod); } if (OrangeTimeSystem.dayPeriod == DayPeriods.NIGHT) { if ($.Param.onNightPeriod!== undefined && $.Param.onNightPeriod > 0) { this.executeCallback($.Param.onNightPeriod); } } if (OrangeTimeSystem.dayPeriod === DayPeriods.EARLY_MORNING) { if ($.Param.onEarlyMorningPeriod!== undefined && $.Param.onEarlyMorningPeriod > 0) { this.executeCallback($.Param.onEarlyMorningPeriod); } } if (OrangeTimeSystem.dayPeriod === DayPeriods.DAY) { if ($.Param.onDayPeriod!== undefined && $.Param.onDayPeriod > 0) { this.executeCallback($.Param.onDayPeriod); } } if (OrangeTimeSystem.dayPeriod === DayPeriods.EVENING) { if ($.Param.onEveningPeriod!== undefined && $.Param.onEveningPeriod > 0) { this.executeCallback($.Param.onEveningPeriod); } } }; $.onChangeTime = function() { if ($.Param.onChangeTime!== undefined && $.Param.onChangeTime > 0) { this.executeCallback($.Param.onChangeTime); } }; OrangeTimeSystem.on('changeDay', $.onChangeDay); OrangeTimeSystem.on('changeMonth', $.onChangeMonth); OrangeTimeSystem.on('changeYear', $.onChangeYear); OrangeTimeSystem.on('changeHour', $.onChangeHour); OrangeTimeSystem.on('changeMinute', $.onChangeMinute); OrangeTimeSystem.on('changeSecond', $.onChangeSecond); OrangeTimeSystem.on('changeDayPeriod', $.onChangeDayPeriod); OrangeTimeSystem.on('changeTime', $.onChangeTime); })(OrangeTimeSystemEvents); Imported["OrangeTimeSystemEvents"] = 1.3; ======================= File: OrangeNoteTagToVariable.js ======================= <gh_stars>10-100 /*============================================================================= * Orange - Notetag to Variable * By Hudell - www.hudell.com * OrangeNoteTagToVariable.js * Version: 1.2 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Allow you to automatically change a Variable value everytime a notetag is found on a map or event - <OrangeNoteTagToVariable> * @author Hudell * * @param VariableId * @desc The number of the Variable to store the value of the notetag * @default 0 * * @param notetag * @desc The name of the notetag to look for on the maps and event notes * @default 0 * * @param noteList * @desc Configure several notes with a single plugin using this param * @default * * @help * Add the <notetag:value> on the notes of the maps and events that you want to tag. * * This plugin can be added multiple times to the same project * (just make a copy of the file and add it) * * ============================================================================ * Latest Version * ============================================================================ * * Get the latest version of this script on * http://hudell.com * *=============================================================================*/ var Imported = Imported || {}; if (Imported["OrangeNoteTagToVariable"] === undefined) { (function() { "use strict"; var getProp = undefined; if (Imported["MVCommons"]!== undefined) { getProp = MVC.getProp; } else { getProp = function (meta, propName){ if (meta === undefined) return undefined; if (meta[propName]!== undefined) return meta[propName]; for (var key in meta) { if (key.toLowerCase() == propName.toLowerCase()) { return meta[key]; } } return undefined; }; } var paramList = []; function updateParamList(){ for (var i = 0; i < $plugins.length; i++) { if ($plugins[i].description.indexOf('<OrangeNoteTagToVariable>') >= 0) { var variableId = Number($plugins[i].parameters['VariableId'] || 0); var notetagName = $plugins[i].parameters['notetag'] || ''; if (variableId > 0 && notetagName.trim().length > 0) { paramList.push({ variableId : variableId, notetagName : notetagName }); } var list = $plugins[i].parameters['noteList']; if (list!== undefined) { var re = /<([^<>:]+):([^>]*)>/g; while(true) { var match = re.exec(list); if (match) { notetagName = match[1]; variableId = Number(match[2] || 0); if (variableId > 0 && notetagName.trim().length > 0) { paramList.push({ variableId : variableId, notetagName : notetagName }); } } else { break; } } } } } } updateParamList(); if (paramList.length > 0) { var updateVariableList = function() { if (SceneManager._scene instanceof Scene_Map) { for (var i = 0; i < paramList.length; i++) { var value = undefined; if ($gameMap._interpreter.isRunning() && $gameMap._interpreter._eventId > 0) { var eventData = $dataMap.events[$gameMap._interpreter._eventId]; if (eventData) { value = getProp(eventData.meta, paramList[i].notetagName); } } if (value === undefined) { value = $gameMap.getNoteTagValue(paramList[i].notetagName); } if (value!== undefined) { $gameVariables.setValue(paramList[i].variableId, value); } } } }; var oldGameInterpreter_setup = Game_Interpreter.prototype.setup; Game_Interpreter.prototype.setup = function(list, eventId) { oldGameInterpreter_setup.call(this, list, eventId); updateVariableList(); }; var oldGameInterpreter_terminate = Game_Interpreter.prototype.terminate; Game_Interpreter.prototype.terminate = function(list, eventId) { oldGameInterpreter_terminate.call(this, list, eventId); updateVariableList(); }; Game_Map.prototype.getNoteTagValue = function(notetagName) { return getProp($dataMap.meta, notetagName); }; var oldGamePlayer_performTransfer = Game_Player.prototype.performTransfer; Game_Player.prototype.performTransfer = function() { oldGamePlayer_performTransfer.call(this); updateVariableList(); }; } })(); Imported["OrangeNoteTagToVariable"] = 1.2; } ======================= File: OrangeHud/OrangeHudAlignedLine.js ======================= /*============================================================================= * Orange - Aligned Line HUD * By HUDell - www.hudell.com * OrangeHudAlignedLine.js * Version: 1.1.1 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc OrangeHudAlignedLine 1.0 - Adds a new Variable to Orange Hud with alignment support * @author Hudell * * @param GroupName * @desc The name of the HUD group where this line should be displayed * @default main * * @param Pattern * @desc The pattern of the line that will be drawn * @default %1 * * @param VariableId * @desc The number of the variable that will be displayed on this line. * @default 1 * * @param SwitchId * @desc Set this to a switch number to use it to control the visibility of this line * @default 0 * * @param X * @desc The X position of the variable line inside the HUD * @default * * @param Y * @desc The Y position of the variable line inside the HUD * @default * * @param Width * @desc The Width of the
1,505
oto)); } final _$ClienteControllerBaseActionController = ActionController(name: 'ClienteControllerBase'); @override dynamic visualizarSenha() { final _$actionInfo = _$ClienteControllerBaseActionController.startAction( name: 'ClienteControllerBase.visualizarSenha'); try { return super.visualizarSenha(); } finally { _$ClienteControllerBaseActionController.endAction(_$actionInfo); } } @override String toString() { return ''' clientes: ${clientes}, cliente: ${cliente}, formData: ${formData}, senhaVisivel: ${senhaVisivel}, clienteSelecionado: ${clienteSelecionado}, arquivo: ${arquivo}, error: ${error}, dioError: ${dioError}, mensagem: ${mensagem} '''; } } ======================= File: lib/src/core/controller/caixa_controller.g.dart ======================= // GENERATED CODE - DO NOT MODIFY BY HAND part of 'caixa_controller.dart'; // ************************************************************************** // StoreGenerator // ************************************************************************** // ignore_for_file: non_constant_identifier_names, unnecessary_brace_in_string_interps, unnecessary_lambdas, prefer_expression_function_bodies, lines_longer_than_80_chars, avoid_as, avoid_annotating_with_dynamic mixin _$CaixaController on CaixaControllerBase, Store { final _$caixasAtom = Atom(name: 'CaixaControllerBase.caixas'); @override List<Caixa> get caixas { _$caixasAtom.reportRead(); return super.caixas; } @override set caixas(List<Caixa> value) { _$caixasAtom.reportWrite(value, super.caixas, () { super.caixas = value; }); } final _$caixaAtom = Atom(name: 'CaixaControllerBase.caixa'); @override int get caixa { _$caixaAtom.reportRead(); return super.caixa; } @override set caixa(int value) { _$caixaAtom.reportWrite(value, super.caixa, () { super.caixa = value; }); } final _$caixaSelecionadoAtom = Atom(name: 'CaixaControllerBase.caixaSelecionado'); @override Caixa get caixaSelecionado { _$caixaSelecionadoAtom.reportRead(); return super.caixaSelecionado; } @override set caixaSelecionado(Caixa value) { _$caixaSelecionadoAtom.reportWrite(value, super.caixaSelecionado, () { super.caixaSelecionado = value; }); } final _$errorAtom = Atom(name: 'CaixaControllerBase.error'); @override Exception get error { _$errorAtom.reportRead(); return super.error; } @override set error(Exception value) { _$errorAtom.reportWrite(value, super.error, () { super.error = value; }); } final _$dioErrorAtom = Atom(name: 'CaixaControllerBase.dioError'); @override DioError get dioError { _$dioErrorAtom.reportRead(); return super.dioError; } @override set dioError(DioError value) { _$dioErrorAtom.reportWrite(value, super.dioError, () { super.dioError = value; }); } final _$mensagemAtom = Atom(name: 'CaixaControllerBase.mensagem'); @override String get mensagem { _$mensagemAtom.reportRead(); return super.mensagem; } @override set mensagem(String value) { _$mensagemAtom.reportWrite(value, super.mensagem, () { super.mensagem = value; }); } final _$getAllAsyncAction = AsyncAction('CaixaControllerBase.getAll'); @override Future<List<Caixa>> getAll() { return _$getAllAsyncAction.run(() => super.getAll()); } final _$createAsyncAction = AsyncAction('CaixaControllerBase.create'); @override Future<int> create(Caixa p) { return _$createAsyncAction.run(() => super.create(p)); } final _$updateAsyncAction = AsyncAction('CaixaControllerBase.update'); @override Future<int> update(int id, Caixa p) { return _$updateAsyncAction.run(() => super.update(id, p)); } @override String toString() { return ''' caixas: ${caixas}, caixa: ${caixa}, caixaSelecionado: ${caixaSelecionado}, error: ${error}, dioError: ${dioError}, mensagem: ${mensagem} '''; } } ======================= File: lib/src/api/interceptors/dio_response.dart ======================= <reponame>ofertasbv/ofertaflutterweb import 'dart:convert'; class DioResponse { DioResponse({ this.data, this.expire, }); final dynamic data; final DateTime expire; bool get expired => expire.difference(DateTime.now()).inMinutes < 0; DioResponse copyWith({ dynamic data, DateTime expire, }) => DioResponse( data: data?? this.data, expire: expire?? this.expire, ); String toRawJson() => json.encode(toJson()); Map<String, dynamic> toJson() => { "data": data, "expire": expire.toString(), }; factory DioResponse.fromRawJson(String str) => DioResponse.fromJson(json.decode(str)); factory DioResponse.fromJson(Map<String, dynamic> json) => DioResponse( data: json["data"], expire: DateTime.parse(json["expire"]), ); } ======================= File: lib/src/core/controller/pagamento_controller.g.dart ======================= // GENERATED CODE - DO NOT MODIFY BY HAND part of 'pagamento_controller.dart'; // ************************************************************************** // StoreGenerator // ************************************************************************** // ignore_for_file: non_constant_identifier_names, unnecessary_brace_in_string_interps, unnecessary_lambdas, prefer_expression_function_bodies, lines_longer_than_80_chars, avoid_as, avoid_annotating_with_dynamic mixin _$PagamentoController on PagamentoControllerBase, Store { final _$pagamentosAtom = Atom(name: 'PagamentoControllerBase.pagamentos'); @override List<Pagamento> get pagamentos { _$pagamentosAtom.reportRead(); return super.pagamentos; } @override set pagamentos(List<Pagamento> value) { _$pagamentosAtom.reportWrite(value, super.pagamentos, () { super.pagamentos = value; }); } final _$pagamentoAtom = Atom(name: 'PagamentoControllerBase.pagamento'); @override int get pagamento { _$pagamentoAtom.reportRead(); return super.pagamento; } @override set pagamento(int value) { _$pagamentoAtom.reportWrite(value, super.pagamento, () { super.pagamento = value; }); } final _$errorAtom = Atom(name: 'PagamentoControllerBase.error'); @override Exception get error { _$errorAtom.reportRead(); return super.error; } @override set error(Exception value) { _$errorAtom.reportWrite(value, super.error, () { super.error = value; }); } final _$dioErrorAtom = Atom(name: 'PagamentoControllerBase.dioError'); @override DioError get dioError { _$dioErrorAtom.reportRead(); return super.dioError; } @override set dioError(DioError value) { _$dioErrorAtom.reportWrite(value, super.dioError, () { super.dioError = value; }); } final _$mensagemAtom = Atom(name: 'PagamentoControllerBase.mensagem'); @override String get mensagem { _$mensagemAtom.reportRead(); return super.mensagem; } @override set mensagem(String value) { _$mensagemAtom.reportWrite(value, super.mensagem, () { super.mensagem = value; }); } final _$getAllAsyncAction = AsyncAction('PagamentoControllerBase.getAll'); @override Future<List<Pagamento>> getAll() { return _$getAllAsyncAction.run(() => super.getAll()); } final _$createAsyncAction = AsyncAction('PagamentoControllerBase.create'); @override Future<int> create(Pagamento p) { return _$createAsyncAction.run(() => super.create(p)); } final _$updateAsyncAction = AsyncAction('PagamentoControllerBase.update'); @override Future<int> update(int id, Pagamento p) { return _$updateAsyncAction.run(() => super.update(id, p)); } @override String toString() { return ''' pagamentos: ${pagamentos}, pagamento: ${pagamento}, error: ${error}, dioError: ${dioError}, mensagem: ${mensagem} '''; } } ======================= File: lib/src/core/controller/permissao_controller.g.dart ======================= // GENERATED CODE - DO NOT MODIFY BY HAND part of 'permissao_controller.dart'; // ************************************************************************** // StoreGenerator // ************************************************************************** // ignore_for_file: non_constant_identifier_names, unnecessary_brace_in_string_interps, unnecessary_lambdas, prefer_expression_function_bodies, lines_longer_than_80_chars, avoid_as, avoid_annotating_with_dynamic mixin _$PermissaoController on PermissaoControllerBase, Store { final _$permissoesAtom = Atom(name: 'PermissaoControllerBase.permissoes'); @override List<Permissao> get permissoes { _$permissoesAtom.reportRead(); return super.permissoes; } @override set permissoes(List<Permissao> value) { _$permissoesAtom.reportWrite(value, super.permissoes, () { super.permissoes = value; }); } final _$permissaoAtom = Atom(name: 'PermissaoControllerBase.permissao'); @override int get permissao { _$permissaoAtom.reportRead(); return super.permissao; } @override set permissao(int value) { _$permissaoAtom.reportWrite(value, super.permissao, () { super.permissao = value; }); } final _$errorAtom = Atom(name: 'PermissaoControllerBase.error'); @override Exception get error { _$errorAtom.reportRead(); return super.error; } @override set error(Exception value) { _$errorAtom.reportWrite(value, super.error, () { super.error = value; }); } final _$dioErrorAtom = Atom(name: 'PermissaoControllerBase.dioError'); @override DioError get dioError { _$dioErrorAtom.reportRead(); return super.dioError; } @override set dioError(DioError value) { _$dioErrorAtom.reportWrite(value, super.dioError, () { super.dioError = value; }); } final _$mensagemAtom = Atom(name: 'PermissaoControllerBase.mensagem'); @override String get mensagem { _$mensagemAtom.reportRead(); return super.mensagem; } @override set mensagem(String value) { _$mensagemAtom.reportWrite(value, super.mensagem, () { super.mensagem = value; }); } final _$getAllAsyncAction = AsyncAction('PermissaoControllerBase.getAll'); @override Future<List<Permissao>> getAll() { return _$getAllAsyncAction.run(() => super.getAll()); } final _$createAsyncAction = AsyncAction('PermissaoControllerBase.create'); @override Future<int> create(Permissao p) { return _$createAsyncAction.run(() => super.create(p)); } final _$updateAsyncAction = AsyncAction('PermissaoControllerBase.update'); @override Future<int> update(int id, Permissao p) { return _$updateAsyncAction.run(() => super.update(id, p)); } @override String toString() { return ''' permissoes: ${permissoes}, permissao: ${permissao}, error: ${error}, dioError: ${dioError}, mensagem: ${mensagem} '''; } } ======================= File: lib/src/paginas/loja/loja_produto_page.dart ======================= <gh_stars>0 import 'package:flutter/material.dart'; import 'package:flutter_mobx/flutter_mobx.dart'; import 'package:get_it/get_it.dart'; import 'package:intl/intl.dart'; import 'package:nosso/src/core/controller/produto_controller.dart'; import 'package:nosso/src/core/model/produto.dart'; import 'package:nosso/src/paginas/produto/produto_create_page.dart'; import 'package:nosso/src/paginas/produto/produto_detalhes_tab.dart'; import 'package:nosso/src/util/container/container_produto.dart'; import 'package:nosso/src/util/load/circular_progresso.dart'; class LojaProdutoPage extends StatefulWidget { @override _LojaProdutoPageState createState() => _LojaProdutoPageState(); } class _LojaProdutoPageState extends State<LojaProdutoPage> { var produtoController = GetIt.I.get<ProdutoController>(); var formatMoeda = new NumberFormat("#,##0.00", "pt_BR"); @override void initState() { produtoController.getAllByLojaById(2); super.initState(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("Meus produtos"), actions: [ Observer( builder: (context) { if (produtoController.error!= null) { return Text("Não foi possível carregar"); } if (produtoController.produtosByLoja == null) { return Center( child: Icon(Icons.warning_amber_outlined), ); } return CircleAvatar( backgroundColor: Colors.grey[300], foregroundColor: Colors.purple[800], child: Text( (produtoController.produtosByLoja.length?? 0).toString(), style: TextStyle(color: Colors.yellow[900]), ), ); }, ), SizedBox(width: 20), ], ), body: builderConteudoList(), floatingActionButton: FloatingActionButton( elevation: 10, child: Icon(Icons.add), onPressed: () { Navigator.of(context).pop(); Navigator.push( context, MaterialPageRoute(builder: (context) { return ProdutoCreatePage(); }), ); }, ), ); } builderConteudoList() { return Container( padding: EdgeInsets.only(top: 0), child: Observer( builder: (context) { List<Produto> produtos = produtoController.produtosByLoja; if (produtoController.error!= null) { return Text("Não foi possível buscar produtos"); } if (produtos == null) { return CircularProgressor(); } return builderListProduto(produtos); }, ), ); } builderListProduto(List<Produto> produtos) { double containerWidth = 250; double containerHeight = 20; return ListView.builder( scrollDirection: Axis.vertical, itemCount: produtos.length, itemBuilder: (context, index) { Produto p = produtos[index]; return GestureDetector( child: Padding( padding: EdgeInsets.symmetric(vertical: 0), child: ContainerProduto(produtoController, p), ), onTap: () { Navigator.of(context).push( MaterialPageRoute( builder: (BuildContext context) { return ProdutoDetalhesTab(p); }, ), ); }, ); }, ); } builderList(List<Produto> produtos) { double containerWidth = 160; double containerHeight = 30; DateFormat dateFormat = DateFormat('dd/MM/yyyy'); return ListView.builder( itemCount: produtos.length, itemBuilder: (context, index) { Produto p = produtos[index]; return GestureDetector( child: ListTile( isThreeLine: true, leading: Container( padding: EdgeInsets.all(1), decoration: new BoxDecoration( gradient: LinearGradient( colors: [Colors.purple, Colors.grey[900]], ), border: Border.all( color: Colors.black, width: 1, ), borderRadius: BorderRadius.circular(35), ), child: CircleAvatar( backgroundColor: Colors.grey[100], radius: 25, backgroundImage: NetworkImage( "${produtoController.arquivo + p.foto}", ), ), ), title: Text(p.nome), subtitle: Text( "R\$ ${formatMoeda.format(p.estoque.valorUnitario - ((p.estoque.valorUnitario * p.promocao.desconto) / 100))}", style: TextStyle( color: Colors.green, fontSize: 14, fontWeight: FontWeight.bold), ), trailing: Container( height: 80, width: 50, child: buildPopupMenuButton(context, p), ), ), onTap: () { Navigator.of(context).push( MaterialPageRoute( builder: (BuildContext context) { return ProdutoDetalhesTab(p); }, ), ); }, ); }, ); } PopupMenuButton<String> buildPopupMenuButton( BuildContext context, Produto p) { return PopupMenuButton<String>( padding: EdgeInsets.zero, enabled: true, elevation: 1, icon: Icon(Icons.more_vert), onSelected: (valor) { if (valor == "novo") { print("novo"); } if (valor == "editar") { print("editar"); Navigator.of(context).push( MaterialPageRoute( builder: (BuildContext context) { return ProdutoCreatePage( produto: p, ); }, ), ); } if (valor == "editar") { print("editar"); } }, itemBuilder: (BuildContext context) => <PopupMenuEntry<String>>[ const PopupMenuItem<String>( value: 'novo', child: ListTile( leading: Icon(Icons.add), title: Text('novo'), ), ), const PopupMenuItem<String>( value: 'editar', child: ListTile( leading: Icon(Icons.edit), title: Text('editar'), ), ), const PopupMenuItem<String>( value: 'delete', child: ListTile( leading: Icon(Icons.delete), title: Text('Delete'), ), ) ], ); } } ======================= File: lib/src/core/controller/cor_controller.g.dart ======================= // GENERATED CODE - DO NOT MODIFY BY HAND part of 'cor_controller.dart'; // ************************************************************************** // StoreGenerator // ************************************************************************** // ignore_for_file: non_constant_identifier_names, unnecessary_brace_in_string_interps, unnecessary_lambdas, prefer_expression_function_bodies, lines_longer_than_80_chars, avoid_as, avoid_annotating_with_dynamic mixin _$CorController on CorControllerBase, Store { final _$coresAtom = Atom(name: 'CorControllerBase.cores'); @override List<Cor> get cores { _$coresAtom.reportRead(); return super.cores; } @override set cores(List<Cor> value) { _$coresAtom.reportWrite(value, super.cores, () { super.cores = value; }); } final _$corAtom = Atom(name: 'CorControllerBase.cor'); @override int get cor { _$corAtom.reportRead(); return super.cor; } @override set cor(int value) { _$corAtom.reportWrite(value, super.cor, () { super.cor = value; }); } final _$errorAtom = Atom(name: 'CorControllerBase.error'); @override Exception get error { _$errorAtom.reportRead(); return super.error; } @override set error(Exception value) { _$errorAtom.reportWrite(value, super.error, () { super.error = value; }); } final _$dioErrorAtom = Atom(name: 'CorControllerBase.dioError'); @override DioError get dioError { _$dioErrorAtom.reportRead(); return super.dioError; } @override set dioError(DioError value) { _$dioErrorAtom.reportWrite(value, super.dioError, () { super.dioError = value; }); } final _$mensagemAtom = Atom(name: 'CorControllerBase.mensagem'); @override String get mensagem { _$mensagemAtom.reportRead(); return super.mensagem; } @override set mensagem(String value) { _$mensagemAtom.reportWrite(value, super.mensagem, () { super.mensagem = value; }); } final _$getAllAsyncAction = AsyncAction('CorControllerBase.getAll'); @override Future<List<Cor>> getAll() { return _$getAllAsyncAction.run(() => super.getAll()); } final _$createAsyncAction = AsyncAction('CorControllerBase.create'); @override Future<int> create(Cor p) { return _$createAsyncAction.run(() => super.create(p)); } final _$updateAsyncAction = AsyncAction('CorControllerBase.update'); @override Future<int> update(int id, Cor p) { return _$updateAsyncAction.run(() => super.update(id, p)); } @override String toString() { return ''' cores: ${cores}, cor: ${cor}, error: ${error}, dioError: ${dioError}, mensagem: ${mensagem} '''; } } ======================= File: lib/src/util/Examples/teste_mapa.dart ======================= import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter_mobx/flutter_mobx.dart'; import 'package:geolocator/geolocator.dart'; import 'package:get_it/get_it.dart'; import 'package:google_maps_flutter/google_maps_flutter.dart'; import 'package:nosso/src/api/constants/constant_api.dart'; import 'package:nosso/src/core/controller/loja_controller.dart'; import 'package:nosso/src/core/model/loja.dart'; import 'package:nosso/src/paginas/loja/loja_detalhes_tab.dart'; class TesteMapa extends StatefulWidget { const TesteMapa({ Key key, this.androidFusedLocation, }) : super(key: key); final bool androidFusedLocation; @override _TesteMapaState createState() => _TesteMapaState(); } class _TesteMapaState extends State<TesteMapa> { var lojaController = GetIt.I.get<LojaController>(); var loja = Loja(); var selectedCard = 'WEIGHT'; Position posicaoAtual; List<LatLng> latLng = <LatLng>[]; List<Marker> allMarkers = []; MapType mapType = MapType.normal; Completer<GoogleMapController> completer = Completer(); @override void initState() { super.initState(); localizacaoAtual(); lojaController.getAll(); } @override void didUpdateWidget(Widget oldWidget) { super.didUpdateWidget(oldWidget); setState(() { posicaoAtual = null; }); localizacaoAtual(); } selectCard(cardTitle) { setState(() { selectedCard = cardTitle; }); } onMapTypeButtonPressedNormal() { setState(() { mapType = MapType.normal; }); } onMapTypeButtonPressedTerra() { setState(() { mapType = MapType.terrain; }); } onMapTypeButtonPressedSatelite() { setState(() { mapType = MapType.satellite; }); } void criarMapa(GoogleMapController controller) async { await completer.complete(controller); } localizacaoAtual() { Geolocator.getCurrentPosition( desiredAccuracy: LocationAccuracy.high, ).then((posicao) { if (mounted) { setState(() => posicaoAtual = posicao); } }).catchError((e) { // }); } markers(Loja p) { return Marker( markerId: MarkerId(p.nome), position: LatLng(p.enderecos[0].latitude, p.enderecos[0].longitude), infoWindow: InfoWindow(title: p.nome, snippet: p.enderecos[0].logradouro), icon: BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueOrange), ); } movimentarCamera(double latitude, double longitude) async { GoogleMapController googleMapController = await completer.future; googleMapController.animateCamera( CameraUpdate.newCameraPosition( CameraPosition( target: LatLng(latitude, longitude), zoom: 18.0, tilt: 30, ), ), ); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("Localzação comercial"), ), body: posicaoAtual == null ? Container( child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ Center(child: CircularProgressIndicator()), FloatingActionButton.extended( onPressed: () { //_getUserLocation(); }, label: Text('Localizando...'), ) ], ), ) : Stack( children: [ Observer( builder: (context) { List<Loja> lojas = lojaController.lojas; if (lojaController.error!= null) { return Text("Não foi possível buscar lojas"); } if (lojas == null) { return GoogleMap( onMapCreated: criarMapa, mapType: mapType, initialCameraPosition: CameraPosition( target: LatLng( posicaoAtual.latitude, posicaoAtual.longitude, ), zoom: 12.0, ), myLocationEnabled: true, mapToolbarEnabled: false, ); } allMarkers = lojas.map((p) { return Marker( icon: BitmapDescriptor.defaultMarkerWithHue( BitmapDescriptor.hueYellow), infoWindow: InfoWindow( title: p.nome, snippet: p.enderecos[0].logradouro + ", " + p.enderecos[0].numero, ), markerId: MarkerId(p.nome), position: LatLng(p.enderecos[0].latitude?? 0.0, p.enderecos[0].longitude?? 0.0), onTap: () { showDialogAlert(context, p); }); }).toList(); return GoogleMap( onMapCreated: criarMapa, mapType: mapType, initialCameraPosition: CameraPosition( target: LatLng( posicaoAtual.latitude, posicaoAtual.longitude, ), zoom: 12.0, ), myLocationEnabled: true, mapToolbarEnabled: false, rotateGesturesEnabled: true, zoomControlsEnabled: false, markers: Set.of(allMarkers), ); }, ), Padding( padding: EdgeInsets.only(top: 60, right: 10), child: Align( alignment: Alignment.topRight, child: Column( children: <Widget>[ FloatingActionButton( onPressed: () { showDialogAlertTypeMap(context); }, materialTapTargetSize: MaterialTapTargetSize.shrinkWrap, child: Icon( Icons.map, size: 25, ), tooltip: "tipo de mapa", focusElevation: 5, mini: true, ), ], ), ), ), Align( alignment: Alignment.bottomCenter, child: Container( height: 110, color: Colors.transparent, padding: EdgeInsets.all(2), margin: EdgeInsets.only(bottom: 0), child: Observer( builder: (context) { List<Loja> lojas = lojaController.lojas; if (lojaController.error!= null) { return Text("Não foi possível buscar lojas"); } if (lojas == null) { return Center( child: Text("não foi possível carregar lojas"), ); } return builderList(lojas); }, ), ), ), ], ), ); } builderList(List<Loja> lojas) { return ListView.builder( scrollDirection: Axis.horizontal, itemCount: lojas.length, itemBuilder: (context, index) { Loja p = lojas[index]; return GestureDetector( child: AnimatedContainer( duration: Duration(seconds: 1), decoration: BoxDecoration( color: p.nome == selectedCard? Colors.yellow[200] : Colors.white, borderRadius: BorderRadius.circular(10), ), width: 240, padding: EdgeInsets.all(2), margin: EdgeInsets.only(left: 10), child: Row( children: <Widget>[ AspectRatio( aspectRatio: 0.9, child: ClipRRect( borderRadius: BorderRadius.circular(10), child: Image.network( ConstantApi.urlArquivoProduto + p.foto, fit: BoxFit.cover, ), ), ), Expanded( child: Container( padding: EdgeInsets.all(5), child: ListTile( title: Text(p.nome), subtitle: Text(p.telefone), ), ), ), ], ), ), onTap: () { selectCard(p.nome); movimentarCamera( p.enderecos[0].latitude, p.enderecos[0].longitude, ); }, ); }, ); } showDialogAlert(BuildContext context, Loja p) async { return showDialog( context: context, barrierDismissible: false, // user must tap button for close dialog! builder: (BuildContext context) { return AlertDialog( title: Text('Localização'), content: Container( height: 200, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text("${p.nome}"), Text("${p.enderecos[0].logradouro}, ${p.enderecos[0].numero}"), ], ), ), actions: <Widget>[ FlatButton( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(0), side: BorderSide(color: Colors.grey), ), color: Colors.white, textColor: Colors.grey, padding: EdgeInsets.all(10), child: const Text('CANCELAR'), onPressed: () { Navigator.of(context).pop(); }, ), FlatButton( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(0), side: BorderSide(color: Colors.blue), ), color: Colors.white, textColor: Colors.blue, padding: EdgeInsets.all(10), child: const Text('DETALHES'), onPressed: () { Navigator.of(context).push( MaterialPageRoute( builder: (BuildContext context) { return LojaDetalhesTab(p); }, ), ); }, ), ], ); }, ); } showDialogAlertTypeMap(BuildContext context) async { return showDialog( context: context, barrierDismissible: false, // user must tap button for close dialog! builder: (BuildContext context) { return AlertDialog( title: Text('Tipo de mapa'), content: Container( height: 200, width: double.infinity, child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ GestureDetector( child: Container( child: Column( children: <Widget>[ ClipRRect( borderRadius: BorderRadius.circular(10), child: Image.asset( ConstantApi.urlNormal, fit: BoxFit.cover, height: 60, width: 60, ), ), Text("Padrão"), ], ), ), onTap: () { onMapTypeButtonPressedNormal(); Navigator.of(context).pop(); }, ), GestureDetector( child: Container( child: Column( children: <Widget>[ ClipRRect( borderRadius: BorderRadius.circular(10), child: Image.asset( ConstantApi.urlSatelite, fit: BoxFit.cover, height: 60, width: 60, ), ), Text("Satélite"), ], ), ), onTap: () { onMapTypeButtonPressedSatelite(); Navigator.of(context).pop(); }, ), GestureDetector( child: Container( child: Column( children: <Widget>[ ClipRRect( borderRadius: BorderRadius.circular(10), child: Image.asset( ConstantApi.urlRelevo, fit: BoxFit.cover, height: 60, width: 60, ), ), Text( "Terra", ), ], ), ), onTap: () { onMapTypeButtonPressedTerra(); Navigator.of(context).pop(); }, ), ], ), ), actions: <Widget>[ FlatButton( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(0), side: BorderSide(color: Colors.grey), ), color: Colors.white, textColor: Colors.grey, padding: EdgeInsets.all(10), child: const Text('CANCELAR'), onPressed: () { Navigator.of(context).pop(); }, ), ], ); }, ); } } ======================= File: lib/src/paginas/caixafluxoentrada/caixafluxoentrada_create_page.dart ======================= <filename>lib/src/paginas/caixafluxoentrada/caixafluxoentrada_create_page.dart import 'dart:async'; import 'package:datetime_picker_formfield/datetime_picker_formfield.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_mobx/flutter_mobx.dart'; import 'package:fluttertoast/fluttertoast.dart'; import 'package:get_it/get_it.dart'; import 'package:intl/intl.dart'; import 'package:mask_text_input_formatter/mask_text_input_formatter.dart'; import 'package:nosso/src/core/controller/caixafluxo_controller.dart'; import 'package:nosso/src/core/controller/caixafluxoentrada_controller.dart'; import 'package:nosso/src/core/controller/vendedor_controller.dart'; import 'package:nosso/src/core/model/caixaentrada.dart'; import 'package:nosso/src/core/model/caixafluxo.dart'; import 'package:nosso/src/core/model/vendedor.dart'; import 'package:nosso/src/paginas/caixafluxoentrada/caixafluxoentrada_page.dart'; import 'package:nosso/src/paginas/produto/produto_search.dart'; import 'package:nosso/src/util/dialogs/dialogs.dart'; import 'package:nosso/src/util/dropdown/dropdown_vendedor.dart'; import 'package:nosso/src/util/validador/validador_caixafluxo.dart'; class CaixaFluxoEntradaCreatePage extends StatefulWidget { CaixaFluxoEntrada entrada; CaixaFluxoEntradaCreatePage({Key key, this.entrada}) : super(key: key); @override _CaixaFluxoEntradaCreatePageState createState() => _CaixaFluxoEntradaCreatePageState(c: this.entrada); } class _CaixaFluxoEntradaCreatePageState extends State<CaixaFluxoEntradaCreatePage> with ValidadorCaixaFluxo { _CaixaFluxoEntradaCreatePageState({this.c}); var caixafluxoentradaController = GetIt.I.get<CaixafluxoentradaController>(); var caixafluxoController = GetIt.I.get<CaixafluxoController>(); var vendedorController = GetIt.I.get<VendedorController>(); var dialogs = Dialogs(); var saldoAnteriorController = TextEditingController(); var valorEntradaController = TextEditingController(); var valorSaidaController = TextEditingController(); var valorTotalController = TextEditingController(); CaixaFluxoEntrada c; CaixaFluxo caixaFluxo; Vendedor vendedorSelecionado; Controller controller; @override void initState() { if (c == null) { c = CaixaFluxoEntrada(); } super.initState(); } @override didChangeDependencies() { controller = Controller(); super.didChangeDependencies(); } showToast(String cardTitle) { Fluttertoast.showToast( msg: "$cardTitle", gravity: ToastGravity.CENTER, timeInSecForIos: 10, fontSize: 16.0, ); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("Caixa entrada cadastro"), actions: <Widget>[ SizedBox(width: 20), IconButton( icon: Icon( Icons.search, size: 30, ), onPressed: () { showSearch(context: context, delegate: ProdutoSearchDelegate()); }, ) ], ), body: Observer( builder: (context) { if (caixafluxoController.dioError == null) { return buildListViewForm(context); } else { print("Erro: ${caixafluxoController.mensagem}"); showToast("${caixafluxoController.mensagem}"); return buildListViewForm(context); } }, ), ); } buildListViewForm(BuildContext context) { var dateFormat = DateFormat('dd/MM/yyyy HH:mm'); var maskFormatterNumero = new MaskTextInputFormatter( mask: '####-####-####-####', filter: {"#": RegExp(r'[0-9]')}); var focus = FocusScope.of(context); return ListView( children: <Widget>[ Container( color: Theme.of(context).accentColor.withOpacity(0.1), padding: EdgeInsets.all(0), child: ListTile( title: Text("Dados do fluxo de caixa"), ), ), SizedBox(height: 10), Container( padding: EdgeInsets.all(15), child: Container( height: 200, decoration: new BoxDecoration( gradient: LinearGradient( colors: [ Theme.of(context).primaryColor, Theme.of(context).accentColor ], ), border: Border.all( color: Colors.transparent, width: 1, ), borderRadius: BorderRadius.circular(10), ), child: Column( children: [ Container( padding: EdgeInsets.all(15), child: Row( children: [ Text("FLUXO DE CAIXA"), Icon(Icons.vpn_key_outlined), ], mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.center, ), ), SizedBox(height: 10), Container( padding: EdgeInsets.all(15), child: Row( children: [ Text( "${dateFormat.format(DateTime.now())}", style: TextStyle( fontSize: 18, fontWeight: FontWeight.bold, ), ), Icon(Icons.calculate_outlined), ], mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.center, ), ), SizedBox(height: 10), Container( padding: EdgeInsets.all(15), child: Row( children: [ Text("CAIXA 01 - PC01"), Icon(Icons.computer), ], mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.center, ), ) ], ), ), ), SizedBox(height: 0), Container( padding: EdgeInsets.all(5), child: Form( key: controller.formKey, child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ DropDownVendedor(vendedorSelecionado), Observer( builder: (context) { if (vendedorController.vendedoreSelecionado == null) { return Container( padding: EdgeInsets.only(left: 25), child: Container( child: vendedorController.mensagem == null ? Text( "campo obrigatório *", style: TextStyle( color: Colors.red, fontSize: 12, ), ) : Text( "${vendedorController.mensagem}", style: TextStyle( color: Colors.red, fontSize: 12, ), ), ), ); } return Container( padding: EdgeInsets.only(left: 25), child: Container( child: Icon(Icons.check_outlined, color: Colors.green), ), ); }, ), SizedBox(height: 0), Container( padding: EdgeInsets.all(15), child: Column( children: <Widget>[ SizedBox(height: 0), TextFormField( initialValue: c.descricao, onSaved: (value) => c.descricao = value, validator: validateDescricao, decoration: InputDecoration( labelText: "Descrição do caixa", border: OutlineInputBorder( gapPadding: 0.0, borderRadius: BorderRadius.circular(5), ), hintText: "Descrição", hintStyle: TextStyle(color: Colors.grey[400]), prefixIcon: Icon(Icons.credit_card), ), onEditingComplete: () => focus.nextFocus(), keyboardType: TextInputType.number, inputFormatters: [maskFormatterNumero], maxLength: 23, ), SizedBox(height: 10), TextFormField( controller: valorEntradaController, validator: validateValorEntrada, onSaved: (value) { c.valorEntrada = double.tryParse(value); }, decoration: InputDecoration( labelText: "Valor entrada", hintText: "Valor entrada", prefixIcon: Icon( Icons.monetization_on_outlined, color: Colors.grey, ), suffixIcon: IconButton( onPressed: () => valorEntradaController.clear(), icon: Icon(Icons.clear), ), contentPadding: EdgeInsets.fromLTRB(20.0, 20.0, 20.0, 20.0), border: OutlineInputBorder( borderRadius: BorderRadius.circular(5.0)), focusedBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.purple[900]), gapPadding: 1, borderRadius: BorderRadius.circular(5.0), ), ), onEditingComplete: () => focus.nextFocus(), keyboardType: TextInputType.numberWithOptions(decimal: false), maxLength: 6, ), SizedBox(height: 10), DateTimeField( initialValue: c.dataRegistro, onSaved: (value) => c.dataRegistro = value, validator: validateDataAbertura, format: dateFormat, decoration: InputDecoration( labelText: "Data de registro", prefixIcon: Icon( Icons.calendar_today, color: Colors.grey, ), suffixIcon: Icon(Icons.close), contentPadding: EdgeInsets.fromLTRB(20.0, 20.0, 20.0, 20.0), border: OutlineInputBorder( borderRadius: BorderRadius.circular(5.0)), focusedBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.purple[900]), gapPadding: 1, borderRadius: BorderRadius.circular(5.0), ), ), onEditingComplete: () => focus.nextFocus(), onShowPicker: (context, currentValue) { return showDatePicker( context: context, firstDate: DateTime(2000), initialDate: currentValue?? DateTime.now(), locale: Locale('pt', 'BR'), lastDate: DateTime(2030), ); }, keyboardType: TextInputType.datetime, ), ], ), ), ], ), ), ), SizedBox(height: 0), Container( padding: EdgeInsets.all(20), child: RaisedButton.icon( label: Text("Enviar formulário"), icon: Icon(Icons.check), onPressed: () { if (controller.validate()) { if (c.id == null) { dialogs.information(context, "prepando para o cadastro..."); Timer(Duration(seconds: 3), () { caixafluxoentradaController.create(c).then((value) { print("resultado : ${value}"); }); Navigator.of(context).pop(); buildPush(context); }); } else { dialogs.information( context, "preparando para o alteração..."); Timer(Duration(seconds: 3), () { caixafluxoentradaController.update(c.id, c); Navigator.of(context).pop(); buildPush(context); }); } } }, ), ), ], ); } buildPush(BuildContext context) { return Navigator.push( context, MaterialPageRoute( builder: (context) => CaixaFluxoEntradaPage(), ), ); } } class Controller { var formKey = GlobalKey<FormState>(); bool validate() { var form = formKey.currentState; if (form.validate()) { form.save(); return true; } else return false; } } ======================= File: lib/src/core/repository/usuario_repository.dart ======================= import 'package:dio/dio.dart'; import 'package:nosso/src/api/dio/custom_dio.dart'; import 'package:nosso/src/api/dio/custon_dio.dart'; import 'package:nosso/src/core/model/usuario.dart'; import 'package:shared_preferences/shared_preferences.dart'; class UsuarioRepository { CustonDio dio = CustonDio(); Future<List<Usuario>> getAllById(int id) async { try { print("carregando usuarios by id"); var response = await dio.client.get("/usuarios/${id}"); return (response.data as List).map((c) => Usuario.fromJson(c)).toList(); } on DioError catch (e) { print(e.message); } return null; } Future<List<Usuario>> getAll() async { try { print("carregando usuarios"); var response = await dio.client.get("/usuarios"); return (response.data as List).map((c) => Usuario.fromJson(c)).toList(); } on DioError catch (e) { print(e.message); } return null; } Future<Usuario> getByEmail(String email) async { try { print("carregando usuarios by email"); var response = await dio.client.get("/usuarios/email/$email"); return Usuario.fromJson(response.data); } on DioError catch (e) { print(e.message); } return null; } Future<Usuario> getByLogin(String email, String senha) async { try { print("carregando usuario by login"); var response = await dio.client.get("/usuarios/login/$email/$senha"); print("Status login: ${response.statusCode}"); return Usuario.fromJson(response.data); } on DioError catch (e) { print(e.message); } return null; } Future<int> update(int id, Map<String, dynamic> data) async { var response = await dio.client.put("/usuarios/update/$id", data: data); return response.statusCode; } Future<int> create(Map<String, dynamic> data) async { var response = await dio.client.post("/usuarios/create", data: data); return response.statusCode; } Future<int> loginToken(Map<String, dynamic> data) async { var response = await dio.client .post("/oauth/token", data: data, options: Options(headers: {})); print(response.data); print(response.headers); print(response.request); print(response.statusCode); return response.statusCode; } Future<int> login(Map<String, dynamic> data) async { // Dio dio = Dio(); Map<String, String> headers = { "Content-type": "application/x-www-form-urlencoded", // "Accept": "application/json", "Authorization": "Basic bW9iaWxlOm0wYjFsMzA=", }; var data = { // "client" : "mobile", "username": "<EMAIL>", "password": "<PASSWORD>", "grant_type": "password" }; var response = await dio.client.post( "/oauth/token", data: data, options: Options(headers: headers), ); return response.statusCode; // .then((res) async { // SharedPreferences prefs = await SharedPreferences.getInstance(); // await prefs.setString('token', res.data['token']); // }).catchError((err) { // throw Exception('Login ou senha inválidos'); // }); } } ======================= File: lib/src/paginas/vendedor/vendedor_list.dart ======================= <filename>lib/src/paginas/vendedor/vendedor_list.dart import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter_mobx/flutter_mobx.dart'; import 'package:get_it/get_it.dart'; import 'package:nosso/src/core/controller/vendedor_controller.dart'; import 'package:nosso/src/core/model/vendedor.dart'; import 'package:nosso/src/paginas/vendedor/vendedor_create_page.dart'; import 'package:nosso/src/util/load/circular_progresso.dart'; class VendedorList extends StatefulWidget { @override _VendedorListState createState() => _VendedorListState(); } class _VendedorListState extends State<VendedorList> with AutomaticKeepAliveClientMixin<VendedorList> { var vendedorController = GetIt.I.get<VendedorController>(); @override void initState() { vendedorController.getAll(); super.initState(); } Future<void> onRefresh() { return vendedorController.getAll(); } bool isLoading = true; @override Widget build(BuildContext context) { return builderConteudoList(); } builderConteudoList() { return Container( padding: EdgeInsets.only(top: 0), child: Observer( builder: (context) { List<Vendedor> vendedores = vendedorController.vendedores; if (vendedorController.error!= null) { return Text("Não foi possível carregados dados"); } if (vendedores == null) { return CircularProgressor(); } return RefreshIndicator( onRefresh: onRefresh, child: builderList(vendedores), ); }, ), ); } ListView builderList(List<Vendedor> vendedores) { double containerWidth = 160; double containerHeight = 30; return ListView.builder( itemCount: vendedores.length, itemBuilder: (context, index) { Vendedor p = vendedores[index]; return GestureDetector( child: ListTile( isThreeLine: true, leading: Container( padding: EdgeInsets.all(1), decoration: new BoxDecoration( gradient: LinearGradient( colors: [ Theme.of(context).primaryColor, Theme.of(context).primaryColor ], ), border: Border.all( color: Colors.black, width: 1, ), borderRadius: BorderRadius.circular(35), ), child: p.foto == null ? CircleAvatar( backgroundColor: Colors.grey[100], radius: 20, child: Icon(Icons.photo)) : CircleAvatar( backgroundColor: Colors.grey[100], radius: 20, backgroundImage: NetworkImage( "${vendedorController.arquivo + p.foto}", ), ), ), title: Text(p.nome), subtitle: Text("${p.telefone}"), trailing: Container( height: 80, width: 50, child: buildPopupMenuButton(context, p), ), ), onTap: () {}, ); }, ); } PopupMenuButton<String> buildPopupMenuButton( BuildContext context, Vendedor p) { return PopupMenuButton<String>( padding: EdgeInsets.zero, icon: Icon(Icons.more_vert), onSelected: (valor) { if (valor == "novo") { print("novo"); } if (valor == "editar") { print("editar"); Navigator.of(context).push( MaterialPageRoute( builder: (BuildContext context) { return VendedorCreatePage( vendedor: p, ); }, ), ); } if (valor == "delete") { print("delete"); } }, itemBuilder: (BuildContext context) => <PopupMenuEntry<String>>[ const PopupMenuItem<String>( value: 'novo', child: ListTile( leading: Icon(Icons.add), title: Text('novo'), ), ), const PopupMenuItem<String>( value: 'editar', child: ListTile( leading: Icon(Icons.edit), title: Text('editar'), ), ), const PopupMenuItem<String>( value: 'delete', child: ListTile( leading: Icon(Icons.delete), title: Text('delete'), ), ), ], ); } @override // TODO: implement wantKeepAlive bool get wantKeepAlive => true; } ======================= File: lib/src/core/enum/pagamento_tipo.dart ======================= <reponame>ofertasbv/ofertaflutterweb enum PagamentoTipo { VISTA, PRAZO, } ======================= File: lib/src/core/controller/arquivo_controller.dart ======================= <filename>lib/src/core/controller/arquivo_controller.dart import 'dart:io'; import 'package:dio/dio.dart'; import 'package:mobx/mobx.dart'; import 'package:nosso/src/api/constants/constant_api.dart'; import 'package:nosso/src/core/model/arquivo.dart'; import 'package:nosso/src/core/repository/arquivo_repository.dart'; part 'arquivo_controller.g.dart'; class ArquivoController = ArquivoControllerBase with _$ArquivoController; abstract class ArquivoControllerBase with Store { ArquivoRepository arquivoRepository; ArquivoControllerBase() { arquivoRepository = ArquivoRepository(); } @observable List<Arquivo> arquivos; @observable int arquivo; @observable var formData; @observable Exception error; @observable DioError dioError; @observable String mensagem; @observable String arquivoFoto = ConstantApi.urlArquivoArquivo; @action Future<List<Arquivo>> getAll() async { try { arquivos = await arquivoRepository.getAll(); return arquivos; } catch (e) { error = e; } } @action Future<int> create(Arquivo p) async { try { arquivo = await arquivoRepository.create(p.toJson()); if (arquivo == null) { mensagem = "sem dados"; } else { return arquivo; } } on DioError catch (e) { mensagem = e.message; dioError = e; } } @action Future<int> update(int id, Arquivo p) async { try { arquivo = await arquivoRepository.update(id, p.toJson()); return arquivo; } on DioError catch (e) { mensagem = e.message; dioError = e; } } @action Future<String> upload(File foto, String fileName) async { try { formData = await arquivoRepository.upload(foto, fileName); return formData; } catch (e) { error = e; } } @action Future<void> deleteFoto(String foto) async { try { await arquivoRepository.deleteFoto(foto); } catch (e) { error = e; } } } ======================= File: lib/src/core/model/loja.dart ======================= <reponame>ofertasbv/ofertaflutterweb import 'package:nosso/src/core/model/endereco.dart'; import 'package:nosso/src/core/model/pessoa.dart'; import 'package:nosso/src/core/model/produto.dart'; import 'package:nosso/src/core/model/usuario.dart'; class Loja extends Pessoa { int id; String nome; String telefone; String tipoPessoa; DateTime dataRegistro; String foto; Usuario usuario = new Usuario(); String razaoSocial; String cnpj; List<Produto> produtos; List<Endereco> enderecos = List<Endereco>(); Loja({ this.id, this.nome, this.telefone, this.tipoPessoa, this.dataRegistro, this.foto, this.usuario, this.razaoSocial, this.cnpj, this.produtos, this.enderecos, }); Loja.fromJson(Map<String, dynamic> json) { id = json['id']; nome = json['nome']; telefone = json['telefone']; tipoPessoa = json['tipoPessoa']; dataRegistro = DateTime.tryParse(json['dataRegistro'].toString()); foto = json['foto']; usuario = json['usuario']!= null? new Usuario.fromJson(json['usuario']) : null; razaoSocial = json['razaoSocial']; cnpj = json['cnpj']; if (json['produtos']!= null) { produtos = new List<Produto>(); json['produtos'].forEach((v) { produtos.add(new Produto.fromJson(v)); }); } if (json['enderecos']!= null) { enderecos = new List<Endereco>(); json['enderecos'].forEach((v) { enderecos.add(new Endereco.fromJson(v)); }); } } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['id'] = this.id; data['nome'] = this.nome; data['telefone'] = this.telefone; data['tipoPessoa'] = this.tipoPessoa; data['dataRegistro'] = this.dataRegistro.toIso8601String(); data['foto'] = this.foto; if (this.usuario!= null) { data['usuario'] = this.usuario.toJson(); } data['razaoSocial'] = this.razaoSocial; data['cnpj'] = this.cnpj; if (this.produtos!= null) { data['produtos'] = this.produtos.map((v) => v.toJson()).toList(); } if (this.enderecos!= null) { data['enderecos'] = this.enderecos.map((v) => v.toJson()).toList(); } return data; } } ======================= File: lib/src/core/enum/fatura_status.dart ======================= enum FaturaStatus { PAGA, PENDENTE, CANCELADA, } ======================= File: lib/src/core/controller/promocaotipo_controller.g.dart ======================= // GENERATED CODE - DO NOT MODIFY BY HAND part of 'promocaotipo_controller.dart'; // ************************************************************************** // StoreGenerator // ************************************************************************** // ignore_for_file: non_constant_identifier_names, unnecessary_brace_in_string_interps, unnecessary_lambdas, prefer_expression_function_bodies, lines_longer_than_80_chars, avoid_as, avoid_annotating_with_dynamic mixin _$PromocaoTipoController on PromocaoTipoControllerBase, Store { final _$promocaoTiposAtom = Atom(name: 'PromocaoTipoControllerBase.promocaoTipos'); @override List<PromocaoTipo> get promocaoTipos { _$promocaoTiposAtom.reportRead(); return super.promocaoTipos; } @override set promocaoTipos(List<PromocaoTipo> value) { _$promocaoTiposAtom.reportWrite(value, super.promocaoTipos, () { super.promocaoTipos = value; }); } final _$promocaoTipoAtom = Atom(name: 'PromocaoTipoControllerBase.promocaoTipo'); @override int get promocaoTipo { _$promocaoTipoAtom.reportRead(); return super.promocaoTipo; } @override set promocaoTipo(int value) { _$promocaoTipoAtom.reportWrite(value, super.promocaoTipo, () { super.promocaoTipo = value; }); } final _$promocaoTipoSelecionadaAtom = Atom(name: 'PromocaoTipoControllerBase.promocaoTipoSelecionada'); @override PromocaoTipo get promocaoTipoSelecionada { _$promocaoTipoSelecionadaAtom.reportRead(); return super.promocaoTipoSelecionada; } @override set promocaoTipoSelecionada(PromocaoTipo value) { _$promocaoTipoSelecionadaAtom .reportWrite(value, super.promocaoTipoSelecionada, () { super.promocaoTipoSelecionada = value; }); } final _$errorAtom = Atom(name: 'PromocaoTipoControllerBase.error'); @override Exception get error { _$errorAtom.reportRead(); return super.error; } @override set error(Exception value) { _$errorAtom.reportWrite(value, super.error, () { super.error = value; }); } final _$dioErrorAtom = Atom(name: 'PromocaoTipoControllerBase.dioError'); @override DioError get dioError { _$dioErrorAtom.reportRead(); return super.dioError; } @override set dioError(DioError value) { _$dioErrorAtom.reportWrite(value, super.dioError, () { super.dioError = value; }); } final _$mensagemAtom = Atom(name: 'PromocaoTipoControllerBase.mensagem'); @override String get mensagem { _$mensagemAtom.reportRead(); return super.mensagem; } @override set mensagem(String value) { _$mensagemAtom.reportWrite(value, super.mensagem, () { super.mensagem = value; }); } final _$getAllAsyncAction = AsyncAction('PromocaoTipoControllerBase.getAll'); @override Future<List<PromocaoTipo>> getAll() { return _$getAllAsyncAction.run(() => super.getAll()); } final _$createAsyncAction = AsyncAction('PromocaoTipoControllerBase.create'); @override Future<int> create(PromocaoTipo p) { return _$createAsyncAction.run(() => super.create(p)); } final _$updateAsyncAction = AsyncAction('PromocaoTipoControllerBase.update'); @override Future<int> update(int id, PromocaoTipo p) { return _$updateAsyncAction.run(() => super.update(id, p)); } @override String toString() { return ''' promocaoTipos: ${promocaoTipos}, promocaoTipo: ${promocaoTipo}, promocaoTipoSelecionada: ${promocaoTipoSelecionada}, error: ${error}, dioError: ${dioError}, mensagem: ${mensagem} '''; } } ======================= File: lib/src/util/dropdown/dropdown_endereco.dart ======================= <gh_stars>0 import 'package:flutter/material.dart'; import 'package:flutter_mobx/flutter_mobx.dart'; import 'package:get_it/get_it.dart'; import 'package:nosso/src/core/controller/endereco_controller.dart'; import 'package:nosso/src/core/model/endereco.dart'; import 'package:nosso/src/paginas/endereco/endereco_search.dart'; class DropDownEndereco extends StatelessWidget { Endereco endereco; DropDownEndereco(this.endereco); @override Widget build(BuildContext context) { var enderecoController = GetIt.I.get<EnderecoController>(); return Observer( builder: (context) { Endereco endereco = enderecoController.enderecoSelecionado; return Container( padding: EdgeInsets.all(15), child: Container( decoration: BoxDecoration( border: Border.all(color: Colors.grey), borderRadius: BorderRadius.circular(5), ), child: ListTile( title: Text("Endereço *"), subtitle: endereco == null ? Text("Selecione um endereço") : Text("${endereco.logradouro}, ${endereco.numero} - ${endereco.complemento}"), leading: Icon(Icons.location_on_outlined), trailing: Icon(Icons.arrow_drop_down_sharp), onTap: () { showSearch( context: context, delegate: EnderecoSearchDelegate(), ); }, ), ), ); }, ); } } ======================= File: lib/src/paginas/pedidoitem/pedito_itens_page.dart ======================= <reponame>ofertasbv/ofertaflutterweb import 'dart:ui'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_mobx/flutter_mobx.dart'; import 'package:get_it/get_it.dart'; import 'package:intl/intl.dart'; import 'package:nosso/src/api/constants/constant_api.dart'; import 'package:nosso/src/core/controller/pedidoItem_controller.dart'; import 'package:nosso/src/core/model/pedidoitem.dart'; import 'package:nosso/src/paginas/produto/produto_tab.dart'; import 'package:nosso/src/util/load/circular_progresso.dart'; import 'package:nosso/src/util/snackbar/snackbar_global.dart'; class PedidoItensList extends StatefulWidget { @override _PedidoItensListState createState() => _PedidoItensListState(); } class _PedidoItensListState extends State<PedidoItensList> { var pedidoItemController = GetIt.I.get<PedidoItemController>(); var formatMoeda = new NumberFormat("#,##0.00", "pt_BR"); @override void initState() { pedidoItemController.pedidosItens(); pedidoItemController.calculateTotal(); super.initState(); } showSnackbar(BuildContext context, String texto) { final snackbar = SnackBar(content: Text(texto)); GlobalScaffold.instance.showSnackbar(snackbar); } @override Widget build(BuildContext context) { return builderConteudoList(); } builderConteudoList() { return Container( padding: EdgeInsets.only(top: 0), child: Observer( builder: (context) { List<PedidoItem> itens = pedidoItemController.itens; if (pedidoItemController.error!= null) { return Text("Não foi possível carregados dados"); } if (itens == null) { return CircularProgressor(); } if (itens.length == 0) { return Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Center( child: Icon( Icons.shopping_basket, color: Colors.green, size: 100, ), ), Text("Sua cesta está vazia"), SizedBox(height: 20), RaisedButton.icon( onPressed: () { Navigator.of(context).push( MaterialPageRoute( builder: (BuildContext context) { return ProdutoTab(); }, ), ); }, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(0), side: BorderSide(color: Colors.blue), ), color: Colors.white, textColor: Colors.green, padding: EdgeInsets.all(10), icon: Icon( Icons.home, color: Colors.blue, ), label: Text( "ESCOLHER PRODUTOS", style: TextStyle( color: Colors.blue, ), ), elevation: 0, ), ], ), ); } return builderList(itens); }, ), ); } ListView builderList(List<PedidoItem> itens) { double containerWidth = 200; double containerHeight = 20; return ListView.builder( itemCount: itens.length, itemBuilder: (context, index) { PedidoItem p = itens[index]; p.valorUnitario = p.produto.estoque.valorUnitario; p.valorTotal = (p.quantidade * p.valorUnitario); return GestureDetector( child: Column( children: <Widget>[ Padding( padding: EdgeInsets.symmetric(vertical: 2), child: Card( child: Container( color: Colors.grey[100], padding: EdgeInsets.all(5), child: Row( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ ClipRRect( borderRadius: BorderRadius.circular(10), child: Image.network( ConstantApi.urlArquivoProduto + p.produto.foto, fit: BoxFit.cover, width: 100, height: 130, ), ), Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Container( height: 30, width: containerWidth, child: Text( p.produto.nome, overflow: TextOverflow.ellipsis, style: TextStyle( color: Colors.black, fontWeight: FontWeight.bold, ), ), ), SizedBox(height: 5), Container( height: containerHeight, width: containerWidth, //color: Colors.grey[300], child: Row( crossAxisAlignment: CrossAxisAlignment.stretch, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Text( "Valor unitário ", style: TextStyle( color: Colors.grey, fontWeight: FontWeight.bold, ), ), Text( "R\$ ${formatMoeda.format(p.valorUnitario)}", style: TextStyle( color: Colors.green, ), ), ], ), ), SizedBox(height: 5), Container( height: containerHeight, width: containerWidth, //color: Colors.grey[300], child: Row( crossAxisAlignment: CrossAxisAlignment.stretch, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Text( "SubTotal ", style: TextStyle( color: Colors.grey, ), ), Text( "R\$ ${formatMoeda.format(p.valorTotal)}", style: TextStyle( color: Colors.green, ), ), ], ), ), SizedBox(height: 5), Container( width: containerWidth, height: 40, child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ CircleAvatar( backgroundColor: Colors.grey[200], foregroundColor: Colors.redAccent, radius: 20, child: IconButton( icon: Icon(Icons.delete_forever), splashColor: Colors.black, onPressed: () { showDialogAlert(context, p); }, ), ), Container( width: 110, height: 30, decoration: BoxDecoration( borderRadius: BorderRadius.circular(10), color: Colors.grey[200], ), child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ SizedBox( child: CircleAvatar( backgroundColor: Colors.grey[200], foregroundColor: Colors.black, child: IconButton( icon: Icon(Icons .indeterminate_check_box_outlined), splashColor: Colors.black, onPressed: () { setState(() { print("removendo - "); print("${p.quantidade}"); pedidoItemController .decremento(p); // pedidoItemController // .calculateTotal(); }); }, ), ), width: 38, ), Container( width: 30, height: 30, color: Colors.grey[100], child: Center( child: Text( "${p.quantidade}", style: TextStyle( color: Colors.black, fontWeight: FontWeight.bold, ), ), ), ), SizedBox( child: CircleAvatar( backgroundColor: Colors.grey[200], foregroundColor: Colors.black, child: IconButton( icon: Icon(Icons.add), splashColor: Colors.black, onPressed: () { setState(() { print("adicionando + "); print("${p.quantidade}"); pedidoItemController .incremento(p); // pedidoItemController // .calculateTotal(); }); }, ), ), width: 38, ), ], ), ), ], ), ), ], ) ], ), ), ), ), ], ), ); }, ); } showDialogAlert(BuildContext context, PedidoItem p) async { return showDialog( context: context, barrierDismissible: false, // user must tap button for close dialog! builder: (BuildContext context) { return AlertDialog( title: Text( "Deseja remover este item?", style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold), ), content: Container( height: 200, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text("${p.produto.nome}"), Text("Cod: ${p.produto.id}"), SizedBox( height: 20, ), Center( child: ClipRRect( borderRadius: BorderRadius.circular(10), child: Image.network( ConstantApi.urlArquivoProduto + p.produto.foto, fit: BoxFit.cover, width: 100, height: 100, ), ), ), ], ), ), actions: <Widget>[ RaisedButton.icon( icon: Icon( Icons.cancel, color: Colors.grey, ), shape: RoundedRectangleBorder( side: BorderSide(color: Colors.grey), borderRadius: BorderRadius.all( Radius.circular(0), ), ), label: Text('CANCELAR'), color: Colors.white, elevation: 0, onPressed: () { Navigator.of(context).pop(); }, ), RaisedButton.icon( icon: Icon( Icons.restore_from_trash, color: Colors.green, ), shape: RoundedRectangleBorder( side: BorderSide(color: Colors.green), borderRadius: BorderRadius.all( Radius.circular(0), ), ), label: Text('EXCLUIR'), color: Colors.white, elevation: 0, onPressed: () { setState(() { pedidoItemController.remove(p); pedidoItemController.itens; }); // showSnackbar(context, "Produto ${p.produto.nome} removido"); Navigator.of(context).pop(); }, ), ], ); }, ); } } ======================= File: lib/src/core/controller/permissao_controller.dart ======================= import 'package:dio/dio.dart'; import 'package:mobx/mobx.dart'; import 'package:nosso/src/core/model/permissao.dart'; import 'package:nosso/src/core/repository/permissao_repository.dart'; part 'permissao_controller.g.dart'; class PermissaoController = PermissaoControllerBase with _$PermissaoController; abstract class PermissaoControllerBase with Store { PermissaoRepository permissaoRepository; PermissaoControllerBase() { permissaoRepository = PermissaoRepository(); } @observable List<Permissao> permissoes; @observable int permissao; @observable Exception error; @observable DioError dioError; @observable String mensagem; @action Future<List<Permissao>> getAll() async { try { permissoes = await permissaoRepository.getAll(); return permissoes; } catch (e) { error = e; } } @action Future<int> create(Permissao p) async { try { permissao = await permissaoRepository.create(p.toJson()); if (permissao == null) { mensagem = "sem dados"; } else { return permissao; } } on DioError catch (e) { mensagem = e.message; dioError = e; } } @action Future<int> update(int id, Permissao p) async { try { permissao = await permissaoRepository.update(id, p.toJson()); return permissao; } on DioError catch (e) { mensagem = e.message; dioError = e; } } } ======================= File: lib/src/paginas/promocao/promocao_detalhes_info.dart ======================= <reponame>ofertasbv/ofertaflutterweb import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; import 'package:nosso/src/core/model/promocao.dart'; class PromocaoDetalhesInfo extends StatefulWidget { Promocao p; PromocaoDetalhesInfo(this.p); @override _PromocaoDetalhesInfoState createState() => _PromocaoDetalhesInfoState(); } class _PromocaoDetalhesInfoState extends State<PromocaoDetalhesInfo> { Promocao p; @override Widget build(BuildContext context) { p = widget.p; return buildContainer(p); } buildContainer(Promocao p) { var dateFormat = DateFormat('dd/MM/yyyy HH:mm'); return ListView( children: [ Container( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Card( child: Container( padding: EdgeInsets.all(0), width: double.infinity, child: Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ ListTile( title: Text("Promoção"), subtitle: Text("${p.nome}"), trailing: Icon(Icons.check_outlined), leading: Icon(Icons.add_alert_outlined), ), Divider(), ListTile( title: Text("Descrição"), subtitle: Text("${p.descricao}"), trailing: Icon(Icons.check_outlined), leading: Icon(Icons.textsms_outlined), ), Divider(), ListTile( title: Text("Data Registro"), subtitle: Text("${dateFormat.format(p.dataRegistro)}"), trailing: Icon(Icons.check_outlined), leading: Icon(Icons.calendar_today_outlined), ), ListTile( title: Text("Loja"), subtitle: Text("${p.loja.nome}"), trailing: Icon(Icons.check_outlined), leading: Icon(Icons.local_convenience_store_outlined), ), ListTile( title: Text("Validade"), subtitle: Text( "${dateFormat.format(p.dataInicio)} até ${dateFormat.format(p.dataFinal)}"), trailing: Icon(Icons.check_outlined), leading: Icon(Icons.calendar_today_outlined), ), Divider(), ListTile( title: Text("Desconto"), subtitle: Text("R\$ ${p.desconto}"), trailing: Icon(Icons.check_outlined), leading: Icon(Icons.monetization_on_outlined), ), ], ), ), ), ], ), ), ], ); } } ======================= File: lib/src/core/controller/caixafluxo_controller.dart ======================= import 'package:dio/dio.dart'; import 'package:mobx/mobx.dart'; import 'package:nosso/src/core/model/caixafluxo.dart'; import 'package:nosso/src/core/repository/caixafluxo_repository.dart'; part 'caixafluxo_controller.g.dart'; class CaixafluxoController = CaixafluxoControllerBase with _$CaixafluxoController; abstract class CaixafluxoControllerBase with Store { CaixaFluxoRepository caixaFluxoRepository; CaixafluxoControllerBase() { caixaFluxoRepository = CaixaFluxoRepository(); } @observable List<CaixaFluxo> caixaFluxos; @observable int caixaFluxo; @observable Exception error; @observable DioError dioError; @observable String mensagem; @action Future<List<CaixaFluxo>> getAll() async { try { caixaFluxos = await caixaFluxoRepository.getAll(); return caixaFluxos; } catch (e) { error = e; } } @action Future<int> create(CaixaFluxo p) async { try { caixaFluxo = await caixaFluxoRepository.create(p.toJson()); if (caixaFluxo == null) { mensagem = "sem dados"; } else { return caixaFluxo; } } on DioError catch (e) { mensagem = e.message; dioError = e; } } @action Future<int> update(int id, CaixaFluxo p) async { try { caixaFluxo = await caixaFluxoRepository.update(id, p.toJson()); return caixaFluxo; } on DioError catch (e) { mensagem = e.message; dioError = e; } } } ======================= File: lib/src/paginas/produto/produto_list.dart ======================= import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_mobx/flutter_mobx.dart'; import 'package:get_it/get_it.dart'; import 'package:mobx/src/api/observable_collections.dart'; import 'package:nosso/src/core/controller/produto_controller.dart'; import 'package:nosso/src/core/model/content.dart'; import 'package:nosso/src/core/model/produto.dart'; import 'package:nosso/src/core/model/subcategoria.dart'; import 'package:nosso/src/paginas/produto/produto_detalhes_tab.dart'; import 'package:nosso/src/util/container/container_produto.dart'; import 'package:nosso/src/util/filter/produto_filter.dart'; import 'package:nosso/src/util/load/circular_progresso.dart'; class ProdutoList extends StatefulWidget { ProdutoFilter filter; ProdutoList({Key key, this.filter}) : super(key: key); @override _ProdutoListState createState() => _ProdutoListState(); } class _ProdutoListState extends State<ProdutoList> with AutomaticKeepAliveClientMixin<ProdutoList> { _ProdutoListState({this.filter}); var produtoController = GetIt.I.get<ProdutoController>(); SubCategoria s; ProdutoFilter filter; int size = 0; int page = 0; @override void initState() { super.initState(); } Future<void> onRefresh() { if (filter!= null) { produtoController.getFilter(filter, size, page); } else { return produtoController.getFilter(filter, size, page); } return null; } @override Widget build(BuildContext context) { return builderConteudoList(); } builderConteudoList() { return Container( padding: EdgeInsets.only(top: 0), child: Observer( builder: (context) { List<Produto> produtos = produtoController.produtos; if (produtoController.error!= null) { return Text("Não foi possível buscar produtos"); } if (produtos == null) { return CircularProgressor(); } return RefreshIndicator( onRefresh: onRefresh, child: builderListProduto(produtos), ); }, ), ); } builderListProduto(List<Produto> produtos) { double containerWidth = 250; double containerHeight = 20; return ListView.builder( scrollDirection: Axis.vertical, itemCount: produtos.length, itemBuilder: (context, index) { Produto p = produtos[index]; return GestureDetector( child: Padding( padding: EdgeInsets.symmetric(vertical: 0), child: ContainerProduto(produtoController, p), ), onTap: () { Navigator.of(context).push( MaterialPageRoute( builder: (BuildContext context) { return ProdutoDetalhesTab(p); }, ), ); }, ); }, ); } @override // TODO: implement wantKeepAlive bool get wantKeepAlive => true; } ======================= File: lib/src/paginas/pedidoitem/pedidoitem_page.dart ======================= <filename>lib/src/paginas/pedidoitem/pedidoitem_page.dart import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_mobx/flutter_mobx.dart'; import 'package:get_it/get_it.dart'; import 'package:nosso/src/core/controller/pedidoItem_controller.dart'; import 'package:nosso/src/paginas/pdv/caixa_pdv_page.dart'; import 'package:nosso/src/paginas/pedidoitem/pedidoitem_list.dart'; class PedidoItemPage extends StatelessWidget { var pedidoItemController = GetIt.I.get<PedidoItemController>(); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("Itens pedido"), actions: <Widget>[ Observer( builder: (context) { if (pedidoItemController.error!= null) { return Text("Não foi possível carregar"); } if (pedidoItemController.pedidoItens == null) { return Center( child: Icon(Icons.warning_amber_outlined), ); } return Chip( label: Text( (pedidoItemController.pedidoItens.length?? 0).toString(), ), ); }, ), SizedBox(width: 20), ], ), body: PedidoItemList(), floatingActionButton: FloatingActionButton( elevation: 10, child: Icon(Icons.add), onPressed: () { Navigator.push( context, MaterialPageRoute( builder: (context) { return CaixaPDVPage(); }, ), ); }, ), ); } } ======================= File: lib/src/core/repository/produto_repository.dart ======================= import 'dart:io'; import 'package:dio/dio.dart'; import 'package:nosso/src/api/constants/constant_api.dart'; import 'package:nosso/src/api/dio/custon_dio.dart'; import 'package:nosso/src/core/model/produto.dart'; import 'package:nosso/src/core/model/produtopage.dart'; import 'package:nosso/src/core/model/produtoprincipal.dart'; import 'package:nosso/src/util/filter/produto_filter.dart'; class ProdutoRepository { CustonDio dio = CustonDio(); Future<List<ProdutoPrincipal>> nextPageProduto() async { try { var response = await dio.client.get("/produtos"); return (response.data).map((c) => Produto.fromJson(c)).toList(); } on Exception catch (error) { print(error); return null; } } Future<List<Produto>> getAllById(int id) async { try { print("carregando produtos by id"); var response = await dio.client.get("/produtos/${id}"); print("resposta: ${response}"); return (response.data as List).map((c) => Produto.fromJson(c)).toList(); } on DioError catch (e) { print(e.message); } return null; } Future<List<Produto>> getAll() async { try { print("carregando produtos"); var response = await dio.client.get("/produtos"); return (response.data as List).map((c) => Produto.fromJson(c)).toList(); } on DioError catch (e) { print(e.message); } return null; } Future<ProdutoData> getAllPageable( ProdutoFilter filter, int size, int page) async { try { return dio.client .get( "/produtos?nomeProduto=${filter.nomeProduto}&size=${size}&page=${page}") .then((p) => ProdutoData.fromJson(p.data)); } on DioError catch (e) { print(e.message); } return null; } Future<List<Produto>> getFilter( ProdutoFilter filter, int size, int page) async { try { print("carregando produtos filtrados"); var response = await dio.client.get("/produtos"); return (response.data as List).map((c) => Produto.fromJson(c)).toList(); } on DioError catch (e) { print(e.message); } return null; } Future<List<Produto>> getAllBySubCategoriaById(int id) async { try { print("carregando produtos da subcategoria"); var response = await dio.client.get("/produtos/subcategoria/$id"); return (response.data as List).map((c) => Produto.fromJson(c)).toList(); } on DioError catch (e) { print(e.message); } return null; } Future<List<Produto>> getAllByLojaById(int id) async { try { print("carregando produtos da loja"); var response = await dio.client.get("/produtos/loja/$id"); return (response.data as List).map((c) => Produto.fromJson(c)).toList(); } on DioError catch (e) { print(e.message); } return null; } Future<Produto> getByCodBarra(String codigoBarra) async { try { print("carregando produtos by codigo de barra"); var response = await dio.client.get("/produtos/codigobarra/$codigoBarra"); return Produto.fromJson(response.data); } on DioError catch (e) { print(e.message); } return null; } Future<int> create(Map<String, dynamic> data) async { var response = await dio.client.post("/produtos/create", data: data); return response.statusCode; } Future<int> update(int id, Map<String, dynamic> data) async { var response = await dio.client.put("/produtos/update/$id", data: data); return response.statusCode; } Future<void> deleteFoto(String foto) async { try { var response = await dio.client.delete("/produtos/delete/foto/$foto"); return response.statusCode; } on DioError catch (e) { throw (e.message); } } Future<String> upload(File file, String fileName) async { var arquivo = file.path; var paramentros = { "foto": await MultipartFile.fromFile(arquivo, filename: fileName) }; FormData formData = FormData.fromMap(paramentros); var response = await dio.client .post(ConstantApi.urlList + "/produtos/upload", data: formData); return response.toString(); } } ======================= File: lib/src/util/container/container_produto.dart ======================= <filename>lib/src/util/container/container_produto.dart import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; import 'package:nosso/src/core/controller/produto_controller.dart'; import 'package:nosso/src/core/model/content.dart'; import 'package:nosso/src/core/model/produto.dart'; import 'package:nosso/src/paginas/produto/produto_create_page.dart'; class ContainerProduto extends StatelessWidget { ProdutoController produtoController; Produto p; ContainerProduto(this.produtoController, this.p); @override Widget build(BuildContext context) { var formatMoeda = new NumberFormat("#,##0.00", "pt_BR"); return Card( shape: RoundedRectangleBorder( borderRadius: new BorderRadius.circular(10), side: BorderSide(color: Colors.grey[200], width: 1), ), child: AnimatedContainer( width: 350, height: 150, duration: Duration(seconds: 1), decoration: BoxDecoration( gradient: LinearGradient( colors: [ Colors.grey[100].withOpacity(0.1), Colors.grey[100].withOpacity(0.4), ], begin: Alignment.topLeft, end: Alignment.bottomRight, ), border: Border.all(color: Colors.transparent), borderRadius: BorderRadius.circular(10), ), child: Row( crossAxisAlignment: CrossAxisAlignment.stretch, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Container( decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(10), ), child: Stack( alignment: Alignment.bottomRight, children: [ ClipRRect( borderRadius: BorderRadius.circular(10), child: Image.network( produtoController.arquivo + p.foto, fit: BoxFit.cover, width: 100, height: 150, ), ), Padding( padding: EdgeInsets.zero, child: Align( alignment: Alignment.bottomRight, child: p.novo == true ? Chip( label: Text( "novo", style: TextStyle( fontSize: 10, color: Colors.redAccent, fontWeight: FontWeight.w500, ), ), ) : Chip( label: Text( "atual", style: TextStyle( fontSize: 10, color: Colors.redAccent, fontWeight: FontWeight.w500, ), ), ), ), ), ], ), ), Expanded( child: Container( width: double.infinity, color: Colors.transparent, child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Container( child: ListTile( title: Text( "${p.nome}", overflow: TextOverflow.ellipsis, ), subtitle: Text("Código. ${p.id}"), trailing: CircleAvatar( backgroundColor: Colors.grey[300], foregroundColor: Colors.redAccent, child: IconButton( splashColor: Colors.black, icon: Icon( Icons.favorite_border, color: Colors.redAccent, size: 15, ), onPressed: () {}, ), ), ), ), Container( child: ListTile( title: Text( "R\$ ${formatMoeda.format(p.estoque.valorUnitario)}", style: TextStyle( fontSize: 15, color: Colors.grey, fontWeight: FontWeight.w500, decoration: TextDecoration.lineThrough, decorationStyle: TextDecorationStyle.dashed, ), ), subtitle: Text( "R\$ ${formatMoeda.format(p.estoque.valorUnitario - ((p.estoque.valorUnitario * p.promocao.desconto) / 100))} a vista", style: TextStyle( fontSize: 16, color: Colors.green, fontWeight: FontWeight.bold, ), ), trailing: buildPopupMenuButton(context, p), ), ), ], ), ), ), ], ), ), ); } PopupMenuButton<String> buildPopupMenuButton( BuildContext context, Produto p) { return PopupMenuButton<String>( padding: EdgeInsets.zero, enabled: true, elevation: 1, icon: Icon(Icons.more_vert), onSelected: (valor) { if (valor == "novo") { print("novo"); Navigator.of(context).push( MaterialPageRoute( builder: (BuildContext context) { return ProdutoCreatePage(); }, ), ); } if (valor == "editar") { print("editar"); Navigator.of(context).push( MaterialPageRoute( builder: (BuildContext context) { return ProdutoCreatePage( produto: p, ); }, ), ); } if (valor == "delete") { print("delete"); } }, itemBuilder: (BuildContext context) => <PopupMenuEntry<String>>[ const PopupMenuItem<String>( value: 'novo', child: ListTile( leading: Icon(Icons.add), title: Text('novo'), ), ), const PopupMenuItem<String>( value: 'editar', child: ListTile( leading: Icon(Icons.edit), title: Text('editar'), ), ), const PopupMenuItem<String>( value: 'delete', child: ListTile( leading: Icon(Icons.delete), title: Text('Delete'), ), ) ], ); } } ======================= File: lib/src/core/controller/categoria_controller.g.dart ======================= // GENERATED CODE - DO NOT MODIFY BY HAND part of 'categoria_controller.dart'; // ************************************************************************** // StoreGenerator // ************************************************************************** // ignore_for_file: non_constant_identifier_names, unnecessary_brace_in_string_interps, unnecessary_lambdas, prefer_expression_function_bodies, lines_longer_than_80_chars, avoid_as, avoid_annotating_with_dynamic mixin _$CategoriaController on CategoriaControllerBase, Store { final _$categoriasAtom = Atom(name: 'CategoriaControllerBase.categorias'); @override List<Categoria> get categorias { _$categoriasAtom.reportRead(); return super.categorias; } @override set categorias(List<Categoria> value) { _$categoriasAtom.reportWrite(value, super.categorias, () { super.categorias = value; }); } final _$categoriaAtom = Atom(name: 'CategoriaControllerBase.categoria'); @override int get categoria { _$categoriaAtom.reportRead(); return super.categoria; } @override set categoria(int value) { _$categoriaAtom.reportWrite(value, super.categoria, () { super.categoria = value; }); } final _$formDataAtom = Atom(name: 'CategoriaControllerBase.formData'); @override dynamic get formData { _$formDataAtom.reportRead(); return super.formData; } @override set formData(dynamic value) { _$formDataAtom.reportWrite(value, super.formData, () { super.formData = value; }); } final _$errorAtom = Atom(name: 'CategoriaControllerBase.error'); @override Exception get error { _$errorAtom.reportRead(); return super.error; } @override set error(Exception value) { _$errorAtom.reportWrite(value, super.error, () { super.error = value; }); } final _$dioErrorAtom = Atom(name: 'CategoriaControllerBase.dioError'); @override DioError get dioError { _$dioErrorAtom.reportRead(); return super.dioError; } @override set dioError(DioError value) { _$dioErrorAtom.reportWrite(value, super.dioError, () { super.dioError = value; }); } final _$mensagemAtom = Atom(name: 'CategoriaControllerBase.mensagem'); @override String get mensagem { _$mensagemAtom.reportRead(); return super.mensagem; } @override set mensagem(String value) { _$mensagemAtom.reportWrite(value, super.mensagem, () { super.mensagem = value; }); } final _$categoriaSelecionadaAtom = Atom(name: 'CategoriaControllerBase.categoriaSelecionada'); @override Categoria get categoriaSelecionada { _$categoriaSelecionadaAtom.reportRead(); return super.categoriaSelecionada; } @override set categoriaSelecionada(Categoria value) { _$categoriaSelecionadaAtom.reportWrite(value, super.categoriaSelecionada, () { super.categoriaSelecionada = value; }); } final _$arquivoAtom = Atom(name: 'CategoriaControllerBase.arquivo'); @override String get arquivo { _$arquivoAtom.reportRead(); return super.arquivo; } @override set arquivo(String value) { _$arquivoAtom.reportWrite(value, super.arquivo, () { super.arquivo = value; }); } final _$getAllAsyncAction = AsyncAction('CategoriaControllerBase.getAll'); @override Future<List<Categoria>> getAll() { return _$getAllAsyncAction.run(() => super.getAll()); } final _$getAllByNomeAsyncAction = AsyncAction('CategoriaControllerBase.getAllByNome'); @override Future<List<Categoria>> getAllByNome(String nome) { return _$getAllByNomeAsyncAction.run(() => super.getAllByNome(nome)); } final _$createAsyncAction = AsyncAction('CategoriaControllerBase.create'); @override Future<int> create(Categoria p) { return _$createAsyncAction.run(() => super.create(p)); } final _$updateAsyncAction = AsyncAction('CategoriaControllerBase.update'); @override Future<int> update(int id, Categoria p) { return _$updateAsyncAction.run(() => super.update(id, p)); } final _$uploadAsyncAction = AsyncAction('CategoriaControllerBase.upload'); @override Future<String> upload(File foto, String fileName) { return _$uploadAsyncAction.run(() => super.upload(foto, fileName)); } final _$deleteFotoAsyncAction = AsyncAction('CategoriaControllerBase.deleteFoto'); @override Future<void> deleteFoto(String foto) { return _$deleteFotoAsyncAction.run(() => super.deleteFoto(foto)); } @override String toString() { return ''' categorias: ${categorias}, categoria: ${categoria}, formData: ${formData}, error: ${error}, dioError: ${dioError}, mensagem: ${mensagem}, categoriaSelecionada: ${categoriaSelecionada}, arquivo: ${arquivo} '''; } } ======================= File: lib/src/paginas/usuario/usuario_perfil_loja.dart ======================= <reponame>ofertasbv/ofertaflutterweb import 'dart:io'; import 'package:flutter/material.dart'; import 'package:get_it/get_it.dart'; import 'package:nosso/src/core/controller/loja_controller.dart'; import 'package:nosso/src/core/controller/usuario_controller.dart'; import 'package:nosso/src/core/model/loja.dart'; import 'package:nosso/src/core/model/uploadFileResponse.dart'; import 'package:nosso/src/paginas/endereco/endereco_loja_page.dart'; import 'package:nosso/src/paginas/loja/loja_produto_page.dart'; import 'package:nosso/src/paginas/loja/loja_promocao_page.dart'; import 'package:nosso/src/paginas/usuario/usuario_create_page.dart'; import 'package:nosso/src/paginas/usuario/usuario_edit_loja.dart'; import 'package:nosso/src/util/upload/upload_response.dart'; class UsuarioPerfilLoja extends StatefulWidget { Loja loja; UsuarioPerfilLoja({Key key, this.loja}) : super(key: key); @override _UsuarioPerfilLojaState createState() => _UsuarioPerfilLojaState(p: this.loja); } class _UsuarioPerfilLojaState extends State<UsuarioPerfilLoja> { _UsuarioPerfilLojaState({this.p}); var usuarioController = GetIt.I.get<UsuarioController>(); var lojaController = GetIt.I.get<LojaController>(); var uploadFileResponse = UploadFileResponse(); var response = UploadRespnse(); var scaffoldKey = GlobalKey<ScaffoldState>(); Loja p; File file; bool isEnabledEnviar = false; bool isEnabledDelete = false; @override void initState() { if (p == null) { p = Loja(); } super.initState(); } enableButton() { setState(() { isEnabledEnviar = true; }); } disableButton() { setState(() { isEnabledDelete = true; }); } onClickUpload() async { if (file!= null) { var url = await lojaController.upload(file, p.foto); print("url: ${url}"); print("========= UPLOAD FILE RESPONSE ========= "); uploadFileResponse = response.response(uploadFileResponse, url); print("fileName: ${uploadFileResponse.fileName}"); print("fileDownloadUri: ${uploadFileResponse.fileDownloadUri}"); print("fileType: ${uploadFileResponse.fileType}"); print("size: ${uploadFileResponse.size}"); p.foto = uploadFileResponse.fileName; setState(() { uploadFileResponse; }); showSnackbar(context, "Arquivo anexada com sucesso!"); } } showSnackbar(BuildContext context, String content) { scaffoldKey.currentState.showSnackBar( SnackBar( content: Text(content), action: SnackBarAction( label: "OK", onPressed: () {}, ), ), ); } @override Widget build(BuildContext context) { return ListView( children: [ Container( height: 150, color: Theme.of(context).primaryColor, child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Container( padding: EdgeInsets.all(1), decoration: new BoxDecoration( gradient: LinearGradient( colors: [Theme.of(context).primaryColor, Theme.of(context).primaryColor], ), border: Border.all( color: Colors.black, width: 1, ), borderRadius: BorderRadius.circular(50), ), child: GestureDetector( onTap: () { // openBottomSheet(context); }, child: CircleAvatar( backgroundColor: Colors.grey[100], radius: 30, child: file!= null ? Image.file( file, fit: BoxFit.fitWidth, width: double.infinity, height: 300, ) : usuarioController.usuarioSelecionado.pessoa.foto!= null ? CircleAvatar( radius: 50, backgroundImage: NetworkImage( lojaController.arquivo + usuarioController.usuarioSelecionado.pessoa.foto, ), ) : CircleAvatar( radius: 50, child: Icon( Icons.camera_alt_outlined, ), ), ), ), ), SizedBox(height: 0), Container( alignment: Alignment.center, padding: EdgeInsets.all(2), height: 30, child: Text( "${usuarioController.usuarioSelecionado.pessoa.nome}", style: TextStyle( color: Colors.grey[100], ), ), ), Container( alignment: Alignment.center, padding: EdgeInsets.all(2), height: 30, child: Text( "${usuarioController.usuarioSelecionado.pessoa.tipoPessoa}", style: TextStyle( color: Colors.grey[100], ), ), ), ], ), ), Container( height: 600, child: Column( mainAxisAlignment: MainAxisAlignment.spaceAround, crossAxisAlignment: CrossAxisAlignment.center, children: [ ListTile( title: Text("Cupom de desconto"), subtitle: Text("Adicionar cupom de desconto"), leading: CircleAvatar( child: Icon(Icons.games_outlined), ), onTap: () { Navigator.of(context).push( MaterialPageRoute( builder: (BuildContext context) { return UsuarioCreatePage(); }, ), ); }, ), ListTile( title: Text("Meus produtos"), subtitle: Text("Todos os seus produtos"), leading: CircleAvatar( child: Icon(Icons.shopping_basket_outlined), ), onTap: () { Navigator.of(context).push( MaterialPageRoute( builder: (BuildContext context) { return LojaProdutoPage(); }, ), ); }, ), ListTile( title: Text("Minhas ofertas"), subtitle: Text("Todas as suas ofertas"), leading: CircleAvatar( child: Icon(Icons.add_alert_outlined), ), onTap: () { Navigator.of(context).push( MaterialPageRoute( builder: (BuildContext context) { return LojaPromocaoPage(); }, ), ); }, ), ListTile( title: Text("Dados Comerciais"), subtitle: Text("Alterar senha, login, email, e dados comerciais"), leading: CircleAvatar( child: Icon(Icons.account_circle_outlined), ), onTap: () { Navigator.of(context).push( MaterialPageRoute( builder: (BuildContext context) { return UsuarioEditLoja(); }, ), ); }, ), ListTile( title: Text("Minhas avaliações"), subtitle: Text("Suas opiniões dos produtos de desejo"), leading: CircleAvatar( child: Icon(Icons.star_border), ), onTap: () { Navigator.of(context).push( MaterialPageRoute( builder: (BuildContext context) { return UsuarioCreatePage(); }, ), ); }, ), ListTile( title: Text("Endereço de loja"), subtitle: Text("Altere seu endereço"), leading: CircleAvatar( child: Icon(Icons.location_on_outlined), ), onTap: () { Navigator.of(context).push( MaterialPageRoute( builder: (BuildContext context) { return EnderecoLojaPage(); }, ), ); }, ), ListTile( title: Text("Atedimento ao cliente"), subtitle: Text("Adicionar atendimento por e-mail"), leading: CircleAvatar( child: Icon(Icons.email_outlined), ), onTap: () { Navigator.of(context).push( MaterialPageRoute( builder: (BuildContext context) { return UsuarioCreatePage(); }, ), ); }, ), ListTile( title: Text("Sair"), subtitle: Text("Acesse com outra conta"), leading: CircleAvatar( child: Icon(Icons.logout), ), onTap: () { Navigator.of(context).push( MaterialPageRoute( builder: (BuildContext context) { return UsuarioCreatePage(); }, ), ); }, ), ], ), ), ], ); } } ======================= File: lib/src/paginas/endereco/endereco_search.dart ======================= import 'package:flutter/material.dart'; import 'package:flutter_mobx/flutter_mobx.dart'; import 'package:get_it/get_it.dart'; import 'package:nosso/src/core/controller/endereco_controller.dart'; import 'package:nosso/src/core/model/endereco.dart'; import 'package:nosso/src/core/model/produto.dart'; import 'package:nosso/src/util/load/circular_progresso.dart'; class EnderecoSearchDelegate extends SearchDelegate<Produto> { var enderecoController = GetIt.I.get<EnderecoController>(); @override List<Widget> buildActions(BuildContext context) { return [ IconButton( icon: Icon(Icons.clear), onPressed: () { query = ""; }, ), ]; } @override Widget buildLeading(BuildContext context) { return IconButton( icon: AnimatedIcon( icon: AnimatedIcons.menu_arrow, progress: transitionAnimation, ), onPressed: () { close(context, null); }, autofocus: true, ); } @override Widget buildResults(BuildContext context) { return Text(query); } @override Widget buildSuggestions(BuildContext context) { enderecoController.getAll(); return Observer( builder: (context) { List<Endereco> enderecos = enderecoController.enderecos; if (enderecoController.error!= null) { return Text("Não foi possível buscar endereços"); } if (enderecoController == null) { return CircularProgressor(); } final resultados = query.isEmpty ? [] : enderecos .where((p) => p.logradouro.toLowerCase().startsWith(query.toLowerCase())) .toList(); if (resultados.length == 0) { return Center( child: Text("pesquisar endereço"), ); } return ListView.builder( itemBuilder: (context, index) { Endereco e = resultados[index]; return ListTile( leading: CircleAvatar( backgroundColor: Colors.grey[200], maxRadius: 25, minRadius: 25, child: Icon(Icons.location_on_outlined), ), title: RichText( text: TextSpan( text: e.logradouro.substring(0, query.length), style: TextStyle( color: Colors.black, fontWeight: FontWeight.bold, ), children: [ TextSpan( text: e.logradouro.substring(query.length) + ", " + e.numero + " - " + e.complemento, style: TextStyle(color: Colors.grey)) ], ), ), onTap: () { enderecoController.enderecoSelecionado = e; Navigator.of(context).pop(); }, ); }, itemCount: resultados.length, ); }, ); } } ======================= File: lib/src/util/validador/validador_login.dart ======================= <gh_stars>0 import 'dart:async'; class LoginValidators { String validateEmail(String text) { if (text.isEmpty) { return "preencha o valor com email"; } if (!text.contains("@")) { return "email inválido"; } } String validateSenha(String text) { if (text.isEmpty) { return "preencha o valor com senha"; } if (text.length < 4) { return "a senha deve ter 4 caracteres"; } } final validatePassword = StreamTransformer<String, String>.fromHandlers( handleData: (password, sink) { if (password.length > 4) { sink.add(password); } else { sink.addError("Senha inválida, deve conter pelo menos 4 caracteres"); } }, ); } ======================= File: lib/src/util/dialogs/dialog_categoria.dart ======================= import 'package:flutter/material.dart'; import 'package:flutter_mobx/flutter_mobx.dart'; import 'package:get_it/get_it.dart'; import 'package:nosso/src/core/controller/categoria_controller.dart'; import 'package:nosso/src/core/model/categoria.dart'; import 'package:nosso/src/util/load/circular_progresso_mini.dart'; class DialogCategoria extends StatefulWidget { Categoria categoria; DialogCategoria(this.categoria); @override _DialogCategoriaState createState() => _DialogCategoriaState(this.categoria); } class _DialogCategoriaState extends State<DialogCategoria> { _DialogCategoriaState(this.categoria); var categoriaController = GetIt.I.get<CategoriaController>(); Categoria categoria; @override void initState() { categoriaController.getAll(); super.initState(); } @override Widget build(BuildContext context) { return builderConteudoListSubCategorias(); } builderConteudoListSubCategorias() { return Container( padding: EdgeInsets.only(top: 0), child: Observer( builder: (context) { List<Categoria> categorias = categoriaController.categorias; if (categoriaController.error!= null) { return Text("Não foi possível carregados dados"); } if (categorias == null) { return CircularProgressorMini(); } return builderListCategorias(categorias); }, ), ); } builderListCategorias(List<Categoria> categorias) { double containerWidth = 160; double containerHeight = 20; return ListView.builder( itemCount: categorias.length, itemBuilder: (context, index) { Categoria c = categorias[index]; return Column( children: [ GestureDetector( child: ListTile( leading: Container( padding: EdgeInsets.all(1), decoration: new BoxDecoration( gradient: LinearGradient( colors: [Colors.purple, Colors.grey[900]], ), border: Border.all( color: Colors.black, width: 1, ), borderRadius: BorderRadius.circular(35), ), child: c.foto!= null ? CircleAvatar( backgroundColor: Colors.grey[100], radius: 20, backgroundImage: NetworkImage( "${categoriaController.arquivo + c.foto}", ), ) : CircleAvatar(), ), title: Text(c.nome), ), onTap: () { categoriaController.categoriaSelecionada = c; print( "Categoria: ${categoriaController.categoriaSelecionada.nome}"); Navigator.of(context).pop(); }, ), Divider() ], ); }, ); } } class AlertCategoria { alert(BuildContext context, Categoria categoria) { return showDialog( context: context, builder: (BuildContext context) { return AlertDialog( shape: RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(32.0))), contentPadding: EdgeInsets.only(top: 10.0), content: Container( width: 300.0, child: DialogCategoria(categoria), ), actions: [ FlatButton( onPressed: () { Navigator.pop(context); }, child: Text("ok"), ) ], ); }, ); } } ======================= File: lib/src/core/controller/favorito_controller.g.dart ======================= <filename>lib/src/core/controller/favorito_controller.g.dart // GENERATED CODE - DO NOT MODIFY BY HAND part of 'favorito_controller.dart'; // ************************************************************************** // StoreGenerator // ************************************************************************** // ignore_for_file: non_constant_identifier_names, unnecessary_brace_in_string_interps, unnecessary_lambdas, prefer_expression_function_bodies, lines_longer_than_80_chars, avoid_as, avoid_annotating_with_dynamic mixin _$FavoritoController on FavoritoControllerBase, Store { final _$favoritosAtom = Atom(name: 'FavoritoControllerBase.favoritos'); @override List<Favorito> get favoritos { _$favoritosAtom.reportRead(); return super.favoritos; } @override set favoritos(List<Favorito> value) { _$favoritosAtom.reportWrite(value, super.favoritos, () { super.favoritos = value; }); } final _$favoritoAtom = Atom(name: 'FavoritoControllerBase.favorito'); @override int get favorito { _$favoritoAtom.reportRead(); return super.favorito; } @override set favorito(int value) { _$favoritoAtom.reportWrite(value, super.favorito, () { super.favorito = value; }); } final _$errorAtom = Atom(name: 'FavoritoControllerBase.error'); @override Exception get error { _$errorAtom.reportRead(); return super.error; } @override set error(Exception value) { _$errorAtom.reportWrite(value, super.error, () { super.error = value; }); } final _$dioErrorAtom = Atom(name: 'FavoritoControllerBase.dioError'); @override DioError get dioError { _$dioErrorAtom.reportRead(); return super.dioError; } @override set dioError(DioError value) { _$dioErrorAtom.reportWrite(value, super.dioError, () { super.dioError = value; }); } final _$mensagemAtom = Atom(name: 'FavoritoControllerBase.mensagem'); @override String get mensagem { _$mensagemAtom.reportRead(); return super.mensagem; } @override set mensagem(String value) { _$mensagemAtom.reportWrite(value, super.mensagem, () { super.mensagem = value; }); } final _$getAllAsyncAction = AsyncAction('FavoritoControllerBase.getAll'); @override Future<List<Favorito>> getAll() { return _$getAllAsyncAction.run(() => super.getAll()); } final _$createAsyncAction = AsyncAction('FavoritoControllerBase.create'); @override Future<int> create(Favorito p) { return _$createAsyncAction.run(() => super.create(p)); } final _$updateAsyncAction = AsyncAction('FavoritoControllerBase.update'); @override Future<int> update(int id, Favorito p) { return _$updateAsyncAction.run(() => super.update(id, p)); } @override String toString() { return ''' favoritos: ${favoritos}, favorito: ${favorito}, error: ${error}, dioError: ${dioError}, mensagem: ${mensagem} '''; } } ======================= File: lib/src/paginas/produto/produto_create_page.dart ======================= import 'dart:async'; import 'dart:io'; import 'package:barcode_scan/barcode_scan.dart'; import 'package:datetime_picker_formfield/datetime_picker_formfield.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_mobx/flutter_mobx.dart'; import 'package:fluttertoast/fluttertoast.dart'; import 'package:get_it/get_it.dart'; import 'package:intl/intl.dart'; import 'package:nosso/src/core/controller/cor_controller.dart'; import 'package:nosso/src/core/controller/marca_controller.dart'; import 'package:nosso/src/core/controller/promocao_controller.dart'; import 'package:nosso/src/core/controller/subcategoria_controller.dart'; import 'package:nosso/src/core/controller/loja_controller.dart'; import 'package:nosso/src/core/controller/produto_controller.dart'; import 'package:nosso/src/core/controller/tamanho_controller.dart'; import 'package:nosso/src/core/model/arquivo.dart'; import 'package:nosso/src/core/model/cor.dart'; import 'package:nosso/src/core/model/estoque.dart'; import 'package:nosso/src/core/model/loja.dart'; import 'package:nosso/src/core/model/marca.dart'; import 'package:nosso/src/core/model/produto.dart'; import 'package:nosso/src/core/model/promocao.dart'; import 'package:nosso/src/core/model/subcategoria.dart'; import 'package:nosso/src/core/model/tamanho.dart'; import 'package:nosso/src/core/model/uploadFileResponse.dart'; import 'package:nosso/src/paginas/produto/produto_tab.dart'; import 'package:nosso/src/util/componentes/image_source_sheet.dart'; import 'package:nosso/src/util/dialogs/dialogs.dart'; import 'package:nosso/src/util/dropdown/dropdown_cor.dart'; import 'package:nosso/src/util/dropdown/dropdown_loja.dart'; import 'package:nosso/src/util/dropdown/dropdown_marca.dart'; import 'package:nosso/src/util/dropdown/dropdown_promocao.dart'; import 'package:nosso/src/util/dropdown/dropdown_subcategoria.dart'; import 'package:nosso/src/util/dropdown/dropdown_tamanho.dart'; import 'package:nosso/src/util/upload/upload_response.dart'; import 'package:nosso/src/util/validador/validador_produto.dart'; class ProdutoCreatePage extends StatefulWidget { Produto produto; ProdutoCreatePage({Key key, this.produto}) : super(key: key); @override _ProdutoCreatePageState createState() => _ProdutoCreatePageState(p: this.produto); } class _ProdutoCreatePageState extends State<ProdutoCreatePage> with ValidadorProduto { _ProdutoCreatePageState({this.p}); var produtoController = GetIt.I.get<ProdutoController>(); var subCategoriaController = GetIt.I.get<SubCategoriaController>(); var lojaController = GetIt.I.get<LojaController>(); var marcaController = GetIt.I.get<MarcaController>(); var promocaoController = GetIt.I.get<PromoCaoController>(); var tamanhoController = GetIt.I.get<TamanhoController>(); var corController = GetIt.I.get<CorController>(); Dialogs dialogs = Dialogs(); final scaffoldKey = GlobalKey<ScaffoldState>(); Future<List<SubCategoria>> subCategorias; Future<List<Marca>> marcas; Future<List<Promocao>> promocoes; Future<List<Loja>> lojas; List<Arquivo> arquivoSelecionados = List(); Produto p; Estoque e; SubCategoria subCategoriaSelecionada; Loja lojaSelecionada; Promocao promocaoSelecionada; Marca marcaSelecionada; List<Cor> coreSelecionados; List<Tamanho> tamanhoSelecionados; Controller controller; var controllerCodigoBarra = TextEditingController(); var controllerQuantidade = TextEditingController(); var controllerValorUnitario = TextEditingController(); var controllerDesconto = TextEditingController(); var controllerPecentual = TextEditingController(); var controllerValorVenda = TextEditingController(); var uploadFileResponse = UploadFileResponse(); var response = UploadRespnse(); String barcode = ""; bool novo; bool status; bool destaque; double desconto; double valor; int quantidade; String medida; String tamanho; String origem; File file; @override void initState() { if (p == null) { p = Produto(); e = Estoque(); novo = false; status = false; destaque = false; medida = "UNIDADE"; origem = "NACIONAL"; } else { novo = p.novo; status = p.status; destaque = p.destaque; e = p.estoque; lojaController.lojaSelecionada = p.loja; subCategoriaController.subCategoriaSelecionada = p.subCategoria; marcaController.marcaSelecionada = p.marca; promocaoController.promocaoSelecionada = p.promocao; // produtoController.corSelecionadas = p.cores; // produtoController.tamanhoSelecionados = p.tamanhos; controllerQuantidade.text = p.estoque.quantidade.toStringAsFixed(0); controllerValorUnitario.text = p.estoque.valorUnitario.toStringAsFixed(2); controllerValorVenda.text = p.estoque.valorVenda.toStringAsFixed(2); controllerPecentual.text = p.estoque.percentual.toStringAsFixed(2); } produtoController.getAll(); super.initState(); } @override void didChangeDependencies() { controller = Controller(); super.didChangeDependencies(); } executar(String nomeAudio) {} barcodeScanning() async { try { String barcode = await BarcodeScanner.scan(); setState(() { executar("beep-07"); this.barcode = barcode; controllerCodigoBarra.text = this.barcode; }); } on FormatException { setState(() => this.barcode = 'Nada capturado.'); } catch (e) { setState(() => this.barcode = 'Erros: $e'); } } bool isEnabledEnviar = false; bool isEnabledDelete = false; enableButton() { setState(() { isEnabledEnviar = true; }); } disableButton() { setState(() { isEnabledDelete = true; }); } onClickUpload() async { if (file!= null) { var url = await promocaoController.upload(file, p.foto); print("url: ${url}"); print("========= UPLOAD FILE RESPONSE ========= "); uploadFileResponse = response.response(uploadFileResponse, url); print("fileName: ${uploadFileResponse.fileName}"); print("fileDownloadUri: ${uploadFileResponse.fileDownloadUri}"); print("fileType: ${uploadFileResponse.fileType}"); print("size: ${uploadFileResponse.size}"); p.foto = uploadFileResponse.fileName; setState(() { uploadFileResponse; }); showSnackbar(context, "Arquivo anexada com sucesso!"); } } showToast(String cardTitle) { Fluttertoast.showToast( msg: "$cardTitle", gravity: ToastGravity.CENTER, timeInSecForIos: 10, fontSize: 16.0, ); } showSnackbar(BuildContext context, String content) { scaffoldKey.currentState.showSnackBar( SnackBar( content: Text(content), action: SnackBarAction( label: "OK", onPressed: () {}, ), ), ); } calcularValorVenda() { double valor = (double.tryParse(controllerValorUnitario.text) * double.tryParse(controllerPecentual.text)) / 100; controllerValorVenda.text = valor.toStringAsFixed(2); } @override Widget build(BuildContext context) { return Scaffold( key: scaffoldKey, appBar: AppBar( title: p.nome == null? Text("Cadastro de produtos") : Text(p.nome), ), body: Observer( builder: (context) { if (produtoController.dioError == null) { return buildListViewForm(context); } else { print("Erro: ${produtoController.mensagem}"); showToast("${produtoController.mensagem}"); return buildListViewForm(context); } }, ), ); } buildListViewForm(BuildContext context) { var focus = FocusScope.of(context); var dateFormat = DateFormat('dd/MM/yyyy'); var formatter = NumberFormat("00.00"); var formata = new NumberFormat("#,##0.00", "pt_BR"); p.estoque = e; p.loja = lojaController.lojaSelecionada; p.subCategoria = subCategoriaController.subCategoriaSelecionada; p.marca = marcaController.marcaSelecionada; p.promocao = promocaoController.promocaoSelecionada; // p.tamanhos = produtoController.tamanhoSelecionados; // p.cores = produtoController.corSelecionadas; return ListView( children: <Widget>[ Container( padding: EdgeInsets.all(0), child: Form( key: controller.formKey, child: Column( mainAxisAlignment: MainAxisAlignment.start, mainAxisSize: MainAxisSize.max, crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Container( height: 350, color: Colors.grey[400], child: GestureDetector( onTap: () { showModalBottomSheet( context: context, builder: (context) => ImageSourceSheet( onImageSelected: (image) { setState(() { Navigator.of(context).pop(); file = image; String arquivo = file.path.split('/').last; print("Image: ${arquivo}"); enableButton(); }); }, ), ); }, child: Container( color: Colors.grey[600], padding: EdgeInsets.all(5), child: Container( width: double.infinity, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ file!= null ? Image.file( file, fit: BoxFit.fitWidth, width: double.infinity, height: 340, ) : p.foto!= null ? CircleAvatar( radius: 50, backgroundImage: NetworkImage( produtoController.arquivo + p.foto, ), ) : CircleAvatar( radius: 50, child: Icon( Icons.camera_alt_outlined, ), ), ], ), ), ), ), ), Container( padding: EdgeInsets.all(5), color: Colors.grey[300], child: Column( children: <Widget>[ Container( padding: EdgeInsets.all(10), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ RaisedButton( child: Icon(Icons.delete_forever), shape: new CircleBorder(), onPressed: isEnabledDelete ? () => produtoController.deleteFoto(p.foto) : null, ), RaisedButton( child: Icon(Icons.photo), shape: new CircleBorder(), onPressed: () { showModalBottomSheet( context: context, builder: (context) => ImageSourceSheet( onImageSelected: (image) { setState(() { Navigator.of(context).pop(); file = image; String arquivo = file.path.split('/').last; print("Image: ${arquivo}"); enableButton(); }); }, ), ); }, ), RaisedButton( child: Icon(Icons.check), shape: new CircleBorder(), onPressed: isEnabledEnviar ? () => onClickUpload() : null, ) ], ), ), ], ), ), ExpansionTile( title: Text("Descrição"), children: [ uploadFileResponse.fileName!= null ? Container( height: 400, padding: EdgeInsets.all(5), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( child: ListTile( title: Text("fileName"), subtitle: Text("${uploadFileResponse.fileName}"), ), ), Container( child: ListTile( title: Text("fileDownloadUri"), subtitle: Text( "${uploadFileResponse.fileDownloadUri}"), ), ), Container( child: ListTile( title: Text("fileType"), subtitle: Text("${uploadFileResponse.fileType}"), ), ), Container( child: ListTile( title: Text("size"), subtitle: Text("${uploadFileResponse.size}"), ), ), ], ), ) : Container( padding: EdgeInsets.all(15), child: Text("Deve anexar uma foto"), alignment: Alignment.bottomLeft, ), ], ), SizedBox(height: 10), Container( padding: EdgeInsets.all(15), width: double.maxFinite, child: Column( crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ TextFormField( initialValue: p.codigoBarra, controller: p.codigoBarra == null ? controllerCodigoBarra : null, onSaved: (value) => p.codigoBarra = value, validator: validateCodigoBarra, decoration: InputDecoration( prefixIcon: Icon( Icons.camera_alt_outlined, color: Colors.grey, ), suffixIcon: IconButton( onPressed: () => controllerCodigoBarra.clear(), icon: Icon(Icons.clear), ), labelText: "Entre com código de barra ou clique (scanner)", hintText: "Código de barra", contentPadding: EdgeInsets.fromLTRB(20.0, 20.0, 20.0, 20.0), border: OutlineInputBorder( borderRadius: BorderRadius.circular(5.0), ), focusedBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.purple[900]), gapPadding: 1, borderRadius: BorderRadius.circular(5.0), ), ), onEditingComplete: () => focus.nextFocus(), keyboardType: TextInputType.text, maxLength: 20, ), SizedBox(height: 10), RaisedButton.icon( elevation: 0.0, icon: Icon(Icons.photo_camera_outlined), shape: RoundedRectangleBorder( borderRadius: new BorderRadius.circular(30), side: BorderSide(color: Colors.transparent), ), label: Text("Scanner"), onPressed: () { barcodeScanning(); }, ), ], ), ), /* ================ Cadastro produto ================ */ SizedBox(height: 0), Container( padding: EdgeInsets.all(15), child: Column( children: <Widget>[ TextFormField( initialValue: p.nome, onSaved: (value) => p.nome = value, validator: validateNome, decoration: InputDecoration( labelText: "Nome", hintText: "nome produto", prefixIcon: Icon( Icons.shopping_cart, color: Colors.grey, ), suffixIcon: Icon(Icons.close), contentPadding: EdgeInsets.fromLTRB(20.0, 20.0, 20.0, 20.0), border: OutlineInputBorder( borderRadius: BorderRadius.circular(5.0), ), focusedBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.purple[900]), gapPadding: 1, borderRadius: BorderRadius.circular(5.0), ), ), onEditingComplete: () => focus.nextFocus(), keyboardType: TextInputType.text, maxLength: 100, maxLines: null, ), SizedBox(height: 10), TextFormField( initialValue: p.descricao, onSaved: (value) => p.descricao = value, validator: validateDescricao, decoration: InputDecoration( labelText: "Descrição", hintText: "descrição produto", prefixIcon: Icon( Icons.description, color: Colors.grey, ), suffixIcon: Icon(Icons.close), contentPadding: EdgeInsets.fromLTRB(20.0, 20.0, 20.0, 20.0), border: OutlineInputBorder( borderRadius: BorderRadius.circular(5.0)), focusedBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.purple[900]), gapPadding: 1, borderRadius: BorderRadius.circular(5.0), ), ), onEditingComplete: () => focus.nextFocus(), keyboardType: TextInputType.text, maxLength: 100, maxLines: null, ), SizedBox(height: 10), TextFormField( initialValue: p.sku, onSaved: (value) => p.sku = value, validator: validateSKU, decoration: InputDecoration( labelText: "SKU", hintText: "sku produto", prefixIcon: Icon( Icons.shopping_cart, color: Colors.grey, ), suffixIcon: Icon(Icons.close), contentPadding: EdgeInsets.fromLTRB(20.0, 20.0, 20.0, 20.0), border: OutlineInputBorder( borderRadius: BorderRadius.circular(5.0)), focusedBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.purple[900]), gapPadding: 1, borderRadius: BorderRadius.circular(5.0), ), ), onEditingComplete: () => focus.nextFocus(), keyboardType: TextInputType.text, maxLength: 100, maxLines: 1, ), SizedBox(height: 10), TextFormField( controller: controllerQuantidade, onSaved: (value) { p.valorTotal = double.tryParse(value); }, validator: validateQuantidade, decoration: InputDecoration( labelText: "Valor total", hintText: "Valor total", prefixIcon: Icon( Icons.mode_edit, color: Colors.grey, ), suffixIcon: Icon(Icons.close), contentPadding: EdgeInsets.fromLTRB(20.0, 20.0, 20.0, 20.0), border: OutlineInputBorder( borderRadius: BorderRadius.circular(5.0)), focusedBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.purple[900]), gapPadding: 1, borderRadius: BorderRadius.circular(5.0), ), ), onEditingComplete: () => focus.nextFocus(), keyboardType: TextInputType.numberWithOptions(decimal: false), maxLength: 6, ), SizedBox(height: 10), TextFormField( controller: controllerValorUnitario, onSaved: (value) { p.estoque.valorUnitario = double.tryParse(value); }, validator: validateValorUnitario, decoration: InputDecoration( labelText: "Valor unitário", hintText: "Valor unitário", prefixIcon: Icon( Icons.monetization_on_outlined, color: Colors.grey, ), suffixIcon: IconButton( onPressed: () => controllerValorUnitario.clear(), icon: Icon(Icons.clear), ), contentPadding: EdgeInsets.fromLTRB(20.0, 20.0, 20.0, 20.0), border: OutlineInputBorder( borderRadius: BorderRadius.circular(5.0)), focusedBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.purple[900]), gapPadding: 1, borderRadius: BorderRadius.circular(5.0), ), ), onEditingComplete: () => focus.nextFocus(), keyboardType: TextInputType.numberWithOptions(decimal: true), maxLength: 10, ), SizedBox(height: 10), TextFormField( controller: controllerPecentual, onSaved: (value) { p.estoque.percentual = double.tryParse(value); }, validator: validatePercentual, onChanged: (percentual) { valor = (double.tryParse( controllerValorUnitario.text) + (double.tryParse(controllerValorUnitario.text) * double.tryParse( controllerPecentual.text)) / 100); controllerValorVenda.text = valor.toStringAsFixed(2); }, decoration: InputDecoration( labelText: "Percentual de ganho", hintText: "Percentual de ganho", prefixIcon: Icon( Icons.monetization_on_outlined, color: Colors.grey, ), suffixIcon: IconButton( onPressed: () => controllerPecentual.clear(), icon: Icon(Icons.clear), ), contentPadding: EdgeInsets.fromLTRB(20.0, 20.0, 20.0, 20.0), border: OutlineInputBorder( borderRadius: BorderRadius.circular(5.0)), focusedBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.purple[900]), gapPadding: 1, borderRadius: BorderRadius.circular(5.0), ), ), onEditingComplete: () => focus.nextFocus(), keyboardType: TextInputType.numberWithOptions(decimal: true), maxLength: 10, ), SizedBox(height: 10), TextFormField( controller: controllerValorVenda, onSaved: (value) { p.estoque.valorVenda = double.tryParse(value); }, validator: validateValorVenda, decoration: InputDecoration( labelText: "Valor de venda", hintText: "Valor de venda", prefixIcon: Icon( Icons.monetization_on_outlined, color: Colors.grey, ), suffixIcon: IconButton( onPressed: () => controllerValorVenda.clear(), icon: Icon(Icons.clear), ), contentPadding: EdgeInsets.fromLTRB(20.0, 20.0, 20.0, 20.0), border: OutlineInputBorder( borderRadius: BorderRadius.circular(5.0)), focusedBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.purple[900]), gapPadding: 1, borderRadius: BorderRadius.circular(5.0), ), ), onEditingComplete: () => focus.nextFocus(), keyboardType: TextInputType.numberWithOptions(decimal: true), maxLength: 10, enabled: false, ), SizedBox(height: 10), DateTimeField( initialValue: p.estoque.dataRegistro, format: dateFormat, validator: validateDateRegistro, onSaved: (value) => p.dataRegistro = value, decoration: InputDecoration( labelText: "Data registro", hintText: "99-09-9999", prefixIcon: Icon( Icons.calendar_today, color: Colors.grey, ), suffixIcon: Icon(Icons.close), contentPadding: EdgeInsets.fromLTRB(20.0, 20.0, 20.0, 20.0), border: OutlineInputBorder( borderRadius: BorderRadius.circular(5.0)), focusedBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.purple[900]), gapPadding: 1, borderRadius: BorderRadius.circular(5.0), ), ), onEditingComplete: () => focus.nextFocus(), onShowPicker: (context, currentValue) { return showDatePicker( context: context, firstDate: DateTime(2000), initialDate: currentValue?? DateTime.now(), locale: Locale('pt', 'BR'), lastDate: DateTime(2030), ); }, maxLength: 10, ), SizedBox(height: 10), DateTimeField( initialValue: p.estoque.dataVencimento, format: dateFormat, validator: validateDateVencimento, onSaved: (value) => p.dataRegistro = value, decoration: InputDecoration( labelText: "Data vencimento", hintText: "99-09-9999", prefixIcon: Icon( Icons.calendar_today, color: Colors.grey, ), suffixIcon: Icon(Icons.close), contentPadding: EdgeInsets.fromLTRB(20.0, 20.0, 20.0, 20.0), border: OutlineInputBorder( borderRadius: BorderRadius.circular(5.0)), focusedBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.purple[900]), gapPadding: 1, borderRadius: BorderRadius.circular(5.0), ), ), onEditingComplete: () => focus.nextFocus(), onShowPicker: (context, currentValue) { return showDatePicker( context: context, firstDate: DateTime(2000), initialDate: currentValue?? DateTime.now(), locale: Locale('pt', 'BR'), lastDate: DateTime(2030), ); }, maxLength: 10, ), ], ), ), SizedBox(height: 0), Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ DropDownMarca(), Observer( builder: (context) { if (marcaController.marcaSelecionada == null) { return Container( padding: EdgeInsets.only(left: 25), child: Container( child: marcaController.mensagem == null ? Text( "Campo obrigatório *", style: TextStyle( color: Colors.red, fontSize: 12, ), ) : Text( "${marcaController.mensagem}", style: TextStyle( color: Colors.red, fontSize: 12, ), ), ), ); } return Container( padding: EdgeInsets.only(left: 25), child: Container( child: Icon(Icons.check_outlined, color: Colors.green), ), ); }, ), SizedBox(height: 10), DropDownSubCategoria(subCategoriaSelecionada), Observer( builder: (context) { if (subCategoriaController.subCategoriaSelecionada == null) { return Container( padding: EdgeInsets.only(left: 25), child: Container( child: subCategoriaController.mensagem == null ? Text( "campo obrigatório *", style: TextStyle( color: Colors.red, fontSize: 12, ), ) : Text( "${subCategoriaController.mensagem}", style: TextStyle( color: Colors.red, fontSize: 12, ), ), ), ); } return Container( padding: EdgeInsets.only(left: 25), child: Container( child: Icon(Icons.check_outlined, color: Colors.green), ), ); }, ), SizedBox(height: 10), DropDownLoja(lojaSelecionada), Observer( builder: (context) { if (lojaController.lojaSelecionada == null) { return Container( padding: EdgeInsets.only(left: 25), child: Container( child: lojaController.mensagem == null ? Text( "campo obrigatório *", style: TextStyle( color: Colors.red, fontSize: 12, ), ) : Text( "${lojaController.mensagem}", style: TextStyle( color: Colors.red, fontSize: 12, ), ), ), ); } return Container( padding: EdgeInsets.only(left: 25), child: Container( child: Icon(Icons.check_outlined, color: Colors.green), ), ); }, ), SizedBox(height: 10), DropDownPromocao(promocaoSelecionada), Observer( builder: (context) { if (promocaoController.promocaoSelecionada == null) { return Container( padding: EdgeInsets.only(left: 25), child: Container( child: promocaoController.mensagem == null ? Text( "campo obrigatório *", style: TextStyle( color: Colors.red, fontSize: 12, ), ) : Text( "${promocaoController.mensagem}", style: TextStyle( color: Colors.red, fontSize: 12, ), ), ), ); } return Container( padding: EdgeInsets.only(left: 25), child: Container( child: Icon(Icons.check_outlined, color: Colors.green), ), ); }, ), SizedBox(height: 10), DropDownCor(coreSelecionados), SizedBox(height: 10), DropDownTamanho(tamanhoSelecionados), SizedBox(height: 10), ], ), SizedBox(height: 0), Container( padding: EdgeInsets.all(15), child: Container( child: Column( children: <Widget>[ Container( decoration: BoxDecoration( border: Border.all(color: Colors.grey), borderRadius: BorderRadius.circular(5), ), child: SwitchListTile( autofocus: true, title: Text("Produto novo? "), subtitle: Text("sim/não"), value: p.novo = novo, secondary: const Icon(Icons.check_outlined), onChanged: (bool valor) { setState(() { novo = valor; print("Novo: " + p.novo.toString()); }); }, ), ), SizedBox(height: 30), Container( decoration: BoxDecoration( border: Border.all(color: Colors.grey), borderRadius: BorderRadius.circular(5), ), child: SwitchListTile( subtitle: Text("sim/não"), title: Text("Produto Disponível?"), value: p.status = status, secondary: const Icon(Icons.check_outlined), onChanged: (bool valor) { setState(() { status = valor; print("Disponivel: " + p.status.toString()); }); }, ), ), SizedBox(height: 30), Container( decoration: BoxDecoration( border: Border.all(color: Colors.grey), borderRadius: BorderRadius.circular(5), ), child: SwitchListTile( autofocus: true, subtitle: Text("sim/não"), title: Text("Produto destaque?"), value: p.destaque = destaque, secondary: const Icon(Icons.check_outlined), onChanged: (bool valor) { setState(() { destaque = valor; print("Destaque: " + p.destaque.toString()); }); }, ), ), ], ), ), ), Container( padding: EdgeInsets.all(15), child: Container( padding: EdgeInsets.all(10), decoration: BoxDecoration( border: Border.all(color: Colors.grey), borderRadius: BorderRadius.circular(5), ), child: Column( children: <Widget>[ Column( crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ Text("Unidade de medida"), RadioListTile( controlAffinity: ListTileControlAffinity.trailing, title: Text("UNIDADE"), value: "UNIDADE", groupValue: p.medida == null ? p.medida = medida : p.medida, secondary: const Icon(Icons.check_outlined), onChanged: (String valor) { setState(() { p.medida = valor; print("Medida: " + p.medida); }); }, ), RadioListTile( controlAffinity: ListTileControlAffinity.trailing, title: Text("PEÇA"), value: "PECA", groupValue: p.medida == null ? p.medida = medida : p.medida, secondary: const Icon(Icons.check_outlined), onChanged: (String valor) { setState(() { p.medida = valor; print("Medida: " + p.medida); }); }, ), RadioListTile( controlAffinity: ListTileControlAffinity.trailing, title: Text("QUILOGRAMA"), value: "QUILOGRAMA", groupValue: p.medida == null ? p.medida = medida : p.medida, secondary: const Icon(Icons.check_outlined), onChanged: (String valor) { setState(() { p.medida = valor; print("resultado: " + p.medida); }); }, ), RadioListTile( controlAffinity: ListTileControlAffinity.trailing, title: Text("OUTRO"), value: "OUTRO", groupValue: p.medida == null ? p.medida = medida : p.medida, secondary: const Icon(Icons.check_outlined), onChanged: (String valor) { setState(() { p.medida = valor; print("resultado: " + p.medida); }); }, ), ], ), ], ), ), ), Container( padding: EdgeInsets.all(15), child: Container( padding: EdgeInsets.all(5), decoration: BoxDecoration( border: Border.all(color: Colors.grey), borderRadius: BorderRadius.circular(5), ), child: Column( children: <Widget>[ Column( crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ Text("Origem do produto"), RadioListTile( controlAffinity: ListTileControlAffinity.trailing, title: Text("NACIONAL"), value: "NACIONAL", groupValue: p.origem == null ? p.origem = origem : p.origem, secondary: const Icon(Icons.check_outlined), onChanged: (String valor) { setState(() { p.origem = valor; print("Origem: " + p.origem); }); }, ), RadioListTile( controlAffinity: ListTileControlAffinity.trailing, title: Text("INTERNACIONAL"), value: "INTERNACIONAL", groupValue: p.origem == null ? p.origem = origem : p.origem, secondary: const Icon(Icons.check_outlined), onChanged: (String valor) { setState(() { p.origem = valor; print("Origem: " + p.origem); }); }, ), ], ), ], ), ), ), ], ), ), ), SizedBox(height: 0), Container( padding: EdgeInsets.all(15), child: RaisedButton.icon( label: Text("Enviar formulário"), icon: Icon(Icons.check), onPressed: () { if (controller.validate()) { if (p.id == null) { dialogs.information(context, "prepando para o cadastro..."); Timer(Duration(seconds: 3), () { DateTime agora = DateTime.now(); print("Loja: ${p.loja.nome}"); print("SubCategoria: ${p.subCategoria.nome}"); print("Marca: ${p.marca.nome}"); print("Promoção: ${p.promocao.nome}"); print("Foto: ${p.foto}"); print("Código de Barra: ${p.codigoBarra}"); print("Produto: ${p.nome}"); print("Quantidade: ${p.estoque.quantidade}"); print("Valor: ${p.estoque.valorUnitario}"); print("Novo: ${p.novo}"); print("Status: ${p.status}"); print("Destaque: ${p.destaque}"); print("Medida: ${p.medida}"); print("Origem: ${p.origem}"); print("Data: ${p.dataRegistro}"); print("Agora: ${agora}"); for (Cor c in corController.cores) { print("Cores: ${c.descricao}"); } for (Tamanho c in tamanhoController.tamanhos) { print("Tamanhos: ${c.descricao}"); } p.cores.addAll(produtoController.corSelecionadas); p.tamanhos.addAll(produtoController.tamanhoSelecionados); p.estoque.quantidade = int.tryParse(controllerQuantidade.text); p.estoque.valorUnitario = double.tryParse(controllerValorUnitario.text); p.estoque.valorVenda = double.tryParse(controllerValorVenda.text); p.estoque.percentual = double.tryParse(controllerPecentual.text); produtoController.create(p).then((value) { print("resultado : ${value}"); }); // Navigator.of(context).pop(); // buildPush(context); }); } else { dialogs.information( context, "preparando para o alteração..."); Timer(Duration(seconds: 3), () { DateTime agora = DateTime.now(); print("Loja: ${p.loja.nome}"); print("SubCategoria: ${p.subCategoria.nome}"); print("Marca: ${p.marca.nome}"); print("Promoção: ${p.promocao.nome}"); print("Foto: ${p.foto}"); print("Código de Barra: ${p.codigoBarra}"); print("Produto: ${p.nome}"); print("Quantidade: ${p.estoque.quantidade}"); print("Valor: ${p.estoque.valorUnitario}"); print("Novo: ${p.novo}"); print("Status: ${p.status}"); print("Destaque: ${p.destaque}"); print("Medida: ${p.medida}"); print("Origem: ${p.origem}"); for (Cor c in produtoController.corSelecionadas) { print("Cores: ${c.descricao}"); } for (Tamanho c in produtoController.tamanhoSelecionados) { print("Tamanhos: ${c.descricao}"); } p.cores.addAll(produtoController.corSelecionadas); p.tamanhos.addAll(produtoController.tamanhoSelecionados); p.estoque.quantidade = int.tryParse(controllerQuantidade.text); p.estoque.valorUnitario = double.tryParse(controllerValorUnitario.text); p.estoque.valorVenda = double.tryParse(controllerValorVenda.text); p.estoque.percentual = double.tryParse(controllerPecentual.text); // produtoController.update(p.id, p); // Navigator.of(context).pop(); // buildPush(context); }); } } }), ), SizedBox(height: 20), ], ); } buildPush(BuildContext context) { return Navigator.push( context, MaterialPageRoute( builder: (context) => ProdutoTab(), ), ); } } class Controller { var formKey = GlobalKey<FormState>(); bool validate() { var form = formKey.currentState; if (form.validate()) { form.save(); return true; } else return false; } } ======================= File: lib/src/core/controller/endereco_controller.g.dart ======================= // GENERATED CODE - DO NOT MODIFY BY HAND part of 'endereco_controller.dart'; // ************************************************************************** // StoreGenerator // ************************************************************************** // ignore_for_file: non_constant_identifier_names, unnecessary_brace_in_string_interps, unnecessary_lambdas, prefer_expression_function_bodies, lines_longer_than_80_chars, avoid_as, avoid_annotating_with_dynamic mixin _$EnderecoController on EnderecoControllerBase, Store { final _$enderecosAtom = Atom(name: 'EnderecoControllerBase.enderecos'); @override List<Endereco> get enderecos { _$enderecosAtom.reportRead(); return super.enderecos; } @override set enderecos(List<Endereco> value) { _$enderecosAtom.reportWrite(value, super.enderecos, () { super.enderecos = value; }); } final _$enderecoAtom = Atom(name: 'EnderecoControllerBase.endereco'); @override int get endereco { _$enderecoAtom.reportRead(); return super.endereco; } @override set endereco(int value) { _$enderecoAtom.reportWrite(value, super.endereco, () { super.endereco = value; }); } final _$errorAtom = Atom(name: 'EnderecoControllerBase.error'); @override Exception get error { _$errorAtom.reportRead(); return super.error; } @override set error(Exception value) { _$errorAtom.reportWrite(value, super.error, () { super.error = value; }); } final _$dioErrorAtom = Atom(name: 'EnderecoControllerBase.dioError'); @override DioError get dioError { _$dioErrorAtom.reportRead(); return super.dioError; } @override set dioError(DioError value) { _$dioErrorAtom.reportWrite(value, super.dioError, () { super.dioError = value; }); } final _$mensagemAtom = Atom(name: 'EnderecoControllerBase.mensagem'); @override String get mensagem { _$mensagemAtom.reportRead(); return super.mensagem; } @override set mensagem(String value) { _$mensagemAtom.reportWrite(value, super.mensagem, () { super.mensagem = value; }); } final _$enderecoSelecionadoAtom = Atom(name: 'EnderecoControllerBase.enderecoSelecionado'); @override Endereco get enderecoSelecionado { _$enderecoSelecionadoAtom.reportRead(); return super.enderecoSelecionado; } @override set enderecoSelecionado(Endereco value) { _$enderecoSelecionadoAtom.reportWrite(value, super.enderecoSelecionado, () { super.enderecoSelecionado = value; }); } final _$getAllAsyncAction = AsyncAction('EnderecoControllerBase.getAll'); @override Future<List<Endereco>> getAll() { return _$getAllAsyncAction.run(() => super.getAll()); } final _$getAllByPessoaAsyncAction = AsyncAction('EnderecoControllerBase.getAllByPessoa'); @override Future<List<Endereco>> getAllByPessoa(int id) { return _$getAllByPessoaAsyncAction.run(() => super.getAllByPessoa(id)); } final _$getCepAsyncAction = AsyncAction('EnderecoControllerBase.getCep'); @override Future<Endereco> getCep(String cep) { return _$getCepAsyncAction.run(() => super.getCep(cep)); } final _$createAsyncAction = AsyncAction('EnderecoControllerBase.create'); @override Future<int> create(Endereco p) { return _$createAsyncAction.run(() => super.create(p)); } final _$updateAsyncAction = AsyncAction('EnderecoControllerBase.update'); @override Future<int> update(int id, Endereco p) { return _$updateAsyncAction.run(() => super.update(id, p)); } @override String toString() { return ''' enderecos: ${enderecos}, endereco: ${endereco}, error: ${error}, dioError: ${dioError}, mensagem: ${mensagem}, enderecoSelecionado: ${enderecoSelecionado} '''; } } ======================= File: lib/src/util/dropdown/dropdown_categoria.dart ======================= import 'package:flutter/material.dart'; import 'package:flutter_mobx/flutter_mobx.dart'; import 'package:get_it/get_it.dart'; import 'package:nosso/src/core/controller/categoria_controller.dart'; import 'package:nosso/src/core/model/categoria.dart'; import 'package:nosso/src/util/dialogs/dialog_categoria.dart'; class DropDownCategoria extends StatelessWidget { @override Widget build(BuildContext context) { var categoriaController = GetIt.I.get<CategoriaController>(); AlertCategoria alertCateria = AlertCategoria(); return Observer( builder: (context) { Categoria categoria = categoriaController.categoriaSelecionada; return Container( padding: EdgeInsets.all(15), child: Container( decoration: BoxDecoration( border: Border.all(color: Colors.grey), borderRadius: BorderRadius.circular(5), ), child: ListTile( title: Text("Categoria *"), subtitle: categoria == null ? Text("Selecione uma categoria") : Text(categoriaController.categoriaSelecionada.nome), leading: Icon(Icons.list_alt_outlined), trailing: Icon(Icons.arrow_drop_down_sharp), onTap: () { alertCateria.alert(context, categoria); }, ), ), ); }, ); } } ======================= File: lib/src/core/repository/caixasaida_repository.dart ======================= import 'package:dio/dio.dart'; import 'package:nosso/src/api/dio/custon_dio.dart'; import 'package:nosso/src/core/model/caixasaida.dart'; class CaixaSaidaRepository { CustonDio dio = CustonDio(); Future<List<CaixaFluxoSaida>> getAllById(int id) async { try { print("carregando caixafluxosaidas by id"); var response = await dio.client.get("/caixafluxosaidas/${id}"); return (response.data as List) .map((c) => CaixaFluxoSaida.fromJson(c)) .toList(); } on DioError catch (e) { print(e.message); } return null; } Future<List<CaixaFluxoSaida>> getAll() async { try { print("carregando caixafluxosaidas"); var response = await dio.client.get("/caixafluxosaidas"); return (response.data as List) .map((c) => CaixaFluxoSaida.fromJson(c)) .toList(); } on DioError catch (e) { print(e.message); } return null; } Future<int> create(Map<String, dynamic> data) async { var response = await dio.client.post("/caixafluxosaidas/create", data: data); return response.statusCode; } Future<int> update(int id, Map<String, dynamic> data) async { var response = await dio.client.put("/caixafluxosaidas/update/$id", data: data); return response.statusCode; } } ======================= File: lib/src/util/container/container_categoria.dart ======================= import 'package:flutter/material.dart'; import 'package:nosso/src/core/controller/categoria_controller.dart'; import 'package:nosso/src/core/model/categoria.dart'; import 'package:nosso/src/paginas/categoria/categoria_create_page.dart'; class ContainerCategoria extends StatelessWidget { CategoriaController categoriaController; Categoria p; ContainerCategoria(this.categoriaController, this.p); @override Widget build(BuildContext context) { return ListTile( isThreeLine: false, leading: Container( padding: EdgeInsets.all(1), decoration: new BoxDecoration( gradient: LinearGradient( colors: [Theme.of(context).primaryColor, Theme.of(context).primaryColor], ), border: Border.all( color: Colors.black, width: 1, ), borderRadius: BorderRadius.circular(35), ), child: CircleAvatar( backgroundColor: Colors.grey[100], radius: 20, backgroundImage: NetworkImage( "${categoriaController.arquivo + p.foto}", ), ), ), title: Text(p.nome), subtitle: Text("código ${p.id}"), trailing: Container( height: 80, width: 50, child: buildPopupMenuButton(context, p), ), ); } PopupMenuButton<String> buildPopupMenuButton( BuildContext context, Categoria c) { return PopupMenuButton<String>( padding: EdgeInsets.zero, icon: Icon(Icons.more_vert), onSelected: (valor) { if (valor == "novo") { print("novo"); } if (valor == "editar") { print("editar"); Navigator.of(context).pop(); Navigator.of(context).push( MaterialPageRoute( builder: (BuildContext context) { return CategoriaCreatePage( categoria: c, ); }, ), ); } if (valor == "delete") { print("delete"); } }, itemBuilder: (BuildContext context) => <PopupMenuEntry<String>>[ const PopupMenuItem<String>( value: 'novo', child: ListTile( leading: Icon(Icons.add), title: Text('novo'), ), ), const PopupMenuItem<String>( value: 'editar', child: ListTile( leading: Icon(Icons.edit), title: Text('editar'), ), ), const PopupMenuItem<String>( value: 'delete', child: ListTile( leading: Icon(Icons.delete), title: Text('Delete'), ), ) ], ); } } ======================= File: lib/src/util/dialogs/dialog_produto_filter.dart ======================= <filename>lib/src/util/dialogs/dialog_produto_filter.dart import 'package:flutter/material.dart'; import 'package:flutter_mobx/flutter_mobx.dart'; import 'package:get_it/get_it.dart'; import 'package:nosso/src/core/controller/subcategoria_controller.dart'; import 'package:nosso/src/core/model/subcategoria.dart'; import 'package:nosso/src/util/filter/produto_filter.dart'; import 'package:nosso/src/util/load/circular_progresso_mini.dart'; class DialogProdutoFilter extends StatefulWidget { ProdutoFilter filter; DialogProdutoFilter(this.filter); @override _DialogProdutoFilterState createState() => _DialogProdutoFilterState(this.filter); } class _DialogProdutoFilterState extends State<DialogProdutoFilter> { _DialogProdutoFilterState(this.filter); var subCategoriaController = GetIt.I.get<SubCategoriaController>(); ProdutoFilter filter; @override void initState() { if (filter == null) { filter = ProdutoFilter(); } subCategoriaController.getAll(); super.initState(); } @override Widget build(BuildContext context) { return builderConteudoListSubCategorias(); } builderConteudoListSubCategorias() { return Container( padding: EdgeInsets.only(top: 0), child: Observer( builder: (context) { List<SubCategoria> categorias = subCategoriaController.subCategorias; if (subCategoriaController.error!= null) { return Text("Não foi possível carregados dados"); } if (categorias == null) { return CircularProgressorMini(); } return builderListCategorias(categorias); }, ), ); } builderListCategorias(List<SubCategoria> categorias) { double containerWidth = 160; double containerHeight = 20; return ListView.builder( itemCount: categorias.length, itemBuilder: (context, index) { SubCategoria c = categorias[index]; return Column( children: [ GestureDetector( child: ListTile( leading: CircleAvatar( backgroundColor: Colors.grey[200], radius: 20, child: Icon(Icons.check_outlined), ), title: Text(c.nome), ), onTap: () { setState(() { // filter.categoria = c.nome; print("SubCategoria: ${filter.subCategoria}"); }); }, ), Divider() ], ); }, ); } } class AlertProdutoFilter { alert(BuildContext context, ProdutoFilter filter) { return showDialog( context: context, builder: (BuildContext context) { return AlertDialog( shape: RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(32.0))), contentPadding: EdgeInsets.only(top: 10.0), content: Container( width: 300.0, child: DialogProdutoFilter(filter), ), actions: [ FlatButton( onPressed: () { Navigator.of(context).pop(); }, child: Text("Cancelar"), ), FlatButton( onPressed: () { Navigator.of(context).pop(); }, child: Text("Aplicar"), ) ], ); }, ); } } ======================= File: lib/src/core/controller/caixafluxoentrada_controller.dart ======================= import 'package:dio/dio.dart'; import 'package:mobx/mobx.dart'; import 'package:nosso/src/core/model/caixaentrada.dart'; import 'package:nosso/src/core/repository/caixaentrada_repository.dart'; part 'caixafluxoentrada_controller.g.dart'; class CaixafluxoentradaController = CaixafluxoentradaControllerBase with _$CaixafluxoentradaController; abstract class CaixafluxoentradaControllerBase with Store { CaixaEntradaRepository caixaEntradaRepository; CaixafluxoEntradaControllerBase() { caixaEntradaRepository = CaixaEntradaRepository(); } @observable List<CaixaFluxoEntrada> caixaEntradas; @observable int caixaEntrada; @observable Exception error; @observable DioError dioError; @observable String mensagem; @action Future<List<CaixaFluxoEntrada>> getAll() async { try { caixaEntradas = await caixaEntradaRepository.getAll(); return caixaEntradas; } catch (e) { error = e; } } @action Future<int> create(CaixaFluxoEntrada p) async { try { caixaEntrada = await caixaEntradaRepository.create(p.toJson()); if (caixaEntrada == null) { mensagem = "sem dados"; } else { return caixaEntrada; } } on DioError catch (e) { mensagem = e.message; dioError = e; } } @action Future<int> update(int id, CaixaFluxoEntrada p) async { try { caixaEntrada = await caixaEntradaRepository.update(id, p.toJson()); return caixaEntrada; } on DioError catch (e) { mensagem = e.message; dioError = e; } } } ======================= File: lib/src/paginas/endereco/endereco_loja_page.dart ======================= import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_mobx/flutter_mobx.dart'; import 'package:get_it/get_it.dart'; import 'package:nosso/src/core/controller/endereco_controller.dart'; import 'package:nosso/src/core/model/endereco.dart'; import 'package:nosso/src/paginas/endereco/endereco_create_page.dart'; import 'package:nosso/src/paginas/endereco/endereco_location.dart'; import 'package:nosso/src/util/load/circular_progresso.dart'; class EnderecoLojaPage extends StatefulWidget { @override _EnderecoLojaPageState createState() => _EnderecoLojaPageState(); } class _EnderecoLojaPageState extends State<EnderecoLojaPage> { var enderecoController = GetIt.I.get<EnderecoController>(); @override void initState() { enderecoController.getAllByPessoa(3); super.initState(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("Endereços da loja"), actions: <Widget>[ Observer( builder: (context) { if (enderecoController.error!= null) { return Text("Não foi possível carregar"); } if (enderecoController.enderecos == null) { return Center( child: Icon(Icons.warning_amber_outlined), ); } return Chip( label: Text( (enderecoController.enderecos.length?? 0).toString(), ), ); }, ), SizedBox(width: 20), ], ), body: builderConteudoList(), floatingActionButton: Column( mainAxisAlignment: MainAxisAlignment.end, children: <Widget>[ SizedBox( width: 8, height: 8, ), FloatingActionButton( elevation: 10, child: Icon(Icons.add), onPressed: () { Navigator.of(context).pop(); Navigator.push( context, MaterialPageRoute( builder: (context) { return EnderecoCreatePage(); }, ), ); }, ) ], ), ); } builderConteudoList() { return Container( padding: EdgeInsets.only(top: 0), child: Observer( builder: (context) { List<Endereco> enderecos = enderecoController.enderecos; if (enderecoController.error!= null) { return Text("Não foi possível carregados dados"); } if (enderecos == null) { return CircularProgressor(); } return builderList(enderecos); }, ), ); } ListView builderList(List<Endereco> enderecos) { double containerWidth = 160; double containerHeight = 30; return ListView.builder( itemCount: enderecos.length, itemBuilder: (context, index) { Endereco e = enderecos[index]; return GestureDetector( child: ListTile( isThreeLine: true, leading: Container( padding: EdgeInsets.all(1), decoration: new BoxDecoration( gradient: LinearGradient( colors: [Theme.of(context).primaryColor, Theme.of(context).primaryColor], ), border: Border.all( color: Colors.black, width: 1, ), borderRadius: BorderRadius.circular(35), ), child: CircleAvatar( backgroundColor: Colors.grey[100], radius: 20, child: Icon(Icons.location_on_outlined), ), ), title: Text("${e.logradouro}, ${e.numero}"), subtitle: Text("${e.complemento}"), trailing: Container( height: 80, width: 50, child: buildPopupMenuButton(context, e), ), ), onTap: () {}, ); }, ); } PopupMenuButton<String> buildPopupMenuButton( BuildContext context, Endereco e) { return PopupMenuButton<String>( padding: EdgeInsets.zero, icon: Icon(Icons.more_vert), onSelected: (valor) { if (valor == "novo") { print("novo"); } if (valor == "editar") { print("editar"); Navigator.of(context).pop(); Navigator.of(context).push( MaterialPageRoute( builder: (BuildContext context) { return EnderecoCreatePage( endereco: e, ); }, ), ); } if (valor == "detalhes") { print("detalhes"); Navigator.of(context).pop(); Navigator.of(context).push( MaterialPageRoute( builder: (BuildContext context) { return EnderecoLocation(endereco: e); }, ), ); } if (valor == "delete") { print("delete"); } }, itemBuilder: (BuildContext context) => <PopupMenuEntry<String>>[ const PopupMenuItem<String>( value: 'novo', child: ListTile( leading: Icon(Icons.add), title: Text('novo'), ), ), const PopupMenuItem<String>( value: 'editar', child: ListTile( leading: Icon(Icons.edit), title: Text('editar'), ), ), const PopupMenuItem<String>( value: 'detalhes', child: ListTile( leading: Icon(Icons.location_on_outlined), title: Text('detalhes'), ), ), const PopupMenuItem<String>( value: 'delete', child: ListTile( leading: Icon(Icons.delete), title: Text('Delete'), ), ) ], ); } } ======================= File: lib/src/paginas/marca/marca_create_page.dart ======================= import 'dart:async'; import 'dart:core'; import 'dart:io'; import 'package:flutter/material.dart'; import 'package:flutter_mobx/flutter_mobx.dart'; import 'package:fluttertoast/fluttertoast.dart'; import 'package:get_it/get_it.dart'; import 'package:nosso/src/core/controller/marca_controller.dart'; import 'package:nosso/src/core/model/marca.dart'; import 'package:nosso/src/paginas/marca/marca_page.dart'; import 'package:nosso/src/util/dialogs/dialogs.dart'; class MarcaCreatePage extends StatefulWidget { Marca marca; MarcaCreatePage({Key key, this.marca}) : super(key: key); @override _MarcaCreatePageState createState() => _MarcaCreatePageState(c: marca); } class _MarcaCreatePageState extends State<MarcaCreatePage> { var marcaController = GetIt.I.get<MarcaController>(); Dialogs dialogs = Dialogs(); Marca c; File file; bool isButtonDesable = false; final scaffoldKey = GlobalKey<ScaffoldState>(); _MarcaCreatePageState({this.c}); var controllerNome = TextEditingController(); @override void initState() { marcaController.getAll(); if (c == null) { c = Marca(); } super.initState(); } Controller controller; @override didChangeDependencies() { controller = Controller(); super.didChangeDependencies(); } showToast(String cardTitle) { Fluttertoast.showToast( msg: "$cardTitle", gravity: ToastGravity.CENTER, timeInSecForIos: 10, fontSize: 16.0, ); } showSnackbar(BuildContext context, String content) { scaffoldKey.currentState.showSnackBar( SnackBar( content: Text(content), action: SnackBarAction( label: "OK", onPressed: () {}, ), ), ); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: c.nome == null? Text("Cadastro de marca") : Text(c.nome), ), body: Observer( builder: (context) { if (marcaController.dioError == null) { return buildListViewForm(context); } else { print("Erro: ${marcaController.mensagem}"); showToast("${marcaController.mensagem}"); return buildListViewForm(context); } }, ), ); } buildListViewForm(BuildContext context) { var focus = FocusScope.of(context); return ListView( children: <Widget>[ Container( color: Theme.of(context).accentColor.withOpacity(0.1), padding: EdgeInsets.all(0), child: ListTile( title: Text("Cadastrar marca de produtos"), trailing: Icon(Icons.shopping_cart_outlined), ), ), SizedBox(height: 10), Container( padding: EdgeInsets.all(10), child: Form( key: controller.formKey, child: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ Container( padding: EdgeInsets.all(5), child: Column( children: <Widget>[ TextFormField( initialValue: c.nome, onSaved: (value) => c.nome = value, validator: (value) => value.isEmpty? "campo obrigário" : null, decoration: InputDecoration( labelText: "Nome", hintText: "nome categoria", prefixIcon: Icon( Icons.edit, color: Colors.grey, ), suffixIcon: Icon(Icons.close), labelStyle: TextStyle(color: Colors.black), border: OutlineInputBorder( borderRadius: BorderRadius.circular(5.0)), focusedBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.lime[900]), gapPadding: 1, borderRadius: BorderRadius.circular(5.0), ), ), onEditingComplete: () => focus.nextFocus(), keyboardType: TextInputType.text, maxLength: 50, maxLines: 1, ), ], ), ), ], ), ), ), SizedBox(height: 0), Container( padding: EdgeInsets.all(15), child: RaisedButton.icon( label: Text("Enviar formulário"), icon: Icon(Icons.check), onPressed: () { if (controller.validate()) { if (c.id == null) { dialogs.information(context, "prepando para o cadastro..."); Timer(Duration(seconds: 3), () { marcaController.create(c).then((value) { print("resultado : ${value}"); }); Navigator.of(context).pop(); buildPush(context); }); } else { dialogs.information( context, "preparando para o alteração..."); Timer(Duration(seconds: 3), () { marcaController.update(c.id, c); Navigator.of(context).pop(); buildPush(context); }); } } }, ), ), ], ); } buildPush(BuildContext context) { return Navigator.push( context, MaterialPageRoute( builder: (context) => MarcaPage(), ), ); } } class Controller { var formKey = GlobalKey<FormState>(); bool validate() { var form = formKey.currentState; if (form.validate()) { form.save(); return true; } else return false; } } ======================= File: lib/src/util/dialogs/dialog_promocao.dart ======================= <gh_stars>0 import 'package:flutter/material.dart'; import 'package:flutter_mobx/flutter_mobx.dart'; import 'package:get_it/get_it.dart'; import 'package:nosso/src/api/constants/constant_api.dart'; import 'package:nosso/src/core/controller/promocao_controller.dart'; import 'package:nosso/src/core/model/promocao.dart'; import 'package:nosso/src/util/load/circular_progresso_mini.dart'; class DialogPromocao extends StatefulWidget { Promocao promocao; DialogPromocao(this.promocao); @override _DialogPromocaoState createState() => _DialogPromocaoState(this.promocao); } class _DialogPromocaoState extends State<DialogPromocao> { _DialogPromocaoState(this.promocao); var promocaoController = GetIt.I.get<PromoCaoController>(); Promocao promocao; @override void initState() { promocaoController.getAll(); super.initState(); } @override Widget build(BuildContext context) { return builderConteudoListPromocao(); } /* =================== PROMOÇÃO LISTA =================== */ builderConteudoListPromocao() { return Container( padding: EdgeInsets.only(top: 0), child: Observer( builder: (context) { List<Promocao> promocoes = promocaoController.promocoes; if (promocaoController.error!= null) { return Text("Não foi possível carregados dados"); } if (promocoes == null) { return CircularProgressorMini(); } return builderListPromocoes(promocoes); }, ), ); } builderListPromocoes(List<Promocao> promocoes) { double containerWidth = 160; double containerHeight = 20; return ListView.builder( itemCount: promocoes.length, itemBuilder: (context, index) { Promocao c = promocoes[index]; return Column( children: [ GestureDetector( child: ListTile( leading: Container( padding: EdgeInsets.all(1), decoration: new BoxDecoration( gradient: LinearGradient( colors: [Colors.purple, Colors.grey[900]], ), border: Border.all( color: Colors.black, width: 1, ), borderRadius: BorderRadius.circular(35), ), child: c.foto!= null ? CircleAvatar( backgroundColor: Colors.grey[100], radius: 20, backgroundImage: NetworkImage( "${promocaoController.arquivo + c.foto}", ), ) : CircleAvatar(), ), title: Text(c.nome), ), onTap: () { promocaoController.promocaoSelecionada = c; print("Loja: ${promocaoController.promocaoSelecionada.nome}"); Navigator.of(context).pop(); }, ), Divider() ], ); }, ); } } class AlertPromocao { alert(BuildContext context, Promocao promocao) { return showDialog( context: context, builder: (BuildContext context) { return AlertDialog( shape: RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(32.0))), contentPadding: EdgeInsets.only(top: 10.0), content: Container( width: 300.0, child: DialogPromocao(promocao), ), actions: [ FlatButton( onPressed: () { Navigator.pop(context); }, child: Text("ok"), ) ], ); }, ); } } ======================= File: lib/src/util/upload/upload_response.dart ======================= <reponame>ofertasbv/ofertaflutterweb import 'dart:convert'; import 'package:nosso/src/core/model/uploadFileResponse.dart'; class UploadRespnse { response(UploadFileResponse response, String url) { var parseJson = json.decode(url); response.fileName = parseJson['fileName']; response.fileDownloadUri = parseJson['fileDownloadUri']; response.fileType = parseJson['fileType']; response.size = parseJson['size']; return response; } } ======================= File: lib/src/core/model/uploadFileResponse.dart ======================= class UploadFileResponse { String fileName; String fileDownloadUri; String fileType; int size; } ======================= File: lib/src/util/load/circular_progresso.dart ======================= import 'package:flutter/material.dart'; class CircularProgressor extends StatelessWidget { @override Widget build(BuildContext context) { return Center( child: SizedBox( height: 150, width: 150, child: CircularProgressIndicator( strokeWidth: 1.8, backgroundColor: Theme.of(context).primaryColor, valueColor: AlwaysStoppedAnimation<Color>(Colors.black), ), ), ); } } ======================= File: lib/src/core/repository/marca_repository.dart ======================= <filename>lib/src/core/repository/marca_repository.dart import 'dart:io'; import 'package:dio/dio.dart'; import 'package:nosso/src/api/constants/constant_api.dart'; import 'package:nosso/src/api/dio/custon_dio.dart'; import 'package:nosso/src/core/model/marca.dart'; class MarcaRepository { CustonDio dio = CustonDio(); Future<List<Marca>> getAllById(int id) async { try { print("carregando marcas by id"); var response = await dio.client.get("/marcas/${id}"); return (response.data as List).map((c) => Marca.fromJson(c)).toList(); } on DioError catch (e) { print(e.message); } return null; } Future<List<Marca>> getAll() async { try { print("carregando marcas"); var response = await dio.client.get("/marcas"); return (response.data as List).map((c) => Marca.fromJson(c)).toList(); } on DioError catch (e) { print(e.message); } return null; } Future<int> create(Map<String, dynamic> data) async { var response = await dio.client.post("/marcas/create", data: data); return response.statusCode; } Future<int> update(int id, Map<String, dynamic> data) async { var response = await dio.client.put("/marcas/update/$id", data: data); return response.statusCode; } } ======================= File: lib/src/paginas/cliente/cliente_create_page.dart ======================= import 'dart:async'; import 'dart:io'; import 'package:datetime_picker_formfield/datetime_picker_formfield.dart'; import 'package:flutter/material.dart'; import 'package:flutter_mobx/flutter_mobx.dart'; import 'package:fluttertoast/fluttertoast.dart'; import 'package:get_it/get_it.dart'; import 'package:intl/intl.dart'; import 'package:mask_text_input_formatter/mask_text_input_formatter.dart'; import 'package:nosso/src/core/controller/cliente_controller.dart'; import 'package:nosso/src/core/model/cliente.dart'; import 'package:nosso/src/core/model/endereco.dart'; import 'package:nosso/src/core/model/uploadFileResponse.dart'; import 'package:nosso/src/core/model/usuario.dart'; import 'package:nosso/src/paginas/cliente/cliente_page.dart'; import 'package:nosso/src/paginas/usuario/usuario_login_page.dart'; import 'package:nosso/src/util/dialogs/dialogs.dart'; import 'package:nosso/src/util/upload/upload_response.dart'; import 'package:nosso/src/util/validador/validador_pessoa.dart'; class ClienteCreatePage extends StatefulWidget { Cliente cliente; ClienteCreatePage({Key key, this.cliente}) : super(key: key); @override _ClienteCreatePageState createState() => _ClienteCreatePageState(p: this.cliente); } class _ClienteCreatePageState extends State<ClienteCreatePage> with ValidadorPessoa { var clienteController = GetIt.I.get<ClienteController>(); Dialogs dialogs = Dialogs(); Cliente p; Endereco e; Usuario u; _ClienteCreatePageState({this.p}); final scaffoldKey = GlobalKey<ScaffoldState>(); DateTime dataAtual = DateTime.now(); String tipoPessoa; String sexo; String valorSlecionado; File file; var uploadFileResponse = UploadFileResponse(); var response = UploadRespnse(); var senhaController = TextEditingController(); var confirmaSenhaController = TextEditingController(); @override void initState() { if (p == null) { p = Cliente(); u = Usuario(); e = Endereco(); } else { u = p.usuario; } tipoPessoa = "FISICA"; sexo = "MASCULINO"; super.initState(); } Controller controller; @override void didChangeDependencies() { controller = Controller(); super.didChangeDependencies(); } showToast(String cardTitle) { Fluttertoast.showToast( msg: "$cardTitle", gravity: ToastGravity.CENTER, timeInSecForIos: 10, fontSize: 16.0, ); } showSnackbar(BuildContext context, String content) { scaffoldKey.currentState.showSnackBar( SnackBar( content: Text(content), action: SnackBarAction( label: "OK", onPressed: () {}, ), ), ); } @override Widget build(BuildContext context) { return Scaffold( key: scaffoldKey, appBar: AppBar( title: p.nome == null? Text("Cadastro de cliente") : Text(p.nome), ), body: Observer( builder: (context) { if (clienteController.dioError == null) { return buildListViewForm(context); } else { print("Erro: ${clienteController.mensagem}"); showToast("${clienteController.mensagem}"); return buildListViewForm(context); } }, ), ); } buildListViewForm(BuildContext context) { var focus = FocusScope.of(context); var dateFormat = DateFormat('dd-MM-yyyy'); var maskFormatterCelular = new MaskTextInputFormatter( mask: '(##)#####-####', filter: {"#": RegExp(r'[0-9]')}); var maskFormatterCPF = new MaskTextInputFormatter( mask: '###.###.###-##', filter: {"#": RegExp(r'[0-9]')}); p.usuario = u; return ListView( children: <Widget>[ Container( color: Theme.of(context).accentColor.withOpacity(0.1), padding: EdgeInsets.all(0), child: ListTile( title: Text("faça seu cadastro, é rapido e seguro"), trailing: Icon(Icons.person_outline), ), ), SizedBox(height: 20), Container( padding: EdgeInsets.all(10), child: Form( key: controller.formKey, child: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ Container( padding: EdgeInsets.all(5), child: Container( decoration: BoxDecoration( border: Border.all(color: Colors.grey), borderRadius: BorderRadius.circular(5), ), padding: EdgeInsets.all(5), child: Column( children: <Widget>[ Text("Dados Pessoais"), SizedBox(height: 15), Column( crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ RadioListTile( controlAffinity: ListTileControlAffinity.trailing, title: Text("PESSOA FISICA"), value: "FISICA", groupValue: p.tipoPessoa == null ? p.tipoPessoa = tipoPessoa : p.tipoPessoa, onChanged: (String valor) { setState(() { p.tipoPessoa = valor; print("resultado: " + p.tipoPessoa); }); }, ), RadioListTile( controlAffinity: ListTileControlAffinity.trailing, title: Text("PESSOA JURIDICA"), value: "JURIDICA", groupValue: p.tipoPessoa == null ? p.tipoPessoa = tipoPessoa : p.tipoPessoa, onChanged: (String valor) { setState(() { p.tipoPessoa = valor; print("resultado: " + p.tipoPessoa); }); }, ), ], ), ], ), ), ), SizedBox(height: 10), Container( padding: EdgeInsets.all(5), child: Container( decoration: BoxDecoration( border: Border.all(color: Colors.grey), borderRadius: BorderRadius.circular(5), ), padding: EdgeInsets.all(5), child: Column( children: <Widget>[ SizedBox(height: 15), Text("Genero sexual"), Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ RadioListTile( controlAffinity: ListTileControlAffinity.trailing, title: Text("MASCULINO"), value: "MASCULINO", groupValue: p.sexo == null? p.sexo = sexo : p.sexo, onChanged: (String valor) { setState(() { p.sexo = valor; print("sexo: " + p.sexo); }); }, ), RadioListTile( controlAffinity: ListTileControlAffinity.trailing, title: Text("FEMININO"), value: "FEMININO", groupValue: p.sexo == null? p.sexo = sexo : p.sexo, onChanged: (String valor) { setState(() { p.sexo = valor; print("sexo: " + p.sexo); }); }, ), RadioListTile( controlAffinity: ListTileControlAffinity.trailing, title: Text("OUTRO"), value: "OUTRO", groupValue: p.sexo == null? p.sexo = sexo : p.sexo, onChanged: (String valor) { setState(() { p.sexo = valor; print("sexo: " + p.sexo); }); }, ), ], ), ], ), ), ), SizedBox(height: 10), Container( padding: EdgeInsets.all(5), child: Column( children: <Widget>[ TextFormField( initialValue: p.nome, onSaved: (value) => p.nome = value, validator: (value) => value.isEmpty? "Preencha o nome completo" : null, decoration: InputDecoration( labelText: "Nome completo", hintText: "nome", prefixIcon: Icon(Icons.people, color: Colors.grey), suffixIcon: Icon(Icons.close), contentPadding: EdgeInsets.fromLTRB(20.0, 20.0, 20.0, 20.0), border: OutlineInputBorder( borderRadius: BorderRadius.circular(5.0)), focusedBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.lime[900]), gapPadding: 1, borderRadius: BorderRadius.circular(5.0), ), ), onEditingComplete: () => focus.nextFocus(), keyboardType: TextInputType.text, maxLength: 50, ), SizedBox(height: 10), TextFormField( initialValue: p.cpf, onSaved: (value) => p.cpf = value, validator: (value) => value.isEmpty? "Preencha o cpf" : null, decoration: InputDecoration( labelText: "cpf", hintText: "cpf", prefixIcon: Icon(Icons.contact_mail, color: Colors.grey), suffixIcon: Icon(Icons.close), contentPadding: EdgeInsets.fromLTRB(20.0, 20.0, 20.0, 20.0), border: OutlineInputBorder( borderRadius: BorderRadius.circular(5.0)), focusedBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.lime[900]), gapPadding: 1, borderRadius: BorderRadius.circular(5.0), ), ), onEditingComplete: () => focus.nextFocus(), inputFormatters: [maskFormatterCPF], keyboardType: TextInputType.number, maxLength: 14, ), SizedBox(height: 10), TextFormField( initialValue: p.telefone, onSaved: (value) => p.telefone = value, validator: (value) => value.isEmpty? "Preencha o telefone" : null, decoration: InputDecoration( labelText: "Telefone", hintText: "Telefone celular", prefixIcon: Icon(Icons.phone, color: Colors.grey), suffixIcon: Icon(Icons.close), contentPadding: EdgeInsets.fromLTRB(20.0, 20.0, 20.0, 20.0), border: OutlineInputBorder( borderRadius: BorderRadius.circular(5.0)), focusedBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.lime[900]), gapPadding: 1, borderRadius: BorderRadius.circular(5.0), ), ), onEditingComplete: () => focus.nextFocus(), keyboardType: TextInputType.phone, inputFormatters: [maskFormatterCelular], maxLength: 50, ), SizedBox(height: 10), DateTimeField( initialValue: p.dataRegistro, format: dateFormat, validator: validateDateRegsitro, onSaved: (value) => p.dataRegistro = value, decoration: InputDecoration( labelText: "data registro", hintText: "99-09-9999", prefixIcon: Icon( Icons.calendar_today, color: Colors.grey, ), suffixIcon: Icon(Icons.close), contentPadding: EdgeInsets.fromLTRB(20.0, 20.0, 20.0, 20.0), border: OutlineInputBorder( borderRadius: BorderRadius.circular(5.0)), focusedBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.purple[900]), gapPadding: 1, borderRadius: BorderRadius.circular(5.0), ), ), onEditingComplete: () => focus.nextFocus(), onShowPicker: (context, currentValue) { return showDatePicker( context: context, firstDate: DateTime(2000), initialDate: currentValue?? DateTime.now(), locale: Locale('pt', 'BR'), lastDate: DateTime(2030), ); }, maxLength: 10, ), SizedBox(height: 10), TextFormField( initialValue: p.usuario.email, onSaved: (value) => p.usuario.email = value, validator: validateEmail, decoration: InputDecoration( labelText: "Email", hintText: "Email", prefixIcon: Icon(Icons.email, color: Colors.grey), suffixIcon: Icon(Icons.close), contentPadding: EdgeInsets.fromLTRB(20.0, 20.0, 20.0, 20.0), border: OutlineInputBorder( borderRadius: BorderRadius.circular(5.0)), focusedBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.lime[900]), gapPadding: 1, borderRadius: BorderRadius.circular(5.0), ), ), onEditingComplete: () => focus.nextFocus(), keyboardType: TextInputType.emailAddress, maxLength: 50, ), SizedBox(height: 10), TextFormField( controller: senhaController, onSaved: (value) => p.usuario.senha = value, validator: validateSenha, decoration: InputDecoration( labelText: "Senha", hintText: "Senha", prefixIcon: Icon(Icons.security, color: Colors.grey), suffixIcon: IconButton( icon: clienteController.senhaVisivel == true ? Icon(Icons.visibility_outlined, color: Colors.grey) : Icon(Icons.visibility_off_outlined, color: Colors.grey), onPressed: () { clienteController.visualizarSenha(); }, ), contentPadding: EdgeInsets.fromLTRB(20.0, 20.0, 20.0, 20.0), border: OutlineInputBorder( borderRadius: BorderRadius.circular(5.0), ), focusedBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.lime[900]), gapPadding: 1, borderRadius: BorderRadius.circular(5.0), ), ), onEditingComplete: () => focus.nextFocus(), keyboardType: TextInputType.text, obscureText:!clienteController.senhaVisivel, maxLength: 8, ), SizedBox(height: 10), TextFormField( controller: confirmaSenhaController, validator: validateSenha, decoration: InputDecoration( labelText: "<NAME>", hintText: "Confirma senha", prefixIcon: Icon(Icons.security, color: Colors.grey), suffixIcon: IconButton( icon: clienteController.senhaVisivel == true ? Icon(Icons.visibility_outlined, color: Colors.grey) : Icon(Icons.visibility_off_outlined, color: Colors.grey), onPressed: () { clienteController.visualizarSenha(); }, ), contentPadding: EdgeInsets.fromLTRB(20.0, 20.0, 20.0, 20.0), border: OutlineInputBorder( borderRadius: BorderRadius.circular(5.0)), focusedBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.lime[900]), gapPadding: 1, borderRadius: BorderRadius.circular(5.0), ), ), onEditingComplete: () => focus.nextFocus(), keyboardType: TextInputType.text, obscureText:!clienteController.senhaVisivel, maxLength: 8, ), ], ), ), SizedBox(height: 0), ], ), ), ), SizedBox(height: 0), Container( padding: EdgeInsets.all(15), child: RaisedButton.icon( label: Text("Enviar formulário"), icon: Icon(Icons.check), onPressed: () { if (controller.validate()) { if (p.id == null) { if (senhaController.text!= confirmaSenhaController.text) { showSnackbar(context, "senha diferentes"); print("senha diferentes"); } else { dialogs.information(context, "prepando para o cadastro..."); Timer(Duration(seconds: 3), () { print("Pessoa: ${p.tipoPessoa}"); print("Nome: ${p.nome}"); print("CPF: ${p.cpf}"); print("Telefone: ${p.telefone}"); print("DataRegistro: ${p.dataRegistro}"); print("Email: ${p.usuario.email}"); print("Senha: ${p.usuario.senha}"); clienteController.create(p).then((value) { print("resultado : ${value}"); }); buildPush(context); }); } } else { if (p.usuario.senha == p.usuario.confirmaSenha) { showSnackbar(context, "senha diferentes"); print("senha diferentes"); } else { dialogs.information( context, "preparando para o alteração..."); Timer(Duration(seconds: 3), () { print("Pessoa: ${p.tipoPessoa}"); print("Nome: ${p.nome}"); print("CPF: ${p.cpf}"); print("Telefone: ${p.telefone}"); print("DataRegistro: ${p.dataRegistro}"); print("Email: ${p.usuario.email}"); print("Senha: ${p.usuario.senha}"); clienteController.update(p.id, p); buildPush(context); }); } } } }, ), ), SizedBox(height: 10), Container( padding: EdgeInsets.all(10), child: Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ Text("Já tem uma conta? "), GestureDetector( child: Text( "Entrar", style: TextStyle( color: Colors.blue, decoration: TextDecoration.underline, ), ), onTap: () { Navigator.of(context).push( MaterialPageRoute( builder: (BuildContext context) { return UsuarioLoginPage(); }, ), ); }, ) ], ), ), SizedBox(height: 20), ], ); } buildPush(BuildContext context) { Navigator.of(context).pop(); return Navigator.push( context, MaterialPageRoute( builder: (context) => ClientePage(), ), ); } confirmaSenha() { print("senha diferentes"); } } class Controller { var formKey = GlobalKey<FormState>(); bool validate() { var form = formKey.currentState; if (form.validate()) { form.save(); return true; } else return false; } } ======================= File: lib/src/util/dropdown/dropdown_cor.dart ======================= <reponame>ofertasbv/ofertaflutterweb import 'package:flutter/material.dart'; import 'package:flutter_mobx/flutter_mobx.dart'; import 'package:get_it/get_it.dart'; import 'package:nosso/src/core/controller/produto_controller.dart'; import 'package:nosso/src/core/model/cor.dart'; import 'package:nosso/src/util/dialogs/dialog_cor.dart'; class DropDownCor extends StatelessWidget { List<Cor> cores; DropDownCor(this.cores); @override Widget build(BuildContext context) { var produtoController = GetIt.I.get<ProdutoController>(); AlertCor alertCor = AlertCor(); return Observer( builder: (context) { List<Cor> cores = produtoController.corSelecionadas; return Container( padding: EdgeInsets.all(15), child: Container( decoration: BoxDecoration( border: Border.all(color: Colors.grey), borderRadius: BorderRadius.circular(5), ), child: ListTile( title: Text("Cores *"), subtitle: cores.isEmpty ? Text("Selecione cores") : Text("${cores.map((e) => e.descricao)}"), leading: Icon(Icons.list_alt_outlined), trailing: Icon(Icons.arrow_drop_down_sharp), onTap: () { alertCor.alert(context, cores); }, ), ), ); }, ); } } ======================= File: lib/src/core/repository/promocao_repository.dart ======================= <gh_stars>0 import 'dart:io'; import 'package:dio/dio.dart'; import 'package:nosso/src/api/constants/constant_api.dart'; import 'package:nosso/src/api/dio/custon_dio.dart'; import 'package:nosso/src/core/model/promocao.dart'; class PromocaoRepository { CustonDio dio = CustonDio(); Future<List<Promocao>> getAll() async { try { print("carregando promoções"); var response = await dio.client.get("/promocoes"); return (response.data as List).map((c) => Promocao.fromJson(c)).toList(); } on DioError catch (e) { print(e.message); } return null; } Future<List<Promocao>> getAllById(int id) async { try { print("carregando promoções by id"); var response = await dio.client.get("/promocoes/${id}"); return (response.data as List).map((c) => Promocao.fromJson(c)).toList(); } on DioError catch (e) { print(e.message); } return null; } Future<List<Promocao>> getAllByNome(String nome) async { try { print("carregando promoções by nome"); var response = await dio.client.get("/promocoes/nome/${nome}"); return (response.data as List).map((c) => Promocao.fromJson(c)).toList(); } on DioError catch (e) { print(e.message); } return null; } Future<List<Promocao>> getAllByLojaById(int id) async { try { print("carregando promocoes da loja"); var response = await dio.client.get("/promocoes/loja/$id"); return (response.data as List).map((c) => Promocao.fromJson(c)).toList(); } on DioError catch (e) { print(e.message); } return null; } Future<int> create(Map<String, dynamic> data) async { var response = await dio.client.post("/promocoes/create", data: data); return response.statusCode; } Future<int> update(int id, Map<String, dynamic> data) async { var response = await dio.client.put("/promocoes/update/$id", data: data); return response.statusCode; } Future<void> deleteFoto(String foto) async { try { var response = await dio.client.delete("/promocoes/delete/foto/$foto"); return response.statusCode; } on DioError catch (e) { throw (e.message); } } Future<String> upload(File file, String fileName) async { var arquivo = file.path; var paramentros = { "foto": await MultipartFile.fromFile(arquivo, filename: fileName) }; FormData formData = FormData.fromMap(paramentros); var response = await dio.client .post(ConstantApi.urlList + "/promocoes/upload", data: formData); return response.toString(); } } ======================= File: lib/src/core/model/content.dart ======================= <reponame>ofertasbv/ofertaflutterweb import 'package:nosso/src/core/model/arquivo.dart'; import 'package:nosso/src/core/model/cor.dart'; import 'package:nosso/src/core/model/estoque.dart'; import 'package:nosso/src/core/model/loja.dart'; import 'package:nosso/src/core/model/marca.dart'; import 'package:nosso/src/core/model/promocao.dart'; import 'package:nosso/src/core/model/subcategoria.dart'; import 'package:nosso/src/core/model/tamanho.dart'; class Content { int id; String sku; String nome; String descricao; String foto; DateTime dataRegistro; String codigoBarra; bool status; bool novo; bool destaque; String medida; String origem; double valorTotal; SubCategoria subCategoria; Promocao promocao; Loja loja; List<Arquivo> arquivos = List<Arquivo>(); List<Tamanho> tamanhos = List<Tamanho>(); List<Cor> cores = List<Cor>(); Estoque estoque = Estoque(); Marca marca; Content( {this.id, this.sku, this.nome, this.descricao, this.foto, this.dataRegistro, this.codigoBarra, this.status, this.novo, this.destaque, this.medida, this.origem, this.valorTotal, this.subCategoria, this.promocao, this.loja, this.arquivos, this.tamanhos, this.cores, this.estoque, this.marca}); Content.fromJson(Map<String, dynamic> json) { id = json['id']; sku = json['sku']; nome = json['nome']; descricao = json['descricao']; foto = json['foto']; dataRegistro = DateTime.tryParse(json['dataRegistro'].toString()); codigoBarra = json['codigoBarra']; status = json['status']; novo = json['novo']; destaque = json['destaque']; medida = json['medida']; origem = json['origem']; valorTotal = json['valorTotal']; subCategoria = json['subCategoria']!= null ? new SubCategoria.fromJson(json['subCategoria']) : null; promocao = json['promocao']!= null ? new Promocao.fromJson(json['promocao']) : null; loja = json['loja']!= null? new Loja.fromJson(json['loja']) : null; if (json['arquivos']!= null) { arquivos = new List<Arquivo>(); json['arquivos'].forEach((v) { arquivos.add(new Arquivo.fromJson(v)); }); } if (json['tamanhos']!= null) { tamanhos = new List<Tamanho>(); json['tamanhos'].forEach((v) { tamanhos.add(new Tamanho.fromJson(v)); }); } if (json['cores']!= null) { cores = new List<Cor>(); json['cores'].forEach((v) { cores.add(new Cor.fromJson(v)); }); } estoque = json['estoque']!= null? new Estoque.fromJson(json['estoque']) : null; marca = json['marca']!= null? new Marca.fromJson(json['marca']) : null; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['id'] = this.id; data['sku'] = this.sku; data['nome'] = this.nome; data['descricao'] = this.descricao; data['foto'] = this.foto; data['dataRegistro'] = this.dataRegistro.toIso8601String(); data['codigoBarra'] = this.codigoBarra; data['status'] = this.status; data['novo'] = this.novo; data['destaque'] = this.destaque; data['medida'] = this.medida; data['origem'] = this.origem; data['valorTotal'] = this.valorTotal; if (this.subCategoria!= null) { data['subCategoria'] = this.subCategoria.toJson(); } if (this.promocao!= null) { data['promocao'] = this.promocao.toJson(); } if (this.loja!= null) { data['loja'] = this.loja.toJson(); } if (this.arquivos!= null) { data['arquivos'] = this.arquivos.map((v) => v.toJson()).toList(); } if (this.tamanhos!= null) { data['tamanhos'] = this.tamanhos.map((v) => v.toJson()).toList(); } if (this.cores!= null) { data['cores'] = this.cores.map((v) => v.toJson()).toList(); } if (this.estoque!= null) { data['estoque'] = this.estoque.toJson(); } if (this.marca!= null) { data['marca'] = this.marca.toJson(); } return data; } } ======================= File: lib/src/paginas/loja/loja_list.dart ======================= <gh_stars>0 import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter_mobx/flutter_mobx.dart'; import 'package:get_it/get_it.dart'; import 'package:nosso/src/core/controller/loja_controller.dart'; import 'package:nosso/src/core/model/loja.dart'; import 'package:nosso/src/paginas/loja/loja_detalhes_tab.dart'; import 'package:nosso/src/util/container/container_loja.dart'; import 'package:nosso/src/util/load/circular_progresso.dart'; class LojaList extends StatefulWidget { @override _LojaListState createState() => _LojaListState(); } class _LojaListState extends State<LojaList> with AutomaticKeepAliveClientMixin<LojaList> { var lojaController = GetIt.I.get<LojaController>(); var nomeController = TextEditingController(); @override void initState() { lojaController.getAll(); super.initState(); } Future<void> onRefresh() { return lojaController.getAll(); } filterByNome(String nome) { if (nome.trim().isEmpty) { lojaController.getAll(); } else { nome = nomeController.text; lojaController.getAllByNome(nome); } } bool isLoading = true; @override Widget build(BuildContext context) { return Container( width: double.infinity, height: double.infinity, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ SizedBox(height: 0), Container( height: 80, width: double.infinity, color: Colors.grey[100], padding: EdgeInsets.all(5), child: ListTile( subtitle: TextFormField( controller: nomeController, decoration: InputDecoration( labelText: "busca por lojas", prefixIcon: Icon(Icons.search_outlined), suffixIcon: IconButton( onPressed: () => nomeController.clear(), icon: Icon(Icons.clear), ), ), onChanged: filterByNome, ), ), ), Expanded( child: Container( color: Colors.transparent, child: builderConteudoList(), ), ), ], ), ); } builderConteudoList() { return Container( padding: EdgeInsets.only(top: 0), child: Observer( builder: (context) { List<Loja> lojas = lojaController.lojas; if (lojaController.error!= null) { return Text("Não foi possível carregados dados"); } if (lojas == null) { return CircularProgressor(); } return RefreshIndicator( onRefresh: onRefresh, child: builderList(lojas), ); }, ), ); } ListView builderList(List<Loja> lojas) { double containerWidth = 160; double containerHeight = 30; return ListView.builder( itemCount: lojas.length, itemBuilder: (context, index) { Loja p = lojas[index]; return GestureDetector( child: Padding( padding: EdgeInsets.symmetric(vertical: 0), child: ContainerLoja(lojaController, p), ), onTap: () { Navigator.of(context).push( MaterialPageRoute( builder: (BuildContext context) { return LojaDetalhesTab(p); }, ), ); }, ); }, ); } @override // TODO: implement wantKeepAlive bool get wantKeepAlive => true; } ======================= File: lib/src/core/controller/pedidoItem_controller.dart ======================= <gh_stars>0 import 'package:dio/dio.dart'; import 'package:mobx/mobx.dart'; import 'package:nosso/src/core/model/pedidoitem.dart'; import 'package:nosso/src/core/model/produto.dart'; import 'package:nosso/src/core/repository/pedidoItem_repository.dart'; part 'pedidoItem_controller.g.dart'; class PedidoItemController = PedidoItemControllerBase with _$PedidoItemController; abstract class PedidoItemControllerBase with Store { PedidoItemRepository _pedidoItemRepository; PedidoItemControllerBase() { _pedidoItemRepository = PedidoItemRepository(); } @observable int quantidade = 0; @observable double valorUnitario = 0; @observable double valorTotal = 0; @observable double desconto = 0; @observable double total = 0; @observable double totalDesconto = 0; @observable List<PedidoItem> pedidoItens; @observable List<PedidoItem> itens = List<PedidoItem>(); @observable int pedidoitem; @observable Exception error; @observable DioError dioError; @observable String mensagem; @action List<PedidoItem> pedidosItens() { try { return itens; } catch (e) { error = e; } } @action Future<List<PedidoItem>> getAll() async { try { pedidoItens = await _pedidoItemRepository.getAll(); return pedidoItens; } catch (e) { error = e; } } @action Future<int> create(PedidoItem p) async { try { pedidoitem = await _pedidoItemRepository.create(p.toJson()); if (pedidoitem == null) { mensagem = "sem dados"; } else { return pedidoitem; } } on DioError catch (e) { mensagem = e.message; dioError = e; } } @action Future<int> update(int id, PedidoItem p) async { try { pedidoitem = await _pedidoItemRepository.update(id, p.toJson()); return pedidoitem; } on DioError catch (e) { mensagem = e.message; dioError = e; } } @action adicionar(PedidoItem item) { item.quantidade = quantidade; print("Qunatidade: ${item.quantidade}"); if (item.quantidade > 0) { item.valorUnitario = item.produto.estoque.valorUnitario; item.valorTotal = item.quantidade * item.valorUnitario; itens.add(item); calculateTotal(); } } @action isExiste(Produto p) { var result = false; for (PedidoItem p in itens) { if (p.produto.id == p.id) { return result = true; } } return result; } @action isExisteItem(PedidoItem item) { var result = false; for (PedidoItem p in itens) { if (item.produto.nome == p.produto.nome) { return result = true; } } return result; } @action incremento(PedidoItem item) { if (item.quantidade < 10) { item.quantidade++; } calculateTotal(); } @action decremento(PedidoItem item) { if (item.quantidade > 1) { item.quantidade--; } calculateTotal(); } @action remove(PedidoItem item) { itens.remove(item); calculateTotal(); } @action calculateTotal() { this.total = 0.0; itens.forEach((p) { total += p.valorTotal; }); return total; } @action calculateDesconto() { this.totalDesconto = total - desconto; return totalDesconto; } } ======================= File: lib/src/core/controller/estado_controller.dart ======================= <gh_stars>0 import 'package:dio/dio.dart'; import 'package:mobx/mobx.dart'; import 'package:nosso/src/core/model/estado.dart'; import 'package:nosso/src/core/repository/estado_repository.dart'; part 'estado_controller.g.dart'; class EstadoController = EstadoControllerBase with _$EstadoController; abstract class EstadoControllerBase with Store { EstadoRepository estadoRepository; EstadoControllerBase() { estadoRepository = EstadoRepository(); } @observable List<Estado> estados; @observable int estado; @observable Exception error; @observable DioError dioError; @observable String mensagem; @action Future<List<Estado>> getAll() async { try { estados = await estadoRepository.getAll(); return estados; } catch (e) { error = e; } } @action Future<int> create(Estado p) async { try { estado = await estadoRepository.create(p.toJson()); if (estado == null) { mensagem = "sem dados"; } else { return estado; } } on DioError catch (e) { mensagem = e.message; dioError = e; } } @action Future<int> update(int id, Estado p) async { try { estado = await estadoRepository.update(id, p.toJson()); return estado; } on DioError catch (e) { mensagem = e.message; dioError = e; } } } ======================= File: lib/src/util/buttons/simple_round_only_icon_button.dart ======================= <gh_stars>0 import 'package:flutter/material.dart'; class SimpleRoundOnlyIconButton extends StatelessWidget { final Color backgroundColor; final Icon icon; final Color iconColor; final Alignment iconAlignment; final Function onPressed; SimpleRoundOnlyIconButton( {this.backgroundColor = Colors.redAccent, this.icon, this.iconColor, this.iconAlignment = Alignment.center, this.onPressed}); MainAxisAlignment getMainAxisAlignment() { if (this.iconAlignment == Alignment.center) { return MainAxisAlignment.center; } else if (this.iconAlignment == Alignment.centerLeft) { return MainAxisAlignment.start; } else if (this.iconAlignment == Alignment.centerRight) { return MainAxisAlignment.end; } return MainAxisAlignment.center; } @override Widget build(BuildContext context) { return Container( margin: const EdgeInsets.only(top: 20.0), padding: const EdgeInsets.only(left: 20.0, right: 20.0), child: new Row( children: <Widget>[ new Expanded( child: FlatButton( shape: new RoundedRectangleBorder( borderRadius: new BorderRadius.circular(30.0)), splashColor: this.backgroundColor, color: this.backgroundColor, child: new Row( mainAxisAlignment: getMainAxisAlignment(), children: <Widget>[ iconAlignment == Alignment.center ? new Transform.translate( offset: Offset(0.0, 0.0), child: new Container( padding: const EdgeInsets.only( left: 5.0, right: 5.0, top: 10.0, bottom: 10.0), child: FlatButton( shape: new RoundedRectangleBorder( borderRadius: new BorderRadius.circular(28.0)), splashColor: backgroundColor, color: backgroundColor, child: Icon( icon.icon, color: iconColor == null ? Colors.white : iconColor, ), onPressed: () => {}, ), ), ) : Container(), iconAlignment == Alignment.centerLeft ? new Transform.translate( offset: Offset(-10.0, 0.0), child: new Container( padding: const EdgeInsets.only( left: 5.0, right: 5.0, top: 10.0, bottom: 10.0), child: FlatButton( shape: new RoundedRectangleBorder( borderRadius: new BorderRadius.circular(28.0)), splashColor: Colors.white, color: Colors.white, child: Icon( icon.icon, color: iconColor == null ? Colors.white : iconColor, ), onPressed: () => {}, ), ), ) : Container(), iconAlignment == Alignment.centerRight || iconAlignment == Alignment.centerLeft ? Expanded( child: Container(), ) : Container(), iconAlignment == Alignment.centerRight ? new Transform.translate( offset: Offset(10.0, 0.0), child: new Container( padding: const EdgeInsets.only( left: 5.0, right: 5.0, top: 10.0, bottom: 10.0), child: FlatButton( shape: new RoundedRectangleBorder( borderRadius: new BorderRadius.circular(28.0)), splashColor: Colors.white, color: Colors.white, child: Icon( icon.icon, color: this.iconColor, ), onPressed: () => {}, ), ), ) : Container() ], ), onPressed: onPressed, ), ), ], ), ); } } ======================= File: lib/src/core/enum/caixa_status.dart ======================= enum CaixaStatus { ABERTO, FECHADO, } ======================= File: lib/src/paginas/loja/loja_location.dart ======================= import 'dart:async'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_mobx/flutter_mobx.dart'; import 'package:fluttertoast/fluttertoast.dart'; import 'package:get_it/get_it.dart'; import 'package:google_maps_flutter/google_maps_flutter.dart'; import 'package:nosso/src/api/constants/constant_api.dart'; import 'package:nosso/src/core/controller/loja_controller.dart'; import 'package:nosso/src/core/model/loja.dart'; import 'package:nosso/src/paginas/loja/loja_detalhes_tab.dart'; import 'package:nosso/src/paginas/loja/loja_page.dart'; class LojaLocation extends StatefulWidget { @override _LojaLocationState createState() => _LojaLocationState(); } class _LojaLocationState extends State<LojaLocation> { var lojaController = GetIt.I.get<LojaController>(); var loja = Loja(); var selectedCard = 'WEIGHT'; Completer<GoogleMapController> completer = Completer<GoogleMapController>(); List<Marker> allMarkers = []; @override void initState() { super.initState(); lojaController.getAll(); } selectCard(cardTitle) { setState(() { selectedCard = cardTitle; }); } MapType mapType = MapType.normal; static const LatLng center = const LatLng(-4.253467, -49.944051); LatLng lastMapPosition = center; button(Function function, IconData icon) { return FloatingActionButton( onPressed: function, materialTapTargetSize: MaterialTapTargetSize.padded, child: Icon(icon, size: 36), ); } onMapTypeButtonPressedNormal() { setState(() { mapType = MapType.normal; }); } onMapTypeButtonPressedTerra() { setState(() { mapType = MapType.terrain; }); } onMapTypeButtonPressedSatelite() { setState(() { mapType = MapType.satellite; }); } onMapTypeButtonPressedHibrido() { setState(() { mapType = MapType.hybrid; }); } onCamaraMove(CameraPosition position) { lastMapPosition = position.target; } criarMapa(GoogleMapController controller) { completer.complete(controller); } markers(Loja p) { return Marker( markerId: MarkerId(p.nome), position: LatLng(p.enderecos[0].latitude, p.enderecos[0].longitude), infoWindow: InfoWindow(title: p.nome, snippet: p.enderecos[0].logradouro), icon: BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueOrange), ); } static final CameraPosition posicaoCamera = CameraPosition( bearing: 192.833, target: LatLng(-4.253467, -49.944051), tilt: 54, zoom: 14.0, ); movimentarCamera(double latitude, double longitude) async { GoogleMapController googleMapController = await completer.future; googleMapController.animateCamera( CameraUpdate.newCameraPosition( CameraPosition( target: LatLng(latitude, longitude), zoom: 18.0, tilt: 30, ), ), ); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("Localzação comercial"), ), body: Stack( fit: StackFit.expand, children: <Widget>[ Container( height: double.infinity, padding: EdgeInsets.only(top: 0), child: Observer( builder: (context) { List<Loja> lojas = lojaController.lojas; if (lojaController.error!= null) { return Text("Não foi possível buscar lojas"); } if (lojas == null) { return GoogleMap( onTap: (valor) { print("Lat: ${valor.latitude}, Long: ${valor.longitude}"); }, indoorViewEnabled: true, mapToolbarEnabled: true, buildingsEnabled: true, tiltGesturesEnabled: true, zoomGesturesEnabled: true, myLocationEnabled: true, myLocationButtonEnabled: true, rotateGesturesEnabled: true, trafficEnabled: false, onCameraMove: onCamaraMove, mapType: mapType, onMapCreated: criarMapa, initialCameraPosition: CameraPosition( target: lastMapPosition, zoom: 13, tilt: 54), ); } allMarkers = lojas.map((p) { return Marker( icon: BitmapDescriptor.defaultMarkerWithHue( BitmapDescriptor.hueYellow), infoWindow: InfoWindow( title: p.nome, snippet: p.enderecos[0].logradouro + ", " + p.enderecos[0].numero, ), markerId: MarkerId(p.nome), position: LatLng(p.enderecos[0].latitude?? 0.0, p.enderecos[0].longitude?? 0.0), onTap: () { showDialogAlert(context, p); }); }).toList(); return GoogleMap( onTap: (valor) { print("Lat: ${valor.latitude}, Long: ${valor.longitude}"); }, indoorViewEnabled: true, mapToolbarEnabled: true, buildingsEnabled: true, tiltGesturesEnabled: true, zoomGesturesEnabled: true, myLocationEnabled: true, myLocationButtonEnabled: true, rotateGesturesEnabled: true, trafficEnabled: false, onCameraMove: onCamaraMove, mapType: mapType, onMapCreated: criarMapa, initialCameraPosition: CameraPosition( target: lastMapPosition, zoom: 16.0, tilt: 54), markers: Set.of(allMarkers), ); }, ), ), Padding( padding: EdgeInsets.only(top: 60, right: 10), child: Align( alignment: Alignment.topRight, child: Column( children: <Widget>[ FloatingActionButton( onPressed: () { showDialogAlertTypeMap(context); }, materialTapTargetSize: MaterialTapTargetSize.shrinkWrap, child: Icon( Icons.map, size: 25, ), tooltip: "tipo de mapa", focusElevation: 5, mini: true, ), ], ), ), ), Align( alignment: Alignment.bottomCenter, child: Container( height: 110, color: Colors.transparent, padding: EdgeInsets.all(2), margin: EdgeInsets.only(bottom: 0), child: Observer( builder: (context) { List<Loja> lojas = lojaController.lojas; if (lojaController.error!= null) { return Text("Não foi possível buscar lojas"); } if (lojas == null) { return Center( child: Text("não foi possível carregar lojas"), ); } return builderList(lojas); }, ), ), ), ], ), ); } builderList(List<Loja> lojas) { return ListView.builder( scrollDirection: Axis.horizontal, itemCount: lojas.length, itemBuilder: (context, index) { Loja p = lojas[index]; return GestureDetector( child: AnimatedContainer( duration: Duration(seconds: 1), decoration: BoxDecoration( color: p.nome == selectedCard? Colors.yellow[200] : Colors.white, borderRadius: BorderRadius.circular(10), ), width: 240, padding: EdgeInsets.all(2), margin: EdgeInsets.only(left: 10), child: Row( children: <Widget>[ AspectRatio( aspectRatio: 0.9, child: ClipRRect( borderRadius: BorderRadius.circular(10), child: Image.network( ConstantApi.urlArquivoProduto + p.foto, fit: BoxFit.cover, ), ), ), Expanded( child: Container( padding: EdgeInsets.all(5), child: ListTile( title: Text(p.nome), subtitle: Text(p.telefone), ), ), ), ], ), ), onTap: () { selectCard(p.nome); movimentarCamera( p.enderecos[0].latitude, p.enderecos[0].longitude, ); }, ); }, ); } showDialogAlert(BuildContext context, Loja p) async { return showDialog( context: context, barrierDismissible: false, // user must tap button for close dialog! builder: (BuildContext context) { return AlertDialog( title: Text('Localização'), content: Container( height: 200, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text("${p.nome}"), Text("${p.enderecos[0].logradouro}, ${p.enderecos[0].numero}"), ], ), ), actions: <Widget>[ FlatButton( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(0), side: BorderSide(color: Colors.grey), ), color: Colors.white, textColor: Colors.grey, padding: EdgeInsets.all(10), child: const Text('CANCELAR'), onPressed: () { Navigator.of(context).pop(); }, ), FlatButton( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(0), side: BorderSide(color: Colors.blue), ), color: Colors.white, textColor: Colors.blue, padding: EdgeInsets.all(10), child: const Text('DETALHES'), onPressed: () { Navigator.of(context).push( MaterialPageRoute( builder: (BuildContext context) { return LojaDetalhesTab(p); }, ), ); }, ), ], ); }, ); } showDialogAlertTypeMap(BuildContext context) async { return showDialog( context: context, barrierDismissible: false, // user must tap button for close dialog! builder: (BuildContext context) { return AlertDialog( title: Text('Tipo de mapa'), content: Container( height: 200, width: double.infinity, child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ GestureDetector( child: Container( child: Column( children: <Widget>[ ClipRRect( borderRadius: BorderRadius.circular(10), child: Image.asset( ConstantApi.urlNormal, fit: BoxFit.cover, height: 60, width: 60, ), ), Text("Padrão"), ], ), ), onTap: () { onMapTypeButtonPressedNormal(); Navigator.of(context).pop(); }, ), GestureDetector( child: Container( child: Column( children: <Widget>[ ClipRRect( borderRadius: BorderRadius.circular(10), child: Image.asset( ConstantApi.urlSatelite, fit: BoxFit.cover, height: 60, width: 60, ), ), Text("Satélite"), ], ), ), onTap: () { onMapTypeButtonPressedSatelite(); Navigator.of(context).pop(); }, ), GestureDetector( child: Container( child: Column( children: <Widget>[ ClipRRect( borderRadius: BorderRadius.circular(10), child: Image.asset( ConstantApi.urlRelevo, fit: BoxFit.cover, height: 60, width: 60, ), ), Text( "Híbrido", ), ], ), ), onTap: () { onMapTypeButtonPressedHibrido(); Navigator.of(context).pop(); }, ), ], ), ), actions: <Widget>[ FlatButton( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(0), side: BorderSide(color: Colors.grey), ), color: Colors.white, textColor: Colors.grey, padding: EdgeInsets.all(10), child: const Text('CANCELAR'), onPressed: () { Navigator.of(context).pop(); }, ), ], ); }, ); } buildPush(BuildContext context) { return Navigator.push( context, MaterialPageRoute( builder: (context) => LojaPage(), ), ); } } ======================= File: lib/src/util/dialogs/dialog_tamanho.dart ======================= <filename>lib/src/util/dialogs/dialog_tamanho.dart<gh_stars>0 import 'package:flutter/material.dart'; import 'package:flutter_mobx/flutter_mobx.dart'; import 'package:get_it/get_it.dart'; import 'package:nosso/src/core/controller/produto_controller.dart'; import 'package:nosso/src/core/controller/tamanho_controller.dart'; import 'package:nosso/src/core/model/tamanho.dart'; import 'package:nosso/src/util/load/circular_progresso_mini.dart'; class DialogTamanho extends StatefulWidget { @override _DialogTamanhoState createState() => _DialogTamanhoState(); } class _DialogTamanhoState extends State<DialogTamanho> { var tamanhoController = GetIt.I.get<TamanhoController>(); var produtoController = GetIt.I.get<ProdutoController>(); bool clicadoTamanho = false; @override void initState() { tamanhoController.getAll(); super.initState(); } @override Widget build(BuildContext context) { return buildObserverTamanhos(); } onSelectedTamanho(bool selected, Tamanho tamanho) { if (selected == true) { setState(() { produtoController.addTamanhos(tamanho); }); } else { setState(() { produtoController.removerTamanhos(tamanho); }); } } buildObserverTamanhos() { return Observer( builder: (context) { List<Tamanho> tamanhos = tamanhoController.tamanhos; if (tamanhoController.error!= null) { return Text("Não foi possível carregados dados"); } if (tamanhos == null) { return CircularProgressorMini(); } return builderList(tamanhos); }, ); } builderList(List<Tamanho> tamanhos) { double containerWidth = 160; double containerHeight = 20; return ListView.separated( itemCount: tamanhos.length, separatorBuilder: (BuildContext context, int index) => Divider(), itemBuilder: (context, index) { Tamanho c = tamanhos[index]; return CheckboxListTile( value: produtoController.tamanhoSelecionados.contains(tamanhos[index]), onChanged: (bool select) { clicadoTamanho = select; onSelectedTamanho(clicadoTamanho, c); print("Clicado: ${clicadoTamanho} - ${c.descricao}"); for (Tamanho t in produtoController.tamanhoSelecionados) { print("Lista: ${t.descricao}"); } }, title: Text("${c.descricao}"), ); }, ); } } class AlertTamanho { alert(BuildContext context, List<Tamanho> tamanhos) { return showDialog( context: context, builder: (BuildContext context) { return AlertDialog( shape: RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(32.0))), contentPadding: EdgeInsets.only(top: 10.0), content: Container( width: 300.0, child: DialogTamanho(), ), actions: [ FlatButton( onPressed: () { Navigator.pop(context); }, child: Text("ok"), ) ], ); }, ); } } ======================= File: lib/src/paginas/promocaotipo/promocaotipo_page.dart ======================= <gh_stars>0 import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_mobx/flutter_mobx.dart'; import 'package:get_it/get_it.dart'; import 'package:nosso/src/core/controller/promocaotipo_controller.dart'; import 'package:nosso/src/paginas/cor/cor_list.dart'; import 'package:nosso/src/paginas/promocaotipo/promocaotipo_create_page.dart'; class PromocaoTipoPage extends StatelessWidget { var promocaoTipoController = GetIt.I.get<PromocaoTipoController>(); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("Tipos promoções"), actions: <Widget>[ Observer( builder: (context) { if (promocaoTipoController.error!= null) { return Text("Não foi possível carregar"); } if (promocaoTipoController.promocaoTipos == null) { return Center( child: Icon(Icons.warning_amber_outlined), ); } return Chip( label: Text( (promocaoTipoController.promocaoTipos.length?? 0).toString(), ), ); }, ), SizedBox(width: 20), ], ), body: CorList(), floatingActionButton: FloatingActionButton( elevation: 10, child: Icon(Icons.add), onPressed: () { Navigator.pop(context); Navigator.push( context, MaterialPageRoute( builder: (context) { return PromocaoTipoCreatePage(); }, ), ); }, ), ); } } ======================= File: lib/src/util/load/circular_progresso_mini.dart ======================= import 'package:flutter/material.dart'; class CircularProgressorMini extends StatelessWidget { @override Widget build(BuildContext context) { return Center( child: SizedBox( height: 50, width: 50, child: CircularProgressIndicator( strokeWidth: 1.8, backgroundColor: Theme.of(context).primaryColor, valueColor: AlwaysStoppedAnimation<Color>(Colors.black), ), ), ); } } ======================= File: lib/src/paginas/categoria/categoria_list.dart ======================= <filename>lib/src/paginas/categoria/categoria_list.dart import 'dart:async'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_mobx/flutter_mobx.dart'; import 'package:get_it/get_it.dart'; import 'package:nosso/src/core/controller/categoria_controller.dart'; import 'package:nosso/src/core/model/categoria.dart'; import 'package:nosso/src/paginas/categoria/categoria_create_page.dart'; import 'package:nosso/src/paginas/categoria/categoria_subcategoria.dart'; import 'package:nosso/src/util/container/container_categoria.dart'; import 'package:nosso/src/util/load/circular_progresso.dart'; class CategoriaList extends StatefulWidget { @override _CategoriaListState createState() => _CategoriaListState(); } class _CategoriaListState extends State<CategoriaList> with AutomaticKeepAliveClientMixin<CategoriaList> { var categoriaController = GetIt.I.get<CategoriaController>(); @override void initState() { categoriaController.getAll(); super.initState(); } Future<void> onRefresh() { return categoriaController.getAll(); } bool isLoading = true; @override Widget build(BuildContext context) { return builderConteudoList(); } builderConteudoList() { return Container( padding: EdgeInsets.only(top: 0), child: Observer( builder: (context) { List<Categoria> categorias = categoriaController.categorias; if (categoriaController.error!= null) { return Text("Não foi possível carregados dados"); } if (categorias == null) { return CircularProgressor(); } return RefreshIndicator( onRefresh: onRefresh, child: builderList(categorias), ); }, ), ); } builderList(List<Categoria> categorias) { double containerWidth = 160; double containerHeight = 20; return ListView.builder( itemCount: categorias.length, itemBuilder: (context, index) { Categoria c = categorias[index]; return GestureDetector( child: Padding( padding: EdgeInsets.symmetric(vertical: 0), child: ContainerCategoria(categoriaController, c), ), onTap: () { Navigator.of(context).push( MaterialPageRoute( builder: (BuildContext context) { return CategoriaSubCategoria(); }, ), ); }, ); }, ); } @override // TODO: implement wantKeepAlive bool get wantKeepAlive => true; } ======================= File: lib/src/home/promocao_list_home.dart ======================= import 'dart:async'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_mobx/flutter_mobx.dart'; import 'package:get_it/get_it.dart'; import 'package:intl/intl.dart'; import 'package:nosso/src/core/controller/promocao_controller.dart'; import 'package:nosso/src/core/model/loja.dart'; import 'package:nosso/src/core/model/promocao.dart'; import 'package:nosso/src/paginas/promocao/promocao_detalhes_tab.dart'; import 'package:nosso/src/util/load/circular_progresso_mini.dart'; class PromocaoListHome extends StatefulWidget { Loja p; PromocaoListHome({Key key, this.p}) : super(key: key); @override _PromocaoListHomeState createState() => _PromocaoListHomeState(p: this.p); } class _PromocaoListHomeState extends State<PromocaoListHome> with AutomaticKeepAliveClientMixin<PromocaoListHome> { var promocaoController = GetIt.I.get<PromoCaoController>(); var formatMoeda = new NumberFormat("#,##0.00", "pt_BR"); Loja p; _PromocaoListHomeState({this.p}); @override void initState() { promocaoController.getAll(); super.initState(); } Future<void> onRefresh() { return promocaoController.getAll(); } bool isLoading = true; @override Widget build(BuildContext context) { return builderConteudoList(); } builderConteudoList() { return Container( padding: EdgeInsets.only(top: 0), child: Observer( builder: (context) { List<Promocao> promocoes = promocaoController.promocoes; if (promocaoController.error!= null) { return Text("Não foi possível carregados dados"); } if (promocoes == null) { return CircularProgressorMini(); } return RefreshIndicator( onRefresh: onRefresh, child: builderList(promocoes), ); }, ), ); } ListView builderList(List<Promocao> promocoes) { double containerWidth = 350; double containerHeight = 50; return ListView.builder( scrollDirection: Axis.horizontal, itemCount: promocoes.length, itemBuilder: (context, index) { Promocao p = promocoes[index]; return GestureDetector( child: Padding( padding: EdgeInsets.symmetric(horizontal: 2), child: Card( shape: RoundedRectangleBorder( borderRadius: new BorderRadius.circular(10), side: BorderSide(color: Colors.grey[100], width: 1), ), child: AnimatedContainer( width: containerWidth, duration: Duration(seconds: 1), decoration: BoxDecoration( gradient: LinearGradient( colors: [ Colors.grey[100].withOpacity(0.1), Colors.grey[300].withOpacity(0.5), ], begin: Alignment.topLeft, end: Alignment.bottomRight, ), border: Border.all(color: Colors.transparent), borderRadius: BorderRadius.circular(10), ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Container( decoration: BoxDecoration( color: Colors.grey[200], borderRadius: BorderRadius.circular(10), ), child: ClipRRect( borderRadius: BorderRadius.only( topLeft: Radius.circular(10), topRight: Radius.circular(10), bottomRight: Radius.circular(0), bottomLeft: Radius.circular(0), ), child: Image.network( promocaoController.arquivo + p.foto, fit: BoxFit.cover, width: containerWidth, height: 200, ), ), ), SizedBox(height: 0), Container( width: containerWidth, color: Colors.transparent, child: ListTile( title: Text(p.nome), subtitle: Text(p.descricao), trailing: Chip( label: Text("OFF ${formatMoeda.format(p.desconto)}"), ), ), ), ], ), ), ), ), onTap: () { Navigator.of(context).push( MaterialPageRoute( builder: (BuildContext context) { return PromocaoDetalhesTab(p); }, ), ); }, ); }, ); } @override // TODO: implement wantKeepAlive bool get wantKeepAlive => true; } ======================= File: lib/src/api/dio/custom_dio.dart ======================= import 'package:dio/dio.dart'; import 'package:shared_preferences/shared_preferences.dart'; class CustomDio { var _dio; CustomDio() { _dio = Dio(); } CustomDio.withAuthentication() { _dio = Dio(); _dio.interceptors.add(InterceptorsWrapper( onRequest: _onRequest, onResponse: _onRespose, onError: _onError)); } Dio get instance => _dio; _onRequest(RequestOptions options) async { SharedPreferences prefs = await SharedPreferences.getInstance(); var token = prefs.get('token'); options.headers['Authorization'] = token; } _onError(DioError e) { return e; } _onRespose(Response e) { print('########### Response Log'); print(e.data); print('########### Response Log'); } } ======================= File: lib/src/core/repository/arquivo_repository.dart ======================= <reponame>ofertasbv/ofertaflutterweb<gh_stars>0 import 'dart:io'; import 'package:dio/dio.dart'; import 'package:nosso/src/api/constants/constant_api.dart'; import 'package:nosso/src/api/dio/custon_dio.dart'; import 'package:nosso/src/core/model/arquivo.dart'; class ArquivoRepository { CustonDio dio = CustonDio(); Future<List<Arquivo>> getAll() async { try { print("carregando arquivos"); var response = await dio.client.get("/arquivos"); return (response.data as List).map((c) => Arquivo.fromJson(c)).toList(); } on DioError catch (e) { print(e.message); } return null; } Future<List<Arquivo>> getAllById(int id) async { try { print("carregando arquivos by id"); var response = await dio.client.get("/arquivos/${id}"); return (response.data as List).map((c) => Arquivo.fromJson(c)).toList(); } on DioError catch (e) { print(e.message); } return null; } Future<int> create(Map<String, dynamic> data) async { var response = await dio.client.post("/arquivos/create", data: data); return response.statusCode; } Future<int> update(int id, Map<String, dynamic> data) async { var response = await dio.client.put("/arquivos/update/$id", data: data); return response.statusCode; } Future<void> deleteFoto(String foto) async { try { var response = await dio.client.delete("/arquivos/delete/foto/$foto"); return response.statusCode; } on DioError catch (e) { throw (e.message); } } Future<String> upload(File file, String fileName) async { var arquivo = file.path; var paramentros = { "foto": await MultipartFile.fromFile(arquivo, filename: fileName) }; FormData formData = FormData.fromMap(paramentros); var response = await dio.client .post(ConstantApi.urlList + "/arquivos/upload", data: formData); return response.toString(); } } ======================= File: lib/src/util/layout/layout_home.dart ======================= import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:nosso/src/util/layout/home_screen.dart'; class LayoutHomeApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: "Layout home", theme: ThemeData( primarySwatch: Colors.red, primaryColor: Color.fromARGB(255, 4, 125, 141), ), debugShowCheckedModeBanner: false, home: HomeScreen(), ); } } ======================= File: lib/src/core/model/cidade.dart ======================= import 'package:nosso/src/core/model/endereco.dart'; import 'package:nosso/src/core/model/estado.dart'; class Cidade { int id; String nome; Estado estado; List<Endereco> enderecos; Cidade({this.id, this.nome, this.estado, this.enderecos}); Cidade.fromJson(Map<String, dynamic> json) { id = json['id']; nome = json['nome']; estado = json['estado']!= null? new Estado.fromJson(json['estado']) : null; if (json['enderecos']!= null) { enderecos = new List<Endereco>(); json['enderecos'].forEach((v) { enderecos.add(new Endereco.fromJson(v)); }); } } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['id'] = this.id; data['nome'] = this.nome; if (this.estado!= null) { data['estado'] = this.estado.toJson(); } if (this.enderecos!= null) { data['enderecos'] = this.enderecos.map((v) => v.toJson()).toList(); } return data; } } ======================= File: lib/src/paginas/produto/produto_search.dart ======================= import 'package:flutter/material.dart'; import 'package:flutter_mobx/flutter_mobx.dart'; import 'package:get_it/get_it.dart'; import 'package:nosso/src/core/controller/categoria_controller.dart'; import 'package:nosso/src/core/controller/produto_controller.dart'; import 'package:nosso/src/core/model/produto.dart'; import 'package:nosso/src/paginas/categoria/categoria_pesquisa.dart'; import 'package:nosso/src/paginas/produto/produto_detalhes_tab.dart'; import 'package:nosso/src/util/load/circular_progresso.dart'; class ProdutoSearchDelegate extends SearchDelegate<Produto> { var produtoController = GetIt.I.get<ProdutoController>(); var categoriaController = GetIt.I.get<CategoriaController>(); @override List<Widget> buildActions(BuildContext context) { return [ IconButton( icon: Icon( Icons.clear, ), onPressed: () { query = ""; }, ), ]; } @override Widget buildLeading(BuildContext context) { return IconButton( icon: AnimatedIcon( icon: AnimatedIcons.menu_arrow, progress: transitionAnimation, ), onPressed: () { close(context, null); }, autofocus: true, ); } @override Widget buildResults(BuildContext context) { return Text(query); } @override Widget buildSuggestions(BuildContext context) { produtoController.getAll(); return Observer( builder: (context) { List<Produto> produtos = produtoController.produtos; if (produtoController.error!= null) { return Text("Não foi possível buscar produtos"); } if (produtos == null) { return CircularProgressor(); } final resultados = query.isEmpty ? [] : produtos .where( (p) => p.nome.toLowerCase().startsWith(query.toLowerCase())) .toList(); if (resultados.length == 0) { return CategoriaPesquisa(); } return ListView.builder( itemBuilder: (context, index) { Produto p = resultados[index]; return ListTile( isThreeLine: false, leading: CircleAvatar( radius: 20, backgroundImage: NetworkImage( "${produtoController.arquivo + p.foto}", ), ), title: RichText( text: TextSpan( text: p.nome.substring(0, query.length), style: TextStyle( color: Colors.black, fontWeight: FontWeight.bold), children: [ TextSpan( text: p.nome.substring(query.length), style: TextStyle(color: Colors.grey)) ]), ), onTap: () { Navigator.of(context).push( MaterialPageRoute( builder: (BuildContext context) { return ProdutoDetalhesTab(p); }, ), ); }, ); }, itemCount: resultados.length, ); }, ); } } ======================= File: lib/src/core/controller/subcategoria_controller.g.dart ======================= <filename>lib/src/core/controller/subcategoria_controller.g.dart<gh_stars>0 // GENERATED CODE - DO NOT MODIFY BY HAND part of'subcategoria_controller.dart'; // ************************************************************************** // StoreGenerator // ************************************************************************** // ignore_for_file: non_constant_identifier_names, unnecessary_brace_in_string_interps, unnecessary_lambdas, prefer_expression_function_bodies, lines_longer_than_80_chars, avoid_as, avoid_annotating_with_dynamic mixin _$SubCategoriaController on SubCategoriaControllerBase, Store { final _$subCategoriasAtom = Atom(name: 'SubCategoriaControllerBase.subCategorias'); @override List<SubCategoria> get subCategorias { _$subCategoriasAtom.reportRead(); return super.subCategorias; } @override set subCategorias(List<SubCategoria> value) { _$subCategoriasAtom.reportWrite(value, super.subCategorias, () { super.subCategorias = value; }); } final _$subCategoriaAtom = Atom(name: 'SubCategoriaControllerBase.subCategoria'); @override int get subCategoria { _$subCategoriaAtom.reportRead(); return super.subCategoria; } @override set subCategoria(int value) { _$subCategoriaAtom.reportWrite(value, super.subCategoria, () { super.subCategoria = value; }); } final _$errorAtom = Atom(name: 'SubCategoriaControllerBase.error'); @override Exception get error { _$errorAtom.reportRead(); return super.error; } @override set error(Exception value) { _$errorAtom.reportWrite(value, super.error, () { super.error = value; }); } final _$dioErrorAtom = Atom(name: 'SubCategoriaControllerBase.dioError'); @override DioError get dioError { _$dioErrorAtom.reportRead(); return super.dioError; } @override set dioError(DioError value) { _$dioErrorAtom.reportWrite(value, super.dioError, () { super.dioError = value; }); } final _$mensagemAtom = Atom(name: 'SubCategoriaControllerBase.mensagem'); @override String get mensagem { _$mensagemAtom.reportRead(); return super.mensagem; } @override set mensagem(String value) { _$mensagemAtom.reportWrite(value, super.mensagem, () { super.mensagem = value; }); } final _$categoriaSelecionadaAtom = Atom(name: 'SubCategoriaControllerBase.categoriaSelecionada'); @override Categoria get categoriaSelecionada { _$categoriaSelecionadaAtom.reportRead(); return super.categoriaSelecionada; } @override set categoriaSelecionada(Categoria value) { _$categoriaSelecionadaAtom.reportWrite(value, super.categoriaSelecionada, () { super.categoriaSelecionada = value; }); } final _$subCategoriaSelecionadaAtom = Atom(name: 'SubCategoriaControllerBase.subCategoriaSelecionada'); @override SubCategoria get subCategoriaSelecionada { _$subCategoriaSelecionadaAtom.reportRead(); return super.subCategoriaSelecionada; } @override set subCategoriaSelecionada(SubCategoria value) { _$subCategoriaSelecionadaAtom .reportWrite(value, super.subCategoriaSelecionada, () { super.subCategoriaSelecionada = value; }); } final _$getAllAsyncAction = AsyncAction('SubCategoriaControllerBase.getAll'); @override Future<List<SubCategoria>> getAll() { return _$getAllAsyncAction.run(() => super.getAll()); } final _$getAllByNomeAsyncAction = AsyncAction('SubCategoriaControllerBase.getAllByNome'); @override Future<List<SubCategoria>> getAllByNome(String nome) { return _$getAllByNomeAsyncAction.run(() => super.getAllByNome(nome)); } final _$getAllByCategoriaByIdAsyncAction = AsyncAction('SubCategoriaControllerBase.getAllByCategoriaById'); @override Future<List<SubCategoria>> getAllByCategoriaById(int id) { return _$getAllByCategoriaByIdAsyncAction .run(() => super.getAllByCategoriaById(id)); } final _$createAsyncAction = AsyncAction('SubCategoriaControllerBase.create'); @override Future<int> create(SubCategoria p) { return _$createAsyncAction.run(() => super.create(p)); } final _$updateAsyncAction = AsyncAction('SubCategoriaControllerBase.update'); @override Future<int> update(int id, SubCategoria p) { return _$updateAsyncAction.run(() => super.update(id, p)); } @override String toString() { return ''' subCategorias: ${subCategorias}, subCategoria: ${subCategoria}, error: ${error}, dioError: ${dioError}, mensagem: ${mensagem}, categoriaSelecionada: ${categoriaSelecionada}, subCategoriaSelecionada: ${subCategoriaSelecionada} '''; } } ======================= File: lib/src/util/dropdown/dropdown_marca.dart ======================= import 'package:flutter/material.dart'; import 'package:flutter_mobx/flutter_mobx.dart'; import 'package:get_it/get_it.dart'; import 'package:nosso/src/core/controller/marca_controller.dart'; import 'package:nosso/src/core/model/marca.dart'; import 'package:nosso/src/util/dialogs/dialog_marca.dart'; class DropDownMarca extends StatelessWidget { @override Widget build(BuildContext context) { var marcaController = GetIt.I.get<MarcaController>(); AlertMarca alertMarca = AlertMarca(); return Observer( builder: (context) { Marca marca = marcaController.marcaSelecionada; return Container( padding: EdgeInsets.all(15), child: Container( decoration: BoxDecoration( border: Border.all(color: Colors.grey), borderRadius: BorderRadius.circular(5), ), child: ListTile( title: Text("Marca *"), subtitle: marca == null ? Text("Selecione uma marca") : Text(marca.nome), leading: Icon(Icons.list_alt_outlined), trailing: Icon(Icons.arrow_drop_down_sharp), onTap: () { alertMarca.alert(context, marca); }, ), ), ); }, ); } } ======================= File: lib/src/core/controller/pagamento_controller.dart ======================= import 'package:dio/dio.dart'; import 'package:mobx/mobx.dart'; import 'package:nosso/src/core/model/pagamento.dart'; import 'package:nosso/src/core/repository/pagamento_repository.dart'; part 'pagamento_controller.g.dart'; class PagamentoController = PagamentoControllerBase with _$PagamentoController; abstract class PagamentoControllerBase with Store { PagamentoRepository pagamentoRepository; PagamentoControllerBase() { pagamentoRepository = PagamentoRepository(); } @observable List<Pagamento> pagamentos; @observable int pagamento; @observable Exception error; @observable DioError dioError; @observable String mensagem; @action Future<List<Pagamento>> getAll() async { try { pagamentos = await pagamentoRepository.getAll(); return pagamentos; } catch (e) { error = e; } } @action Future<int> create(Pagamento p) async { try { pagamento = await pagamentoRepository.create(p.toJson()); if (pagamento == null) { mensagem = "sem dados"; } else { return pagamento; } } on DioError catch (e) { mensagem = e.message; dioError = e; } } @action Future<int> update(int id, Pagamento p) async { try { pagamento = await pagamentoRepository.update(id, p.toJson()); return pagamento; } on DioError catch (e) { mensagem = e.message; dioError = e; } } } ======================= File: lib/src/util/validador/validador_promocao.dart ======================= <gh_stars>0 class ValidadorPromocao { String validateImages(List images) { if (images.isEmpty) return "Adicione imagens da promoção"; return null; } String validateNome(String text) { if (text.isEmpty) return "Preencha o nome da promoção"; return null; } String validateDescricao(String text) { if (text.isEmpty) return "Preencha a descrição da promoção"; return null; } String validateDesconto(String text) { double desconto = double.tryParse(text); if (desconto!= null) { if (!text.contains(".") || text.split(".")[1].length!= 2) return "Utilize 2 casas decimais"; } else { return "Desconto inválido"; } return null; } String validateDateRegsitro(DateTime dataRegistro) { if (dataRegistro == null) { return "Preencha a data registro da promoção"; } return null; } String validateDateInicio(DateTime dataInicio) { if (dataInicio == null) { return "Preencha a data início da promoção"; } if (dataInicio.isBefore(new DateTime.now())) { return "Data deve ser acima de hoje"; } return null; } String validateDateFinal(DateTime dataFinal) { if (dataFinal == null) { return "Preencha a data final da promoção"; } if (dataFinal.isBefore(new DateTime.now())) { return "Data deve ser acima de hoje"; } return null; } } ======================= File: lib/src/core/controller/loja_controller.dart ======================= import 'dart:async'; import 'dart:io'; import 'package:dio/dio.dart'; import 'package:mobx/mobx.dart'; import 'package:nosso/src/api/constants/constant_api.dart'; import 'package:nosso/src/core/model/loja.dart'; import 'package:nosso/src/core/repository/loja_repository.dart'; part 'loja_controller.g.dart'; class LojaController = LojaControllerBase with _$LojaController; abstract class LojaControllerBase with Store { LojaRepository lojaRepository; LojaControllerBase() { lojaRepository = LojaRepository(); } @observable List<Loja> lojas; @observable int loja; @observable var formData; @observable bool senhaVisivel = false; @action visualizarSenha() { senhaVisivel =!senhaVisivel; } @observable Exception error; @observable DioError dioError; @observable String mensagem; @observable Loja lojaSelecionada; @observable String arquivo = ConstantApi.urlArquivoLoja; @action Future<Loja> getById(int id) async { try { lojaSelecionada = await lojaRepository.getById(id); return lojaSelecionada; } catch (e) { error = e; } } @action Future<List<Loja>> getAllById(int id) async { try { lojas = await lojaRepository.getAllById(id); return lojas; } catch (e) { error = e; } } @action Future<List<Loja>> getAllByNome(String nome) async { try { lojas = await lojaRepository.getAllNome(nome); return lojas; } catch (e) { error = e; } } @action Future<List<Loja>> getAll() async { try { lojas = await lojaRepository.getAll(); return lojas; } catch (e) { error = e; } } @action Future<int> create(Loja p) async { try { loja = await lojaRepository.create(p.toJson()); if (loja == null) { mensagem = "sem dados"; } else { return loja; } } on DioError catch (e) { mensagem = e.message; dioError = e; } } @action Future<int> update(int id, Loja p) async { try { loja = await lojaRepository.update(id, p.toJson()); return loja; } on DioError catch (e) { mensagem = e.message; dioError = e; } } @action Future<String> upload(File foto, String fileName) async { try { formData = await lojaRepository.upload(foto, fileName); return formData; } catch (e) { error = e; } } @action Future<void> deleteFoto(String foto) async { try { await lojaRepository.deleteFoto(foto); } catch (e) { error = e; } } } ======================= File: lib/src/util/validador/validador_pagamento.dart ======================= <filename>lib/src/util/validador/validador_pagamento.dart class ValidadorPagamento { String validateQuantidade(String text) { int quantidade = int.tryParse(text); if (quantidade!= null) { if (quantidade <= 0) return "deve ter pelo menos um item"; } else { return "Quantidade inválida"; } return null; } String validateValorTotal(String text) { double valorTotal = double.tryParse(text); if (valorTotal!= null) { if (!text.contains(".") || text.split(".")[1].length!= 2) return "Utilize 2 casas decimais"; } else { return "Valor total inválido"; } return null; } String validateDataPagamento(DateTime dataPagamento) { if (dataPagamento == null) { return "Preencha a data de pagamento"; } return null; } } ======================= File: lib/src/api/interceptors/cache_interceptor.dart ======================= import 'dart:convert'; import 'package:dio/dio.dart'; import 'package:flutter/cupertino.dart'; import 'package:nosso/src/api/interceptors/dio_response.dart'; import 'package:nosso/src/api/interceptors/local_storage_service.dart'; class CacheInterceptor extends InterceptorsWrapper { @override Future onRequest(RequestOptions options) async { print('Request[${options.method}] => PATH: ${options.path}'); var uri = options.uri; if (options.extra.containsKey('refresh')) { var cache = await _getCache(uri); if (options.extra['refresh'] && cache == null) { return super.onRequest(options); } else { var data = await _getCache(uri); if (data!= null &&!data.expired) { return Response(data: data.data, statusCode: 200); } else { return super.onRequest(options); } } } return super.onRequest(options); } @override Future onResponse(Response response) async { print('Response[${response.statusCode}] => PATH: ${response.request.path}'); if (response.request.extra.containsKey('refresh') && response.request.extra['refresh']) { var cache = await _getCache(response.request.uri); if (cache == null || cache.expired) { save(response.request.uri.toString(), response.data); } } return super.onResponse(response); } Future<DioResponse> _getCache(Uri uri) async { var containsCache = await LocalStorageService.cointains(uri.toString()); if (containsCache) { var data = await LocalStorageService.getValue<String>(uri.toString()); var expire = await LocalStorageService.getValue<String>('${uri}_expire'); var json = jsonDecode("$data"); var res = DioResponse(data: json, expire: DateTime.parse(expire)); debugPrint("Recuperando do Cache $uri"); return res; } else { return null; } } void save(String uri, dynamic data) { var dateTime = DateTime.now().add(Duration(minutes: 1)); LocalStorageService.setValue<String>(uri, jsonEncode(data)); LocalStorageService.setValue<String>('${uri}_expire', dateTime.toString()); debugPrint("Atualizando em cache $uri"); } } ======================= File: lib/src/core/controller/usuario_controller.g.dart ======================= <gh_stars>0 // GENERATED CODE - DO NOT MODIFY BY HAND part of 'usuario_controller.dart'; // ************************************************************************** // StoreGenerator // ************************************************************************** // ignore_for_file: non_constant_identifier_names, unnecessary_brace_in_string_interps, unnecessary_lambdas, prefer_expression_function_bodies, lines_longer_than_80_chars, avoid_as, avoid_annotating_with_dynamic mixin _$UsuarioController on UsuarioControllerBase, Store { final _$usuariosAtom = Atom(name: 'UsuarioControllerBase.usuarios'); @override List<Usuario> get usuarios { _$usuariosAtom.reportRead(); return super.usuarios; } @override set usuarios(List<Usuario> value) { _$usuariosAtom.reportWrite(value, super.usuarios, () { super.usuarios = value; }); } final _$usuarioAtom = Atom(name: 'UsuarioControllerBase.usuario'); @override int get usuario { _$usuarioAtom.reportRead(); return super.usuario; } @override set usuario(int value) { _$usuarioAtom.reportWrite(value, super.usuario, () { super.usuario = value; }); } final _$errorAtom = Atom(name: 'UsuarioControllerBase.error'); @override Exception get error { _$errorAtom.reportRead(); return super.error; } @override set error(Exception value) { _$errorAtom.reportWrite(value, super.error, () { super.error = value; }); } final _$dioErrorAtom = Atom(name: 'UsuarioControllerBase.dioError'); @override DioError get dioError { _$dioErrorAtom.reportRead(); return super.dioError; } @override set dioError(DioError value) { _$dioErrorAtom.reportWrite(value, super.dioError, () { super.dioError = value; }); } final _$mensagemAtom = Atom(name: 'UsuarioControllerBase.mensagem'); @override String get mensagem { _$mensagemAtom.reportRead(); return super.mensagem; } @override set mensagem(String value) { _$mensagemAtom.reportWrite(value, super.mensagem, () { super.mensagem = value; }); } final _$usuarioSelecionadoAtom = Atom(name: 'UsuarioControllerBase.usuarioSelecionado'); @override Usuario get usuarioSelecionado { _$usuarioSelecionadoAtom.reportRead(); return super.usuarioSelecionado; } @override set usuarioSelecionado(Usuario value) { _$usuarioSelecionadoAtom.reportWrite(value, super.usuarioSelecionado, () { super.usuarioSelecionado = value; }); } final _$senhaVisivelAtom = Atom(name: 'UsuarioControllerBase.senhaVisivel'); @override bool get senhaVisivel { _$senhaVisivelAtom.reportRead(); return super.senhaVisivel; } @override set senhaVisivel(bool value) { _$senhaVisivelAtom.reportWrite(value, super.senhaVisivel, () { super.senhaVisivel = value; }); } final _$getAllAsyncAction = AsyncAction('UsuarioControllerBase.getAll'); @override Future<List<Usuario>> getAll() { return _$getAllAsyncAction.run(() => super.getAll()); } final _$getEmailAsyncAction = AsyncAction('UsuarioControllerBase.getEmail'); @override Future<Usuario> getEmail(String email) { return _$getEmailAsyncAction.run(() => super.getEmail(email)); } final _$getLoginAsyncAction = AsyncAction('UsuarioControllerBase.getLogin'); @override Future<Usuario> getLogin(String email, String senha) { return _$getLoginAsyncAction.run(() => super.getLogin(email, senha)); } final _$loginTokenAsyncAction = AsyncAction('UsuarioControllerBase.loginToken'); @override Future<int> loginToken(Usuario p) { return _$loginTokenAsyncAction.run(() => super.loginToken(p)); } final _$createAsyncAction = AsyncAction('UsuarioControllerBase.create'); @override Future<int> create(Usuario p) { return _$createAsyncAction.run(() => super.create(p)); } final _$updateAsyncAction = AsyncAction('UsuarioControllerBase.update'); @override Future<int> update(int id, Usuario p) { return _$updateAsyncAction.run(() => super.update(id, p)); } final _$UsuarioControllerBaseActionController = ActionController(name: 'UsuarioControllerBase'); @override dynamic visualizarSenha() { final _$actionInfo = _$UsuarioControllerBaseActionController.startAction( name: 'UsuarioControllerBase.visualizarSenha'); try { return super.visualizarSenha(); } finally { _$UsuarioControllerBaseActionController.endAction(_$actionInfo); } } @override String toString() { return ''' usuarios: ${usuarios}, usuario: ${usuario}, error: ${error}, dioError: ${dioError}, mensagem: ${mensagem}, usuarioSelecionado: ${usuarioSelecionado}, senhaVisivel: ${senhaVisivel} '''; } } ======================= File: lib/src/core/controller/caixafluxosaida_controller.g.dart ======================= <gh_stars>0 // GENERATED CODE - DO NOT MODIFY BY HAND part of 'caixafluxosaida_controller.dart'; // ************************************************************************** // StoreGenerator // ************************************************************************** // ignore_for_file: non_constant_identifier_names, unnecessary_brace_in_string_interps, unnecessary_lambdas, prefer_expression_function_bodies, lines_longer_than_80_chars, avoid_as, avoid_annotating_with_dynamic mixin _$CaixafluxosaidaController on CaixafluxosaidaControllerBase, Store { final _$caixaSaidasAtom = Atom(name: 'CaixafluxosaidaControllerBase.caixaSaidas'); @override List<CaixaFluxoSaida> get caixaSaidas { _$caixaSaidasAtom.reportRead(); return super.caixaSaidas; } @override set caixaSaidas(List<CaixaFluxoSaida> value) { _$caixaSaidasAtom.reportWrite(value, super.caixaSaidas, () { super.caixaSaidas = value; }); } final _$caixaSaidaAtom = Atom(name: 'CaixafluxosaidaControllerBase.caixaSaida'); @override int get caixaSaida { _$caixaSaidaAtom.reportRead(); return super.caixaSaida; } @override set caixaSaida(int value) { _$caixaSaidaAtom.reportWrite(value, super.caixaSaida, () { super.caixaSaida = value; }); } final _$errorAtom = Atom(name: 'CaixafluxosaidaControllerBase.error'); @override Exception get error { _$errorAtom.reportRead(); return super.error; } @override set error(Exception value) { _$errorAtom.reportWrite(value, super.error, () { super.error = value; }); } final _$dioErrorAtom = Atom(name: 'CaixafluxosaidaControllerBase.dioError'); @override DioError get dioError { _$dioErrorAtom.reportRead(); return super.dioError; } @override set dioError(DioError value) { _$dioErrorAtom.reportWrite(value, super.dioError, () { super.dioError = value; }); } final _$mensagemAtom = Atom(name: 'CaixafluxosaidaControllerBase.mensagem'); @override String get mensagem { _$mensagemAtom.reportRead(); return super.mensagem; } @override set mensagem(String value) { _$mensagemAtom.reportWrite(value, super.mensagem, () { super.mensagem = value; }); } final _$getAllAsyncAction = AsyncAction('CaixafluxosaidaControllerBase.getAll'); @override Future<List<CaixaFluxoSaida>> getAll() { return _$getAllAsyncAction.run(() => super.getAll()); } final _$createAsyncAction = AsyncAction('CaixafluxosaidaControllerBase.create'); @override Future<int> create(CaixaFluxoSaida p) { return _$createAsyncAction.run(() => super.create(p)); } final _$updateAsyncAction = AsyncAction('CaixafluxosaidaControllerBase.update'); @override Future<int> update(int id, CaixaFluxoSaida p) { return _$updateAsyncAction.run(() => super.update(id, p)); } @override String toString() { return ''' caixaSaidas: ${caixaSaidas}, caixaSaida: ${caixaSaida}, error: ${error}, dioError: ${dioError}, mensagem: ${mensagem} '''; } } ======================= File: lib/src/util/validador/validador_pdv.dart ======================= <filename>lib/src/util/validador/validador_pdv.dart<gh_stars>0 class ValidadorPDV { String validateCodigoBarra(String text) { if (text.isEmpty) return "Preencha o código de barra"; return null; } String validateQuantidade(String text) { int quantidade = int.tryParse(text); if (quantidade!= null) { if (quantidade <= 0) return "deve ter pelo menos um item"; } else { return "Quantidade inválida"; } return null; } String validateValorUnitario(String text) { double valorFrete = double.tryParse(text); if (valorFrete!= null) { if (!text.contains(".") || text.split(".")[1].length!= 2) return "Utilize 2 casas decimais"; } else { return "Valor unitário inválido"; } return null; } String validateSubTotal(String text) { double valorFrete = double.tryParse(text); if (valorFrete!= null) { if (!text.contains(".") || text.split(".")[1].length!= 2) return "Utilize 2 casas decimais"; } else { return "SubTotal inválido"; } return null; } String validateValorTotal(String text) { double valorTotal = double.tryParse(text); if (valorTotal!= null) { if (!text.contains(".") || text.split(".")[1].length!= 2) return "Utilize 2 casas decimais"; } else { return "Valor total inválido"; } return null; } String validateDesconto(String text) { double desconto = double.tryParse(text); if (desconto!= null) { if (!text.contains(".") || text.split(".")[1].length!= 2) return "Utilize 2 casas decimais"; } else { return "Desconto inválido"; } return null; } String validateDateEntrega(DateTime dataEntrega) { if (dataEntrega == null) { return "Preencha a data entrega do pedido"; } return null; } } ======================= File: lib/src/paginas/subcategoria/subcategoria_produto.dart ======================= <filename>lib/src/paginas/subcategoria/subcategoria_produto.dart import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_mobx/flutter_mobx.dart'; import 'package:get_it/get_it.dart'; import 'package:nosso/src/core/controller/subcategoria_controller.dart'; import 'package:nosso/src/core/model/categoria.dart'; import 'package:nosso/src/core/model/favorito.dart'; import 'package:nosso/src/core/model/subcategoria.dart'; import 'package:nosso/src/paginas/produto/produto_tab.dart'; import 'package:nosso/src/util/filter/produto_filter.dart'; import 'package:nosso/src/util/load/circular_progresso_mini.dart'; class SubCategoriaProduto extends StatefulWidget { Categoria c; SubCategoriaProduto({Key key, this.c}) : super(key: key); @override _SubCategoriaProdutoState createState() => _SubCategoriaProdutoState(categoria: this.c); } class _SubCategoriaProdutoState extends State<SubCategoriaProduto> with SingleTickerProviderStateMixin { _SubCategoriaProdutoState({this.subCategoria, this.categoria}); var subCategoriaController = GetIt.I.get<SubCategoriaController>(); var nomeController = TextEditingController(); SubCategoria subCategoria; Categoria categoria; Favorito favorito; ProdutoFilter filter; int size = 0; int page = 0; @override void initState() { subCategoriaController.getAllByCategoriaById(categoria.id); super.initState(); } filterByNome(String nome) { if (nome.trim().isEmpty) { subCategoriaController.getAll(); } else { nome = nomeController.text; subCategoriaController.getAllByNome(nome); } } @override Widget build(BuildContext context) { var text = ""; return Scaffold( appBar: AppBar( title: Text(categoria.nome), actions: <Widget>[ Observer( builder: (context) { if (subCategoriaController.error!= null) { return Text("Não foi possível carregar"); } if (subCategoriaController.subCategorias == null) { return Center( child: Icon(Icons.warning_amber_outlined), ); } return Chip( label: Text( (subCategoriaController.subCategorias.length?? 0).toString(), ), ); }, ), IconButton( icon: Icon(Icons.refresh_outlined), onPressed: () { subCategoriaController.getAll(); }, ), ], ), body: Container( height: MediaQuery.of(context).size.height, color: Colors.transparent, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ SizedBox(height: 0), Container( height: 80, width: double.infinity, color: Colors.grey[100], padding: EdgeInsets.all(5), child: ListTile( subtitle: TextFormField( controller: nomeController, decoration: InputDecoration( labelText: "busca por departamentos", prefixIcon: Icon(Icons.search_outlined), suffixIcon: IconButton( onPressed: () => nomeController.clear(), icon: Icon(Icons.clear), ), ), onChanged: filterByNome, ), ), ), Expanded( child: builderConteutoListSubCategoria(), ), ], ), ), ); } builderConteutoListSubCategoria() { return Container( padding: EdgeInsets.only(top: 0), child: Observer( builder: (context) { List<SubCategoria> subCategorias = subCategoriaController.subCategorias; if (subCategoriaController.error!= null) { return Text("Não foi possível carregados dados"); } if (subCategorias == null) { return Center( child: CircularProgressorMini(), ); } if (subCategorias.length == 0) { return Center( child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Center( child: Icon( Icons.mood_outlined, size: 100, ), ), Text( "Ops! sem departamento", ), ], ), ); } return builderListSubCategoria(subCategorias); }, ), ); } builderListSubCategoria(List<SubCategoria> categorias) { double containerWidth = 160; double containerHeight = 20; return ListView.builder( scrollDirection: Axis.vertical, itemCount: categorias.length, itemBuilder: (context, index) { SubCategoria c = categorias[index]; return GestureDetector( child: Container( child: ListTile( isThreeLine: false, leading: Container( padding: EdgeInsets.all(1), child: CircleAvatar( backgroundColor: Colors.grey[500].withOpacity(0.2), foregroundColor: Theme.of(context).primaryColor, radius: 20, child: Text( c.nome.substring(0, 1).toUpperCase(), style: TextStyle( fontSize: 20, fontWeight: FontWeight.bold, ), ), ), ), title: Text(c.nome), subtitle: Text("${c.categoria.nome}"), trailing: Container( height: 80, width: 50, ), ), ), onTap: () { Navigator.of(context).push( MaterialPageRoute( builder: (BuildContext context) { return ProdutoTab(s: c); }, ), ); }, ); }, ); } } ======================= File: lib/src/core/controller/categoria_controller.dart ======================= import 'dart:io'; import 'package:dio/dio.dart'; import 'package:mobx/mobx.dart'; import 'package:nosso/src/api/constants/constant_api.dart'; import 'package:nosso/src/api/dio/custon_dio.dart'; import 'package:nosso/src/core/model/categoria.dart'; import 'package:nosso/src/core/repository/categoria_repository.dart'; part 'categoria_controller.g.dart'; class CategoriaController = CategoriaControllerBase with _$CategoriaController; abstract class CategoriaControllerBase with Store { CategoriaRepository categoriaRepository; CategoriaControllerBase() { categoriaRepository = CategoriaRepository(); } @observable List<Categoria> categorias; @observable int categoria; @observable var formData; @observable Exception error; @observable DioError dioError; @observable String mensagem; @observable Categoria categoriaSelecionada; @observable String arquivo = ConstantApi.urlArquivoCategoria; @action Future<List<Categoria>> getAll() async { try { categorias = await categoriaRepository.getAll(); return categorias; } catch (e) { error = e; } } @action Future<List<Categoria>> getAllByNome(String nome) async { try { categorias = await categoriaRepository.getAllByNome(nome); return categorias; } catch (e) { error = e; } } @action Future<int> create(Categoria p) async { try { categoria = await categoriaRepository.create(p.toJson()); if (categoria == null) { mensagem = "sem dados"; } else { return categoria; } } on DioError catch (e) { mensagem = e.message; dioError = e; } } @action Future<int> update(int id, Categoria p) async { try { categoria = await categoriaRepository.update(id, p.toJson()); return categoria; } on DioError catch (e) { mensagem = e.message; dioError = e; } } @action Future<String> upload(File foto, String fileName) async { try { formData = await categoriaRepository.upload(foto, fileName); return formData; } catch (e) { error = e; } } @action Future<void> deleteFoto(String foto) async { try { await categoriaRepository.deleteFoto(foto); } catch (e) { error = e; } } } ======================= File: lib/src/paginas/promocao/promocao_detalhes-view.dart ======================= <gh_stars>0 import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:get_it/get_it.dart'; import 'package:intl/intl.dart'; import 'package:nosso/src/core/controller/promocao_controller.dart'; import 'package:nosso/src/core/model/promocao.dart'; class PromocaoDetalhesView extends StatefulWidget { Promocao p; PromocaoDetalhesView(this.p); @override _PromocaoDetalhesViewState createState() => _PromocaoDetalhesViewState(); } class _PromocaoDetalhesViewState extends State<PromocaoDetalhesView> { var selectedCard = 'WEIGHT'; var promocaoController = Get
1,506
* <p> * When unit of work clones are built directly from rows no object in the shared * cache points to this valueholder, so it can store the unit of work as its * session. However once that UnitOfWork commits and the valueholder is merged * into the shared cache, the session needs to be reset to the root session, ie. * the server session. */ @Override public void releaseWrappedValueHolder(AbstractSession targetSession) { // On UnitOfWork dont want to do anything. return; } /** * Reset all the fields that are not needed after instantiation. */ @Override protected void resetFields() { //do nothing. nothing should be reset to null; } public void setBackupValueHolder(ValueHolderInterface backupValueHolder) { this.backupValueHolder = backupValueHolder; } protected void setMapping(DatabaseMapping mapping) { this.mapping = mapping; } protected void setRemoteUnitOfWork(UnitOfWorkImpl remoteUnitOfWork) { this.remoteUnitOfWork = remoteUnitOfWork; } protected void setSourceAttributeName(String name) { sourceAttributeName = name; } protected void setSourceObject(Object sourceObject) { this.sourceObject = sourceObject; } protected void setRelationshipSourceObject(Object relationshipSourceObject) { this.relationshipSourceObject = relationshipSourceObject; } protected void setWrappedValueHolder(DatabaseValueHolder valueHolder) { wrappedValueHolder = valueHolder; } /** * INTERNAL: * Return if add/remove should trigger instantiation or avoid. * Current instantiation is avoided is using change tracking. */ @Override public boolean shouldAllowInstantiationDeferral() { return ((WeavedAttributeValueHolderInterface)this.wrappedValueHolder).shouldAllowInstantiationDeferral(); } } ======================= File: foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/queries/WriteObjectQuery.java ======================= /******************************************************************************* * Copyright (c) 1998, 2018 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation from Oracle TopLink ******************************************************************************/ package org.eclipse.persistence.queries; import org.eclipse.persistence.exceptions.*; import org.eclipse.persistence.internal.sessions.UnitOfWorkImpl; /** * <p><b>Purpose</b>: * Used for inserting or updating objects * WriteObjectQuery determines whether to perform a insert or an update on the database. * * <p><b>Responsibilities</b>: * <ul> * <li> Determines whether to perform a insert or an update on the database. * <li> Stores object in identity map for insert if required. * </ul> * * @author <NAME> * @since TOPLink/Java 1.0 */ public class WriteObjectQuery extends ObjectLevelModifyQuery { public WriteObjectQuery() { super(); } public WriteObjectQuery(Object objectToWrite) { this(); setObject(objectToWrite); } public WriteObjectQuery(Call call) { this(); setCall(call); } /** * INTERNAL: * Perform a does exist check to decide whether to perform an insert or update and * delegate the work to the mechanism. Does exists check will also perform an * optimistic lock check if required. * @exception DatabaseException - an error has occurred on the database * @exception OptimisticLockException - an error has occurred using the optimistic lock feature * @return object - the object being written. */ @Override public Object executeDatabaseQuery() throws DatabaseException, OptimisticLockException { if (getObjectChangeSet()!= null) { return getQueryMechanism().executeWriteWithChangeSet(); } else { return getQueryMechanism().executeWrite(); } } /** * INTERNAL: * Perform a does exist check to decide whether to perform an insert or update and * delegate the work to the mechanism. */ public void executeCommit() throws DatabaseException, OptimisticLockException { boolean doesExist; if (getSession().isUnitOfWork()) { doesExist =!((UnitOfWorkImpl)getSession()).isCloneNewObject(getObject()); if (doesExist) { doesExist = ((UnitOfWorkImpl)getSession()).isObjectRegistered(getObject()); } } else { //Initialize does exist query DoesExistQuery existQuery = (DoesExistQuery)this.descriptor.getQueryManager().getDoesExistQuery().clone(); existQuery.setObject(getObject()); existQuery.setPrimaryKey(getPrimaryKey()); existQuery.setDescriptor(this.descriptor); existQuery.setTranslationRow(getTranslationRow()); doesExist = ((Boolean)getSession().executeQuery(existQuery)).booleanValue(); } // Do insert of update if (doesExist) { // Must do an update getQueryMechanism().updateObjectForWrite(); } else { // Must do an insert getQueryMechanism().insertObjectForWrite(); } } /** * INTERNAL: * Perform a does exist check to decide whether to perform an insert or update and * delegate the work to the mechanism. */ public void executeCommitWithChangeSet() throws DatabaseException, OptimisticLockException { // Do insert of update if (!getObjectChangeSet().isNew()) { // Must do an update if (!getSession().getCommitManager().isCommitInPreModify(getObject())) { //If the changeSet is in the PreModify then it is in the process of being written getQueryMechanism().updateObjectForWriteWithChangeSet(); } } else { // check whether the object is already being committed - // if it is and it is new, then a shallow insert must be done if (getSession().getCommitManager().isCommitInPreModify(getObject())) { // a shallow insert must be performed this.dontCascadeParts(); getQueryMechanism().insertObjectForWrite(); getSession().getCommitManager().markShallowCommit(object); } else { // Must do an insert getQueryMechanism().insertObjectForWrite(); } } } /** * INTERNAL: * Returns the specific default redirector for this query type. There are numerous default query redirectors. * See ClassDescriptor for their types. */ @Override protected QueryRedirector getDefaultRedirector(){ return descriptor.getDefaultQueryRedirector(); } /** * PUBLIC: * Return if this is a write object query. */ @Override public boolean isWriteObjectQuery() { return true; } /** * INTERNAL: * Prepare the receiver for execution in a session. */ @Override public void prepareForExecution() throws QueryException { super.prepareForExecution(); // Set the tranlation row, it may already be set in the custom query situation. // PERF: Only build the translation row for updates, as inserts do not have a where clause. if ((!isInsertObjectQuery()) && ((getTranslationRow() == null) || (getTranslationRow().isEmpty()))) { setTranslationRow(this.descriptor.getObjectBuilder().buildRowForTranslation(getObject(), getSession())); } } } ======================= File: sdo/org.eclipse.persistence.sdo/src/org/eclipse/persistence/sdo/helper/DefaultSchemaLocationResolver.java ======================= <filename>sdo/org.eclipse.persistence.sdo/src/org/eclipse/persistence/sdo/helper/DefaultSchemaLocationResolver.java /******************************************************************************* * Copyright (c) 1998, 2018 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation from Oracle TopLink ******************************************************************************/ package org.eclipse.persistence.sdo.helper; import commonj.sdo.Type; import java.util.Map; import javax.xml.namespace.QName; /** * <p><b>Purpose</b>: Default implementation of the org.eclipse.persistence.sdo.helper.SchemaLocationResolver interface * By default set a Map keyed on QName of types and value is the schemaLocation * * @see org.eclipse.persistence.sdo.helper.SchemaLocationResolver */ public class DefaultSchemaLocationResolver implements SchemaLocationResolver { private Map schemaLocationMap; public DefaultSchemaLocationResolver(Map schemaLocationMap) { this.schemaLocationMap = schemaLocationMap; } /** * Return the value for the schemaLocation attribute of the generated Import * @param sourceType the source type * @param targetType the target type * @return the value for the schemaLocation attribute of the generated Import */ @Override public String resolveSchemaLocation(Type sourceType, Type targetType) { QName qname = new QName(targetType.getURI(), targetType.getName()); String schemaLocation = (String)schemaLocationMap.get(qname); return schemaLocation; } /** * Set the map of schemaLocations keyed on QName of the target SDO Type * @param schemaLocations Map keyed on QName of the target SDO Type */ public void setMap(Map schemaLocations) { schemaLocationMap = schemaLocations; } } ======================= File: jpa/org.eclipse.persistence.jpa/src/org/eclipse/persistence/internal/jpa/config/queries/PlsqlRecordImpl.java ======================= /******************************************************************************* * Copyright (c) 2013, 2018 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * <NAME> - initial API and implementation ******************************************************************************/ package org.eclipse.persistence.internal.jpa.config.queries; import java.util.ArrayList; import org.eclipse.persistence.internal.jpa.metadata.queries.PLSQLParameterMetadata; import org.eclipse.persistence.internal.jpa.metadata.queries.PLSQLRecordMetadata; import org.eclipse.persistence.jpa.config.PlsqlParameter; import org.eclipse.persistence.jpa.config.PlsqlRecord; /** * JPA scripting API implementation. * * @author <NAME> * @since EclipseLink 2.5.1 */ public class PlsqlRecordImpl extends AbstractPlsqlTypeImpl<PLSQLRecordMetadata, PlsqlRecord> implements PlsqlRecord { public PlsqlRecordImpl() { super(new PLSQLRecordMetadata()); getMetadata().setFields(new ArrayList<PLSQLParameterMetadata>()); } @Override public PlsqlParameter addField() { PlsqlParameterImpl parameter = new PlsqlParameterImpl(); getMetadata().getFields().add(parameter.getMetadata()); return parameter; } } ======================= File: foundation/org.eclipse.persistence.oracle.nosql/src/org/eclipse/persistence/internal/nosql/adapters/nosql/OracleNoSQLConnectionFactory.java ======================= <reponame>jgrassel/eclipselink /******************************************************************************* * Copyright (c) 2011, 2018 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation ******************************************************************************/ package org.eclipse.persistence.internal.nosql.adapters.nosql; import javax.naming.Reference; import javax.resource.ResourceException; import javax.resource.cci.Connection; import javax.resource.cci.ConnectionFactory; import javax.resource.cci.ConnectionSpec; import javax.resource.cci.RecordFactory; import javax.resource.cci.ResourceAdapterMetaData; import oracle.kv.KVStore; import oracle.kv.KVStoreConfig; import oracle.kv.KVStoreFactory; /** * Connection factory for Oracle NoSQL JCA adapter. * * @author James * @since EclipseLink 2.4 */ public class OracleNoSQLConnectionFactory implements ConnectionFactory { /** * Default constructor. */ public OracleNoSQLConnectionFactory() { } @Override public Connection getConnection() throws ResourceException { return getConnection(new OracleNoSQLJCAConnectionSpec()); } @Override public Connection getConnection(ConnectionSpec spec) throws ResourceException { OracleNoSQLJCAConnectionSpec connectionSpec = (OracleNoSQLJCAConnectionSpec)spec; KVStore store = null; try { KVStoreFactory factory = new KVStoreFactory(); String[] hosts = new String[connectionSpec.getHosts().size()]; int index = 0; for (String host : connectionSpec.getHosts()) { hosts[index] = host; index++; } KVStoreConfig config = new KVStoreConfig(connectionSpec.getStore(), hosts); store = factory.getStore(config); } catch (Exception exception) { ResourceException resourceException = new ResourceException(exception.toString()); resourceException.initCause(exception); throw resourceException; } return new OracleNoSQLConnection(store, connectionSpec); } @Override public ResourceAdapterMetaData getMetaData() { return new OracleNoSQLAdapterMetaData(); } @Override public RecordFactory getRecordFactory() { return new OracleNoSQLRecordFactory(); } @Override public Reference getReference() { return new Reference(getClass().getName()); } @Override public void setReference(Reference reference) { } } ======================= File: foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/oxm/record/DOMRecord.java ======================= /******************************************************************************* * Copyright (c) 1998, 2018 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation from Oracle TopLink ******************************************************************************/ package org.eclipse.persistence.oxm.record; import java.io.Reader; import java.io.StringReader; import java.io.StringWriter; import java.io.Writer; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; import java.util.Vector; import javax.xml.namespace.QName; import org.eclipse.persistence.internal.core.sessions.CoreAbstractSession; import org.eclipse.persistence.internal.helper.DatabaseField; import org.eclipse.persistence.internal.helper.Helper; import org.eclipse.persistence.internal.oxm.ReferenceResolver; import org.eclipse.persistence.internal.oxm.UnmarshalXPathEngine; import org.eclipse.persistence.internal.oxm.XMLConversionManager; import org.eclipse.persistence.oxm.IDResolver; import org.eclipse.persistence.oxm.XMLField; import org.eclipse.persistence.oxm.XMLConstants; import org.eclipse.persistence.oxm.XMLLogin; import org.eclipse.persistence.internal.oxm.XPathEngine; import org.eclipse.persistence.internal.oxm.mappings.Field; import org.eclipse.persistence.internal.oxm.record.TransformationRecord; import org.eclipse.persistence.internal.sessions.AbstractRecord; import org.eclipse.persistence.internal.sessions.AbstractSession; import org.eclipse.persistence.oxm.NamespaceResolver; import org.eclipse.persistence.oxm.mappings.nullpolicy.AbstractNullPolicy; import org.eclipse.persistence.platform.xml.XMLParser; import org.eclipse.persistence.platform.xml.XMLPlatform; import org.eclipse.persistence.platform.xml.XMLPlatformFactory; import org.eclipse.persistence.platform.xml.XMLTransformer; import org.eclipse.persistence.exceptions.ValidationException; import org.eclipse.persistence.exceptions.XMLMarshalException; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.DocumentFragment; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * PUBLIC: * Provides a Record/Map API on an XML DOM element. */ public class DOMRecord extends XMLRecord implements TransformationRecord { private Node dom; private Node currentNode; private XMLField lastUpdatedField; private ReferenceResolver referenceResolver; /** * INTERNAL: * Default constructor. */ public DOMRecord() { super(); setNamespaceResolver(new NamespaceResolver()); referenceResolver = new ReferenceResolver(); // Required for subclasses. } /** * INTERNAL: * Create a record with the root element name. */ public DOMRecord(String rootElementName) { this(rootElementName, (NamespaceResolver)null); } /** * INTERNAL: * Create a record with the root element name get the namespace URI from the namespaceResolver. */ public DOMRecord(String rootElementName, NamespaceResolver namespaceResolver) { this(); String rootElementNamespaceURI = resolveNamespace(namespaceResolver, rootElementName); setDOM(createNewDocument(rootElementName, rootElementNamespaceURI)); } /** * INTERNAL: * Create a record with the root element name get the namespace URI from the namespaceResolver. */ public DOMRecord(String rootElementName, String rootElementNamespaceURI) { this(); setDOM(createNewDocument(rootElementName, rootElementNamespaceURI)); } /** * INTERNAL: * Create a record with the local root element name, that is a child of the parent. */ public DOMRecord(String localRootElementName, Node parent) { this(localRootElementName, (NamespaceResolver)null, parent); } /** * INTERNAL: * Create a record with the local root element name, that is a child of the parent. * Lookup the namespace URI from the namespaceResolver. */ public DOMRecord(String localRootElementName, NamespaceResolver namespaceResolver, Node parent) { this(); Document document; if (parent instanceof Document) { document = (Document)parent; } else { document = parent.getOwnerDocument(); } String localRootElementNamespaceURI = resolveNamespace(namespaceResolver, localRootElementName); Element child = document.createElementNS(localRootElementNamespaceURI, localRootElementName); parent.appendChild(child); setDOM(child); } /** * INTERNAL: * Create a record with the element. */ public DOMRecord(Element element) { this(); setDOM(element); } public DOMRecord(Node node) { this(); setDOM(node); } /** * INTERNAL: * Create a record with the element. */ public DOMRecord(Document document) { this(); setDOM(document.getDocumentElement()); } /** * PUBLIC: * Get the local name of the context root element. */ @Override public String getLocalName() { String localName = getDOM().getLocalName(); if (null!= localName) { return localName; } return getDOM().getNodeName(); } /** * PUBLIC: * Get the namespace URI for the context root element. */ @Override public String getNamespaceURI() { return getDOM().getNamespaceURI(); } /** * INTERNAL: * The ReferenceResolver that is leveraged by key based mappings. * @since EclipseLink 2.5.0 */ public ReferenceResolver getReferenceResolver() { if(null == referenceResolver) { referenceResolver = new ReferenceResolver(); } return referenceResolver; } /** * INTERNAL: * Set the ReferenceResolver that will be leveraged by key based mappings. * @since EclipseLink 2.5.0 */ public void setReferenceResolver(ReferenceResolver referenceResolver) { this.referenceResolver = referenceResolver; } /** * INTERNAL: * Add the field-value pair to the document. */ @Override public void add(DatabaseField key, Object value) { // Value may be a direct value, nested record, or collection of values. Object nodeValue = convertToNodeValue(value); XPathEngine.getInstance().create(convertToXMLField(key), dom, nodeValue, session); } /** * INTERNAL: * Convert the value which may be a direct value, nested record, or set of nested records, * to a node value usable with the XPathEngine. */ private Object convertToNodeValue(Object value) { if (value instanceof List) { List values = (List)value; Vector nodeValues = new Vector(values.size()); for (int index = 0; index < values.size(); index++) { Object nestedValue = values.get(index); nodeValues.add(convertToNodeValue(nestedValue)); } return nodeValues; } else if (value instanceof DOMRecord) { return ((DOMRecord)value).getDOM(); } else if (value!= null && value.getClass() == XMLEntry.class) { XMLEntry entry = (XMLEntry)value; entry.setValue(convertToNodeValue(entry.getValue())); return entry; } else { return value; } } /** * PUBLIC: * Clear the sub-nodes of the DOM. */ @Override public void clear() { if(getDOM() instanceof Element) { String domName = ((Element)getDOM()).getTagName(); this.dom = createNewDocument(domName, null); this.currentNode = this.dom; } } /** * INTERNAL: * Clone the row and its values. */ @Override public DOMRecord clone() { DOMRecord clone = (DOMRecord)super.clone(); if (clone!= null) { clone.setDOM((Element)dom.cloneNode(true)); } return clone; } /** * INTERNAL: * Creates a new Document and returns the root element of that document */ public Node createNewDocument(String defaultRootElementName) { return createNewDocument(defaultRootElementName, null); } /** * INTERNAL: * Creates a new Document and returns the root element of that document */ public Node createNewDocument(String defaultRootElementName, String namespaceURI) { XMLPlatform xmlPlatform = XMLPlatformFactory.getInstance().getXMLPlatform(); Document document = xmlPlatform.createDocument(); if (defaultRootElementName == null || defaultRootElementName.length() == 0) { DocumentFragment fragment = document.createDocumentFragment(); return fragment; } else { Node rootNode = document.createElementNS(namespaceURI, defaultRootElementName); document.appendChild(rootNode); return document.getDocumentElement(); } } /** * PUBLIC: * Return the document. */ @Override public Document getDocument() { return getDOM().getOwnerDocument(); } /** * INTERNAL: * Check if the field is contained in the row. */ @Override public boolean containsKey(DatabaseField key) { XMLField xmlField = convertToXMLField(key); NodeList nodeList = UnmarshalXPathEngine.getInstance().selectNodes(dom, xmlField, xmlField.getNamespaceResolver()); return nodeList.getLength() > 0; } /** * PUBLIC: * Check if the value is contained in the row. */ @Override public boolean contains(Object value) { return values().contains(value); } @Override public Object get(DatabaseField key) { Object value = getIndicatingNoEntry(key); if(value == noEntry) { return null; } return value; } /** * INTERNAL: * Given a DatabaseField return the corresponding value from the document */ @Override public Object getIndicatingNoEntry(DatabaseField key) { return getIndicatingNoEntry(key, false, false); } public Object getIndicatingNoEntry(DatabaseField key, boolean shouldReturnNode) { return getIndicatingNoEntry(key, shouldReturnNode, false); } public Object getIndicatingNoEntry(DatabaseField key, boolean shouldReturnNode, boolean checkForXsiNil) { XMLField field = convertToXMLField(key); // handle'self' xpath if (field.isSelfField()) { return this; } Object result = UnmarshalXPathEngine.getInstance().selectSingleNode(dom, field, field.getNamespaceResolver(), checkForXsiNil); if(result == noEntry) { if(shouldReturnNode) { return null; } return noEntry; } if (result == NIL) { return NIL; } Node node = (Node)result; if(shouldReturnNode) { return node; } // If a node was not found return null if (null == node) { return null; } // For Attributes and Text nodes return their value if (Node.ELEMENT_NODE!= node.getNodeType()) { if (node.getNodeType() == Node.ATTRIBUTE_NODE) { getValueFromAttribute((Attr)node, field); } // For Text, must handle typed elements return getValueFromElement((Element)node.getParentNode(), node, field); } // If an element was found return buildNestedRow((Element)node); } /** * INTERNAL: * Retrieve the value for the field name. */ @Override public Object getValues(String key) { Object value = getValuesIndicatingNoEntry(new XMLField(key)); if (value == AbstractRecord.noEntry) { return null; } return value; } /** * INTERNAL: * Given a DatabaseField, return the corresponding values from the document */ @Override public Object getValues(DatabaseField key) { return this.getValues(key, null); } public Object getValues(DatabaseField key, AbstractNullPolicy nullPolicy) { Object value = getValuesIndicatingNoEntry(key, nullPolicy); if (value == AbstractRecord.noEntry) { return null; } return value; } public Object getValuesIndicatingNoEntry(DatabaseField key) { return this.getValuesIndicatingNoEntry(key, null); } public Object getValuesIndicatingNoEntry(DatabaseField key, AbstractNullPolicy nullPolicy) { return getValuesIndicatingNoEntry(key, false, nullPolicy); } public List<XMLEntry> getValuesIndicatingNoEntry(List<DatabaseField> keys) { return getValuesIndicatingNoEntry(keys, false); } public List<XMLEntry> getValuesIndicatingNoEntry(List<DatabaseField> keys, boolean shouldReturnNodes) { List<XMLField> xmlFields = convertToXMLField(keys); List<XMLEntry> values = UnmarshalXPathEngine.getInstance().selectNodes(dom, xmlFields, xmlFields.get(0).getNamespaceResolver()); if(shouldReturnNodes) { return values; } for(XMLEntry next:values) { Node nextNode = (Node)next.getValue(); if(!(nextNode.getNodeType() == Node.ELEMENT_NODE)) { Object value = getValueFromElement((Element)nextNode.getParentNode(), nextNode, next.getXMLField()); next.setValue(value); } else { next.setValue(buildNestedRow((Element)nextNode)); } } return values; } /** * INTERNAL: * Given a DatabaseField, return the corresponding values from the document */ public Object getValuesIndicatingNoEntry(DatabaseField key, boolean shouldReturnNodes) { return this.getValuesIndicatingNoEntry(key, shouldReturnNodes, null); } public Object getValuesIndicatingNoEntry(DatabaseField key, boolean shouldReturnNodes, AbstractNullPolicy nullPolicy) { XMLField field = convertToXMLField(key); NodeList nodeList = UnmarshalXPathEngine.getInstance().selectNodes(dom, field, field.getNamespaceResolver(), nullPolicy); // If a node was not found return null if (null == nodeList) { return null; } int resultSize = nodeList.getLength(); Vector result = new Vector(resultSize); if (resultSize == 0) { return result; } if(shouldReturnNodes) { //just copy all the nodes into the result vector and return it for(int i = 0; i < resultSize; i++) { result.add(nodeList.item(i)); } return result; } // Assumption: NodeList contains nodes of the same type Node firstNode = nodeList.item(0); if ((firstNode == null) || (firstNode.getNodeType()!= Node.ELEMENT_NODE)) { if (field.usesSingleNode() && (resultSize == 1)) { Node next = nodeList.item(0); if (next == null) { result.add(null); } else { Vector list = new Vector(); String sourceObject = next.getNodeValue(); StringTokenizer tokenizer = new StringTokenizer(sourceObject, " "); while (tokenizer.hasMoreElements()) { String token = tokenizer.nextToken(); Object nextItem = convertValue((Element)next.getParentNode(), field, token); list.add(nextItem); } return list; } } for (int x = 0; x < resultSize; x++) { Node next = nodeList.item(x); if (next == null) { result.add(null); } else { result.add(getValueFromElement((Element)next.getParentNode(), next, field)); } } } else { for (int x = 0; x < resultSize; x++) { result.add(buildNestedRow((Element)nodeList.item(x))); } } return result; } private Object getValueFromAttribute(Attr node, XMLField key) { currentNode = node.getOwnerElement(); Object convertedValue = key.convertValueBasedOnSchemaType(node.getNodeValue(), (XMLConversionManager) session.getDatasourcePlatform().getConversionManager(), this); currentNode = getDOM(); return convertedValue; } private Object getValueFromElement(Element node, Node textChild, Field key) { Object value = textChild.getNodeValue(); return convertValue(node, key, value); } private Object convertValue(Element node, Field key, Object value) { XMLConversionManager xmlCnvMgr = (XMLConversionManager) session.getDatasourcePlatform().getConversionManager(); if (key.isTypedTextField() && (node!= null)) { String schemaType = node.getAttributeNS(javax.xml.XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI, XMLConstants.SCHEMA_TYPE_ATTRIBUTE); if ((null!= schemaType) && (schemaType.length() > 0)) { QName qname = null; int index = schemaType.indexOf(XMLConstants.COLON); if (index == -1) { qname = new QName(schemaType); Class convertClass = key.getJavaClass(qname, xmlCnvMgr); return xmlCnvMgr.convertObject(value, convertClass); } else { String prefix = schemaType.substring(0, index); String localPart = schemaType.substring(index + 1); XMLPlatform xmlPlatform = XMLPlatformFactory.getInstance().getXMLPlatform(); String url = xmlPlatform.resolveNamespacePrefix(node, prefix); qname = new QName(url, localPart); Class convertClass = key.getJavaClass(qname, xmlCnvMgr); return xmlCnvMgr.convertObject(value, convertClass, qname); } } } currentNode = node; Object convertedValue = key.convertValueBasedOnSchemaType(value, xmlCnvMgr, this); currentNode = getDOM(); return convertedValue; } /** * INTERNAL: * Build the nested record, this can be overwriten by subclasses to use their subclass instance. */ public XMLRecord buildNestedRow(Element element) { DOMRecord record = new DOMRecord(element); record.setUnmarshaller(this.getUnmarshaller()); record.setOwningObject(this.getCurrentObject()); record.setDocPresPolicy(this.getDocPresPolicy()); record.setReferenceResolver(referenceResolver); return record; } /** * PUBLIC: * Return the DOM. */ @Override public Node getDOM() { return dom; } /** * INTERNAL: * Set the field value into the DOM. * The field name must be a valid simple XPath expression. */ @Override public Object put(DatabaseField key, Object value) { // Value may be a direct value, nested record, or collection of values. XMLField field = convertToXMLField(key); Object nodeValue = convertToNodeValue(value); NodeList replaced = null; boolean isEmptyCollection = false; if (nodeValue instanceof Collection) { isEmptyCollection = ((Collection)nodeValue).size() == 0; replaced = XPathEngine.getInstance().replaceCollection(convertToXMLField(key), dom, (Collection)nodeValue, session); } else { replaced = XPathEngine.getInstance().replaceValue(convertToXMLField(key), dom, nodeValue, session); } if (replaced.getLength() == 0) { // Replace does nothing if the node did not exist, return no nodes. XPathEngine.getInstance().create(convertToXMLField(key), dom, nodeValue, lastUpdatedField, getDocPresPolicy(), session); } else if (replaced.item(0) == getDOM()) { // If the root element/record element was changed must update the record's reference. setDOM(getDocument().getDocumentElement()); } if(!field.getXPathFragment().isAttribute() &&!field.getXPathFragment().nameIsText()) { if(value!= null &&!isEmptyCollection) { this.lastUpdatedField = field; } } return replaced; } public Object put(List<XMLField> xmlFields, List<XMLEntry> values) { Vector valuesToWrite = (Vector)convertToNodeValue(values); List<XMLEntry> replaced = null; replaced = XPathEngine.getInstance().replaceCollection(xmlFields, valuesToWrite, dom, getDocPresPolicy(), lastUpdatedField, session); if(replaced.size() == 0) { XPathEngine.getInstance().create(xmlFields, dom, valuesToWrite, lastUpdatedField, getDocPresPolicy(), session); } return replaced; } @Override public Object put(Object key, Object value) throws ValidationException { if (key instanceof String) { return put((String)key, value); } else if (key instanceof DatabaseField) { return put((DatabaseField)key, value); } else if (key instanceof List) { return put((List<XMLField>)key, (List<XMLEntry>)value); } else { throw ValidationException.onlyFieldsAreValidKeysForDatabaseRows(); } } /** * INTERNAL: * Remove the field key from the row. */ @Override public Object remove(DatabaseField key) { return XPathEngine.getInstance().remove(convertToXMLField(key), dom, true); } /** * INTERNAL: * replaces the value at index with value */ @Override public void replaceAt(Object value, int index) { throw XMLMarshalException.operationNotSupported("replaceAt(Object value, int index)"); } /** * PUBLIC: */ @Override public Set entrySet() { int size = this.size(); Map tempMap = new HashMap(size); Vector fields = getFields(); Vector values = getValues(); for (int i = 0; i < size; i++) { tempMap.put(fields.elementAt(i), values.elementAt(i)); } return tempMap.entrySet(); } /** * INTERNAL: * Setting fields vector will not update the document so this is not supported */ @Override protected void setFields(Vector fields) throws XMLMarshalException { throw XMLMarshalException.operationNotSupported("setField(Vector fields)"); } /** * INTERNAL: * This should not be used, but added some support for it as * is called from some places such as sdk call used in the descriptor to define operation not supported, * may also be called from toplin in some places. */ @Override public Vector getFields() { int length = getDOM().getChildNodes().getLength(); Node nextNode = null; if(length > 0) { nextNode = getDOM().getChildNodes().item(0); } Vector fields = new Vector(length); while(nextNode!= null) { fields.add(new DatabaseField(nextNode.getNodeName())); nextNode = nextNode.getNextSibling(); } return fields; } /** * INTERNAL: * This should not be used, but added some support for it as * is called from some places such as sdk call used in the descriptor to define operation not supported, * may also be called from TopLink in some places. */ @Override public Vector getValues() { int length = getDOM().getChildNodes().getLength(); Node nextNode = null; if(length > 0) { nextNode = getDOM().getFirstChild(); } Vector values = new Vector(length); while(nextNode!= null) { values.add(nextNode); nextNode = nextNode.getNextSibling(); } return values; } /** * INTERNAL: * Setting values vector will not update the document so this is not supported */ @Override protected void setValues(Vector values) throws XMLMarshalException { throw XMLMarshalException.operationNotSupported("setValues(Vector values)"); } /** * INTERNAL: * Sets the dom and updated document to be the owner document of the given element */ public void setDOM(Node element) { this.dom = element; this.currentNode = element; this.getNamespaceResolver().setDOM(element); } public void setDOM(Element element) { this.dom = element; this.currentNode = element; this.getNamespaceResolver().setDOM(element); } /** * INTERNAL: * Print the dom XML string. */ @Override public String toString() { StringWriter writer = new StringWriter(); writer.write(Helper.getShortClassName(getClass())); writer.write("("); transformToWriter(writer); writer.write(")"); return writer.toString(); } /** * PUBLIC: * Return the set of element names from the DOM. */ @Override public Set keySet() { int length = getDOM().getChildNodes().getLength(); HashSet keys = new HashSet(length); for (int index = 0; index < length; index++) { keys.add(getDOM().getChildNodes().item(index).getNodeName()); } return keys; } /** * PUBLIC: * Return the collection of element values from the DOM. */ @Override public Collection values() { int length = getDOM().getChildNodes().getLength(); Vector values = new Vector(length); for (int index = 0; index < length; index++) { values.add(getDOM().getChildNodes().item(index)); } return values; } /** * Return the number of elements in the DOM. */ @Override public int size() { return getDOM().getAttributes().getLength() + getDOM().getChildNodes().getLength(); } /** * Set the XML from an XML string. */ public void transformFromXML(String xml) { Reader reader = new StringReader(xml); transformFromXML(reader); } /** * INTERNAL: * Return the namespace uri for the prefix of the given local name */ private String resolveNamespace(NamespaceResolver namespaceResolver, String localName) { if(localName == null) { return null; } int colonIndex = localName.indexOf(XMLConstants.COLON); if (colonIndex < 0) { // handle target/default namespace if (namespaceResolver!= null) { return namespaceResolver.getDefaultNamespaceURI(); } return null; } else { if (namespaceResolver == null) { //throw an exception if the name has a : in it but the namespaceresolver is null throw XMLMarshalException.namespaceResolverNotSpecified(localName); } String prefix = localName.substring(0, colonIndex); String uri = namespaceResolver.resolveNamespacePrefix(prefix); if (uri == null) { //throw an exception if the prefix is not found in the namespaceresolver throw XMLMarshalException.namespaceNotFound(prefix); } return uri; } } @Override public void setSession(AbstractSession session) { this.session = session; if (session!= null && session.getDatasourceLogin() instanceof XMLLogin) { this.equalNamespaceResolvers = ((XMLLogin) session.getDatasourceLogin()).hasEqualNamespaceResolvers(); } } /** * Set the XML from an XML reader. */ public void transformFromXML(Reader reader) { XMLParser parser = XMLPlatformFactory.getInstance().getXMLPlatform().newXMLParser(); Document document = parser.parse(reader); setDOM(document.getDocumentElement()); } /** * Return the XML string representation of the DOM. */ @Override public String transformToXML() { StringWriter writer = new StringWriter(); transformToWriter(writer); return writer.toString(); } /** * Write the XML string representation of the DOM. */ public void transformToWriter(Writer writer) { XMLTransformer xmlTransformer = XMLPlatformFactory.getInstance().getXMLPlatform().newXMLTransformer(); xmlTransformer.transform(this.getDOM(), writer); } @Override public String resolveNamespacePrefix(String prefix) { XMLPlatform xmlPlatform = XMLPlatformFactory.getInstance().getXMLPlatform(); return xmlPlatform.resolveNamespacePrefix(currentNode, prefix); } /** * INTERNAL: * If the UnmarshalRecord has a ReferenceResolver, tell it to resolve its * references. * @since EclipseLink 2.5.0 */ public void resolveReferences(CoreAbstractSession abstractSession, IDResolver idResolver) { if(null!= referenceResolver) { referenceResolver.resolveReferences(abstractSession, idResolver, unmarshaller.getErrorHandler()); } } } ======================= File: jpa/org.eclipse.persistence.jpa.jpql/src/org/eclipse/persistence/jpa/jpql/parser/EclipseLinkJPQLGrammar2_4.java ======================= /******************************************************************************* * Copyright (c) 2006, 2018 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation * ******************************************************************************/ package org.eclipse.persistence.jpa.jpql.parser; import org.eclipse.persistence.jpa.jpql.EclipseLinkVersion; import org.eclipse.persistence.jpa.jpql.JPAVersion; import org.eclipse.persistence.jpa.jpql.parser.FunctionExpressionFactory.ParameterCount; import static org.eclipse.persistence.jpa.jpql.parser.Expression.*; /** * <p>This {@link JPQLGrammar} provides support for parsing JPQL queries defined in <a * href="http://jcp.org/en/jsr/detail?id=317">JSR-338 - Java Persistence 2.1</a> and the additional * support provided by EclipseLink 2.4.</p> * * The BNFs of the additional support are the following: * * <pre><code> select_statement ::= select_clause from_clause [where_clause] [groupby_clause] [having_clause] [orderby_clause] {union_clause}* * * union_clause ::= { UNION | INTERSECT | EXCEPT} [ALL] subquery * * from_clause ::= FROM identification_variable_declaration {, {identification_variable_declaration | * collection_member_declaration | * (subquery) | * table_variable_declaration }}* * * range_variable_declaration ::= root_object [AS] identification_variable * * root_object ::= abstract_schema_name | fully_qualified_class_name * * table_variable_declaration ::= table_expression [AS] identification_variable * * join ::= join_spec { abstract_schema_name | join_association_path_expression } [AS] identification_variable [join_condition] * * functions_returning_datetime ::= cast_expression | * extract_expression | * ... * * functions_returning_string ::= cast_expression | * extract_expression | * ... * * functions_returning_numeric ::= cast_expression | * extract_expression | * ... * * simple_cond_expression ::= regexp_expression | * ... * * function_expression ::= { FUNC | FUNCTION | OPERATOR | SQL | COLUMN } (string_literal {, function_arg}*) * * regexp_expression ::= string_expression REGEXP pattern_value * * extract_expression ::= EXTRACT(date_part_literal [FROM] scalar_expression) * * table_expression ::= TABLE(string_literal) * * date_part_literal ::= { MICROSECOND | SECOND | MINUTE | HOUR | DAY | WEEK | MONTH | QUARTER | * YEAR | SECOND_MICROSECOND | MINUTE_MICROSECOND | MINUTE_SECOND | * HOUR_MICROSECOND | HOUR_SECOND | HOUR_MINUTE | DAY_MICROSECOND | * DAY_SECOND | DAY_MINUTE | DAY_HOUR | YEAR_MONTH, etc } * * cast_expression ::= CAST(scalar_expression [AS] database_type) * * database_type ::= data_type_literal [( [numeric_literal [, numeric_literal]] )] * * data_type_literal ::= [CHAR, VARCHAR, NUMERIC, INTEGER, DATE, TIME, TIMESTAMP, etc]</code></pre> * * <p>Provisional API: This interface is part of an interim API that is still under development and * expected to change significantly before reaching stability. It is available at this early stage * to solicit feedback from pioneering adopters on the understanding that any code that uses this * API will almost certainly be broken (repeatedly) as the API evolves.</p> * * @version 2.5 * @since 2.4 * @author <NAME> */ @SuppressWarnings("nls") public final class EclipseLinkJPQLGrammar2_4 extends AbstractJPQLGrammar { /** * The singleton instance of this {@link EclipseLinkJPQLGrammar2_4}. */ private static final JPQLGrammar INSTANCE = new EclipseLinkJPQLGrammar2_4(); /** * The EclipseLink version, which is 2.4. */ public static final EclipseLinkVersion VERSION = EclipseLinkVersion.VERSION_2_4; /** * Creates a new <code>EclipseLinkJPQLGrammar2_4</code>. */ public EclipseLinkJPQLGrammar2_4() { super(); } /** * Creates a new <code>EclipseLinkJPQLGrammar2_4</code>. * * @param jpqlGrammar The {@link JPQLGrammar} to extend with the content of this one without * instantiating the base {@link JPQLGrammar} */ private EclipseLinkJPQLGrammar2_4(AbstractJPQLGrammar jpqlGrammar) { super(jpqlGrammar); } /** * Extends the given {@link JPQLGrammar} with the information of this one without instantiating * the base {@link JPQLGrammar}. * * @param jpqlGrammar The {@link JPQLGrammar} to extend with the content of this one without * instantiating the base {@link JPQLGrammar} */ public static void extend(AbstractJPQLGrammar jpqlGrammar) { new EclipseLinkJPQLGrammar2_4(jpqlGrammar); } /** * Returns the singleton instance of this class. * * @return The singleton instance of {@link EclipseLinkJPQLGrammar2_4} */ public static JPQLGrammar instance() { return INSTANCE; } /** * {@inheritDoc} */ @Override protected JPQLGrammar buildBaseGrammar() { // First build the JPQL 2.1 grammar JPQLGrammar2_1 jpqlGrammar = new JPQLGrammar2_1(); // Extend it by adding the EclipseLink 2.0 additional support EclipseLinkJPQLGrammar2_0.extend(jpqlGrammar); // Extend it by adding the EclipseLink 2.1 additional support EclipseLinkJPQLGrammar2_1.extend(jpqlGrammar); return jpqlGrammar; } /** * {@inheritDoc} */ @Override public JPAVersion getJPAVersion() { return JPAVersion.VERSION_2_1; } /** * {@inheritDoc} */ @Override public String getProvider() { return DefaultEclipseLinkJPQLGrammar.PROVIDER_NAME; } /** * {@inheritDoc} */ @Override public String getProviderVersion() { return VERSION.getVersion(); } /** * {@inheritDoc} */ @Override protected void initializeBNFs() { registerBNF(new CastExpressionBNF()); registerBNF(new DatabaseTypeQueryBNF()); registerBNF(new ExtractExpressionBNF()); registerBNF(new InternalColumnExpressionBNF()); registerBNF(new RegexpExpressionBNF()); registerBNF(new TableExpressionBNF()); registerBNF(new TableVariableDeclarationBNF()); registerBNF(new UnionClauseBNF()); // This is required to properly validate an entity name used as a join association path addChildBNF(JoinAssociationPathExpressionBNF.ID, AbstractSchemaNameBNF.ID); // Override (internal) simple_select_expression to add support for result variable registerBNF(new SimpleResultVariableBNF()); // Note: This should only support SQL expression addChildBNF(SimpleConditionalExpressionBNF.ID, FunctionExpressionBNF.ID); // CAST addChildBNF(FunctionsReturningDatetimeBNF.ID, CastExpressionBNF.ID); addChildBNF(FunctionsReturningNumericsBNF.ID, CastExpressionBNF.ID); addChildBNF(FunctionsReturningStringsBNF.ID, CastExpressionBNF.ID); // EXTRACT addChildBNF(FunctionsReturningDatetimeBNF.ID, ExtractExpressionBNF.ID); addChildBNF(FunctionsReturningNumericsBNF.ID, ExtractExpressionBNF.ID); addChildBNF(FunctionsReturningStringsBNF.ID, ExtractExpressionBNF.ID); // REGEXP addChildBNF(SimpleConditionalExpressionBNF.ID, RegexpExpressionBNF.ID); // Add subquery support to RangeDeclarationBNF addChildBNF(RangeDeclarationBNF.ID, SubqueryBNF.ID); // Add table declaration to the FROM clause's declaration addChildBNF(InternalFromClauseBNF.ID, TableVariableDeclarationBNF.ID); addChildBNF(InternalSimpleFromClauseBNF.ID, TableVariableDeclarationBNF.ID); // Trickle down the handling of a sub expression (subquery) to RangeVariableDeclaration // and in order to keep the hierarchy intact, otherwise the default behavior would be // FromClause would parse the subquery immediately. // // FromClause // |- IdentificationVariableDeclaration // |- RangeVariableDeclaration [(subquery) AS identification_variable] // |- SubExpression // |- SimpleSelectStatement setHandleSubExpression(InternalFromClauseBNF.ID, true); setHandleSubExpression(InternalSimpleFromClauseBNF.ID, true); setHandleSubExpression(IdentificationVariableDeclarationBNF.ID, true); setHandleSubExpression(RangeVariableDeclarationBNF.ID, true); } /** * {@inheritDoc} */ @Override protected void initializeExpressionFactories() { registerFactory(new CastExpressionFactory()); registerFactory(new DatabaseTypeFactory()); registerFactory(new ExtractExpressionFactory()); registerFactory(new JoinCollectionValuedPathExpressionFactory()); registerFactory(new OnClauseFactory()); registerFactory(new RegexpExpressionFactory()); registerFactory(new TableExpressionFactory()); registerFactory(new TableVariableDeclarationFactory()); registerFactory(new UnionClauseFactory()); // Add a new FunctionExpression for 'COLUMN' since it has different rules FunctionExpressionFactory columnExpressionFactory = new FunctionExpressionFactory(COLUMN, COLUMN); columnExpressionFactory.setParameterCount(ParameterCount.ONE); columnExpressionFactory.setParameterQueryBNFId(InternalColumnExpressionBNF.ID); registerFactory(columnExpressionFactory); // Add COLUMN ExpressionFactory to FunctionExpressionBNF addChildFactory(FunctionExpressionBNF.ID, COLUMN); // Change the fallback ExpressionFactory to add support for an abstract schema name // as a valid join association path expression setFallbackExpressionFactoryId(JoinAssociationPathExpressionBNF.ID, JoinCollectionValuedPathExpressionFactory.ID); } /** * {@inheritDoc} */ @Override protected void initializeIdentifiers() { // Expand FunctionExpression to support 'FUNCTION', 'OPERATOR' and 'SQL' addIdentifiers(FunctionExpressionFactory.ID, FUNCTION, OPERATOR, SQL); registerIdentifierRole(CAST, IdentifierRole.FUNCTION); // FUNCTION(n, x1,..., x2) registerIdentifierRole(COLUMN, IdentifierRole.FUNCTION); // FUNCTION(n, x1,..., x2) registerIdentifierRole(EXCEPT, IdentifierRole.CLAUSE); registerIdentifierRole(EXTRACT, IdentifierRole.FUNCTION); // EXTRACT(x FROM y) registerIdentifierRole(FUNCTION, IdentifierRole.FUNCTION); // FUNCTION(n, x1,..., x2) registerIdentifierRole(INTERSECT, IdentifierRole.CLAUSE); registerIdentifierRole(NULLS_FIRST, IdentifierRole.COMPLEMENT); registerIdentifierRole(NULLS_LAST, IdentifierRole.COMPLEMENT); registerIdentifierRole(ON, IdentifierRole.CLAUSE); // ON x registerIdentifierRole(OPERATOR, IdentifierRole.FUNCTION); // FUNCTION(n, x1,..., x2) registerIdentifierRole(REGEXP, IdentifierRole.COMPOUND_FUNCTION); // x REGEXP y registerIdentifierRole(SQL, IdentifierRole.FUNCTION); // FUNCTION(n, x1,..., x2) registerIdentifierRole(TABLE, IdentifierRole.FUNCTION); // TABLE('TABLE_NAME') registerIdentifierRole(UNION, IdentifierRole.CLAUSE); registerIdentifierVersion(CAST, JPAVersion.VERSION_2_1); registerIdentifierVersion(COLUMN, JPAVersion.VERSION_2_1); registerIdentifierVersion(EXCEPT, JPAVersion.VERSION_2_1); registerIdentifierVersion(EXTRACT, JPAVersion.VERSION_2_1); registerIdentifierVersion(FUNCTION, JPAVersion.VERSION_2_1); registerIdentifierVersion(INTERSECT, JPAVersion.VERSION_2_1); registerIdentifierVersion(NULLS_FIRST, JPAVersion.VERSION_2_1); registerIdentifierVersion(NULLS_LAST, JPAVersion.VERSION_2_1); registerIdentifierVersion(ON, JPAVersion.VERSION_2_1); registerIdentifierVersion(OPERATOR, JPAVersion.VERSION_2_1); registerIdentifierVersion(REGEXP, JPAVersion.VERSION_2_1); registerIdentifierVersion(SQL, JPAVersion.VERSION_2_1); registerIdentifierVersion(TABLE, JPAVersion.VERSION_2_1); registerIdentifierVersion(UNION, JPAVersion.VERSION_2_1); // Partial identifiers registerIdentifierRole("NULLS", IdentifierRole.CLAUSE); // Part of NULLS FIRST, NULLS LAST registerIdentifierRole("FIRST", IdentifierRole.CLAUSE); // Part of NULLS FIRST registerIdentifierRole("LAST", IdentifierRole.CLAUSE); // Part of NULLS LAST } /** * {@inheritDoc} */ @Override public String toString() { return "EclipseLink 2.4"; } } ======================= File: foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/sessions/server/Server.java ======================= /******************************************************************************* * Copyright (c) 1998, 2018 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation from Oracle TopLink ******************************************************************************/ package org.eclipse.persistence.sessions.server; import org.eclipse.persistence.sessions.*; import org.eclipse.persistence.exceptions.*; /** * <p> * <b>Purpose</b>: A single session that supports multiple user/clients connection at the same time. * <p> * <b>Description</b>: This session supports a shared session that can be used by multiple users * or clients in a three-tiered application. It brokers client sessions to allow read and write access * through a unified object cache. The server session uses a single connection pool by default, but allows multiple connection * pools and separate read/write pools to be configured. All changes to objects and the database must be done through * a unit of work acquired from the client session, this allows the changes to occur in a transactional object * space and under a exclusive database connection. * <p> * <b>Responsibilities</b>: * <ul> * <li> Connection pooling. * <li> Reading objects and maintaining the object cache. * <li> Brokering client sessions. * <li> Requiring the UnitOfWork to be used for modification. * </ul> * * @see Server * @see ClientSession * @see UnitOfWork */ public interface Server extends org.eclipse.persistence.sessions.DatabaseSession { /** * PUBLIC: * Return a client session for this server session. * Each user/client connected to this server session must acquire there own client session * to communicate to the server through. * This method allows for a client session to be acquired sharing the same login as the server session. */ public ClientSession acquireClientSession() throws DatabaseException; /** * PUBLIC: * Return a client session for this server session. * Each user/client connected to this server session must acquire there own client session * to communicate to the server through. * This method allows for a client session to be acquired sharing its connection from a pool * of connection allocated on the server session. * By default this uses a lazy connection policy. */ public ClientSession acquireClientSession(String poolName); /** * PUBLIC: * Return a client session for this server session. * Each user/client connected to this server session must acquire there own client session * to communicate to the server through. * The client must provide its own login to use, and the client session returned * will have its own exclusive database connection. This connection will be used to perform * all database modification for all units of work acquired from the client session. * By default this does not use a lazy connection policy. */ public ClientSession acquireClientSession(Login login); /** * PUBLIC: * Return a client session for this server session. * The connection policy specifies how the client session's connection will be acquired. */ public ClientSession acquireClientSession(ConnectionPolicy connectionPolicy); /** * PUBLIC: * Add the connection pool. * Connections are pooled to share and restrict the number of database connections. */ public void addConnectionPool(String poolName, Login login, int minNumberOfConnections, int maxNumberOfConnections); /** * PUBLIC: * Connection are pooled to share and restrict the number of database connections. */ public void addConnectionPool(ConnectionPool pool); /** * PUBLIC: * Return the pool by name. */ public ConnectionPool getConnectionPool(String poolName); /** * PUBLIC: * The default connection policy is used by default by the acquireClientConnection() protocol. * By default it uses the default connection pool. */ public ConnectionPolicy getDefaultConnectionPolicy(); /** * PUBLIC: * Return the default connection pool. */ public ConnectionPool getDefaultConnectionPool(); /** * PUBLIC: * Return the number of non-pooled database connections allowed. * This can be enforced to make up for the resource limitation of most JDBC drivers and database clients. * By default this is 50. */ public int getMaxNumberOfNonPooledConnections(); /** * PUBLIC: * Handles allocating connections for read queries. * <p> * By default a read connection pool is not used, the default connection pool is used for reading. * <p> The read connection pool is not used while in transaction. * @see #setReadConnectionPool(ConnectionPool) * @see #useExclusiveReadConnectionPool * @see #useExternalReadConnectionPool * @see #useReadConnectionPool */ public ConnectionPool getReadConnectionPool(); /** * PUBLIC: * Set the login. */ @Override public void setDatasourceLogin(Login login); /** * PUBLIC: * The default connection policy is used by default by the acquireClientConnection() protocol. * By default it uses the default connection pool. */ public void setDefaultConnectionPolicy(ConnectionPolicy defaultConnectionPolicy); /** * PUBLIC: * Set the number of non-pooled database connections allowed. * This can be enforced to make up for the resource limitation of most JDBC drivers and database clients. * By default this is 50. */ public void setMaxNumberOfNonPooledConnections(int maxNumberOfNonPooledConnections); /** * PUBLIC: * Sets the read connection pool directly. * <p> * Either {@link #useExclusiveReadConnectionPool} or {@link #useExternalReadConnectionPool} is * called in the constructor. For a connection pool using concurrent reading * {@link #useReadConnectionPool} should be called on a new instance of <code>this</code>. * * @throws ValidationException if already connected */ public void setReadConnectionPool(ConnectionPool readConnectionPool); /** * PUBLIC: * Sets the read connection pool to be a separate exclusive <code>ConnectionPool</code> * with the minimum and maximum number of connections. * <p> * A separate read connection pool is not used by default, by default the default connection pool is used for reading. * A separate read connection pool can be used to dedicate a pool of connections only for reading. * It can also be used to use a non-JTA DataSource for reading to avoid JTA overhead, * or to use a different user login for reading. * * @see #getReadConnectionPool * @see #setReadConnectionPool(ConnectionPool) * @see #useReadConnectionPool * @see #useExternalReadConnectionPool */ public void useExclusiveReadConnectionPool(int minNumberOfConnections, int maxNumberOfConnections); /** * PUBLIC: * Sets the read connection pool to be a separate exclusive <code>ConnectionPool</code> * with the initial, minimum and maximum number of connections. * <p> * A separate read connection pool is not used by default, by default the default connection pool is used for reading. * A separate read connection pool can be used to dedicate a pool of connections only for reading. * It can also be used to use a non-JTA DataSource for reading to avoid JTA overhead, * or to use a different user login for reading. * * @see #getReadConnectionPool * @see #setReadConnectionPool(ConnectionPool) * @see #useReadConnectionPool * @see #useExternalReadConnectionPool */ public void useExclusiveReadConnectionPool(int initialNumberOfConnections, int minNumberOfConnections, int maxNumberOfConnections); /** * PUBLIC: * Sets the read connection pool to be an <code>ExternalConnectionPool</code>. * <p> * This type of connection pool will be created and configured automatically if * an external connection pooling is used. * * @see #getReadConnectionPool * @see #setReadConnectionPool(ConnectionPool) * @see #useReadConnectionPool * @see #useExclusiveReadConnectionPool */ public void useExternalReadConnectionPool(); /** * PUBLIC: * Sets the read connection pool to be a separate shared <code>ConnectionPool</code> * with the minimum and maximum number of connections. * <p> * A separate read connection pool is not used by default, by default the default connection pool is used for reading. * A separate read connection pool can be used to dedicate a pool of connections only for reading. * It can also be used to use a non-JTA DataSource for reading to avoid JTA overhead, * or to use a different user login for reading. * <p> * Since read connections are not used for writing, multiple users can * theoretically use the same connection at the same time. * However some JDBC drivers do not allow this, or have poor concurrency when this is done. * <p> * Use this read connection pool to take advantage of concurrent reading. * <p> * @param minNumberOfConnections * @param maxNumberOfConnections As multiple readers can use the same connection * concurrently fewer connections are needed. * @see #getReadConnectionPool * @see #setReadConnectionPool(ConnectionPool) * @see #useExternalReadConnectionPool * @see #useExclusiveReadConnectionPool */ public void useReadConnectionPool(int minNumberOfConnections, int maxNumberOfConnections); /** * PUBLIC: * Sets the read connection pool to be a separate shared <code>ConnectionPool</code> * with the minimum and maximum number of connections. * <p> * A separate read connection pool is not used by default, by default the default connection pool is used for reading. * A separate read connection pool can be used to dedicate a pool of connections only for reading. * It can also be used to use a non-JTA DataSource for reading to avoid JTA overhead, * or to use a different user login for reading. * <p> * Since read connections are not used for writing, multiple users can * theoretically use the same connection at the same time. * However some JDBC drivers do not allow this, or have poor concurrency when this is done. * <p> * Use this read connection pool to take advantage of concurrent reading. * <p> * @param initialNumberOfConnections connections connected at startup * @param minNumberOfConnections connections that are pooled * @param maxNumberOfConnections As multiple readers can use the same connection * concurrently fewer connections are needed. * @see #getReadConnectionPool * @see #setReadConnectionPool(ConnectionPool) * @see #useExternalReadConnectionPool * @see #useExclusiveReadConnectionPool */ public void useReadConnectionPool(int initialNumberOfConnections, int minNumberOfConnections, int maxNumberOfConnections); } ======================= File: jpa/org.eclipse.persistence.jpa/src/org/eclipse/persistence/internal/jpa/metadata/converters/LobMetadata.java ======================= /******************************************************************************* * Copyright (c) 1998, 2018 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * 05/16/2008-1.0M8 <NAME> * - 218084: Implement metadata merging functionality between mapping files * 03/27/2009-2.0 <NAME> * - 241413: JPA 2.0 Add EclipseLink support for Map type attributes * 04/27/2010-2.1 <NAME> * - 309856: MappedSuperclasses from XML are not being initialized properly * 03/24/2011-2.3 <NAME> * - 337323: Multi-tenant with shared schema support (part 1) ******************************************************************************/ package org.eclipse.persistence.internal.jpa.metadata.converters; import java.io.Serializable; import org.eclipse.persistence.mappings.DatabaseMapping; import org.eclipse.persistence.mappings.converters.SerializedObjectConverter; import org.eclipse.persistence.mappings.converters.TypeConversionConverter; import org.eclipse.persistence.exceptions.ValidationException; import org.eclipse.persistence.internal.jpa.metadata.accessors.MetadataAccessor; import org.eclipse.persistence.internal.jpa.metadata.accessors.mappings.MappingAccessor; import org.eclipse.persistence.internal.jpa.metadata.accessors.objects.MetadataAnnotation; import org.eclipse.persistence.internal.jpa.metadata.accessors.objects.MetadataClass; /** * INTERNAL: * Abstract converter class that parents both the JPA and Eclipselink * converters. * * Key notes: * - any metadata mapped from XML to this class must be compared in the * equals method. * - when loading from annotations, the constructor accepts the metadata * accessor this metadata was loaded from. Used it to look up any * 'companion' annotation needed for processing. * - methods should be preserved in alphabetical order. * * @author <NAME> * @since EclipseLink 1.2 */ public class LobMetadata extends MetadataConverter { /** * INTERNAL: * Used for XML loading. */ public LobMetadata() { super("<lob>"); } /** * INTERNAL: * Used for annotation loading. */ public LobMetadata(MetadataAnnotation lob, MetadataAccessor accessor) { super(lob, accessor); // Nothing to read off a lob. } /** * INTERNAL: */ @Override public boolean equals(Object objectToCompare) { return super.equals(objectToCompare) && objectToCompare instanceof LobMetadata; } @Override public int hashCode() { return super.hashCode(); } /** * INTERNAL: * Returns true if the given class is a valid blob type. */ public static boolean isValidBlobType(MetadataClass cls) { return cls.equals(byte[].class) || cls.equals(Byte[].class) || cls.equals(java.sql.Blob.class); } /** * INTERNAL: * Returns true if the given class is a valid clob type. */ public static boolean isValidClobType(MetadataClass cls) { return cls.equals(char[].class) || cls.equals(String.class) || cls.equals(Character[].class) || cls.equals(java.sql.Clob.class); } /** * INTERNAL: * Returns true if the given class is a valid lob type. */ public static boolean isValidLobType(MetadataClass cls) { return isValidClobType(cls) || isValidBlobType(cls); } /** * INTERNAL: * Every converter needs to be able to process themselves. */ @Override public void process(DatabaseMapping mapping, MappingAccessor accessor, MetadataClass referenceClass, boolean isForMapKey) { // Set the field classification type on the mapping based on the // referenceClass type. if (isValidClobType(referenceClass)) { setFieldClassification(mapping, java.sql.Clob.class, isForMapKey); setConverter(mapping, new TypeConversionConverter(mapping), isForMapKey); } else if (isValidBlobType(referenceClass)) { setFieldClassification(mapping, java.sql.Blob.class, isForMapKey); setConverter(mapping, new TypeConversionConverter(mapping), isForMapKey); } else if (referenceClass.extendsInterface(Serializable.class)) { setFieldClassification(mapping, java.sql.Blob.class, isForMapKey); setConverter(mapping, new SerializedObjectConverter(mapping), isForMapKey); } else { // The referenceClass is neither a valid BLOB or CLOB attribute. throw ValidationException.invalidTypeForLOBAttribute(mapping.getAttributeName(), referenceClass, accessor.getJavaClass()); } } } ======================= File: foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/internal/sessions/UnitOfWorkChangeSet.java ======================= <gh_stars>0 /******************************************************************************* * Copyright (c) 1998, 2018 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation from Oracle TopLink ******************************************************************************/ package org.eclipse.persistence.internal.sessions; import java.io.Serializable; import java.util.HashMap; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.eclipse.persistence.descriptors.ClassDescriptor; import org.eclipse.persistence.internal.identitymaps.CacheId; import org.eclipse.persistence.internal.identitymaps.CacheKey; import org.eclipse.persistence.mappings.DatabaseMapping; import org.eclipse.persistence.queries.FetchGroup; /** * <p> * <b>Purpose</b>: This is the overall collection of changes. * <p> * <b>Description</b>: It holds all of the object changes and * all ObjectChanges, with the same classType and primary keys, referenced in a changeSet should be * the same object. * <p> */ public class UnitOfWorkChangeSet implements Serializable, org.eclipse.persistence.sessions.changesets.UnitOfWorkChangeSet { /** This is the collection of ObjectChanges held by this ChangeSet */ // *** TODO fix transients *** */ protected Map<Class, Map<ObjectChangeSet, ObjectChangeSet>> objectChanges; // This collection holds the new objects which will have no real identity until inserted. protected Map<Class, Map<ObjectChangeSet, ObjectChangeSet>> newObjectChangeSets; protected Map<Object, ObjectChangeSet> cloneToObjectChangeSet; protected Map<ObjectChangeSet, Object> objectChangeSetToUOWClone; protected Map<ObjectChangeSet, ObjectChangeSet> aggregateChangeSets; protected Map<ObjectChangeSet, ObjectChangeSet> allChangeSets; protected Map<ObjectChangeSet, ObjectChangeSet> deletedObjects; /** This attribute is set to true if a changeSet with changes has been added */ protected boolean hasChanges; protected boolean hasForcedChanges; /** * Flag set when calling commitToDatabaseWithPreBuiltChangeSet * so we are aware the UOW does not contain the changes from this change set. */ protected boolean isChangeSetFromOutsideUOW; /** Stores unit of work before it is serialized. */ protected transient AbstractSession session; /** * INTERNAL: * Create a ChangeSet */ public UnitOfWorkChangeSet() { } /** * INTERNAL: * Create a ChangeSet */ public UnitOfWorkChangeSet(AbstractSession session) { this.session = session; } /** * Return the session. * This only exists before serialization. */ public AbstractSession getSession() { return session; } /** * INTERNAL: * Set the session. * This only exists before serialization. */ public void setSession(AbstractSession session) { this.session = session; } /** * INTERNAL: * Add the Deleted objects to the changeSet. */ public void addDeletedObjects(Map deletedObjects, AbstractSession session) { Iterator enumtr = deletedObjects.keySet().iterator(); while (enumtr.hasNext()) { Object object = enumtr.next(); this.addDeletedObject(object, session); } } /** * INTERNAL: * Add the Deleted object to the changeSet. */ public void addDeletedObject(Object object, AbstractSession session) { //CR 4080 - must prevent aggregate objects added to DeletedObjects list ClassDescriptor descriptor = session.getDescriptor(object); if (!descriptor.isAggregateCollectionDescriptor()) { ObjectChangeSet set = descriptor.getObjectBuilder().createObjectChangeSet(object, this, false, session); // needed for xml change set set.setShouldBeDeleted(true); getDeletedObjects().put(set, set); } } /** * INTERNAL: * Add to the changes for 'object' object to this changeSet. This method * will not add to the lists that are used for identity lookups. * The passed change set *must* either have changes or forced changes. * @see addObjectChangeSetForIdentity() * @param forceToNewObjectList - Any pre commit actions should pass in true * since new objects have extra-handling. Anything post commit, pass in * false. */ public void addObjectChangeSet(ObjectChangeSet objectChanges, AbstractSession session, boolean forceToNewObjectList) { if (objectChanges!= null) { if (objectChanges.isNew() && forceToNewObjectList) { // Add it to the new list (unless there is no force, that is, // we are in a post commit and we can trust the cache key then) // so we do not loose it as it may not have a valid primary key // it will be moved to the standard list once it is inserted. addNewObjectChangeSet(objectChanges, session); getAllChangeSets().put(objectChanges, objectChanges); } else { // If this object change set has changes or forced changes then // record this. Must be done for each change set added because // some may not contain'real' changes. This is the case for // opt. read lock and forceUdpate. Keep the flags separate // because we don't want to cache sync. a change set with no //'real' changes. boolean objectChangeSetHasChanges = objectChanges.hasChanges(); if (objectChangeSetHasChanges) { this.setHasChanges(true); this.hasForcedChanges = this.hasForcedChanges || objectChanges.hasForcedChanges(); } else { // Object change set doesn't have changes so it has to have // forced changes. this.hasForcedChanges = true; } if (!objectChanges.isAggregate()) { if (objectChangeSetHasChanges) { // Each time I create a changeSet it is added to this // list and when I compute a changeSet for this object // I again add it to these lists so that before this // UOWChangeSet is Serialized there is a copy of every // changeSet which has changes affecting cache in // allChangeSets. getAllChangeSets().put(objectChanges, objectChanges); } if (objectChanges.getId()!= null) { Map<ObjectChangeSet, ObjectChangeSet> map = getObjectChanges().get(objectChanges.getClassType()); if (map == null) { map = new HashMap<ObjectChangeSet, ObjectChangeSet>(); getObjectChanges().put(objectChanges.getClassType(), map); map.put(objectChanges, objectChanges); } else { map.put(objectChanges, objectChanges); } } } } } } /** * INTERNAL: * Add to the changes for 'object' object to this changeSet. This method will not * add to the lists that are used for identity lookups. It is called specifically * for new objects, and new object will be moved to the standard changes list by * the QueryMechanism after insert. * @see addObjectChangeSetForIdentity() * @param objectChanges the new object change set */ protected void addNewObjectChangeSet(ObjectChangeSet objectChanges, AbstractSession session) { Map<ObjectChangeSet, ObjectChangeSet> changeSetTable = getNewObjectChangeSets().get(objectChanges.getClassType(session)); if (changeSetTable == null) { // 2612538 - the default size of Map (32) is appropriate changeSetTable = new IdentityHashMap<ObjectChangeSet, ObjectChangeSet>(); getNewObjectChangeSets().put(objectChanges.getClassType(session), changeSetTable); } changeSetTable.put(objectChanges, objectChanges); this.hasChanges = true; } /** * INTERNAL: * This method can be used find the equivalent changeset within this UnitOfWorkChangeSet * Aggregates, and new objects without primaryKeys from serialized ChangeSets will not be found * Which may result in duplicates, in the UnitOfWorkChangeSet. */ public ObjectChangeSet findObjectChangeSet(ObjectChangeSet changeSet, UnitOfWorkChangeSet mergeFromChangeSet) { Map<ObjectChangeSet, ObjectChangeSet> changes = getObjectChanges().get(changeSet.getClassType()); ObjectChangeSet potential = null; if (changes!= null) { potential = changes.get(changeSet); } if (potential == null) { potential = (ObjectChangeSet)getObjectChangeSetForClone(changeSet.getUnitOfWorkClone()); } return potential; } /** * INTERNAL: * This method will be used during the merge process to either find an equivalent change set * within this UnitOfWorkChangeSet or integrate that changeset into this UOW ChangeSet */ public ObjectChangeSet findOrIntegrateObjectChangeSet(ObjectChangeSet tofind, UnitOfWorkChangeSet mergeFromChangeSet) { if (tofind == null) { return tofind; } ObjectChangeSet localChangeSet = this.findObjectChangeSet(tofind, mergeFromChangeSet); if (localChangeSet == null) {//not found locally then replace it with the one from the merging changeset if (tofind.getDescriptor() == null) { tofind.getClassType(this.session); tofind.setDescriptor(this.session.getDescriptor(tofind.getClassType())); } localChangeSet = new ObjectChangeSet(tofind.getId(), tofind.getDescriptor(), tofind.getUnitOfWorkClone(), this, tofind.isNew()); this.addObjectChangeSetForIdentity(localChangeSet, localChangeSet.getUnitOfWorkClone()); } return localChangeSet; } /** * INTERNAL" * This method is used during the merge process to either find the existing ChangeSet or create a new one. */ public ObjectChangeSet findOrCreateLocalObjectChangeSet(Object entityClone, ClassDescriptor descriptor, boolean isNew){ ObjectChangeSet changes = (ObjectChangeSet)this.getObjectChangeSetForClone(entityClone); if (changes == null) { if (descriptor.hasInheritance() && descriptor.getJavaClass()!= entityClone.getClass()) { descriptor = descriptor.getInheritancePolicy().getSubclassDescriptor(entityClone.getClass()); } if (descriptor.isAggregateDescriptor()) { changes = new AggregateObjectChangeSet(CacheId.EMPTY, descriptor, entityClone, this, isNew); } else { changes = new ObjectChangeSet(descriptor.getObjectBuilder().extractPrimaryKeyFromObject(entityClone, session), descriptor, entityClone, this, isNew); } changes.setIsAggregate(descriptor.isDescriptorTypeAggregate()); this.addObjectChangeSetForIdentity(changes, entityClone); } return changes; } /** * INTERNAL: * Add change records to the lists used to maintain identity. This will not actually * add the changes to 'object' to the change set. * @see addObjectChangeSet() * @param objectChanges prototype.changeset.ObjectChanges */ public void addObjectChangeSetForIdentity(ObjectChangeSet objectChanges, Object object) { if ((objectChanges == null) || (object == null)) { return; } if (objectChanges.isAggregate()) { getAggregateChangeSets().put(objectChanges, objectChanges); } getObjectChangeSetToUOWClone().put(objectChanges, object); getCloneToObjectChangeSet().put(object, objectChanges); } /** * INTERNAL: * Get the Aggregate list. Lazy initializes the map if required. */ public Map<ObjectChangeSet, ObjectChangeSet> getAggregateChangeSets() { if (this.aggregateChangeSets == null) { this.aggregateChangeSets = new IdentityHashMap<ObjectChangeSet, ObjectChangeSet>(); } return this.aggregateChangeSets; } /** * INTERNAL: * This method returns a reference to the collection. */ @Override public Map<ObjectChangeSet, ObjectChangeSet> getAllChangeSets() { if (this.allChangeSets == null) { // 2612538 - the default size of Map (32) is appropriate this.allChangeSets = new IdentityHashMap<ObjectChangeSet, ObjectChangeSet>(); } return this.allChangeSets; } /** * INTERNAL: * Return a new UnitOfWorkChangeSet that only includes data require for the remote merge, * for cache coordination. * * @param session current database session */ public UnitOfWorkChangeSet buildCacheCoordinationMergeChangeSet(AbstractSession session) { //bug 4416412: Map sent instead of Vector Map writableChangeSets = new IdentityHashMap(); for (ObjectChangeSet changeSet : getAllChangeSets().values()) { // navigate through the related change sets here and set their cache synchronization type as well ClassDescriptor descriptor = changeSet.getDescriptor(); int syncType = descriptor.getCachePolicy().getCacheSynchronizationType(); // Bug 486845 - ensure that any existing protected foreign keys are set // in the changeSet for objects with protected cache isolation if (descriptor.isProtectedIsolation()) { CacheKey activeCacheKey = changeSet.getActiveCacheKey(); if (activeCacheKey!= null && activeCacheKey.hasProtectedForeignKeys()) { changeSet.setProtectedForeignKeys(activeCacheKey.getProtectedForeignKeys().clone()); } } // Change sets for new objects will only be sent as part of the UnitOfWorkChangeSet // if they are meant to be merged into the distributed cache. // Note: New objects could still be sent if the are referred to by a change record. if ((syncType!= ClassDescriptor.DO_NOT_SEND_CHANGES) && (!changeSet.isNew() || (syncType == ClassDescriptor.SEND_NEW_OBJECTS_WITH_CHANGES))) { changeSet.unitOfWorkChangeSet.setSession(null); writableChangeSets.put(changeSet, changeSet); } // bug 530681: ensureChanges(AbstractSession, ObjectChangeSet, ClassDescriptor) from ObjectChangeSet was moved here if (changeSet.isNew() && ((changeSet.changes == null) || changeSet.changes.isEmpty() || syncType!= ClassDescriptor.SEND_NEW_OBJECTS_WITH_CHANGES)) { ensureChanges(session, changeSet, descriptor); } } Map sendableDeletedObjects = new IdentityHashMap(); for (ObjectChangeSet changeSet : getDeletedObjects().keySet()) { // navigate through the related change sets here and set their cache synchronization type as well ClassDescriptor descriptor = changeSet.getDescriptor(); int syncType = descriptor.getCacheSynchronizationType(); // Change sets for new objects will only be sent as part of the UnitOfWorkChangeSet // if they are meant to be merged into the distributed cache. // Note: New objects could still be sent if the are referred to by a change record. if (syncType!= ClassDescriptor.DO_NOT_SEND_CHANGES) { changeSet.unitOfWorkChangeSet.setSession(null); sendableDeletedObjects.put(changeSet, changeSet); } } // Do not write if nothing to write i.e. only does inserts if (writableChangeSets.isEmpty() && sendableDeletedObjects.isEmpty()) { return null; } UnitOfWorkChangeSet remoteChangeSet = new UnitOfWorkChangeSet(); if (!writableChangeSets.isEmpty()) { remoteChangeSet.allChangeSets = writableChangeSets; } if (!sendableDeletedObjects.isEmpty()) { remoteChangeSet.deletedObjects = sendableDeletedObjects; } return remoteChangeSet; } /** * Ensure the change set is populated for cache coordination. * * @param session current database session * @param changeSet change set to populate * @param descriptor class (relational) descriptor related to the change set */ private void ensureChanges(final AbstractSession session, final ObjectChangeSet changeSet, final ClassDescriptor descriptor) { FetchGroup fetchGroup = null; if (descriptor.hasFetchGroupManager()) { fetchGroup = descriptor.getFetchGroupManager().getObjectFetchGroup(changeSet.cloneObject); } for (DatabaseMapping mapping : descriptor.getMappings()) { if (fetchGroup == null || fetchGroup.containsAttributeInternal(mapping.getAttributeName())) { changeSet.addChange(mapping.compareForChange(changeSet.cloneObject, changeSet.cloneObject, changeSet, session)); } } } /** * INTERNAL: * Get the clone to object change hash table. Lazy initializes the map if required. */ public Map<Object, ObjectChangeSet> getCloneToObjectChangeSet() { if (cloneToObjectChangeSet == null) { cloneToObjectChangeSet = new IdentityHashMap(); } return cloneToObjectChangeSet; } /** * INTERNAL: * This method returns the reference to the deleted objects from the changeSet. */ @Override public Map<ObjectChangeSet, ObjectChangeSet> getDeletedObjects() { if (this.deletedObjects == null) { // 2612538 - the default size of Map (32) is appropriate this.deletedObjects = new IdentityHashMap(); } return deletedObjects; } /** * INTERNAL: * Returns the ObjectChanges held by this ChangeSet. */ public Map<Class, Map<ObjectChangeSet, ObjectChangeSet>> getObjectChanges() { if (objectChanges == null) { objectChanges = new HashMap<Class, Map<ObjectChangeSet, ObjectChangeSet>>(); } return objectChanges; } /** * INTERNAL: * Returns the set of classes corresponding to updated objects in objectChanges. * @return HashSet<Class> */ public Set<ClassDescriptor> findUpdatedObjectsClasses() { if (this.objectChanges == null || this.objectChanges.isEmpty()) { return null; } HashSet<ClassDescriptor> updatedObjectsClasses = new HashSet<ClassDescriptor>(getObjectChanges().size()); for (Map<ObjectChangeSet, ObjectChangeSet> objectChanges : getObjectChanges().values()) { for (ObjectChangeSet changeSet : objectChanges.values()) { // any change set will do if(!changeSet.isNew()) { // found updated object - add its class to the set updatedObjectsClasses.add(changeSet.getDescriptor()); // and go to the table corresponding to the next class break; } } } return updatedObjectsClasses; } /** * ADVANCED: * Get ChangeSet for a particular clone * @return ObjectChangeSet the changeSet that represents a particular clone */ @Override public org.eclipse.persistence.sessions.changesets.ObjectChangeSet getObjectChangeSetForClone(Object clone) { if ((clone == null) || (this.cloneToObjectChangeSet == null)) { return null; } return this.cloneToObjectChangeSet.get(clone); } /** * INTERNAL: * This method returns a reference to the collection * @return Map */ protected Map<ObjectChangeSet, Object> getObjectChangeSetToUOWClone() { if (this.objectChangeSetToUOWClone == null) { // 2612538 - the default size of Map (32) is appropriate this.objectChangeSetToUOWClone = new IdentityHashMap<ObjectChangeSet, Object>(); } return objectChangeSetToUOWClone; } /** * ADVANCED: * This method returns the Clone for a particular changeSet * @return Object the clone represented by the changeSet */ @Override public Object getUOWCloneForObjectChangeSet(org.eclipse.persistence.sessions.changesets.ObjectChangeSet changeSet) { if ((changeSet == null) || (this.objectChangeSetToUOWClone == null)) { return null; } return this.objectChangeSetToUOWClone.get(changeSet); } /** * INTERNAL: * Returns true if the Unit Of Work change Set has changes */ @Override public boolean hasChanges() { // All of the object change sets were empty (none contained changes) // The this.hasChanges variable is set in addObjectChangeSet return (this.hasChanges || (this.deletedObjects!= null) && (!this.deletedObjects.isEmpty())); } /** * INTERNAL: * Returns true if any deleted objects. * This should be used before accessing deleted object to avoid creation of map. */ public boolean hasDeletedObjects() { return (this.deletedObjects!= null) && (!this.deletedObjects.isEmpty()); } /** * INTERNAL: * Set whether the Unit Of Work change Set has changes */ public void setHasChanges(boolean flag) { this.hasChanges = flag; } /** * INTERNAL: * Returns true if this uowChangeSet contains an objectChangeSet that has forced * SQL changes. This is true whenever CMPPolicy.getForceUpdate() == true. * @return boolean */ public boolean hasForcedChanges() { return this.hasForcedChanges; } /** * INTERNAL: * This method will be used to merge a change set into an UnitOfWorkChangeSet * This method returns the local instance of the changeset */ public ObjectChangeSet mergeObjectChanges(ObjectChangeSet objectChangeSet, UnitOfWorkChangeSet mergeFromChangeSet) { ObjectChangeSet localChangeSet = this.findOrIntegrateObjectChangeSet(objectChangeSet, mergeFromChangeSet); if (localChangeSet!= null) { localChangeSet.mergeObjectChanges(objectChangeSet, this, mergeFromChangeSet); } return localChangeSet; } /** * INTERNAL: * THis method will be used to merge another changeset into this changeset. The * Main use of this method is for non-deferred writes and checkpointing so that * the accumulated changes are collected and merged at the end of the transaction. */ public void mergeUnitOfWorkChangeSet(UnitOfWorkChangeSet mergeFromChangeSet, AbstractSession session, boolean postCommit) { if (mergeFromChangeSet == null) { return; } for (Map<ObjectChangeSet, ObjectChangeSet> objectChanges : mergeFromChangeSet.getObjectChanges().values()) { for (ObjectChangeSet objectChangeSet : objectChanges.values()) { objectChangeSet = mergeObjectChanges(objectChangeSet, mergeFromChangeSet); addObjectChangeSet(objectChangeSet, session,!postCommit); } } //merging a serialized UnitOfWorkChangeSet can result in duplicate deletes //if a delete for the same object already exists in this UOWChangeSet. if (mergeFromChangeSet.hasDeletedObjects()) { for (ObjectChangeSet objectChangeSet : mergeFromChangeSet.getDeletedObjects().values()) { ObjectChangeSet localObjectChangeSet = findObjectChangeSet(objectChangeSet, mergeFromChangeSet); if (localObjectChangeSet == null) { localObjectChangeSet = objectChangeSet; } getDeletedObjects().put(localObjectChangeSet, localObjectChangeSet); } } } /** * INTERNAL: * Used to rehash the new objects back into the objectChanges list for serialization * Assumes the transaction in in post commit stage. */ public void putNewObjectInChangesList(ObjectChangeSet objectChangeSet, AbstractSession session) { // Must reset the cache key for new objects assigned in insert. if (objectChangeSet.getId() == null) { Object clone = objectChangeSet.getUnitOfWorkClone(); objectChangeSet.setId(session.getDescriptor(clone.getClass()).getObjectBuilder().extractPrimaryKeyFromObject(clone, session, false)); } addObjectChangeSet(objectChangeSet, session, false); removeObjectChangeSetFromNewList(objectChangeSet, session); } /** * INTERNAL: * Used to remove a new object from the new objects list once it has been * inserted and added to the objectChangesList */ public void removeObjectChangeSetFromNewList(ObjectChangeSet objectChangeSet, AbstractSession session) { Map table = getNewObjectChangeSets().get(objectChangeSet.getClassType(session)); if (table!= null) { table.remove(objectChangeSet); } } /** * INTERNAL: * Add the changed Object's records to the ChangeSet. */ public void removeObjectChangeSet(ObjectChangeSet changeSet) { if (changeSet == null) { return; } Object object = getObjectChangeSetToUOWClone().get(changeSet); if (changeSet.isAggregate()) { getAggregateChangeSets().remove(changeSet); } else { Map classChanges = getObjectChanges().get(object.getClass()); if (classChanges!= null) { classChanges.remove(changeSet); } } getObjectChangeSetToUOWClone().remove(changeSet); if (object!= null) { getCloneToObjectChangeSet().remove(object); } getAllChangeSets().remove(changeSet); } /** * INTERNAL: * Set the internal flag that tells that this change set was built outside this * UOW and the changes it contains cannot be calculated from the contents of this UOW */ public void setIsChangeSetFromOutsideUOW(boolean isChangeSetFromOutsideUOW){ this.isChangeSetFromOutsideUOW = isChangeSetFromOutsideUOW; } /** * INTERNAL: * Get the internal flag that tells that this change set was built outside this * UOW and the changes it contains cannot be calculated from the contents of this UOW */ public boolean isChangeSetFromOutsideUOW(){ return isChangeSetFromOutsideUOW; } /** * INTERNAL: * This method is used to set the map for cloneToObject reference. */ public void setCloneToObjectChangeSet(Map<Object, ObjectChangeSet> cloneToObjectChangeSet) { this.cloneToObjectChangeSet = cloneToObjectChangeSet; } /** * INTERNAL: * Sets the collection of ObjectChanges in the change Set. */ protected void setObjectChanges(Map objectChanges) { this.objectChanges = objectChanges; } /** * INTERNAL: * Sets the collection of ObjectChanges in the change Set. */ public void setAllChangeSets(Map allChangeSets) { this.allChangeSets = allChangeSets; } /** * INTERNAL: * Sets the collection of deleted objects. */ public void setDeletedObjects(Map deletedObjects) { this.deletedObjects = deletedObjects; } /** * INTERNAL: * This method is used to insert a new collection into the UOWChangeSet. */ public void setObjectChangeSetToUOWClone(Map<ObjectChangeSet, Object> objectChangeSetToUOWClone) { this.objectChangeSetToUOWClone = objectChangeSetToUOWClone; } /** * INTERNAL: * This method will return a reference to the new object change set collections. */ public Map<Class, Map<ObjectChangeSet, ObjectChangeSet>> getNewObjectChangeSets() { if (this.newObjectChangeSets == null) { this.newObjectChangeSets = new HashMap<Class, Map<ObjectChangeSet, ObjectChangeSet>>(); } return this.newObjectChangeSets; } } ======================= File: jpa/org.eclipse.persistence.jpa.jpql/src/org/eclipse/persistence/jpa/jpql/tools/model/query/BetweenExpressionStateObject.java ======================= <gh_stars>0 /******************************************************************************* * Copyright (c) 2011, 2018 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation * ******************************************************************************/ package org.eclipse.persistence.jpa.jpql.tools.model.query; import java.io.IOException; import java.util.List; import org.eclipse.persistence.jpa.jpql.parser.BetweenExpression; import org.eclipse.persistence.jpa.jpql.parser.InternalBetweenExpressionBNF; import static org.eclipse.persistence.jpa.jpql.parser.AbstractExpression.*; /** * Used in conditional expression to determine whether the result of an expression falls within an * inclusive range of values. Numeric, string and date expression can be evaluated in this way. * * <div><b>BNF:</b> <code>between_expression ::= arithmetic_expression [NOT] BETWEEN arithmetic_expression AND arithmetic_expression |<br> * string_expression [NOT] BETWEEN string_expression AND string_expression |<br> * datetime_expression [NOT] BETWEEN datetime_expression AND datetime_expression</code></div><p> * * @see BetweenExpression * * @version 2.4 * @since 2.4 * @author <NAME> */ @SuppressWarnings({"nls", "unused"}) // unused used for the import statement: see bug 330740 public class BetweenExpressionStateObject extends AbstractStateObject { /** * The {@link StateObject} representing the lower bound expression. */ private StateObject lowerBoundStateObject; /** * Determines whether the <code><b>NOT</b></code> identifier is part of the expression or not. */ private boolean not; /** * The {@link StateObject} representing the expression to determine if its result falls within * the lower and upper bounds. */ private StateObject stateObject; /** * The {@link StateObject} representing the upper bound expression. */ private StateObject upperBoundStateObject; /** * Notifies the {@link StateObject} representing the lower bound expression has changed. */ public static final String LOWER_STATE_OBJECT_PROPERTY = "lowerBoundStateObject"; /** * Notifies the visibility of the <code><b>NOT</b></code> identifier has changed. */ public static final String NOT_PROPERTY = "not"; /** * Notifies the state object property has changed. */ public static final String STATE_OBJECT_PROPERTY = "stateObject"; /** * Notifies the {@link StateObject} representing the upper bound expression has changed. */ public static final String UPPER_STATE_OBJECT_PROPERTY = "upperBoundStateObject"; /** * Creates a new <code>BetweenExpressionStateObject</code>. * * @param parent The parent of this state object, which cannot be <code>null</code> * @exception NullPointerException The given parent cannot be <code>null</code> */ public BetweenExpressionStateObject(StateObject parent) { super(parent); } /** * Creates a new <code>BetweenExpressionStateObject</code>. * * @param parent The parent of this state object, which cannot be <code>null</code> * @param stateObject The {@link StateObject} representing the expression to compare its result * to the lower and upper bounds * @param not Determines whether the <code><b>NOT</b></code> identifier is part of the expression * or not * @param lowerBound The {@link StateObject} representing the lower bound expression * @param upperBound The {@link StateObject} representing the upper bound expression * @exception NullPointerException The given parent cannot be <code>null</code> */ public BetweenExpressionStateObject(StateObject parent, StateObject stateObject, boolean not, StateObject lowerBound, StateObject upperBound) { super(parent); this.not = not; this.stateObject = parent(stateObject); this.lowerBoundStateObject = parent(lowerBound); this.upperBoundStateObject = parent(upperBound); } /** * Creates a new <code>BetweenExpressionStateObject</code>. * * @param parent The parent of this state object, which cannot be <code>null</code> * @param stateObject The {@link StateObject} representing the expression to compare its result * to the lower and upper bounds * @param lowerBound The {@link StateObject} representing the lower bound expression * @param upperBound The {@link StateObject} representing the upper bound expression * @exception NullPointerException The given parent cannot be <code>null</code> */ public BetweenExpressionStateObject(StateObject parent, StateObject stateObject, StateObject lowerBound, StateObject upperBound) { this(parent, stateObject, false, lowerBound, upperBound); } /** * Creates a new <code>BetweenExpressionStateObject</code>. * * @param parent The parent of this state object, which cannot be <code>null</code> * @param jpqlFragment The JPQL fragment representing the expression to compare its result to the * lower and upper bounds, the fragment will be parsed and converted into a {@link StateObject} * @param not Determines whether the <code><b>NOT</b></code> identifier is part of the expression * or not * @param lowerBoundJpqlFragment The JPQL fragment representing the lower bound of the range, the * fragment will be parsed and converted into a {@link StateObject} * @param upperBoundJpqlFragment The JPQL fragment representing the upper bound of the range, the * fragment will be parsed and converted into a {@link StateObject} * @exception NullPointerException The given parent cannot be <code>null</code> */ public BetweenExpressionStateObject(StateObject parent, String jpqlFragment, boolean not, String lowerBoundJpqlFragment, String upperBoundJpqlFragment) { super(parent); this.not = not; parse(jpqlFragment); parseLowerBound(lowerBoundJpqlFragment); parseUpperBound(upperBoundJpqlFragment); } /** * Creates a new <code>BetweenExpressionStateObject</code>. * * @param parent The parent of this state object, which cannot be <code>null</code> * @param jpqlFragment The JPQL fragment representing the expression to compare its result to the * lower and upper bounds, the fragment will be parsed and converted into a {@link StateObject} * @param lowerBoundJpqlFragment The JPQL fragment representing the lowe bound of the range, the * fragment will be parsed and converted into a {@link StateObject} * @param upperBoundJpqlFragment The JPQL fragment representing the upper bound of the range, the * fragment will be parsed and converted into a {@link StateObject} * @exception NullPointerException The given parent cannot be <code>null</code> */ public BetweenExpressionStateObject(StateObject parent, String jpqlFragment, String lowerBoundJpqlFragment, String upperBoundJpqlFragment) { this(parent, jpqlFragment, false, lowerBoundJpqlFragment, upperBoundJpqlFragment); } /** * {@inheritDoc} */ @Override public void accept(StateObjectVisitor visitor) { visitor.visit(this); } /** * {@inheritDoc} */ @Override protected void addChildren(List<StateObject> children) { super.addChildren(children); if (stateObject!= null) { children.add(stateObject); } if (lowerBoundStateObject!= null) { children.add(lowerBoundStateObject); } if (upperBoundStateObject!= null) { children.add(upperBoundStateObject); } } /** * Makes sure the <code><b>NOT</b></code> identifier is specified. * * @return This object */ public BetweenExpressionStateObject addNot() { if (!not) { setNot(true); } return this; } /** * {@inheritDoc} */ @Override public BetweenExpression getExpression() { return (BetweenExpression) super.getExpression(); } /** * Returns the {@link StateObject} representing the lower bound of the range. * * @return The expression representing the lower bound */ public StateObject getLowerBound() { return lowerBoundStateObject; } /** * Returns the {@link StateObject} representing the expression to determine if its result falls * within the lower and upper bounds. * * @return The expression to check if its result is in the range of the lower and upper bounds */ public StateObject getStateObject() { return stateObject; } /** * Returns the {@link StateObject} representing the upper bound of the range. * * @return The expression representing the upper bound */ public StateObject getUpperBound() { return upperBoundStateObject; } /** * Determines whether the {@link StateObject} representing the lower bound is defined or not. * * @return <code>true</code> if the {@link StateObject} representing the expression to check if * its result falls into a range has been defined; <code>false</code> otherwise */ public boolean hasLowerBound() { return lowerBoundStateObject!= null; } /** * Determines whether the <code><b>NOT</b></code> identifier is used or not. * * @return <code>true</code> if the <code><b>NOT</b></code> identifier is part of the expression; * <code>false</code> otherwise */ public boolean hasNot() { return not; } /** * Determines whether the {@link StateObject} representing the expression to determine if its * result falls within the lower and upper bounds has been defined or not. * * @return <code>true</code> if the {@link StateObject} representing the lower bound expression * has been defined; <code>false</code> otherwise */ public boolean hasStateObject() { return stateObject!= null; } /** * Determines whether the {@link StateObject} representing the upper bound is defined or not. * * @return <code>true</code> if the {@link StateObject} representing the upper bound expression * has been defined; <code>false</code> otherwise */ public boolean hasUpperBound() { return upperBoundStateObject!= null; } /** * {@inheritDoc} */ @Override public boolean isEquivalent(StateObject stateObject) { if (super.isEquivalent(stateObject)) { BetweenExpressionStateObject between = (BetweenExpressionStateObject) stateObject; return not == between.not && areEquivalent(stateObject, between.stateObject) && areEquivalent(lowerBoundStateObject, between.lowerBoundStateObject) && areEquivalent(upperBoundStateObject, between.upperBoundStateObject); } return false; } /** * Parses the given JPQL fragment, which will represent the expression to compare its result to * the lower and upper bounds. * * @param jpqlFragment The JPQL fragment representing the expression to compare its result to the * lower and upper bounds, the fragment will be parsed and converted into a {@link StateObject} */ public void parse(String jpqlFragment) { StateObject stateObject = buildStateObject(jpqlFragment, InternalBetweenExpressionBNF.ID); setStateObject(stateObject); } /** * Parses the given JPQL fragment, which will represent the lower bound of the range. * * @param jpqlFragment The JPQL fragment representing the lower bound of the range, the fragment * will be parsed and converted into a {@link StateObject} */ public void parseLowerBound(String jpqlFragment) { StateObject stateObject = buildStateObject(jpqlFragment, InternalBetweenExpressionBNF.ID); setLowerBound(stateObject); } /** * Parses the given JPQL fragment, which will represent the upper bound of the range. * * @param jpqlFragment The JPQL fragment representing the upper bound of the range, the fragment * will be parsed and converted into a {@link StateObject} */ public void parseUpperBound(String jpqlFragment) { StateObject stateObject = buildStateObject(jpqlFragment, InternalBetweenExpressionBNF.ID); setUpperBound(stateObject); } /** * Makes sure the <code><b>NOT</b></code> identifier is not specified. */ public void removeNot() { if (not) { setNot(false); } } /** * Keeps a reference of the {@link BetweenExpression parsed object} object, which should only be * done when this object is instantiated during the conversion of a parsed JPQL query into * {@link StateObject StateObjects}. * * @param expression The {@link BetweenExpression parsed object} representing a <code><b>BETWEEN</b></code> * expression */ public void setExpression(BetweenExpression expression) { super.setExpression(expression); } /** * Sets the {@link StateObject} representing the lower bound of the range. * * @param lowerBound The {@link StateObject} representing the lower bound expression */ public void setLowerBound(StateObject lowerBound) { StateObject oldLowerBoundStateObject = lowerBoundStateObject; lowerBoundStateObject = parent(lowerBound); firePropertyChanged(LOWER_STATE_OBJECT_PROPERTY, oldLowerBoundStateObject, lowerBoundStateObject); } /** * Sets whether the <code><b>NOT</b></code> identifier should be part of the expression or not. * * @param not <code>true</code> if the <code><b>NOT</b></code> identifier should be part of the * expression; <code>false</code> otherwise */ public void setNot(boolean not) { boolean oldNot = this.not; this.not = not; firePropertyChanged(NOT_PROPERTY, oldNot, not); } /** * Sets the {@link StateObject} representing the expression to determine if its result falls * within the lower and upper bounds. * * @param stateObject The expression to check if its result is in the range of the lower and * upper bounds */ public void setStateObject(StateObject stateObject) { StateObject oldStateObject = this.stateObject; this.stateObject = parent(stateObject); firePropertyChanged(STATE_OBJECT_PROPERTY, oldStateObject, stateObject); } /** * Sets the {@link StateObject} representing the upper bound of the range. * * @param upperBound The {@link StateObject} representing the upper bound expression */ public void setUpperBound(StateObject upperBound) { StateObject oldUpperBoundStateObject = upperBoundStateObject; upperBoundStateObject = parent(upperBound); firePropertyChanged(UPPER_STATE_OBJECT_PROPERTY, oldUpperBoundStateObject, upperBoundStateObject); } /** * Changes the visibility state of the <code><b>NOT</b></code> identifier. */ public void toggleNot() { setNot(!not); } /** * {@inheritDoc} */ @Override protected void toTextInternal(Appendable writer) throws IOException { if (stateObject!= null) { stateObject.toString(writer); writer.append(SPACE); } writer.append(not? NOT_BETWEEN : BETWEEN); if (lowerBoundStateObject!= null) { writer.append(SPACE); lowerBoundStateObject.toString(writer); } writer.append(SPACE); writer.append(AND); if (upperBoundStateObject!= null) { writer.append(SPACE); upperBoundStateObject.toString(writer); } } } ======================= File: foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/internal/oxm/record/UnmarshalRecordImpl.java ======================= <gh_stars>0 /******************************************************************************* * Copyright (c) 1998, 2018 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation from Oracle TopLink * <NAME> - 2.6.0 - added case insensitive unmarshalling ******************************************************************************/ package org.eclipse.persistence.internal.oxm.record; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.namespace.QName; import org.eclipse.persistence.core.descriptors.CoreDescriptor; import org.eclipse.persistence.core.descriptors.CoreDescriptorEventManager; import org.eclipse.persistence.core.descriptors.CoreInheritancePolicy; import org.eclipse.persistence.core.queries.CoreAttributeGroup; import org.eclipse.persistence.descriptors.DescriptorEvent; import org.eclipse.persistence.descriptors.DescriptorEventManager; import org.eclipse.persistence.exceptions.EclipseLinkException; import org.eclipse.persistence.exceptions.XMLMarshalException; import org.eclipse.persistence.internal.core.helper.CoreField; import org.eclipse.persistence.internal.core.sessions.CoreAbstractRecord; import org.eclipse.persistence.internal.core.sessions.CoreAbstractSession; import org.eclipse.persistence.internal.identitymaps.CacheId; import org.eclipse.persistence.internal.oxm.Constants; import org.eclipse.persistence.internal.oxm.ContainerValue; import org.eclipse.persistence.internal.oxm.ConversionManager; import org.eclipse.persistence.internal.oxm.IDResolver; import org.eclipse.persistence.internal.oxm.MappingNodeValue; import org.eclipse.persistence.internal.oxm.NamespaceResolver; import org.eclipse.persistence.internal.oxm.NodeValue; import org.eclipse.persistence.internal.oxm.NullCapableValue; import org.eclipse.persistence.internal.oxm.ObjectBuilder; import org.eclipse.persistence.internal.oxm.Reference; import org.eclipse.persistence.internal.oxm.ReferenceResolver; import org.eclipse.persistence.internal.oxm.Root; import org.eclipse.persistence.internal.oxm.SAXFragmentBuilder; import org.eclipse.persistence.internal.oxm.StrBuffer; import org.eclipse.persistence.internal.oxm.Unmarshaller; import org.eclipse.persistence.internal.oxm.XPathFragment; import org.eclipse.persistence.internal.oxm.XPathNode; import org.eclipse.persistence.internal.oxm.XPathPredicate; import org.eclipse.persistence.internal.oxm.XPathQName; import org.eclipse.persistence.internal.oxm.mappings.Descriptor; import org.eclipse.persistence.internal.oxm.mappings.DirectMapping; import org.eclipse.persistence.internal.oxm.mappings.Field; import org.eclipse.persistence.internal.oxm.mappings.Mapping; import org.eclipse.persistence.internal.oxm.mappings.TransformationMapping; import org.eclipse.persistence.internal.oxm.record.namespaces.StackUnmarshalNamespaceResolver; import org.eclipse.persistence.internal.oxm.record.namespaces.UnmarshalNamespaceResolver; import org.eclipse.persistence.internal.oxm.unmapped.UnmappedContentHandler; import org.eclipse.persistence.internal.security.PrivilegedNewInstanceFromClass; import org.eclipse.persistence.internal.sessions.AbstractSession; import org.eclipse.persistence.sessions.coordination.CommandProcessor; import org.w3c.dom.Document; import org.xml.sax.Attributes; import org.xml.sax.ErrorHandler; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.ext.Locator2; import org.xml.sax.ext.Locator2Impl; /** * <p><b>Purpose:</b>Provide an implementation of ContentHandler that is used by TopLink OXM to * build mapped Java Objects from SAX events. * <p><b>Responsibilities:</b><ul> * <li>Implement the ContentHandler and LexicalHandler interfaces</li> * <li>Make calls into the appropriate NodeValues based on the incoming SAXEvents</li> * <li>Make callbacks into XMLReader for newObject events</li> * <li>Maintain a map of Collections to be populated for collection mappings.</li> * * @see org.eclipse.persistence.internal.oxm.XPathNode * @see org.eclipse.persistence.internal.oxm.NodeValue * @see org.eclipse.persistence.internal.oxm.TreeObjectBuilder * @author bdoughan * */ public class UnmarshalRecordImpl<TRANSFORMATION_RECORD extends TransformationRecord> extends CoreAbstractRecord implements UnmarshalRecord<CoreAbstractSession, CoreField, IDResolver, ObjectBuilder, TRANSFORMATION_RECORD, Unmarshaller> { protected XMLReader xmlReader; private ObjectBuilder treeObjectBuilder; private XPathFragment xPathFragment; private XPathNode xPathNode; /** * Used to increase performance. We are trying to predict next mapping to unmarshal. * It can reduce the number of map lookups. */ private XPathNode predictedNextXPathNode; private int levelIndex; private UnmarshalRecord childRecord; protected UnmarshalRecord parentRecord; private TRANSFORMATION_RECORD transformationRecord; private List<UnmarshalRecord> selfRecords; private Map<XPathFragment, Integer> indexMap; private List<NullCapableValue> nullCapableValues; private Object[] containerInstances; private List<ContainerValue> defaultEmptyContainerValues; private List<ContainerValue> populatedContainerValues; private boolean isBufferCDATA; private Attributes attributes; private QName typeQName; protected String rootElementLocalName; protected String rootElementName; protected String rootElementNamespaceUri; private SAXFragmentBuilder fragmentBuilder; private Map<String, String> prefixesForFragment; private String encoding; private String version; private String schemaLocation; private String noNamespaceSchemaLocation; private boolean isSelfRecord; private UnmarshalContext unmarshalContext; private UnmarshalNamespaceResolver unmarshalNamespaceResolver; private boolean isXsiNil; private boolean xpathNodeIsMixedContent = false; private int unmappedLevel = -1; private ReferenceResolver referenceResolver; protected Unmarshaller unmarshaller; protected Object currentObject; protected CoreAbstractSession session; protected boolean namespaceAware; private XPathQName leafElementType; private NamespaceResolver namespaceResolver; private CoreAttributeGroup unmarshalAttributeGroup; // The "snapshot" location of this object, for @XmlLocation private Locator xmlLocation; protected XPathFragment textWrapperFragment; private ConversionManager conversionManager; protected UnmarshalRecordImpl() { } public UnmarshalRecordImpl(ObjectBuilder objectBuilder) { this(objectBuilder, new ReferenceResolver()); } private UnmarshalRecordImpl(ObjectBuilder objectBuilder, ReferenceResolver referenceResolver) { super(); this.referenceResolver = referenceResolver; this.xPathFragment = new XPathFragment(); xPathFragment.setNamespaceAware(isNamespaceAware()); this.setUnmarshalAttributeGroup(DEFAULT_ATTRIBUTE_GROUP); initialize(objectBuilder); } @Override public UnmarshalRecord initialize(ObjectBuilder treeObjectBuilder) { this.isBufferCDATA = false; this.treeObjectBuilder = treeObjectBuilder; if (null!= treeObjectBuilder) { this.xPathNode = treeObjectBuilder.getRootXPathNode(); if (null!= treeObjectBuilder.getNullCapableValues()) { this.nullCapableValues = new ArrayList<NullCapableValue>(treeObjectBuilder.getNullCapableValues()); } if (null!= treeObjectBuilder.getDefaultEmptyContainerValues()){ this.defaultEmptyContainerValues = new ArrayList<ContainerValue>(treeObjectBuilder.getDefaultEmptyContainerValues()); } } isSelfRecord = false; return this; } private void reset() { xPathNode = null; childRecord = null; transformationRecord = null; if(null!= selfRecords) { selfRecords.clear(); } if(null!= indexMap) { indexMap.clear(); } nullCapableValues = null; isBufferCDATA = false; attributes = null; typeQName = null; isSelfRecord = false; unmarshalContext = null; isXsiNil = false; unmappedLevel = -1; predictedNextXPathNode = null; } @Override public String getLocalName() { return rootElementLocalName; } @Override public void setLocalName(String localName) { rootElementLocalName = localName; } public String getNamespaceURI() { throw XMLMarshalException.operationNotSupported("getNamespaceURI"); } public void clear() { throw XMLMarshalException.operationNotSupported("clear"); } public Document getDocument() { throw XMLMarshalException.operationNotSupported("getDocument"); } public String transformToXML() { throw XMLMarshalException.operationNotSupported("transformToXML"); } @Override public XMLReader getXMLReader() { return this.xmlReader; } @Override public void setXMLReader(XMLReader xmlReader) { this.xmlReader = xmlReader; namespaceAware = xmlReader.isNamespaceAware(); if(xPathFragment!= null){ xPathFragment.setNamespaceAware(isNamespaceAware()); } } @Override public UnmarshalRecord getChildRecord() { return this.childRecord; } @Override public void setChildRecord(UnmarshalRecord childRecord) { this.childRecord = childRecord; if (null!= childRecord) { childRecord.setParentRecord(this); } } @Override public UnmarshalRecord getParentRecord() { return this.parentRecord; } /** * INTERNAL: * The ReferenceResolver that is leveraged by key based mappings. * @since EclipseLink 2.5.0 */ @Override public ReferenceResolver getReferenceResolver() { if(null == referenceResolver) { referenceResolver = new ReferenceResolver(); } return referenceResolver; } /** * INTERNAL: * Set the ReferenceResolver that will be leveraged by key based mappings. * @since EclipseLink 2.5.0 */ @Override public void setReferenceResolver(ReferenceResolver referenceResolver) { this.referenceResolver = referenceResolver; } /** * Return the root element's prefix qualified name */ @Override public String getRootElementName() { return rootElementName; } @Override public void setRootElementName(String qName) { this.rootElementName = qName; } /** * Return the root element's namespace URI */ @Override public String getRootElementNamespaceUri() { return rootElementNamespaceUri; } @Override public void setRootElementNamespaceUri(String uri) { this.rootElementNamespaceUri = uri; } @Override public void setParentRecord(UnmarshalRecord parentRecord) { this.parentRecord = parentRecord; } @Override public TRANSFORMATION_RECORD getTransformationRecord() { return this.transformationRecord; } @Override public void setTransformationRecord(TRANSFORMATION_RECORD transformationRecord) { this.transformationRecord = transformationRecord; } @Override public UnmarshalNamespaceResolver getUnmarshalNamespaceResolver() { if(null == unmarshalNamespaceResolver) { this.unmarshalNamespaceResolver = new StackUnmarshalNamespaceResolver(); } return this.unmarshalNamespaceResolver; } @Override public void setUnmarshalNamespaceResolver(UnmarshalNamespaceResolver anUnmarshalNamespaceResolver) { this.unmarshalNamespaceResolver = anUnmarshalNamespaceResolver; } @Override public List getNullCapableValues() { if (null == nullCapableValues) { this.nullCapableValues = new ArrayList<NullCapableValue>(); } return this.nullCapableValues; } @Override public void removeNullCapableValue(NullCapableValue nullCapableValue) { if(null!= nullCapableValues) { nullCapableValues.remove(nullCapableValue); } } @Override public Object getContainerInstance(ContainerValue c) { return getContainerInstance(c, true); } @Override public Object getContainerInstance(ContainerValue c, boolean createContainerIfNecessary) { Object containerInstance = containerInstances[c.getIndex()]; if (containerInstance == null) { Mapping mapping = c.getMapping(); //don't attempt to do a get on a readOnly property. if(c.getReuseContainer() &&!(mapping.isReadOnly())) { containerInstance = mapping.getAttributeValueFromObject(currentObject); } if(null == containerInstance && createContainerIfNecessary) { containerInstance = c.getContainerInstance(); } containerInstances[c.getIndex()] = containerInstance; populatedContainerValues.add(c); if(defaultEmptyContainerValues!= null){ defaultEmptyContainerValues.remove(c); } } return containerInstance; } @Override public void setContainerInstance(int index, Object containerInstance) { containerInstances[index] = containerInstance; } /** * PUBLIC: * Gets the encoding for this document. Only set on the root-level UnmarshalRecord * @return a String representing the encoding for this doc */ @Override public String getEncoding() { return encoding; } /** * INTERNAL: */ public void setEncoding(String enc) { this.encoding = enc; } /** * PUBLIC: * Gets the XML Version for this document. Only set on the root-level * UnmarshalRecord, if supported by the parser. */ @Override public String getVersion() { return version; } /** * INTERNAL: */ public void setVersion(String version) { this.version = version; } @Override public String getSchemaLocation() { return schemaLocation; } public void setSchemaLocation(String schemaLocation) { this.schemaLocation = schemaLocation; } @Override public String getNoNamespaceSchemaLocation() { return noNamespaceSchemaLocation; } public void setNoNamespaceSchemaLocation(String location) { this.noNamespaceSchemaLocation = location; } protected StrBuffer getStringBuffer() { return unmarshaller.getStringBuffer(); } @Override public CharSequence getCharacters() { return unmarshaller.getStringBuffer(); } @Override public Attributes getAttributes() { return this.attributes; } @Override public void setAttributes(Attributes attributes) { this.attributes = attributes; } @Override public QName getTypeQName() { return this.typeQName; } @Override public void setTypeQName(QName typeQName) { this.typeQName = typeQName; } @Override public void setDocumentLocator(Locator locator) { if(xmlReader!= null){ xmlReader.setLocator(locator); if (null == rootElementName && null == rootElementLocalName && parentRecord == null && locator instanceof Locator2){ Locator2 loc = (Locator2)locator; this.setEncoding(loc.getEncoding()); this.setVersion(loc.getXMLVersion()); } } } public Locator getDocumentLocator() { if(xmlReader!= null){ return xmlReader.getLocator(); } return null; } @Override public Object get(CoreField key) { Field xmlField = this.convertToXMLField(key); XPathFragment lastFragment = xmlField.getLastXPathFragment(); String namespaceURI = lastFragment.getNamespaceURI(); if(namespaceURI == null){ NamespaceResolver namespaceResolver = xmlField.getNamespaceResolver(); namespaceURI = Constants.EMPTY_STRING; if (null!= namespaceResolver &&!(lastFragment.isAttribute() && lastFragment.getPrefix() == null)) { namespaceURI = namespaceResolver.resolveNamespacePrefix(lastFragment.getPrefix()); if (null == namespaceURI) { namespaceURI = Constants.EMPTY_STRING; } } } if(isNamespaceAware()){ return attributes.getValue(namespaceURI, lastFragment.getLocalName()); } return attributes.getValue(lastFragment.getLocalName()); } @Override public XPathNode getXPathNode() { return xPathNode; } @Override public Descriptor getDescriptor() { return (Descriptor) treeObjectBuilder.getDescriptor(); } @Override public UnmarshalContext getUnmarshalContext() { return unmarshalContext; } @Override public void setUnmarshalContext(UnmarshalContext unmarshalContext) { this.unmarshalContext = unmarshalContext; } @Override public boolean isNil() { return this.isXsiNil; } @Override public void setNil(boolean nil) { this.isXsiNil = nil; } @Override public void startDocument() throws SAXException { if (unmarshaller.getIDResolver()!= null && parentRecord == null) { unmarshaller.getIDResolver().startDocument(unmarshaller.getErrorHandler()); } } private void initializeRecord(Attributes attrs) throws SAXException{ this.setAttributes(attrs); Descriptor xmlDescriptor = (Descriptor) treeObjectBuilder.getDescriptor(); if(!xmlDescriptor.hasInheritance() || xmlDescriptor.getInheritancePolicy().getClassIndicatorField() == null){ initialize((ObjectBuilder)xmlDescriptor.getObjectBuilder()); initializeRecord((Mapping)null); return; } CoreInheritancePolicy inheritancePolicy = xmlDescriptor.getInheritancePolicy(); Class classValue = treeObjectBuilder.classFromRow(this, session); if (classValue == null) { // no xsi:type attribute - look for type indicator on the default root element QName leafElementType = xmlDescriptor.getDefaultRootElementType(); // if we have a user-set type, try to get the class from the inheritance policy if (leafElementType!= null) { XPathQName xpathQName = new XPathQName(leafElementType, isNamespaceAware()); Object indicator = inheritancePolicy.getClassIndicatorMapping().get(xpathQName); if(indicator!= null) { classValue = (Class)indicator; } } } if (classValue!= null) { xmlDescriptor = (Descriptor)session.getDescriptor(classValue); } initialize((ObjectBuilder)xmlDescriptor.getObjectBuilder()); initializeRecord((Mapping)null); } @Override public void initializeRecord(Mapping selfRecordMapping) throws SAXException { try { Descriptor xmlDescriptor = (Descriptor) treeObjectBuilder.getDescriptor(); if(xmlDescriptor.isSequencedObject()) { unmarshalContext = new SequencedUnmarshalContext(); } else { unmarshalContext = ObjectUnmarshalContext.getInstance(); } currentObject = this.xmlReader.getCurrentObject(session, selfRecordMapping); if (currentObject == null) { currentObject = treeObjectBuilder.buildNewInstance(); } if (xmlDescriptor.getLocationAccessor()!= null && xmlReader.getLocator()!= null){ // Check to see if this Descriptor isLocationAware // Store the snapshot of the current documentLocator xmlLocation = new Locator2Impl(xmlReader.getLocator()); } Object parentRecordCurrentObject = null; if (null!= this.parentRecord) { parentRecordCurrentObject = parentRecord.getCurrentObject(); } Unmarshaller.Listener xmlUnmarshalListener = unmarshaller.getUnmarshalListener(); if (null!= xmlUnmarshalListener) { if (null == this.parentRecord) { xmlUnmarshalListener.beforeUnmarshal(currentObject, null); } else { xmlUnmarshalListener.beforeUnmarshal(currentObject, parentRecordCurrentObject); } } if (null == parentRecord) { this.xmlReader.newObjectEvent(currentObject, null, selfRecordMapping); } else { this.xmlReader.newObjectEvent(currentObject, parentRecordCurrentObject, selfRecordMapping); } List containerValues = treeObjectBuilder.getContainerValues(); if (null!= containerValues) { int containerSize = containerValues.size(); containerInstances = new Object[containerSize]; populatedContainerValues = new ArrayList(containerSize); } if (null!= xPathNode.getSelfChildren()) { int selfChildrenSize = xPathNode.getSelfChildren().size(); selfRecords = new ArrayList<UnmarshalRecord>(selfChildrenSize); for (int x = 0; x < selfChildrenSize; x++) { NodeValue nv = xPathNode.getSelfChildren().get(x).getNodeValue(); if (null!= nv) { selfRecords.add(nv.buildSelfRecord(this, attributes)); } } } } catch (EclipseLinkException e) { if (null == xmlReader.getErrorHandler()) { throw e; } else { SAXParseException saxParseException = new SAXParseException(null, getDocumentLocator(), e); xmlReader.getErrorHandler().error(saxParseException); } } } @Override public void endDocument() throws SAXException { if (unmarshaller.getIDResolver()!= null && parentRecord == null) { unmarshaller.getIDResolver().endDocument(); } if (null!= selfRecords) { for (int x = 0, selfRecordsSize = selfRecords.size(); x < selfRecordsSize; x++) { UnmarshalRecord selfRecord = selfRecords.get(x); if(selfRecord!= null){ selfRecord.endDocument(); } } } if (null!= xPathNode.getSelfChildren()) { int selfChildrenSize = xPathNode.getSelfChildren().size(); for (int x = 0; x < selfChildrenSize; x++) { XPathNode selfNode = xPathNode.getSelfChildren().get(x); if (null!= selfNode.getNodeValue()) { selfNode.getNodeValue().endSelfNodeValue(this, selfRecords.get(x), attributes); } } } CoreDescriptor xmlDescriptor = treeObjectBuilder.getDescriptor(); try { // PROCESS COLLECTION MAPPINGS //All populated containerValues need to be set on the object if(null!= populatedContainerValues){ for (int populatedCVSize=populatedContainerValues.size(), i = populatedCVSize-1; i>=0; i--) { ContainerValue cv = (populatedContainerValues.get(i)); cv.setContainerInstance(currentObject, getContainerInstance(cv, cv.isDefaultEmptyContainer())); } } //Additionally if any containerValues are defaultEmptyContainerValues they need to be set to a new empty container if(null!= defaultEmptyContainerValues){ for (int defaultEmptyCVSize=defaultEmptyContainerValues.size(),i = defaultEmptyCVSize-1; i>=0; i--) { ContainerValue cv = (defaultEmptyContainerValues.get(i)); cv.setContainerInstance(currentObject, getContainerInstance(cv, cv.isDefaultEmptyContainer())); } } // PROCESS NULL CAPABLE VALUES // This must be done because the node may not have existed to // trigger the mapping. if(null!= nullCapableValues) { for (int x = 0, nullValuesSize = nullCapableValues.size(); x < nullValuesSize; x++) { nullCapableValues.get(x).setNullValue(currentObject, session); } } // PROCESS TRANSFORMATION MAPPINGS List<TransformationMapping> transformationMappings = treeObjectBuilder.getTransformationMappings(); if (null!= transformationMappings) { for (int x = 0, transformationMappingsSize = transformationMappings.size(); x < transformationMappingsSize; x++) { TransformationMapping transformationMapping = transformationMappings.get(x); transformationMapping.readFromRowIntoObject((XMLRecord) transformationRecord, currentObject, session, true); } } Unmarshaller.Listener listener = unmarshaller.getUnmarshalListener(); if (listener!= null) { if (this.parentRecord!= null) { listener.afterUnmarshal(currentObject, parentRecord.getCurrentObject()); } else { listener.afterUnmarshal(currentObject, null); } } // HANDLE POST BUILD EVENTS if(xmlDescriptor.hasEventManager()) { CoreDescriptorEventManager eventManager = xmlDescriptor.getEventManager(); if (null!= eventManager && eventManager.hasAnyEventListeners()) { DescriptorEvent event = new DescriptorEvent(currentObject); event.setSession((AbstractSession) session); event.setRecord(null); //this); event.setEventCode(DescriptorEventManager.PostBuildEvent); eventManager.executeEvent(event); } } } catch (EclipseLinkException e) { if (null == xmlReader.getErrorHandler()) { throw e; } else { SAXParseException saxParseException = new SAXParseException(null, getDocumentLocator(), e); xmlReader.getErrorHandler().error(saxParseException); } } // if the object has any primary key fields set, add it to the cache if(null!= referenceResolver) { if(null!= xmlDescriptor) { List primaryKeyFields = xmlDescriptor.getPrimaryKeyFields(); if(null!= primaryKeyFields) { int primaryKeyFieldsSize = primaryKeyFields.size(); if (primaryKeyFieldsSize > 0) { CacheId pk = (CacheId) treeObjectBuilder.extractPrimaryKeyFromObject(currentObject, session); for (int x=0; x<primaryKeyFieldsSize; x++) { Object value = pk.getPrimaryKey()[x]; if (null == value) { Field pkField = (Field) xmlDescriptor.getPrimaryKeyFields().get(x); pk.set(x, unmarshaller.getContext().getValueByXPath(currentObject, pkField.getXPath(), pkField.getNamespaceResolver(), Object.class)); } } referenceResolver.putValue(xmlDescriptor.getJavaClass(), pk, currentObject); if (unmarshaller.getIDResolver()!= null) { try { if (primaryKeyFieldsSize > 1) { Map<String, Object> idWrapper = new HashMap<String, Object>(); for (int x = 0; x < primaryKeyFieldsSize; x++) { String idName = (String) xmlDescriptor.getPrimaryKeyFieldNames().get(x); Object idValue = pk.getPrimaryKey()[x]; idWrapper.put(idName, idValue); } unmarshaller.getIDResolver().bind(idWrapper, currentObject); } else { unmarshaller.getIDResolver().bind(pk.getPrimaryKey()[0], currentObject); } } catch (SAXException e) { throw XMLMarshalException.unmarshalException(e); } } } } } } if(null!= parentRecord) { reset(); } // Set XML Location if applicable if (xmlLocation!= null && ((Descriptor) xmlDescriptor).getLocationAccessor()!= null) { ((Descriptor) xmlDescriptor).getLocationAccessor().setAttributeValueInObject(getCurrentObject(), xmlLocation); } } @Override public void startPrefixMapping(String prefix, String uri) throws SAXException { getUnmarshalNamespaceResolver().push(prefix, uri); getPrefixesForFragment().put(prefix, uri); } @Override public void endPrefixMapping(String prefix) throws SAXException { getUnmarshalNamespaceResolver().pop(prefix); } @Override public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException { if (currentObject == null) { initializeRecord(atts); } XPathFragment xPathNodeXPathFragment = xPathNode.getXPathFragment(); if((null!= xPathNodeXPathFragment && xPathNodeXPathFragment.nameIsText()) || xpathNodeIsMixedContent) { xpathNodeIsMixedContent = false; NodeValue xPathNodeUnmarshalNodeValue = xPathNode.getUnmarshalNodeValue(); if (null!= xPathNodeUnmarshalNodeValue) { boolean isIncludedInAttributeGroup = true; if(xPathNodeUnmarshalNodeValue.isMappingNodeValue()) { Mapping mapping = ((MappingNodeValue)xPathNodeUnmarshalNodeValue).getMapping(); isIncludedInAttributeGroup = this.unmarshalAttributeGroup.containsAttributeInternal(mapping.getAttributeName()); } if(isIncludedInAttributeGroup) { xPathNodeUnmarshalNodeValue.endElement(xPathFragment, this); if (xPathNode.getParent()!= null) { xPathNode = xPathNode.getParent(); } } } } // set the root element's local name and namespace prefix and look for // schema locations etc. if (null == rootElementName && null == rootElementLocalName && parentRecord == null){ rootElementLocalName = localName; rootElementName = qName; rootElementNamespaceUri = namespaceURI; schemaLocation = atts.getValue(javax.xml.XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI, Constants.SCHEMA_LOCATION); noNamespaceSchemaLocation = atts.getValue(javax.xml.XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI, Constants.NO_NS_SCHEMA_LOCATION); } try { if (null!= selfRecords) { for (int x = 0, selfRecordsSize = selfRecords.size(); x < selfRecordsSize; x++) { UnmarshalRecord selfRecord = selfRecords.get(x); if(selfRecord == null){ getFragmentBuilder().startElement(namespaceURI, localName, qName, atts); }else{ selfRecord.startElement(namespaceURI, localName, qName, atts); } } } if(unmappedLevel!= -1 && unmappedLevel <= levelIndex) { levelIndex++; return; } XPathNode node = null; if (null!= predictedNextXPathNode) { XPathFragment xpf = predictedNextXPathNode.getXPathFragment(); if (null!= xpf && xPathNode == predictedNextXPathNode.getParent() && (localName == xpf.getLocalName() || localName.equals(xpf.getLocalName())) && (namespaceURI == xpf.getNamespaceURI() || namespaceURI.equals(xpf.getNamespaceURI())) && null == xpf.getPredicate() &&!xpf.containsIndex()) { updateXPathFragment(qName, localName, namespaceURI); node = predictedNextXPathNode; } } if (null == node) { node = getNonAttributeXPathNode(namespaceURI, localName, qName, atts); } if (null == node) { NodeValue parentNodeValue = xPathNode.getUnmarshalNodeValue(); if ((null == xPathNode.getXPathFragment()) && (parentNodeValue!= null)) { XPathFragment parentFragment = new XPathFragment(); parentFragment.setNamespaceAware(isNamespaceAware()); if(namespaceURI!= null && namespaceURI.length() == 0){ parentFragment.setLocalName(qName); parentFragment.setNamespaceURI(null); } else { parentFragment.setLocalName(localName); parentFragment.setNamespaceURI(namespaceURI); } if (parentNodeValue.startElement(parentFragment, this, atts)) { levelIndex++; } else { // UNMAPPED CONTENT startUnmappedElement(namespaceURI, localName, qName, atts); return; } } else { // UNMAPPED CONTENT levelIndex++; startUnmappedElement(namespaceURI, localName, qName, atts); return; } } else { xPathNode = node; unmarshalContext.startElement(this); levelIndex++; if(xmlReader.getMediaType().isApplicationXML()) { String xsiNilValue = atts.getValue(javax.xml.XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI, Constants.SCHEMA_NIL_ATTRIBUTE); if (xsiNilValue!= null) { setNil(xsiNilValue.equals(Constants.BOOLEAN_STRING_TRUE) || xsiNilValue.equals("1")); } } if(node.getNullCapableValue()!= null){ getNullCapableValues().add(node.getNullCapableValue()); } NodeValue nodeValue = node.getUnmarshalNodeValue(); if (null!= nodeValue) { boolean isIncludedInAttributeGroup = true; if(nodeValue.isMappingNodeValue()) { Mapping mapping = ((MappingNodeValue)nodeValue).getMapping(); isIncludedInAttributeGroup = this.unmarshalAttributeGroup.containsAttributeInternal(mapping.getAttributeName()); } if (!isIncludedInAttributeGroup ||!nodeValue.startElement(xPathFragment, this, atts)) { // UNMAPPED CONTENT startUnmappedElement(namespaceURI, localName, qName, atts); return; } } //Handle Attributes if(xPathNode.getAttributeChildren()!= null || xPathNode.getAnyAttributeNodeValue()!= null || selfRecords!= null) { for (int i = 0, size=atts.getLength(); i < size; i++) { String attNamespace = atts.getURI(i); String attLocalName = atts.getLocalName(i); String value = atts.getValue(i); NodeValue attributeNodeValue = null; // Some parsers don't set the URI/local name for namespace // attributes if ((attLocalName == null) || (attLocalName.length() == 0)) { String qname = atts.getQName(i); if (qname!= null) { int qnameLength = qname.length(); if (qnameLength > 0) { int idx = qname.indexOf(Constants.COLON); if (idx > 0) { attLocalName = qname.substring(idx + 1, qnameLength); String attPrefix = qname.substring(0, idx); if (attPrefix.equals(javax.xml.XMLConstants.XMLNS_ATTRIBUTE)) { attNamespace = javax.xml.XMLConstants.XMLNS_ATTRIBUTE_NS_URI; } } else { attLocalName = qname; if (attLocalName.equals(javax.xml.XMLConstants.XMLNS_ATTRIBUTE)) { attNamespace = javax.xml.XMLConstants.XMLNS_ATTRIBUTE_NS_URI; } } } } } //Look for any Self-Mapping nodes that may want this attribute. if (this.selfRecords!= null) { for (int j = 0; j < selfRecords.size(); j++) { UnmarshalRecord nestedRecord = selfRecords.get(j); if(nestedRecord!= null){ attributeNodeValue = nestedRecord.getAttributeChildNodeValue(attNamespace, attLocalName); if (attributeNodeValue!= null) { attributeNodeValue.attribute(nestedRecord, attNamespace, attLocalName, value); } } } } if (attributeNodeValue == null) { attributeNodeValue = this.getAttributeChildNodeValue(attNamespace, attLocalName); try { if (attributeNodeValue!= null) { if(attributeNodeValue.isMappingNodeValue()) { Mapping mapping = ((MappingNodeValue)attributeNodeValue).getMapping(); if(!unmarshalAttributeGroup.containsAttributeInternal(mapping.getAttributeName())) { continue; } } attributeNodeValue.attribute(this, attNamespace, attLocalName, value); } else { if (xPathNode.getAnyAttributeNodeValue()!= null) { xPathNode.getAnyAttributeNodeValue().attribute(this, attNamespace, attLocalName, value); } } } catch(EclipseLinkException e) { if ((null == xmlReader) || (null == xmlReader.getErrorHandler())) { throw e; } else { SAXParseException saxParseException = new SAXParseException(e.getLocalizedMessage(), getDocumentLocator(), e); xmlReader.getErrorHandler().warning(saxParseException); } } } } } } if(prefixesForFragment!= null){ this.prefixesForFragment.clear(); } } catch (EclipseLinkException e) { if ((null == xmlReader) || (null == xmlReader.getErrorHandler())) { throw e; } else { SAXParseException saxParseException = new SAXParseException(e.getLocalizedMessage(), getDocumentLocator(), e); xmlReader.getErrorHandler().error(saxParseException); } } } private void updateXPathFragment(String qName, String localName, String namespaceURI) { if (namespaceURI!= null && namespaceURI.length() == 0) { xPathFragment.setLocalName(qName); xPathFragment.setNamespaceURI(null); } else { xPathFragment.setLocalName(localName); xPathFragment.setNamespaceURI(namespaceURI); } } public void startUnmappedElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException { if(xmlReader.getMediaType().isApplicationXML() && null == selfRecords &&!isSelfRecord) { ErrorHandler errorHandler = xmlReader.getErrorHandler(); // Bug 452584 - check if a warning exception should be generated when an unmapped element is encountered if(null!= errorHandler && unmarshaller.shouldWarnOnUnmappedElement()) { StringBuilder messageBuilder = new StringBuilder("unexpected element (uri:\""); if(null!= namespaceURI) { messageBuilder.append(namespaceURI); } messageBuilder.append("\", local:\""); messageBuilder.append(localName); messageBuilder.append("\"). Expected elements are "); List<XPathNode> nonAttributeChildren = xPathNode.getNonAttributeChildren(); if(nonAttributeChildren == null || nonAttributeChildren.size() == 0) { messageBuilder.append("(none)"); } else { for(int x=0, size=nonAttributeChildren.size(); x<size; x++) { XPathFragment nonAttributeChildXPathFragment = nonAttributeChildren.get(x).getXPathFragment(); messageBuilder.append("<{"); String nonAttributeChildXPathFragmentNamespaceURI = nonAttributeChildXPathFragment.getNamespaceURI(); if(null!= nonAttributeChildXPathFragmentNamespaceURI) { messageBuilder.append(nonAttributeChildXPathFragmentNamespaceURI); } messageBuilder.append('}'); messageBuilder.append(nonAttributeChildXPathFragment.getLocalName()); messageBuilder.append('>'); if(x<size-1) { messageBuilder.append(','); } } } errorHandler.warning(new SAXParseException(messageBuilder.toString(), getDocumentLocator())); } } if ((null!= selfRecords) || (null == xmlReader) || isSelfRecord()) { if(-1 == unmappedLevel) { this.unmappedLevel = this.levelIndex; } return; } Class unmappedContentHandlerClass = unmarshaller.getUnmappedContentHandlerClass(); UnmappedContentHandler unmappedContentHandler; if (null == unmappedContentHandlerClass) { unmappedContentHandler = DEFAULT_UNMAPPED_CONTENT_HANDLER; } else { try { PrivilegedNewInstanceFromClass privilegedNewInstanceFromClass = new PrivilegedNewInstanceFromClass(unmappedContentHandlerClass); unmappedContentHandler = (UnmappedContentHandler)privilegedNewInstanceFromClass.run(); } catch (ClassCastException e) { throw XMLMarshalException.unmappedContentHandlerDoesntImplement(e, unmappedContentHandlerClass.getName()); } catch (IllegalAccessException e) { throw XMLMarshalException.errorInstantiatingUnmappedContentHandler(e, unmappedContentHandlerClass.getName()); } catch (InstantiationException e) { throw XMLMarshalException.errorInstantiatingUnmappedContentHandler(e, unmappedContentHandlerClass.getName()); } } UnmappedContentHandlerWrapper unmappedContentHandlerWrapper = new UnmappedContentHandlerWrapper(this, unmappedContentHandler); unmappedContentHandlerWrapper.startElement(namespaceURI, localName, qName, atts); xmlReader.setContentHandler(unmappedContentHandlerWrapper); xmlReader.setLexicalHandler(unmappedContentHandlerWrapper); } @Override public void endElement(String namespaceURI, String localName, String qName) throws SAXException { try { if (null!= selfRecords) { for (int x = 0, selfRecordsSize = selfRecords.size(); x < selfRecordsSize; x++) { UnmarshalRecord selfRecord = selfRecords.get(x); if(selfRecord!= null){ selfRecord.endElement(namespaceURI, localName, qName); }else{ getFragmentBuilder().endSelfElement(namespaceURI, localName, qName); } } } if(-1!= unmappedLevel && unmappedLevel <= levelIndex) { if(levelIndex == unmappedLevel) { unmappedLevel = -1; } levelIndex--; return; } NodeValue unmarshalNodeValue = xPathNode.getUnmarshalNodeValue(); if (null!= unmarshalNodeValue) { boolean isIncludedInAttributeGroup = true; if(unmarshalNodeValue.isMappingNodeValue()) { Mapping mapping = ((MappingNodeValue)unmarshalNodeValue).getMapping(); isIncludedInAttributeGroup = this.unmarshalAttributeGroup.containsAttributeInternal(mapping.getAttributeName()); } try { if(isIncludedInAttributeGroup) { unmarshalNodeValue.endElement(xPathFragment, this); } else { resetStringBuffer(); } } catch(EclipseLinkException e) { if ((null == xmlReader) || (null == xmlReader.getErrorHandler())) { throw e; } else { SAXParseException saxParseException = new SAXParseException(e.getLocalizedMessage(), getDocumentLocator(), e); xmlReader.getErrorHandler().warning(saxParseException); } } } else { XPathNode textNode = xPathNode.getTextNode(); if (null!= textNode && getStringBuffer().length() == 0) { NodeValue textNodeUnmarshalNodeValue = textNode.getUnmarshalNodeValue(); if(textNode.isWhitespaceAware()){ if (textNodeUnmarshalNodeValue.isMappingNodeValue()) { Mapping mapping = ((MappingNodeValue)textNodeUnmarshalNodeValue).getMapping(); if(mapping.isAbstractDirectMapping() && isNil()) { Object nullValue = ((DirectMapping)mapping).getNullValue(); if(!(Constants.EMPTY_STRING.equals(nullValue))) { setAttributeValue(null, mapping); this.removeNullCapableValue((NullCapableValue)textNodeUnmarshalNodeValue); } } else { textNodeUnmarshalNodeValue.endElement(xPathFragment, this); } setNil(false); } }else{ //This means empty tag if(textNodeUnmarshalNodeValue.isMappingNodeValue()) { Mapping mapping = ((MappingNodeValue)textNodeUnmarshalNodeValue).getMapping(); if(mapping.isAbstractDirectMapping() &&!isNil() && ((DirectMapping)mapping).getNullPolicy().isNullRepresentedByXsiNil()){ removeNullCapableValue((NullCapableValue)textNodeUnmarshalNodeValue); } } } } } XPathFragment xPathFragment = xPathNode.getXPathFragment(); if((null!= xPathFragment && xPathFragment.nameIsText()) || (xpathNodeIsMixedContent && xPathNode.getParent()!= null)) { xPathNode = xPathNode.getParent(); } NodeValue xPathNodeUnmarshalNodeValue = xPathNode.getUnmarshalNodeValue(); if (null!= xPathNodeUnmarshalNodeValue && xPathNodeUnmarshalNodeValue.isContainerValue()) { predictedNextXPathNode = xPathNode; } else { predictedNextXPathNode = xPathNode.getNextNode(); } if (null!= xPathNode.getParent()) { xPathNode = xPathNode.getParent(); } xpathNodeIsMixedContent = false; unmarshalContext.endElement(this); typeQName = null; levelIndex--; if(isNil() && levelIndex > 0) { setNil(false); } if ((0 == levelIndex) && (null!=parentRecord) &&!isSelfRecord()) { endDocument(); // don't endElement on, or pass control to, a'self' parent UnmarshalRecord pRec = parentRecord; while (pRec.isSelfRecord()) { pRec = pRec.getParentRecord(); } pRec.endElement(namespaceURI, localName, qName); xmlReader.setContentHandler(pRec); xmlReader.setLexicalHandler(pRec); } } catch (EclipseLinkException e) { if ((null == xmlReader) || (null == xmlReader.getErrorHandler())) { throw e; } else { Locator locator = xmlReader.getLocator(); SAXParseException saxParseException = new SAXParseException(null, getDocumentLocator(), e); xmlReader.getErrorHandler().warning(saxParseException); } } } @Override public void endUnmappedElement(String namespaceURI, String localName, String qName) throws SAXException { typeQName = null; levelIndex--; if ((0 == levelIndex) && (null!= parentRecord) &&!isSelfRecord()) { endDocument(); // don't endElement on, or pass control to, a'self' parent UnmarshalRecord pRec = parentRecord; while (pRec.isSelfRecord()) { pRec = pRec.getParentRecord(); } pRec.endElement(namespaceURI, localName, qName); xmlReader.setContentHandler(pRec); xmlReader.setLexicalHandler(pRec); } setNil(false); // null unmapped element processed. We have to reset nil status } @Override public void characters(char[] ch, int start, int length) throws SAXException { if(currentObject == null){ return; } try { int strBufferInitialLength = -1; if (null!= selfRecords) { strBufferInitialLength = getStringBuffer().length(); for (int x = 0, selfRecordsSize = selfRecords.size(); x < selfRecordsSize; x++) { UnmarshalRecord selfRecord = selfRecords.get(x); if(selfRecord!= null){ selfRecord.characters(ch, start, length); } else { getFragmentBuilder().characters(ch, start, length); } } } if(-1!= unmappedLevel && unmappedLevel <= levelIndex) { return; } XPathNode textNode = xPathNode.getTextNode(); if (null == textNode) { textNode = xPathNode.getAnyNode(); if (textNode!= null) { xpathNodeIsMixedContent = true; this.xPathFragment.setLocalName(null); this.xPathFragment.setNamespaceURI(null); if (0 == length) { return; } } } if (null!= textNode) { if(textNode.getUnmarshalNodeValue().isMixedContentNodeValue()) { String tmpString = new String(ch, start, length); if (!textNode.isWhitespaceAware() && tmpString.trim().length() == 0) { return; } } xPathNode = textNode; unmarshalContext.characters(this); } NodeValue unmarshalNodeValue = xPathNode.getUnmarshalNodeValue(); if (null!= unmarshalNodeValue &&!unmarshalNodeValue.isWrapperNodeValue()) { if(strBufferInitialLength == -1) { getStringBuffer().append(ch, start, length); } else { StrBuffer strBuffer = getStringBuffer(); if(strBufferInitialLength == strBuffer.length()) { strBuffer.append(ch, start, length); } } } } catch (EclipseLinkException e) { if (null == xmlReader.getErrorHandler()) { throw e; } else { SAXParseException saxParseException = new SAXParseException(null, getDocumentLocator(), e); xmlReader.getErrorHandler().error(saxParseException); } } } @Override public void characters(CharSequence characters) throws SAXException { if(null!= characters) { String string = characters.toString(); characters(string.toCharArray(), 0, string.length()); } } @Override public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException { } @Override public void processingInstruction(String target, String data) throws SAXException { } @Override public void skippedEntity(String name) throws SAXException { } /** * INTERNAL: */ @Override public XPathNode getNonAttributeXPathNode(String namespaceURI, String localName, String qName, Attributes attributes) { if (0 == levelIndex) { return xPathNode; } updateXPathFragment(qName, localName, namespaceURI); Map<XPathFragment, XPathNode> nonAttributeChildrenMap = xPathNode.getNonAttributeChildrenMap(); if (null!= nonAttributeChildrenMap) { XPathNode resultNode; if (unmarshaller.isCaseInsensitive()){ resultNode = getNodeFromLookupTable(nonAttributeChildrenMap, false); } else { resultNode = nonAttributeChildrenMap.get(xPathFragment); } XPathNode nonPredicateNode = null; if(resultNode!= null && resultNode.hasPredicateSiblings()) { nonPredicateNode = resultNode; resultNode = null; } if (null == resultNode) { // POSITIONAL MAPPING int newIndex; if (null == this.indexMap) { this.indexMap = new HashMap(); newIndex = 1; } else { Integer oldIndex = indexMap.get(xPathFragment); if (null == oldIndex) { newIndex = 1; } else { newIndex = oldIndex.intValue() + 1; } } indexMap.put(xPathFragment, newIndex); XPathFragment predicateFragment = new XPathFragment(); predicateFragment.setNamespaceAware(isNamespaceAware()); predicateFragment.setNamespaceURI(xPathFragment.getNamespaceURI()); predicateFragment.setLocalName(xPathFragment.getLocalName()); predicateFragment.setIndexValue(newIndex); resultNode = nonAttributeChildrenMap.get(predicateFragment); if (null == resultNode) { predicateFragment.setIndexValue(-1); if(attributes!= null){ for(int x = 0, length = attributes.getLength(); x<length; x++) { XPathFragment conditionFragment = new XPathFragment(); conditionFragment.setLocalName(attributes.getLocalName(x)); conditionFragment.setNamespaceURI(attributes.getURI(x)); conditionFragment.setAttribute(true); XPathPredicate condition = new XPathPredicate(conditionFragment, attributes.getValue(x)); predicateFragment.setPredicate(condition); resultNode = nonAttributeChildrenMap.get(predicateFragment); if(null!= resultNode) { break; } } } //if json, check for text wrapper before handing off to the any if(null == resultNode && xPathNode.getTextNode()!= null){ XPathFragment textWrapperFragment = getTextWrapperFragment(); if(textWrapperFragment!= null && localName.equals(textWrapperFragment.getLocalName())){ resultNode = xPathNode.getTextNode(); } } if(null == resultNode && null == nonPredicateNode) { // ANY MAPPING resultNode = xPathNode.getAnyNode(); } } } if(resultNode == null && nonPredicateNode!= null) { return nonPredicateNode; } return resultNode; } return null; } @Override public String resolveNamespacePrefix(String prefix) { String namespaceURI = getUnmarshalNamespaceResolver().getNamespaceURI(prefix); if(null == namespaceURI && null!= parentRecord) { namespaceURI = parentRecord.resolveNamespacePrefix(prefix); } return namespaceURI; } @Override public String resolveNamespaceUri(String uri) { String prefix = getUnmarshalNamespaceResolver().getPrefix(uri); if (null == prefix) { if (null!= parentRecord) { prefix = parentRecord.resolveNamespaceUri(uri); } } return prefix; } public NodeValue getSelfNodeValueForAttribute(String namespace, String localName) { if (this.selfRecords!= null) { for (int i = 0, selfRecordsSize = selfRecords.size(); i < selfRecordsSize; i++) { UnmarshalRecord nestedRecord = selfRecords.get(i); if(nestedRecord!= null){ NodeValue node = nestedRecord.getAttributeChildNodeValue(namespace, localName); if (node!= null) { return node; } } } } return null; } @Override public NodeValue getAttributeChildNodeValue(String namespace, String localName) { Map<XPathFragment, XPathNode> attributeChildrenMap = xPathNode.getAttributeChildrenMap(); if (attributeChildrenMap!= null) { XPathNode resultNode; xPathFragment.setLocalName(localName); xPathFragment.setNamespaceURI(namespace); if (unmarshaller.isCaseInsensitive()){ resultNode = getNodeFromLookupTable(attributeChildrenMap, true); } else { resultNode = attributeChildrenMap.get(xPathFragment); } if (resultNode!= null) { return resultNode.getUnmarshalNodeValue(); } } return null; } /** * INTERNAL: * Retrieves the XPathNode by searching in the auxiliary case insensitive lookup table. * * @param childrenMap Original Map for construction of the auxiliary table. * @param isAttribute Determine if searching for an element or an attribute. * @return XPathNode object reference, which is also present in the original children map. * @since 2.6.0 */ private XPathNode getNodeFromLookupTable(Map<XPathFragment, XPathNode> childrenMap, boolean isAttribute) { Map<String, XPathNode> lookupTable = xPathNode.getChildrenLookupTable(isAttribute); if(!xPathNode.isChildrenLookupTableFilled(isAttribute)){ this.fillLookupTable(childrenMap, lookupTable); xPathNode.setChildrenLookupTableFilled(isAttribute); } String lowerCaseFragment = xPathFragment.getLocalName().toLowerCase(); if (!xPathFragment.getChildrenCollisionSet(isAttribute).add(lowerCaseFragment)) handleCollision(lowerCaseFragment, false); return lookupTable.get(lowerCaseFragment); } /** * INTERNAL: * Creates an auxiliary lookup table containing lower-cased localNames of XPathFragments. * * Does NOT pass the Turkey test. * * For future development: Handle ISO-8859-9 encoding. * if (encoding.equals("ISO-8859-9")) { * String auxLocalName = entry.getKey().getLocalName().toLowerCase(Locale.forLanguageTag("tr-TR")); * } * * @param childrenMap Table from which the data is acquired. * @param lookupTable Table to which the lower-cased data is stored. * @since 2.6.0 */ private void fillLookupTable(Map<XPathFragment, XPathNode> childrenMap, Map<String, XPathNode> lookupTable) { String lookupName; for (Map.Entry<XPathFragment, XPathNode> entry : childrenMap.entrySet()) { lookupName = entry.getKey().getLocalName().toLowerCase(); if (lookupTable.put(lookupName, entry.getValue())!= null){ handleCollision(lookupName, true); } } } /** * INTERNAL: * Handles collisions, i.e. fragments or fields with the same name, different case. * * @param lookupName Lookup variant of the localName. * @param onXPathNode true - the collision occurred on XPathNode (case for Java fields), * false - the collision occurred on XPathFragment (case for XML elements/attributes). * @since 2.6.0 */ private void handleCollision(String lookupName, boolean onXPathNode) { StringBuilder sb = new StringBuilder() .append(">\nUnmarshalRecordImpl.handleCollision() -->\tCOLLISION on ") .append( onXPathNode ? "XPathNode fields by case insensitive localName \"" : "XPathFragments by case insensitive localName \"" ).append(lookupName).append("\"."); // session.setLogLevel(SessionLog.WARNING); // for debugging ((AbstractSession) session).logMessage(CommandProcessor.LOG_WARNING, sb.toString()); } @Override public SAXFragmentBuilder getFragmentBuilder() { if(this.fragmentBuilder == null){ fragmentBuilder = new SAXFragmentBuilder(this); } return fragmentBuilder; } @Override public void setFragmentBuilder(SAXFragmentBuilder builder) { this.fragmentBuilder = builder; } @Override public void resetStringBuffer() { this.getStringBuffer().reset(); this.isBufferCDATA = false; } @Override public boolean isBufferCDATA() { return isBufferCDATA; } @Override public void comment(char[] data, int start, int length) { } @Override public void startCDATA() { if (null!= xPathNode && xPathNode.getUnmarshalNodeValue()!= null) { this.isBufferCDATA = true; } } @Override public void endCDATA() { } @Override public void startEntity(String entity) { } @Override public void endEntity(String entity) { } @Override public void startDTD(String a, String b, String c) { } @Override public void endDTD() { } /** * Sets the flag which indicates if this UnmarshalRecord * represents a'self' record * * @param isSelfRecord true if this record represents *'self', false otherwise */ @Override public void setSelfRecord(boolean isSelfRecord) { this.isSelfRecord = isSelfRecord; } /** * Indicates if this UnmarshalRecord represents a'self' record * * @return true if this record represents'self', false otherwise */ @Override public boolean isSelfRecord() { return isSelfRecord; } @Override public int getLevelIndex() { return levelIndex; } /** * INTERNAL * @since EclipseLink 2.5.0 */ @Override public void setAttributeValue(Object value, Mapping mapping) { this.unmarshalContext.setAttributeValue(this, value, mapping); } @Override public void addAttributeValue(ContainerValue containerValue, Object value) { this.unmarshalContext.addAttributeValue(this, containerValue, value); } @Override public void addAttributeValue(ContainerValue containerValue, Object value, Object collection) { this.unmarshalContext.addAttributeValue(this, containerValue, value, collection); } @Override public void setAttributeValueNull(ContainerValue containerValue) { this.unmarshalContext.setAttributeValue(this, null, containerValue.getMapping()); int containerIndex = containerValue.getIndex(); populatedContainerValues.remove(containerValue); containerInstances[containerIndex] = null; } @Override public void reference(Reference reference) { this.unmarshalContext.reference(reference); } @Override public void unmappedContent() { if(this.xPathNode.getParent()!= null) { xPathNode = xPathNode.getParent(); } this.unmarshalContext.unmappedContent(this); } @Override public UnmarshalRecord getChildUnmarshalRecord(ObjectBuilder treeObjectBuilder) { if(childRecord!= null &&!childRecord.isSelfRecord()){ childRecord.initialize(treeObjectBuilder); childRecord.setParentRecord(this); return childRecord; }else{ childRecord = new UnmarshalRecordImpl(treeObjectBuilder, referenceResolver); childRecord.setSession(session); childRecord.setUnmarshaller(unmarshaller); childRecord.setTextWrapperFragment(textWrapperFragment); childRecord.setXMLReader(this.xmlReader); childRecord.setFragmentBuilder(fragmentBuilder); childRecord.setUnmarshalNamespaceResolver(unmarshalNamespaceResolver); childRecord.setParentRecord(this); } return childRecord; } /** * INTERNAL: */ @Override public void setUnmarshaller(Unmarshaller unmarshaller) { this.unmarshaller = unmarshaller; //super.setUnmarshaller(unmarshaller); if(xPathFragment!= null){ xPathFragment.setNamespaceAware(isNamespaceAware()); } } /** * INTERNAL * Returns a Map of any prefix mappings that were made before the most recent start * element event. This Map is used so the prefix mappings can be passed along to a * fragment builder in the event that the element in question is going to be unmarshalled * as a Node. */ @Override public Map<String, String> getPrefixesForFragment() { if(prefixesForFragment == null){ prefixesForFragment = new HashMap<String, String>(); } return prefixesForFragment; } @Override public char getNamespaceSeparator(){ return xmlReader.getNamespaceSeparator(); } @Override public void setTextWrapperFragment(XPathFragment newTextWrapperFragment) { textWrapperFragment = newTextWrapperFragment; } @Override public XPathFragment getTextWrapperFragment() { if(xmlReader.getMediaType().isApplicationJSON()){ if(textWrapperFragment == null){ textWrapperFragment = new XPathFragment(); textWrapperFragment.setLocalName(unmarshaller.getValueWrapper()); textWrapperFragment.setNamespaceAware(isNamespaceAware()); textWrapperFragment.setNamespaceSeparator(getNamespaceSeparator()); } return textWrapperFragment; } return null; } /** * INTERNAL: * If the UnmarshalRecord has a ReferenceResolver, tell it to resolve its * references. * @since EclipseLink 2.5.0 */ @Override public void resolveReferences(CoreAbstractSession abstractSession, IDResolver idResolver) { if(null!= referenceResolver) { referenceResolver.resolveReferences(abstractSession, idResolver, unmarshaller.getErrorHandler()); } } /** * INTERNAL: * @since EclipseLink 2.5.0 */ @Override public Root createRoot() { return unmarshaller.createRoot(); } /** * WHAT ABOUT THESE? */ private Field convertToXMLField(CoreField key) { return (Field) key; } @Override public CoreAbstractSession getSession() { return session; } @Override public Unmarshaller getUnmarshaller() { return unmarshaller; } @Override public boolean isNamespaceAware() { return namespaceAware; } @Override public Object getCurrentObject() { return currentObject; } @Override public XPathQName getLeafElementType() { return leafElementType; } @Override public void setCurrentObject(Object object) { this.currentObject = object; } @Override public void setLeafElementType(QName type) { if (type!= null) { setLeafElementType(new XPathQName(type, isNamespaceAware())); } else { setLeafElementType((XPathQName) null); } } public void setLeafElementType(XPathQName type) { leafElementType = type; } @Override public void setSession(CoreAbstractSession session) { this.session = session; } @Override public CoreAttributeGroup getUnmarshalAttributeGroup() { return unmarshalAttributeGroup; } @Override public void setUnmarshalAttributeGroup(CoreAttributeGroup unmarshalAttributeGroup) { this.unmarshalAttributeGroup = unmarshalAttributeGroup; } /** * @since EclipseLink 2.6.0 */ @Override public ConversionManager getConversionManager() { if(null == conversionManager) { conversionManager = (ConversionManager) session.getDatasourcePlatform().getConversionManager(); } return conversionManager; } } ======================= File: jpa/eclipselink.jpa.test.jse/src/org/eclipse/persistence/jpa/collection/model/Param.java ======================= /******************************************************************************* * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation from Oracle TopLink ******************************************************************************/ package org.eclipse.persistence.jpa.collection.model; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Embeddable; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; @Embeddable public class Param { @Basic(optional = false) @Column(name = "NAME", nullable = false) public String name; @ManyToOne(optional = false) @JoinColumn(name = "LEVEL_ID", nullable = false) public Level level; @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((level == null)? 0 : level.hashCode()); result = prime * result + ((name == null)? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass()!= obj.getClass()) { return false; } Param other = (Param) obj; if (level == null) { if (other.level!= null) { return false; } } else if (!level.equals(other.level)) { return false; } if (name == null) { if (other.name!= null) { return false; } } else if (!name.equals(other.name)) { return false; } return true; } } ======================= File: foundation/eclipselink.core.test/src/org/eclipse/persistence/testing/tests/collections/map/MapCollectionsTestModel.java ======================= <filename>foundation/eclipselink.core.test/src/org/eclipse/persistence/testing/tests/collections/map/MapCollectionsTestModel.java /******************************************************************************* * Copyright (c) 1998, 2018 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * tware - initial implementation ******************************************************************************/ package org.eclipse.persistence.testing.tests.collections.map; import org.eclipse.persistence.expressions.Expression; import org.eclipse.persistence.expressions.ExpressionBuilder; import org.eclipse.persistence.mappings.ForeignReferenceMapping; import org.eclipse.persistence.testing.framework.TestModel; import org.eclipse.persistence.testing.framework.TestSuite; import org.eclipse.persistence.testing.models.collections.map.AggregateAggregateMapHolder; import org.eclipse.persistence.testing.models.collections.map.AggregateDirectMapHolder; import org.eclipse.persistence.testing.models.collections.map.AggregateEntity1MMapHolder; import org.eclipse.persistence.testing.models.collections.map.AggregateEntityMapHolder; import org.eclipse.persistence.testing.models.collections.map.AggregateEntityU1MMapHolder; import org.eclipse.persistence.testing.models.collections.map.AggregateMapKey; import org.eclipse.persistence.testing.models.collections.map.DirectAggregateMapHolder; import org.eclipse.persistence.testing.models.collections.map.DirectDirectMapHolder; import org.eclipse.persistence.testing.models.collections.map.DirectEntity1MMapHolder; import org.eclipse.persistence.testing.models.collections.map.DirectEntityMapHolder; import org.eclipse.persistence.testing.models.collections.map.DirectEntityU1MMapHolder; import org.eclipse.persistence.testing.models.collections.map.EntityAggregateMapHolder; import org.eclipse.persistence.testing.models.collections.map.EntityDirectMapHolder; import org.eclipse.persistence.testing.models.collections.map.EntityEntity1MMapHolder; import org.eclipse.persistence.testing.models.collections.map.EntityEntityMapHolder; import org.eclipse.persistence.testing.models.collections.map.EntityEntityU1MMapHolder; import org.eclipse.persistence.testing.models.collections.map.EntityMapKey; import org.eclipse.persistence.testing.models.collections.map.MapCollectionsSystem; import org.eclipse.persistence.testing.tests.expressions.ReadAllExpressionTest; public class MapCollectionsTestModel extends TestModel { public MapCollectionsTestModel() { setDescription("This model tests reading/writing/deleting of the map collections model."); } public void addRequiredSystems() { addRequiredSystem(new MapCollectionsSystem()); } public void addTests() { addTest(getDirectMapMappingTestSuite()); addTest(getAggregateCollectionMappingTestSuite()); addTest(getOneToManyMappingTestSuite()); addTest(getUnidirectionalOneToManyMappingTestSuite()); addTest(getManyToManyMappingTestSuite()); } public static TestSuite getDirectMapMappingTestSuite(){ TestSuite suite = new TestSuite(); suite.setName("Direct Map Mapping Map Test Suite"); suite.setDescription("This suite tests using DirectMapMapping with different types of keys."); // Read suite.addTest(new TestReadDirectDirectMapMapping()); suite.addTest(new TestReadAggregateDirectMapMapping()); suite.addTest(new TestReadEntityDirectMapMapping()); // Update suite.addTest(new TestUpdateDirectDirectMapMapping()); suite.addTest(new TestUpdateAggregateDirectMapMapping()); suite.addTest(new TestUpdateEntityDirectMapMapping()); // Private Owned - DirectMapMappings are automatically private owned // as a result, the only relevant test here is one with an EntityKey suite.addTest(new TestUpdateEntityDirectMapMapping(true)); // Join suite.addTest(new TestReadDirectDirectMapMapping(ForeignReferenceMapping.INNER_JOIN)); suite.addTest(new TestReadAggregateDirectMapMapping(ForeignReferenceMapping.INNER_JOIN)); suite.addTest(new TestReadEntityDirectMapMapping(ForeignReferenceMapping.INNER_JOIN)); //Expressions ReadAllExpressionTest test = new ReadAllExpressionTest(DirectDirectMapHolder.class, 1); ExpressionBuilder holders = new ExpressionBuilder(); Expression exp = holders.anyOf("directToDirectMap").mapKey().equal(1); test.setExpression(exp); suite.addTest(test); test = new ReadAllExpressionTest(AggregateDirectMapHolder.class, 1); AggregateMapKey aggkey = new AggregateMapKey(); aggkey.setKey(11); holders = new ExpressionBuilder(); exp = holders.anyOf("aggregateToDirectMap").mapKey().equal(aggkey); test.setExpression(exp); suite.addTest(test); test = new ReadAllExpressionTest(EntityDirectMapHolder.class, 1); EntityMapKey entKey = new EntityMapKey(); entKey.setId(333); entKey.setData("data3"); holders = new ExpressionBuilder(); exp = holders.anyOf("entityToDirectMap").mapKey().equal(entKey); test.setExpression(exp); suite.addTest(test); return suite; } public static TestSuite getAggregateCollectionMappingTestSuite(){ TestSuite suite = new TestSuite(); suite.setName("AggregateCollectionMapping Map Test Suite"); suite.setDescription("This suite tests using AggregateCollectionMapping with a Map"); // Read suite.addTest(new TestReadDirectAggregateMapMapping()); suite.addTest(new TestReadAggregateAggregateMapMapping()); suite.addTest(new TestReadEntityAggregateMapMapping()); // Update suite.addTest(new TestUpdateDirectAggregateMapMapping()); suite.addTest(new TestUpdateAggregateAggregateMapMapping()); suite.addTest(new TestUpdateEntityAggregateMapMapping()); // Private Owned - AggregateCollectionMappings are automatically private owned // as a result, the only relevant test here is one with an EntityKey suite.addTest(new TestUpdateEntityAggregateMapMapping(true)); // Join suite.addTest(new TestReadDirectAggregateMapMapping(ForeignReferenceMapping.INNER_JOIN)); suite.addTest(new TestReadAggregateAggregateMapMapping(ForeignReferenceMapping.INNER_JOIN)); suite.addTest(new TestReadEntityAggregateMapMapping(ForeignReferenceMapping.INNER_JOIN)); ReadAllExpressionTest test = new ReadAllExpressionTest(DirectAggregateMapHolder.class, 1); ExpressionBuilder holders = new ExpressionBuilder(); Expression exp = holders.anyOf("directToAggregateMap").mapKey().equal(1); test.setExpression(exp); suite.addTest(test); test = new ReadAllExpressionTest(AggregateAggregateMapHolder.class, 1); AggregateMapKey aggkey = new AggregateMapKey(); aggkey.setKey(11); holders = new ExpressionBuilder(); exp = holders.anyOf("aggregateToAggregateMap").mapKey().equal(aggkey); test.setExpression(exp); suite.addTest(test); test = new ReadAllExpressionTest(EntityAggregateMapHolder.class, 1); EntityMapKey entKey = new EntityMapKey(); entKey.setId(111); entKey.setData("111"); holders = new ExpressionBuilder(); exp = holders.anyOf("entityToAggregateMap").mapKey().equal(entKey); test.setExpression(exp); suite.addTest(test); return suite; } public static TestSuite getOneToManyMappingTestSuite(){ TestSuite suite = new TestSuite(); suite.setName("OneToManyMapping Map Test Suite"); suite.setDescription("This suite tests using OneToManyMapping with a Map"); // Read suite.addTest(new TestReadDirectEntity1MMapMapping()); suite.addTest(new TestReadAggregateEntity1MMapMapping()); suite.addTest(new TestReadEntityEntity1MMapMapping()); // Update suite.addTest(new TestUpdateDirectEntity1MMapMapping()); suite.addTest(new TestUpdateAggregateEntity1MMapMapping()); suite.addTest(new TestUpdateEntityEntity1MMapMapping()); // Private Owned suite.addTest(new TestUpdateDirectEntity1MMapMapping(true)); suite.addTest(new TestUpdateAggregateEntity1MMapMapping(true)); suite.addTest(new TestUpdateEntityEntity1MMapMapping(true)); // Joining suite.addTest(new TestReadDirectEntity1MMapMapping(ForeignReferenceMapping.INNER_JOIN)); suite.addTest(new TestReadAggregateEntity1MMapMapping(ForeignReferenceMapping.INNER_JOIN)); suite.addTest(new TestReadEntityEntity1MMapMapping(ForeignReferenceMapping.INNER_JOIN)); //Expressions ReadAllExpressionTest test = new ReadAllExpressionTest(DirectEntity1MMapHolder.class, 1); ExpressionBuilder holders = new ExpressionBuilder(); Expression exp = holders.anyOf("directToEntityMap").mapKey().equal(11); test.setExpression(exp); suite.addTest(test); test = new ReadAllExpressionTest(AggregateEntity1MMapHolder.class, 1); AggregateMapKey aggkey = new AggregateMapKey(); aggkey.setKey(11); holders = new ExpressionBuilder(); exp = holders.anyOf("aggregateToEntityMap").mapKey().equal(aggkey); test.setExpression(exp); suite.addTest(test); test = new ReadAllExpressionTest(AggregateEntity1MMapHolder.class, 1); holders = new ExpressionBuilder(); exp = holders.anyOf("aggregateToEntityMap").mapKey().get("key").equal(11); test.setExpression(exp); suite.addTest(test); test = new ReadAllExpressionTest(EntityEntity1MMapHolder.class, 1); EntityMapKey entKey = new EntityMapKey(); entKey.setId(555); entKey.setData("data5"); holders = new ExpressionBuilder(); exp = holders.anyOf("entityToEntityMap").mapKey().equal(entKey); test.setExpression(exp); suite.addTest(test); test = new ReadAllExpressionTest(EntityEntity1MMapHolder.class, 1); holders = new ExpressionBuilder(); exp = holders.anyOf("entityToEntityMap").mapKey().get("data").equal("data5"); test.setExpression(exp); suite.addTest(test); suite.addTest(new MapKeyDirectEntity1MReportQueryTestCase()); suite.addTest(new MapKeyAggregateEntity1MReportQueryTestCase()); suite.addTest(new MapKeyEntityEntity1MReportQueryTestCase()); suite.addTest(new MapEntryDirectEntity1MReportQueryTest()); suite.addTest(new InMemoryDirectEntity1MTest()); return suite; } public static TestSuite getUnidirectionalOneToManyMappingTestSuite(){ TestSuite suite = new TestSuite(); suite.setName("UnidirectionalOneToManyMapping Map Test Suite"); suite.setDescription("This suite tests using UnidirectionalOneToManyMapping with a Map"); // Read suite.addTest(new TestReadDirectEntityU1MMapMapping()); suite.addTest(new TestReadAggregateEntityU1MMapMapping()); suite.addTest(new TestReadEntityEntityU1MMapMapping()); // Update suite.addTest(new TestUpdateDirectEntityU1MMapMapping()); suite.addTest(new TestUpdateAggregateEntityU1MMapMapping()); suite.addTest(new TestUpdateEntityEntityU1MMapMapping()); // Private Owned suite.addTest(new TestUpdateDirectEntityU1MMapMapping(true)); suite.addTest(new TestUpdateAggregateEntityU1MMapMapping(true)); suite.addTest(new TestUpdateEntityEntityU1MMapMapping(true)); // Joining suite.addTest(new TestReadDirectEntityU1MMapMapping(ForeignReferenceMapping.INNER_JOIN)); suite.addTest(new TestReadAggregateEntityU1MMapMapping(ForeignReferenceMapping.INNER_JOIN)); suite.addTest(new TestReadEntityEntityU1MMapMapping(ForeignReferenceMapping.INNER_JOIN)); //Expressions ReadAllExpressionTest test = new ReadAllExpressionTest(DirectEntityU1MMapHolder.class, 1); ExpressionBuilder holders = new ExpressionBuilder(); Expression exp = holders.anyOf("directToEntityMap").mapKey().equal(11); test.setExpression(exp); suite.addTest(test); test = new ReadAllExpressionTest(AggregateEntityU1MMapHolder.class, 1); AggregateMapKey aggkey = new AggregateMapKey(); aggkey.setKey(11); holders = new ExpressionBuilder(); exp = holders.anyOf("aggregateToEntityMap").mapKey().equal(aggkey); test.setExpression(exp); suite.addTest(test); test = new ReadAllExpressionTest(EntityEntityU1MMapHolder.class, 1); EntityMapKey entKey = new EntityMapKey(); entKey.setId(999); entKey.setData("data9"); holders = new ExpressionBuilder(); exp = holders.anyOf("entityToEntityMap").mapKey().equal(entKey); test.setExpression(exp); suite.addTest(test); return suite; } public static TestSuite getManyToManyMappingTestSuite(){ TestSuite suite = new TestSuite(); suite.setName("ManyToManyMapping Map Test Suite"); suite.setDescription("This suite tests using ManyToManyMapping with a Map"); // Read suite.addTest(new TestReadDirectEntityMapMapping()); suite.addTest(new TestReadAggregateEntityMapMapping()); suite.addTest(new TestReadEntityEntityMapMapping()); // Update suite.addTest(new TestUpdateDirectEntityMapMapping()); suite.addTest(new TestUpdateAggregateEntityMapMapping()); suite.addTest(new TestUpdateEntityEntityMapMapping()); // private owned suite.addTest(new TestUpdateDirectEntityMapMapping(true)); suite.addTest(new TestUpdateAggregateEntityMapMapping(true)); suite.addTest(new TestUpdateEntityEntityMapMapping(true)); // Joining suite.addTest(new TestReadDirectEntityMapMapping(ForeignReferenceMapping.INNER_JOIN)); suite.addTest(new TestReadAggregateEntityMapMapping(ForeignReferenceMapping.INNER_JOIN)); suite.addTest(new TestReadEntityEntityMapMapping(ForeignReferenceMapping.INNER_JOIN)); //Expressions ReadAllExpressionTest test = new ReadAllExpressionTest(DirectEntityMapHolder.class, 1); ExpressionBuilder holders = new ExpressionBuilder(); Expression exp = holders.anyOf("directToEntityMap").mapKey().equal(11); test.setExpression(exp); suite.addTest(test); test = new ReadAllExpressionTest(AggregateEntityMapHolder.class, 1); AggregateMapKey aggkey = new AggregateMapKey(); aggkey.setKey(11); holders = new ExpressionBuilder(); exp = holders.anyOf("aggregateToEntityMap").mapKey().equal(aggkey); test.setExpression(exp); suite.addTest(test); test = new ReadAllExpressionTest(EntityEntityMapHolder.class, 1); EntityMapKey entKey = new EntityMapKey(); entKey.setId(777); entKey.setData("data7"); holders = new ExpressionBuilder(); exp = holders.anyOf("entityToEntityMap").mapKey().equal(entKey); test.setExpression(exp); suite.addTest(test); return suite; } public static junit.framework.TestSuite suite() { return new MapCollectionsTestModel(); } } ======================= File: moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/javamodel/AnnotationProxy.java ======================= <reponame>jgrassel/eclipselink<filename>moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/javamodel/AnnotationProxy.java /******************************************************************************* * Copyright (c) 1998, 2018 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * dmccann - December 10/2009 - 2.0.1 - Initial implementation ******************************************************************************/ package org.eclipse.persistence.jaxb.javamodel; import java.lang.annotation.Annotation; import java.lang.reflect.Array; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.HashMap; import java.util.Map; import org.eclipse.persistence.internal.helper.ConversionManager; /** * <p> * <b>Purpose:</b>The purpose of this class is to act as a dynamic proxy that * allows JDK Annotation method calls to be made on a non Annotation object. * * <p> * <b>Responsibilities:</b> * <ul> * <li>Create and return a dynamic proxy instance based on an Annotation class * and a <code>Map</code> of components (method name to value pairs)</li> * <li>Allow JDK Annotation method calls to be invoked on the proxy object</li> * </ul> * <p> * This class provides a means to invoke JDK Annotation method calls on a non * Annotation instance. * * @see java.lang.reflect.Proxy */ public class AnnotationProxy implements InvocationHandler { private Map<String, Object> components; private ConversionManager conversionMgr; private static final String ANNOTATION_TYPE_METHOD_NAME = "annotationType"; /** * This constructor sets the <code>Map</code> of components (method name to * value pairs)and the ConversionManager to be used when converting values * in the <code>Map</code> based on the return type of the associated * <code>Method</code> Note that the preferred method of obtaining an * instance of this proxy class is via * <code>getProxy(Map, Class<A>, ClassLoader, ConversionManager)</code> * * @param components * <code>Map</code> of method name to value pairs * @param conversionMgr * <code>ConversionManager</code> instance for converting to the * correct return type in the <code>invoke</code> method */ private AnnotationProxy(Map<String, Object> components, ConversionManager conversionMgr) { this.components = components; this.conversionMgr = conversionMgr; } /** * This is the preferred way to obtain an instance of a dynamic proxy. * * The method takes a <code>ClassLoader</code> (which is used to load the * target <code>Annotation</code>), a <code>Class</code> (which indicates * the target <code>Annotation</code>, i.e. * <code>javax.xml.bind.annotation.XmlElement.class)</code>, and a * <code>Map</code> of method name to value pairs, which represent the * method names on the <code>Annotation</code> and the values that are to be * returned from each method call. For example, if this proxy is to be used * for an <code>@XmlElement</code>, the <code>Map</code> should contain the * following keys: * * <ul> * <li>defaultValue</li> <li>name</li> <li>namespace</li> <li>nillable</li> * <li>required</li> <li> type</li> * </ul> * * Following are example key/value pairs : * * <ul> * <li>"defaultValue", "##default"</li> <li>"name", "employee"</li> <li> * "namespace", "www.example.org"</li> <li>"nillable", false</li> <li> * "required", false</li> <li>"type", * javax.xml.bind.annotation.XmlElement.DEFAULT.class</li> * </ul> * * @param components * <code>Map</code> of method name/value pairs for this proxy * instance * @param annoClass * The interface for the proxy class to implement * @param cl * The <code>ClassLoader</code> to define the proxy class * @param conversionMgr * <code>ConversionManager</code> instance for converting to the * correct return type in the <code>invoke</code> method * @return A dynamic proxy instance based on a Java model JavaAnnotation */ public static <A extends Annotation> A getProxy(Map<String, Object> components, Class<A> annoClass, ClassLoader cl, ConversionManager conversionMgr) { // add the 'annotationType' method name/value pair to the components map if (components == null) { components = new HashMap<String, Object>(); } components.put(ANNOTATION_TYPE_METHOD_NAME, annoClass.getName()); // Pass the classloader to the ConversionManager as well // conversionMgr.setLoader(cl); return (A) Proxy.newProxyInstance(cl, new Class[] { annoClass }, new AnnotationProxy(components, conversionMgr)); } /** * Return the <code>Map</code> of method name/value pairs for this proxy * instance. * * @return <code>Map</code> of method name/value pairs for this proxy * instance */ public Map<String, Object> getComponents() { return this.components; } /** * Invoke a given <code>Method</code> on this proxy. The component * <code>Map</code> will be accessed using the given <code>Method</code>'s * name, and if an entry exists, the associated value is returned. * * @param proxy * Satisfy the <code>InvocationHandler</code> interface - not * used * @param method * The <code>Method</code> instance corresponding to the * interface method invoked on the proxy instance * @param args * Satisfy the <code>InvocationHandler</code> interface - not * used * @return The value from the method invocation on the proxy instance */ @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (components == null) { return null; } Class returnType = method.getReturnType(); Object value = getComponents().get(method.getName()); if (value == null && returnType == boolean.class) { return false; } if (value == null && returnType == Boolean.class) { return Boolean.FALSE; } if (returnType.isArray()) { return handleArrayData(returnType, value); } // use the ConversionManager to ensure that the correct type is returned return conversionMgr.convertObject(value, returnType); } private Object handleArrayData(Class returnType, Object value) { if (value == null) { return null; } Object[] data = (Object[]) value; Class componentType = returnType.getComponentType(); Object[] convertedArray = (Object[]) Array.newInstance(componentType, data.length); for (int i = 0; i < data.length; i++) { convertedArray[i] = conversionMgr.convertObject(data[i], componentType); } return convertedArray; } } ======================= File: foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/eis/interactions/XQueryInteraction.java ======================= <gh_stars>0 /******************************************************************************* * Copyright (c) 1998, 2018 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation from Oracle TopLink ******************************************************************************/ package org.eclipse.persistence.eis.interactions; import java.util.*; import java.io.*; import org.w3c.dom.Element; import org.eclipse.persistence.internal.databaseaccess.Accessor; import org.eclipse.persistence.internal.databaseaccess.QueryStringCall; import org.eclipse.persistence.internal.helper.*; import org.eclipse.persistence.internal.sessions.AbstractRecord; import org.eclipse.persistence.internal.sessions.AbstractSession; import org.eclipse.persistence.internal.sessions.EmptyRecord; import org.eclipse.persistence.oxm.record.XMLRecord; import org.eclipse.persistence.eis.*; /** * Defines the specification for a call to a JCA interaction that uses XQuery. * Translates the XQuery from the query arguments. * Builds the input and output XML records. * * @author James * @since OracleAS TopLink 10<i>g</i> (10.0.3) */ public class XQueryInteraction extends XMLInteraction implements QueryStringCall { protected String xQueryString; /** * Default constructor. */ public XQueryInteraction() { super(); this.xQueryString = ""; } /** * Construct the interaction with the XQuery string. */ public XQueryInteraction(String xQueryString) { super(); this.xQueryString = xQueryString; } /** * PUBLIC: * Return the XQuery string. */ public String getXQueryString() { return xQueryString; } /** * PUBLIC: * Set the XQuery string. */ public void setXQueryString(String xQueryString) { this.xQueryString = xQueryString; } /** * INTERNAL: * Return the query string. */ @Override public String getQueryString() { return getXQueryString(); } /** * INTERNAL: * Set the query string. */ @Override public void setQueryString(String queryString) { setXQueryString(queryString); } /** * INTERNAL: * Allow the call to translate the XQuery arguments. */ @Override public void translate(AbstractRecord translationRow, AbstractRecord modifyRow, AbstractSession session) { // may need to set the session on the translation row if (translationRow!= EmptyRecord.getEmptyRecord() && getQuery()!= null && getQuery().getDescriptor()!= null) { ((XMLRecord) translationRow).setSession(session); } setInputRow(modifyRow); translateQueryString(translationRow, modifyRow, session); } /** * Create a DOM for this interaction. * Convert the database row or arguments into an XML DOM tree. * Handles arguments different as the XQuery and input can both have parameters. */ @Override public Element createInputDOM(EISAccessor accessor) { // The input record can either be build from the interaction arguments, // or the modify row. if ((getInputRow()!= null) && (!hasArguments())) { return super.createInputDOM(accessor); } XMLRecord parameterRow = createXMLRecord(getInputRootElementName()); for (int index = 0; index < getArgumentNames().size(); index++) { String parameterName = (String)getArgumentNames().get(index); Object parameter = getInputRow().get(parameterName); parameterRow.put(parameterName, parameter); } return (Element)parameterRow.getDOM(); } /** * INTERNAL: * Translate the custom query markers. */ @Override public void prepare(AbstractSession session) { if (isPrepared()) { return; } super.prepare(session); translateCustomQuery(); setIsPrepared(true); } /** * Return the string for logging purposes. */ @Override public String getLogString(Accessor accessor) { StringWriter writer = new StringWriter(); writer.write("Executing "); writer.write(toString()); writer.write(Helper.cr()); writer.write("\tspec => "); writer.write(String.valueOf(getInteractionSpec())); writer.write(Helper.cr()); writer.write("\txQuery => "); writer.write(getXQueryString()); writer.write(Helper.cr()); writer.write("\tinput => ["); if (hasParameters()) { for (Iterator iterator = getParameters().iterator(); iterator.hasNext();) { Object parameter = iterator.next(); writer.write(String.valueOf(parameter)); if (iterator.hasNext()) { writer.write(", "); } else { writer.write("]"); } } } else { writer.write(String.valueOf(getInputRow())); writer.write("]"); } return writer.toString(); } /** * INTERNAL: * Return the character to use for the argument marker. *? is used in SQL, however other query languages such as XQuery need to use other markers. */ @Override protected char argumentMarker() { return '#'; } /** * INTERNAL: * Return the characters that represent non-arguments names. */ @Override protected String whitespace() { return ",;\"'< \n\t"; } @Override public boolean isQueryStringCall() { return true; } } ======================= File: foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/internal/indirection/CacheBasedValueHolder.java ======================= /******************************************************************************* * Copyright (c) 1998, 2018 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * <NAME> - initial API and implementation ******************************************************************************/ package org.eclipse.persistence.internal.indirection; import java.util.Collection; import org.eclipse.persistence.exceptions.DatabaseException; import org.eclipse.persistence.exceptions.ValidationException; import org.eclipse.persistence.internal.queries.ContainerPolicy; import org.eclipse.persistence.internal.sessions.AbstractRecord; import org.eclipse.persistence.internal.sessions.AbstractSession; import org.eclipse.persistence.internal.sessions.UnitOfWorkImpl; import org.eclipse.persistence.mappings.ForeignReferenceMapping; /** * <p> * <b>Purpose:</b> In certain cases the contents of a relationship may be * retrievable from a cache. This ValueHolder instance provides the mechanism to * store a cached relationship and to load that relationship from a cache. This * functionality requires that the persistent identities of the targets can be * collected as database type foreign key queries are unavailable. * * @author gyorke * @since EclipseLink 1.1 */ public class CacheBasedValueHolder extends DatabaseValueHolder { protected transient ForeignReferenceMapping mapping; protected Object[] references; /** Setting to force the instantiation of the Collection on modification */ protected boolean shouldAllowInstantiationDeferral = true; public CacheBasedValueHolder(Object[] pks, AbstractRecord foreignKeys, AbstractSession session, ForeignReferenceMapping mapping){ super(); this.references = pks; this.mapping = mapping; this.session = session; this.row = foreignKeys; } public Object[] getCachedPKs(){ return this.references; } /** * Process against the UOW and attempt to load a local copy before going to the shared cache * If null is returned then the calling UOW will instantiate as normal. */ @Override public Object getValue(UnitOfWorkImpl uow) { if (this.references!= null && this.references.length!= 0){ if (mapping.isCollectionMapping()){ Collection result = uow.getIdentityMapAccessorInstance().getAllFromIdentityMapWithEntityPK(this.references, this.mapping.getReferenceDescriptor()).values(); if (result.size() == references.length){ ContainerPolicy cp = mapping.getContainerPolicy(); Object container = cp.containerInstance(result.size()); for (Object object : result){ cp.addInto(object, container, uow); } return container; } }else{ return uow.getIdentityMapAccessorInstance().getFromIdentityMap(this.references[0], this.mapping.getReferenceClass()); } } return null; } @Override protected Object instantiate() throws DatabaseException { return instantiate(this.session); } protected Object instantiate(AbstractSession localSession) throws DatabaseException { if (session == null){ throw ValidationException.instantiatingValueholderWithNullSession(); } return mapping.valueFromPKList(references, row, localSession); } /** * Triggers UnitOfWork valueholders directly without triggering the wrapped * valueholder (this). * <p> * When in transaction and/or for pessimistic locking the UnitOfWorkValueHolder * needs to be triggered directly without triggering the wrapped valueholder. * However only the wrapped valueholder knows how to trigger the indirection, * i.e. it may be a batchValueHolder, and it stores all the info like the row * and the query. * Note: This method is not thread-safe. It must be used in a synchronized manner */ @Override public Object instantiateForUnitOfWorkValueHolder(UnitOfWorkValueHolder unitOfWorkValueHolder) { return instantiate(unitOfWorkValueHolder.getUnitOfWork()); } @Override public boolean isPessimisticLockingValueHolder() { return false; } /** * Set if instantiation deferral on modification should be available. */ public void setShouldAllowInstantiationDeferral(boolean shouldAllowInstantiationDeferral){ this.shouldAllowInstantiationDeferral = shouldAllowInstantiationDeferral; } /** * INTERNAL: * Return if add/remove should trigger instantiation or avoid. * Current instantiation is avoided is using change tracking. */ @Override public boolean shouldAllowInstantiationDeferral() { return this.shouldAllowInstantiationDeferral; } } ======================= File: jpa/org.eclipse.persistence.jpa.jpql/src/org/eclipse/persistence/jpa/jpql/parser/ExistsExpression.java ======================= /******************************************************************************* * Copyright (c) 2006, 2018 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation * ******************************************************************************/ package org.eclipse.persistence.jpa.jpql.parser; import org.eclipse.persistence.jpa.jpql.ExpressionTools; import org.eclipse.persistence.jpa.jpql.WordParser; /** * An <b>EXISTS</b> expression is a predicate that is <code>true</code> only if the result of the * subquery consists of one or more values and that is <code>false</code> otherwise. * * <div><b>BNF:</b> <code>exists_expression ::= [NOT] EXISTS(subquery)</code><p></div> * * @version 2.5 * @since 2.3 * @author <NAME> */ public final class ExistsExpression extends AbstractSingleEncapsulatedExpression { /** * The actual <b>NOT</b> identifier found in the string representation of the JPQL query. */ private String notIdentifier; /** * Creates a new <code>ExistsExpression</code>. * * @param parent The parent of this expression */ public ExistsExpression(AbstractExpression parent) { super(parent, EXISTS); } /** * {@inheritDoc} */ @Override public void accept(ExpressionVisitor visitor) { visitor.visit(this); } /** * {@inheritDoc} */ @Override public String getEncapsulatedExpressionQueryBNFId() { return SubqueryBNF.ID; } /** * Returns the actual <b>NOT</b> identifier found in the string representation of the JPQL query, * which has the actual case that was used. * * @return The <b>NOT</b> identifier that was actually parsed, or an empty string if it was not * parsed */ public String getActualNotIdentifier() { return (notIdentifier!= null)? notIdentifier : ExpressionTools.EMPTY_STRING; } /** * {@inheritDoc} */ @Override public JPQLQueryBNF getQueryBNF() { return getQueryBNF(ExistsExpressionBNF.ID); } /** * Determines whether the identifier <b>NOT</b> was parsed. * * @return <code>true</code> if the identifier <b>NOT</b> was parsed; <code>false</code> otherwise */ public boolean hasNot() { return (notIdentifier!= null); } /** * {@inheritDoc} */ @Override protected void parse(WordParser wordParser, boolean tolerant) { // Parse 'NOT' if (wordParser.startsWithIgnoreCase('N')) { int position = wordParser.position(); notIdentifier = wordParser.substring(position, position + 3); setText(NOT_EXISTS); } super.parse(wordParser, tolerant); } /** * {@inheritDoc} */ @Override protected AbstractExpression parse(WordParser wordParser, String queryBNFId, boolean tolerant) { if (tolerant) { return super.parse(wordParser, queryBNFId, tolerant); } SimpleSelectStatement expression = new SimpleSelectStatement(this); expression.parse(wordParser, tolerant); return expression; } } ======================= File: jpa/org.eclipse.persistence.jpa.modelgen/src/org/eclipse/persistence/internal/jpa/modelgen/visitors/ElementVisitor.java ======================= <filename>jpa/org.eclipse.persistence.jpa.modelgen/src/org/eclipse/persistence/internal/jpa/modelgen/visitors/ElementVisitor.java /******************************************************************************* * Copyright (c) 1998, 2018 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * 08/10/2009-2.0 <NAME> * - 267391: JPA 2.0 implement/extend/use an APT tooling library for MetaModel API canonical classes * 08/25/2010-2.2 <NAME> * - 309445: CannonicalModelProcessor process all files * 11/23/2010-2.2 <NAME> * - 330660: Canonical model generator throws ClassCastException when using package-info.java ******************************************************************************/ package org.eclipse.persistence.internal.jpa.modelgen.visitors; import static org.eclipse.persistence.internal.jpa.metadata.MetadataConstants.ECLIPSELINK_PERSISTENCE_PACKAGE_PREFIX; import static org.eclipse.persistence.internal.jpa.metadata.MetadataConstants.JPA_PERSISTENCE_PACKAGE_PREFIX; import java.util.List; import java.util.Set; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; import javax.lang.model.element.PackageElement; import javax.lang.model.element.TypeElement; import javax.lang.model.element.TypeParameterElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.AbstractElementVisitor6; import javax.tools.Diagnostic.Kind; import org.eclipse.persistence.internal.helper.Helper; import org.eclipse.persistence.internal.jpa.metadata.MetadataLogger; import org.eclipse.persistence.internal.jpa.metadata.accessors.objects.MetadataAnnotatedElement; import org.eclipse.persistence.internal.jpa.metadata.accessors.objects.MetadataAnnotation; import org.eclipse.persistence.internal.jpa.metadata.accessors.objects.MetadataClass; import org.eclipse.persistence.internal.jpa.metadata.accessors.objects.MetadataField; import org.eclipse.persistence.internal.jpa.metadata.accessors.objects.MetadataMethod; import org.eclipse.persistence.internal.jpa.modelgen.MetadataMirrorFactory; import org.eclipse.persistence.logging.LogCategory; import org.eclipse.persistence.logging.LogLevel; /** * An element visitor. * * @author <NAME> * @since EclipseLink 1.2 */ public class ElementVisitor<R, P> extends AbstractElementVisitor6<MetadataAnnotatedElement, MetadataClass> { private ProcessingEnvironment processingEnv; private TypeVisitor<MetadataAnnotatedElement, MetadataAnnotatedElement> typeVisitor; /** * INTERNAL: */ public ElementVisitor(ProcessingEnvironment processingEnv) { this.processingEnv = processingEnv; typeVisitor = new TypeVisitor<MetadataAnnotatedElement, MetadataAnnotatedElement>(); } /** * INTERNAL: * The pre-processing stages requires some knowledge of the annotation * values (e.g. targetEntity) so we will visit the annotation values * and build complete MetadataAnnotation from the mirrors. */ protected void buildMetadataAnnotations(MetadataAnnotatedElement annotatedElement, List<? extends AnnotationMirror> annotationMirrors) { AnnotationValueVisitor<Object, Object> visitor = new AnnotationValueVisitor<Object, Object>(); for (AnnotationMirror annotationMirror : annotationMirrors) { String annotation = annotationMirror.getAnnotationType().toString() ; // Only add annotations that we care about. Be nice to have API // that we could call into with the annotation mirror to the // processor to see if it is a supported annotation. That is, it // would tie into the @SupportedAnnotationTypes({"javax.persistence.*", "org.eclipse.persistence.annotations.*"}) // declaration from CanonicalModelProcessor, but I couldn't find a // way to do this. For now we'll check the strings (similar to what // is done with our ASM factory). if (annotation.contains(JPA_PERSISTENCE_PACKAGE_PREFIX) || annotation.contains(ECLIPSELINK_PERSISTENCE_PACKAGE_PREFIX)) { annotatedElement.addAnnotation((MetadataAnnotation) visitor.visitAnnotation(annotationMirror, null)); } } } /** * INTERNAL: */ protected int getModifiers(Set<Modifier> modifiers) { int mods = 0; for (Modifier modifier : modifiers) { if (modifier.equals(Modifier.ABSTRACT)) { mods += java.lang.reflect.Modifier.ABSTRACT; } if (modifier.equals(Modifier.FINAL)) { mods += java.lang.reflect.Modifier.FINAL; } if (modifier.equals(Modifier.NATIVE)) { mods += java.lang.reflect.Modifier.NATIVE; } if (modifier.equals(Modifier.PRIVATE)) { mods += java.lang.reflect.Modifier.PRIVATE; } if (modifier.equals(Modifier.PROTECTED)) { mods += java.lang.reflect.Modifier.PROTECTED; } if (modifier.equals(Modifier.PUBLIC)) { mods += java.lang.reflect.Modifier.PUBLIC; } if (modifier.equals(Modifier.STATIC)) { mods += java.lang.reflect.Modifier.STATIC; } if (modifier.equals(Modifier.STRICTFP)) { mods += java.lang.reflect.Modifier.STRICT; } if (modifier.equals(Modifier.SYNCHRONIZED)) { mods += java.lang.reflect.Modifier.SYNCHRONIZED; } if (modifier.equals(Modifier.TRANSIENT)) { mods += java.lang.reflect.Modifier.TRANSIENT; } if (modifier.equals(Modifier.VOLATILE)) { mods += java.lang.reflect.Modifier.VOLATILE; } } return mods; } /** * INTERNAL: * Visit an executable and create a MetadataMethod object. */ @Override public MetadataMethod visitExecutable(ExecutableElement executableElement, MetadataClass metadataClass) { MetadataMethod method = new MetadataMethod(metadataClass.getMetadataFactory(), metadataClass); // Set the name. method.setName(executableElement.getSimpleName().toString()); // Set the attribute name. method.setAttributeName(Helper.getAttributeNameFromMethodName(method.getName())); // Set the modifiers. method.setModifiers(getModifiers(executableElement.getModifiers())); // Visit executable element for the parameters, return type and generic type. executableElement.asType().accept(typeVisitor, method); // Set the annotations. buildMetadataAnnotations(method, executableElement.getAnnotationMirrors()); // Handle multiple methods with the same name. MetadataMethod existing = metadataClass.getMethods().get(method.getName()); if (existing == null) { metadataClass.addMethod(method); } else { while (existing.getNext()!= null) { existing = existing.getNext(); } existing.setNext(method); } return method; } /** * INTERNAL: * Visit a packing-info.java file. We currently don't support package level * annotations, but if we did and they impacted canonical model generation * we would pick them up here. We should never hit this visit since we * filter out package elements, and package elements can not be referenced * from classes. */ @Override public MetadataClass visitPackage(PackageElement packageElement, MetadataClass metadataClass) { MetadataLogger logger = ((MetadataMirrorFactory) metadataClass.getMetadataFactory()).getLogger(); if (logger.shouldLog(LogLevel.FINE, LogCategory.PROCESSOR)) { processingEnv.getMessager().printMessage(Kind.NOTE, "ElementVisitor Package NOT IMPLEMENTED : " + packageElement); } return null; } /** * INTERNAL: */ @Override public MetadataClass visitType(TypeElement typeElement, MetadataClass metadataClass) { MetadataMirrorFactory factory = ((MetadataMirrorFactory) metadataClass.getMetadataFactory()); if (factory.getLogger().shouldLog(LogLevel.FINEST, LogCategory.PROCESSOR)) { processingEnv.getMessager().printMessage(Kind.NOTE, "Visiting class: " + typeElement); } // Set the qualified name. metadataClass.setName(typeElement.getQualifiedName().toString()); // By default, set the type to be the same as the name, which in most // cases is correct. For non JDK elements we'll visit the typeElement // further (see below). This will further process any generic types, // e.g. Employee<Integer>. For the most part I don't think we need to // care, certainly not with JDK classes but for round elements we'll // set them anyway. metadataClass.setType(metadataClass.getName()); // Add the interfaces. for (TypeMirror interfaceCls : typeElement.getInterfaces()) { metadataClass.addInterface(factory.getMetadataClass(interfaceCls).getName()); } // Set the superclass name (if there is one) TypeMirror superclass = typeElement.getSuperclass(); if (superclass!= null) { metadataClass.setSuperclassName(factory.getMetadataClass(superclass).getName()); } // As a performance gain, limit what is visited by JDK elements. if (! metadataClass.isJDK()) { // Set the modifiers. metadataClass.setModifiers(getModifiers(typeElement.getModifiers())); // Visit the type element for type and generic type. typeElement.asType().accept(typeVisitor, metadataClass); // Visit the enclosed elements. for (Element enclosedElement : typeElement.getEnclosedElements()) { ElementKind kind = enclosedElement.getKind(); if (kind.isClass() || kind.isInterface()) { metadataClass.addEnclosedClass(factory.getMetadataClass(enclosedElement)); } else { enclosedElement.accept(this, metadataClass); } } // Visit the annotations only if it is a round element. buildMetadataAnnotations(metadataClass, typeElement.getAnnotationMirrors()); } return metadataClass; } /** * INTERNAL: * Visit a generic type parameter (either to a field or method) * e.g Collection&lt;X&gt;, the type parameter being X. */ @Override public MetadataClass visitTypeParameter(TypeParameterElement typeParameterElement, MetadataClass metadataClass) { metadataClass.setName(typeParameterElement.getSimpleName().toString()); metadataClass.setType(TypeVisitor.GENERIC_TYPE); return metadataClass; } /** * INTERNAL: * Visit a variable and create a MetadataField object. */ @Override public MetadataField visitVariable(VariableElement variableElement, MetadataClass metadataClass) { MetadataField field = new MetadataField(metadataClass); // Set the name. field.setName(variableElement.getSimpleName().toString()); // Set the attribute name (same as name in this case) field.setAttributeName(field.getName()); // Visit the variable element for type and generic type. variableElement.asType().accept(typeVisitor, field); // Set the modifiers. field.setModifiers(getModifiers(variableElement.getModifiers())); // Set the annotations. buildMetadataAnnotations(field, variableElement.getAnnotationMirrors()); // Add the field to the class and return the field. metadataClass.addField(field); return field; } } ======================= File: foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/indirection/ValueHolder.java ======================= /******************************************************************************* * Copyright (c) 1998, 2018 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation from Oracle TopLink ******************************************************************************/ package org.eclipse.persistence.indirection; import java.io.Serializable; /** * <p> * <b>Purpose</b>: Act as a place holder for a variable that required a value holder interface. * This class should be used to initialze an objects attributes that are using indirection is their mappings. */ public class ValueHolder implements WeavedAttributeValueHolderInterface, Cloneable, Serializable { /** * Stores the wrapped object. */ protected Object value; /** * The two variable below are used as part of the implementation of WeavedAttributeValueHolderInterface * They are used to track whether a valueholder that has been weaved into a class is coordinated * with the underlying property */ // Set internally in TopLink when the state of coordination between a weaved valueholder and the underlying property is known private boolean isCoordinatedWithProperty = false; // Used to determine if this ValueHolder was added instantiated as part of the constructor of a weaved class private boolean isNewlyWeavedValueHolder = false; /** * PUBLIC: * Initialize the holder. */ public ValueHolder() { super(); } /** * PUBLIC: * Initialize the holder with an object. */ public ValueHolder(Object value) { this.value = value; } /** * INTERNAL: */ @Override public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException exception) { ; } return null; } /** * PUBLIC: * Return the wrapped object. */ @Override public Object getValue() { return value; } /** * Used as part of the implementation of WeavedAttributeValueHolderInterface * Used to track whether a valueholder that has been weaved into a class is coordinated * with the underlying property */ @Override public boolean isCoordinatedWithProperty(){ return isCoordinatedWithProperty; } /** * Used as part of the implementation of WeavedAttributeValueHolderInterface * Used to determine if this ValueHolder was added instantiated as part of * the constructor of a weaved class */ @Override public boolean isNewlyWeavedValueHolder(){ return isNewlyWeavedValueHolder; } /** * PUBLIC: * Return a boolean indicating whether the * wrapped object has been set or not. */ @Override public boolean isInstantiated() { // Always return true since we consider // null to be a valid wrapped object. return true; } /** * Used as part of the implementation of WeavedAttributeValueHolderInterface * Used to track whether a valueholder that has been weaved into a class is coordinated * with the underlying property * * This method will be called internall when the state of Coordination between the * weaved valueholder and the underlying value is known */ @Override public void setIsCoordinatedWithProperty(boolean coordinated){ this.isCoordinatedWithProperty = coordinated; // this is not a newly weaved valueholder any more since we have done some coordination work isNewlyWeavedValueHolder = false; } /** * Used as part of the implementation of WeavedAttributeValueHolderInterface * Used to determine if this ValueHolder was added instantiated as part of * the constructor of a weaved class * * This method will be called when a ValueHolder is instantiated in a weaved class */ @Override public void setIsNewlyWeavedValueHolder(boolean isNew){ this.isNewlyWeavedValueHolder = isNew; } /** * PUBLIC: * Set the wrapped object. */ @Override public void setValue(Object value) { this.value = value; } /** * INTERNAL: * Return if add/remove should trigger instantiation or avoid. * Current instantiation is avoided is using change tracking. */ @Override public boolean shouldAllowInstantiationDeferral() { return false; } /** * INTERNAL: */ @Override public String toString() { if (getValue() == null) { return "{" + null + "}"; } return "{" + getValue().toString() + "}"; } } ======================= File: foundation/org.eclipse.persistence.oracle.nosql/src/org/eclipse/persistence/internal/nosql/adapters/nosql/OracleNoSQLConnectionMetaData.java ======================= /******************************************************************************* * Copyright (c) 2011, 2018 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation ******************************************************************************/ package org.eclipse.persistence.internal.nosql.adapters.nosql; import javax.resource.*; import javax.resource.cci.*; import oracle.kv.KVVersion; /** * Defines the meta-data for the Oracle NoSQL adaptor * * @author James * @since EclipseLink 2.4 */ public class OracleNoSQLConnectionMetaData implements ConnectionMetaData { protected OracleNoSQLConnection connection; /** * Default constructor. */ public OracleNoSQLConnectionMetaData(OracleNoSQLConnection connection) { this.connection = connection; } @Override public String getEISProductName() throws ResourceException { try { return "Oracle NoSQL Database"; } catch (Exception exception) { throw new ResourceException(exception.toString()); } } @Override public String getEISProductVersion() throws ResourceException { try { return KVVersion.CURRENT_VERSION.getVersionString(); } catch (Exception exception) { throw new ResourceException(exception.toString()); } } @Override public String getUserName() throws ResourceException { try { return ""; } catch (Exception exception) { throw new ResourceException(exception.toString()); } } } ======================= File: foundation/org.eclipse.persistence.nosql/src/org/eclipse/persistence/internal/eis/adapters/xmlfile/XMLFileConnection.java ======================= /******************************************************************************* * Copyright (c) 1998, 2018 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation from Oracle TopLink ******************************************************************************/ package org.eclipse.persistence.internal.eis.adapters.xmlfile; import javax.resource.cci.*; import org.eclipse.persistence.exceptions.ValidationException; /** * Connection to XML file JCA adapter. * This is an emulated JCA adapter that access XML files. * * @author James * @since OracleAS TopLink 10<i>g</i> (10.0.3) */ public class XMLFileConnection implements Connection { protected XMLFileConnectionSpec spec; protected XMLFileTransaction transaction; /** * Default constructor. */ public XMLFileConnection() { this.transaction = new XMLFileTransaction(this); } public XMLFileConnection(XMLFileConnectionSpec spec) { this(); this.spec = spec; } @Override public void close() { } @Override public Interaction createInteraction() { return new XMLFileInteraction(this); } public XMLFileConnectionSpec getConnectionSpec() { return spec; } @Override public LocalTransaction getLocalTransaction() { return transaction; } public XMLFileTransaction getXMLFileTransaction() { return transaction; } @Override public ConnectionMetaData getMetaData() { return new XMLFileConnectionMetaData(); } /** * Result sets are not supported. */ @Override public ResultSetInfo getResultSetInfo() { throw ValidationException.operationNotSupported("getResultSetInfo"); } } ======================= File: dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/resources/unversioned/SingleResultQueryResource.java ======================= /******************************************************************************* * Copyright (c) 2011, 2018 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * ******************************************************************************/ package org.eclipse.persistence.jpa.rs.resources.unversioned; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import org.eclipse.persistence.jpa.rs.resources.common.AbstractSingleResultQueryResource; /** * PersistenceResource * * @deprecated Use {@link org.eclipse.persistence.jpa.rs.resources.SingleResultQueryResource} instead. * */ @Deprecated // Fix for Bug 393320 - JPA-RS: Respect the Accept Header for a singleResultQuery @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.APPLICATION_OCTET_STREAM }) @Path("/{context}/singleResultQuery/") public class SingleResultQueryResource extends AbstractSingleResultQueryResource { @GET @Path("{name}") public Response namedQuerySingleResult(@PathParam("context") String persistenceUnit, @PathParam("name") String name, @Context HttpHeaders hh, @Context UriInfo ui) { setRequestUniqueId(); return namedQuerySingleResultInternal(null, persistenceUnit, name, hh, ui); } } ======================= File: foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/eis/interactions/IndexedInteraction.java ======================= <reponame>jgrassel/eclipselink /******************************************************************************* * Copyright (c) 1998, 2018 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation from Oracle TopLink ******************************************************************************/ package org.eclipse.persistence.eis.interactions; import java.util.*; import javax.resource.*; import javax.resource.cci.*; import org.eclipse.persistence.internal.helper.DatabaseField; import org.eclipse.persistence.internal.sessions.AbstractRecord; import org.eclipse.persistence.sessions.DatabaseRecord; import org.eclipse.persistence.eis.*; /** * Defines the specification for a call to a JCA interaction that uses indexed records. * Builds the input and output records from the arguments. * * @author James * @since OracleAS TopLink 10<i>g</i> (10.0.3) */ public class IndexedInteraction extends EISInteraction { /** * Default constructor. */ public IndexedInteraction() { super(); } /** * PUBLIC: * Define the argument to the interaction for the index argument. * This must be called in the order of the arguments in the input indexed record. * The argumentFieldName is the field or argument name in the descriptor that maps to the indexed value. */ public void addArgument(String argumentFieldName) { getArguments().addElement(new DatabaseField(argumentFieldName)); } /** * PUBLIC: * Define the argument to the interaction for the index argument. * This must be called in the order of the arguments in the input indexed record. * The argumentValue is the value of the argument to be used to pass to the interaction. */ public void addArgumentValue(Object argumentValue) { getArguments().addElement(argumentValue); } /** * PUBLIC: * Define the field/argument name to be substitute for the index output argument. * This must be called in the order of the output arguments in the result indexed record. * The argumentFieldName is the field or argument name in the descriptor that maps to the indexed value. */ @Override public void addOutputArgument(String argumentFieldName) { getOutputArguments().addElement(new DatabaseField(argumentFieldName)); } /** * The arguments are the values in order of occurance in the record. */ @Override public Vector getArguments() { return super.getArguments(); } /** * The output arguments in order of occurance in the record. */ @Override public Vector getOutputArguments() { return super.getOutputArguments(); } /** * The arguments are the values in order of occurance in the record. */ @Override public void setArguments(Vector arguments) { super.setArguments(arguments); } /** * The output arguments in order of occurance in the record. */ @Override public void setOutputArguments(Vector outputArguments) { super.setOutputArguments(outputArguments); } /** * Create an indexed input record for this interaction. * Populate the data into the record from this interaction's arguments. */ @Override public Record createInputRecord(EISAccessor accessor) { try { IndexedRecord record = accessor.getRecordFactory().createIndexedRecord(getInputRecordName()); for (int index = 0; index < getParameters().size(); index++) { Object parameter = getParameters().get(index); // Allow conversion of nested rows and collections. record.add(createRecordElement("", parameter, accessor)); } return record; } catch (ResourceException exception) { throw EISException.resourceException(exception, accessor, null); } } /** * Build a database row from the record returned from the interaction. * Also handles MappedRecords for case of input being indexed but mapped ouput. */ @Override public AbstractRecord buildRow(Record record, EISAccessor accessor) { AbstractRecord row = null; if (record instanceof IndexedRecord) { IndexedRecord indexedRecord = (IndexedRecord)record; row = new DatabaseRecord(indexedRecord.size()); for (int index = 0; index < indexedRecord.size(); index++) { DatabaseField field = (DatabaseField)getOutputArguments().get(index); row.put(field, indexedRecord.get(index)); } } else if (record instanceof MappedRecord) { MappedRecord mappedRecord = (MappedRecord)record; // Handle the case of a single output argument of the entire row contained within the return record. if (getOutputArgumentNames().size() == 1) { mappedRecord = (MappedRecord)mappedRecord.get(getOutputArgumentNames().get(0)); // Handle the case were the output row is mapped into a database row of values. } else if (getOutputArgumentNames().size() > 1) { row = new DatabaseRecord(getOutputArgumentNames().size()); for (int index = 0; index < getOutputArgumentNames().size(); index++) { DatabaseField field = (DatabaseField)getOutputArguments().get(index); row.put(field, mappedRecord.get(getOutputArgumentNames().get(index))); } return row; } // Wrapped the record in a database to avoid loosing any information in conversion to database row, // also gets around problem of some adatpers not supporting keySet or entrySet. row = new EISMappedRecord(mappedRecord, accessor); } else { row = new DatabaseRecord(1); row.put(getOutputResultPath(), record); } return row; } } ======================= File: jpa/org.eclipse.persistence.jpa/src/org/eclipse/persistence/internal/jpa/config/listeners/EntityListenerImpl.java ======================= <gh_stars>0 /******************************************************************************* * Copyright (c) 2013, 2018 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * <NAME> - initial API and implementation ******************************************************************************/ package org.eclipse.persistence.internal.jpa.config.listeners; import org.eclipse.persistence.internal.jpa.config.MetadataImpl; import org.eclipse.persistence.internal.jpa.metadata.listeners.EntityListenerMetadata; import org.eclipse.persistence.jpa.config.EntityListener; /** * JPA scripting API implementation. * * @author <NAME> * @since EclipseLink 2.5.1 */ public class EntityListenerImpl extends MetadataImpl<EntityListenerMetadata> implements EntityListener { public EntityListenerImpl() { super(new EntityListenerMetadata()); } @Override public EntityListener setClass(String className) { getMetadata().setClassName(className); return this; } @Override public EntityListener setPostLoad(String methodName) { getMetadata().setPostLoad(methodName); return this; } @Override public EntityListener setPostPersist(String methodName) { getMetadata().setPostPersist(methodName); return this; } @Override public EntityListener setPostRemove(String methodName) { getMetadata().setPostRemove(methodName); return this; } @Override public EntityListener setPostUpdate(String methodName) { getMetadata().setPostUpdate(methodName); return this; } @Override public EntityListener setPrePersist(String methodName) { getMetadata().setPrePersist(methodName); return this; } @Override public EntityListener setPreRemove(String methodName) { getMetadata().setPreRemove(methodName); return this; } @Override public EntityListener setPreUpdate(String methodName) { getMetadata().setPreUpdate(methodName); return this; } } ======================= File: moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/internal/jaxb/many/JAXBArrayAttributeAccessor.java ======================= /******************************************************************************* * Copyright (c) 2011, 2018 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * <NAME> & <NAME> = 2.1 - Initial contribution ******************************************************************************/ package org.eclipse.persistence.internal.jaxb.many; import java.lang.reflect.Array; import java.util.Arrays; import java.util.List; import org.eclipse.persistence.core.mappings.CoreAttributeAccessor; import org.eclipse.persistence.exceptions.DescriptorException; import org.eclipse.persistence.internal.core.queries.CoreContainerPolicy; import org.eclipse.persistence.internal.security.PrivilegedAccessHelper; import org.eclipse.persistence.mappings.AttributeAccessor; /** * AttributeAccessor used in conjunction with an XMLCompositeDirectCollectionMapping to enable * support for mapping to arrays */ public class JAXBArrayAttributeAccessor extends AttributeAccessor { private CoreAttributeAccessor nestedAccessor; private CoreContainerPolicy containerPolicy; private String componentClassName; private Class componentClass; private String adaptedClassName; private Class<? extends ManyValue> adaptedClass; private ClassLoader classLoader; public JAXBArrayAttributeAccessor(CoreAttributeAccessor nestedAccessor, CoreContainerPolicy containerPolicy, ClassLoader classLoader) { this.nestedAccessor = nestedAccessor; this.containerPolicy = containerPolicy; this.classLoader = classLoader; } @Override public Object getAttributeValueFromObject(Object object) throws DescriptorException { Object arrayValue = nestedAccessor.getAttributeValueFromObject(object); if (arrayValue == null) { return null; } int length = Array.getLength(arrayValue); Object results = containerPolicy.containerInstance(length); if (null == adaptedClass) { for (int x = 0; x < length; x++) { containerPolicy.addInto(Array.get(arrayValue, x), results, null); } } else { for (int x = 0; x < length; x++) { try { ManyValue manyValue = PrivilegedAccessHelper.newInstanceFromClass(adaptedClass); manyValue.setItem(Array.get(arrayValue, x)); containerPolicy.addInto(manyValue, results, null); } catch (Exception e) { throw new RuntimeException(e); } } } return results; } @Override public void setAttributeValueInObject(Object object, Object value) throws DescriptorException { List listValue = (List) value; if (null == listValue || listValue.isEmpty()) { nestedAccessor.setAttributeValueInObject(object, null); return; } int[] dims = new int[1]; int listValueSize = listValue.size(); dims[0] = listValueSize; if (listValueSize > 0) { Object firstItem = listValue.get(0); if (firstItem instanceof ManyValue) { dims = getDimensions(dims, ((ManyValue) firstItem).getItem()); } } Object arrayValue = Array.newInstance(componentClass, dims); for (int i = 0; i < listValueSize; i++) { Object next = listValue.get(i); if (next instanceof ManyValue) { next = ((ManyValue) next).getItem(); } Array.set(arrayValue, i, next); } nestedAccessor.setAttributeValueInObject(object, arrayValue); } @Override public void initializeAttributes(Class theJavaClass) throws DescriptorException { nestedAccessor.initializeAttributes(theJavaClass); if (adaptedClass == null && adaptedClassName!= null) { try { adaptedClass = PrivilegedAccessHelper.getClassForName(adaptedClassName, true, classLoader); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } if (componentClass == null && componentClassName!= null) { try { componentClass = PrivilegedAccessHelper.getClassForName(componentClassName, true, classLoader); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } } public void setAdaptedClass(Class adaptedClass) { this.adaptedClass = componentClass; } public void setComponentClass(Class componentClass) { this.componentClass = componentClass; } public void setAdaptedClassName(String adaptedClassName) { this.adaptedClassName = adaptedClassName; } public void setComponentClassName(String componentClassName) { this.componentClassName = componentClassName; } private int[] getDimensions(int[] dimensions, Object array) { int[] newDimensions = Arrays.copyOf(dimensions, dimensions.length + 1); newDimensions[newDimensions.length - 1] = Array.getLength(array); Object nestedArray = Array.get(array, 0); if (nestedArray.getClass().isArray()) { return getDimensions(newDimensions, nestedArray); } return newDimensions; } public void setNestedAccessor(AttributeAccessor a) { this.nestedAccessor = a; } @Override public void setIsWriteOnly(boolean aBoolean) { super.setIsWriteOnly(aBoolean); this.nestedAccessor.setIsWriteOnly(aBoolean); } @Override public void setIsReadOnly(boolean aBoolean) { super.setIsReadOnly(aBoolean); this.nestedAccessor.setIsReadOnly(aBoolean); } } ======================= File: foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/sequencing/DefaultSequence.java ======================= /******************************************************************************* * Copyright (c) 1998, 2018 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation from Oracle TopLink ******************************************************************************/ package org.eclipse.persistence.sequencing; import java.util.Vector; import org.eclipse.persistence.internal.databaseaccess.Accessor; import org.eclipse.persistence.internal.sessions.AbstractSession; /** * <p> * <b>Purpose</b>: Reference to the default sequence. * <p> * <b>Description</b> * This sequence can be used to provide a sequence using the session's * default sequencing mechanism but override the pre-allocation size. */ public class DefaultSequence extends Sequence { public DefaultSequence() { super(); } /** * Create a new sequence with the name. */ public DefaultSequence(String name) { super(name, 0); } /** * Create a new sequence with the name and sequence pre-allocation size. */ public DefaultSequence(String name, int size) { super(name, size); } public DefaultSequence(String name, int size, int initialValue) { super(name, size, initialValue); } /** * INTERNAL: * Return the platform's default sequence. */ public Sequence getDefaultSequence() { return getDatasourcePlatform().getDefaultSequence(); } public boolean hasPreallocationSize() { return size!= 0; } @Override public int getPreallocationSize() { if ((size!= 0) || (getDefaultSequence() == null)) { return size; } else { return getDefaultSequence().getPreallocationSize(); } } @Override public int getInitialValue() { if ((initialValue!= 0) || (getDefaultSequence() == null)) { return initialValue; } else { return getDefaultSequence().getInitialValue(); } } @Override public boolean equals(Object obj) { if (obj instanceof DefaultSequence) { return equalNameAndSize(this, (DefaultSequence)obj); } else { return false; } } @Override public int hashCode() { return super.hashCode(); } /** * INTERNAL: * Indicates whether sequencing value should be acquired after INSERT. * Note that preallocation could be used only in case sequencing values * should be acquired before insert (this method returns false). * In default implementation, it is true for table sequencing and native * sequencing on Oracle platform, false for native sequencing on other platforms. */ @Override public boolean shouldAcquireValueAfterInsert() { return getDefaultSequence().shouldAcquireValueAfterInsert(); } /** * INTERNAL: * Indicates whether the existing pk value should always be overridden by the sequence. */ @Override public boolean shouldAlwaysOverrideExistingValue(String seqName) { return this.shouldAlwaysOverrideExistingValue || getDefaultSequence().shouldAlwaysOverrideExistingValue(seqName); } /** * INTERNAL: * Indicates whether several sequencing values should be acquired at a time * and be kept by TopLink. This in only possible in case sequencing numbers should * be acquired before insert (shouldAcquireValueAfterInsert()==false). * In default implementation, it is true for table sequencing and native * sequencing on Oracle platform, false for native sequencing on other platforms. */ @Override public boolean shouldUsePreallocation() { return getDefaultSequence().shouldUsePreallocation(); } /** * INTERNAL: * Indicates whether EclipseLink should internally call beginTransaction() before * getGeneratedValue/Vector, and commitTransaction after. * In default implementation, it is true for table sequencing and * false for native sequencing. */ @Override public boolean shouldUseTransaction() { return getDefaultSequence().shouldUseTransaction(); } /** * INTERNAL: * Return the newly-generated sequencing value. * Used only in case preallocation is not used (shouldUsePreallocation()==false). * Accessor may be non-null only in case shouldUseSeparateConnection()==true. * Even in this case accessor could be null - if SequencingControl().shouldUseSeparateConnection()==false; * Therefore in case shouldUseSeparateConnection()==true, implementation should handle * both cases: use a separate connection if provided (accessor!= null), or get by * without it (accessor == null). * @param accessor Accessor is a separate sequencing accessor (may be null); * @param writeSession Session is a Session used for writing (either ClientSession or DatabaseSession); * @param seqName String is sequencing number field name */ @Override public Object getGeneratedValue(Accessor accessor, AbstractSession writeSession, String seqName) { return getDefaultSequence().getGeneratedValue(accessor, writeSession, seqName); } /** * INTERNAL: * Return a Vector of newly-generated sequencing values. * Used only in case preallocation is used (shouldUsePreallocation()==true). * Accessor may be non-null only in case shouldUseSeparateConnection()==true. * Even in this case accessor could be null - if SequencingControl().shouldUseSeparateConnection()==false; * Therefore in case shouldUseSeparateConnection()==true, implementation should handle * both cases: use a separate connection if provided (accessor!= null), or get by * without it (accessor == null). * @param accessor Accessor is a separate sequencing accessor (may be null); * @param writeSession Session is a Session used for writing (either ClientSession or DatabaseSession); * @param seqName String is sequencing number field name * @param size int number of values to preallocate (output Vector size). */ @Override public Vector getGeneratedVector(Accessor accessor, AbstractSession writeSession, String seqName, int size) { return getDefaultSequence().getGeneratedVector(accessor, writeSession, seqName, size); } /** * INTERNAL: * This method is called when Sequencing object is created. * It's a chance to do initialization. */ @Override public void onConnect() { qualifier = getDefaultSequence().getQualifier(); } /** * INTERNAL: * This method is called when Sequencing object is destroyed.. * It's a chance to do deinitialization. */ @Override public void onDisconnect() { qualifier = ""; } /** * PUBLIC: * Indicates that Sequence is connected. */ @Override public boolean isConnected() { return getDefaultSequence().isConnected(); } /** * INTERNAL: * Ignored, getDefaultSequence().getQualifier() used instead. */ @Override public void setQualifier(String qualifier) { } } ======================= File: moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/prefixmapper/packageinfonamespace/package-info.java ======================= /******************************************************************************* * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * 03/16/2018-2.7.2 <NAME> * - 531349 - @XmlSchema Prefix is not honoured if root element is nil ******************************************************************************/ @XmlSchema( namespace = "NS", elementFormDefault = XmlNsForm.QUALIFIED, xmlns = { @XmlNs(namespaceURI = "extraUri", prefix = "PRE"), @XmlNs(namespaceURI = "http://www.w3.org/2001/XMLSchema-instance", prefix = "xsi") }) package org.eclipse.persistence.testing.jaxb.prefixmapper.packageinfonamespace; import javax.xml.bind.annotation.XmlNs; import javax.xml.bind.annotation.XmlNsForm; import javax.xml.bind.annotation.XmlSchema; ======================= File: moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/json/JSONTestSuite.java ======================= /******************************************************************************* * Copyright (c) 1998, 2018 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * <NAME> - August 2011 - 2.4 - Initial implementation ******************************************************************************/ package org.eclipse.persistence.testing.jaxb.json; import junit.framework.Test; import junit.framework.TestSuite; import org.eclipse.persistence.testing.jaxb.json.adapter.JsonMapAdapterTestCases; import org.eclipse.persistence.testing.jaxb.json.any.AnyTestCases; import org.eclipse.persistence.testing.jaxb.json.attribute.JSONAttributeNoXmlRootElementIncludeRootFalseTestCases; import org.eclipse.persistence.testing.jaxb.json.attribute.JSONAttributeNoXmlRootElementInheritanceTestCases; import org.eclipse.persistence.testing.jaxb.json.attribute.JSONAttributeNoXmlRootElementJAXBElementTestCases; import org.eclipse.persistence.testing.jaxb.json.attribute.JSONAttributeNoXmlRootElementTestCases; import org.eclipse.persistence.testing.jaxb.json.attribute.JSONAttributePrefixEmptyStringTestCases; import org.eclipse.persistence.testing.jaxb.json.attribute.JSONAttributePrefixOnContextTestCases; import org.eclipse.persistence.testing.jaxb.json.attribute.JSONAttributePrefixOnMarshallerTestCases; import org.eclipse.persistence.testing.jaxb.json.attribute.SimpleBeanAttrNullTestCases; import org.eclipse.persistence.testing.jaxb.json.characters.EscapeCharactersTestCases; import org.eclipse.persistence.testing.jaxb.json.characters.UTF8TestCases; import org.eclipse.persistence.testing.jaxb.json.characters.UsAsciiTestCases; import org.eclipse.persistence.testing.jaxb.json.emptyroot.EmptyNullMarshalUnmarshalTestCases; import org.eclipse.persistence.testing.jaxb.json.multiline.MultiLineStringTestCases; import org.eclipse.persistence.testing.jaxb.json.namespaces.DifferentNamespacesTestCases; import org.eclipse.persistence.testing.jaxb.json.namespaces.NamespaceInheritanceSeparatorContextTestCases; import org.eclipse.persistence.testing.jaxb.json.namespaces.NamespaceInheritanceSeparatorTestCases; import org.eclipse.persistence.testing.jaxb.json.namespaces.NamespaceInheritanceTestCases; import org.eclipse.persistence.testing.jaxb.json.namespaces.NamespacesOnContextTestCases; import org.eclipse.persistence.testing.jaxb.json.namespaces.NamespacesOnUnmarshalOnlyTestCases; import org.eclipse.persistence.testing.jaxb.json.namespaces.SeparatorInNameTestCases; import org.eclipse.persistence.testing.jaxb.json.nil.NilElementsUsageTestCases; import org.eclipse.persistence.testing.jaxb.json.norootelement.IncludeRootFalseWithXMLRootElementTestCases; import org.eclipse.persistence.testing.jaxb.json.norootelement.IncludeRootTrueWithXMLRootElementTestCases; import org.eclipse.persistence.testing.jaxb.json.norootelement.InheritanceNoRootTestCases; import org.eclipse.persistence.testing.jaxb.json.norootelement.NoRootElementNSTestCases; import org.eclipse.persistence.testing.jaxb.json.norootelement.NoRootElementTestCases; import org.eclipse.persistence.testing.jaxb.json.padding.JSONWithPaddingTestCases; import org.eclipse.persistence.testing.jaxb.json.rootlevellist.RootLevelListTestCases; import org.eclipse.persistence.testing.jaxb.json.type.TypeNameValueTestCases; import org.eclipse.persistence.testing.jaxb.json.type.TypePrefixTestCases; import org.eclipse.persistence.testing.jaxb.json.type.TypePropertyInheritanceTestCases; import org.eclipse.persistence.testing.jaxb.json.type.TypePropertyTestCases; import org.eclipse.persistence.testing.jaxb.json.unmapped.JsonUnmappedTestCases; import org.eclipse.persistence.testing.jaxb.json.wrapper.AllWrapperTestCases; import org.eclipse.persistence.testing.jaxb.json.xmlvalue.XMLValuePropDifferentTestCases; import org.eclipse.persistence.testing.jaxb.json.xmlvalue.XMLValuePropTestCases; import org.eclipse.persistence.testing.oxm.xmlconversionmanager.NumberTestCases; public class JSONTestSuite extends TestSuite { public static Test suite() { TestSuite suite = new TestSuite("JSONTestSuite"); suite.addTestSuite(JSONAttributePrefixOnContextTestCases.class); suite.addTestSuite(JSONAttributePrefixEmptyStringTestCases.class); suite.addTestSuite(JSONAttributePrefixOnMarshallerTestCases.class); suite.addTestSuite(JSONAttributeNoXmlRootElementTestCases.class); suite.addTestSuite(JSONAttributeNoXmlRootElementIncludeRootFalseTestCases.class); suite.addTestSuite(JsonMapAdapterTestCases.class); suite.addTestSuite(JSONAttributeNoXmlRootElementInheritanceTestCases.class); suite.addTestSuite(JSONAttributeNoXmlRootElementJAXBElementTestCases.class); suite.addTestSuite(SimpleBeanAttrNullTestCases.class); suite.addTestSuite(DifferentNamespacesTestCases.class); suite.addTestSuite(NamespacesOnContextTestCases.class); suite.addTestSuite(NamespacesOnUnmarshalOnlyTestCases.class); suite.addTestSuite(NoRootElementTestCases.class); suite.addTestSuite(NoRootElementNSTestCases.class); suite.addTestSuite(NamespaceInheritanceTestCases.class); suite.addTestSuite(NamespaceInheritanceSeparatorTestCases.class); suite.addTestSuite(NamespaceInheritanceSeparatorContextTestCases.class); suite.addTestSuite(NilElementsUsageTestCases.class); suite.addTestSuite(SeparatorInNameTestCases.class); suite.addTestSuite(IncludeRootFalseWithXMLRootElementTestCases.class); suite.addTestSuite(IncludeRootTrueWithXMLRootElementTestCases.class); suite.addTestSuite(XMLValuePropTestCases.class); suite.addTestSuite(XMLValuePropDifferentTestCases.class); suite.addTestSuite(NumberTestCases.class); suite.addTestSuite(EscapeCharactersTestCases.class); suite.addTestSuite(UsAsciiTestCases.class); suite.addTestSuite(UTF8TestCases.class); suite.addTest(RootLevelListTestCases.suite()); suite.addTestSuite(EmptyNullMarshalUnmarshalTestCases.class); suite.addTestSuite(InheritanceNoRootTestCases.class); suite.addTest(JSONWithPaddingTestCases.suite()); suite.addTest(AnyTestCases.suite()); suite.addTest(AllWrapperTestCases.suite()); suite.addTestSuite(MultiLineStringTestCases.class); suite.addTestSuite(TypeNameValueTestCases.class); suite.addTestSuite(TypePrefixTestCases.class); suite.addTestSuite(TypePropertyInheritanceTestCases.class); suite.addTestSuite(TypePropertyTestCases.class); suite.addTestSuite(JsonUnmappedTestCases.class); return suite; } } ======================= File: foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/tools/schemaframework/IndexDefinition.java ======================= /******************************************************************************* * Copyright (c) 2011, 2018 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation ******************************************************************************/ package org.eclipse.persistence.tools.schemaframework; import java.util.*; import java.io.*; import org.eclipse.persistence.exceptions.*; import org.eclipse.persistence.internal.sessions.AbstractSession; /** * <p> * <b>Purpose</b>: Allow for indexes to be created. * <p> * @author <NAME> * @since EclipseLink 2.2 */ public class IndexDefinition extends DatabaseObjectDefinition { protected String targetTable; protected List<String> fields; protected boolean isUnique; public IndexDefinition() { this.fields = new ArrayList(); } public boolean isUnique() { return isUnique; } public void setIsUnique(boolean isUnique) { this.isUnique = isUnique; } public String getTargetTable() { return targetTable; } /** * PUBLIC: * set qualified table name. */ public void setTargetTable(String targetTable) { this.targetTable = targetTable; } /** * PUBLIC: * Add the field to the index. */ public void addField(String fieldName) { this.fields.add(fieldName); } /** * INTERNAL: * Return the create type statement. */ @Override public Writer buildCreationWriter(AbstractSession session, Writer writer) throws ValidationException { try { writer.write(session.getPlatform().buildCreateIndex(getTargetTable(), getName(), getQualifier(), isUnique(), this.fields.toArray(new String[0]))); } catch (IOException ioException) { throw ValidationException.fileError(ioException); } return writer; } /** * INTERNAL: * Return the drop type statement. */ @Override public Writer buildDeletionWriter(AbstractSession session, Writer writer) throws ValidationException { try { writer.write(session.getPlatform().buildDropIndex(getTargetTable(), getName(), getQualifier())); } catch (IOException ioException) { throw ValidationException.fileError(ioException); } return writer; } public List<String> getFields() { return fields; } public void setFields(List<String> fields) { this.fields = fields; } } ======================= File: jpa/org.eclipse.persistence.jpa/src/org/eclipse/persistence/internal/jpa/config/columns/JoinColumnImpl.java ======================= /******************************************************************************* * Copyright (c) 2013, 2018 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * <NAME> - initial API and implementation ******************************************************************************/ package org.eclipse.persistence.internal.jpa.config.columns; import org.eclipse.persistence.internal.jpa.metadata.columns.JoinColumnMetadata; import org.eclipse.persistence.jpa.config.JoinColumn; /** * JPA scripting API implementation. * * @author <NAME> * @since EclipseLink 2.5.1 */ public class JoinColumnImpl extends AbstractRelationalColumnImpl<JoinColumnMetadata, JoinColumn> implements JoinColumn { public JoinColumnImpl() { super(new JoinColumnMetadata()); } @Override public JoinColumn setInsertable(Boolean insertable) { getMetadata().setInsertable(insertable); return this; } @Override public JoinColumn setNullable(Boolean nullable) { getMetadata().setNullable(nullable); return this; } @Override public JoinColumn setTable(String table) { getMetadata().setTable(table); return this; } @Override public JoinColumn setUpdatable(Boolean updatable) { getMetadata().setUpdatable(updatable); return this; } @Override public JoinColumn setUnique(Boolean unique) { getMetadata().setUnique(unique); return this; } } ======================= File: foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/exceptions/i18n/XMLPlatformExceptionResource.java ======================= /******************************************************************************* * Copyright (c) 1998, 2018 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation from Oracle TopLink ******************************************************************************/ package org.eclipse.persistence.exceptions.i18n; import java.util.ListResourceBundle; /** * INTERNAL: */ public class XMLPlatformExceptionResource extends ListResourceBundle { static final Object[][] contents = { { "27001", "The XML Platform class was not found: {0}" }, { "27002", "The XML Platform could not be instantiated: {0}" }, { "27003", "A new XML document could not be created." }, { "27004", "The XPath was invalid." }, { "27005", "An error occurred while validating the document." }, { "27006", "Could not resolve XML Schema: {0}" }, { "27101", "An error occurred while parsing the document." }, { "27102", "File not found: [{0}]" }, { "27103", "** Parsing error, line [{0}], uri [{1}] [{2}]" }, { "27201", "An error occurred while transforming the document." }, { "27202", "Unknown type encountered: {0}" }, }; /** * Return the lookup table. */ @Override protected Object[][] getContents() { return contents; } } ======================= File: jpa/eclipselink.jpa.test.jse/src/org/eclipse/persistence/jpa/test/property/model/Parent.java ======================= /******************************************************************************* * Copyright (c) 2018 IBM Corporation. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * 04/11/2018 - <NAME> * - 533148 : Add the eclipselink.jpa.sql-call-deferral property ******************************************************************************/ package org.eclipse.persistence.jpa.test.property.model; import javax.persistence.Entity; import javax.persistence.PrimaryKeyJoinColumn; import javax.persistence.Table; @Entity @Table(name = "PARENT") @PrimaryKeyJoinColumn(name="PARENT_PK", referencedColumnName="ABSTRACTPARENT_PK") public class Parent extends AbstractParent { } ======================= File: foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/internal/helper/CustomObjectInputStream.java ======================= /******************************************************************************* * Copyright (c) 1998, 2018 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation from Oracle TopLink ******************************************************************************/ package org.eclipse.persistence.internal.helper; import java.lang.Class; import java.lang.ClassNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.ObjectStreamClass; import java.io.ObjectInputStream; import org.eclipse.persistence.sessions.Session; import org.eclipse.persistence.internal.helper.ConversionManager; /** * INTERNAL: * Defines a custom ObjectInputStream that is used with SerializedObjectConverter * to ensure the correct class loader is used. * BUG# 2813583 * * @author <NAME> * @version 1.0 March 25/03 */ public class CustomObjectInputStream extends ObjectInputStream { ConversionManager m_conversionManager; public CustomObjectInputStream(InputStream stream, Session session) throws IOException { super(stream); m_conversionManager = session.getDatasourceLogin().getDatasourcePlatform().getConversionManager(); } @Override public Class resolveClass(ObjectStreamClass classDesc) throws ClassNotFoundException, IOException { return m_conversionManager.convertClassNameToClass(classDesc.getName()); } } ======================= File: jpa/org.eclipse.persistence.jpa.jpql/src/org/eclipse/persistence/jpa/jpql/tools/model/query/KeywordExpressionStateObject.java ======================= /******************************************************************************* * Copyright (c) 2011, 2018 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation * ******************************************************************************/ package org.eclipse.persistence.jpa.jpql.tools.model.query; import org.eclipse.persistence.jpa.jpql.Assert; import org.eclipse.persistence.jpa.jpql.parser.KeywordExpression; import static org.eclipse.persistence.jpa.jpql.parser.Expression.*; /** * The expression representing some keywords: <code>TRUE</code>, <code>FALSE</code> or <code>NULL</code>. * * @see KeywordExpression * * @version 2.4 * @since 2.4 * @author <NAME> */ @SuppressWarnings("nls") public class KeywordExpressionStateObject extends SimpleStateObject { /** * Creates a new <code>KeywordExpressionStateObject</code>. * * @param parent The parent of this state object, which cannot be <code>null</code> * @exception NullPointerException The given parent cannot be <code>null</code> */ public KeywordExpressionStateObject(StateObject parent) { super(parent); } /** * Creates a new <code>KeywordExpressionStateObject</code>. * * @param parent The parent of this state object, which cannot be <code>null</code> * @param text Either {@link org.eclipse.persistence.jpa.jpql.parser.Expression#TRUE TRUE}, * {@link org.eclipse.persistence.jpa.jpql.parser.Expression#FALSE FALSE} or * {@link org.eclipse.persistence.jpa.jpql.parser.Expression#NULL NULL} * @exception NullPointerException The given parent cannot be <code>null</code> */ public KeywordExpressionStateObject(StateObject parent, String text) { super(parent, text); validateIdentifier(text); } /** * {@inheritDoc} */ @Override public void accept(StateObjectVisitor visitor) { visitor.visit(this); } /** * {@inheritDoc} */ @Override public KeywordExpression getExpression() { return (KeywordExpression) super.getExpression(); } /** * Keeps a reference of the {@link KeywordExpression parsed object} object, which should only be * done when this object is instantiated during the conversion of a parsed JPQL query into * {@link StateObject StateObjects}. * * @param expression The {@link KeywordExpression parsed object} representing one of the three * possible keyword: <code><b>TRUE</b></code>, <code><b>FALSE</b></code> or <code><b>NULL</b></code> */ public void setExpression(KeywordExpression expression) { super.setExpression(expression); } /** * {@inheritDoc} */ @Override public void setText(String text) { validateIdentifier(text); super.setText(text); } protected void validateIdentifier(String text) { Assert.isValid(text, "Only TRUE, FALSE, and NULL are valid identifiers.", TRUE, FALSE, NULL); } } ======================= File: foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/descriptors/changetracking/DeferredChangeDetectionPolicy.java ======================= /******************************************************************************* * Copyright (c) 1998, 2018 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation from Oracle TopLink ******************************************************************************/ package org.eclipse.persistence.descriptors.changetracking; import java.beans.PropertyChangeListener; import java.util.*; import org.eclipse.persistence.internal.sessions.ObjectChangeSet; import org.eclipse.persistence.queries.*; import org.eclipse.persistence.internal.descriptors.*; import org.eclipse.persistence.internal.descriptors.changetracking.ObjectChangeListener; import org.eclipse.persistence.internal.sessions.MergeManager; import org.eclipse.persistence.descriptors.ClassDescriptor; import org.eclipse.persistence.mappings.*; import org.eclipse.persistence.descriptors.DescriptorEvent; import org.eclipse.persistence.descriptors.DescriptorEventManager; import org.eclipse.persistence.exceptions.ValidationException; import org.eclipse.persistence.internal.sessions.AbstractSession; import org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork; import org.eclipse.persistence.internal.sessions.UnitOfWorkChangeSet; import org.eclipse.persistence.internal.sessions.UnitOfWorkImpl; /** * PUBLIC: * A DeferredChangeDetectionPolicy defers all change detection to the UnitOfWork's * change detection process. Essentially, the calculateChanges() method will run * for all objects in a UnitOfWork. This is the default ObjectChangePolicy unless weaving is used. * * @author <NAME> */ public class DeferredChangeDetectionPolicy implements ObjectChangePolicy, java.io.Serializable { /** * INTERNAL: * PERF: Calculate change for the new object, avoids check for new since already know. */ @Override public ObjectChangeSet calculateChangesForNewObject(Object clone, UnitOfWorkChangeSet changeSet, UnitOfWorkImpl unitOfWork, ClassDescriptor descriptor, boolean shouldRaiseEvent) { return calculateChanges(clone, null, true, changeSet, unitOfWork, descriptor, shouldRaiseEvent); } /** * INTERNAL: * PERF: Calculate change for the new object, avoids check for new since already know. */ @Override public ObjectChangeSet calculateChangesForExistingObject(Object clone, UnitOfWorkChangeSet changeSet, UnitOfWorkImpl unitOfWork, ClassDescriptor descriptor, boolean shouldRaiseEvent) { return calculateChanges(clone, unitOfWork.getBackupClone(clone, descriptor), false, changeSet, unitOfWork, descriptor, shouldRaiseEvent); } /** * INTERNAL: * calculateChanges creates a change set for a particular object. In DeferredChangeDetectionPolicy * all mappings will be compared against a backup copy of the object. * @return an object change set describing * the changes to this object * @param clone the Object to compute a change set for * @param backUp the old version of the object to use for comparison * @param changeSet the change set to add changes to * @param unitOfWork the current session * @param descriptor the descriptor for this object * @param shouldRaiseEvent indicates whether PreUpdate event should be risen (usually true) */ @Override public ObjectChangeSet calculateChanges(Object clone, Object backUp, boolean isNew, UnitOfWorkChangeSet changeSet, UnitOfWorkImpl unitOfWork, ClassDescriptor descriptor, boolean shouldRaiseEvent) { // PERF: Avoid events if no listeners. if (descriptor.getEventManager().hasAnyEventListeners() && shouldRaiseEvent) { // The query is built for compatibility to old event mechanism. WriteObjectQuery writeQuery = new WriteObjectQuery(clone.getClass()); writeQuery.setObject(clone); writeQuery.setBackupClone(backUp); writeQuery.setSession(unitOfWork); writeQuery.setDescriptor(descriptor); descriptor.getEventManager().executeEvent(new DescriptorEvent(DescriptorEventManager.PreWriteEvent, writeQuery)); if (isNew) { descriptor.getEventManager().executeEvent(new DescriptorEvent(DescriptorEventManager.PreInsertEvent, writeQuery)); } else { descriptor.getEventManager().executeEvent(new DescriptorEvent(DescriptorEventManager.PreUpdateEvent, writeQuery)); } } ObjectChangeSet changes = createObjectChangeSet(clone, backUp, changeSet, isNew, unitOfWork, descriptor); if(changes.hasChanges() && descriptor.hasMappingsPostCalculateChanges() &&! changes.isNew() &&! unitOfWork.getCommitManager().isActive() &&!unitOfWork.isNestedUnitOfWork()) { // if we are in the commit because of an event skip this postCalculateChanges step as we have already executed it. int size = descriptor.getMappingsPostCalculateChanges().size(); for(int i=0; i < size; i++) { DatabaseMapping mapping = descriptor.getMappingsPostCalculateChanges().get(i); org.eclipse.persistence.sessions.changesets.ChangeRecord record = changes.getChangesForAttributeNamed(mapping.getAttributeName()); if(record!= null) { // Deferred attributes will already have been acted on, therefore we need // to post calculate changes to ensure orphaned objects are removed. mapping.postCalculateChanges(record, unitOfWork); } } } //Check if the user set the PK to null and throw an exception (bug# 4569755) if (changes.getId() == null &&!isNew &&!changes.isAggregate()) { if(!(unitOfWork.isNestedUnitOfWork()) || (unitOfWork.isNestedUnitOfWork() &&!(unitOfWork.isNewObjectInParent(clone)|| unitOfWork.isUnregisteredNewObjectInParent(unitOfWork.getCloneToOriginals().get(clone))))) { Object id = descriptor.getObjectBuilder().extractPrimaryKeyFromObject(clone, unitOfWork, false); throw ValidationException.nullPrimaryKeyInUnitOfWorkClone(clone, id); } } // if forceUpdate or optimistic read locking is on, mark changeSet. This is to force it // to be stored and used for writing out SQL later on if ((descriptor.getCMPPolicy()!= null) && (descriptor.getCMPPolicy().getForceUpdate())) { changes.setHasCmpPolicyForcedUpdate(true); } if (!changes.hasForcedChangesFromCascadeLocking() && unitOfWork.hasOptimisticReadLockObjects()) { Boolean modifyVersionField = (Boolean)unitOfWork.getOptimisticReadLockObjects().get(clone); if ((modifyVersionField!= null) && (unitOfWork instanceof RepeatableWriteUnitOfWork) && (((RepeatableWriteUnitOfWork)unitOfWork).getCumulativeUOWChangeSet()!= null)) { // modify the version field if the UOW cumulative change set does not contain a changeset for this clone if (((RepeatableWriteUnitOfWork)unitOfWork).getCumulativeUOWChangeSet().getObjectChangeSetForClone(clone) == null) { modifyVersionField = Boolean.TRUE; } } changes.setShouldModifyVersionField(modifyVersionField); } if (changes.hasChanges() || changes.hasForcedChanges()) { return changes; } return null; } /** * INTERNAL: * This is a place holder for reseting the listener on one of the subclasses */ @Override public void clearChanges(Object object, UnitOfWorkImpl uow, ClassDescriptor descriptor, boolean forRefresh) { } /** * INTERNAL: * Create ObjectChangeSet */ public ObjectChangeSet createObjectChangeSet(Object clone, Object backUp, org.eclipse.persistence.internal.sessions.UnitOfWorkChangeSet changeSet, boolean isNew, AbstractSession session, ClassDescriptor descriptor) { return this.createObjectChangeSetThroughComparison(clone, backUp, changeSet, isNew, session, descriptor); } /** * INTERNAL: * Create ObjectChangeSet */ @Override public ObjectChangeSet createObjectChangeSetThroughComparison(Object clone, Object backUp, org.eclipse.persistence.internal.sessions.UnitOfWorkChangeSet changeSet, boolean isNew, AbstractSession session, ClassDescriptor descriptor) { ObjectBuilder builder = descriptor.getObjectBuilder(); ObjectChangeSet changes = builder.createObjectChangeSet(clone, changeSet, isNew, true, session); // The following code deals with reads that force changes to the flag associated with optimistic locking. FetchGroup fetchGroup = null; // The flag indicates whether should get fetch group - to avoid doing // that twice. Useful because fetchGroup may be null. boolean shouldGetFetchGroup = true; if ((descriptor.usesOptimisticLocking()) && (changes.getId()!= null)) { if (descriptor.hasFetchGroupManager()) { fetchGroup = descriptor.getFetchGroupManager().getObjectFetchGroup(clone); } if (fetchGroup == null || fetchGroup!= descriptor.getFetchGroupManager().getIdEntityFetchGroup()) { changes.setOptimisticLockingPolicyAndInitialWriteLockValue(descriptor.getOptimisticLockingPolicy(), session); } // already tried to get the fetch group - no need to do that again. shouldGetFetchGroup = false; } // PERF: Do not create change records for new objects. if (!isNew || descriptor.shouldUseFullChangeSetsForNewObjects() || descriptor.isDescriptorTypeAggregate()) { // PERF: Avoid synchronized enumerator as is concurrency bottleneck. List mappings = descriptor.getMappings(); int mappingsSize = mappings.size(); if(shouldGetFetchGroup && descriptor.hasFetchGroupManager()) { fetchGroup = descriptor.getFetchGroupManager().getObjectFetchGroup(clone); } for (int index = 0; index < mappingsSize; index++) { DatabaseMapping mapping = (DatabaseMapping)mappings.get(index); if ((fetchGroup == null) || fetchGroup.containsAttributeInternal(mapping.getAttributeName())) { changes.addChange(mapping.compareForChange(clone, backUp, changes, session)); } } } return changes; } /** * INTERNAL: * This method is used to disable changetracking temporarily */ @Override public void dissableEventProcessing(Object changeTracker){ //no-op } /** * INTERNAL: * This method is used to enable changetracking temporarily */ @Override public void enableEventProcessing(Object changeTracker){ //no-op } /** * INTERNAL: * Return true if the Object should be compared, false otherwise. In DeferredChangeDetectionPolicy, * true is always returned since always allow the UnitOfWork to calculate changes. * @param object the object that will be compared * @param unitOfWork the active unitOfWork * @param descriptor the descriptor for the current object */ @Override public boolean shouldCompareExistingObjectForChange(Object object, UnitOfWorkImpl unitOfWork, ClassDescriptor descriptor) { return true; } /** * INTERNAL: * Build back up clone. Used if clone is new because listener should not be set. */ @Override public Object buildBackupClone(Object clone, ObjectBuilder builder, UnitOfWorkImpl uow) { return builder.buildBackupClone(clone, uow); } /** * INTERNAL: * Assign ChangeListener to an aggregate object */ @Override public void setAggregateChangeListener(Object parent, Object aggregate, UnitOfWorkImpl uow, ClassDescriptor descriptor, String mappingAttribute){ //no-op } /** * INTERNAL: * Set ChangeListener for the clone */ @Override public PropertyChangeListener setChangeListener(Object clone, UnitOfWorkImpl uow, ClassDescriptor descriptor) { return null; } /** * INTERNAL: * Set the ObjectChangeSet on the Listener, initially used for aggregate support */ @Override public void setChangeSetOnListener(ObjectChangeSet objectChangeSet, Object clone){ //no-op } /** * INTERNAL: * Clear changes in the ChangeListener of the clone */ @Override public void updateWithChanges(Object clone, ObjectChangeSet objectChangeSet, UnitOfWorkImpl uow, ClassDescriptor descriptor) { if (objectChangeSet == null) { return; } Object backupClone = uow.getCloneMapping().get(clone); if (backupClone!= null) { // If new just re-build the backup clone, otherwise use MergeManager (should be a special merge though, not the default constructor like it is...) if (objectChangeSet.isNew()) { uow.getCloneMapping().put(clone, descriptor.getObjectBuilder().buildBackupClone(clone, uow)); } else { MergeManager mergeManager = new MergeManager(uow); mergeManager.setCascadePolicy(MergeManager.NO_CASCADE); descriptor.getObjectBuilder().mergeChangesIntoObject(backupClone, objectChangeSet, clone, mergeManager, mergeManager.getSession()); } } clearChanges(clone, uow, descriptor, false); } /** * INTERNAL: * This may cause a property change event to be raised to a listener in the case that a listener exists. * If there is no listener then this call is a no-op */ @Override public void raiseInternalPropertyChangeEvent(Object source, String propertyName, Object oldValue, Object newValue){ //no-op } /** * INTERNAL: * This method is used to revert an object within the unit of work * @param cloneMapping may not be the same as what is in the uow */ @Override public void revertChanges(Object clone, ClassDescriptor descriptor, UnitOfWorkImpl uow, Map cloneMapping, boolean forRefresh) { cloneMapping.put(clone, buildBackupClone(clone, descriptor.getObjectBuilder(), uow)); clearChanges(clone, uow, descriptor, forRefresh); } /** * INTERNAL: * initialize the Policy */ @Override public void initialize(AbstractSession session, ClassDescriptor descriptor) { //do nothing } /** * Used to track instances of the change policies without doing an instance of check */ @Override public boolean isDeferredChangeDetectionPolicy(){ return true; } /** * Used to track instances of the change policies without doing an instance of check */ @Override public boolean isObjectChangeTrackingPolicy(){ return false; } /** * Used to track instances of the change policies without doing an instance of check */ @Override public boolean isAttributeChangeTrackingPolicy(){ return false; } /** * INTERNAL: * In cases where a relationship with detached or new entities is merged into itself previous changes may have been recorded for * the detached/new entity that need to be updated. */ @Override public void updateListenerForSelfMerge(ObjectChangeListener listener, ForeignReferenceMapping mapping, Object source, Object target, UnitOfWorkImpl unitOfWork) { //not applicable for this change detection type. } } ======================= File: moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/xmlelementref/nills2/OptFoo.java ======================= <reponame>jgrassel/eclipselink /******************************************************************************* * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation from Oracle TopLink ******************************************************************************/ package org.eclipse.persistence.testing.jaxb.xmlelementref.nills2; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElementRef; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class OptFoo { @XmlElementRef(name = "bar", namespace = "NS", type = JAXBElement.class, required = false) protected JAXBElement<Bar> bar; public OptFoo() {} public OptFoo(final JAXBElement<Bar> bar) { this.bar = bar; } public JAXBElement<Bar> getBar() { return bar; } public void setBar(final JAXBElement<Bar> bar) { this.bar = bar; } @Override public boolean equals(Object obj) { if (!(obj instanceof OptFoo)) { return false; } OptFoo e = (OptFoo) obj; if (!isEqual(e.getBar(), this.getBar())) { return false; } return true; } private boolean isEqual(JAXBElement<?> e1, JAXBElement<?> e2) { return e1.getName().equals(e2.getName()) && e1.getDeclaredType().equals(e2.getDeclaredType()) && (e1.isNil() == e2.isNil()) && (e1.getValue()).equals(e2.getValue()); } } ======================= File: foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/internal/sessions/remote/RemoteUnitOfWork.java ======================= <filename>foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/internal/sessions/remote/RemoteUnitOfWork.java /******************************************************************************* * Copyright (c) 1998, 2018 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation from Oracle TopLink * 07/15/2011-2.2.1 <NAME> * - 349424: persists during an preCalculateUnitOfWorkChangeSet event are lost ******************************************************************************/ package org.eclipse.persistence.internal.sessions.remote; import java.util.*; import org.eclipse.persistence.config.ReferenceMode; import org.eclipse.persistence.descriptors.ClassDescriptor; import org.eclipse.persistence.descriptors.DescriptorQueryManager; import org.eclipse.persistence.exceptions.*; import org.eclipse.persistence.internal.sessions.*; import org.eclipse.persistence.internal.databaseaccess.Platform; import org.eclipse.persistence.internal.helper.*; import org.eclipse.persistence.platform.database.DatabasePlatform; import org.eclipse.persistence.queries.DatabaseQuery; import org.eclipse.persistence.queries.ObjectLevelReadQuery; import org.eclipse.persistence.sessions.SessionProfiler; import org.eclipse.persistence.sessions.remote.*; import org.eclipse.persistence.logging.SessionLog; /** * Counter part of the unit of work which exists on the client side. */ public class RemoteUnitOfWork extends RepeatableWriteUnitOfWork { protected List newObjectsCache; protected List unregisteredNewObjectsCache; protected boolean isOnClient; protected transient RemoteSessionController parentSessionController; protected boolean isFlush; public RemoteUnitOfWork() { } public RemoteUnitOfWork(RemoteUnitOfWork parent) { this(parent, null); } public RemoteUnitOfWork(DistributedSession parent) { this(parent, null); } public RemoteUnitOfWork(RemoteUnitOfWork parent, ReferenceMode referenceMode) { super(parent, referenceMode); this.isOnClient = true; this.discoverUnregisteredNewObjectsWithoutPersist = true; } public RemoteUnitOfWork(DistributedSession parent, ReferenceMode referenceMode) { super(parent, referenceMode); this.isOnClient = true; this.discoverUnregisteredNewObjectsWithoutPersist = true; } public
1,507
_exp_param_t *pf_params; vrna_md_t *md; vrna_callback_hc_evaluate *evaluate; struct hc_ext_def_dat hc_dat_local; contribution = 0; S1 = fc->sequence_encoding; S2 = fc->sequence_encoding2; pf_params = fc->exp_params; md = &(pf_params->model_details); sn = fc->strand_number; ends = fc->strand_end; q = fc->exp_matrices->q; scale = fc->exp_matrices->scale; my_iindx = fc->iindx; evaluate = prepare_hc_ext_def(fc, &hc_dat_local); if ((sn[i]!= sn[j]) && (evaluate(i, j, i, j, VRNA_DECOMP_EXT_STEM, &hc_dat_local))) { /* most obious strand nick is at end of sn[i] and start of sn[j] */ type = vrna_get_ptype_md(S2[j], S2[i], md); s5 = (sn[j] == sn[j - 1])? S1[j - 1] : -1; s3 = (sn[i] == sn[i + 1])? S1[i + 1] : -1; qbase = vrna_exp_E_ext_stem(type, s5, s3, pf_params) * scale[2]; tmp = 0.; /* * if (evaluate(i + 1, * j - 1, * ends[sn[i]], * ends[sn[i]] + 1, * VRNA_DECOMP_EXT_EXT_EXT, * &hc_dat_local)) */ if (sn[i]!= sn[i + 1]) { if ((sn[j - 1]!= sn[j]) && (i + 1 == j)) tmp = 1.; else if (sn[j - 1] == sn[j]) tmp = q[my_iindx[i + 1] - j + 1]; } else if (sn[j - 1]!= sn[j]) { tmp = q[my_iindx[i + 1] - j + 1]; } else { tmp = q[my_iindx[i + 1] - ends[sn[i]]] * q[my_iindx[ends[sn[i]] + 1] - j + 1]; /* check whether we find more strand nicks between i and j */ nick = ends[sn[i]] + 1; while (sn[nick]!= sn[j]) { /* * if (evaluate(i + 1, * j - 1, * ends[sn[nick]], * ends[sn[nick]] + 1, * VRNA_DECOMP_EXT_EXT_EXT, * &hc_dat_local)) */ tmp2 = 1.; if (i + 1 <= ends[sn[nick]]) tmp2 *= q[my_iindx[i + 1] - ends[sn[nick]]]; if (ends[sn[nick]] + 1 <= j - 1) tmp2 *= q[my_iindx[ends[sn[nick]] + 1] - j + 1]; tmp += tmp2; nick = ends[sn[nick]] + 1; } } contribution = qbase * tmp; } return contribution; } ======================= File: src/ViennaRNA/fold_compound.h ======================= #ifndef VIENNA_RNA_PACKAGE_FOLD_COMPOUND_H #define VIENNA_RNA_PACKAGE_FOLD_COMPOUND_H /** * @file fold_compound.h * @ingroup fold_compound * @brief The Basic Fold Compound API */ /** * @addtogroup fold_compound The Fold Compound * @{ * * @brief This module provides interfaces that deal with the most basic data structure used * in structure predicting and energy evaluating function of the RNAlib. * * Throughout the entire RNAlib, the #vrna_fold_compound_t, is used to group * information and data that is required for structure prediction and energy evaluation. * Here, you'll find interface functions to create, modify, and delete #vrna_fold_compound_t * data structures. */ /** * @brief Typename for the fold_compound data structure #vrna_fc_s */ typedef struct vrna_fc_s vrna_fold_compound_t; /** * @brief Callback to free memory allocated for auxiliary user-provided data * * This type of user-implemented function usually deletes auxiliary data structures. * The user must take care to free all the memory occupied by the data structure passed. * * @callback * @parblock * This callback is supposed to free memory occupied by an auxiliary data structure. * It will be called when the #vrna_fold_compound_t is erased from memory through a * call to vrna_fold_compound_free() and will be passed the address of memory previously * bound to the #vrna_fold_compound_t via vrna_fold_compound_add_auxdata(). * @endparblock * * @see vrna_fold_compound_add_auxdata(), vrna_fold_compound_free(), vrna_fold_compound_add_callback() * * @param data The data that needs to be free'd */ typedef void (vrna_callback_free_auxdata)(void *data); /** * @brief Callback to perform specific user-defined actions before, or after recursive computations * * @callback * @parblock * This function will be called to notify a third-party implementation about the status of * a currently ongoing recursion. The purpose of this callback mechanism is to provide users * with a simple way to ensure pre- and post conditions for auxiliary mechanisms attached to * our implementations. * @endparblock * * @see vrna_fold_compound_add_auxdata(), vrna_fold_compound_add_callback(), vrna_mfe(), * vrna_pf(), * #VRNA_STATUS_MFE_PRE, #VRNA_STATUS_MFE_POST, #VRNA_STATUS_PF_PRE, #VRNA_STATUS_PF_POST * * @param status The status indicator * @param data The data structure that was assigned with vrna_fold_compound_add_auxdata() * @param status The status indicator */ typedef void (vrna_callback_recursion_status)(unsigned char status, void *data); /** * @brief Status message indicating that MFE computations are about to begin * * @see #vrna_fold_compound_t.stat_cb, vrna_callback_recursion_status(), vrna_mfe(), vrna_fold(), vrna_circfold(), * vrna_alifold(), vrna_circalifold(), vrna_cofold() */ #define VRNA_STATUS_MFE_PRE (unsigned char)1 /** * @brief Status message indicating that MFE computations are finished * * @see #vrna_fold_compound_t.stat_cb, vrna_callback_recursion_status(), vrna_mfe(), vrna_fold(), vrna_circfold(), * vrna_alifold(), vrna_circalifold(), vrna_cofold() */ #define VRNA_STATUS_MFE_POST (unsigned char)2 /** * @brief Status message indicating that Partition function computations are about to begin * * @see #vrna_fold_compound_t.stat_cb, vrna_callback_recursion_status(), vrna_pf() */ #define VRNA_STATUS_PF_PRE (unsigned char)3 /** * @brief Status message indicating that Partition function computations are finished * * @see #vrna_fold_compound_t.stat_cb, vrna_callback_recursion_status(), vrna_pf() */ #define VRNA_STATUS_PF_POST (unsigned char)4 #include <ViennaRNA/model.h> #include <ViennaRNA/params/basic.h> #include <ViennaRNA/sequence.h> #include <ViennaRNA/dp_matrices.h> #include <ViennaRNA/constraints/hard.h> #include <ViennaRNA/constraints/soft.h> #include <ViennaRNA/grammar.h> #include <ViennaRNA/structured_domains.h> #include <ViennaRNA/unstructured_domains.h> #ifdef VRNA_WITH_SVM #include <ViennaRNA/zscore.h> #endif /** * @brief An enumerator that is used to specify the type of a #vrna_fold_compound_t */ typedef enum { VRNA_FC_TYPE_SINGLE, /**< Type is suitable for single, and hybridizing sequences */ VRNA_FC_TYPE_COMPARATIVE /**< Type is suitable for sequence alignments (consensus structure prediction) */ } vrna_fc_type_e; /** * @brief The most basic data structure required by many functions throughout the RNAlib * * @note Please read the documentation of this data structure carefully! Some attributes are only available for * specific types this data structure can adopt. * * @warning Reading/Writing from/to attributes that are not within the scope of the current type usually result * in undefined behavior! * * @see #vrna_fold_compound_t.type, vrna_fold_compound(), vrna_fold_compound_comparative(), vrna_fold_compound_free(), * #VRNA_FC_TYPE_SINGLE, #VRNA_FC_TYPE_COMPARATIVE */ struct vrna_fc_s { /** * @name Common data fields * @{ */ const vrna_fc_type_e type; /**< @brief The type of the #vrna_fold_compound_t. * @details Currently possible values are #VRNA_FC_TYPE_SINGLE, and #VRNA_FC_TYPE_COMPARATIVE * @warning Do not edit this attribute, it will be automagically set by * the corresponding get() methods for the #vrna_fold_compound_t. * The value specified in this attribute dictates the set of other * attributes to use within this data structure. */ unsigned int length; /**< @brief The length of the sequence (or sequence alignment) */ int cutpoint; /**< @brief The position of the (cofold) cutpoint within the provided sequence. * If there is no cutpoint, this field will be set to -1 */ unsigned int *strand_number; /**< @brief The strand number a particular nucleotide is associated with */ unsigned int *strand_order; /**< @brief The strand order, i.e. permutation of current concatenated sequence */ unsigned int *strand_order_uniq; /**< @brief The strand order array where identical sequences have the same ID */ unsigned int *strand_start; /**< @brief The start position of a particular strand within the current concatenated sequence */ unsigned int *strand_end; /**< @brief The end (last) position of a particular strand within the current concatenated sequence */ unsigned int strands; vrna_seq_t *nucleotides; vrna_msa_t *alignment; vrna_hc_t *hc; /**< @brief The hard constraints data structure used for structure prediction */ vrna_mx_mfe_t *matrices; /**< @brief The MFE DP matrices */ vrna_mx_pf_t *exp_matrices; /**< @brief The PF DP matrices */ vrna_param_t *params; /**< @brief The precomputed free energy contributions for each type of loop */ vrna_exp_param_t *exp_params; /**< @brief The precomputed free energy contributions as Boltzmann factors */ int *iindx; /**< @brief DP matrix accessor */ int *jindx; /**< @brief DP matrix accessor */ /** * @} * * @name User-defined data fields * @{ */ vrna_callback_recursion_status *stat_cb; /**< @brief Recursion status callback (usually called just before, and * after recursive computations in the library * @see vrna_callback_recursion_status(), vrna_fold_compound_add_callback() */ void *auxdata; /**< @brief A pointer to auxiliary, user-defined data * @see vrna_fold_compound_add_auxdata(), #vrna_fold_compound_t.free_auxdata */ vrna_callback_free_auxdata *free_auxdata; /**< @brief A callback to free auxiliary user data whenever the fold_compound itself is free'd * @see #vrna_fold_compound_t.auxdata, vrna_callback_free_auxdata() */ /** * @} * * @name Secondary Structure Decomposition (grammar) related data fields * @{ */ /* data structure to adjust additional structural domains, such as G-quadruplexes */ vrna_sd_t *domains_struc; /**< @brief Additional structured domains */ /* data structure to adjust additional contributions to unpaired stretches, e.g. due to protein binding */ vrna_ud_t *domains_up; /**< @brief Additional unstructured domains */ /* auxiliary (user-defined) extension to the folding grammar */ vrna_gr_aux_t *aux_grammar; /** * @} */ #ifndef VRNA_DISABLE_C11_FEATURES /* C11 support for unnamed unions/structs */ union { struct { #endif /** * @name Data fields available for single/hybrid structure prediction * @{ */ char *sequence; /**< @brief The input sequence string * @warning Only available if @verbatim type==VRNA_FC_TYPE_SINGLE @endverbatim */ short *sequence_encoding; /**< @brief Numerical encoding of the input sequence * @see vrna_sequence_encode() * @warning Only available if @verbatim type==VRNA_FC_TYPE_SINGLE @endverbatim */ short *sequence_encoding2; char *ptype; /**< @brief Pair type array * * Contains the numerical encoding of the pair type for each pair (i,j) used * in MFE, Partition function and Evaluation computations. * @note This array is always indexed via jindx, in contrast to previously * different indexing between mfe and pf variants! * @warning Only available if @verbatim type==VRNA_FC_TYPE_SINGLE @endverbatim * @see vrna_idx_col_wise(), vrna_ptypes() */ char *ptype_pf_compat; /**< @brief ptype array indexed via iindx * @deprecated This attribute will vanish in the future! * It's meant for backward compatibility only! * @warning Only available if @verbatim type==VRNA_FC_TYPE_SINGLE @endverbatim */ vrna_sc_t *sc; /**< @brief The soft constraints for usage in structure prediction and evaluation * @warning Only available if @verbatim type==VRNA_FC_TYPE_SINGLE @endverbatim */ /** * @} */ #ifndef VRNA_DISABLE_C11_FEATURES /* C11 support for unnamed unions/structs */ }; struct { #endif /** * @name Data fields for consensus structure prediction * @{ */ char **sequences; /**< @brief The aligned sequences * @note The end of the alignment is indicated by a NULL pointer in the second dimension * @warning Only available if @verbatim type==VRNA_FC_TYPE_COMPARATIVE @endverbatim */ unsigned int n_seq; /**< @brief The number of sequences in the alignment * @warning Only available if @verbatim type==VRNA_FC_TYPE_COMPARATIVE @endverbatim */ char *cons_seq; /**< @brief The consensus sequence of the aligned sequences * @warning Only available if @verbatim type==VRNA_FC_TYPE_COMPARATIVE @endverbatim */ short *S_cons; /**< @brief Numerical encoding of the consensus sequence * @warning Only available if @verbatim type==VRNA_FC_TYPE_COMPARATIVE @endverbatim */ short **S; /**< @brief Numerical encoding of the sequences in the alignment * @warning Only available if @verbatim type==VRNA_FC_TYPE_COMPARATIVE @endverbatim */ short **S5; /**< @brief S5[s][i] holds next base 5' of i in sequence s * @warning Only available if @verbatim type==VRNA_FC_TYPE_COMPARATIVE @endverbatim */ short **S3; /**< @brief Sl[s][i] holds next base 3' of i in sequence s * @warning Only available if @verbatim type==VRNA_FC_TYPE_COMPARATIVE @endverbatim */ char **Ss; unsigned int **a2s; int *pscore; /**< @brief Precomputed array of pair types expressed as pairing scores * @warning Only available if @verbatim type==VRNA_FC_TYPE_COMPARATIVE @endverbatim */ int **pscore_local; /**< @brief Precomputed array of pair types expressed as pairing scores * @warning Only available if @verbatim type==VRNA_FC_TYPE_COMPARATIVE @endverbatim */ short *pscore_pf_compat; /**< @brief Precomputed array of pair types expressed as pairing scores indexed via iindx * @deprecated This attribute will vanish in the future! * @warning Only available if @verbatim type==VRNA_FC_TYPE_COMPARATIVE @endverbatim */ vrna_sc_t **scs; /**< @brief A set of soft constraints (for each sequence in the alignment) * @warning Only available if @verbatim type==VRNA_FC_TYPE_COMPARATIVE @endverbatim */ int oldAliEn; /** * @} */ #ifndef VRNA_DISABLE_C11_FEATURES }; }; #endif /** * @name Additional data fields for Distance Class Partitioning * * These data fields are typically populated with meaningful data only if used in the context of Distance Class Partitioning * @{ */ unsigned int maxD1; /**< @brief Maximum allowed base pair distance to first reference */ unsigned int maxD2; /**< @brief Maximum allowed base pair distance to second reference */ short *reference_pt1; /**< @brief A pairtable of the first reference structure */ short *reference_pt2; /**< @brief A pairtable of the second reference structure */ unsigned int *referenceBPs1; /**< @brief Matrix containing number of basepairs of reference structure1 in interval [i,j] */ unsigned int *referenceBPs2; /**< @brief Matrix containing number of basepairs of reference structure2 in interval [i,j] */ unsigned int *bpdist; /**< @brief Matrix containing base pair distance of reference structure 1 and 2 on interval [i,j] */ unsigned int *mm1; /**< @brief Maximum matching matrix, reference struct 1 disallowed */ unsigned int *mm2; /**< @brief Maximum matching matrix, reference struct 2 disallowed */ /** * @} */ /** * @name Additional data fields for local folding * * These data fields are typically populated with meaningful data only if used in the context of local folding * @{ */ int window_size; /**< @brief window size for local folding sliding window approach */ char **ptype_local; /**< @brief Pair type array (for local folding) */ #ifdef VRNA_WITH_SVM vrna_zsc_dat_t zscore_data; #endif /** * @} */ }; /* the definitions below should be used for functions that return/receive/destroy fold compound data structures */ /** * @brief Option flag to specify default settings/requirements */ #define VRNA_OPTION_DEFAULT 0U /** * @brief Option flag to specify requirement of Minimum Free Energy (MFE) DP matrices * and corresponding set of energy parameters * * @see vrna_fold_compound(), vrna_fold_compound_comparative(), #VRNA_OPTION_EVAL_ONLY */ #define VRNA_OPTION_MFE 1U /** * @brief Option flag to specify requirement of Partition Function (PF) DP matrices * and corresponding set of Boltzmann factors * * @see vrna_fold_compound(), vrna_fold_compound_comparative(), #VRNA_OPTION_EVAL_ONLY */ #define VRNA_OPTION_PF 2U /** * @brief Option flag to specify requirement of dimer DP matrices */ #define VRNA_OPTION_HYBRID 4U /** * @brief Option flag to specify that neither MFE, nor PF DP matrices are required * * Use this flag in conjuntion with #VRNA_OPTION_MFE, and #VRNA_OPTION_PF to save * memory for a #vrna_fold_compound_t obtained from vrna_fold_compound(), or vrna_fold_compound_comparative() * in cases where only energy evaluation but no structure prediction is required. * * @see vrna_fold_compound(), vrna_fold_compound_comparative(), vrna_eval_structure() */ #define VRNA_OPTION_EVAL_ONLY 8U /** * @brief Option flag to specify requirement of DP matrices for local folding approaches */ #define VRNA_OPTION_WINDOW 16U /** * @brief Retrieve a #vrna_fold_compound_t data structure for single sequences and hybridizing sequences * * This function provides an easy interface to obtain a prefilled #vrna_fold_compound_t by passing a single * sequence, or two contatenated sequences as input. For the latter, sequences need to be seperated by * an '&' character like this: @verbatim char *sequence = "GGGG&CCCC"; @endverbatim * * The optional parameter @p md_p can be used to specify the model details for successive computations * based on the content of the generated #vrna_fold_compound_t. Passing NULL will instruct the function * to use default model details. * The third parameter @p options may be used to specify dynamic programming (DP) matrix requirements. * * #### Options #### * * #VRNA_OPTION_DEFAULT - @copybrief #VRNA_OPTION_DEFAULT * * #VRNA_OPTION_MFE - @copybrief #VRNA_OPTION_MFE * * #VRNA_OPTION_PF - @copybrief #VRNA_OPTION_PF * * #VRNA_OPTION_WINDOW - @copybrief #VRNA_OPTION_WINDOW * * The above options may be OR-ed together. * * If you just need the folding compound serving as a container for your data, you can simply pass * #VRNA_OPTION_DEFAULT to the @p option parameter. This creates a #vrna_fold_compound_t without DP * matrices, thus saving memory. Subsequent calls of any structure prediction function will then take * care of allocating the memory required for the DP matrices. * If you only intend to evaluate structures instead of actually predicting them, you may use the * #VRNA_OPTION_EVAL_ONLY macro. This will seriously speedup the creation of the #vrna_fold_compound_t. * * @note The sequence string must be uppercase, and should contain only RNA (resp. DNA) alphabet depending * on what energy parameter set is used * * @see vrna_fold_compound_free(), vrna_fold_compound_comparative(), #vrna_md_t * * @param sequence A single sequence, or two concatenated sequences seperated by an '&' character * @param md_p An optional set of model details * @param options The options for DP matrices memory allocation * @return A prefilled vrna_fold_compound_t ready to be used for computations (may be @p NULL on error) */ vrna_fold_compound_t * vrna_fold_compound(const char *sequence, const vrna_md_t *md_p, unsigned int options); /** * @brief Retrieve a #vrna_fold_compound_t data structure for sequence alignments * * This function provides an easy interface to obtain a prefilled #vrna_fold_compound_t by passing an * alignment of sequences. * * The optional parameter @p md_p can be used to specify the model details for successive computations * based on the content of the generated #vrna_fold_compound_t. Passing NULL will instruct the function * to use default model details. * The third parameter @p options may be used to specify dynamic programming (DP) matrix requirements. * * #### Options #### * * #VRNA_OPTION_DEFAULT - @copybrief #VRNA_OPTION_DEFAULT * * #VRNA_OPTION_MFE - @copybrief #VRNA_OPTION_MFE * * #VRNA_OPTION_PF - @copybrief #VRNA_OPTION_PF * * #VRNA_OPTION_WINDOW - @copybrief #VRNA_OPTION_WINDOW * * The above options may be OR-ed together. * * If you just need the folding compound serving as a container for your data, you can simply pass * #VRNA_OPTION_DEFAULT to the @p option parameter. This creates a #vrna_fold_compound_t without DP * matrices, thus saving memory. Subsequent calls of any structure prediction function will then take * care of allocating the memory required for the DP matrices. * If you only intend to evaluate structures instead of actually predicting them, you may use the * #VRNA_OPTION_EVAL_ONLY macro. This will seriously speedup the creation of the #vrna_fold_compound_t. * * @note The sequence strings must be uppercase, and should contain only RNA (resp. DNA) alphabet including * gap characters depending on what energy parameter set is used. * * @see vrna_fold_compound_free(), vrna_fold_compound(), #vrna_md_t, #VRNA_OPTION_MFE, #VRNA_OPTION_PF, * #VRNA_OPTION_EVAL_ONLY, read_clustal() * * @param sequences A sequence alignment including 'gap' characters * @param md_p An optional set of model details * @param options The options for DP matrices memory allocation * @return A prefilled vrna_fold_compound_t ready to be used for computations (may be @p NULL on error) */ vrna_fold_compound_t * vrna_fold_compound_comparative(const char **sequences, vrna_md_t *md_p, unsigned int options); vrna_fold_compound_t * vrna_fold_compound_comparative2(const char **sequences, const char **names, const unsigned char *orientation, const unsigned long long *start, const unsigned long long *genome_size, vrna_md_t *md_p, unsigned int options); vrna_fold_compound_t * vrna_fold_compound_TwoD(const char *sequence, const char *s1, const char *s2, vrna_md_t *md_p, unsigned int options); int vrna_fold_compound_prepare(vrna_fold_compound_t *fc, unsigned int options); /** * @brief Free memory occupied by a #vrna_fold_compound_t * * @see vrna_fold_compound(), vrna_fold_compound_comparative(), vrna_mx_mfe_free(), vrna_mx_pf_free() * * @param fc The #vrna_fold_compound_t that is to be erased from memory */ void vrna_fold_compound_free(vrna_fold_compound_t *fc); /** * @brief Add auxiliary data to the #vrna_fold_compound_t * * This function allows one to bind arbitrary data to a #vrna_fold_compound_t which may later on be used * by one of the callback functions, e.g. vrna_callback_recursion_status(). To allow for proper cleanup * of the memory occupied by this auxiliary data, the user may also provide a pointer to a cleanup function * that free's the corresponding memory. This function will be called automatically when the #vrna_fold_compound_t * is free'd with vrna_fold_compound_free(). * * @note Before attaching the arbitrary data pointer, this function will call the vrna_callback_free_auxdata() * on any pre-existing data that is already attached. * * @see vrna_callback_free_auxdata() * @param fc The fold_compound the arbitrary data pointer should be associated with * @param data A pointer to an arbitrary data structure * @param f A pointer to function that free's memory occupied by the arbitrary data (May be NULL) */ void vrna_fold_compound_add_auxdata(vrna_fold_compound_t *fc, void *data, vrna_callback_free_auxdata *f); /** * @brief Add a recursion status callback to the #vrna_fold_compound_t * * Binding a recursion status callback function to a #vrna_fold_compound_t allows one to perform * arbitrary operations just before, or after an actual recursive computations, e.g. MFE prediction, * is performed by the RNAlib. The callback function will be provided with a pointer to its * #vrna_fold_compound_t, and a status message. Hence, it has complete access to all variables that * incluence the recursive computations. * * @see vrna_callback_recursion_status(), #vrna_fold_compound_t, * #VRNA_STATUS_MFE_PRE, #VRNA_STATUS_MFE_POST, #VRNA_STATUS_PF_PRE, #VRNA_STATUS_PF_POST * * @param fc The fold_compound the callback function should be attached to * @param f The pointer to the recursion status callback function */ void vrna_fold_compound_add_callback(vrna_fold_compound_t *fc, vrna_callback_recursion_status *f); /** * @} */ #endif ======================= File: src/ViennaRNA/eval.c ======================= <filename>src/ViennaRNA/eval.c /** \file eval.c */ /* * Free energy evaluation * * c <NAME>, <NAME> * original implementation by * <NAME> * * ViennaRNA Package >= v2.0 by <NAME> * * Vienna RNA package */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdio.h> #include <stdlib.h> #include <math.h> #include <ctype.h> #include <string.h> #include <unistd.h> #include <limits.h> #include "ViennaRNA/utils/basic.h" #include "ViennaRNA/utils/structures.h" #include "ViennaRNA/params/default.h" #include "ViennaRNA/model.h" #include "ViennaRNA/fold_vars.h" #include "ViennaRNA/params/basic.h" #include "ViennaRNA/constraints/hard.h" #include "ViennaRNA/constraints/soft.h" #include "ViennaRNA/loops/all.h" #include "ViennaRNA/gquad.h" #include "ViennaRNA/cofold.h" #include "ViennaRNA/alphabet.h" #include "ViennaRNA/datastructures/char_stream.h" #include "ViennaRNA/eval.h" #include "ViennaRNA/color_output.inc" #define ADD_OR_INF(a, b) (((a)!= INF) && ((b)!= INF)? (a) + (b) : INF) #define MULTISTRAND_EVAL /* ################################# # GLOBAL VARIABLES # ################################# */ /* ################################# # PRIVATE VARIABLES # ################################# */ /* ################################# # PRIVATE FUNCTION DECLARATIONS # ################################# */ PRIVATE int stack_energy(vrna_fold_compound_t *vc, int i, const short *pt, vrna_cstr_t output_stream, int verbostiy_level); PRIVATE int energy_of_ml_pt(vrna_fold_compound_t *vc, int i, const short *pt); #ifndef MULTISTRAND_EVAL PRIVATE int cut_in_loop(int i, const short *pt, unsigned int *sn); #endif PRIVATE int eval_pt(vrna_fold_compound_t *vc, const short *pt, vrna_cstr_t output_stream, int verbosity_level); PRIVATE int eval_circ_pt(vrna_fold_compound_t *vc, const short *pt, vrna_cstr_t output_stream, int verbosity_level); PRIVATE int en_corr_of_loop_gquad(vrna_fold_compound_t *vc, int i, int j, const char *structure, const short *pt, vrna_cstr_t output_stream, int verbosity_level); PRIVATE float wrap_eval_structure(vrna_fold_compound_t *vc, const char *structure, const short *pt, vrna_cstr_t output_stream, int verbosity); /* consensus structure variants below */ PRIVATE int covar_energy_of_struct_pt(vrna_fold_compound_t *vc, const short *pt); PRIVATE int stack_energy_covar_pt(vrna_fold_compound_t *vc, int i, const short *ptable); PRIVATE int en_corr_of_loop_gquad_ali(vrna_fold_compound_t *vc, int i, int j, const char *structure, const short *pt, const int *loop_idx, vrna_cstr_t output_stream, int verbosity_level); PRIVATE int covar_en_corr_of_loop_gquad(vrna_fold_compound_t *vc, int i, int j, const char *structure, const short *pt, const int *loop_idx); #ifdef MULTISTRAND_EVAL PRIVATE int energy_of_extLoop_pt(vrna_fold_compound_t *fc, unsigned int begin, const short *pt); #else PRIVATE int energy_of_extLoop_pt(vrna_fold_compound_t *vc, int i, const short *pt); #endif PRIVATE int energy_of_ext_loop_components(vrna_fold_compound_t *fc, const short *pt, vrna_cstr_t output_stream, int verbosity_level); PRIVATE int first_pair_after_last_nick(unsigned int i, unsigned int j, const short *pt, unsigned int *sn); /* ################################# # BEGIN OF FUNCTION DEFINITIONS # ################################# */ PUBLIC float vrna_eval_structure_v(vrna_fold_compound_t *vc, const char *structure, int verbosity_level, FILE *file) { if (strlen(structure)!= vc->length) { vrna_message_warning("vrna_eval_structure_*: " "string and structure have unequal length (%d vs. %d)", vc->length, strlen(structure)); return (float)INF / 100.; } vrna_cstr_t output_stream = vrna_cstr(vc->length, (file)? file : stdout); short *pt = vrna_ptable(structure); float en = wrap_eval_structure(vc, structure, pt, output_stream, verbosity_level); vrna_cstr_fflush(output_stream); vrna_cstr_free(output_stream); free(pt); return en; } PUBLIC float vrna_eval_structure_cstr(vrna_fold_compound_t *vc, const char *structure, int verbosity_level, vrna_cstr_t output_stream) { if (strlen(structure)!= vc->length) { vrna_message_warning("vrna_eval_structure_*: " "string and structure have unequal length (%d vs. %d)", vc->length, strlen(structure)); return (float)INF / 100.; } short *pt = vrna_ptable(structure); float en = wrap_eval_structure(vc, structure, pt, output_stream, verbosity_level); free(pt); return en; } PUBLIC float vrna_eval_covar_structure(vrna_fold_compound_t *vc, const char *structure) { int res, gq, *loop_idx; short *pt; pt = vrna_ptable(structure); res = 0; gq = vc->params->model_details.gquad; vc->params->model_details.gquad = 0; if (vc->type == VRNA_FC_TYPE_COMPARATIVE) { res = covar_energy_of_struct_pt(vc, pt); vc->params->model_details.gquad = gq; if (gq) { loop_idx = vrna_loopidx_from_ptable(pt); res -= covar_en_corr_of_loop_gquad(vc, 1, vc->length, structure, pt, (const int *)loop_idx); free(loop_idx); } } free(pt); return (float)res / (100. * (float)vc->n_seq); } PUBLIC int vrna_eval_structure_pt_v(vrna_fold_compound_t *vc, const short *pt, int verbosity_level, FILE *file) { int e = INF; if (pt && vc) { if (pt[0]!= (short)vc->length) { vrna_message_warning("vrna_eval_structure_*: " "string and structure have unequal length (%d vs. %d)", vc->length, pt[0]); return INF; } vrna_cstr_t output_stream = vrna_cstr(vc->length, (file)? file : stdout); e = eval_pt(vc, pt, output_stream, verbosity_level); vrna_cstr_fflush(output_stream); vrna_cstr_free(output_stream); } return e; } PUBLIC int vrna_eval_loop_pt_v(vrna_fold_compound_t *vc, int i, const short *pt, int verbosity_level) { /* compute energy of a single loop closed by base pair (i,j) */ unsigned int *sn; int j, type, p, q, energy; short *s; vrna_param_t *P; energy = INF; if (pt && vc) { P = vc->params; sn = vc->strand_number; s = vc->sequence_encoding2; vrna_sc_prepare(vc, VRNA_OPTION_MFE); /* evaluate exterior loop? */ if (i == 0) return energy_of_extLoop_pt(vc, 0, pt); j = pt[i]; if (j < i) { vrna_message_warning("vrna_eval_loop_pt*: " "i = %d is unpaired in loop_energy()", i); return INF; } type = P->model_details.pair[s[i]][s[j]]; if (type == 0) { type = 7; if (verbosity_level > VRNA_VERBOSITY_QUIET) { vrna_message_warning("bases %d and %d (%c%c) can't pair!", i, j, vrna_nucleotide_decode(s[i], &(P->model_details)), vrna_nucleotide_decode(s[j], &(P->model_details))); } } p = i; q = j; while (pt[++p] == 0); while (pt[--q] == 0); #ifdef MULTISTRAND_EVAL /* check, whether this is a base pair enclosing an external loop, i.e. strand-nick in loop */ unsigned int begin; if ((vc->strands > 1) && ((begin = first_pair_after_last_nick(p, q, pt, sn))!= 0)) return energy_of_extLoop_pt(vc, begin, pt); #endif if (p > q) { /* Hairpin */ energy = vrna_eval_hp_loop(vc, i, j); } else if (pt[q]!= (short)p) { /* multi-loop */ #ifndef MULTISTRAND_EVAL int ii; ii = cut_in_loop(i, (const short *)pt, sn); energy = (ii == 0)? energy_of_ml_pt(vc, i, (const short *)pt) : energy_of_extLoop_pt(vc, ii, (const short *)pt); #else energy = energy_of_ml_pt(vc, i, (const short *)pt); #endif } else { /* found interior loop */ int type_2; type_2 = P->model_details.pair[s[q]][s[p]]; if (type_2 == 0) { type_2 = 7; if (verbosity_level > VRNA_VERBOSITY_QUIET) { vrna_message_warning("bases %d and %d (%c%c) can't pair!", p, q, vrna_nucleotide_decode(s[p], &(P->model_details)), vrna_nucleotide_decode(s[q], &(P->model_details))); } } energy = vrna_eval_int_loop(vc, i, j, p, q); } } return energy; } PUBLIC int vrna_eval_move_pt(vrna_fold_compound_t *vc, short *pt, int m1, int m2) { /*compute change in energy given by move (m1,m2)*/ int en_post, en_pre, i, j, k, l, len; len = vc->length; k = (m1 > 0)? m1 : -m1; l = (m2 > 0)? m2 : -m2; /* first find the enclosing pair i<k<l<j */ for (j = l + 1; j <= len; j++) { if (pt[j] <= 0) continue; /* unpaired */ if (pt[j] < k) break; /* found it */ if (pt[j] > j) { j = pt[j]; /* skip substructure */ } else { vrna_message_warning("vrna_eval_move_pt: " "illegal move or broken pair table in vrna_eval_move_pt()\n" "%d %d %d %d ", m1, m2, j, pt[j]); return INF; } } i = (j <= len)? pt[j] : 0; en_pre = vrna_eval_loop_pt(vc, i, (const short *)pt); en_post = 0; if (m1 < 0) { /*it's a delete move */ en_pre += vrna_eval_loop_pt(vc, k, (const short *)pt); pt[k] = 0; pt[l] = 0; } else { /* insert move */ pt[k] = l; pt[l] = k; en_post += vrna_eval_loop_pt(vc, k, (const short *)pt); } en_post += vrna_eval_loop_pt(vc, i, (const short *)pt); /* restore pair table */ if (m1 < 0) { pt[k] = l; pt[l] = k; } else { pt[k] = 0; pt[l] = 0; } #ifndef MULTISTRAND_EVAL /* Cofolding -- Check if move changes COFOLD-Penalty */ if (sn[k]!= sn[l]) { int p, c; p = c = 0; for (p = 1; p < ss[so[1]];) { /* Count basepairs between two strands */ if (pt[p]!= 0) { if (sn[p] == sn[pt[p]]) /* Skip stuff */ p = pt[p]; else if (++c > 1) break; /* Count a basepair, break if we have more than one */ } p++; } if (m1 < 0 && c == 1) /* First and only inserted basepair */ return en_post - en_pre - P->DuplexInit; else if (c == 0) /* Must have been a delete move */ return en_post - en_pre + P->DuplexInit; } #endif return en_post - en_pre; } /* ################################# # STATIC helper functions below # ################################# */ PRIVATE INLINE int eval_ext_int_loop(vrna_fold_compound_t *vc, int i, int j, int p, int q) { unsigned char type, type_2; short **SS, **S5, **S3, *S, si, sj, sp, sq; unsigned int s, n_seq, **a2s; int e, length; vrna_param_t *P; vrna_md_t *md; vrna_sc_t *sc, **scs; length = vc->length; P = vc->params; md = &(P->model_details); S = vc->sequence_encoding; e = INF; switch (vc->type) { case VRNA_FC_TYPE_SINGLE: si = S[j + 1]; sj = S[i - 1]; sp = S[p - 1]; sq = S[q + 1]; type = vrna_get_ptype_md(S[j], S[i], md); type_2 = vrna_get_ptype_md(S[q], S[p], md); sc = vc->sc; e = ubf_eval_ext_int_loop(i, j, p, q, i - 1, j + 1, p - 1, q + 1, si, sj, sp, sq, type, type_2, length, P, sc); break; case VRNA_FC_TYPE_COMPARATIVE: n_seq = vc->n_seq; SS = vc->S; S5 = vc->S5; S3 = vc->S3; a2s = vc->a2s; n_seq = vc->n_seq; scs = vc->scs; for (e = 0, s = 0; s < n_seq; s++) { type = vrna_get_ptype_md(SS[s][j], SS[s][i], md); type_2 = vrna_get_ptype_md(SS[s][q], SS[s][p], md); sc = (scs && scs[s])? scs[s] : NULL; e += ubf_eval_ext_int_loop(a2s[s][i], a2s[s][j], a2s[s][p], a2s[s][q], a2s[s][i - 1], a2s[s][j + 1], a2s[s][p - 1], a2s[s][q + 1], S3[s][j], S5[s][i], S5[s][p], S3[s][q], type, type_2, a2s[s][length], P, sc); } break; } return e; } PRIVATE float wrap_eval_structure(vrna_fold_compound_t *vc, const char *structure, const short *pt, vrna_cstr_t output_stream, int verbosity) { int res, gq, L, l[3]; float energy; energy = (float)INF / 100.; gq = vc->params->model_details.gquad; vc->params->model_details.gquad = 0; switch (vc->type) { case VRNA_FC_TYPE_SINGLE: if (vc->params->model_details.circ) res = eval_circ_pt(vc, pt, output_stream, verbosity); else res = eval_pt(vc, pt, output_stream, verbosity); vc->params->model_details.gquad = gq; if (gq && (parse_gquad(structure, &L, l) > 0)) { if (verbosity > 0) vrna_cstr_print_eval_sd_corr(output_stream); res += en_corr_of_loop_gquad(vc, 1, vc->length, structure, pt, output_stream, verbosity); } energy = (float)res / 100.; break; case VRNA_FC_TYPE_COMPARATIVE: if (vc->params->model_details.circ) res = eval_circ_pt(vc, pt, output_stream, verbosity); else res = eval_pt(vc, pt, output_stream, verbosity); vc->params->model_details.gquad = gq; if (gq && (parse_gquad(structure, &L, l) > 0)) { if (verbosity > 0) vrna_cstr_print_eval_sd_corr(output_stream); int *loop_idx = vrna_loopidx_from_ptable(pt); res += en_corr_of_loop_gquad_ali(vc, 1, vc->length, structure, pt, (const int *)loop_idx, output_stream, verbosity); free(loop_idx); } energy = (float)res / (100. * (float)vc->n_seq); break; default: /* do nothing */ break; } return energy; } PRIVATE int eval_pt(vrna_fold_compound_t *vc, const short *pt, vrna_cstr_t output_stream, int verbosity_level) { int ee, energy; if (vc->params->model_details.gquad) vrna_message_warning("vrna_eval_*_pt: No gquadruplex support!\n" "Ignoring potential gquads in structure!\n" "Use e.g. vrna_eval_structure() instead!"); vrna_sc_prepare(vc, VRNA_OPTION_MFE); #ifdef MULTISTRAND_EVAL energy = energy_of_extLoop_pt(vc, 0, pt); if (verbosity_level > 0) { vrna_cstr_print_eval_ext_loop(output_stream, (vc->type == VRNA_FC_TYPE_COMPARATIVE)? (int)energy / (int)vc->n_seq : energy); } ee = energy_of_ext_loop_components(vc, pt, output_stream, verbosity_level); energy = ADD_OR_INF(energy, ee); #else energy = vc->params->model_details.backtrack_type == 'M'? energy_of_ml_pt(vc, 0, pt) : energy_of_extLoop_pt(vc, 0, pt); if (verbosity_level > 0) { vrna_cstr_print_eval_ext_loop(output_stream, (vc->type == VRNA_FC_TYPE_COMPARATIVE)? (int)energy / (int)vc->n_seq : energy); } for (i = 1; i <= length; i++) { if (pt[i] == 0) continue; ee = stack_energy(vc, i, pt, output_stream, verbosity_level); energy = ADD_OR_INF(energy, ee); i = pt[i]; } if (energy!= INF) { for (i = 1; sn[i]!= sn[length]; i++) { if (sn[i]!= sn[pt[i]]) { energy += vc->params->DuplexInit; break; } } } #endif return energy; } #ifdef MULTISTRAND_EVAL PRIVATE int energy_of_extLoop_pt(vrna_fold_compound_t *fc, unsigned int begin, const short *pt) { short *s, *s1, s5, s3, **S, **S5, **S3; unsigned int a, n, u, tt, *so, *sn, *ss, sss, strand, last_strand, i, j, last_i, start, n_seq, **a2s, strand_start, strand_end; int energy, dangle_model, bonus, e, e_mm3_occupied, e_mm3_available; vrna_param_t *P; vrna_md_t *md; vrna_sc_t *sc, **scs; n = fc->length; n_seq = (fc->type == VRNA_FC_TYPE_SINGLE)? 1 : fc->n_seq; s = (fc->type == VRNA_FC_TYPE_SINGLE)? fc->sequence_encoding2 : NULL; s1 = (fc->type == VRNA_FC_TYPE_SINGLE)? fc->sequence_encoding : NULL; S = (fc->type == VRNA_FC_TYPE_SINGLE)? NULL : fc->S; S5 = (fc->type == VRNA_FC_TYPE_SINGLE)? NULL : fc->S5; S3 = (fc->type == VRNA_FC_TYPE_SINGLE)? NULL : fc->S3; a2s = (fc->type == VRNA_FC_TYPE_SINGLE)? NULL : fc->a2s; so = fc->strand_order; sn = fc->strand_number; ss = fc->strand_start; P = fc->params; md = &(P->model_details); sc = (fc->type == VRNA_FC_TYPE_SINGLE)? fc->sc : NULL; scs = (fc->type == VRNA_FC_TYPE_SINGLE)? NULL : fc->scs; dangle_model = md->dangles; energy = 0; strand_start = strand_end = 0; /* * if begin == 0, or there exists only a single strand, * we evaluiate the entire external loop */ if ((begin == 0) || (fc->strands < 2)) { strand_end = fc->strands - 1; } else { /* * otherwise, we either evaluate an unconnected strand or the * external loop part that connects the current strand (sn[begin]) */ for (a = strand_start; a < fc->strands; a++) if (so[a] == sn[begin]) { strand_start = strand_end = a; break; } } /* start scanning for enclosing pair from each strand nick */ for (a = strand_start; a <= strand_end; a++) { e = 0; bonus = 0; e_mm3_available = INF; e_mm3_occupied = 0; strand = last_strand = so[a]; /* strand number in current permutation */ i = last_i = start = ss[strand]; while (i <= n) { if (sn[i]!= last_strand) { /* add energy of previous unpaired region */ switch (fc->type) { case VRNA_FC_TYPE_SINGLE: if (sc) if (sc->energy_up) bonus += sc->energy_up[last_i][i - last_i]; break; case VRNA_FC_TYPE_COMPARATIVE: if (scs) { for (sss = 0; sss < n_seq; sss++) { if (scs[sss]) { if (scs[sss]->energy_up) { u = a2s[sss][i] - a2s[sss][last_i]; bonus += scs[sss]->energy_up[a2s[sss][last_i]][u]; } } } } break; } break; } if ((pt[i]!= 0) && (pt[i] > i)) { /* * pairs down-stream * add energy of previous unpaired region */ switch (fc->type) { case VRNA_FC_TYPE_SINGLE: if (sc) if (sc->energy_up) bonus += sc->energy_up[last_i][i - last_i]; break; case VRNA_FC_TYPE_COMPARATIVE: if (scs) { for (sss = 0; sss < n_seq; sss++) { if (scs[sss]) { if (scs[sss]->energy_up) { u = a2s[sss][i] - a2s[sss][last_i]; bonus += scs[sss]->energy_up[a2s[sss][last_i]][u]; } } } } break; } j = (unsigned int)pt[i]; /* add energy of branch */ switch (fc->type) { case VRNA_FC_TYPE_SINGLE: tt = vrna_get_ptype_md(s[i], s[j], md); switch (dangle_model) { case 0: e += vrna_E_ext_stem(tt, -1, -1, P); break; case 2: s5 = ((sn[i - 1] == sn[i]) && (i > 1))? s1[i - 1] : -1; s3 = ((sn[j] == sn[j + 1]) && (j < n))? s1[j + 1] : -1; e += vrna_E_ext_stem(tt, s5, s3, P); break; default: s5 = ((sn[i - 1] == sn[i]) && (i > 1) && (!pt[i - 1]))? s1[i - 1] : -1; s3 = ((sn[j] == sn[j + 1]) && (j < n) && (!pt[j + 1]))? s1[j + 1] : -1; if ((last_i + 1 < i) || ((last_i == start) && (last_i < i))) { e_mm3_available = MIN2(e_mm3_available, e_mm3_occupied); e_mm3_occupied = e_mm3_available; } e = MIN2( e_mm3_occupied + vrna_E_ext_stem(tt, -1, s3, P), e_mm3_available + vrna_E_ext_stem(tt, s5, s3, P) ); e_mm3_available = MIN2( e_mm3_occupied + vrna_E_ext_stem(tt, -1, -1, P), e_mm3_available + vrna_E_ext_stem(tt, s5, -1, P) ); e_mm3_occupied = e; break; } break; case VRNA_FC_TYPE_COMPARATIVE: for (sss = 0; sss < n_seq; sss++) { tt = vrna_get_ptype_md(S[sss][i], S[sss][j], md); switch (dangle_model) { case 0: e += vrna_E_ext_stem(tt, -1, -1, P); break; case 2: s5 = ((sn[i - 1] == sn[i]) && (a2s[sss][i] > 1))? S5[sss][i] : -1; s3 = ((sn[j] == sn[j + 1]) && (a2s[sss][j] < a2s[sss][n]))? S3[sss][j] : -1; e += vrna_E_ext_stem(tt, s5, s3, P); break; default: /* odd dangles not implemented yet */ break; } } break; } i = j; /* skip the branch we'ce just evaluated */ last_i = i + 1; /* update last unpaired nt */ last_strand = sn[i]; /* update current strand number */ } else if (pt[i]!= 0) { /* * found 3' end of enclosing pair * add energy of previous unpaired region */ switch (fc->type) { case VRNA_FC_TYPE_SINGLE: if (sc) if (sc->energy_up) bonus += sc->energy_up[last_i][i - last_i]; break; case VRNA_FC_TYPE_COMPARATIVE: if (scs) { for (sss = 0; sss < n_seq; sss++) { if (scs[sss]) { if (scs[sss]->energy_up) { u = a2s[sss][i] - a2s[sss][last_i]; bonus += scs[sss]->energy_up[a2s[sss][last_i]][u]; } } } } break; } j = i; i = (unsigned int)pt[i]; /* add energy of enclosing base pair */ switch (fc->type) { case VRNA_FC_TYPE_SINGLE: tt = vrna_get_ptype_md(s[j], s[i], md); switch (dangle_model) { case 0: e += vrna_E_ext_stem(tt, -1, -1, P); break; case 2: s5 = (sn[j - 1] == sn[j])? s1[j - 1] : -1; s3 = (sn[i] == sn[i + 1])? s1[i + 1] : -1; e += vrna_E_ext_stem(tt, s5, s3, P); break; default: s5 = ((sn[j - 1] == sn[j]) && (!pt[j - 1]))? s1[j - 1] : -1; s3 = ((sn[i] == sn[i + 1]) && (!pt[i + 1]))? s1[i + 1] : -1; if ((last_i + 1 < j) || ((last_i == start) && (last_i < j))) { e_mm3_available = MIN2(e_mm3_available, e_mm3_occupied); e_mm3_occupied = e_mm3_available; } e = MIN2( e_mm3_occupied + vrna_E_ext_stem(tt, -1, s3, P), e_mm3_available + vrna_E_ext_stem(tt, s5, s3, P) ); e_mm3_available = MIN2( e_mm3_occupied + vrna_E_ext_stem(tt, -1, -1, P), e_mm3_available + vrna_E_ext_stem(tt, s5, -1, P) ); e_mm3_occupied = e; break; } break; case VRNA_FC_TYPE_COMPARATIVE: for (sss = 0; sss < n_seq; sss++) { tt = vrna_get_ptype_md(S[sss][j], S[sss][i], md); switch (dangle_model) { case 0: e += vrna_E_ext_stem(tt, -1, -1, P); break; case 2: s5 = (sn[j - 1] == sn[j])? S5[sss][j] : -1; s3 = (sn[i] == sn[i + 1])? S3[sss][i] : -1; e += vrna_E_ext_stem(tt, s5, s3, P); break; default: /* odd dangles not implemented yet */ break; } } break; } /* add duplex initiation penalty */ if (dangle_model % 2) { e_mm3_available += P->DuplexInit * n_seq; e_mm3_occupied += P->DuplexInit * n_seq; } else { e += fc->params->DuplexInit * n_seq; } /* update index variables */ last_i = i + 1; last_strand = sn[i]; } else if (i == n) { /* * end of outer-most external loop * add energy of unpaired region */ switch (fc->type) { case VRNA_FC_TYPE_SINGLE: if (sc) if (sc->energy_up) bonus += sc->energy_up[last_i][i - last_i + 1]; break; case VRNA_FC_TYPE_COMPARATIVE: if (scs) { for (sss = 0; sss < n_seq; sss++) { if (scs[sss]) { if (scs[sss]->energy_up) { u = a2s[sss][i + 1] - a2s[sss][last_i]; bonus += scs[sss]->energy_up[a2s[sss][last_i]][u]; } } } } break; } } i++; } if (dangle_model % 2) e = MIN2(e_mm3_available, e_mm3_occupied); e += bonus; energy += e; } return energy; } PRIVATE int energy_of_ext_loop_components(vrna_fold_compound_t *fc, const short *pt, vrna_cstr_t output_stream, int verbosity_level) { unsigned int last_s, s, i, n, a, *so, *sn, *ss; int energy = 0; n = fc->length; so = fc->strand_order; sn = fc->strand_number; ss = fc->strand_start; energy = 0; /* start scanning for enclosing pair from each strand start site in 5'->3' direction */ for (a = 0; a < fc->strands; a++) { s = last_s = so[a]; /* strand number in current permutation */ i = ss[s]; while (i <= n) { if (sn[i]!= last_s) break; if (pt[i]!= 0) { if (pt[i] > i) { /* * pairs down-stream * add energy of enclosed substem */ energy += stack_energy(fc, i, pt, output_stream, verbosity_level); i = (unsigned int)pt[i]; last_s = sn[i]; /* update current strand number */ } else { /* * found 3' end of enclosing pair * update index variables */ i = (unsigned int)pt[i]; last_s = sn[i]; } } i++; } } return energy; } #endif PRIVATE int eval_circ_pt(vrna_fold_compound_t *vc, const short *pt, vrna_cstr_t output_stream, int verbosity_level) { unsigned int s, n_seq; int i, j, length, energy, en0, degree; unsigned int **a2s; vrna_param_t *P; vrna_sc_t *sc, **scs; energy = 0; en0 = 0; degree = 0; length = vc->length; P = vc->params; sc = (vc->type == VRNA_FC_TYPE_SINGLE)? vc->sc : NULL; scs = (vc->type == VRNA_FC_TYPE_COMPARATIVE)? vc->scs : NULL; if (P->model_details.gquad) vrna_message_warning("vrna_eval_*_pt: No gquadruplex support!\n" "Ignoring potential gquads in structure!\n" "Use e.g. vrna_eval_structure() instead!"); vrna_sc_prepare(vc, VRNA_OPTION_MFE); /* evaluate all stems in exterior loop */ for (i = 1; i <= length; i++) { if (pt[i] == 0) continue; degree++; energy += stack_energy(vc, i, (const short *)pt, output_stream, verbosity_level); i = pt[i]; } /* find first stem */ for (i = 1; (i <= length) && (!pt[i]); i++); j = pt[i]; /* evaluate exterior loop itself */ switch (degree) { case 0: /* unstructured */ switch (vc->type) { case VRNA_FC_TYPE_SINGLE: if (sc) if (sc->energy_up) en0 += sc->energy_up[1][length]; break; case VRNA_FC_TYPE_COMPARATIVE: n_seq = vc->n_seq; a2s = vc->a2s; if (scs) { for (s = 0; s < n_seq; s++) if (scs[s] && scs[s]->energy_up) en0 += scs[s]->energy_up[1][a2s[s][length]]; } break; } break; case 1: /* hairpin loop */ en0 = vrna_eval_ext_hp_loop(vc, i, j); break; case 2: /* interior loop */ { int p, q; /* seek to next pair */ for (p = j + 1; pt[p] == 0; p++); q = pt[p]; en0 = eval_ext_int_loop(vc, i, j, p, q); } break; default: /* multibranch loop */ en0 = energy_of_ml_pt(vc, 0, (const short *)pt); if (vc->type == VRNA_FC_TYPE_SINGLE) en0 -= E_MLstem(0, -1, -1, P); /* remove virtual closing pair */ break; } if (verbosity_level > 0) { vrna_cstr_print_eval_ext_loop(output_stream, (vc->type == VRNA_FC_TYPE_COMPARATIVE)? (int)en0 / (int)vc->n_seq : en0); } energy += en0; return energy; } /*---------------------------------------------------------------------------*/ /* returns a correction term that may be added to the energy retrieved * from energy_of_struct_par() to correct misinterpreted loops. This * correction is necessary since energy_of_struct_par() will forget * about the existance of gquadruplexes and just treat them as unpaired * regions. * * recursive variant */ PRIVATE int en_corr_of_loop_gquad(vrna_fold_compound_t *vc, int i, int j, const char *structure, const short *pt, vrna_cstr_t output_stream, int verbosity_level) { char *sequence; int pos, tmp_e, energy, p, q, r, s, u, type, type2, L, l[3], *rtype, *loop_idx; int num_elem, num_g, elem_i, elem_j, up_mis; short *s1, *s2; vrna_param_t *P; vrna_md_t *md; sequence = vc->sequence; loop_idx = vrna_loopidx_from_ptable(pt); s1 = vc->sequence_encoding; s2 = vc->sequence_encoding2; P = vc->params; md = &(P->model_details); rtype = &(md->rtype[0]); energy = 0; q = i; while ((pos = parse_gquad(structure + q - 1, &L, l)) > 0) { q += pos - 1; p = q - 4 * L - l[0] - l[1] - l[2] + 1; if (q > j) break; /* we've found the first g-quadruplex at position [p,q] */ tmp_e = E_gquad(L, l, P); energy += tmp_e; if (verbosity_level > 0) vrna_cstr_print_eval_gquad(output_stream, p, L, l, tmp_e); /* check if it's enclosed in a base pair */ if (loop_idx[p] == 0) { q++; continue; /* g-quad in exterior loop */ } else { /* find its enclosing pair */ num_elem = 0; num_g = 1; r = p - 1; up_mis = q - p + 1; /* seek for first pairing base located 5' of the g-quad */ for (r = p - 1;!pt[r] && (r >= i); r--); if (r < pt[r]) { /* found the enclosing pair */ s = pt[r]; } else { num_elem++; elem_i = pt[r]; elem_j = r; r = pt[r] - 1; /* seek for next pairing base 5' of r */ for (;!pt[r] && (r >= i); r--); if (r < pt[r]) { /* found the enclosing pair */ s = pt[r]; } else { /* hop over stems and unpaired nucleotides */ while ((r > pt[r]) && (r >= i)) { if (pt[r]) { r = pt[r]; num_elem++; } r--; } s = pt[r]; /* found the enclosing pair */ } } /* now we have the enclosing pair (r,s) */ u = q + 1; /* we know everything about the 5' part of this loop so check the 3' part */ while (u < s) { if (structure[u - 1] == '.') { u++; } else if (structure[u - 1] == '+') { /* found another gquad */ pos = parse_gquad(structure + u - 1, &L, l); if (pos > 0) { tmp_e = E_gquad(L, l, P); if (verbosity_level > 0) vrna_cstr_print_eval_gquad(output_stream, pos, L, l, tmp_e); energy += tmp_e; up_mis += pos; u += pos; num_g++; } } else { /* we must have found a stem */ num_elem++; elem_i = u; elem_j = pt[u]; energy += en_corr_of_loop_gquad(vc, u, pt[u], structure, pt, output_stream, verbosity_level); u = pt[u] + 1; } } /* here, u == s */ int e_minus, e_plus; e_plus = e_minus = 0; /* we are done since we've found no other 3' structure element */ switch (num_elem) { /* g-quad was misinterpreted as hairpin closed by (r,s) */ case 0: e_minus = vrna_eval_hp_loop(vc, r, s); if (verbosity_level > 0) { vrna_cstr_print_eval_hp_loop_revert(output_stream, r, s, sequence[r - 1], sequence[s - 1], e_minus); } type = md->pair[s2[r]][s2[s]]; /* if we consider the G-Quadruplex, we have */ if (num_g == 1) { /* a) an interior loop like structure */ if (dangles == 2) e_plus += P->mismatchI[type][s1[r + 1]][s1[s - 1]]; if (type > 2) e_plus += P->TerminalAU; e_plus += P->internal_loop[s - r - 1 - up_mis]; if (verbosity_level > 0) { vrna_cstr_print_eval_int_loop(output_stream, r, s, sequence[r - 1], sequence[s - 1], p, q, sequence[p - 1], sequence[q - 1], e_plus); } } else { /* or b) a multibranch loop like structure */ e_plus = P->MLclosing + E_MLstem(rtype[type], s1[s - 1], s1[r + 1], P) + num_g * E_MLstem(0, -1, -1, P) + (s - r - 1 - up_mis) * P->MLbase; if (verbosity_level > 0) { vrna_cstr_print_eval_mb_loop(output_stream, r, s, sequence[r - 1], sequence[s - 1], e_plus); } } energy += e_plus - e_minus; break; /* g-quad was misinterpreted as interior loop closed by (r,s) with enclosed pair (elem_i, elem_j) */ case 1: type = md->pair[s2[r]][s2[s]]; type2 = md->pair[s2[elem_i]][s2[elem_j]]; e_plus = P->MLclosing + E_MLstem(rtype[type], s1[s - 1], s1[r + 1], P) + (elem_i - r - 1 + s - elem_j - 1 - up_mis) * P->MLbase + E_MLstem(type2, s1[elem_i - 1], s1[elem_j + 1], P); e_plus += num_g * E_MLstem(0, -1, -1, P); e_minus = vrna_eval_int_loop(vc, r, s, elem_i, elem_j); energy += e_plus - e_minus; if (verbosity_level > 0) { vrna_cstr_print_eval_int_loop_revert(output_stream, r, s, sequence[r - 1], sequence[j - 1], elem_i, elem_j, sequence[elem_i - 1], sequence[elem_j - 1], e_minus); vrna_cstr_print_eval_mb_loop(output_stream, r, s, sequence[r - 1], sequence[s - 1], e_plus); } break; /* gquad was misinterpreted as unpaired nucleotides in a multiloop */ default: e_minus = (up_mis) * P->MLbase; e_plus = num_g * E_MLstem(0, -1, -1, P); energy += e_plus - e_minus; if (verbosity_level > 0) { vrna_cstr_print_eval_mb_loop_revert(output_stream, r, s, sequence[r - 1], sequence[s - 1], e_minus); vrna_cstr_print_eval_mb_loop(output_stream, r, s, sequence[r - 1], sequence[s - 1], e_plus); } break; } q = s + 1; } } free(loop_idx); return energy; } #ifndef MULTISTRAND_EVAL PRIVATE int eval_hp_loop_fake(vrna_fold_compound_t *fc, int i, int j) { short *S, *S2; unsigned int *sn; int u, e, ij, type, *idx, en, noGUclosure; vrna_param_t *P; vrna_sc_t *sc; vrna_md_t *md; vrna_ud_t *domains_up; idx = fc->jindx; P = fc->params; md = &(P->model_details); noGUclosure = md->noGUclosure; sn = fc->strand_number; domains_up = fc->domains_up; e = INF; switch (fc->type) { /* single sequences and cofolding hybrids */ case VRNA_FC_TYPE_SINGLE: S = fc->sequence_encoding; S2 = fc->sequence_encoding2; sc = fc->sc; u = j - i - 1; ij = idx[j] + i; type = vrna_get_ptype_md(S2[j], S2[i], md); if (noGUclosure && ((type == 3) || (type == 4))) break; /* hairpin-like exterior loop (for cofolding) */ short si, sj; si = (sn[i + 1] == sn[i])? S[i + 1] : -1; sj = (sn[j] == sn[j - 1])? S[j - 1] : -1; if (md->dangles) e = vrna_E_ext_stem(type, sj, si, P); else e = vrna_E_ext_stem(type, -1, -1, P); /* add soft constraints */ if (sc) { if (sc->energy_up) e += sc->energy_up[i + 1][u]; if (sc->energy_bp) e += sc->energy_bp[ij]; if (sc->f) e += sc->f(i, j, i, j, VRNA_DECOMP_PAIR_HP, sc->data); } /* consider possible ligand binding */ if (domains_up && domains_up->energy_cb) { en = domains_up->energy_cb(fc, i + 1, j - 1, VRNA_UNSTRUCTURED_DOMAIN_HP_LOOP, domains_up->data); if (en!= INF) en += e; e = MIN2(e, en); } break; /* nothing */ default: break; } return e; } #endif #ifdef MULTISTRAND_EVAL /* * returns first base pairing partner * after the last strand nick in the loop * enclosed by (i,j). */ PRIVATE int first_pair_after_last_nick(unsigned int i, unsigned int j, const short *pt, unsigned int *sn) { unsigned int p, r, first_strand, last_strand; first_strand = sn[i]; last_strand = sn[j]; p = j; if (first_strand!= last_strand) { /* go backwards from j to first strand nick */ for (r = j - 1; r > i; r--) { if (sn[r]!= last_strand) break; if (pt[r]!= 0) { /* hop over base pair and store 5' pairing partner */ r = p = pt[r]; last_strand = sn[p]; } } } return (last_strand == first_strand)? 0 : p; } #endif PRIVATE int stack_energy(vrna_fold_compound_t *vc, int i, const short *pt, vrna_cstr_t output_stream, int verbosity_level) { /* recursively calculate energy of substructure enclosed by (i,j) */ unsigned int *sn; int ee, energy, j, p, q; char *string; short *s; vrna_param_t *P; vrna_md_t *md; sn = vc->strand_number; s = vc->sequence_encoding2; P = vc->params; md = &(P->model_details); energy = 0; j = pt[i]; if (vc->type == VRNA_FC_TYPE_SINGLE) { string = vc->sequence; if (md->pair[s[i]][s[j]] == 0) { if (verbosity_level > VRNA_VERBOSITY_QUIET) { vrna_message_warning("bases %d and %d (%c%c) can't pair!", i, j, string[i - 1], string[j - 1]); } } } else if (vc->type == VRNA_FC_TYPE_COMPARATIVE) { string = vc->cons_seq; } else { return INF; } p = i; q = j; while (p < q) { /* process all stacks and interior loops */ while (pt[++p] == 0); while (pt[--q] == 0); if ((pt[q]!= (short)p) || (p > q)) break; #ifdef MULTISTRAND_EVAL if ((sn[i] == sn[p]) && (sn[q] == sn[j])) { if (vc->type == VRNA_FC_TYPE_SINGLE) { if (md->pair[s[q]][s[p]] == 0) { if (verbosity_level > VRNA_VERBOSITY_QUIET) { vrna_message_warning("bases %d and %d (%c%c) can't pair!", p, q, string[p - 1], string[q - 1]); } } } ee = vrna_eval_int_loop(vc, i, j, p, q); if (verbosity_level > 0) { vrna_cstr_print_eval_int_loop(output_stream, i, j, string[i - 1], string[j - 1], p, q, string[p - 1], string[q - 1], (vc->type == VRNA_FC_TYPE_COMPARATIVE)? (int)ee / (int)vc->n_seq : ee); } energy += ee; i = p; j = q; } else { return energy; } #else ee = 0; if (vc->type == VRNA_FC_TYPE_SINGLE) { if (md->pair[s[q]][s[p]] == 0) { if (verbosity_level > VRNA_VERBOSITY_QUIET) { vrna_message_warning("bases %d and %d (%c%c) can't pair!", p, q, string[p - 1], string[q - 1]); } } } ee = vrna_eval_int_loop(vc, i, j, p, q); if (verbosity_level > 0) { vrna_cstr_print_eval_int_loop(output_stream, i, j, string[i - 1], string[j - 1], p, q, string[p - 1], string[q - 1], (vc->type == VRNA_FC_TYPE_COMPARATIVE)? (int)ee / (int)vc->n_seq : ee); } energy = ADD_OR_INF(energy, ee); i = p; j = q; #endif } /* end while */ /* p,q don't pair must have found hairpin or multiloop */ if (p > q) { /* hairpin */ #ifdef MULTISTRAND_EVAL if (sn[i] == sn[j]) { ee = vrna_eval_hp_loop(vc, i, j); if (verbosity_level > 0) { vrna_cstr_print_eval_hp_loop(output_stream, i, j, string[i - 1], string[j - 1], (vc->type == VRNA_FC_TYPE_COMPARATIVE)? (int)ee / (int)vc->n_seq : ee); } energy += ee; } #else if (sn[j]!= sn[i]) ee = eval_hp_loop_fake(vc, i, j); else ee = vrna_eval_hp_loop(vc, i, j); energy = ADD_OR_INF(energy, ee); if (verbosity_level > 0) { vrna_cstr_print_eval_hp_loop(output_stream, i, j, string[i - 1], string[j - 1], (vc->type == VRNA_FC_TYPE_COMPARATIVE)? (int)ee / (int)vc->n_seq : ee); } #endif return energy; } /* (i,j) is exterior pair of multiloop or external loop */ #ifdef MULTISTRAND_EVAL if (!first_pair_after_last_nick(i, j, pt, sn)) { while (p < j) { /* add up the contributions of the substructures of the ML */ energy += stack_energy(vc, p, pt, output_stream, verbosity_level); p = pt[p]; /* search for next base pair in multiloop */ while (pt[++p] == 0); } ee = energy_of_ml_pt(vc, i, pt); if (verbosity_level > 0) { vrna_cstr_print_eval_mb_loop(output_stream, i, j, string[i - 1], string[j - 1], (vc->type == VRNA_FC_TYPE_COMPARATIVE)? (int)ee / (int)vc->n_seq : ee); } energy += ee; } else { return energy; } #else while (p < j) { /* add up the contributions of the substructures of the ML */ ee = stack_energy(vc, p, pt, output_stream, verbosity_level); energy = ADD_OR_INF(energy, ee); p = pt[p]; /* search for next base pair in multiloop */ while (pt[++p] == 0); } ee = 0; switch (vc->type) { case VRNA_FC_TYPE_SINGLE: { int ii = cut_in_loop(i, pt, sn); ee = (ii == 0)? energy_of_ml_pt(vc, i, pt) : energy_of_extLoop_pt(vc, ii, pt); } break; case VRNA_FC_TYPE_COMPARATIVE: ee = energy_of_ml_pt(vc, i, pt); break; } energy = ADD_OR_INF(energy, ee); if (verbosity_level > 0) { vrna_cstr_print_eval_mb_loop(output_stream, i, j, string[i - 1], string[j - 1], (vc->type == VRNA_FC_TYPE_COMPARATIVE)? (int)ee / (int)vc->n_seq : ee); } #endif return energy; } /*---------------------------------------------------------------------------*/ #ifndef MULTISTRAND_EVAL /** *** Calculate the energy contribution of *** stabilizing dangling-ends/mismatches *** for all stems branching off the exterior *** loop **/ PRIVATE int energy_of_extLoop_pt(vrna_fold_compound_t *vc, int i, const short *pt) { unsigned int *sn; int energy, mm5, mm3, bonus, p, q, q_prev, length, dangle_model, n_seq, ss, u, start; short *s, *s1, **S, **S5, **S3; unsigned int **a2s; vrna_param_t *P; vrna_md_t *md; vrna_sc_t *sc, **scs; /* helper variables for dangles == 1 case */ int E3_available; /* energy of 5' part where 5' mismatch is available for current stem */ int E3_occupied; /* energy of 5' part where 5' mismatch is unavailable for current stem */ /* initialize vars */ length = vc->length; sn = vc->strand_number; P = vc->params; md = &(P->model_details); dangle_model = md->dangles; s = (vc->type == VRNA_FC_TYPE_SINGLE)? vc->sequence_encoding2 : NULL; s1 = (vc->type == VRNA_FC_TYPE_SINGLE)? vc->sequence_encoding : NULL; sc = (vc->type == VRNA_FC_TYPE_SINGLE)? vc->sc : NULL; S = (vc->type == VRNA_FC_TYPE_SINGLE)? NULL : vc->S; S5 = (vc->type == VRNA_FC_TYPE_SINGLE)? NULL : vc->S5; S3 = (vc->type == VRNA_FC_TYPE_SINGLE)? NULL : vc->S3; a2s = (vc->type == VRNA_FC_TYPE_SINGLE)? NULL : vc->a2s; n_seq = (vc->type == VRNA_FC_TYPE_SINGLE)? 1 : vc->n_seq; scs = (vc->type == VRNA_FC_TYPE_SINGLE)? NULL : vc->scs; energy = 0; bonus = 0; p = start = (i == 0)? 1 : i; q_prev = -1; if (dangle_model % 2 == 1) { E3_available = INF; E3_occupied = 0; } /* seek to opening (or closing) base of first stem */ while (p <= length &&!pt[p]) p++; switch (vc->type) { case VRNA_FC_TYPE_SINGLE: /* add soft constraints for first unpaired nucleotides */ if (sc) { if (sc->energy_up) bonus += sc->energy_up[start][p - start]; /* how do we handle generalized soft constraints here? */ } break; case VRNA_FC_TYPE_COMPARATIVE: /* add soft constraints for first unpaired nucleotides */ if (scs) { for (ss = 0; ss < n_seq; ss++) { if (scs[ss]) { if (scs[ss]->energy_up) { u = a2s[ss][p] - a2s[ss][start]; bonus += scs[ss]->energy_up[a2s[ss][start]][u]; } /* how do we handle generalized soft constraints here? */ } } } break; default: return INF; break; } while (p < length) { int tt; /* p must have a pairing partner */ q = (int)pt[p]; switch (vc->type) { case VRNA_FC_TYPE_SINGLE: /* get type of base pair (p,q) */ tt = vrna_get_ptype_md(s[p], s[q], md); switch (dangle_model) { /* no dangles */ case 0: energy += vrna_E_ext_stem(tt, -1, -1, P); break; /* the beloved double dangles */ case 2: mm5 = ((sn[p - 1] == sn[p]) && (p > 1)) ? s1[p - 1] : -1; mm3 = ((sn[q] == sn[q + 1]) && (q < length)) ? s1[q + 1] : -1; energy += vrna_E_ext_stem(tt, mm5, mm3, P); break; default: { int tmp; if (q_prev + 2 < p) { E3_available = MIN2(E3_available, E3_occupied); E3_occupied = E3_available; } mm5 = ((sn[p - 1] == sn[p]) && (p > 1) &&!pt[p - 1]) ? s1[p - 1] : -1; mm3 = ((sn[q] == sn[q + 1]) && (q < length) &&!pt[q + 1]) ? s1[q + 1] : -1; tmp = MIN2( E3_occupied + vrna_E_ext_stem(tt, -1, mm3, P), E3_available + vrna_E_ext_stem(tt, mm5, mm3, P) ); E3_available = MIN2( E3_occupied + vrna_E_ext_stem(tt, -1, -1, P), E3_available + vrna_E_ext_stem(tt, mm5, -1, P) ); E3_occupied = tmp; } break; } /* end switch dangle_model */ break; case VRNA_FC_TYPE_COMPARATIVE: for (ss = 0; ss < n_seq; ss++) { /* get type of base pair (p,q) */ tt = vrna_get_ptype_md(S[ss][p], S[ss][q], md); switch (dangle_model) { case 0: energy += vrna_E_ext_stem(tt, -1, -1, P); break; case 2: mm5 = (a2s[ss][p] > 1)? S5[ss][p] : -1; mm3 = (a2s[ss][q] < a2s[ss][length])? S3[ss][q] : -1; energy += vrna_E_ext_stem(tt, mm5, mm3, P); break; default: break; /* odd dangles not implemented yet */ } } break; default: break; /* this should never happen */ } /* seek to the next stem */ p = q + 1; q_prev = q; while (p <= length &&!pt[p]) p++; switch (vc->type) { case VRNA_FC_TYPE_SINGLE: /* add soft constraints for unpaired region */ if (sc && (q_prev + 1 <= length)) { if (sc->energy_up) bonus += sc->energy_up[q_prev + 1][p - q_prev - 1]; /* how do we handle generalized soft constraints here? */ } break; case VRNA_FC_TYPE_COMPARATIVE: if (scs) { for (ss = 0; ss < n_seq; ss++) { if (scs[ss]) { if (scs[ss]->energy_up) { u = a2s[ss][p] - a2s[ss][q_prev + 1]; bonus += scs[ss]->energy_up[a2s[ss][q_prev + 1]][u]; } } } } break; default: break; /* this should never happen */ } if (p == i) break; /* cut was in loop */ } if (dangle_model % 2 == 1) energy = MIN2(E3_occupied, E3_available); return energy + bonus; } #endif /** *** i is the 5'-base of the closing pair *** *** since each helix can coaxially stack with at most one of its *** neighbors we need an auxiliarry variable cx_energy *** which contains the best energy given that the last two pairs stack. *** energy holds the best energy given the previous two pairs do not *** stack (i.e. the two current helices may stack) *** We don't allow the last helix to stack with the first, thus we have to *** walk around the Loop twice with two starting points and take the minimum ***/ PRIVATE int energy_of_ml_pt(vrna_fold_compound_t *vc, int i, const short *pt) { unsigned int *sn; int energy, cx_energy, tmp, tmp2, best_energy = INF, bonus, *idx, dangle_model, logML, circular, *rtype, ss, n, n_seq; int i1, j, p, q, q_prev, q_prev2, u, uu, x, type, count, mm5, mm3, tt, ld5, new_cx, dang5, dang3, dang; int e_stem, e_stem5, e_stem3, e_stem53; int mlintern[NBPAIRS + 1]; short *s, *s1, **S, **S5, **S3; unsigned int **a2s; vrna_param_t *P; vrna_md_t *md; vrna_sc_t *sc, **scs; /* helper variables for dangles == 1|5 case */ int E_mm5_available; /* energy of 5' part where 5' mismatch of current stem is available */ int E_mm5_occupied; /* energy of 5' part where 5' mismatch of current stem is unavailable */ int E2_mm5_available; /* energy of 5' part where 5' mismatch of current stem is available with possible 3' dangle for enclosing pair (i,j) */ int E2_mm5_occupied; /* energy of 5' part where 5' mismatch of current stem is unavailable with possible 3' dangle for enclosing pair (i,j) */ n = vc->length; sn = vc->strand_number; P = vc->params; md = &(P->model_details); idx = vc->jindx; circular = md->circ; dangle_model = md->dangles; logML = md->logML; rtype = &(md->rtype[0]); s = (vc->type == VRNA_FC_TYPE_SINGLE)? vc->sequence_encoding2 : NULL; s1 = (vc->type == VRNA_FC_TYPE_SINGLE)? vc->sequence_encoding : NULL; sc = (vc->type == VRNA_FC_TYPE_SINGLE)? vc->sc : NULL; S = (vc->type == VRNA_FC_TYPE_SINGLE)? NULL : vc->S; S5 = (vc->type == VRNA_FC_TYPE_SINGLE)? NULL : vc->S5; S3 = (vc->type == VRNA_FC_TYPE_SINGLE)? NULL : vc->S3; a2s = (vc->type == VRNA_FC_TYPE_SINGLE)? NULL : vc->a2s; n_seq = (vc->type == VRNA_FC_TYPE_SINGLE)? 1 : vc->n_seq; scs = (vc->type == VRNA_FC_TYPE_SINGLE)? NULL : vc->scs; bonus = 0; if (i >= pt[i]) { vrna_message_warning("energy_of_ml_pt: i is not 5' base of a closing pair!"); return INF; } j = (i == 0)? n + 1 : (int)pt[i]; switch (vc->type) { case VRNA_FC_TYPE_SINGLE: if (i!= 0) { /* (i,j) is closing pair of multibranch loop, add soft constraints */ if (sc) if (sc->energy_bp) bonus += sc->energy_bp[idx[j] + i]; } break; case VRNA_FC_TYPE_COMPARATIVE: if ((dangle_model % 2) || (dangle_model > 2) || (dangle_model < 0)) { vrna_message_warning( "consensus structure evaluation for odd dangle models not implemented (yet)!"); return INF; } if (i!= 0) { /* (i,j) is closing pair of multibranch loop, add soft constraints */ if (scs) { for (ss = 0; ss < n_seq; ss++) if (scs[ss] && scs[ss]->energy_bp) bonus += scs[ss]->energy_bp[idx[j] + i]; } } break; default: return INF; break; } /* init the variables */ energy = 0; u = 0; /* the total number of unpaired nucleotides */ p = i + 1; q_prev = i - 1; q_prev2 = i; for (x = 0; x <= NBPAIRS; x++) mlintern[x] = P->MLintern[x]; /* seek to opening base of first stem */ while (p <= j &&!pt[p]) p++; /* add bonus energies for first stretch of unpaired nucleotides */ switch (vc->type) { case VRNA_FC_TYPE_SINGLE: u += p - i - 1; if (sc) if (sc->energy_up) bonus += sc->energy_up[i + 1][u]; break; case VRNA_FC_TYPE_COMPARATIVE: if (scs) { for (ss = 0; ss < n_seq; ss++) { uu = a2s[ss][p] - a2s[ss][i + 1]; if (scs[ss] && scs[ss]->energy_up) bonus += scs[ss]->energy_up[a2s[ss][i + 1]][uu]; u += uu; } } else { for (ss = 0; ss < n_seq; ss++) u += a2s[ss][p] - a2s[ss][i + 1]; } break; default: break; /* this should never happen */ } switch (dangle_model) { case 0: switch (vc->type) { case VRNA_FC_TYPE_SINGLE: while (p < j) { /* p must have a pairing partner */ q = (int)pt[p]; /* get type of base pair (p,q) */ tt = vrna_get_ptype_md(s[p], s[q], md); energy += E_MLstem(tt, -1, -1, P); /* seek to the next stem */ p = q + 1; q_prev = q_prev2 = q; while (p < j &&!pt[p]) p++; u += p - q - 1; /* add unpaired nucleotides */ if (sc) if (sc->energy_up) bonus += sc->energy_up[q + 1][p - q - 1]; } /* now lets get the energy of the enclosing stem */ if (i > 0) { /* actual closing pair */ tt = vrna_get_ptype_md(s[j], s[i], md); energy += E_MLstem(tt, -1, -1, P); } else { /* virtual closing pair */ energy += E_MLstem(0, -1, -1, P); } break; case VRNA_FC_TYPE_COMPARATIVE: while (p < j) { /* p must have a pairing partner */ q = (int)pt[p]; for (ss = 0; ss < n_seq; ss++) { /* get type of base pair (p,q) */ tt = vrna_get_ptype_md(S[ss][p], S[ss][q], md); energy += E_MLstem(tt, -1, -1, P); } /* seek to the next stem */ p = q + 1; q_prev = q_prev2 = q; while (p < j &&!pt[p]) p++; /* add unpaired nucleotides and possible soft constraints */ if (scs) { for (ss = 0; ss < n_seq; ss++) { uu = a2s[ss][p] - a2s[ss][q + 1]; if (scs[ss] && scs[ss]->energy_up) bonus += sc->energy_up[a2s[ss][q + 1]][uu]; u += uu; } } else { for (ss = 0; ss < n_seq; ss++) u += a2s[ss][p] - a2s[ss][q + 1]; } } /* now lets get the energy of the enclosing stem */ if (i > 0) { /* actual closing pair */ for (ss = 0; ss < n_seq; ss++) { tt = vrna_get_ptype_md(S[ss][j], S[ss][i], md); energy += E_MLstem(tt, -1, -1, P); } } break; default: break; /* this should never happen */ } break; case 2: switch (vc->type) { case VRNA_FC_TYPE_SINGLE: while (p < j) { /* p must have a pairing partner */ q = (int)pt[p]; /* get type of base pair (p,q) */ tt = vrna_get_ptype_md(s[p], s[q], md); mm5 = sn[p - 1] == sn[p]? s1[p - 1] : -1; mm3 = sn[q] == sn[q + 1]? s1[q + 1] : -1; energy += E_MLstem(tt, mm5, mm3, P); /* seek to the next stem */ p = q + 1; q_prev = q_prev2 = q; while (p < j &&!pt[p]) p++; u += p - q - 1; /* add unpaired nucleotides */ if (sc) if (sc->energy_up) bonus += sc->energy_up[q + 1][p - q - 1]; } if (i > 0) { /* actual closing pair */ tt = vrna_get_ptype_md(s[j], s[i], md); mm5 = sn[j - 1] == sn[j]? s1[j - 1] : -1; mm3 = sn[i] == sn[i + 1]? s1[i + 1] : -1; energy += E_MLstem(tt, mm5, mm3, P); } else { /* virtual closing pair */ energy += E_MLstem(0, -1, -1, P); } break; case VRNA_FC_TYPE_COMPARATIVE: while (p < j) { /* p must have a pairing partner */ q = (int)pt[p]; for (ss = 0; ss < n_seq; ss++) { /* get type of base pair (p,q) */ tt = vrna_get_ptype_md(S[ss][p], S[ss][q], md); mm5 = ((a2s[ss][p] > 1) || circular)? S5[ss][p] : -1; mm3 = ((a2s[ss][q] < a2s[ss][n]) || circular)? S3[ss][q] : -1; energy += E_MLstem(tt, mm5, mm3, P); } /* seek to the next stem */ p = q + 1; q_prev = q_prev2 = q; while (p < j &&!pt[p]) p++; /* add unpaired nucleotides and possible soft constraints */ if (scs) { for (ss = 0; ss < n_seq; ss++) { uu = a2s[ss][p] - a2s[ss][q + 1]; if (scs[ss] && scs[ss]->energy_up) bonus += sc->energy_up[a2s[ss][q + 1]][uu]; u += uu; } } else { for (ss = 0; ss < n_seq; ss++) u += a2s[ss][p] - a2s[ss][q + 1]; } } if (i > 0) { /* actual closing pair */ for (ss = 0; ss < n_seq; ss++) { tt = vrna_get_ptype_md(S[ss][j], S[ss][i], md); mm5 = S5[ss][j]; mm3 = S3[ss][i]; energy += E_MLstem(tt, mm5, mm3, P); } } break; default: break; /* this should never happen */ } break; case 3: /* we treat helix stacking different */ for (count = 0; count < 2; count++) { /* do it twice */ ld5 = 0; /* 5' dangle energy on prev pair (type) */ if (i == 0) { j = (unsigned int)pt[0] + 1; type = 0; /* no pair */ } else { j = (unsigned int)pt[i]; type = vrna_get_ptype_md(s[j], s[i], md); /* prime the ld5 variable */ if (sn[j - 1] == sn[j]) { ld5 = P->dangle5[type][s1[j - 1]]; if ((p = (unsigned int)pt[j - 2]) && (sn[j - 2] == sn[j - 1])) if (P->dangle3[md->pair[s[p]][s[j - 2]]][s1[j - 1]] < ld5) ld5 = 0; } } i1 = i; p = i + 1; u = 0; energy = 0; cx_energy = INF; do { /* walk around the multi-loop */ new_cx = INF; /* hop over unpaired positions */ while (p <= (unsigned int)pt[0] && pt[p] == 0) p++; /* memorize number of unpaired positions */ u += p - i1 - 1; if (sc) if (sc->energy_up) bonus += sc->energy_up[i1 + 1][p - i1 - 1]; /* get position of pairing partner */ if (p == (unsigned int)pt[0] + 1) { q = 0; tt = 0; /* virtual root pair */ } else { q = (unsigned int)pt[p]; /* get type of base pair P->q */ tt = vrna_get_ptype_md(s[p], s[q], md); } energy += mlintern[tt]; cx_energy += mlintern[tt]; dang5 = dang3 = 0; if ((sn[p - 1] == sn[p]) && (p > 1)) dang5 = P->dangle5[tt][s1[p - 1]]; /* 5'dangle of pq pair */ if ((sn[i1] == sn[i1 + 1]) && (i1 < (unsigned int)s[0])) dang3 = P->dangle3[type][s1[i1 + 1]]; /* 3'dangle of previous pair */ switch (p - i1 - 1) { case 0: /* adjacent helices */ if (i1!= 0) { if (sn[i1] == sn[p]) { new_cx = energy + P->stack[rtype[type]][rtype[tt]]; /* subtract 5'dangle and TerminalAU penalty */ new_cx += -ld5 - mlintern[tt] - mlintern[type] + 2 * mlintern[1]; } ld5 = 0; energy = MIN2(energy, cx_energy); } break; case 1: /* 1 unpaired base between helices */ dang = MIN2(dang3, dang5); energy = energy + dang; ld5 = dang - dang3; /* may be problem here: Suppose * cx_energy>energy, cx_energy+dang5<energy * and the following helices are also stacked (i.e. * we'll subtract the dang5 again */ if (cx_energy + dang5 < energy) { energy = cx_energy + dang5; ld5 = dang5; } new_cx = INF; /* no coax stacking with mismatch for now */ break; default: /* many unpaired base between helices */ energy += dang5 + dang3; energy = MIN2(energy, cx_energy + dang5); new_cx = INF; /* no coax stacking possible */ ld5 = dang5; break; } type = tt; cx_energy = new_cx; i1 = q; p = q + 1; } while (q!= i); best_energy = MIN2(energy, best_energy); /* don't use cx_energy here */ /* skip a helix and start again */ while (pt[p] == 0) p++; if (i == (unsigned int)pt[p]) break; i = (unsigned int)pt[p]; } /* end doing it twice */ energy = best_energy; break; default: E_mm5_available = E2_mm5_available = INF; E_mm5_occupied = E2_mm5_occupied = 0; while (p < j) { /* p must have a pairing partner */ q = (int)pt[p]; /* get type of base pair (p,q) */ tt = vrna_get_ptype_md(s[p], s[q], md); if (q_prev + 2 < p) { E_mm5_available = MIN2(E_mm5_available, E_mm5_occupied); E_mm5_occupied = E_mm5_available; } if (q_prev2 + 2 < p) { E2_mm5_available = MIN2(E2_mm5_available, E2_mm5_occupied); E2_mm5_occupied = E2_mm5_available; } mm5 = ((sn[p - 1] == sn[p]) &&!pt[p - 1]) ? s1[p - 1] : -1; mm3 = ((sn[q] == sn[q + 1]) &&!pt[q + 1]) ? s1[q + 1] : -1; e_stem = E_MLstem(tt, -1, -1, P); e_stem5 = E_MLstem(tt, mm5, -1, P); e_stem3 = E_MLstem(tt, -1, mm3, P); e_stem53 = E_MLstem(tt, mm5, mm3, P); tmp = E_mm5_occupied + e_stem3; tmp = MIN2(tmp, E_mm5_available + e_stem53); tmp = MIN2(tmp, E_mm5_available + e_stem3); tmp2 = E_mm5_occupied + e_stem; tmp2 = MIN2(tmp2, E_mm5_available + e_stem5); tmp2 = MIN2(tmp2, E_mm5_available + e_stem); E_mm5_occupied = tmp; E_mm5_available = tmp2; tmp = E2_mm5_occupied + e_stem3; tmp = MIN2(tmp, E2_mm5_available + e_stem53); tmp = MIN2(tmp, E2_mm5_available + e_stem3); tmp2 = E2_mm5_occupied + e_stem; tmp2 = MIN2(tmp2, E2_mm5_available + e_stem5); tmp2 = MIN2(tmp2, E2_mm5_available + e_stem); E2_mm5_occupied = tmp; E2_mm5_available = tmp2; /* seek to the next stem */ p = q + 1; q_prev = q_prev2 = q; while (p < j &&!pt[p]) p++; u += p - q - 1; /* add unpaired nucleotides */ if (sc) if (sc->energy_up) bonus += sc->energy_up[q + 1][p - q - 1]; } if (i > 0) { /* actual closing pair */ type = vrna_get_ptype_md(s[j], s[i], md); mm5 = ((sn[j - 1] == sn[j]) &&!pt[j - 1]) ? s1[j - 1] : -1; mm3 = ((sn[i] == sn[i + 1]) &&!pt[i + 1]) ? s1[i + 1] : -1; if (q_prev + 2 < p) { E_mm5_available = MIN2(E_mm5_available, E_mm5_occupied); E_mm5_occupied = E_mm5_available; } if (q_prev2 + 2 < p) { E2_mm5_available = MIN2(E2_mm5_available, E2_mm5_occupied); E2_mm5_occupied = E2_mm5_available; } e_stem = E_MLstem(type, -1, -1, P); e_stem5 = E_MLstem(type, mm5, -1, P); e_stem3 = E_MLstem(type, -1, mm3, P); e_stem53 = E_MLstem(type, mm5, mm3, P); } else { /* virtual closing pair */ e_stem = e_stem5 = e_stem3 = e_stem53 = E_MLstem(0, -1, -1, P); } /* now lets see how we get the minimum including the enclosing stem */ energy = E_mm5_occupied + e_stem; energy = MIN2(energy, E_mm5_available + e_stem5); energy = MIN2(energy, E_mm5_available + e_stem); energy = MIN2(energy, E2_mm5_occupied + e_stem3); energy = MIN2(energy, E2_mm5_occupied + e_stem); energy = MIN2(energy, E2_mm5_available + e_stem53); energy = MIN2(energy, E2_mm5_available + e_stem3); energy = MIN2(energy, E2_mm5_available + e_stem5); energy = MIN2(energy, E2_mm5_available + e_stem); break; }/* end switch dangle_model */ switch (vc->type) { case VRNA_FC_TYPE_SINGLE: energy += P->MLclosing; break; case VRNA_FC_TYPE_COMPARATIVE: energy += P->MLclosing * n_seq; break; default: break; } /* * logarithmic ML loop energy if logML * does this work for comparative predictions as well? */ if (logML && (u > 6)) energy += 6 * P->MLbase + (int)(P->lxc * log((double)u / 6.)); else energy += (u * P->MLbase); return energy + bonus; } #ifndef MULTISTRAND_EVAL PRIVATE int cut_in_loop(int i, const short *pt, unsigned int *sn) { /* walk around the loop; return 5' pos of first pair after cut if * cut_point in loop else 0 */ int p, j; p = j = pt[i]; do { i = pt[p]; p = i + 1; while (pt[p] == 0) p++; } while ((p!= j) && (sn[i] == sn[p])); return sn[i] == sn[p]? 0 : p; } #endif /* below are the consensus structure evaluation functions */ PRIVATE int covar_energy_of_struct_pt(vrna_fold_compound_t *vc, const short *pt) { int e = 0; int length = vc->length; int i; for (i = 1; i <= length; i++) { if (pt[i] == 0) continue; e += stack_energy_covar_pt(vc, i, pt); i = pt[i]; } return e; } PRIVATE int en_corr_of_loop_gquad_ali(vrna_fold_compound_t *vc, int i, int j, const char *structure, const short *pt, const int *loop_idx, vrna_cstr_t output_stream, int verbosity_level) { int pos, cnt, tmp_e, energy, p, q, r, s, u, type, gq_en[2]; int num_elem, num_g, elem_i, elem_j, up_mis; int L, l[3]; char *sequence = vc->cons_seq; short **S = vc->S; short **S5 = vc->S5; short **S3 = vc->S3; vrna_param_t *P = vc->params; vrna_md_t *md = &(P->model_details); int n_seq = vc->n_seq; int dangle_model = md->dangles; energy = 0; q = i; while ((pos = parse_gquad(structure + q - 1, &L, l)) > 0) { q += pos - 1; p = q - 4 * L - l[0] - l[1] - l[2] + 1; if (q > j) break; /* we've found the first g-quadruplex at position [p,q] */ E_gquad_ali_en(p, L, l, (const short **)S, vc->a2s, n_seq, P, gq_en); tmp_e = gq_en[0]; energy += tmp_e; if (verbosity_level > 0) { vrna_cstr_print_eval_gquad(output_stream, p, L, l, (int)tmp_e / (int)n_seq); } /* check if it's enclosed in a base pair */ if (loop_idx[p] == 0) { q++; continue; /* g-quad in exterior loop */ } else { /* find its enclosing pair */ num_elem = 0; num_g = 1; r = p - 1; up_mis = q - p + 1; /* seek for first pairing base located 5' of the g-quad */ for (r = p - 1;!pt[r] && (r >= i); r--); if (r < pt[r]) { /* found the enclosing pair */ s = pt[r]; } else { num_elem++; elem_i = pt[r]; elem_j = r; r = pt[r] - 1; /* seek for next pairing base 5' of r */ for (;!pt[r] && (r >= i); r--); if (r < pt[r]) { /* found the enclosing pair */ s = pt[r]; } else { /* hop over stems and unpaired nucleotides */ while ((r > pt[r]) && (r >= i)) { if (pt[r]) { r = pt[r]; num_elem++; } r--; } s = pt[r]; /* found the enclosing pair */ } } /* now we have the enclosing pair (r,s) */ u = q + 1; /* we know everything about the 5' part of this loop so check the 3' part */ while (u < s) { if (structure[u - 1] == '.') { u++; } else if (structure[u - 1] == '+') { /* found another gquad */ pos = parse_gquad(structure + u - 1, &L, l); if (pos > 0) { E_gquad_ali_en(u, L, l, (const short **)S, vc->a2s, n_seq, P, gq_en); if (verbosity_level > 0) { vrna_cstr_print_eval_gquad(output_stream, pos, L, l, (int)tmp_e / (int)n_seq); } tmp_e = gq_en[0]; energy += tmp_e; up_mis += pos; u += pos; num_g++; } } else { /* we must have found a stem */ num_elem++; elem_i = u; elem_j = pt[u]; energy += en_corr_of_loop_gquad_ali(vc, u, pt[u], structure, pt, loop_idx, output_stream, verbosity_level); u = pt[u] + 1; } } /* here, u == s */ int e_minus, e_plus, e_temp; e_plus = e_minus = 0; /* we are done since we've found no other 3' structure element */ switch (num_elem) { /* g-quad was misinterpreted as hairpin closed by (r,s) */ case 0: e_minus = vrna_eval_hp_loop(vc, r, s); if (verbosity_level > 0) { vrna_cstr_print_eval_hp_loop_revert(output_stream, r, s, sequence[r - 1], sequence[s - 1], (int)e_minus / (int)n_seq); } /* if we consider the G-Quadruplex, we have */ if (num_g == 1) { /* a) an interior loop like structure */ for (cnt = 0; cnt < n_seq; cnt++) { type = vrna_get_ptype_md(S[cnt][r], S[cnt][s], md); if (dangle_model == 2) e_plus += P->mismatchI[type][S3[cnt][r]][S5[cnt][s]]; if (type > 2) e_plus += P->TerminalAU; } e_plus += n_seq * P->internal_loop[s - r - 1 - up_mis]; if (verbosity_level > 0) { vrna_cstr_print_eval_int_loop(output_stream, r, s, sequence[r - 1], sequence[s - 1], p, q, sequence[p - 1], sequence[q - 1], (int)e_plus / (int)n_seq); } } else { /* or b) a multibranch loop like structure */ for (cnt = 0; cnt < n_seq; cnt++) { type = vrna_get_ptype_md(S[cnt][s], S[cnt][r], md); e_plus += E_MLstem(type, S5[cnt][s], S3[cnt][r], P); } e_temp = num_g * E_MLstem(0, -1, -1, P) + P->MLclosing + (elem_i - r - 1 + s - elem_j - 1 - up_mis) * P->MLbase; e_plus += n_seq * e_temp; if (verbosity_level > 0) { vrna_cstr_print_eval_mb_loop(output_stream, r, s, sequence[r - 1], sequence[s - 1], (int)e_plus / (int)n_seq); } } energy += e_plus - e_minus; break; /* g-quad was misinterpreted as interior loop closed by (r,s) with enclosed pair (elem_i, elem_j) */ case 1: e_minus = vrna_eval_int_loop(vc, r, s, elem_i, elem_j); for (cnt = 0; cnt < n_seq; cnt++) { type = vrna_get_ptype_md(S[cnt][s], S[cnt][r], md); e_plus += E_MLstem(type, S5[cnt][s], S3[cnt][r], P); type = vrna_get_ptype_md(S[cnt][elem_i], S[cnt][elem_j], md); e_plus += E_MLstem(type, S5[cnt][elem_i], S3[cnt][elem_j], P); } e_temp = num_g * E_MLstem(0, -1, -1, P) + P->MLclosing + (elem_i - r - 1 + s - elem_j - 1 - up_mis) * P->MLbase; e_plus += n_seq * e_temp; energy += e_plus - e_minus; if (verbosity_level > 0) { vrna_cstr_print_eval_int_loop_revert(output_stream, r, s, sequence[r - 1], sequence[j - 1], elem_i, elem_j, sequence[elem_i - 1], sequence[elem_j - 1], (int)e_minus / (int)n_seq); vrna_cstr_print_eval_mb_loop(output_stream, r, s, sequence[r - 1], sequence[s - 1], (int)e_plus / (int)n_seq); } break; /* gquad was misinterpreted as unpaired nucleotides in a multiloop */ default: e_minus = (up_mis) * P->MLbase * n_seq; e_plus = num_g * E_MLstem(0, -1, -1, P) * n_seq; energy += e_plus - e_minus; if (verbosity_level > 0) { vrna_cstr_print_eval_mb_loop_revert(output_stream, r, s, sequence[r - 1], sequence[s - 1], (int)e_minus / (int)n_seq); vrna_cstr_print_eval_mb_loop(output_stream, r, s, sequence[r - 1], sequence[s - 1], (int)e_plus / (int)n_seq); } break; } q = s + 1; } } return energy; } PRIVATE int covar_en_corr_of_loop_gquad(vrna_fold_compound_t *vc, int i, int j, const char *structure, const short *pt, const int *loop_idx) { int pos, en_covar, p, q, r, s, u, gq_en[2]; int num_elem, num_g, up_mis; int L, l[3]; short **S = vc->S; vrna_param_t *P = vc->params; int n_seq = vc->n_seq; en_covar = 0; q = i; while ((pos = parse_gquad(structure + q - 1, &L, l)) > 0) { q += pos - 1; p = q - 4 * L - l[0] - l[1] - l[2] + 1; if (q > j) break; /* we've found the first g-quadruplex at position [p,q] */ E_gquad_ali_en(p, L, l, (const short **)S, vc->a2s, n_seq, P, gq_en); en_covar += gq_en[1]; /* check if it's enclosed in a base pair */ if (loop_idx[p] == 0) { q++; continue; /* g-quad in exterior loop */ } else { /* find its enclosing pair */ num_elem = 0; num_g = 1; r = p - 1; up_mis = q - p + 1; /* seek for first pairing base located 5' of the g-quad */ for (r = p - 1;!pt[r] && (r >= i); r--); if (r < pt[r]) { /* found the enclosing pair */ s = pt[r]; } else { num_elem++; r = pt[r] - 1; /* seek for next pairing base 5' of r */ for (;!pt[r] && (r >= i); r--); if (r < pt[r]) { /* found the enclosing pair */ s = pt[r]; } else { /* hop over stems and unpaired nucleotides */ while ((r > pt[r]) && (r >= i)) { if (pt[r]) { r = pt[r]; num_elem++; } r--; } s = pt[r]; /* found the enclosing pair */ } } /* now we have the enclosing pair (r,s) */ u = q + 1; /* we know everything about the 5' part of this loop so check the 3' part */ while (u < s) { if (structure[u - 1] == '.') { u++; } else if (structure[u - 1] == '+') { /* found another gquad */ pos = parse_gquad(structure + u - 1, &L, l); if (pos > 0) { E_gquad_ali_en(u, L, l, (const short **)S, vc->a2s, n_seq, P, gq_en); en_covar += gq_en[1]; up_mis += pos; u += pos; num_g++; } } else { /* we must have found a stem */ num_elem++; en_covar += covar_en_corr_of_loop_gquad(vc, u, pt[u], structure, pt, loop_idx); u = pt[u] + 1; } } /* we are done since we've found no other 3' structure element */ q = s + 1; } } return en_covar; } PRIVATE int stack_energy_covar_pt(vrna_fold_compound_t *vc, int i, const short *pt) { /* calculate energy of substructure enclosed by (i,j) */ int *indx = vc->jindx; /* index for moving in the triangle matrices c[] and fMl[]*/ int *pscore = vc->pscore; /* precomputed array of pair types */ int energy = 0; int j, p, q; j = pt[i]; p = i; q = j; while (p < q) { /* process all stacks and interior loops */ while (pt[++p] == 0); while (pt[--q] == 0); if ((pt[q]!= (short)p) || (p > q)) break; energy += pscore[indx[j] + i]; i = p; j = q; } /* end while */ /* p,q don't pair must have found hairpin or multiloop */ if (p > q) { /* hairpin case */ energy += pscore[indx[j] + i]; return energy; } /* (i,j) is exterior pair of multiloop */ energy += pscore[indx[j] + i]; while (p < j) { /* add up the contributions of the substructures of the ML */ energy += stack_energy_covar_pt(vc, p, pt); p = pt[p]; /* search for next base pair in multiloop */ while (pt[++p] == 0); } return energy; } ======================= File: src/ViennaRNA/wrap_dlib.h ======================= #ifndef VIENNARNA_DLIB_WRAPPER_H #define VIENNARNA_DLIB_WRAPPER_H #ifdef __cplusplus extern "C" { #endif double * vrna_equilibrium_conc(const double *eq_constants, double *concentration_strands, const unsigned int **A, size_t num_strands, size_t num_complexes); #ifdef __cplusplus } #endif #endif ======================= File: src/ViennaRNA/boltzmann_sampling.h ======================= #ifndef VIENNA_RNA_PACKAGE_BOLTZMANN_SAMPLING_H #define VIENNA_RNA_PACKAGE_BOLTZMANN_SAMPLING_H /** * @file boltzmann_sampling.h * @ingroup subopt_and_representatives * @brief Boltzmann Sampling of secondary structures from the ensemble * * A.k.a. Stochastic backtracking */ /** * @addtogroup subopt_stochbt * @{ * @brief Functions to draw random structure samples from the ensemble according to their * equilibrium probability */ /** * @brief Boltzmann sampling flag indicating default backtracing mode * * @see vrna_pbacktrack5_num(), vrna_pbacktrack5_cb(), vrna_pbacktrack5_resume(), * vrna_pbacktrack5_resume_cb(), vrna_pbacktrack_num(), vrna_pbacktrack_cb(), * vrna_pbacktrack_resume(), vrna_pbacktrack_resume_cb() */ #define VRNA_PBACKTRACK_DEFAULT 0 /** * @brief Boltzmann sampling flag indicating non-redundant backtracing mode * * This flag will turn the Boltzmann sampling into non-redundant backtracing * mode along the lines of Michalik et al. 2017 @cite michalik:2017 * * @see vrna_pbacktrack5_num(), vrna_pbacktrack5_cb(), vrna_pbacktrack5_resume(), * vrna_pbacktrack5_resume_cb(), vrna_pbacktrack_num(), vrna_pbacktrack_cb(), * vrna_pbacktrack_resume(), vrna_pbacktrack_resume_cb() */ #define VRNA_PBACKTRACK_NON_REDUNDANT 1 /** * @brief Callback for Boltzmann sampling * * @callback * @parblock * This function will be called for each secondary structure that has been successfully backtraced * from the partition function DP matrices. * @endparblock * * @see vrna_pbacktrack5_cb(), vrna_pbacktrack_cb(), vrna_pbacktrack5_resume_cb(), * vrna_pbacktrack_resume_cb() * * @param structure The secondary structure in dot-bracket notation * @param data Some arbitrary, auxiliary data address as provided to the calling function */ typedef void (vrna_boltzmann_sampling_callback)(const char *stucture, void *data); /** * @brief Boltzmann sampling memory data structure * * This structure is required for properly resuming a previous sampling round in * specialized Boltzmann sampling, such as non-redundant backtracking. * * Initialize with @p NULL and pass its address to the corresponding * functions vrna_pbacktrack5_resume(), etc. * * @note Do not forget to release memory occupied by this data structure before * losing its context! Use vrna_pbacktrack_mem_free(). * * @see vrna_pbacktrack5_resume(), vrna_pbacktrack_resume(), vrna_pbacktrack5_resume_cb(), * vrna_pbacktrack_resume_cb(), vrna_pbacktrack_mem_free() */ typedef struct vrna_pbacktrack_memory_s *vrna_pbacktrack_mem_t; #include <ViennaRNA/fold_compound.h> /** * @brief Sample a secondary structure of a subsequence from the Boltzmann ensemble according its probability * * Perform a probabilistic (stochastic) backtracing in the partition function DP arrays * to obtain a secondary structure. The parameter @p length specifies the length * of the substructure starting from the 5' end. * * The structure @f$ s @f$ with free energy @f$ E(s) @f$ is picked from the Boltzmann distributed * ensemble according to its probability * @f[ * p(s) = \frac{exp(-E(s) / kT)}{Z} * @f] * with partition function @f$ Z = \sum_s exp(-E(s) / kT) @f$, Boltzmann constant @f$ k @f$ and * thermodynamic temperature @f$ T @f$. * * @pre Unique multiloop decomposition has to be active upon creation of @p fc with vrna_fold_compound() * or similar. This can be done easily by passing vrna_fold_compound() a model details parameter * with vrna_md_t.uniq_ML = 1. * @pre vrna_pf() has to be called first to fill the partition function matrices * * @note This function is polymorphic. It accepts #vrna_fold_compound_t of type * #VRNA_FC_TYPE_SINGLE, and #VRNA_FC_TYPE_COMPARATIVE. * * @see vrna_pbacktrack5_num(), vrna_pbacktrack5_cb(), vrna_pbacktrack() * * @param fc The fold compound data structure * @param length The length of the subsequence to consider (starting with 5' end) * @return A sampled secondary structure in dot-bracket notation (or NULL on error) */ char * vrna_pbacktrack5(vrna_fold_compound_t *fc, unsigned int length); /** * @brief Obtain a set of secondary structure samples for a subsequence from the Boltzmann ensemble according their probability * * Perform a probabilistic (stochastic) backtracing in the partition function DP arrays * to obtain a set of @p num_samples secondary structures. The parameter @p length specifies * the length of the substructure starting from the 5' end. * * Any structure @f$ s @f$ with free energy @f$ E(s) @f$ is picked from the Boltzmann distributed * ensemble according to its probability * @f[ * p(s) = \frac{exp(-E(s) / kT)}{Z} * @f] * with partition function @f$ Z = \sum_s exp(-E(s) / kT) @f$, Boltzmann constant @f$ k @f$ and * thermodynamic temperature @f$ T @f$. * * Using the @p options flag one can switch between regular (#VRNA_PBACKTRACK_DEFAULT) backtracing * mode, and non-redundant sampling (#VRNA_PBACKTRACK_NON_REDUNDANT) along the lines of Michalik * et al. 2017 @cite michalik:2017. * * @pre Unique multiloop decomposition has to be active upon creation of @p fc with vrna_fold_compound() * or similar. This can be done easily by passing vrna_fold_compound() a model details parameter * with vrna_md_t.uniq_ML = 1. * @pre vrna_pf() has to be called first to fill the partition function matrices * * @note This function is polymorphic. It accepts #vrna_fold_compound_t of type * #VRNA_FC_TYPE_SINGLE, and #VRNA_FC_TYPE_COMPARATIVE. * * @warning In non-redundant sampling mode (#VRNA_PBACKTRACK_NON_REDUNDANT), this function may * not yield the full number of requested samples. This may happen if * a) the number of requested structures is larger than the total number * of structuresin the ensemble, * b) numeric instabilities prevent the backtracking function to enumerate * structures with high free energies, or * c) any other error occurs. * * @see vrna_pbacktrack5(), vrna_pbacktrack5_cb(), vrna_pbacktrack_num(), * #VRNA_PBACKTRACK_DEFAULT, #VRNA_PBACKTRACK_NON_REDUNDANT * * @param fc The fold compound data structure * @param num_samples The size of the sample set, i.e. number of structures * @param length The length of the subsequence to consider (starting with 5' end) * @param options A bitwise OR-flag indicating the backtracing mode. * @return A set of secondary structure samples in dot-bracket notation terminated by NULL (or NULL on error) */ char ** vrna_pbacktrack5_num(vrna_fold_compound_t *fc, unsigned int num_samples, unsigned int length, unsigned int options); /** * @brief Obtain a set of secondary structure samples for a subsequence from the Boltzmann ensemble according their probability * * Perform a probabilistic (stochastic) backtracing in the partition function DP arrays * to obtain a set of @p num_samples secondary structures. The parameter @p length specifies * the length of the substructure starting from the 5' end. * * Any structure @f$ s @f$ with free energy @f$ E(s) @f$ is picked from the Boltzmann distributed * ensemble according to its probability * @f[ * p(s) = \frac{exp(-E(s) / kT)}{Z} * @f] * with partition function @f$ Z = \sum_s exp(-E(s) / kT) @f$, Boltzmann constant @f$ k @f$ and * thermodynamic temperature @f$ T @f$. * * Using the @p options flag one can switch between regular (#VRNA_PBACKTRACK_DEFAULT) backtracing * mode, and non-redundant sampling (#VRNA_PBACKTRACK_NON_REDUNDANT) along the lines of Michalik * et al. 2017 @cite michalik:2017. * * In contrast to vrna_pbacktrack5() and vrna_pbacktrack5_num() this function yields the * structure samples through a callback mechanism. * * @pre Unique multiloop decomposition has to be active upon creation of @p fc with vrna_fold_compound() * or similar. This can be done easily by passing vrna_fold_compound() a model details parameter * with vrna_md_t.uniq_ML = 1. * @pre vrna_pf() has to be called first to fill the partition function matrices * * @note This function is polymorphic. It accepts #vrna_fold_compound_t of type * #VRNA_FC_TYPE_SINGLE, and #VRNA_FC_TYPE_COMPARATIVE. * * @warning In non-redundant sampling mode (#VRNA_PBACKTRACK_NON_REDUNDANT), this function may * not yield the full number of requested samples. This may happen if * a) the number of requested structures is larger than the total number * of structuresin the ensemble, * b) numeric instabilities prevent the backtracking function to enumerate * structures with high free energies, or * c) any other error occurs. * * @see vrna_pbacktrack5(), vrna_pbacktrack5_num(), vrna_pbacktrack_cb(), * #VRNA_PBACKTRACK_DEFAULT, #VRNA_PBACKTRACK_NON_REDUNDANT * * @param fc The fold compound data structure * @param num_samples The size of the sample set, i.e. number of structures * @param length The length of the subsequence to consider (starting with 5' end) * @param cb The callback that receives the sampled structure * @param data A data structure passed through to the callback @p cb * @param options A bitwise OR-flag indicating the backtracing mode. * @return The number of structures actually backtraced */ unsigned int vrna_pbacktrack5_cb(vrna_fold_compound_t *fc, unsigned int num_samples, unsigned int length, vrna_boltzmann_sampling_callback *cb, void *data, unsigned int options); /** * @brief Obtain a set of secondary structure samples for a subsequence from the Boltzmann ensemble according their probability * * Perform a probabilistic (stochastic) backtracing in the partition function DP arrays * to obtain a set of @p num_samples secondary structures. The parameter @p length specifies * the length of the substructure starting from the 5' end. * * Any structure @f$ s @f$ with free energy @f$ E(s) @f$ is picked from the Boltzmann distributed * ensemble according to its probability * @f[ * p(s) = \frac{exp(-E(s) / kT)}{Z} * @f] * with partition function @f$ Z = \sum_s exp(-E(s) / kT) @f$, Boltzmann constant @f$ k @f$ and * thermodynamic temperature @f$ T @f$. * * Using the @p options flag one can switch between regular (#VRNA_PBACKTRACK_DEFAULT) backtracing * mode, and non-redundant sampling (#VRNA_PBACKTRACK_NON_REDUNDANT) along the lines of Michalik * et al. 2017 @cite michalik:2017. * * In contrast to vrna_pbacktrack5_cb() this function allows for resuming a previous * sampling round in specialized Boltzmann sampling, such as non-redundant backtracking. * For that purpose, the user passes the address of a Boltzmann sampling data structure * (#vrna_pbacktrack_mem_t) which will be re-used in each round of sampling, i.e. each * successive call to vrna_pbacktrack5_resume_cb() or vrna_pbacktrack5_resume(). * * A successive sample call to this function may look like: * @code{.c} * vrna_pbacktrack_mem_t nonredundant_memory = NULL; * * // sample the first 100 structures * vrna_pbacktrack5_resume(fc, * 100, * fc->length, * &nonredundant_memory, * options); * * // sample another 500 structures * vrna_pbacktrack5_resume(fc, * 500, * fc->length, * &nonredundant_memory, * options); * * // release memory occupied by the non-redundant memory data structure * vrna_pbacktrack_mem_free(nonredundant_memory); * @endcode * * @pre Unique multiloop decomposition has to be active upon creation of @p fc with vrna_fold_compound() * or similar. This can be done easily by passing vrna_fold_compound() a model details parameter * with vrna_md_t.uniq_ML = 1. * @pre vrna_pf() has to be called first to fill the partition function matrices * * @note This function is polymorphic. It accepts #vrna_fold_compound_t of type * #VRNA_FC_TYPE_SINGLE, and #VRNA_FC_TYPE_COMPARATIVE. * * @warning In non-redundant sampling mode (#VRNA_PBACKTRACK_NON_REDUNDANT), this function may * not yield the full number of requested samples. This may happen if * a) the number of requested structures is larger than the total number * of structuresin the ensemble, * b) numeric instabilities prevent the backtracking function to enumerate * structures with high free energies, or * c) any other error occurs. * * @see vrna_pbacktrack5_resume_cb(), vrna_pbacktrack5_cb(), vrna_pbacktrack_resume(), * #vrna_pbacktrack_mem_t, #VRNA_PBACKTRACK_DEFAULT, #VRNA_PBACKTRACK_NON_REDUNDANT, * vrna_pbacktrack_mem_free * * @param fc The fold compound data structure * @param num_samples The size of the sample set, i.e. number of structures * @param length The length of the subsequence to consider (starting with 5' end) * @param nr_mem The address of the Boltzmann sampling memory data structure * @param options A bitwise OR-flag indicating the backtracing mode. * @return A set of secondary structure samples in dot-bracket notation terminated by NULL (or NULL on error) */ char ** vrna_pbacktrack5_resume(vrna_fold_compound_t *vc, unsigned int num_samples, unsigned int length, vrna_pbacktrack_mem_t *nr_mem, unsigned int options); /** * @brief Obtain a set of secondary structure samples for a subsequence from the Boltzmann ensemble according their probability * * Perform a probabilistic (stochastic) backtracing in the partition function DP arrays * to obtain a set of @p num_samples secondary structures. The parameter @p length specifies * the length of the substructure starting from the 5' end. * * Any structure @f$ s @f$ with free energy @f$ E(s) @f$ is picked from the Boltzmann distributed * ensemble according to its probability * @f[ * p(s) = \frac{exp(-E(s) / kT)}{Z} * @f] * with partition function @f$ Z = \sum_s exp(-E(s) / kT) @f$, Boltzmann constant @f$ k @f$ and * thermodynamic temperature @f$ T @f$. * * Using the @p options flag one can switch between regular (#VRNA_PBACKTRACK_DEFAULT) backtracing * mode, and non-redundant sampling (#VRNA_PBACKTRACK_NON_REDUNDANT) along the lines of Michalik * et al. 2017 @cite michalik:2017. * * In contrast to vrna_pbacktrack5_resume() this function yields the structure samples * through a callback mechanism. * * A successive sample call to this function may look like: * @code{.c} * vrna_pbacktrack_mem_t nonredundant_memory = NULL; * * // sample the first 100 structures * vrna_pbacktrack5_resume_cb(fc, * 100, * fc->length, * &callback_function, * (void *)&callback_data, * &nonredundant_memory, * options); * * // sample another 500 structures * vrna_pbacktrack5_resume_cb(fc, * 500, * fc->length, * &callback_function, * (void *)&callback_data, * &nonredundant_memory, * options); * * // release memory occupied by the non-redundant memory data structure * vrna_pbacktrack_mem_free(nonredundant_memory); * @endcode * * @pre Unique multiloop decomposition has to be active upon creation of @p fc with vrna_fold_compound() * or similar. This can be done easily by passing vrna_fold_compound() a model details parameter * with vrna_md_t.uniq_ML = 1. * @pre vrna_pf() has to be called first to fill the partition function matrices * * @note This function is polymorphic. It accepts #vrna_fold_compound_t of type * #VRNA_FC_TYPE_SINGLE, and #VRNA_FC_TYPE_COMPARATIVE. * * @warning In non-redundant sampling mode (#VRNA_PBACKTRACK_NON_REDUNDANT), this function may * not yield the full number of requested samples. This may happen if * a) the number of requested structures is larger than the total number * of structuresin the ensemble, * b) numeric instabilities prevent the backtracking function to enumerate * structures with high free energies, or * c) any other error occurs. * * @see vrna_pbacktrack5_resume(), vrna_pbacktrack5_cb(), vrna_pbacktrack_resume_cb(), * #vrna_pbacktrack_mem_t, #VRNA_PBACKTRACK_DEFAULT, #VRNA_PBACKTRACK_NON_REDUNDANT, * vrna_pbacktrack_mem_free * * @param fc The fold compound data structure * @param num_samples The size of the sample set, i.e. number of structures * @param length The length of the subsequence to consider (starting with 5' end) * @param cb The callback that receives the sampled structure * @param data A data structure passed through to the callback @p cb * @param nr_mem The address of the Boltzmann sampling memory data structure * @param options A bitwise OR-flag indicating the backtracing mode. * @return The number of structures actually backtraced */ unsigned int vrna_pbacktrack5_resume_cb(vrna_fold_compound_t *fc, unsigned int num_samples, unsigned int length, vrna_boltzmann_sampling_callback *cb, void *data, vrna_pbacktrack_mem_t *nr_mem, unsigned int options); /** * @brief Sample a secondary structure from the Boltzmann ensemble according its probability * * Perform a probabilistic (stochastic) backtracing in the partition function DP arrays * to obtain a secondary structure. * * The structure @f$ s @f$ with free energy @f$ E(s) @f$ is picked from the Boltzmann distributed * ensemble according to its probability * @f[ * p(s) = \frac{exp(-E(s) / kT)}{Z} * @f] * with partition function @f$ Z = \sum_s exp(-E(s) / kT) @f$, Boltzmann constant @f$ k @f$ and * thermodynamic temperature @f$ T @f$. * * @pre Unique multiloop decomposition has to be active upon creation of @p fc with vrna_fold_compound() * or similar. This can be done easily by passing vrna_fold_compound() a model details parameter * with vrna_md_t.uniq_ML = 1. * @pre vrna_pf() has to be called first to fill the partition function matrices * * @note This function is polymorphic. It accepts #vrna_fold_compound_t of type * #VRNA_FC_TYPE_SINGLE, and #VRNA_FC_TYPE_COMPARATIVE. * * @see vrna_pbacktrack5(), vrna_pbacktrack_num, vrna_pbacktrack_cb() * * @param fc The fold compound data structure * @return A sampled secondary structure in dot-bracket notation (or NULL on error) */ char * vrna_pbacktrack(vrna_fold_compound_t *fc); /** * @brief Obtain a set of secondary structure samples from the Boltzmann ensemble according their probability * * Perform a probabilistic (stochastic) backtracing in the partition function DP arrays * to obtain a set of @p num_samples secondary structures. * * Any structure @f$ s @f$ with free energy @f$ E(s) @f$ is picked from the Boltzmann distributed * ensemble according to its probability * @f[ * p(s) = \frac{exp(-E(s) / kT)}{Z} * @f] * with partition function @f$ Z = \sum_s exp(-E(s) / kT) @f$, Boltzmann constant @f$ k @f$ and * thermodynamic temperature @f$ T @f$. * * Using the @p options flag one can switch between regular (#VRNA_PBACKTRACK_DEFAULT) backtracing * mode, and non-redundant sampling (#VRNA_PBACKTRACK_NON_REDUNDANT) along the lines of Michalik * et al. 2017 @cite michalik:2017. * * @pre Unique multiloop decomposition has to be active upon creation of @p fc with vrna_fold_compound() * or similar. This can be done easily by passing vrna_fold_compound() a model details parameter * with vrna_md_t.uniq_ML = 1. * @pre vrna_pf() has to be called first to fill the partition function matrices * * @note This function is polymorphic. It accepts #vrna_fold_compound_t of type * #VRNA_FC_TYPE_SINGLE, and #VRNA_FC_TYPE_COMPARATIVE. * * @warning In non-redundant sampling mode (#VRNA_PBACKTRACK_NON_REDUNDANT), this function may * not yield the full number of requested samples. This may happen if * a) the number of requested structures is larger than the total number * of structuresin the ensemble, * b) numeric instabilities prevent the backtracking function to enumerate * structures with high free energies, or * c) any other error occurs. * * @see vrna_pbacktrack(), vrna_pbacktrack_cb(), vrna_pbacktrack5_num(), * #VRNA_PBACKTRACK_DEFAULT, #VRNA_PBACKTRACK_NON_REDUNDANT * * @param fc The fold compound data structure * @param num_samples The size of the sample set, i.e. number of structures * @param options A bitwise OR-flag indicating the backtracing mode. * @return A set of secondary structure samples in dot-bracket notation terminated by NULL (or NULL on error) */ char ** vrna_pbacktrack_num(vrna_fold_compound_t *fc, unsigned int num_samples, unsigned int options); /** * @brief Obtain a set of secondary structure samples from the Boltzmann ensemble according their probability * * Perform a probabilistic (stochastic) backtracing in the partition function DP arrays * to obtain a set of @p num_samples secondary structures. * * Any structure @f$ s @f$ with free energy @f$ E(s) @f$ is picked from the Boltzmann distributed * ensemble according to its probability * @f[ * p(s) = \frac{exp(-E(s) / kT)}{Z} * @f] * with partition function @f$ Z = \sum_s exp(-E(s) / kT) @f$, Boltzmann constant @f$ k @f$ and * thermodynamic temperature @f$ T @f$. * * Using the @p options flag one can switch between regular (#VRNA_PBACKTRACK_DEFAULT) backtracing * mode, and non-redundant sampling (#VRNA_PBACKTRACK_NON_REDUNDANT) along the lines of Michalik * et al. 2017 @cite michalik:2017. * * In contrast to vrna_pbacktrack() and vrna_pbacktrack_num() this function yields the * structure samples through a callback mechanism. * * @pre Unique multiloop decomposition has to be active upon creation of @p fc with vrna_fold_compound() * or similar. This can be done easily by passing vrna_fold_compound() a model details parameter * with vrna_md_t.uniq_ML = 1. * @pre vrna_pf() has to be called first to fill the partition function matrices * * @note This function is polymorphic. It accepts #vrna_fold_compound_t of type * #VRNA_FC_TYPE_SINGLE, and #VRNA_FC_TYPE_COMPARATIVE. * * @warning In non-redundant sampling mode (#VRNA_PBACKTRACK_NON_REDUNDANT), this function may * not yield the full number of requested samples. This may happen if * a) the number of requested structures is larger than the total number * of structuresin the ensemble, * b) numeric instabilities prevent the backtracking function to enumerate * structures with high free energies, or * c) any other error occurs. * * @see vrna_pbacktrack(), vrna_pbacktrack_num(), vrna_pbacktrack5_cb(), * #VRNA_PBACKTRACK_DEFAULT, #VRNA_PBACKTRACK_NON_REDUNDANT * * @param fc The fold compound data structure * @param num_samples The size of the sample set, i.e. number of structures * @param cb The callback that receives the sampled structure * @param data A data structure passed through to the callback @p cb * @param options A bitwise OR-flag indicating the backtracing mode. * @return The number of structures actually backtraced */ unsigned int vrna_pbacktrack_cb(vrna_fold_compound_t *fc, unsigned int num_samples, vrna_boltzmann_sampling_callback *cb, void *data, unsigned int options); /** * @brief Obtain a set of secondary structure samples from the Boltzmann ensemble according their probability * * Perform a probabilistic (stochastic) backtracing in the partition function DP arrays * to obtain a set of @p num_samples secondary structures. * * Any structure @f$ s @f$ with free energy @f$ E(s) @f$ is picked from the Boltzmann distributed * ensemble according to its probability * @f[ * p(s) = \frac{exp(-E(s) / kT)}{Z} * @f] * with partition function @f$ Z = \sum_s exp(-E(s) / kT) @f$, Boltzmann constant @f$ k @f$ and * thermodynamic temperature @f$ T @f$. * * Using the @p options flag one can switch between regular (#VRNA_PBACKTRACK_DEFAULT) backtracing * mode, and non-redundant sampling (#VRNA_PBACKTRACK_NON_REDUNDANT) along the lines of Michalik * et al. 2017 @cite michalik:2017. * * In contrast to vrna_pbacktrack_cb() this function allows for resuming a previous * sampling round in specialized Boltzmann sampling, such as non-redundant backtracking. * For that purpose, the user passes the address of a Boltzmann sampling data structure * (#vrna_pbacktrack_mem_t) which will be re-used in each round of sampling, i.e. each * successive call to vrna_pbacktrack_resume_cb() or vrna_pbacktrack_resume(). * * A successive sample call to this function may look like: * @code{.c} * vrna_pbacktrack_mem_t nonredundant_memory = NULL; * * // sample the first 100 structures * vrna_pbacktrack_resume(fc, * 100, * &nonredundant_memory, * options); * * // sample another 500 structures * vrna_pbacktrack_resume(fc, * 500, * &nonredundant_memory, * options); * * // release memory occupied by the non-redundant memory data structure * vrna_pbacktrack_mem_free(nonredundant_memory); * @endcode * * @pre Unique multiloop decomposition has to be active upon creation of @p fc with vrna_fold_compound() * or similar. This can be done easily by passing vrna_fold_compound() a model details parameter * with vrna_md_t.uniq_ML = 1. * @pre vrna_pf() has to be called first to fill the partition function matrices * * @note This function is polymorphic. It accepts #vrna_fold_compound_t of type * #VRNA_FC_TYPE_SINGLE, and #VRNA_FC_TYPE_COMPARATIVE. * * @warning In non-redundant sampling mode (#VRNA_PBACKTRACK_NON_REDUNDANT), this function may * not yield the full number of requested samples. This may happen if * a) the number of requested structures is larger than the total number * of structuresin the ensemble, * b) numeric instabilities prevent the backtracking function to enumerate * structures with high free energies, or * c) any other error occurs. * * @see vrna_pbacktrack_resume_cb(), vrna_pbacktrack_cb(), vrna_pbacktrack5_resume(), * #vrna_pbacktrack_mem_t, #VRNA_PBACKTRACK_DEFAULT, #VRNA_PBACKTRACK_NON_REDUNDANT, * vrna_pbacktrack_mem_free * * @param fc The fold compound data structure * @param num_samples The size of the sample set, i.e. number of structures * @param nr_mem The address of the Boltzmann sampling memory data structure * @param options A bitwise OR-flag indicating the backtracing mode. * @return A set of secondary structure samples in dot-bracket notation terminated by NULL (or NULL on error) */ char ** vrna_pbacktrack_resume(vrna_fold_compound_t *fc, unsigned int num_samples, vrna_pbacktrack_mem_t *nr_mem, unsigned int options); /** * @brief Obtain a set of secondary structure samples from the Boltzmann ensemble according their probability * * Perform a probabilistic (stochastic) backtracing in the partition function DP arrays * to obtain a set of @p num_samples secondary structures. * * Any structure @f$ s @f$ with free energy @f$ E(s) @f$ is picked from the Boltzmann distributed * ensemble according to its probability * @f[ * p(s) = \frac{exp(-E(s) / kT)}{Z} * @f] * with partition function @f$ Z = \sum_s exp(-E(s) / kT) @f$, Boltzmann constant @f$ k @f$ and * thermodynamic temperature @f$ T @f$. * * Using the @p options flag one can switch between regular (#VRNA_PBACKTRACK_DEFAULT) backtracing * mode, and non-redundant sampling (#VRNA_PBACKTRACK_NON_REDUNDANT) along the lines of Michalik * et al. 2017 @cite michalik:2017. * * In contrast to vrna_pbacktrack5_resume() this function yields the structure samples * through a callback mechanism. * * A successive sample call to this function may look like: * @code{.c} * vrna_pbacktrack_mem_t nonredundant_memory = NULL; * * // sample the first 100 structures * vrna_pbacktrack5_resume_cb(fc, * 100, * &callback_function, * (void *)&callback_data, * &nonredundant_memory, * options); * * // sample another 500 structures * vrna_pbacktrack5_resume_cb(fc, * 500, * &callback_function, * (void *)&callback_data, * &nonredundant_memory, * options); * * // release memory occupied by the non-redundant memory data structure * vrna_pbacktrack_mem_free(nonredundant_memory); * @endcode * * @pre Unique multiloop decomposition has to be active upon creation of @p fc with vrna_fold_compound() * or similar. This can be done easily by passing vrna_fold_compound() a model details parameter * with vrna_md_t.uniq_ML = 1. * @pre vrna_pf() has to be called first to fill the partition function matrices * * @note This function is polymorphic. It accepts #vrna_fold_compound_t of type * #VRNA_FC_TYPE_SINGLE, and #VRNA_FC_TYPE_COMPARATIVE. * * @warning In non-redundant sampling mode (#VRNA_PBACKTRACK_NON_REDUNDANT), this function may * not yield the full number of requested samples. This may happen if * a) the number of requested structures is larger than the total number * of structuresin the ensemble, * b) numeric instabilities prevent the backtracking function to enumerate * structures with high free energies, or * c) any other error occurs. * * @see vrna_pbacktrack_resume(), vrna_pbacktrack_cb(), vrna_pbacktrack5_resume_cb(), * #vrna_pbacktrack_mem_t, #VRNA_PBACKTRACK_DEFAULT, #VRNA_PBACKTRACK_NON_REDUNDANT, * vrna_pbacktrack_mem_free * * @param fc The fold compound data structure * @param num_samples The size of the sample set, i.e. number of structures * @param cb The callback that receives the sampled structure * @param data A data structure passed through to the callback @p cb * @param nr_mem The address of the Boltzmann sampling memory data structure * @param options A bitwise OR-flag indicating the backtracing mode. * @return The number of structures actually backtraced */ unsigned int vrna_pbacktrack_resume_cb(vrna_fold_compound_t *fc, unsigned int num_samples, vrna_boltzmann_sampling_callback *cb, void *data, vrna_pbacktrack_mem_t *nr_mem, unsigned int options); /** * @brief Sample a secondary structure of a subsequence from the Boltzmann ensemble according its probability * * Perform a probabilistic (stochastic) backtracing in the partition function DP arrays * to obtain a secondary structure. The parameters @p start and @p end specify the interval * @f$ [start:end] @f$ of the subsequence with @f$ 1 \leq start < end \leq n@f$ for sequence length @f$ n @f$, * the structure @f$ s_{start,end} @f$ should be drawn from. * * The resulting substructure @f$ s_{start,end} @f$ with free energy @f$ E(s_{start, end}) @f$ is picked from * the Boltzmann distributed sub ensemble of all structures within the interval @f$ [start:end] @f$ according * to its probability * @f[ * p(s_{start,end}) = \frac{exp(-E(s_{start,end}) / kT)}{Z_{start,end}} * @f] * with partition function @f$ Z_{start,end} = \sum_{s_{start,end}} exp(-E(s_{start,end}) / kT) @f$, * Boltzmann constant @f$ k @f$ and thermodynamic temperature @f$ T @f$. * * @pre Unique multiloop decomposition has to be active upon creation of @p fc with vrna_fold_compound() * or similar. This can be done easily by passing vrna_fold_compound() a model details parameter * with vrna_md_t.uniq_ML = 1. * @pre vrna_pf() has to be called first to fill the partition function matrices * * @note This function is polymorphic. It accepts #vrna_fold_compound_t of type * #VRNA_FC_TYPE_SINGLE, and #VRNA_FC_TYPE_COMPARATIVE. * * @see vrna_pbacktrack_sub_num(), vrna_pbacktrack_sub_cb(), vrna_pbacktrack() * * @param fc The fold compound data structure * @param start The start of the subsequence to consider, i.e. 5'-end position(1-based) * @param end The end of the subsequence to consider, i.e. 3'-end position (1-based) * @return A sampled secondary structure in dot-bracket notation (or NULL on error) */ char * vrna_pbacktrack_sub(vrna_fold_compound_t *fc, unsigned int start, unsigned int end); /** * @brief Obtain a set of secondary structure samples for a subsequence from the Boltzmann ensemble according their probability * * Perform a probabilistic (stochastic) backtracing in the partition function DP arrays * to obtain a set of @p num_samples secondary structures. The parameter @p length specifies * the length of the substructure starting from the 5' end. * * Any structure @f$ s @f$ with free energy @f$ E(s) @f$ is picked from the Boltzmann distributed * ensemble according to its probability * @f[ * p(s) = \frac{exp(-E(s) / kT)}{Z} * @f] * with partition function @f$ Z = \sum_s exp(-E(s) / kT) @f$, Boltzmann constant @f$ k @f$ and * thermodynamic temperature @f$ T @f$. * * Using the @p options flag one can switch between regular (#VRNA_PBACKTRACK_DEFAULT) backtracing * mode, and non-redundant sampling (#VRNA_PBACKTRACK_NON_REDUNDANT) along the lines of Michalik * et al. 2017 @cite michalik:2017. * * @pre Unique multiloop decomposition has to be active upon creation of @p fc with vrna_fold_compound() * or similar. This can be done easily by passing vrna_fold_compound() a model details parameter * with vrna_md_t.uniq_ML = 1. * @pre vrna_pf() has to be called first to fill the partition function matrices * * @note This function is polymorphic. It accepts #vrna_fold_compound_t of type * #VRNA_FC_TYPE_SINGLE, and #VRNA_FC_TYPE_COMPARATIVE. * * @warning In non-redundant sampling mode (#VRNA_PBACKTRACK_NON_REDUNDANT), this function may * not yield the full number of requested samples. This may happen if * a) the number of requested structures is larger than the total number * of structuresin the ensemble, * b) numeric instabilities prevent the backtracking function to enumerate * structures with high free energies, or * c) any other error occurs. * * @see vrna_pbacktrack_sub(), vrna_pbacktrack_sub_cb(), vrna_pbacktrack_num(), * #VRNA_PBACKTRACK_DEFAULT, #VRNA_PBACKTRACK_NON_REDUNDANT * * @param fc The fold compound data structure * @param num_samples The size of the sample set, i.e. number of structures * @param start The start of the subsequence to consider, i.e. 5'-end position(1-based) * @param end The end of the subsequence to consider, i.e. 3'-end position (1-based) * @param options A bitwise OR-flag indicating the backtracing mode. * @return A set of secondary structure samples in dot-bracket notation terminated by NULL (or NULL on error) */ char ** vrna_pbacktrack_sub_num(vrna_fold_compound_t *fc, unsigned int num_samples, unsigned int start, unsigned int end, unsigned int options); /** * @brief Obtain a set of secondary structure samples for a subsequence from the Boltzmann ensemble according their probability * * Perform a probabilistic (stochastic) backtracing in the partition function DP arrays * to obtain a set of @p num_samples secondary structures. The parameter @p length specifies * the length of the substructure starting from the 5' end. * * Any structure @f$ s @f$ with free energy @f$ E(s) @f$ is picked from the Boltzmann distributed * ensemble according to its probability * @f[ * p(s) = \frac{exp(-E(s) / kT)}{Z} * @f] * with partition function @f$ Z = \sum_s exp(-E(s) / kT) @f$, Boltzmann constant @f$ k @f$ and * thermodynamic temperature @f$ T @f$. * * Using the @p options flag one can switch between regular (#VRNA_PBACKTRACK_DEFAULT) backtracing * mode, and non-redundant sampling (#VRNA_PBACKTRACK_NON_REDUNDANT) along the lines of Michalik * et al. 2017 @cite michalik:2017. * * In contrast to vrna_pbacktrack5() and vrna_pbacktrack5_num() this function yields the * structure samples through a callback mechanism. * * @pre Unique multiloop decomposition has to be active upon creation of @p fc with vrna_fold_compound() * or similar. This can be done easily by passing vrna_fold_compound() a model details parameter * with vrna_md_t.uniq_ML = 1. * @pre vrna_pf() has to be called first to fill the partition function matrices * * @note This function is polymorphic. It accepts #vrna_fold_compound_t of type * #VRNA_FC_TYPE_SINGLE, and #VRNA_FC_TYPE_COMPARATIVE. * * @warning In non-redundant sampling mode (#VRNA_PBACKTRACK_NON_REDUNDANT), this function may * not yield the full number of requested samples. This may happen if * a) the number of requested structures is larger than the total number * of structuresin the ensemble, * b) numeric instabilities prevent the backtracking function to enumerate * structures with high free energies, or * c) any other error occurs. * * @see vrna_pbacktrack5(), vrna_pbacktrack5_num(), vrna_pbacktrack_cb(), * #VRNA_PBACKTRACK_DEFAULT, #VRNA_PBACKTRACK_NON_REDUNDANT * * @param fc The fold compound data structure * @param num_samples The size of the sample set, i.e. number of structures * @param start The start of the subsequence to consider, i.e. 5'-end position(1-based) * @param end The end of the subsequence to consider, i.e. 3'-end position (1-based) * @param cb The callback that receives the sampled structure * @param data A data structure passed through to the callback @p cb * @param options A bitwise OR-flag indicating the backtracing mode. * @return The number of structures actually backtraced */ unsigned int vrna_pbacktrack_sub_cb(vrna_fold_compound_t *fc, unsigned int num_samples, unsigned int start, unsigned int end, vrna_boltzmann_sampling_callback *cb, void *data, unsigned int options); /** * @brief Obtain a set of secondary structure samples for a subsequence from the Boltzmann ensemble according their probability * * Perform a probabilistic (stochastic) backtracing in the partition function DP arrays * to obtain a set of @p num_samples secondary structures. The parameter @p length specifies * the length of the substructure starting from the 5' end. * * Any structure @f$ s @f$ with free energy @f$ E(s) @f$ is picked from the Boltzmann distributed * ensemble according to its probability * @f[ * p(s) = \frac{exp(-E(s) / kT)}{Z} * @f] * with partition function @f$ Z = \sum_s exp(-E(s) / kT) @f$, Boltzmann constant @f$ k @f$ and * thermodynamic temperature @f$ T @f$. * * Using the @p options flag one can switch between regular (#VRNA_PBACKTRACK_DEFAULT) backtracing * mode, and non-redundant sampling (#VRNA_PBACKTRACK_NON_REDUNDANT) along the lines of Michalik * et al. 2017 @cite michalik:2017. * * In contrast to vrna_pbacktrack5_cb() this function allows for resuming a previous * sampling round in specialized Boltzmann sampling, such as non-redundant backtracking. * For that purpose, the user passes the address of a Boltzmann sampling data structure * (#vrna_pbacktrack_mem_t) which will be re-used in each round of sampling, i.e. each * successive call to vrna_pbacktrack5_resume_cb() or vrna_pbacktrack5_resume(). * * A successive sample call to this function may look like: * @code{.c} * vrna_pbacktrack_mem_t nonredundant_memory = NULL; * * // sample the first 100 structures * vrna_pbacktrack5_resume(fc, * 100, * fc->length, * &nonredundant_memory, * options); * * // sample another 500 structures * vrna_pbacktrack5_resume(fc, * 500, * fc->length, * &nonredundant_memory, * options); * * // release memory occupied by the non-redundant memory data structure * vrna_pbacktrack_mem_free(nonredundant_memory); * @endcode * * @pre Unique multiloop decomposition has to be active upon creation of @p fc with vrna_fold_compound() * or similar. This can be done easily by passing vrna_fold_compound() a model details parameter * with vrna_md_t.uniq_ML = 1. * @pre vrna_pf() has to be called first to fill the partition function matrices * * @note This function is polymorphic. It accepts #vrna_fold_compound_t of type * #VRNA_FC_TYPE_SINGLE, and #VRNA_FC_TYPE_COMPARATIVE. * * @warning In non-redundant sampling mode (#VRNA_PBACKTRACK_NON_REDUNDANT), this function may * not yield the full number of requested samples. This may happen if * a) the number of requested structures is larger than the total number * of structuresin the ensemble, * b) numeric instabilities prevent the backtracking function to enumerate * structures with high free energies, or * c) any other error occurs. * * @see vrna_pbacktrack5_resume_cb(), vrna_pbacktrack5_cb(), vrna_pbacktrack_resume(), * #vrna_pbacktrack_mem_t, #VRNA_PBACKTRACK_DEFAULT, #VRNA_PBACKTRACK_NON_REDUNDANT, * vrna_pbacktrack_mem_free * * @param fc The fold compound data structure * @param num_samples The size of the sample set, i.e. number of structures * @param start The start of the subsequence to consider, i.e. 5'-end position(1-based) * @param end The end of the subsequence to consider, i.e. 3'-end position (1-based) * @param nr_mem The address of the Boltzmann sampling memory data structure * @param options A bitwise OR-flag indicating the backtracing mode. * @return A set of secondary structure samples in dot-bracket notation terminated by NULL (or NULL on error) */ char ** vrna_pbacktrack_sub_resume(vrna_fold_compound_t *vc, unsigned int num_samples, unsigned int start, unsigned int end, vrna_pbacktrack_mem_t *nr_mem, unsigned int options); /** * @brief Obtain a set of secondary structure samples for a subsequence from the Boltzmann ensemble according their probability * * Perform a probabilistic (stochastic) backtracing in the partition function DP arrays * to obtain a set of @p num_samples secondary structures. The parameter @p length specifies * the length of the substructure starting from the 5' end. * * Any structure @f$ s @f$ with free energy @f$ E(s) @f$ is picked from the Boltzmann distributed * ensemble according to its probability * @f[ * p(s) = \frac{exp(-E(s) / kT)}{Z} * @f] * with partition function @f$ Z = \sum_s exp(-E(s) / kT) @f$, Boltzmann constant @f$ k @f$ and * thermodynamic temperature @f$ T @f$. * * Using the @p options flag one can switch between regular (#VRNA_PBACKTRACK_DEFAULT) backtracing * mode, and non-redundant sampling (#VRNA_PBACKTRACK_NON_REDUNDANT) along the lines of Michalik * et al. 2017 @cite michalik:2017. * * In contrast to vrna_pbacktrack5_resume() this function yields the structure samples * through a callback mechanism. * * A successive sample call to this function may look like: * @code{.c} * vrna_pbacktrack_mem_t nonredundant_memory = NULL; * * // sample the first 100 structures * vrna_pbacktrack5_resume_cb(fc, * 100, * fc->length, * &callback_function, * (void *)&callback_data, * &nonredundant_memory, * options); * * // sample another 500 structures * vrna_pbacktrack5_resume_cb(fc, * 500, * fc->length, * &callback_function, * (void *)&callback_data, * &nonredundant_memory, * options); * * // release memory occupied by the non-redundant memory data structure * vrna_pbacktrack_mem_free(nonredundant_memory); * @endcode * * @pre Unique multiloop decomposition has to be active upon creation of @p fc with vrna_fold_compound() * or similar. This can be done easily by passing vrna_fold_compound() a model details parameter * with vrna_md_t.uniq_ML = 1. * @pre vrna_pf() has to be called first to fill the partition function matrices * * @note This function is polymorphic. It accepts #vrna_fold_compound_t of type * #VRNA_FC_TYPE_SINGLE, and #VRNA_FC_TYPE_COMPARATIVE. * * @warning In non-redundant sampling mode (#VRNA_PBACKTRACK_NON_REDUNDANT), this function may * not yield the full number of requested samples. This may happen if * a) the number of requested structures is larger than the total number * of structuresin the ensemble, * b) numeric instabilities prevent the backtracking function to enumerate * structures with high free energies, or * c) any other error occurs. * * @see vrna_pbacktrack5_resume(), vrna_pbacktrack5_cb(), vrna_pbacktrack_resume_cb(), * #vrna_pbacktrack_mem_t, #VRNA_PBACKTRACK_DEFAULT, #VRNA_PBACKTRACK_NON_REDUNDANT, * vrna_pbacktrack_mem_free * * @param fc The fold compound data structure * @param num_samples The size of the sample set, i.e. number of structures * @param start The start of the subsequence to consider, i.e. 5'-end position(1-based) * @param end The end of the subsequence to consider, i.e. 3'-end position (1-based) * @param cb The callback that receives the sampled structure * @param data A data structure passed through to the callback @p cb * @param nr_mem The address of the Boltzmann sampling memory data structure * @param options A bitwise OR-flag indicating the backtracing mode. * @return The number of structures actually backtraced */ unsigned int vrna_pbacktrack_sub_resume_cb(vrna_fold_compound_t *fc, unsigned int num_samples, unsigned int start, unsigned int end, vrna_boltzmann_sampling_callback *bs_cb, void *data, vrna_pbacktrack_mem_t *nr_mem, unsigned int options); /** * @brief Release memory occupied by a Boltzmann sampling memory data structure * * @see #vrna_pbacktrack_mem_t, vrna_pbacktrack5_resume(), vrna_pbacktrack5_resume_cb(), * vrna_pbacktrack_resume(), vrna_pbacktrack_resume_cb() * * @param s The non-redundancy memory data structure */ void vrna_pbacktrack_mem_free(vrna_pbacktrack_mem_t s); /**@}*/ #endif ======================= File: src/bin/RNAheat.c ======================= /* * Heat Capacity of RNA molecule * * c <NAME> and <NAME> * Vienna RNA package * * * calculates specific heat using C = - T d^2/dT^2 G(T) */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <math.h> #include <unistd.h> #include "ViennaRNA/utils/basic.h" #include "ViennaRNA/utils/strings.h" #include "ViennaRNA/params/basic.h" #include "ViennaRNA/params/io.h" #include "ViennaRNA/io/file_formats.h" #include "ViennaRNA/datastructures/char_stream.h" #include "ViennaRNA/datastructures/stream_output.h" #include "ViennaRNA/heat_capacity.h" #include "ViennaRNA/color_output.inc" #include "RNAheat_cmdl.h" #include "gengetopt_helper.h" #include "input_id_helpers.h" #include "parallel_helpers.h" #define MAXWIDTH 201 struct options { int filename_full; int noconv; float T_min; float T_max; float h; int mpoints; vrna_md_t md; dataset_id id_control; int jobs; int keep_order; unsigned int next_record_number; vrna_ostream_t output_queue; }; struct record_data { unsigned int number; char *id; char *sequence; char *SEQ_ID; char *input_filename; int multiline_input; struct options *options; int tty; }; struct output_stream { vrna_cstr_t data; vrna_cstr_t err; }; static int process_input(FILE *input_stream, const char *input_filename, struct options *opt); static void process_record(struct record_data *record); static void print_to_stream_callback(float temperature, float hc, void *d); void init_default_options(struct options *opt) { opt->filename_full = 0; opt->noconv = 0; vrna_md_set_default(&(opt->md)); opt->md.backtrack = 0; opt->md.compute_bpp = 0; opt->T_min = 0.; opt->T_max = 100.; opt->h = 1; opt->mpoints = 2; opt->jobs = 1; opt->keep_order = 1; opt->next_record_number = 0; opt->output_queue = NULL; } static char ** collect_unnamed_options(struct RNAheat_args_info *ggostruct, int *num_files) { char **input_files = NULL; unsigned int i; *num_files = 0; /* collect all unnamed options */ if (ggostruct->inputs_num > 0) { input_files = (char **)vrna_realloc(input_files, sizeof(char *) * ggostruct->inputs_num); for (i = 0; i < ggostruct->inputs_num; i++) input_files[(*num_files)++] = strdup(ggostruct->inputs[i]); } return input_files; } static char ** append_input_files(struct RNAheat_args_info *ggostruct, char **files, int *numfiles) { unsigned int i; if (ggostruct->infile_given) { files = (char **)vrna_realloc(files, sizeof(char *) * (*numfiles + ggostruct->infile_given)); for (i = 0; i < ggostruct->infile_given; i++) files[(*numfiles)++] = strdup(ggostruct->infile_arg[i]); } return files; } void flush_cstr_callback(void *auxdata, unsigned int i, void *data) { struct output_stream *s = (struct output_stream *)data; /* flush/free errors first */ vrna_cstr_free(s->err); /* flush/free data[k] */ vrna_cstr_free(s->data); free(s); } int main(int argc, char *argv[]) { struct RNAheat_args_info args_info; char **input_files; int num_input; struct options opt; num_input = 0; init_default_options(&opt); /* ############################################# # check the command line parameters ############################################# */ if (RNAheat_cmdline_parser(argc, argv, &args_info)!= 0) exit(1); /* * - dangles * - special_hp * - gquad * - energy_set * - ns_bases * - parameter file */ ggo_get_md_eval(args_info, opt.md); /* check dangle model */ if (!((opt.md.dangles == 0) || (opt.md.dangles == 2))) { vrna_message_warning("required dangle model not implemented, falling back to default dangles=2"); opt.md.dangles = 2; } /* * - noLP * - noGU * - noGUclosure * - maxBPspan */ ggo_get_md_fold(args_info, opt.md); ggo_get_circ(args_info, opt.md.circ); /* do not convert DNA nucleotide "T" to appropriate RNA "U" */ if (args_info.noconv_given) opt.noconv = 1; /* Tmin */ if (args_info.Tmin_given) opt.T_min = args_info.Tmin_arg; /* Tmax */ if (args_info.Tmax_given) opt.T_max = args_info.Tmax_arg; /* step size */ if (args_info.stepsize_given) opt.h = args_info.stepsize_arg; /* ipoints */ if (args_info.ipoints_given) { opt.mpoints = args_info.ipoints_arg; if (opt.mpoints < 1) opt.mpoints = 1; if (opt.mpoints > 100) opt.mpoints = 100; } if (args_info.jobs_given) { #if VRNA_WITH_PTHREADS int thread_max = max_user_threads(); if (args_info.jobs_arg == 0) { /* use maximum of concurrent threads */ int proc_cores, proc_cores_conf; if (num_proc_cores(&proc_cores, &proc_cores_conf)) { opt.jobs = MIN2(thread_max, proc_cores_conf); } else { vrna_message_warning("Could not determine number of available processor cores!\n" "Defaulting to serial computation"); opt.jobs = 1; } } else { opt.jobs = MIN2(thread_max, args_info.jobs_arg); } opt.jobs = MAX2(1, opt.jobs); #else vrna_message_warning( "This version of RNAheat has been built without parallel input processing capabilities"); #endif if (args_info.unordered_given) opt.keep_order = 0; } input_files = collect_unnamed_options(&args_info, &num_input); input_files = append_input_files(&args_info, input_files, &num_input); /* parse options for ID manipulation */ ggo_get_id_control(args_info, opt.id_control, "Sequence", "sequence", "_", 4, 1); /* free allocated memory of command line data structure */ RNAheat_cmdline_parser_free(&args_info); /* ############################################# # begin initializing ############################################# */ if (opt.md.circ && opt.md.gquad) vrna_message_error("G-Quadruplex support is currently not available for circular RNA structures"); if (opt.keep_order) opt.output_queue = vrna_ostream_init(&flush_cstr_callback, NULL); /* ############################################# # main loop: continue until end of file ############################################# */ INIT_PARALLELIZATION(opt.jobs); if (num_input > 0) { int i, skip; for (skip = i = 0; i < num_input; i++) { if (!skip) { FILE *input_stream = fopen((const char *)input_files[i], "r"); if (!input_stream) vrna_message_error("Unable to open %d. input file \"%s\" for reading", i + 1, input_files[i]); if (process_input(input_stream, (const char *)input_files[i], &opt) == 0) skip = 1; fclose(input_stream); } free(input_files[i]); } } else { (void)process_input(stdin, NULL, &opt); } UNINIT_PARALLELIZATION /* ################################################ # post processing ################################################ */ vrna_ostream_free(opt.output_queue); free(input_files); free_id_data(opt.id_control); return EXIT_SUCCESS; } static int process_input(FILE *input_stream, const char *input_filename, struct options *opt) { int ret = 1; int istty_in = isatty(fileno(input_stream)); int istty_out = isatty(fileno(stdout)); unsigned int read_opt = VRNA_INPUT_NO_REST; /* print user help if we get input from tty */ if (istty_in && istty_out) { vrna_message_input_seq_simple(); read_opt |= VRNA_INPUT_NOSKIP_BLANK_LINES; } /* ############################################# # main loop: continue until end of file ############################################# */ do { char *rec_sequence, *rec_id, **rec_rest; unsigned int rec_type; int maybe_multiline; rec_id = NULL; rec_rest = NULL; maybe_multiline = 0; rec_type = vrna_file_fasta_read_record(&rec_id, &rec_sequence, &rec_rest, input_stream, read_opt); if (rec_type & (VRNA_INPUT_ERROR | VRNA_INPUT_QUIT)) break; /* ######################################################## # init everything according to the data we've read ######################################################## */ if (rec_id) { maybe_multiline = 1; /* remove '>' from FASTA header */ rec_id = memmove(rec_id, rec_id + 1, strlen(rec_id)); } /* construct the sequence ID */ set_next_id(&rec_id, opt->id_control); struct record_data *record = (struct record_data *)vrna_alloc(sizeof(struct record_data)); record->number = opt->next_record_number; record->sequence = rec_sequence; record->SEQ_ID = fileprefix_from_id(rec_id, opt->id_control, opt->filename_full); record->id = rec_id; record->multiline_input = maybe_multiline; record->options = opt; record->tty = istty_in && istty_out; record->input_filename = (input_filename)? strdup(input_filename) : NULL; if (opt->output_queue) vrna_ostream_request(opt->output_queue, opt->next_record_number++); RUN_IN_PARALLEL(process_record, record); /* print user help for the next round if we get input from tty */ if (istty_in && istty_out) vrna_message_input_seq_simple(); } while (1); return ret; } static void process_record(struct record_data *record) { char *rec_sequence; int n, m; float T_min, T_max, h; vrna_fold_compound_t *fc; struct options *opt; struct output_stream *o_stream; opt = record->options; o_stream = (struct output_stream *)vrna_alloc(sizeof(struct output_stream)); rec_sequence = strdup(record->sequence); T_min = opt->T_min; T_max = opt->T_max; h = opt->h; m = opt->mpoints; /* convert DNA alphabet to RNA if not explicitely switched off */ if (!opt->noconv) { vrna_seq_toRNA(rec_sequence); vrna_seq_toRNA(record->sequence); } /* convert sequence to uppercase letters only */ vrna_seq_toupper(rec_sequence); fc = vrna_fold_compound(rec_sequence, &(opt->md), VRNA_OPTION_DEFAULT); if (!fc) { vrna_message_warning("Skipping computations for \"%s\"", (record->id)? record->id : "identifier unavailable"); return; } n = (int)fc->length; /* retrieve string stream bound to stdout, 6*length should be enough memory to start with */ o_stream->data = vrna_cstr(6 * n, stdout); /* retrieve string stream bound to stderr for any info messages */ o_stream->err = vrna_cstr(n, stderr); if (record->tty) vrna_message_info(stdout, "length = %d", n); /* ######################################################## # begin actual computations ######################################################## */ vrna_cstr_print_fasta_header(o_stream->data, record->id); (void)vrna_heat_capacity_cb(fc, T_min, T_max, h, m, &print_to_stream_callback, (void *)o_stream->data); if (opt->output_queue) vrna_ostream_provide(opt->output_queue, record->number, (void *)o_stream); else flush_cstr_callback(NULL, 0, (void *)o_stream); /* clean up */ vrna_fold_compound_free(fc); free(record->id); free(record->SEQ_ID); free(record->sequence); free(rec_sequence); free(record->input_filename); free(record); } PRIVATE void print_to_stream_callback(float temperature, float hc, void *d) { vrna_cstr_printf_tbody((vrna_cstr_t)d, "%g\t%g", temperature, hc); } ======================= File: src/ViennaRNA/utils/higher_order_functions.c ======================= #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdio.h> #include <stdlib.h> #include <math.h> #include "ViennaRNA/utils/basic.h" #include "ViennaRNA/utils/cpu.h" typedef int (proto_fun_zip_reduce)(const int *a, const int *b, int size); /* ################################# # PRIVATE FUNCTION DECLARATIONS # ################################# */ static int zip_add_min_dispatcher(const int *a, const int *b, int size); static int fun_zip_add_min_default(const int *e1, const int *e2, int count); #if VRNA_WITH_SIMD_AVX512 int vrna_fun_zip_add_min_avx512(const int *e1, const int *e2, int count); #endif #if VRNA_WITH_SIMD_SSE41 int vrna_fun_zip_add_min_sse41(const int *e1, const int *e2, int count); #endif static proto_fun_zip_reduce *fun_zip_add_min = &zip_add_min_dispatcher; /* ################################# # BEGIN OF FUNCTION DEFINITIONS # ################################# */ PUBLIC void vrna_fun_dispatch_disable(void) { fun_zip_add_min = &fun_zip_add_min_default; } PUBLIC void vrna_fun_dispatch_enable(void) { fun_zip_add_min = &zip_add_min_dispatcher; } PUBLIC int vrna_fun_zip_add_min(const int *e1, const int *e2, int count) { return (*fun_zip_add_min)(e1, e2, count); } /* ################################# # STATIC helper functions below # ################################# */ /* zip_add_min() dispatcher */ static int zip_add_min_dispatcher(const int *a, const int *b, int size) { unsigned int features = vrna_cpu_simd_capabilities(); #if VRNA_WITH_SIMD_AVX512 if (features & VRNA_CPU_SIMD_AVX512F) { fun_zip_add_min = &vrna_fun_zip_add_min_avx512; goto exec_fun_zip_add_min; } #endif #if VRNA_WITH_SIMD_SSE41 if (features & VRNA_CPU_SIMD_SSE41) { fun_zip_add_min = &vrna_fun_zip_add_min_sse41; goto exec_fun_zip_add_min; } #endif fun_zip_add_min = &fun_zip_add_min_default; exec_fun_zip_add_min: return (*fun_zip_add_min)(a, b, size); } static int fun_zip_add_min_default(const int *e1, const int *e2, int count) { int i; int decomp = INF; for (i = 0; i < count; i++) { if ((e1[i]!= INF) && (e2[i]!= INF)) { const int en = e1[i] + e2[i]; decomp = MIN2(decomp, en); } } return decomp; } ======================= File: src/ViennaRNA/loops/multibranch.c ======================= <filename>src/ViennaRNA/loops/multibranch.c /* * WBL 24 Aug 2018 Add AVX512 based on sources_034_578/modular_decomposition_id3.c * WBL 22 Aug 2018 by hand d3c17fd3e04e2419c147a1e097d3c4d2c5a6f11d lines 1355-1357 */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdio.h> #include <stdlib.h> #include <math.h> #include <ctype.h> #include <string.h> #include "ViennaRNA/utils/basic.h" #include "ViennaRNA/fold_vars.h" #include "ViennaRNA/alphabet.h" #include "ViennaRNA/params/default.h" #include "ViennaRNA/constraints/hard.h" #include "ViennaRNA/constraints/soft.h" #include "ViennaRNA/loops/external.h" #include "ViennaRNA/gquad.h" #include "ViennaRNA/structured_domains.h" #include "ViennaRNA/unstructured_domains.h" #include "ViennaRNA/loops/multibranch.h" #include "ViennaRNA/utils/higher_order_functions.h" #ifdef __GNUC__ # define INLINE inline #else # define INLINE #endif #include "multibranch_hc.inc" #include "multibranch_sc.inc" /* ################################# # PRIVATE FUNCTION DECLARATIONS # ################################# */ PRIVATE int E_mb_loop_fast(vrna_fold_compound_t *fc, int i, int j, int *dmli1, int *dmli2); PRIVATE int E_ml_stems_fast(vrna_fold_compound_t *fc, int i, int j, int *fmi, int *dmli); PRIVATE int extend_fm_3p(int i, int j, int *fm, vrna_fold_compound_t *fc, vrna_callback_hc_evaluate *evaluate, struct hc_mb_def_dat *hc_data, struct sc_mb_dat *sc_wrapper); PRIVATE int E_mb_loop_stack(vrna_fold_compound_t *fc, int i, int j); PRIVATE INLINE int ml_pair5(vrna_fold_compound_t *fc, int i, int j, int *dmli2, vrna_callback_hc_evaluate *evaluate, struct hc_mb_def_dat *hc_wrapper, struct sc_mb_dat *sc_wrapper); PRIVATE INLINE int ml_pair3(vrna_fold_compound_t *fc, int i, int j, int *dmli1, vrna_callback_hc_evaluate *evaluate, struct hc_mb_def_dat *hc_wrapper, struct sc_mb_dat *sc_wrapper); PRIVATE INLINE int ml_pair53(vrna_fold_compound_t *fc, int i, int j, int *dmli1, int *dmli2, vrna_callback_hc_evaluate *evaluate, struct hc_mb_def_dat *hc_wrapper, struct sc_mb_dat *sc_wrapper); /* ################################# # BEGIN OF FUNCTION DEFINITIONS # ################################# */ PUBLIC int vrna_E_mb_loop_fast(vrna_fold_compound_t *fc, int i, int j, int *dmli1, int *dmli2) { int e = INF; if (fc) e = E_mb_loop_fast(fc, i, j, dmli1, dmli2); return e; } PUBLIC int vrna_E_ml_stems_fast(vrna_fold_compound_t *fc, int i, int j, int *fmi, int *dmli) { int e = INF; if (fc) e = E_ml_stems_fast(fc, i, j, fmi, dmli); return e; } PUBLIC int vrna_E_mb_loop_stack(vrna_fold_compound_t *fc, int i, int j) { int e = INF; if (fc) e = E_mb_loop_stack(fc, i, j); return e; } PUBLIC int E_ml_rightmost_stem(int i, int j, vrna_fold_compound_t *fc) { int e; e = INF; if ((fc) && (fc->matrices) && (fc->matrices->fM1)) { struct hc_mb_def_dat hc_dat_local; struct sc_mb_dat sc_wrapper; vrna_callback_hc_evaluate *evaluate; evaluate = prepare_hc_mb_def(fc, &hc_dat_local); init_sc_mb(fc, &sc_wrapper); e = extend_fm_3p(i, j, fc->matrices->fM1, fc, evaluate, &hc_dat_local, &sc_wrapper); if ((fc->aux_grammar) && (fc->aux_grammar->cb_aux_m1)) { int ee = fc->aux_grammar->cb_aux_m1(fc, i, j, fc->aux_grammar->data); e = MIN2(e, ee); } free_sc_mb(&sc_wrapper); } return e; } /* ##################################### # BEGIN OF STATIC HELPER FUNCTIONS # ##################################### */ PRIVATE INLINE int ml_pair_d0(vrna_fold_compound_t *fc, int i, int j, int *dmli1, vrna_callback_hc_evaluate *evaluate, struct hc_mb_def_dat *hc_wrapper, struct sc_mb_dat *sc_wrapper) { short *S, **SS; unsigned int tt, s, n_seq; int e; vrna_param_t *P; vrna_md_t *md; e = INF; if (evaluate(i, j, i + 1, j - 1, VRNA_DECOMP_PAIR_ML, hc_wrapper)) { e = dmli1[j - 1]; if (e!= INF) { P = fc->params; md = &(P->model_details); switch (fc->type) { case VRNA_FC_TYPE_SINGLE: S = fc->sequence_encoding2; tt = vrna_get_ptype_md(S[j], S[i], md); if (md->noGUclosure && ((tt == 3) || (tt == 4))) return INF; /* not allowed */ e += E_MLstem(tt, -1, -1, P) + P->MLclosing; break; case VRNA_FC_TYPE_COMPARATIVE: n_seq = fc->n_seq; SS = fc->S; for (s = 0; s < n_seq; s++) { tt = vrna_get_ptype_md(SS[s][j], SS[s][i], md); e += E_MLstem(tt, -1, -1, P); } e += n_seq * P->MLclosing; break; } if (sc_wrapper->pair) e += sc_wrapper->pair(i, j, sc_wrapper); } } return e; } PRIVATE INLINE int ml_pair_d1(vrna_fold_compound_t *fc, int i, int j, int *dmli1, int *dmli2, vrna_callback_hc_evaluate *evaluate, struct hc_mb_def_dat *hc_wrapper, struct sc_mb_dat *sc_wrapper) { int e, en; /* new closing pair (i,j) with mb part [i+1,j-1] */ e = ml_pair_d0(fc, i, j, dmli1, evaluate, hc_wrapper, sc_wrapper); /* new closing pair (i,j) with mb part [i+2,j-1] */ en = ml_pair5(fc, i, j, dmli2, evaluate, hc_wrapper, sc_wrapper); e = MIN2(e, en); /* new closing pair (i,j) with mb part [i+1, j-2] */ en = ml_pair3(fc, i, j, dmli1, evaluate, hc_wrapper, sc_wrapper); e = MIN2(e, en); /* new closing pair (i,j) with mb part [i+2.j-2] */ en = ml_pair53(fc, i, j, dmli1, dmli2, evaluate, hc_wrapper, sc_wrapper); e = MIN2(e, en); return e; } PRIVATE INLINE int ml_pair_d2(vrna_fold_compound_t *fc, int i, int j, int *dmli1, vrna_callback_hc_evaluate *evaluate, struct hc_mb_def_dat *hc_wrapper, struct sc_mb_dat *sc_wrapper) { short *S, *S2, **SS, **S5, **S3, si1, sj1; unsigned int tt, strands, *sn, s, n_seq; int e; vrna_param_t *P; vrna_md_t *md; e = INF; if (evaluate(i, j, i + 1, j - 1, VRNA_DECOMP_PAIR_ML, hc_wrapper)) { e = dmli1[j - 1]; if (e!= INF) { P = fc->params; md = &(P->model_details); switch (fc->type) { case VRNA_FC_TYPE_SINGLE: strands = fc->strands; sn = fc->strand_number; S = fc->sequence_encoding; S2 = fc->sequence_encoding2; tt = vrna_get_ptype_md(S2[j], S2[i], md); if (md->noGUclosure && ((tt == 3) || (tt == 4))) return INF; /* not allowed */ si1 = ((strands == 1) || (sn[i] == sn[i + 1]))? S[i + 1] : -1; sj1 = ((strands == 1) || (sn[j - 1] == sn[j]))? S[j - 1] : -1; e += E_MLstem(tt, sj1, si1, P) + P->MLclosing; break; case VRNA_FC_TYPE_COMPARATIVE: n_seq = fc->n_seq; SS = fc->S; S5 = fc->S5; S3 = fc->S3; for (s = 0; s < n_seq; s++) { tt = vrna_get_ptype_md(SS[s][j], SS[s][i], md); e += E_MLstem(tt, S5[s][j], S3[s][i], P); } e += n_seq * P->MLclosing; break; } if (sc_wrapper->pair) e += sc_wrapper->pair(i, j, sc_wrapper); } } return e; } PRIVATE INLINE int ml_pair5(vrna_fold_compound_t *fc, int i, int j, int *dmli2, vrna_callback_hc_evaluate *evaluate, struct hc_mb_def_dat *hc_wrapper, struct sc_mb_dat *sc_wrapper) { short *S, *S2, **SS, **S3, si1; unsigned int tt, strands, *sn, n_seq, s; int e; vrna_param_t *P; vrna_md_t *md; e = INF; if (evaluate(i, j, i + 2, j - 1, VRNA_DECOMP_PAIR_ML, hc_wrapper)) { e = dmli2[j - 1]; if (e!= INF) { P = fc->params; md = &(P->model_details); switch (fc->type) { case VRNA_FC_TYPE_SINGLE: strands = fc->strands; sn = fc->strand_number; S = fc->sequence_encoding; S2 = fc->sequence_encoding2; tt = vrna_get_ptype_md(S2[j], S2[i], md); if (md->noGUclosure && ((tt == 3) || (tt == 4))) return INF; /* not allowed */ si1 = ((strands == 1) || (sn[i] == sn[i + 2]))? S[i + 1] : -1; e += E_MLstem(tt, -1, si1, P) + P->MLclosing + P->MLbase; break; case VRNA_FC_TYPE_COMPARATIVE: n_seq = fc->n_seq; SS = fc->S; S3 = fc->S3; for (s = 0; s < n_seq; s++) { tt = vrna_get_ptype_md(SS[s][j], SS[s][i], md); e += E_MLstem(tt, -1, S3[s][i], P); } e += (P->MLclosing + P->MLbase) * n_seq; break; } if (sc_wrapper->pair5) e += sc_wrapper->pair5(i, j, sc_wrapper); } } return e; } PRIVATE INLINE int ml_pair3(vrna_fold_compound_t *fc, int i, int j, int *dmli1, vrna_callback_hc_evaluate *evaluate, struct hc_mb_def_dat *hc_wrapper, struct sc_mb_dat *sc_wrapper) { short *S, *S2, **SS, **S5, sj1; unsigned int tt, strands, *sn, n_seq, s; int e; vrna_param_t *P; vrna_md_t *md; e = INF; if (evaluate(i, j, i + 1, j - 2, VRNA_DECOMP_PAIR_ML, hc_wrapper)) { e = dmli1[j - 2]; if (e!= INF) { P = fc->params; md = &(P->model_details); switch (fc->type) { case VRNA_FC_TYPE_SINGLE: strands = fc->strands; sn = fc->strand_number; S = fc->sequence_encoding; S2 = fc->sequence_encoding2; tt = vrna_get_ptype_md(S2[j], S2[i], md); if (md->noGUclosure && ((tt == 3) || (tt == 4))) return INF; /* not allowed */ sj1 = ((strands == 1) || (sn[j - 2] == sn[j]))? S[j - 1] : -1; e += E_MLstem(tt, sj1, -1, P) + P->MLclosing + P->MLbase; break; case VRNA_FC_TYPE_COMPARATIVE: n_seq = fc->n_seq; SS = fc->S; S5 = fc->S5; for (s = 0; s < n_seq; s++) { tt = vrna_get_ptype_md(SS[s][j], SS[s][i], md); e += E_MLstem(tt, S5[s][j], -1, P); } e += (P->MLclosing + P->MLbase) * n_seq; break; } if (sc_wrapper->pair3) e += sc_wrapper->pair3(i, j, sc_wrapper); } } return e; } PRIVATE INLINE int ml_pair53(vrna_fold_compound_t *fc, int i, int j, int *dmli1, int *dmli2, vrna_callback_hc_evaluate *evaluate, struct hc_mb_def_dat *hc_wrapper, struct sc_mb_dat *sc_wrapper) { short *S, *S2, **SS, **S3, **S5, si1, sj1; unsigned int tt, strands, *sn, n_seq, s; int e; vrna_param_t *P; vrna_md_t *md; e = INF; if (evaluate(i, j, i + 2, j - 2, VRNA_DECOMP_PAIR_ML, hc_wrapper)) { e = dmli2[j - 2]; if (e!= INF) { P = fc->params; md = &(P->model_details); switch (fc->type) { case VRNA_FC_TYPE_SINGLE: strands = fc->strands; sn = fc->strand_number; S = fc->sequence_encoding; S2 = fc->sequence_encoding2; tt = vrna_get_ptype_md(S2[j], S2[i], md); if (md->noGUclosure && ((tt == 3) || (tt == 4))) return INF; /* not allowed */ si1 = ((strands == 1) || (sn[i] == sn[i + 2]))? S[i + 1] : -1; sj1 = ((strands == 1) || (sn[j - 2] == sn[j]))? S[j - 1] : -1; e += E_MLstem(tt, sj1, si1, P) + P->MLclosing + 2 * P->MLbase; break; case VRNA_FC_TYPE_COMPARATIVE: n_seq = fc->n_seq; SS = fc->S; S5 = fc->S5; S3 = fc->S3; for (s = 0; s < n_seq; s++) { tt = vrna_get_ptype_md(SS[s][j], SS[s][i], md); e += E_MLstem(tt, S5[s][j], S3[s][i], P); } e += (P->MLclosing + 2 * P->MLbase) * n_seq; break; } if (sc_wrapper->pair53) e += sc_wrapper->pair53(i, j, sc_wrapper); } } return e; } #if 0 PRIVATE int E_mb_loop_fake(vrna_fold_compound_t *fc, int i, int j) { short S_i1, S_j1, *S, *S2; unsigned int strands, *sn; int decomp, en, e, *fC, dangle_model, tt, noGUclosure; vrna_param_t *P; vrna_md_t *md; vrna_callback_hc_evaluate *evaluate; struct hc_mb_def_dat hc_dat_local; S = fc->sequence_encoding; S2 = fc->sequence_encoding2; strands = fc->strands; sn = fc->strand_number; fC = fc->matrices->fc; P = fc->params; md = &(P->model_details); noGUclosure = md->noGUclosure; dangle_model = md->dangles; /* init values */ e = INF; decomp = INF; evaluate = prepare_hc_mb_def_ext(fc, &hc_dat_local); tt = vrna_get_ptype_md(S2[j], S2[i], md); if (noGUclosure && ((tt == 3) || (tt == 4))) return e; if (strands == 1) { S_i1 = S[i + 1]; S_j1 = S[j - 1]; } else { S_i1 = (sn[i] == sn[i + 1])? S[i + 1] : -1; S_j1 = (sn[j - 1] == sn[j])? S[j - 1] : -1; } /* multibranch like cofold structure with cut somewhere between i and j */ if (evaluate(i, j, i, j, VRNA_DECOMP_EXT_STEM, &hc_dat_local)) { if ((fC[i + 1]!= INF) && (fC[j - 1]!= INF)) { decomp = fC[i + 1] + fC[j - 1]; switch (dangle_model) { case 0: decomp += vrna_E_ext_stem(tt, -1, -1, P); break; case 2: decomp += vrna_E_ext_stem(tt, S_j1, S_i1, P); break; default: decomp += vrna_E_ext_stem(tt, -1, -1, P); break; } } } if (dangle_model % 2) { /* dangles == 1 || dangles == 3 */ if (evaluate(i + 1, j - 1, i + 2, j - 1, VRNA_DECOMP_EXT_EXT, &hc_dat_local)) { if ((fC[i + 2]!= INF) && (fC[j - 1]!= INF)) { en = fC[i + 2] + fC[j - 1] + vrna_E_ext_stem(tt, -1, S_i1, P); decomp = MIN2(decomp, en); } } if (evaluate(i + 1, j - 1, i + 1, j - 2, VRNA_DECOMP_EXT_EXT, &hc_dat_local)) { if ((fC[i + 1]!= INF) && (fC[j - 2]!= INF)) { en = fC[i + 1] + fC[j - 2] + vrna_E_ext_stem(tt, S_j1, -1, P); decomp = MIN2(decomp, en); } } if (evaluate(i + 1, j - 1, i + 2, j - 2, VRNA_DECOMP_EXT_EXT, &hc_dat_local)) { if ((fC[i + 2]!= INF) && (fC[j - 2]!= INF)) { en = fC[i + 2] + fC[j - 2] + vrna_E_ext_stem(tt, S_j1, S_i1, P); decomp = MIN2(decomp, en); } } } e = MIN2(e, decomp); return e; } #endif PRIVATE int E_mb_loop_fast(vrna_fold_compound_t *fc, int i, int j, int *dmli1, int *dmli2) { int decomp, e, dangle_model; vrna_param_t *P; vrna_md_t *md; vrna_callback_hc_evaluate *evaluate; struct hc_mb_def_dat hc_dat_local; struct sc_mb_dat sc_wrapper; P = fc->params; md = &(P->model_details); dangle_model = md->dangles; /* init values */ e = INF; decomp = INF; evaluate = prepare_hc_mb_def(fc, &hc_dat_local); init_sc_mb(fc, &sc_wrapper); /* do pointer magic for sliding window implementation */ if (fc->hc->type == VRNA_HC_WINDOW) { dmli1 -= i + 1; if (dmli2) dmli2 -= i + 2; } switch (dangle_model) { /* no dangles */ case 0: decomp = ml_pair_d0(fc, i, j, dmli1, evaluate, &hc_dat_local, &sc_wrapper); break; /* double dangles */ case 2: decomp = ml_pair_d2(fc, i, j, dmli1, evaluate, &hc_dat_local, &sc_wrapper); break; /* normal dangles, aka dangles = 1 || 3 */ default: decomp = ml_pair_d1(fc, i, j, dmli1, dmli2, evaluate, &hc_dat_local, &sc_wrapper); break; } free_sc_mb(&sc_wrapper); e = MIN2(e, decomp); #if 0 /* add additional cases for possible strand nicks between i and j */ if ((fc->type == VRNA_FC_TYPE_SINGLE) && (sn[i]!= sn[j])) { decomp = E_mb_loop_fake(fc, i, j); e = MIN2(e, decomp); } #endif return e; } PRIVATE int E_mb_loop_stack(vrna_fold_compound_t *fc, int i, int j) { char *ptype, **ptype_local; short **SS; unsigned int n_seq, s, *tt, sliding_window; int *c, *fML, e, decomp, en, i1k, k1j1, ij, k, *indx, turn, type, type_2, *rtype, **c_local, **fML_local; vrna_param_t *P; vrna_md_t *md; vrna_callback_hc_evaluate *evaluate; struct hc_mb_def_dat hc_dat_local; struct sc_mb_dat sc_wrapper; sliding_window = (fc->hc->type == VRNA_HC_WINDOW)? 1 : 0; n_seq = (fc->type == VRNA_FC_TYPE_SINGLE)? 1 : fc->n_seq; SS = (fc->type == VRNA_FC_TYPE_SINGLE)? NULL : fc->S; indx = fc->jindx; P = fc->params; md = &(P->model_details); turn = md->min_loop_size; c = (sliding_window)? NULL : fc->matrices->c; fML = (sliding_window)? NULL : fc->matrices->fML; c_local = (sliding_window)? fc->matrices->c_local : NULL; fML_local = (sliding_window)? fc->matrices->fML_local : NULL; ptype = (fc->type == VRNA_FC_TYPE_SINGLE)? (sliding_window? NULL : fc->ptype) : NULL; ptype_local = (fc->type == VRNA_FC_TYPE_SINGLE)? (sliding_window? fc->ptype_local : NULL) : NULL; rtype = (fc->type == VRNA_FC_TYPE_SINGLE)? &(md->rtype[0]) : NULL; tt = NULL; type = 0; ij = (sliding_window)? 0 : indx[j] + i; e = INF; evaluate = prepare_hc_mb_def(fc, &hc_dat_local); init_sc_mb(fc, &sc_wrapper); /* prepare type(s) for enclosing pair (i, j) */ if (fc->type == VRNA_FC_TYPE_COMPARATIVE) { tt = (unsigned int *)vrna_alloc(sizeof(unsigned int) * n_seq); for (s = 0; s < n_seq; s++) tt[s] = vrna_get_ptype_md(SS[s][i], SS[s][j], md); } else if (sliding_window) { type = vrna_get_ptype_window(i, j, ptype_local); } else { type = vrna_get_ptype(ij, ptype); } if (evaluate(i, j, i + 1, j - 1, VRNA_DECOMP_PAIR_ML, &hc_dat_local)) { decomp = INF; if (sliding_window) { for (k = i + 2 + turn; k < j - 2 - turn; k++) { if (evaluate(i, j, i + 1, k, VRNA_DECOMP_ML_COAXIAL, &hc_dat_local)) { en = c_local[i + 1][k - i - 1] + fML_local[k + 1][j - 1 - k - 1]; switch (fc->type) { case VRNA_FC_TYPE_SINGLE: type_2 = rtype[vrna_get_ptype_window(i + 1, k, ptype_local)]; en += P->stack[type][type_2]; break; case VRNA_FC_TYPE_COMPARATIVE: for (s = 0; s < n_seq; s++) { type_2 = vrna_get_ptype_md(SS[s][k], SS[s][i + 1], md); en += P->stack[tt[s]][type_2]; } break; } if (sc_wrapper.coaxial_cls) en += sc_wrapper.coaxial_cls(i, j, i + 1, k, &sc_wrapper); decomp = MIN2(decomp, en); } if (evaluate(i, j, k + 1, j - 1, VRNA_DECOMP_ML_COAXIAL, &hc_dat_local)) { en = c_local[k + 1][j - 1 - k - 1] + fML_local[i + 1][k - i - 1]; switch (fc->type) { case VRNA_FC_TYPE_SINGLE: type_2 = rtype[vrna_get_ptype_window(k + 1, j - 1, ptype_local)]; en += P->stack[type][type_2]; break; case VRNA_FC_TYPE_COMPARATIVE: for (s = 0; s < n_seq; s++) { type_2 = vrna_get_ptype_md(SS[s][j - 1], SS[s][k + 1], md); en += P->stack[tt[s]][type_2]; } break; } if (sc_wrapper.coaxial_cls) en += sc_wrapper.coaxial_cls(i, j, k + 1, j - 1, &sc_wrapper); decomp = MIN2(decomp, en); } } } else { k1j1 = indx[j - 1] + i + 2 + turn + 1; for (k = i + 2 + turn; k < j - 2 - turn; k++, k1j1++) { i1k = indx[k] + i + 1; if (evaluate(i, j, i + 1, k, VRNA_DECOMP_ML_COAXIAL, &hc_dat_local)) { en = c[i1k] + fML[k1j1]; switch (fc->type) { case VRNA_FC_TYPE_SINGLE: type_2 = rtype[vrna_get_ptype(i1k, ptype)]; en += P->stack[type][type_2]; break; case VRNA_FC_TYPE_COMPARATIVE: for (s = 0; s < n_seq; s++) { type_2 = vrna_get_ptype_md(SS[s][k], SS[s][i + 1], md); en += P->stack[tt[s]][type_2]; } break; } if (sc_wrapper.coaxial_cls) en += sc_wrapper.coaxial_cls(i, j, i + 1, k, &sc_wrapper); decomp = MIN2(decomp, en); } if (evaluate(i, j, k + 1, j - 1, VRNA_DECOMP_ML_COAXIAL, &hc_dat_local)) { en = c[k1j1] + fML[i1k]; switch (fc->type) { case VRNA_FC_TYPE_SINGLE: type_2 = rtype[vrna_get_ptype(k1j1, ptype)]; en += P->stack[type][type_2]; break; case VRNA_FC_TYPE_COMPARATIVE: for (s = 0; s < n_seq; s++) { type_2 = vrna_get_ptype_md(SS[s][j - 1], SS[s][k + 1], md); en += P->stack[tt[s]][type_2]; } break; } if (sc_wrapper.coaxial_cls) en += sc_wrapper.coaxial_cls(i, j, k + 1, j - 1, &sc_wrapper); decomp = MIN2(decomp, en); } } } /* no TermAU penalty if coax stack */ decomp += (2 * P->MLintern[1] + P->MLclosing) * n_seq; if (sc_wrapper.pair) decomp += sc_wrapper.pair(i, j, &sc_wrapper); e = decomp; } free_sc_mb(&sc_wrapper); free(tt); return e; } /* * compose a multibranch loop part fm[i:j] * by either c[i,j]/ggg[i,j] or fm[i:j-1] * * This function can be used for fM and fM1 */ PRIVATE int extend_fm_3p(int i, int j, int *fm, vrna_fold_compound_t *fc, vrna_callback_hc_evaluate *evaluate, struct hc_mb_def_dat *hc_dat_local, struct sc_mb_dat *sc_wrapper) { short *S, **SS, **S5, **S3; unsigned int *sn, n_seq, s, sliding_window; int en, en2, length, *indx, *c, **c_local, **fm_local, *ggg, **ggg_local, ij, type, dangle_model, with_gquad, e, u, k, cnt, with_ud; vrna_param_t *P; vrna_md_t *md; vrna_ud_t *domains_up; sliding_window = (fc->hc->type == VRNA_HC_WINDOW)? 1 : 0; n_seq = (fc->type == VRNA_FC_TYPE_SINGLE)? 1 : fc->n_seq; length = fc->length; S = (fc->type == VRNA_FC_TYPE_SINGLE)? fc->sequence_encoding : NULL; SS = (fc->type == VRNA_FC_TYPE_SINGLE)? NULL : fc->S; S5 = (fc->type == VRNA_FC_TYPE_SINGLE)? NULL : fc->S5; S3 = (fc->type == VRNA_FC_TYPE_SINGLE)? NULL : fc->S3; indx = (sliding_window)? NULL : fc->jindx; sn = fc->strand_number; c = (sliding_window)? NULL : fc->matrices->c; ggg = (sliding_window)? NULL : fc->matrices->ggg; c_local = (sliding_window)? fc->matrices->c_local : NULL; fm_local = (sliding_window)? fc->matrices->fML_local : NULL; ggg_local = (sliding_window)? fc->matrices->ggg_local : NULL; ij = (sliding_window)? 0 : indx[j] + i; P = fc->params; md = &(P->model_details); dangle_model = md->dangles; with_gquad = md->gquad; domains_up = fc->domains_up; with_ud = (domains_up && domains_up->energy_cb)? 1 : 0; e = INF; if (fm == NULL) { if (sliding_window) fm_local = fc->matrices->fML_local; else fm = fc->matrices->fML; } if (evaluate(i, j, i, j, VRNA_DECOMP_ML_STEM, hc_dat_local)) { en = (sliding_window)? c_local[i][j - i] : c[ij]; if (en!= INF) { switch (fc->type) { case VRNA_FC_TYPE_SINGLE: type = (sliding_window)? vrna_get_ptype_window(i, j, fc->ptype_local) : vrna_get_ptype( ij, fc->ptype); if (dangle_model == 2) en += E_MLstem(type, (i == 1)? S[length] : S[i - 1], S[j + 1], P); else en += E_MLstem(type, -1, -1, P); break; case VRNA_FC_TYPE_COMPARATIVE: if (dangle_model == 2) { for (s = 0; s < n_seq; s++) { type = vrna_get_ptype_md(SS[s][i], SS[s][j], md); en += E_MLstem(type, S5[s][i], S3[s][j], P); } } else { for (s = 0; s < n_seq; s++) { type = vrna_get_ptype_md(SS[s][i], SS[s][j], md); en += E_MLstem(type, -1, -1, P); } } break; } if (sc_wrapper->red_stem) en += sc_wrapper->red_stem(i, j, i, j, sc_wrapper); e = MIN2(e, en); } } if (with_gquad) { if (sn[i] == sn[j]) { en = (sliding_window)? ggg_local[i][j - i] : ggg[ij]; en += E_MLstem(0, -1, -1, P) * n_seq; e = MIN2(e, en); } } if (evaluate(i, j, i, j - 1, VRNA_DECOMP_ML_ML, hc_dat_local)) { en = (sliding_window)? fm_local[i][j - 1 - i] : fm[indx[j - 1] + i]; if (en!= INF) { en += P->MLbase * n_seq; if (sc_wrapper->red_ml) en += sc_wrapper->red_ml(i, j, i, j - 1, sc_wrapper); e = MIN2(e, en); } } if (dangle_model % 2) { if ((i + 1 < j) && (evaluate(i, j, i + 1, j, VRNA_DECOMP_ML_STEM, hc_dat_local))) { en = (sliding_window)? c_local[i + 1][j - i - 1] : c[indx[j] + i + 1]; if (en!= INF) { switch (fc->type) { case VRNA_FC_TYPE_SINGLE: type = (sliding_window)? vrna_get_ptype_window(i + 1, j, fc->ptype_local) : vrna_get_ptype(indx[j] + i + 1, fc->ptype); en += E_MLstem(type, S[i], -1, P); break; case VRNA_FC_TYPE_COMPARATIVE: for (s = 0; s < n_seq; s++) { type = vrna_get_ptype_md(SS[s][i + 1], SS[s][j], md); en += E_MLstem(type, S5[s][i + 1], -1, P); } break; } if (sc_wrapper->red_stem) en += sc_wrapper->red_stem(i, j, i + 1, j, sc_wrapper); e = MIN2(e, en); } } if ((i + 1 < j) && (evaluate(i, j, i, j - 1, VRNA_DECOMP_ML_STEM, hc_dat_local))) { en = (sliding_window)? c_local[i][j - 1 - i] : c[indx[j - 1] + i]; if (en!= INF) { switch (fc->type) { case VRNA_FC_TYPE_SINGLE: type = (sliding_window)? vrna_get_ptype_window(i, j - 1, fc->ptype_local) : vrna_get_ptype(indx[j - 1] + i, fc->ptype); en += E_MLstem(type, -1, S[j], P); break; case VRNA_FC_TYPE_COMPARATIVE: for (s = 0; s < n_seq; s++) { type = vrna_get_ptype_md(SS[s][i], SS[s][j - 1], md); en += E_MLstem(type, -1, S3[s][j], P); } break; } if (sc_wrapper->red_stem) en += sc_wrapper->red_stem(i, j, i, j - 1, sc_wrapper); e = MIN2(e, en); } } if ((i + 2 < j) && (evaluate(i, j, i + 1, j - 1, VRNA_DECOMP_ML_STEM, hc_dat_local))) { en = (sliding_window)? c_local[i + 1][j - 1 - i - 1] : c[indx[j - 1] + i + 1]; if (en!= INF) { switch (fc->type) { case VRNA_FC_TYPE_SINGLE: type = (sliding_window)? vrna_get_ptype_window(i + 1, j - 1, fc->ptype_local) : vrna_get_ptype(indx[j - 1] + i + 1, fc->ptype); en += E_MLstem(type, S[i], S[j], P); break; case VRNA_FC_TYPE_COMPARATIVE: for (s = 0; s < n_seq; s++) { type = vrna_get_ptype_md(SS[s][i + 1], SS[s][j - 1], md); en += E_MLstem(type, S5[s][i], S3[s][j], P); } break; } if (sc_wrapper->red_stem) en += sc_wrapper->red_stem(i, j, i + 1, j - 1, sc_wrapper); e = MIN2(e, en); } } } if (with_ud) { for (cnt = 0; cnt < domains_up->uniq_motif_count; cnt++) { u = domains_up->uniq_motif_size[cnt]; k = j - u + 1; if ((k > i) && (evaluate(i, j, i, k - 1, VRNA_DECOMP_ML_ML, hc_dat_local))) { en = (sliding_window)? fm_local[i][k - 1 - i] : fm[indx[k - 1] + i]; if (en!= INF) { en += u * P->MLbase * n_seq; en2 = domains_up->energy_cb(fc, k, j, VRNA_UNSTRUCTURED_DOMAIN_MB_LOOP | VRNA_UNSTRUCTURED_DOMAIN_MOTIF, domains_up->data); if (en2!= INF) { en += en2; if (sc_wrapper->red_ml) en += sc_wrapper->red_ml(i, j, i, k - 1, sc_wrapper); e = MIN2(e, en); } } } } } return e; } PRIVATE int E_ml_stems_fast(vrna_fold_compound_t *fc, int i, int j, int *fmi, int *dmli) { char *ptype, **ptype_local; short *S, **SS, **S5, **S3; unsigned int *sn, *se, n_seq, s; int k, en, decomp, mm5, mm3, type_2, k1j, length, *indx, *c, *fm, ij, dangle_model, turn, type, *rtype, circular, e, u, cnt, with_ud, sliding_window, **c_local, **fm_local; vrna_hc_t *hc; vrna_sc_t *sc; vrna_param_t *P; vrna_md_t *md; vrna_ud_t *domains_up; vrna_callback_hc_evaluate *evaluate; struct hc_mb_def_dat hc_dat_local; struct sc_mb_dat sc_wrapper; sliding_window = (fc->hc->type == VRNA_HC_WINDOW)? 1 : 0; length = (int)fc->length; ptype = (fc->type == VRNA_FC_TYPE_SINGLE)? ((sliding_window)? NULL : fc->ptype) : NULL; ptype_local = (fc->type == VRNA_FC_TYPE_SINGLE)? ((sliding_window)? fc->ptype_local : NULL) : NULL; S = (fc->type == VRNA_FC_TYPE_SINGLE)? fc->sequence_encoding : NULL; SS = (fc->type == VRNA_FC_TYPE_SINGLE)? NULL : fc->S; S5 = (fc->type == VRNA_FC_TYPE_SINGLE)? NULL : fc->S5; S3 = (fc->type == VRNA_FC_TYPE_SINGLE)? NULL : fc->S3; indx = (sliding_window)? NULL : fc->jindx; n_seq = (fc->type == VRNA_FC_TYPE_SINGLE)? 1 : fc->n_seq; sn = fc->strand_number; se = fc->strand_end; hc = fc->hc; sc = fc->sc; c = (sliding_window)? NULL : fc->matrices->c; c_local = (sliding_window)? fc->matrices->c_local : NULL; fm = (sliding_window)? NULL : fc->matrices->fML; fm_local = (sliding_window)? fc->matrices->fML_local : NULL; P = fc->params; md = &(P->model_details); ij = (sliding_window)? 0 : indx[j] + i; dangle_model = md->dangles; turn = md->min_loop_size; rtype = &(md->rtype[0]); circular = md->circ; domains_up = fc->domains_up; with_ud = (domains_up && domains_up->energy_cb)? 1 : 0; e = INF; evaluate = prepare_hc_mb_def(fc, &hc_dat_local); init_sc_mb(fc, &sc_wrapper); /* * extension with one unpaired nucleotide at the right (3' site) * or full branch of (i,j) */ e = extend_fm_3p(i, j, NULL, fc, evaluate, &hc_dat_local, &sc_wrapper); /* * extension with one unpaired nucleotide at 5' site * and all other variants which are needed for odd * dangle models */ if ((i + turn + 1 < j) && (evaluate(i, j, i + 1, j, VRNA_DECOMP_ML_ML, &hc_dat_local))) { en = (sliding_window)? fm_local[i + 1][j - i - 1] : fm[ij + 1]; if (en!= INF) { en += P->MLbase * n_seq; if (sc_wrapper.red_ml) en += sc_wrapper.red_ml(i, j, i + 1, j, &sc_wrapper); e = MIN2(e, en); } } /* extension with bound ligand on 5'site */ if (with_ud) { for (cnt = 0; cnt < domains_up->uniq_motif_count; cnt++) { u = domains_up->uniq_motif_size[cnt]; k = i + u - 1; if ((k < j) && (evaluate(i, j, k + 1, j, VRNA_DECOMP_ML_ML, &hc_dat_local))) { decomp = (sliding_window)? fm_local[i + u][j - (i + u)] : fm[ij + u]; if (decomp!= INF) { decomp += u * P->MLbase * n_seq; en = domains_up->energy_cb(fc, i, k, VRNA_UNSTRUCTURED_DOMAIN_MB_LOOP | VRNA_UNSTRUCTURED_DOMAIN_MOTIF, domains_up->data); if (en!= INF) { decomp += en; if (sc_wrapper.red_ml) decomp += sc_wrapper.red_ml(i, j, k + 1, j, &sc_wrapper); e = MIN2(e, decomp); } } } } } if (dangle_model % 2) { /* dangle_model = 1 || 3 */ mm5 = mm3 = -1; if (fc->type == VRNA_FC_TYPE_SINGLE) { if ((i > 1) || circular) mm5 = S[i]; if ((j < length) || circular) mm3 = S[j]; } if ((i + turn + 1 < j) && (evaluate(i, j, i + 1, j, VRNA_DECOMP_ML_STEM, &hc_dat_local))) { en = (sliding_window)? c_local[i + 1][j - (i + 1)] : c[ij + 1]; if (en!= INF) { en += P->MLbase * n_seq; switch (fc->type) { case VRNA_FC_TYPE_SINGLE: type = (sliding_window)? vrna_get_ptype_window(i + 1, j, ptype_local) : vrna_get_ptype( ij + 1, ptype); en += E_MLstem(type, mm5, -1, P); break; case VRNA_FC_TYPE_COMPARATIVE: for (s = 0; s < n_seq; s++) { type = vrna_get_ptype_md(SS[s][i + 1], SS[s][j], md); en += E_MLstem(type, S5[s][i + 1], -1, P); } break; } if (sc_wrapper.red_ml) en += sc_wrapper.red_ml(i, j, i + 1, j, &sc_wrapper); e = MIN2(e, en); } } if ((i + turn + 1 < j) && (evaluate(i, j, i, j - 1, VRNA_DECOMP_ML_STEM, &hc_dat_local))) { en = (sliding_window)? c_local[i][j - 1 - i] : c[indx[j - 1] + i]; if (en!= INF) { en += P->MLbase * n_seq; switch (fc->type) { case VRNA_FC_TYPE_SINGLE: type = (sliding_window)? vrna_get_ptype_window(i, j - 1, ptype_local) : vrna_get_ptype( indx[j - 1] + i, ptype); en += E_MLstem(type, -1, mm3, P); break; case VRNA_FC_TYPE_COMPARATIVE: for (s = 0; s < n_seq; s++) { type = vrna_get_ptype_md(SS[s][i], SS[s][j - 1], md); en += E_MLstem(type, -1, S3[s][j - 1], P); } break; } if (sc_wrapper.red_ml) en += sc_wrapper.red_ml(i, j, i, j - 1, &sc_wrapper); e = MIN2(e, en); } } if ((i + turn + 2 < j) && (evaluate(i, j, i + 1, j - 1, VRNA_DECOMP_ML_STEM, &hc_dat_local))) { en = (sliding_window)? c_local[i + 1][j - 1 - (i + 1)] : c[indx[j - 1] + i + 1]; if (en!= INF) { en += 2 * P->MLbase * n_seq; switch (fc->type) { case VRNA_FC_TYPE_SINGLE: type = (sliding_window)? vrna_get_ptype_window(i + 1, j - 1, ptype_local) : vrna_get_ptype( indx[j - 1] + i + 1, ptype); en += E_MLstem(type, mm5, mm3, P); break; case VRNA_FC_TYPE_COMPARATIVE: for (s = 0; s < n_seq; s++) { type = vrna_get_ptype_md(SS[s][i + 1], SS[s][j - 1], md); en += E_MLstem(type, S5[s][i + 1], S3[s][j - 1], P); } break; } if (sc_wrapper.red_ml) en += sc_wrapper.red_ml(i, j, i + 1, j - 1, &sc_wrapper); e = MIN2(e, en); } } /* end special cases for dangles == 1 || dangles == 3 */ } /* modular decomposition -------------------------------*/ if (sliding_window) { fmi -= i; dmli -= i; } /* use fmi pointer that we may extend to include hard/soft constraints if necessary */ int *fmi_tmp = fmi; if (hc->f) { fmi_tmp = (int *)vrna_alloc(sizeof(int) * (j - i + 2)); fmi_tmp -= i; /* copy data */ for (k = i + 1 + turn; k <= j - 2 - turn; k++) fmi_tmp[k] = fmi[k]; /* mask unavailable decompositions */ for (k = i + 1 + turn; k <= j - 2 - turn; k++) if (!hc->f(i, j, k, k + 1, VRNA_DECOMP_ML_ML_ML, hc->data)) fmi_tmp[k] = INF; } if (sc_wrapper.decomp_ml) { if (fmi_tmp == fmi) { fmi_tmp = (int *)vrna_alloc(sizeof(int) * (j - i + 2)); fmi_tmp -= i; /* copy data */ for (k = i + 1 + turn; k <= j - 2 - turn; k++) fmi_tmp[k] = fmi[k]; } for (k = i + 1 + turn; k <= j - 2 - turn; k++) if (fmi_tmp[k]!= INF) fmi_tmp[k] += sc_wrapper.decomp_ml(i, j, k, k + 1, &sc_wrapper); } /* modular decomposition -------------------------------*/ if (sliding_window) { for (decomp = INF, k = i + 1 + turn; k <= j - 2 - turn; k++) { if ((fmi_tmp[k]!= INF) && (fm_local[k + 1][j - (k + 1)]!= INF)) { en = fmi_tmp[k] + fm_local[k + 1][j - (k + 1)]; decomp = MIN2(decomp, en); } } } else { decomp = INF; k = i + turn + 1; if (k >= j) k = j - 1; k1j = indx[j] + k + 1; /* * loop over entire range but skip decompositions with in-between strand nick, * this should be faster than evaluating hard constraints callback for each * decomposition */ while (1) { int last_nt = se[sn[k]]; /* go to last nucleotide of current strand */ if (last_nt > j - turn - 2) last_nt = j - turn - 2; /* at most go to last possible decomposition split before reaching j */ if (last_nt < i) last_nt = i; /* do not start before i */ const int count = last_nt - k; en = vrna_fun_zip_add_min(fmi_tmp + k, fm + k1j, count); decomp = MIN2(decomp, en); /* advance counters by processed subsegment and add 1 for the split point between strands */ k += count + 1; k1j += count + 1; if (k > j - turn - 2) break; } } /* end modular decomposition -------------------------------*/ if (fmi_tmp!= fmi) { fmi_tmp += i; free(fmi_tmp); } dmli[j] = decomp; /* store for use in fast ML decompositon */ e = MIN2(e, decomp); /* coaxial stacking */ if (dangle_model == 3) { /* additional ML decomposition as two coaxially stacked helices */ if (sliding_window) { /* additional ML decomposition as two coaxially stacked helices */ for (decomp = INF, k = i + 1 + turn; k <= j - 2 - turn; k++) { if (evaluate(i, k, k + 1, j, VRNA_DECOMP_ML_COAXIAL_ENC, &hc_dat_local)) { type = rtype[vrna_get_ptype_window(i, k, ptype_local)]; type_2 = rtype[vrna_get_ptype_window(k + 1, j, ptype_local)]; en = c_local[i][k - i] + c_local[k + 1][j - k - 1] + P->stack[type][type_2]; if (sc) if (sc->f) en += sc->f(i, k, k + 1, j, VRNA_DECOMP_ML_COAXIAL_ENC, sc->data); decomp = MIN2(decomp, en); } } } else { int ik; k1j = indx[j] + i + turn + 2; decomp = INF; k = i + turn + 1; if (k >= j) k = j - 1; /* * loop over entire range but skip decompositions with in-between strand nick, * this should be faster than evaluating hard constraints callback for each * decomposition */ while (1) { int last_nt = se[sn[k - 1]]; /* go to last nucleotide of current strand */ if (last_nt > j - turn - 2) last_nt = j - turn - 2; /* at most go to last possible decomposition split before reaching j */ if (last_nt < i) last_nt = i; /* do not start before i */ const int stop = last_nt; for (; k <= stop; k++, k1j++) { ik = indx[k] + i; if (evaluate(i, k, k + 1, j, VRNA_DECOMP_ML_COAXIAL_ENC, &hc_dat_local)) { en = c[ik] + c[k1j]; switch (fc->type) { case VRNA_FC_TYPE_SINGLE: type = rtype[vrna_get_ptype(ik, ptype)]; type_2 = rtype[vrna_get_ptype(k1j, ptype)]; en += P->stack[type][type_2]; break; case VRNA_FC_TYPE_COMPARATIVE: for (s = 0; s < n_seq; s++) { type = vrna_get_ptype_md(SS[s][k], SS[s][i], md); type_2 = vrna_get_ptype_md(SS[s][j], SS[s][k + 1], md); en += P->stack[type][type_2]; } break; } if (sc_wrapper.coaxial_enc) en += sc_wrapper.coaxial_enc(i, k, k + 1, j, &sc_wrapper); decomp = MIN2(decomp, en); } } k++; k1j++; if (k > j - turn - 2) break; } } /* no TermAU penalty if coax stack */ decomp += 2 * P->MLintern[1] * n_seq; #if 0 /* * This is needed for Y shaped ML loops with coax stacking of * interior pairts, but backtracking will fail if activated */ DMLi[j] = MIN2(DMLi[j], decomp); DMLi[j] = MIN2(DMLi[j], DMLi[j - 1] + P->MLbase); DMLi[j] = MIN2(DMLi[j], DMLi1[j] + P->MLbase); new_fML = MIN2(new_fML, DMLi[j]); #endif e = MIN2(e, decomp); } if ((fc->aux_grammar) && (fc->aux_grammar->cb_aux_m)) { en = fc->aux_grammar->cb_aux_m(fc, i, j, fc->aux_grammar->data); e = MIN2(e, en); } fmi[j] = e; free_sc_mb(&sc_wrapper); return e; } ======================= File: src/ViennaRNA/cofold.h ======================= <filename>src/ViennaRNA/cofold.h #ifndef VIENNA_RNA_PACKAGE_COFOLD_H #define VIENNA_RNA_PACKAGE_COFOLD_H #include <ViennaRNA/datastructures/basic.h> #include <ViennaRNA/params/basic.h> #include <ViennaRNA/mfe.h> #ifdef VRNA_WARN_DEPRECATED # if defined(__clang__) # define DEPRECATED(func, msg) func __attribute__ ((deprecated("", msg))) # elif defined(__GNUC__) # define DEPRECATED(func, msg) func __attribute__ ((deprecated(msg))) # else # define DEPRECATED(func, msg) func # endif #else # define DEPRECATED(func, msg) func #endif /** * @file cofold.h * @ingroup mfe_global_deprecated * @brief MFE implementations for RNA-RNA interaction */ #ifndef VRNA_DISABLE_BACKWARD_COMPATIBILITY /** * @brief Compute the minimum free energy of two interacting RNA molecules * * The code is analog to the fold() function. If #cut_point ==-1 results * should be the same as with fold(). * * @ingroup mfe_global_deprecated * * @deprecated use vrna_mfe_dimer() instead * * @param sequence The two sequences concatenated * @param structure Will hold the barcket dot structure of the dimer molecule * @return minimum free energy of the structure */ DEPRECATED(float cofold(const char *sequence, char *structure), "Use vrna_cofold() instead"); /** * @brief Compute the minimum free energy of two interacting RNA molecules * * @deprecated use vrna_mfe_dimer() instead * * @ingroup mfe_global_deprecated */ DEPRECATED(float cofold_par(const char *string, char *structure, vrna_param_t *parameters, int is_constrained), "Use the new API and vrna_mfe_dimer() instead"); /** * @brief Free memory occupied by cofold() * * @deprecated This function will only free memory allocated by a prior call of cofold() or cofold_par(). * See vrna_mfe_dimer() for how to use the new API * * @note folding matrices now reside in the fold compound, and should be free'd there * @see vrna_fc_destroy(), vrna_mfe_dimer() * * @ingroup mfe_global_deprecated */ DEPRECATED(void free_co_arrays(void), "This function is obsolete"); /** * @brief Recalculate parameters * @deprecated See vrna_params_subst() for an alternative using the new API * * @ingroup mfe_global_deprecated */ DEPRECATED(void update_cofold_params(void), "This function is obsolete"); /** * @brief Recalculate parameters * @deprecated See vrna_params_subst() for an alternative using the new API * * @ingroup mfe_global_deprecated */ DEPRECATED(void update_cofold_params_par(vrna_param_t *parameters), "Use the new API with vrna_fold_compound_t instead"); /** * @brief Export the arrays of partition function cofold (with gquadruplex support) * * Export the cofold arrays for use e.g. in the concentration * Computations or suboptimal secondary structure backtracking * * @deprecated folding matrices now reside within the fold compound. Thus, this function will * only work in conjunction with a prior call to cofold() or cofold_par() * * @see vrna_mfe_dimer() for the new API * * @ingroup mfe_global_deprecated * @param f5_p A pointer to the 'f5' array, i.e. array conatining best free energy in interval [1,j] * @param c_p A pointer to the 'c' array, i.e. array containing best free energy in interval [i,j] given that i pairs with j * @param fML_p A pointer to the 'M' array, i.e. array containing best free energy in interval [i,j] for any multiloop segment with at least one stem * @param fM1_p A pointer to the 'M1' array, i.e. array containing best free energy in interval [i,j] for multiloop segment with exactly one stem * @param fc_p A pointer to the 'fc' array, i.e. array... * @param ggg_p A pointer to the 'ggg' array, i.e. array containing best free energy of a gquadruplex delimited by [i,j] * @param indx_p A pointer to the indexing array used for accessing the energy matrices * @param ptype_p A pointer to the ptype array containing the base pair types for each possibility (i,j) */ DEPRECATED(void export_cofold_arrays_gq(int **f5_p, int **c_p, int **fML_p, int **fM1_p, int **fc_p, int **ggg_p, int **indx_p, char **ptype_p), "Use the new API with vrna_fold_compound_t instead"); /** * @brief Export the arrays of partition function cofold * * Export the cofold arrays for use e.g. in the concentration * Computations or suboptimal secondary structure backtracking * * @deprecated folding matrices now reside within the #vrna_fold_compound_t. Thus, this function will * only work in conjunction with a prior call to the deprecated functions cofold() or cofold_par() * * @see vrna_mfe_dimer() for the new API * * @ingroup mfe_global_deprecated * @param f5_p A pointer to the 'f5' array, i.e. array conatining best free energy in interval [1,j] * @param c_p A pointer to the 'c' array, i.e. array containing best free energy in interval [i,j] given that i pairs with j * @param fML_p A pointer to the 'M' array, i.e. array containing best free energy in interval [i,j] for any multiloop segment with at least one stem * @param fM1_p A pointer to the 'M1' array, i.e. array containing best free energy in interval [i,j] for multiloop segment with exactly one stem * @param fc_p A pointer to the 'fc' array, i.e. array... * @param indx_p A pointer to the indexing array used for accessing the energy matrices * @param ptype_p A pointer to the ptype array containing the base pair types for each possibility (i,j) */ DEPRECATED(void export_cofold_arrays(int **f5_p, int **c_p, int **fML_p, int **fM1_p, int **fc_p, int **indx_p, char **ptype_p), "Use the new API with vrna_fold_compound_t instead"); /** * allocate arrays for folding * @deprecated{This function is obsolete and will be removed soon!} * * @ingroup mfe_global_deprecated */ DEPRECATED(void initialize_cofold(int length), "This function is obsolete"); #endif #endif ======================= File: src/ViennaRNA/dp_matrices.c ======================= <reponame>tsjzz/ViennaRNA /** \file dp_matrices.c **/ /* * Dynamic Programming matrix related functions * * This file contains everything necessary to * obtain and destroy data structures representing * dynamic programming (DP) matrices used in the folding * recurrences throughout the VienneRNA paclage * * c <NAME> * * ViennaRNA package */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdlib.h> #include <string.h> #include <math.h> #include "ViennaRNA/datastructures/basic.h" #include "ViennaRNA/model.h" #include "ViennaRNA/utils/basic.h" #include "ViennaRNA/gquad.h" #include "ViennaRNA/dp_matrices.h" /* ################################# # PRIVATE MACROS # ################################# */ /* the definitions below indicate which arrays should be allocated upon retrieval of a matrices data structure */ #define ALLOC_NOTHING 0 #define ALLOC_F 1 #define ALLOC_F5 2 #define ALLOC_F3 4 #define ALLOC_FC 8 #define ALLOC_C 16 #define ALLOC_FML 32 #define ALLOC_PROBS 256 #define ALLOC_AUX 512 #define ALLOC_CIRC 1024 #define ALLOC_MULTISTRAND 2048 #define ALLOC_UNIQ 4096 #define ALLOC_MFE_DEFAULT (ALLOC_F5 | ALLOC_C | ALLOC_FML) #define ALLOC_MFE_LOCAL (ALLOC_F3 | ALLOC_C | ALLOC_FML) #define ALLOC_PF_WO_PROBS (ALLOC_F | ALLOC_C | ALLOC_FML) #define ALLOC_PF_DEFAULT (ALLOC_PF_WO_PROBS | ALLOC_PROBS | ALLOC_AUX) /* ################################# # GLOBAL VARIABLES # ################################# */ /* ################################# # PRIVATE VARIABLES # ################################# */ /* ################################# # PRIVATE FUNCTION DECLARATIONS # ################################# */ PRIVATE unsigned int get_mx_alloc_vector(vrna_fold_compound_t *fc, vrna_mx_type_e type, unsigned int options); PRIVATE unsigned int get_mx_mfe_alloc_vector_current(vrna_mx_mfe_t *mx, vrna_mx_type_e mx_type); PRIVATE unsigned int get_mx_pf_alloc_vector_current(vrna_mx_pf_t *mx, vrna_mx_type_e mx_type); PRIVATE void mfe_matrices_free_default(vrna_mx_mfe_t *self); PRIVATE void mfe_matrices_free_window(vrna_mx_mfe_t *self, unsigned int length, unsigned int window_size); PRIVATE void mfe_matrices_free_2Dfold(vrna_mx_mfe_t *self, unsigned int length, int min_loop_size, int *indx); PRIVATE void pf_matrices_free_default(vrna_mx_pf_t *self); PRIVATE void pf_matrices_free_window(vrna_mx_pf_t *self, unsigned int length, unsigned int window_size); PRIVATE void pf_matrices_free_2Dfold(vrna_mx_pf_t *self, unsigned int length, int turn, int *indx, int *jindx); PRIVATE int add_pf_matrices(vrna_fold_compound_t *vc, vrna_mx_type_e type, unsigned int alloc_vector); PRIVATE int add_mfe_matrices(vrna_fold_compound_t *vc, vrna_mx_type_e type, unsigned int alloc_vector); PRIVATE vrna_mx_mfe_t * init_mx_mfe_default(vrna_fold_compound_t *fc, unsigned int alloc_vector); PRIVATE vrna_mx_mfe_t * init_mx_mfe_window(vrna_fold_compound_t *fc, unsigned int alloc_vector); PRIVATE vrna_mx_mfe_t * init_mx_mfe_2Dfold(vrna_fold_compound_t *fc, unsigned int alloc_vector); PRIVATE INLINE void nullify_mfe(vrna_mx_mfe_t *mx); PRIVATE vrna_mx_pf_t * init_mx_pf_default(vrna_fold_compound_t *fc, unsigned int alloc_vector); PRIVATE vrna_mx_pf_t * init_mx_pf_window(vrna_fold_compound_t *fc, unsigned int alloc_vector); PRIVATE vrna_mx_pf_t * init_mx_pf_2Dfold(vrna_fold_compound_t *fc, unsigned int alloc_vector); PRIVATE INLINE void nullify_pf(vrna_mx_pf_t *mx); /* ################################# # BEGIN OF FUNCTION DEFINITIONS # ################################# */ PUBLIC void vrna_mx_mfe_free(vrna_fold_compound_t *vc) { if (vc) { vrna_mx_mfe_t *self = vc->matrices; if (self) { switch (self->type) { case VRNA_MX_DEFAULT: mfe_matrices_free_default(self); break; case VRNA_MX_WINDOW: mfe_matrices_free_window(self, vc->length, vc->window_size); break; case VRNA_MX_2DFOLD: mfe_matrices_free_2Dfold(self, vc->length, vc->params->model_details.min_loop_size, vc->iindx); break; default: /* do nothing */ break; } free(self); vc->matrices = NULL; } } } PUBLIC void vrna_mx_pf_free(vrna_fold_compound_t *vc) { if (vc) { vrna_mx_pf_t *self = vc->exp_matrices; if (self) { switch (self->type) { case VRNA_MX_DEFAULT: pf_matrices_free_default(self); break; case VRNA_MX_WINDOW: pf_matrices_free_window(self, vc->length, vc->window_size); break; case VRNA_MX_2DFOLD: pf_matrices_free_2Dfold(self, vc->length, vc->exp_params->model_details.min_loop_size, vc->iindx, vc->jindx); break; default: /* do nothing */ break; } free(self->expMLbase); free(self->scale); free(self); vc->exp_matrices = NULL; } } } PUBLIC int vrna_mx_add(vrna_fold_compound_t *vc, vrna_mx_type_e mx_type, unsigned int options) { int ret; ret = 1; if (options & VRNA_OPTION_MFE) ret &= vrna_mx_mfe_add(vc, mx_type, options); if (options & VRNA_OPTION_PF) ret &= vrna_mx_pf_add(vc, mx_type, options); return ret; } PUBLIC int vrna_mx_mfe_add(vrna_fold_compound_t *vc, vrna_mx_type_e mx_type, unsigned int options) { unsigned int mx_alloc_vector; if (vc->params) { options |= VRNA_OPTION_MFE; mx_alloc_vector = get_mx_alloc_vector(vc, mx_type, options); vrna_mx_mfe_free(vc); return add_mfe_matrices(vc, mx_type, mx_alloc_vector); } return 0; } PUBLIC int vrna_mx_pf_add(vrna_fold_compound_t *vc, vrna_mx_type_e mx_type, unsigned int options) { unsigned int mx_alloc_vector; if (vc->exp_params) { mx_alloc_vector = get_mx_alloc_vector(vc, mx_type, options | VRNA_OPTION_PF); vrna_mx_pf_free(vc); return add_pf_matrices(vc, mx_type, mx_alloc_vector); } return 0; } PUBLIC int vrna_mx_prepare(vrna_fold_compound_t *vc, unsigned int options) { int ret, realloc; unsigned int mx_alloc_vector, mx_alloc_vector_current; vrna_mx_type_e mx_type; ret = 1; if (vc) { /* check whether we have the correct DP matrices attached, and if there is * enough memory allocated */ if (options & VRNA_OPTION_MFE) { /* prepare for MFE computation */ if (options & VRNA_OPTION_WINDOW) /* Windowing approach, a.k.a. locally optimal */ mx_type = VRNA_MX_WINDOW; else /* default is regular MFE */ mx_type = VRNA_MX_DEFAULT; if (vc->strands > 1) options |= VRNA_OPTION_HYBRID; realloc = 0; if (!vc->matrices || (vc->matrices->type!= mx_type) || (vc->matrices->length < vc->length)) { realloc = 1; } else { mx_alloc_vector = get_mx_alloc_vector(vc, mx_type, options); mx_alloc_vector_current = get_mx_mfe_alloc_vector_current(vc->matrices, mx_type); if ((mx_alloc_vector & mx_alloc_vector_current)!= mx_alloc_vector) realloc = 1; } if (realloc) /* Add DP matrices, if not they are not present */ ret &= vrna_mx_mfe_add(vc, mx_type, options); } if (options & VRNA_OPTION_PF) { /* prepare for partition function computations */ if (!vc->exp_params) /* return failure if exp_params data is not present */ return 0; if (options & VRNA_OPTION_WINDOW) /* Windowing approach, a.k.a. locally optimal */ mx_type = VRNA_MX_WINDOW; else /* default is regular MFE */ mx_type = VRNA_MX_DEFAULT; if (vc->strands > 1) options |= VRNA_OPTION_HYBRID; realloc = 0; /* Add DP matrices, if not they are not present */ if (!vc->exp_matrices || (vc->exp_matrices->type!= mx_type) || (vc->exp_matrices->length < vc->length)) { realloc = 1; } else { mx_alloc_vector = get_mx_alloc_vector
1,508
var sublistField_custrecord445 = objRecord_LoadCustomer.getSublistValue({ sublistId: idSublista, fieldId: "custrecord445", line: i }) || ""; var sublistField_custrecord444 = objRecord_LoadCustomer.getSublistText({ sublistId: idSublista, fieldId: "custrecord444", line: i }) || ""; var sublistField_custrecord446 = objRecord_LoadCustomer.getSublistText({ sublistId: idSublista, fieldId: "custrecord446", line: i }) || ""; var sublistField_custrecord447 = objRecord_LoadCustomer.getSublistValue({ sublistId: idSublista, fieldId: "custrecord447", line: i }) || ""; if (sublistField_custrecord447!= "") { customerAge = getAge(sublistField_custrecord447) } else { customerAge = ""; } var sublistField_custrecord449 = objRecord_LoadCustomer.getSublistValue({ sublistId: idSublista, fieldId: "custrecord449", line: i }) || null; if (sublistField_custrecord449!= null) { var obj_FirmaMedico = file.load({ id: sublistField_custrecord449 }); file_content_FirmaMedico = "data:image/png;base64," + obj_FirmaMedico.getContents(); } else { file_content_FirmaMedico = ""; } var daysExpirationPrescription = getExpirationDays(sublistField_custrecord443, sublistField_custrecord445); responseData[i] = { "idReceta": parseInt(i) + 1, "data": [{ "nombrePaciente": nameCustomer, "nacimientoPaciente": sublistField_custrecord447, "edadPaciente": customerAge, "fechaReceta": sublistField_custrecord443, "vencimientoRecetaFecha": sublistField_custrecord445, "vencimientoReceta": daysExpirationPrescription, "medicamentosPaciente": sublistField_custrecord444, "observacionesPaciente": sublistField_custrecord446, "firmaMed": file_content_FirmaMedico }] }; } } return responseData; //TODO: Save Data on "Receta" } else if (param_idTransaction == "save" && errorLoad == false) { if (param_custrecord443!= "" && param_custrecord445!= "") { var expirationDate = getExpirationDate(param_custrecord443, param_custrecord445); // obtener fecha de validez } objRecord_LoadCustomer.selectNewLine({ sublistId: idSublista }); if (param_custrecord447!= "") { // Fecha de Nacimiento del Cliente preDate = param_custrecord447.replace("-","/"); preDate = preDate.replace("-","/"); bornDate = new Date(preDate); param_custrecord447 = bornDate.getDate() + "/" + (bornDate.getMonth() + 1) + "/" + bornDate.getFullYear(); objRecord_LoadCustomer.setCurrentSublistText({ sublistId: idSublista, fieldId: 'custrecord447', text: param_custrecord447 }); } if (param_custrecord443!= "") { // Fecha de creación de la receta preDate = param_custrecord443.replace("-","/"); preDate = preDate.replace("-","/"); prescriptionDate = preDate.substring(0,10); prescriptionDate = new Date(prescriptionDate); param_custrecord443 = prescriptionDate.getDate() + "/" + (prescriptionDate.getMonth() + 1) + "/" + prescriptionDate.getFullYear(); objRecord_LoadCustomer.setCurrentSublistText({ sublistId: idSublista, fieldId: 'custrecord443', text: param_custrecord443 }); } if (expirationDate!= "") { // Fecha de vigencia de la receta param_custrecord445 = new Date(expirationDate); log.debug("445", expirationDate); objRecord_LoadCustomer.setCurrentSublistValue({ sublistId: idSublista, fieldId: 'custrecord445', value: param_custrecord445 }); } if (param_custrecord444!= "") { // Medicamentos objRecord_LoadCustomer.setCurrentSublistValue({ sublistId: idSublista, fieldId: 'custrecord444', value: param_custrecord444 }); } if (param_custrecord446!= "") { // Observaciones/indicaciones objRecord_LoadCustomer.setCurrentSublistValue({ sublistId: idSublista, fieldId: 'custrecord446', value: param_custrecord446 }); } if (param_custrecord449!= "") { // Firma del medico para esta receta var image_url_img_firmaRx = https.get({ url: param_custrecord449 }); var objNew_img_firma = file.create({ name: param_idCustomer + "_" + new Date() + "_image_firma", fileType: "PNGIMAGE", contents: image_url_img_firmaRx.body, encoding: file.Encoding.UTF8, folder: 5478419 }); var idNew_img_firma = objNew_img_firma.save(); objRecord_LoadCustomer.setCurrentSublistValue({ sublistId: idSublista, fieldId: 'custrecord449', value: idNew_img_firma }); } objRecord_LoadCustomer.commitLine({ sublistId: idSublista }); try { var idLoadCustomer = objRecord_LoadCustomer.save({ enableSourcing: true, ignoreMandatoryFields: true }); return { "SUCCESS_CREATE_PRESCRIPTION": idLoadCustomer } } catch (error) { return { "ERROR_CREATE_PRESCRIPTION": error } } //TODO: ERROR in get or save method } else { return { "error": 'Please fill the param "idTransaction" with values "get" or "save"' } } } /** * Funcion que devuelve la fecha de vencimiento a partir de la fecha de creación de receta y los días de validez * @param {date} dateCreation Fecha de creación de la recetas * @param {int} daysExpiration Dias de validez de la receta */ function getExpirationDate(dateCreation, daysExpiration) { preDate = dateCreation.replace("-","/"); preDate = preDate.replace("-","/"); prescriptionDate = preDate.substring(0,10); var fecha = new Date(prescriptionDate); var dias = parseInt(daysExpiration); fecha.setDate(fecha.getDate() + dias); newMonth = parseInt(fecha.getMonth()) + 1; var expiration = fecha.getFullYear() + "/" + newMonth + "/" + fecha.getDate(); return expiration; } /** * Funcion que devuelve los dias de validez de una receta a partir de la fecha de creación de la receta y la fecha de vencimiento * @param {date} dateCreation Fecha de creación de la recetas * @param {int} daysExpiration Dias de validez de la receta */ function getExpirationDays(dateCreation, dateExpiration) { var dC = new Date(dateCreation); var dE = new Date(dateExpiration); var intC = parseInt(dC.getDate()) + (parseInt(dC.getMonth() + 1) * 30) + (parseInt(dC.getFullYear()) * 365.25); var intE = parseInt(dE.getDate()) + (parseInt(dE.getMonth() + 1) * 30) + (parseInt(dE.getFullYear()) * 365.25); var daysExpiration = intE - intC; return daysExpiration; } /** * Funcion que retorna la los años enteros transcurridos entre dos fechas * @param {date} fechaNacimiento - se ingresa la fecha inicial desde la que se quiere calcular, por ejemplo: una fecha de nacimiento */ function getAge(fechaNacimiento) { var edad; if (fechaNacimiento == "") { edad = 0; } else { var fN = new Date(fechaNacimiento); var bornDay = fN.getDate(); var bornMonth = fN.getMonth() + 1; var bornYear = fN.getFullYear(); var d = new Date(); var currentDay = d.getDate(); var currentMonth = d.getMonth() + 1; var currentYear = d.getFullYear(); //calculo de las variables para obtener los días transcurridos entre ambas fechas var calcAnio = (parseInt(currentYear) - parseInt(bornYear)) * 365.25; var calcMes = (parseInt(currentMonth) - parseInt(bornMonth)) * 30; var calcDia = (parseInt(currentDay) - parseInt(bornDay)) * 1; var calcEdad = (calcAnio + calcMes + calcDia) / 365.25; //redondeo al entero proximo menor para obtener los años actuales entero entre las dos fechas //y no cambia a menos que la fecha reciente cumpla un año entero relativo a la fecha antigua edad = Math.floor(calcEdad); edad = (isNaN(edad) == true)? "" : edad; } return edad; } return { get: doGet, post: doPost }; }); ======================= File: ue_NetSoft.js ======================= <filename>ue_NetSoft.js /** * @NApiVersion 2.x * @NScriptType UserEventScript * @NModuleScope SameAccount */ define(['N/redirect'], function(redirect) { function beforeLoad(context) { if(context.type == "edit") { context.form.addButton({id: 'custpage_test1', label: 'Boton V2', functionName: 'function1()'}); context.form.clientScriptField = '1977016'; // logging for test log.debug("title", "function beforeLoad(context)"); //context.newRecord.setValue({fieldId: 'comments', value: 'test nota'}); var fieldNota = context.form.getField({id: 'comments'}); log.debug("before load edit", "context.form.getField({id: 'comments'});" + fieldNota); var newField = context.form.addField({id: 'custpage_newfield', label: 'NEW FIELD TEST', type: 'text'}); newField.defaultValue = "default value test"; //fieldNota.updateDisplayType({displayType: 'disabled'}); } //The page will redirect to Suitelet on After Submit function and pass the parameter/s to it /*redirect.toSuitelet({ scriptId: 'customscript913', deploymentId: 'customdeploy1', parameters: { 'recordId':'1273' } });*/ } function beforeSubmit(context) { if(context.type == "edit") { // logging for test log.debug("title", "function beforeSubmit(context)"); //context.newRecord.setValue({fieldId: 'comments', value: 'test nota'}); var getDefaultVal = context.newRecord.getValue({fieldId: 'custpage_newfield'}); log.debug("var getDefaultVal ", getDefaultVal); var getVal = context.newRecord.getValue({fieldId: 'comments'}); if(getVal == "1") throw "¡(beforeSubmit edit) El valor de nota no puede ser 1!"; /*else throw "¡(beforeSubmit edit) El valor de nota es: " + getVal + "!";*/ } } function afterSubmit(context) { // logging for test log.debug("title", "function afterSubmit(context)"); var getVal = context.newRecord.getValue({fieldId: 'comments'}); if(getVal == "redirect") { redirect.toRecord({ id: '411945', type: 'employee' }); } } return { afterSubmit: afterSubmit, beforeLoad: beforeLoad, beforeSubmit: beforeSubmit }; }); ======================= File: osva_CTests.js ======================= /** * @NApiVersion 2.x * @NScriptType ClientScript */ define(['N/ui/dialog'], function(dialog) { function pageInit(context) { } function muestraDatos(paramTest) { var datos = paramTest var options = { title: "Muestra Datos", message: datos //Display the value using an alert dialog }; dialog.alert(options) } return { pageInit: pageInit, muestraDatos: muestraDatos }; }); ======================= File: ue_aprobacionOrdenCompra.js ======================= <reponame>WizyOs/kaloniScripts /** * @NApiVersion 2.x * @NScriptType UserEventScript * @NModuleScope Public */ define(['N/record', 'N/runtime', 'N/redirect', 'N/log'], function(record, runtime, redirect, log) { /* */ function beforeLoad(context) { if(context.type == "view") { /*var recordCaseId = context.newRecord.id; var objRecord = record.load({type: 'SUPPORTCASE', id: recordCaseId, isDynamic: false}); var customform_id = objRecord.getValue({fieldId: 'customform'}); var userObj = runtime.getCurrentUser(); var bandera = false;*/ var currentOrdenCompraId = context.newRecord.id; var rec = record.load({type: 'purchaseorder', id: currentOrdenCompraId}); var approvalstatus = rec.getValue({fieldId: 'approvalstatus'}); log.debug('approvalstatus: ', approvalstatus); var employee = rec.getValue({fieldId: 'employee'}); log.debug('employee: ', employee); var subsidiary = rec.getValue({fieldId:'subsidiary'}); log.debug('subsidiary: ', subsidiary); var total = rec.getValue({fieldId: 'total'}); log.debug('total: ', total); var jORGE_DIAZ_check = context.form.getField({id: 'custbody132'}).defaultValue; log.debug('jORGE_DIAZ_check: ', jORGE_DIAZ_check); var pATRICIA_SANCHEZ_check = context.form.getField({id: 'custbody137'}).defaultValue; log.debug('pATRICIA_SANCHEZ_check: ', pATRICIA_SANCHEZ_check); var sILVIA_MATA_check = context.form.getField({id: 'custbody138'}).defaultValue; log.debug('sILVIA_MATA_check: ', sILVIA_MATA_check); var mICHELLE_ALCANTARA_check = context.form.getField({id: 'custbody139'}).defaultValue; log.debug('mICHELLE_ALCANTARA_check: ', mICHELLE_ALCANTARA_check); var osvaldo_Tinoco_check = context.form.getField({id: 'custbody153'}).defaultValue; log.debug('osvaldo_Tinoco_check: ', osvaldo_Tinoco_check); var vICENTE_CORTINA_check = context.form.getField({id: 'custbody133'}).defaultValue; log.debug('vICENTE_CORTINA_check: ', vICENTE_CORTINA_check); var aBRAHAM_FIGUEROA_check = context.form.getField({id: 'custbody141'}).defaultValue; log.debug('aBRAHAM_FIGUEROA_check: ', aBRAHAM_FIGUEROA_check); var zULMA_APONTE_check = context.form.getField({id: 'custbody140'}).defaultValue; log.debug('zULMA_APONTE_check: ', zULMA_APONTE_check); var eDITH_GUEVARA_check = context.form.getField({id: 'custbody134'}).defaultValue; log.debug('eDITH_GUEVARA_check: ', eDITH_GUEVARA_check); var aLEJANDRA_PORRAS_check = context.form.getField({id: 'custbody135'}).defaultValue; log.debug('aLEJANDRA_PORRAS_check: ', aLEJANDRA_PORRAS_check); context.form.getField('custbody132').updateDisplayType({displayType:'hidden'}); // JORGE DÍAZ (LIMITE 5,000): context.form.getField('custbody137').updateDisplayType({displayType:'hidden'}); // PATRICIA SÁNCHEZ (LIMITE 5,000): context.form.getField('custbody138').updateDisplayType({displayType:'hidden'}); // SILVIA MATA (LIMITE 5,000): context.form.getField('custbody139').updateDisplayType({displayType:'hidden'}); // <NAME> (LIMITE 5,000): context.form.getField('custbody153').updateDisplayType({displayType:'hidden'}); // Osvaldo Tinoco (LIMITE 5,000): context.form.getField('custbody133').updateDisplayType({displayType:'hidden'}); // VICENTE CORTINA. (LIMITE 10,000): context.form.getField('custbody141').updateDisplayType({displayType:'hidden'}); // ABRAHAM FIGUEROA (LIMITE 10,000): context.form.getField('custbody140').updateDisplayType({displayType:'hidden'}); // ZULMA APONTE (LIMITE 19,000): context.form.getField('custbody134').updateDisplayType({displayType:'hidden'}); // EDITH GUEVARA (LIMITE 20,000): context.form.getField('custbody135').updateDisplayType({displayType:'hidden'}); // ALEJANDRA PORRAS (MAYOR A 50,000): if(employee == "62837") // <NAME> { context.form.getField('custbody132').updateDisplayType({displayType:'normal'}); // JOR<NAME>ÍAZ (LIMITE 5,000): context.form.getField('custbody133').updateDisplayType({displayType:'normal'}); // VICENTE CORTINA. (LIMITE 10,000): context.form.getField('custbody134').updateDisplayType({displayType:'normal'}); // EDITH GUEVARA (LIMITE 20,000): context.form.getField('custbody135').updateDisplayType({displayType:'normal'}); // ALEJANDRA PORRAS (MAYOR A 50,000): } if(employee == "1032563") // <NAME> { context.form.getField('custbody134').updateDisplayType({displayType:'normal'}); // EDITH GUEVARA (LIMITE 20,000): context.form.getField('custbody135').updateDisplayType({displayType:'normal'}); // ALEJANDRA PORRAS (MAYOR A 50,000): } if(employee == "593635") // <NAME> { context.form.getField('custbody137').updateDisplayType({displayType:'normal'}); // <NAME> (LIMITE 5,000): context.form.getField('custbody134').updateDisplayType({displayType:'normal'}); // EDITH GUEVARA (LIMITE 20,000): context.form.getField('custbody135').updateDisplayType({displayType:'normal'}); // ALEJANDRA PORRAS (MAYOR A 50,000): } if(employee == "96537") // <NAME> { context.form.getField('custbody138').updateDisplayType({displayType:'normal'}); // SILVIA MATA (LIMITE 5,000): context.form.getField('custbody140').updateDisplayType({displayType:'normal'}); // ZULMA APONTE (LIMITE 19,000): context.form.getField('custbody134').updateDisplayType({displayType:'normal'}); // EDITH GUEVARA (LIMITE 20,000): context.form.getField('custbody135').updateDisplayType({displayType:'normal'}); // ALEJANDRA PORRAS (MAYOR A 50,000): } if(employee == "901088" || employee == "1011198") // <NAME> y Fernanda { context.form.getField('custbody139').updateDisplayType({displayType:'normal'}); // <NAME> (LIMITE 5,000): context.form.getField('custbody141').updateDisplayType({displayType:'normal'}); // <NAME> (LIMITE 10,000): context.form.getField('custbody134').updateDisplayType({displayType:'normal'}); // EDITH GUEVARA (LIMITE 20,000): context.form.getField('custbody135').updateDisplayType({displayType:'normal'}); // ALEJANDRA PORRAS (MAYOR A 50,000): } if(employee == "851871") // <NAME> { context.form.getField('custbody153').updateDisplayType({displayType:'normal'}); // <NAME> (LIMITE 5,000): context.form.getField('custbody141').updateDisplayType({displayType:'normal'}); // ABRAHAM FIGUEROA (LIMITE 10,000): context.form.getField('custbody134').updateDisplayType({displayType:'normal'}); // EDITH GUEVARA (LIMITE 20,000): context.form.getField('custbody135').updateDisplayType({displayType:'normal'}); // ALEJANDRA PORRAS (MAYOR A 50,000): } /*if(subsidiary == "6" && approvalstatus == "1") { var band = false; if(jORGE_DIAZ_check == "T"){ rec.setValue({fieldId: "custbody142", value: '<NAME>'}); band = true; } if(pATRICIA_SANCHEZ_check == "T"){ rec.setValue({fieldId: "custbody142", value: '<NAME>'}); band = true; } if(sILVIA_MATA_check == "T"){ rec.setValue({fieldId: "custbody142", value: '<NAME>'}); band = true; } if(mICHELLE_ALCANTARA_check == "T"){ rec.setValue({fieldId: "custbody142", value: '<NAME>'}); band = true; } if(vICENTE_CORTINA_check == "T"){ rec.setValue({fieldId: "custbody143", value: 'VICENTE CORTINA'}); band = true; } if(aBRAHAM_FIGUEROA_check == "T"){ rec.setValue({fieldId: "custbody143", value: '<NAME>'}); band = true; } if(zULMA_APONTE_check == "T"){ rec.setValue({fieldId: "custbody143", value: 'ZULMA APONTE'}); band = true; } if(eDITH_GUEVARA_check == "T"){ rec.setValue({fieldId: "custbody144", value: '<NAME>'}); band = true; } if(aLEJANDRA_PORRAS_check == "T"){ rec.setValue({fieldId: "custbody145", value: '<NAME>'}); band = true; } if(band){ rec.save({enableSourcing: false, ignoreMandatoryFields: true}); redirect.toRecord({type : 'purchaseorder', id : currentOrdenCompraId}); } }*/ //var aprobado = false; if(subsidiary == "6" && approvalstatus == "1") { if(total > 0 && total <= 5000 && (jORGE_DIAZ_check == "T" || pATRICIA_SANCHEZ_check == "T" || sILVIA_MATA_check == "T" || mICHELLE_ALCANTARA_check == "T" || osvaldo_Tinoco_check == "T")){ log.debug('approvalstatus changed: ', 'Aprobado 5,000'); rec.setValue({fieldId: "approvalstatus", value: '2'}); rec.save({enableSourcing: false, ignoreMandatoryFields: true}); redirect.toRecord({type : 'purchaseorder', id : currentOrdenCompraId}); //aprobado = true; }else if(total > 5000 && total <= 10000 && (jORGE_DIAZ_check == "T" || pATRICIA_SANCHEZ_check == "T" || sILVIA_MATA_check == "T" || mICHELLE_ALCANTARA_check == "T" || osvaldo_Tinoco_check == "T") && (vICENTE_CORTINA_check == "T" || aBRAHAM_FIGUEROA_check == "T")){ log.debug('approvalstatus changed: ', 'Aprobado 10,000'); rec.setValue({fieldId: "approvalstatus", value: '2'}); rec.save({enableSourcing: false, ignoreMandatoryFields: true}); redirect.toRecord({type : 'purchaseorder', id : currentOrdenCompraId}); //aprobado = true; }else if(total > 5000 && total <= 19000 && (jORGE_DIAZ_check == "T" || pATRICIA_SANCHEZ_check == "T" || sILVIA_MATA_check == "T" || mICHELLE_ALCANTARA_check == "T" || osvaldo_Tinoco_check == "T") && zULMA_APONTE_check == "T"){ log.debug('approvalstatus changed: ', 'Aprobado 19,000'); rec.setValue({fieldId: "approvalstatus", value: '2'}); rec.save({enableSourcing: false, ignoreMandatoryFields: true}); redirect.toRecord({type : 'purchaseorder', id : currentOrdenCompraId}); //aprobado = true; }else if(total > 10000 && total <= 20000 && (jORGE_DIAZ_check == "T" || pATRICIA_SANCHEZ_check == "T" || sILVIA_MATA_check == "T" || mICHELLE_ALCANTARA_check == "T" || osvaldo_Tinoco_check == "T") && (vICENTE_CORTINA_check == "T" || aBRAHAM_FIGUEROA_check == "T") && (zULMA_APONTE_check == "T" || eDITH_GUEVARA_check == "T")){ log.debug('approvalstatus changed: ', 'Aprobado 20,000'); rec.setValue({fieldId: "approvalstatus", value: '2'}); rec.save({enableSourcing: false, ignoreMandatoryFields: true}); redirect.toRecord({type : 'purchaseorder', id : currentOrdenCompraId}); //aprobado = true; }else if(total > 20000 && (jORGE_DIAZ_check == "T" || pATRICIA_SANCHEZ_check == "T" || sILVIA_MATA_check == "T" || mICHELLE_ALCANTARA_check == "T" || osvaldo_Tinoco_check == "T") && (vICENTE_CORTINA_check == "T" || aBRAHAM_FIGUEROA_check == "T") && (zULMA_APONTE_check == "T" || eDITH_GUEVARA_check == "T") && aLEJANDRA_PORRAS_check == "T"){ log.debug('approvalstatus changed: ', 'Aprobado mayor a 20,000'); rec.setValue({fieldId: "approvalstatus", value: '2'}); rec.save({enableSourcing: false, ignoreMandatoryFields: true}); redirect.toRecord({type : 'purchaseorder', id : currentOrdenCompraId}); //aprobado = true; } } if(subsidiary == "6" && approvalstatus == "1") // approvalstatus == "1" && aprobado == false { var userObj = runtime.getCurrentUser(); log.debug('userObj: ', userObj); context.form.clientScriptFileId = 3568431; if(employee == "62837") // <NAME> { if(userObj.id == "62860" && total > 0 && total <= 5000) { context.form.addButton({id:'custpage_button_btnRechazarOrdenC', label:'Rechazar', functionName:'btnRechazarOrdenC'}); if(jORGE_DIAZ_check == "F") context.form.addButton({id:'custpage_button_btnJorgeDiaz', label:'Aprobación', functionName:'btnJorgeDiaz'}); // <NAME> }else if(total > 5000 && total <= 10000){ if(userObj.id == "62860") context.form.addButton({id:'custpage_button_btnRechazarOrdenC', label:'Rechazar', functionName:'btnRechazarOrdenC'}); if(userObj.id == "62860" && jORGE_DIAZ_check == "F") context.form.addButton({id:'custpage_button_btnJorgeDiaz', label:'Aprobación', functionName:'btnJorgeDiaz'}); // <NAME> if(userObj.id == "1031937") context.form.addButton({id:'custpage_button_btnRechazarOrdenC', label:'Rechazar', functionName:'btnRechazarOrdenC'}); if(userObj.id == "1031937" && vICENTE_CORTINA_check == "F") context.form.addButton({id:'custpage_button_btnVicenteCortina', label:'Aprobación', functionName:'btnVicenteCortina'}); }else if(total > 10000 && total <= 20000){ if(userObj.id == "62860") context.form.addButton({id:'custpage_button_btnRechazarOrdenC', label:'Rechazar', functionName:'btnRechazarOrdenC'}); if(userObj.id == "62860" && jORGE_DIAZ_check == "F") context.form.addButton({id:'custpage_button_btnJorgeDiaz', label:'Aprobación', functionName:'btnJorgeDiaz'}); // <NAME> if(userObj.id == "1031937") context.form.addButton({id:'custpage_button_btnRechazarOrdenC', label:'Rechazar', functionName:'btnRechazarOrdenC'}); if(userObj.id == "1031937" && vICENTE_CORTINA_check == "F") context.form.addButton({id:'custpage_button_btnVicenteCortina', label:'Aprobación', functionName:'btnVicenteCortina'}); if(userObj.id == "1023329") context.form.addButton({id:'custpage_button_btnRechazarOrdenC', label:'Rechazar', functionName:'btnRechazarOrdenC'}); if(userObj.id == "1023329" && eDITH_GUEVARA_check == "F") context.form.addButton({id:'custpage_button_btnEdithGuevara', label:'Aprobación', functionName:'btnEdithGuevara'}); }else if(total > 20000){ if(userObj.id == "62860") context.form.addButton({id:'custpage_button_btnRechazarOrdenC', label:'Rechazar', functionName:'btnRechazarOrdenC'}); if(userObj.id == "62860" && jORGE_DIAZ_check == "F") context.form.addButton({id:'custpage_button_btnJorgeDiaz', label:'Aprobación', functionName:'btnJorgeDiaz'}); // <NAME> if(userObj.id == "1031937") context.form.addButton({id:'custpage_button_btnRechazarOrdenC', label:'Rechazar', functionName:'btnRechazarOrdenC'}); if(userObj.id == "1031937" && vICENTE_CORTINA_check == "F") context.form.addButton({id:'custpage_button_btnVicenteCortina', label:'Aprobación', functionName:'btnVicenteCortina'}); if(userObj.id == "1023329") context.form.addButton({id:'custpage_button_btnRechazarOrdenC', label:'Rechazar', functionName:'btnRechazarOrdenC'}); if(userObj.id == "1023329" && eDITH_GUEVARA_check == "F") context.form.addButton({id:'custpage_button_btnEdithGuevara', label:'Aprobación', functionName:'btnEdithGuevara'}); if(userObj.id == "975540") context.form.addButton({id:'custpage_button_btnRechazarOrdenC', label:'Rechazar', functionName:'btnRechazarOrdenC'}); if(userObj.id == "975540" && aLEJANDRA_PORRAS_check == "F") context.form.addButton({id:'custpage_button_btnAlejandraPorras', label:'Aprobación', functionName:'btnAlejandraPorras'}); } } if(employee == "1032563") // <NAME> { if(userObj.id == "1023329" && total > 10000 && total <= 20000) { context.form.addButton({id:'custpage_button_btnRechazarOrdenC', label:'Rechazar', functionName:'btnRechazarOrdenC'}); if(eDITH_GUEVARA_check == "F") context.form.addButton({id:'custpage_button_btnEdithGuevara', label:'Aprobación', functionName:'btnEdithGuevara'}); }else if(total > 20000){ if(userObj.id == "1023329") context.form.addButton({id:'custpage_button_btnRechazarOrdenC', label:'Rechazar', functionName:'btnRechazarOrdenC'}); if(userObj.id == "1023329" && eDITH_GUEVARA_check == "F") context.form.addButton({id:'custpage_button_btnEdithGuevara', label:'Aprobación', functionName:'btnEdithGuevara'}); if(userObj.id == "975540") context.form.addButton({id:'custpage_button_btnRechazarOrdenC', label:'Rechazar', functionName:'btnRechazarOrdenC'}); if(userObj.id == "975540" && aLEJANDRA_PORRAS_check == "F") context.form.addButton({id:'custpage_button_btnAlejandraPorras', label:'Aprobación', functionName:'btnAlejandraPorras'}); } } if(employee == "593635") // <NAME> { if(userObj.id == "142184" && total > 0 && total <= 5000) { context.form.addButton({id:'custpage_button_btnRechazarOrdenC', label:'Rechazar', functionName:'btnRechazarOrdenC'}); if(pATRICIA_SANCHEZ_check == "F") context.form.addButton({id:'custpage_button_btnPatriciaSanchez', label:'Aprobación', functionName:'btnPatriciaSanchez'}); }else if(total > 10000 && total <= 20000){ if(userObj.id == "142184") context.form.addButton({id:'custpage_button_btnRechazarOrdenC', label:'Rechazar', functionName:'btnRechazarOrdenC'}); if(userObj.id == "142184" && pATRICIA_SANCHEZ_check == "F") context.form.addButton({id:'custpage_button_btnPatriciaSanchez', label:'Aprobación', functionName:'btnPatriciaSanchez'}); if(userObj.id == "1023329") context.form.addButton({id:'custpage_button_btnRechazarOrdenC', label:'Rechazar', functionName:'btnRechazarOrdenC'}); if(userObj.id == "1023329" && eDITH_GUEVARA_check == "F") context.form.addButton({id:'custpage_button_btnEdithGuevara', label:'Aprobación', functionName:'btnEdithGuevara'}); }else if(total > 20000){ if(userObj.id == "142184") context.form.addButton({id:'custpage_button_btnRechazarOrdenC', label:'Rechazar', functionName:'btnRechazarOrdenC'}); if(userObj.id == "142184" && pATRICIA_SANCHEZ_check == "F") context.form.addButton({id:'custpage_button_btnPatriciaSanchez', label:'Aprobación', functionName:'btnPatriciaSanchez'}); if(userObj.id == "1023329") context.form.addButton({id:'custpage_button_btnRechazarOrdenC', label:'Rechazar', functionName:'btnRechazarOrdenC'}); if(userObj.id == "1023329" && eDITH_GUEVARA_check == "F") context.form.addButton({id:'custpage_button_btnEdithGuevara', label:'Aprobación', functionName:'btnEdithGuevara'}); if(userObj.id == "975540") context.form.addButton({id:'custpage_button_btnRechazarOrdenC', label:'Rechazar', functionName:'btnRechazarOrdenC'}); if(userObj.id == "975540" && aLEJANDRA_PORRAS_check == "F") context.form.addButton({id:'custpage_button_btnAlejandraPorras', label:'Aprobación', functionName:'btnAlejandraPorras'}); } } if(employee == "96537") // <NAME> { if(userObj.id == "739490" && total > 0 && total <= 5000) { context.form.addButton({id:'custpage_button_btnRechazarOrdenC', label:'Rechazar', functionName:'btnRechazarOrdenC'}); if(sILVIA_MATA_check == "F") context.form.addButton({id:'custpage_button_btnSilviaMata', label:'Aprobación', functionName:'btnSilviaMata'}); }else if(total > 5000 && total <= 19000){ if(userObj.id == "739490") context.form.addButton({id:'custpage_button_btnRechazarOrdenC', label:'Rechazar', functionName:'btnRechazarOrdenC'}); if(userObj.id == "739490" && sILVIA_MATA_check == "F") context.form.addButton({id:'custpage_button_btnSilviaMata', label:'Aprobación', functionName:'btnSilviaMata'}); if(userObj.id == "224852") context.form.addButton({id:'custpage_button_btnRechazarOrdenC', label:'Rechazar', functionName:'btnRechazarOrdenC'}); if(userObj.id == "224852" && zULMA_APONTE_check == "F") context.form.addButton({id:'custpage_button_btnZulmaAponte', label:'Aprobación', functionName:'btnZulmaAponte'}); }else if(total > 19000 && total <= 20000){ if(userObj.id == "739490") context.form.addButton({id:'custpage_button_btnRechazarOrdenC', label:'Rechazar', functionName:'btnRechazarOrdenC'}); if(userObj.id == "739490" && sILVIA_MATA_check == "F") context.form.addButton({id:'custpage_button_btnSilviaMata', label:'Aprobación', functionName:'btnSilviaMata'}); if(userObj.id == "224852") context.form.addButton({id:'custpage_button_btnRechazarOrdenC', label:'Rechazar', functionName:'btnRechazarOrdenC'}); if(userObj.id == "224852" && zULMA_APONTE_check == "F") context.form.addButton({id:'custpage_button_btnZulmaAponte', label:'Aprobación', functionName:'btnZulmaAponte'}); if(userObj.id == "1023329") context.form.addButton({id:'custpage_button_btnRechazarOrdenC', label:'Rechazar', functionName:'btnRechazarOrdenC'}); if(userObj.id == "1023329" && eDITH_GUEVARA_check == "F") context.form.addButton({id:'custpage_button_btnEdithGuevara', label:'Aprobación', functionName:'btnEdithGuevara'}); }else if(total > 20000){ if(userObj.id == "739490") context.form.addButton({id:'custpage_button_btnRechazarOrdenC', label:'Rechazar', functionName:'btnRechazarOrdenC'}); if(userObj.id == "739490" && sILVIA_MATA_check == "F") context.form.addButton({id:'custpage_button_btnSilviaMata', label:'Aprobación', functionName:'btnSilviaMata'}); if(userObj.id == "224852") context.form.addButton({id:'custpage_button_btnRechazarOrdenC', label:'Rechazar', functionName:'btnRechazarOrdenC'}); if(userObj.id == "224852" && zULMA_APONTE_check == "F") context.form.addButton({id:'custpage_button_btnZulmaAponte', label:'Aprobación', functionName:'btnZulmaAponte'}); if(userObj.id == "1023329") context.form.addButton({id:'custpage_button_btnRechazarOrdenC', label:'Rechazar', functionName:'btnRechazarOrdenC'}); if(userObj.id == "1023329" && eDITH_GUEVARA_check == "F") context.form.addButton({id:'custpage_button_btnEdithGuevara', label:'Aprobación', functionName:'btnEdithGuevara'}); if(userObj.id == "975540") context.form.addButton({id:'custpage_button_btnRechazarOrdenC', label:'Rechazar', functionName:'btnRechazarOrdenC'}); if(userObj.id == "975540" && aLEJANDRA_PORRAS_check == "F") context.form.addButton({id:'custpage_button_btnAlejandraPorras', label:'Aprobación', functionName:'btnAlejandraPorras'}); } } if(employee == "901088" || employee == "1011198") // <NAME> y Fernanda { if(userObj.id == "411945" && total > 0 && total <= 5000) // || userObj.id == "637079" Yo { context.form.addButton({id:'custpage_button_btnRechazarOrdenC', label:'Rechazar', functionName:'btnRechazarOrdenC'}); if(mICHELLE_ALCANTARA_check == "F") context.form.addButton({id:'custpage_button_btnMichelleAlcantara', label:'Aprobación', functionName:'btnMichelleAlcantara'}); }else if(total > 5000 && total <= 10000){ if(userObj.id == "411945") context.form.addButton({id:'custpage_button_btnRechazarOrdenC', label:'Rechazar', functionName:'btnRechazarOrdenC'}); if(userObj.id == "411945" && mICHELLE_ALCANTARA_check == "F") context.form.addButton({id:'custpage_button_btnMichelleAlcantara', label:'Aprobación', functionName:'btnMichelleAlcantara'}); if(userObj.id == "1034514") context.form.addButton({id:'custpage_button_btnRechazarOrdenC', label:'Rechazar', functionName:'btnRechazarOrdenC'}); if(userObj.id == "1034514" && aBRAHAM_FIGUEROA_check == "F") context.form.addButton({id:'custpage_button_btnAbrahamFigueroa', label:'Aprobación', functionName:'btnAbrahamFigueroa'}); }else if(total > 10000 && total <= 20000){ if(userObj.id == "411945") context.form.addButton({id:'custpage_button_btnRechazarOrdenC', label:'Rechazar', functionName:'btnRechazarOrdenC'}); if(userObj.id == "411945" && mICHELLE_ALCANTARA_check == "F") context.form.addButton({id:'custpage_button_btnMichelleAlcantara', label:'Aprobación', functionName:'btnMichelleAlcantara'}); if(userObj.id == "1034514") context.form.addButton({id:'custpage_button_btnRechazarOrdenC', label:'Rechazar', functionName:'btnRechazarOrdenC'}); if(userObj.id == "1034514" && aBRAHAM_FIGUEROA_check == "F") context.form.addButton({id:'custpage_button_btnAbrahamFigueroa', label:'Aprobación', functionName:'btnAbrahamFigueroa'}); if(userObj.id == "1023329") context.form.addButton({id:'custpage_button_btnRechazarOrdenC', label:'Rechazar', functionName:'btnRechazarOrdenC'}); if(userObj.id == "1023329" && eDITH_GUEVARA_check == "F") context.form.addButton({id:'custpage_button_btnEdithGuevara', label:'Aprobación', functionName:'btnEdithGuevara'}); }else if(total > 20000){ if(userObj.id == "411945") context.form.addButton({id:'custpage_button_btnRechazarOrdenC', label:'Rechazar', functionName:'btnRechazarOrdenC'}); if(userObj.id == "411945" && mICHELLE_ALCANTARA_check == "F") context.form.addButton({id:'custpage_button_btnMichelleAlcantara', label:'Aprobación', functionName:'btnMichelleAlcantara'}); if(userObj.id == "1034514") context.form.addButton({id:'custpage_button_btnRechazarOrdenC', label:'Rechazar', functionName:'btnRechazarOrdenC'}); if(userObj.id == "1034514" && aBRAHAM_FIGUEROA_check == "F") context.form.addButton({id:'custpage_button_btnAbrahamFigueroa', label:'Aprobación', functionName:'btnAbrahamFigueroa'}); if(userObj.id == "1023329") context.form.addButton({id:'custpage_button_btnRechazarOrdenC', label:'Rechazar', functionName:'btnRechazarOrdenC'}); if(userObj.id == "1023329" && eDITH_GUEVARA_check == "F") context.form.addButton({id:'custpage_button_btnEdithGuevara', label:'Aprobación', functionName:'btnEdithGuevara'}); if(userObj.id == "975540") context.form.addButton({id:'custpage_button_btnRechazarOrdenC', label:'Rechazar', functionName:'btnRechazarOrdenC'}); if(userObj.id == "975540" && aLEJANDRA_PORRAS_check == "F") context.form.addButton({id:'custpage_button_btnAlejandraPorras', label:'Aprobación', functionName:'btnAlejandraPorras'}); } } if(employee == "851871") // <NAME> { if(userObj.id == "97772" && total > 0 && total <= 5000) { context.form.addButton({id:'custpage_button_btnRechazarOrdenC', label:'Rechazar', functionName:'btnRechazarOrdenC'}); if(osvaldo_Tinoco_check == "F") context.form.addButton({id:'custpage_button_btnOsvaldoTinoco', label:'Aprobación', functionName:'btnOsvaldoTinoco'}); }else if(total > 5000 && total <= 10000){ if(userObj.id == "97772") context.form.addButton({id:'custpage_button_btnRechazarOrdenC', label:'Rechazar', functionName:'btnRechazarOrdenC'}); if(userObj.id == "97772" && osvaldo_Tinoco_check == "F") context.form.addButton({id:'custpage_button_btnOsvaldoTinoco', label:'Aprobación', functionName:'btnOsvaldoTinoco'}); if(userObj.id == "1034514") context.form.addButton({id:'custpage_button_btnRechazarOrdenC', label:'Rechazar', functionName:'btnRechazarOrdenC'}); if(userObj.id == "1034514" && aBRAHAM_FIGUEROA_check == "F") context.form.addButton({id:'custpage_button_btnAbrahamFigueroa', label:'Aprobación', functionName:'btnAbrahamFigueroa'}); }else if(total > 10000 && total <= 20000){ if(userObj.id == "97772") context.form.addButton({id:'custpage_button_btnRechazarOrdenC', label:'Rechazar', functionName:'btnRechazarOrdenC'}); if(userObj.id == "97772" && osvaldo_Tinoco_check == "F") context.form.addButton({id:'custpage_button_btnOsvaldoTinoco', label:'Aprobación', functionName:'btnOsvaldoTinoco'}); if(userObj.id == "1034514") context.form.addButton({id:'custpage_button_btnRechazarOrdenC', label:'Rechazar', functionName:'btnRechazarOrdenC'}); if(userObj.id == "1034514" && aBRAHAM_FIGUEROA_check == "F") context.form.addButton({id:'custpage_button_btnAbrahamFigueroa', label:'Aprobación', functionName:'btnAbrahamFigueroa'}); if(userObj.id == "1023329") context.form.addButton({id:'custpage_button_btnRechazarOrdenC', label:'Rechazar', functionName:'btnRechazarOrdenC'}); if(userObj.id == "1023329" && eDITH_GUEVARA_check == "F") context.form.addButton({id:'custpage_button_btnEdithGuevara', label:'Aprobación', functionName:'btnEdithGuevara'}); }else if(total > 20000){ if(userObj.id == "97772") context.form.addButton({id:'custpage_button_btnRechazarOrdenC', label:'Rechazar', functionName:'btnRechazarOrdenC'}); if(userObj.id == "97772" && osvaldo_Tinoco_check == "F") context.form.addButton({id:'custpage_button_btnOsvaldoTinoco', label:'Aprobación', functionName:'btnOsvaldoTinoco'}); if(userObj.id == "1034514") context.form.addButton({id:'custpage_button_btnRechazarOrdenC', label:'Rechazar', functionName:'btnRechazarOrdenC'}); if(userObj.id == "1034514" && aBRAHAM_FIGUEROA_check == "F") context.form.addButton({id:'custpage_button_btnAbrahamFigueroa', label:'Aprobación', functionName:'btnAbrahamFigueroa'}); if(userObj.id == "1023329") context.form.addButton({id:'custpage_button_btnRechazarOrdenC', label:'Rechazar', functionName:'btnRechazarOrdenC'}); if(userObj.id == "1023329" && eDITH_GUEVARA_check == "F") context.form.addButton({id:'custpage_button_btnEdithGuevara', label:'Aprobación', functionName:'btnEdithGuevara'}); if(userObj.id == "975540") context.form.addButton({id:'custpage_button_btnRechazarOrdenC', label:'Rechazar', functionName:'btnRechazarOrdenC'}); if(userObj.id == "975540" && aLEJANDRA_PORRAS_check == "F") context.form.addButton({id:'custpage_button_btnAlejandraPorras', label:'Aprobación', functionName:'btnAlejandraPorras'}); } } } } /*if(userObj.role == "1139" || userObj.role == "1094") // 1097 = OSS Contabilidad KHG { if(customform_id == "14") // 14 = atención a cliente injerto { var val_casenumber1 = context.form.getField({id: 'casenumber'}).defaultValue; } }*/ if(context.type == "edit") { context.form.getField('custbody132').updateDisplayType({displayType:'hidden'}); // <NAME> (LIMITE 5,000): context.form.getField('custbody137').updateDisplayType({displayType:'hidden'}); // <NAME> (LIMITE 5,000): context.form.getField('custbody138').updateDisplayType({displayType:'hidden'}); // <NAME> (LIMITE 5,000): context.form.getField('custbody139').updateDisplayType({displayType:'hidden'}); // <NAME> (LIMITE 5,000): context.form.getField('custbody153').updateDisplayType({displayType:'hidden'}); // <NAME> (LIMITE 5,000): context.form.getField('custbody133').updateDisplayType({displayType:'hidden'}); // VICENTE CORTINA. (LIMITE 10,000): context.form.getField('custbody141').updateDisplayType({displayType:'hidden'}); // <NAME> (LIMITE 10,000): context.form.getField('custbody140').updateDisplayType({displayType:'hidden'}); // ZULMA APONTE (LIMITE 19,000): context.form.getField('custbody134').updateDisplayType({displayType:'hidden'}); // <NAME> (LIMITE 20,000): context.form.getField('custbody135').updateDisplayType({displayType:'hidden'}); // <NAME> (MAYOR A 50,000): /*var recordCaseId = context.newRecord.id; var objRecord = record.load({type: 'purchaseorder', id: recordCaseId, isDynamic: false}); log.debug('objRecord: ', objRecord); //var customform_id = objRecord.getValue({fieldId: 'customform'}); var userObj = runtime.getCurrentUser(); log.debug('userObj: ', userObj); if(userObj.role == "1139" || userObj.role == "1094") // 1097 = OSS Contabilidad KHG { if(customform_id == "14") // 14 = atención a cliente injerto { var jorgeDias = objRecord.getText({fieldId: 'custbody132'}); log.debug('jorgeDias: ', jorgeDias); if(userObj!= "62860") { context.form.getField('custbody132').updateDisplayType({displayType:'hidden'}); } else { // if(jorgeDias == "F") context.form.getField('custbody132').updateDisplayType({displayType:'normal'}); context.form.getField('custbody133').updateDisplayType({displayType:'normal'}); context.form.getField('custbody133').updateDisplayType({displayType:'disabled'}); context.form.getField('custbody134').updateDisplayType({displayType:'normal'}); context.form.getField('custbody134').updateDisplayType({displayType:'disabled'}); context.form.getField('custbody135').updateDisplayType({displayType:'normal'}); context.form.getField('custbody135').updateDisplayType({displayType:'disabled'}); } var vicneteCortina = objRecord.getText({fieldId: 'custbody133'}); log.debug('vicneteCortina: ', vicneteCortina); if(userObj!= "1031937") { context.form.getField('custbody133').updateDisplayType({displayType:'hidden'}); } else { // if(vicneteCortina == "F") context.form.getField('custbody133').updateDisplayType({displayType:'normal'}); context.form.getField('custbody132').updateDisplayType({displayType:'normal'}); context.form.getField('custbody132').updateDisplayType({displayType:'disabled'}); context.form.getField('custbody134').updateDisplayType({displayType:'normal'}); context.form.getField('custbody134').updateDisplayType({displayType:'disabled'}); context.form.getField('custbody135').updateDisplayType({displayType:'normal'}); context.form.getField('custbody135').updateDisplayType({displayType:'disabled'}); } var edith = objRecord.getText({fieldId: 'custbody134'}); log.debug('edith: ', edith); if(userObj!= "123405") { context.form.getField('custbody134').updateDisplayType({displayType:'hidden'}); } else { // if(edith == "F") context.form.getField('custbody134').updateDisplayType({displayType:'normal'}); context.form.getField('custbody132').updateDisplayType({displayType:'normal'}); context.form.getField('custbody132').updateDisplayType({displayType:'disabled'}); context.form.getField('custbody133').updateDisplayType({displayType:'normal'}); context.form.getField('custbody133').updateDisplayType({displayType:'disabled'}); context.form.getField('custbody135').updateDisplayType({displayType:'normal'}); context.form.getField('custbody135').updateDisplayType({displayType:'disabled'}); } var gabriela = objRecord.getText({fieldId: 'custbody135'}); log.debug('gabriela: ', gabriela); if(userObj!= "975540") { context.form.getField('custbody135').updateDisplayType({displayType:'hidden'}); } else { // if(gabriela == "F") context.form.getField('custbody135').updateDisplayType({displayType:'normal'}); context.form.getField('custbody132').updateDisplayType({displayType:'normal'}); context.form.getField('custbody132').updateDisplayType({displayType:'disabled'}); context.form.getField('custbody133').updateDisplayType({displayType:'normal'}); context.form.getField('custbody133').updateDisplayType({displayType:'disabled'}); context.form.getField('custbody134').updateDisplayType({displayType:'normal'}); context.form.getField('custbody134').updateDisplayType({displayType:'disabled'}); } var segundoNivel = objRecord.getText({fieldId: 'custbody133'}); log.debug('segundoNivel: ', segundoNivel); if(segundoNivel == "F") { context.form.getField('custbody133').updateDisplayType({displayType:'normal'}); } else { context.form.getField('custbody133').updateDisplayType({displayType:'normal'}); context.form.getField('custbody133').updateDisplayType({displayType:'disabled'}); } } }*/ } } function afterSubmit(context) { if(context.type == "create") { //var userObj = runtime.getCurrentUser(); // logging for test log.debug("title", "ue_ChecksParaAprobarOrdenCompra.js - function afterSubmit(context)"); var recordId = context.newRecord.id; log.debug("recordId: ", recordId); if(recordId!= null && recordId!= "") // && userObj.id!= null && userObj.id!= "" redirect.toSuitelet({scriptId: 'customscript1210', deploymentId: 'customdeploy1', parameters:{'recordId':recordId}}); //, userId: userObj.id } } return { beforeLoad: beforeLoad, afterSubmit: afterSubmit }; }); ======================= File: ScriptFactory/script_save_search/searchFacebook.js ======================= <reponame>WizyOs/kaloniScripts function searchFacebook(){ var fuente = '00166 Campaña Facebook Mx'; var count=''; var location=''; /*Valoraciones Agendadas facebook*/ var revresults = nlapiSearchRecord ('calendarevent','customsearch3242'); for(var z=0; z<revresults.length; z++) { var result1=revresults[z]; var column1=result1.getAllColumns(); var sucursal =result1.getText(column1[1]); count =result1.getValue(column1[0]); if(sucursal==fuente){ location = nlapiLoadRecord('location',44);//Test Face location.setFieldValue('custrecord6', count);//Valoraciones Agendadas nlapiSubmitRecord(location, true); continue; } } /*Valoraciones efectivas facebook*/ var revresults = nlapiSearchRecord ('calendarevent','customsearch3241'); for(var z=0; z<revresults.length; z++) { var result1=revresults[z]; var column1=result1.getAllColumns(); var sucursal =result1.getText(column1[1]); count =result1.getValue(column1[0]); if(sucursal==fuente){ location = nlapiLoadRecord('location',44);//Test Face location.setFieldValue('custrecord7', count);//Val Efectivas nlapiSubmitRecord(location, true); continue; } } /*Leads Facebook*/ var revresults = nlapiSearchRecord ('customer','customsearch3243'); for(var z=0; z<revresults.length; z++) { var result1=revresults[z]; var column1=result1.getAllColumns(); var sucursal =result1.getText(column1[1]); count =result1.getValue(column1[0]); if(sucursal==fuente){ location = nlapiLoadRecord('location',44);//Test Face location.setFieldValue('custrecord31', count);//Leads nlapiSubmitRecord(location, true); continue; } } } ======================= File: rl_appAlbya_createSheduleByCustomer.js ======================= /** * @NApiVersion 2.x * @NScriptType Restlet * @NModuleScope SameAccount */ define(["N/record", "N/log", "N/file", "N/email", "N/search", "N/ui/serverWidget", "N/format", "N/https", "N/url", "N/xml", "N/render", "N/runtime"], function (record, log, file, email, search, serverWidget, format, https, url, xml, render, runtime) { function doGet(params) {} function doPost(params) { var objJson; if (typeof params === "object") { objJson = params; } else { objJson = JSON.parse(params); } log.debug("params", objJson); // FIXME: Params in JSON object var param_action = objJson.action; var param_branchName = objJson.branchName; var param_emailCustomer = objJson.emailCustomer; var param_firstName = objJson.firstName; var param_secondName = objJson.secondName; var param_phone = objJson.phone; var param_startDate = objJson.startDate; var param_startTime = objJson.startTime; var param_endTime = objJson.endTime; var param_areaOfIinterest = objJson.areaOfIinterest; var param_comments = objJson.comments; var param_checkNoticePrivacy = objJson.checkNoticePrivacy; //Check aviso privavidad: custentity155 var param_checkAdvertising = objJson.Advertising; //Check aviso privavidad: custentity155 var param_sheduleType = objJson.sheduleType; //Check de Publicidad: custentity156 // FIXME: GLOBAL VARIABLES var objRecord_newEvent; var objRecord_newProspect; var objRecord_updateProspect; var objRecord_SaveProspect_id var objRecord_newEvent_id; var objRecord_LoadProspect; var internalId; var email; var resourceId; var param_entityid; var subject; var idSheduleType; var prefixTitle; var idStatus; var branchId; // FIXME: CONSTANTS const SHEDULE_TYPE = "12" // Type to "VALORACION" const OWNER_EMPLOYEE = "1133783" // event owner employee id // SUPPORT ARRAYS var arr_endTime = [ // schedule arrangement set to 30 minutes "0000", "0030", "0100", "0130", "0200", "0230", "0300", "0330", "0400", "0430", "0500", "0530", "0600", "0630", "0700", "0730", "0800", "0830", "0900", "0930", "1000", "1030", "1100", "1130", "1200", "1230", "1300", "1330", "1400", "1430", "1500", "1530", "1600", "1630", "1700", "1730", "1800", "1830", "1900", "1930", "2000", "2030", "2100", "2130", "2200", "2230", "2300", "2330" ]; var arr_resourcesByLocation = [ // arrangement of resources by branch { "recordType": "location", "id": "61", "values": { "name": "<NAME>", "phone": "", "city": "Ciudad de México", "state": "CDMX (custom)", "country": "MX", "address.address": "ALB Altavista\r\nAltavista No. 160\r\nCol. San Angel-Inn\r\nAlcaldía Álvaro Obregón\r\nCiudad de México CDMX (custom) 01000\r\nMéxico" }, "resources": [{ "value": "244", "text": "Valoraciones Altavista Alb" }] }, { "recordType": "location", "id": "62", "values": { "name": "<NAME>", "phone": "", "city": "Cancún", "state": "QROO", "country": "MX", "address.address": "ALB Can-Cún \r\nAv,Sayil Lote 2, Manzana 5, Supermanzana 6, Locales 307 y 308\r\nMunicipio de Benito Juárez QROO\r\nCancún QROO Municipio de Benito Juárez QROO\r\nMéxico" }, "resources": [{ "value": "247", "text": "Valoraciones Can-Cun Alb" }] }, { "recordType": "location", "id": "63", "values": { "name": "<NAME>", "phone": "", "city": "Chihuahua", "state": "CHIH", "country": "MX", "address.address": "ALB Chihuahua\r\nCalle Vía Trentino No. 5710 1er Piso Local 106 Edificio Vetro Plaza Citadela Desarrollo El Saucito Sector 49\r\nChihuahua CHIH 31115\r\nMéxico" }, "resources": [{ "value": "250", "text": "Valoraciones Chihuahua Alb" }] }, { "recordType": "location", "id": "64", "values": { "name": "<NAME>", "phone": "", "city": "Zapopan", "state": "JAL", "country": "MX", "address.address": "ALB Guadalajara\r\nBoulevard Puerta de Hierro Num 5150 Torre Medica C Piso 4 Plaza Corporativa\r\nZapopan JAL 45116\r\nMéxico" }, "resources": [{ "value": "255", "text": "Valoraciones Guadalajara Alb" }] }, { "recordType": "location", "id": "65", "values": { "name": "<NAME>", "phone": "", "city": "Monterrey", "state": "NL", "country": "MX", "address.address": "ALB Monterrey\r\nCalz del Valle Alberto Santos 201 2do Piso, Local D Col Del Valle 66220\r\nMonterrey NL 66220\r\nMéxico" }, "resources": [{ "value": "258", "text": "Valoraciones Monterrey Alb" }] }, { "recordType": "location", "id": "66", "values": { "name": "<NAME>", "phone": "", "city": "Ciudad de México", "state": "CDMX (custom)", "country": "MX", "address.address": "ALB Polanco\r\nAnatole France 145, Polanco, Polanco III Secc, Miguel Hidalgo\r\nCiudad de México CDMX (custom) 11550\r\nMéxico" }, "resources": [{ "value": "259", "text": "Valoraciones Polanco Alb" }] }, { "recordType": "location", "id": "67", "values": { "name": "<NAME>", "phone": "", "city": "Puebla", "state": "PUE", "country": "MX", "address.address": "ALB Puebla\r\nLa Plaza Sonata Towers Boulevard Europa No. 17 Int. L2N1 Zona Comercial Fracc. Residencial Lomas de Angelópolis San Andrés Cholula\r\nPuebla PUE 72830\r\nMéxico" }, "resources": [{ "value": "262", "text": "Valoraciones Puebla Alb" }] }, { "recordType": "location", "id": "68", "values": { "name": "<NAME>", "phone": "", "city": "Ciudad de México", "state": "CDMX (custom)", "country": "MX", "address.address": "ALB Santa Fé\r\nAv Vasco De Quiroga No. 3900 Torre B Piso 4 Col. Lomas de Santa Fe Cuajimalpa de Morelos\r\nCiudad de México CDMX (custom) 05348\r\nMéxico" }, "resources": [{ "value": "265", "text": "Valoraciones Santa Fe Alb" }] }, { "recordType": "location", "id": "69", "values": { "name": "<NAME>", "phone": "", "city": "Estado de México", "state": "MEX", "country": "MX", "address.address": "ALB Satélite \r\nPafnuncio Padilla No. 10 Cd. Satélite Naucalpan de Juárez\r\nEstado de México MEX 53100\r\nMéxico" }, "resources": [{ "value": "268", "text": "Valoraciones Satelite Alb" }] }, { "recordType": "location", "id": "70", "values": { "name": "<NAME>", "phone": "", "city": "Tijuana", "state": "BC", "country": "MX", "address.address": "ALB Tijuana\r\nMision San Javier 10643 Via Corporativa int 101 Zona Urbana Rio\r\nTijuana BC 22010\r\nMéxico" }, "resources": [{ "value": "273", "text": "Valoraciones Tijuana Alb" }] }, { "recordType": "location", "id": "71", "values": { "name": "<NAME>", "phone": "", "city": "Veracruz", "state": "VER", "country": "MX", "address.address": "ALB Veracruz\r\nAv. Juan Pablo II No 390 Piso 5 B Fracc Costa de Oro Boca del Rio\r\nVeracruz VER 94299\r\nMéxico" }, "resources": [{ "value": "274", "text": "Valoraciones Veracruz Alb" }] }, { "recordType": "location", "id": "54", "values": { "name": "Cancún", "phone": "", "city": "Ciudad de México", "state": "", "country": "MX", "address.address": "Cancún\r\nAdolfo L. Mateos\r\nAv. 25\r\nPoniente 134\r\nCiudad de México \r\nMéxico" }, "resources": [{ "value": "231", "text": "Valoraciones Cancún (Albya)" }] }, { "recordType": "location", "id": "53", "values": { "name": "Chihuahua", "phone": "", "city": "", "state": "", "country": "MX", "address.address": "XAXX010101000\r\nChihuahua\r\nAv. 85\r\nCol. Benito Juarez\r\nCiudad de México\r\nMéxico" }, "resources": [{ "value": "232", "text": "Valoraciones Chihuahua (Albya)" }] }, { "recordType": "location", "id": "52", "values": { "name": "Guadalajara", "phone": "", "city": "", "state": "", "country": "MX", "address.address": "Guadalajara\r\nMéxico" }, "resources": [{ "value": "224", "text": "Valoraciones Guadalajara (Albya)" }] }, { "recordType": "location", "id": "60", "values": { "name": "<NAME>", "phone": "", "city": "ZAPOPAN", "state": "JAL", "country": "MX", "address.address": "Guadalajara Arboledas Uno\r\nCARNERO 53951\r\nCOL. ARBOLEDAS\r\nZAPOPAN JAL 45070\r\nMéxico" }, "resources": [{ "value": "243", "text": "Valoraciones Guadalajara Arboledas" }] }, { "recordType": "location", "id": "57", "values": { "name": "Polanco", "phone": "", "city": "Ciudad de México", "state": "", "country": "MX", "address.address": "Polanco\r\nAnatole France 145\r\nPolanco\r\nPolanco III Secc, Miguel Hidalgo\r\nCiudad de México 11550\r\nMéxico" }, "resources": [{ "value": "229", "text": "Valoraciones Anatole (Albya)" }] } ]; // FIXME: SUPPORT SETS // TODO: Get and set resource id, shedule type id, subject, prefix of title var objJson_resources = JSON.parse(JSON.stringify(arr_resourcesByLocation)); if (SHEDULE_TYPE == '12') { for (var r in objJson_resources) { if (objJson_resources[r].values.name == param_branchName) { resourceId = objJson_resources[r].resources[0].value; branchId = objJson_resources[r].id; log.debug("resources", "rec " + resourceId + " suc " + branchId) } }; idSheduleType = "12"; subject = "Cita de Valoración"; prefixTitle = "VAL_"; }; // TODO: calculate end time of date if (param_endTime == "" || param_endTime == undefined) { for (var t in arr_endTime) { if (param_startTime == arr_endTime[t]) { param_endTime = arr_endTime[parseInt(t) + 1]; } } } // TODO: convert date in string to date in object var c = objJson.startDate.split("/"); param_startDate = parseInt(c[0]) + "/" + (parseInt(c[1]) + 1) + "/" + parseInt(c[2]); log.debug("fecha",param_startDate); // FIXME: SUPPORT SEARCHES var searchCreacte_CustomerLeadOrProspect = search.create({ type: search.Type.CUSTOMER, filters: [{ name: "email", operator: "is", values: [param_emailCustomer], isor: false, isnot: false, leftparens: 0, rightparens: 0 }], columns: [{ name: "internalid" }, { name: "entityid" }, { name: "altname" }, { name: "email" }, { name: "phone" }, { name: "custentity25" } ] }); var searchPreview_CustomerLeadOrProspect = searchCreacte_CustomerLeadOrProspect .run() .getRange({ start: 0, end: 1 }); if (searchPreview_CustomerLeadOrProspect.length > 0) { var obj_searchPreview_CustomerLeadOrProspect = JSON.parse(JSON.stringify(searchPreview_CustomerLeadOrProspect)); internalId = obj_searchPreview_CustomerLeadOrProspect[0].values.internalid[0].value; email = obj_searchPreview_CustomerLeadOrProspect[0].values.email; param_entityid = obj_searchPreview_CustomerLeadOrProspect[0].values.entityid; log.debug("dataSearch", "internalId " + internalId + " email " + email); } else { internalId = null; email = null; } // FIXME: CREATE SHEDULE if (internalId!== null) { // internalId es el ID del CLIENTE PROSPECTO O LEAD // SI EL CLIENTE EXISTE SOLO SE CREA EL EVENTO try { //FIXME:Actualiza los datos del lead existente y lo pasa a prospecto // ACTUALIZACION DE DATOS LEAD A PROSPECTO objRecord_updateProspect = record.load({ // Carga objeto CUSTOMER type: record.Type.CUSTOMER, id: internalId, isDynamic: true }); objRecord_updateProspect.setText({ // Set NOMBRE fieldId: 'firstname', text: param_firstName }); objRecord_updateProspect.setText({ // Set APELLIDOS fieldId: 'lastname', text: param_secondName }); objRecord_updateProspect.setText({ // Set CELULAR fieldId:'mobilephone', text: param_phone }); objRecord_updateProspect.setValue({ // Set Subsidiaria a Albya fieldId: "subsidiary", value: "19" }); objRecord_updateProspect.setValue({ // Set PAIS a Mexico fieldId: "custentity137", value: "1" }); objRecord_updateProspect.setValue({ // Set Tipo de cliente a Prospecto fieldId: "entitystatus", value: "26" }); objRecord_updateProspect.setValue({ // Set Sucursal fieldId: "custentity25", value: branchId }); /* objRecord_updateProspect.setValue({ // Set Area de interes fieldId: "custentity297", value: param_areaOfIinterest }); */ objRecord_updateProspect.setValue({ // Set Comentarios fieldId: "comments", value: param_comments }); objRecord_updateProspect.setValue({ // Set Comentarios fieldId: "custentity155", value: param_checkNoticePrivacy }); objRecord_SaveProspect_id = objRecord_updateProspect.save({ enableSourcing: false, ignoreMandatoryFields: true }); try { // NUEVO EVENTO de AGENDA objRecord_newEvent = record.create({ // Crea objeto Calendar Event type: record.Type.CALENDAR_EVENT, isDynamic: true }); objRecord_newEvent.setValue({ // Set id Customer en el campo company por necesidad de NetSuite fieldId: "company", value: internalId }); objRecord_newEvent.setValue({ // Set id Empleado en el campo owner por necesidad de NetSuite fieldId: "owner", value: OWNER_EMPLOYEE }); objRecord_newEvent.setValue({ // Set Tipo de Servicio Valoracion Procedimiento o Revisión fieldId: "custevent70", value: idSheduleType }); objRecord_newEvent.setValue({ // Set titulo del evento fieldId: "title", value: prefixTitle + param_entityid + " / " + param_areaOfIinterest }); objRecord_newEvent.setValue({ // Set Sucursal del evento misma que del doctor fieldId: "custevent2", value: branchId }); objRecord_newEvent.setValue({ // Set Asunto fieldId: "custevent79", value: subject }); objRecord_newEvent.setValue({ // Set organizador siempre es Promo Albya fieldId: "organizer", value: "1133783" }); objRecord_newEvent.setText({ // Set fecha de evento fieldId: "startdate", text: param_startDate }); objRecord_newEvent.setText({ // Set hora inicial del evento fieldId: "starttime", text: param_startTime }); objRecord_newEvent.setText({ // Set hora final del evento fieldId: "endtime", text: param_endTime }); /* objRecord_newEvent.setValue({ // Set Tipo de Consulta fieldId: "custevent1197", text: param_tipoConsulta }); objRecord_newEvent.setText({ // Set costo de consulta si, no, no aplica fieldId: "custevent1198", text: param_costoAgenda }); */ objRecord_newEvent.insertLine({ sublistId: "resource", line: 0 }); objRecord_newEvent.setCurrentSublistValue({ sublistId: "resource", fieldId: "resource", value: resourceId }); objRecord_newEvent.commitLine({ sublistId: "resource" }); objRecord_newEvent.insertLine({ sublistId: "attendee", line: 0 }); objRecord_newEvent.setCurrentSublistValue({ sublistId: "attendee", fieldId: "attendee", value: internalId }); objRecord_newEvent.commitLine({ sublistId: "attendee" }); objRecord_newEvent_id = objRecord_newEvent.save({ enableSourcing: false, ignoreMandatoryFields: true }); return { "idProstect": objRecord_SaveProspect_id, "idEvent": objRecord_newEvent_id, //"event": objRecord_newEvent }; } catch (error) { log.error('Error new event si el cliente existe', error); return { "ERR_CREATE_EVENT": error }; } } catch (error) { return { "ERR_UPDATE_CUSTOMER": error }; } } else if (internalId === null) { // internalId es el ID del CLIENTE PROSPECTO O LEAD // SI EL CLIENTE NO EXISTE, SE CREA PROSPECTO PRIMERO try { var objRecord_newProspect = record.create({ type: record.Type.PROSPECT, isDynamic: true }); objRecord_newProspect.setValue({ // Set Nombre fieldId: "customform", value: "150" }); objRecord_newProspect.setText({ // Set Nombre fieldId: "firstname", text: param_firstName }); objRecord_newProspect.setText({ // Set Apelllido fieldId: "lastname", text: param_secondName }); objRecord_newProspect.setValue({ // Set fieldId: "custentity434", value: "219" }); objRecord_newProspect.setValue({ // Set Subsidiaria fieldId: "subsidiary", value: "19" }); objRecord_newProspect.setValue({ // Set Tipo de CLiente a LEAD fieldId: "entitystatus", value: "26" }); objRecord_newProspect.setValue({ // Set Sucursal fieldId: "custentity25", value: branchId }); objRecord_newProspect.setValue({ // Set PAISES fieldId: "custentity137", value: "1" }); objRecord_newProspect.setValue({ // Set Ejecutivo K-Center fieldId: "custentity143", value: "262" }); objRecord_newProspect.setValue({ // Set Celular fieldId: "mobilephone", value: param_phone }); objRecord_newProspect.setValue({ // Set email fieldId: "email", value: param_emailCustomer }); objRecord_newProspect.setValue({ // Set MEDIOS fieldId: "custentity38", value: "219" }); objRecord_newProspect.setValue({ // Set UTM Source fieldId: "custentity133", value: "APP Médico" }); /* objRecord_newProspect.setValue({ // Set Area de interes fieldId: "custentity297", value: param_areaOfIinterest }); */ objRecord_newProspect.setValue({ // Set Comentarios fieldId: "comments", value: param_comments }); objRecord_newProspect.setValue({ // Set Comentarios fieldId: "custentity155", value: param_checkNoticePrivacy }); objRecord_SaveProspect_id = objRecord_newProspect.save({ enableSourcing: false, ignoreMandatoryFields: true }); log.debug("idProspecto", objRecord_SaveProspect_id); objRecord_LoadProspect = record.load({ type: record.Type.CUSTOMER, id: objRecord_SaveProspect_id }); var field_entityId_Prospect = objRecord_LoadProspect.getValue({ fieldId: 'entityid' }); try { // NUEVO EVENTO de AGENDA objRecord_newEvent = record.create({ // Crea objeto Calendar Event type: record.Type.CALENDAR_EVENT, isDynamic: true }); objRecord_newEvent.setValue({ // Set id Customer en el campo company por necesidad de NetSuite fieldId: "company", value: objRecord_SaveProspect_id }); objRecord_newEvent.setValue({ // Set id Empleado en el campo owner por necesidad de NetSuite fieldId: "owner", value: OWNER_EMPLOYEE }); objRecord_newEvent.setValue({ // Set Tipo de Servicio Valoracion Procedimiento o Revisión fieldId: "custevent70", value: idSheduleType }); objRecord_newEvent.setValue({ // Set titulo del evento fieldId: "title", value: prefixTitle + field_entityId_Prospect + " / " + param_areaOfIinterest }); objRecord_newEvent.setValue({ // Set Sucursal del evento misma que del doctor fieldId: "custevent2", value: branchId }); objRecord_newEvent.setValue({ // Set Asunto fieldId: "custevent79", value: subject }); objRecord_newEvent.setValue({ // Set organizador siempre es Promo Albya fieldId: "organizer", value: "1133783" }); objRecord_newEvent.setText({ // Set fecha de evento fieldId: "startdate", text: param_startDate }); objRecord_newEvent.setText({ // Set hora inicial del evento fieldId: "starttime", text: param_startTime }); objRecord_newEvent.setText({ // Set hora final del evento fieldId: "endtime", text: param_endTime }); /* objRecord_newEvent.setValue({ // Set Tipo de Consulta fieldId: "custevent1197", text: param_tipoConsulta }); objRecord_newEvent.setText({ // Set costo de consulta si, no, no aplica fieldId: "custevent1198", text: param_costoAgenda }); */ objRecord_newEvent.insertLine({ sublistId: "resource", line: 0 }); objRecord_newEvent.setCurrentSublistValue({ sublistId: "resource", fieldId: "resource", value: resourceId }); objRecord_newEvent.commitLine({ sublistId: "resource" }); objRecord_newEvent.insertLine({ sublistId: "attendee", line: 0 }); objRecord_newEvent.setCurrentSublistValue({ sublistId: "attendee", fieldId: "attendee", value: objRecord_SaveProspect_id }); objRecord_newEvent.commitLine({ sublistId: "attendee" }); objRecord_newEvent_id = objRecord_newEvent.save({ enableSourcing: false, ignoreMandatoryFields: true }); return [{ "idProstect": objRecord_SaveProspect_id, "idEvent": objRecord_newEvent_id }]; } catch (error) { log.error('Error new event si el cliente NO existe', error); return { "ERR_CREATE_EVENT": error }; } } catch (error) { return { "ERR_CREATE_PROSPECT": error }; } } } return { post: doPost }; }); ======================= File: mail_toSend_61dias.js ======================= <gh_stars>0 /** * @NApiVersion 2.x * @NScriptType ScheduledScript * @NModuleScope SameAccount */ define(["N/ui/serverWidget", "N/crypto", "N/https", "N/runtime", "N/encode", "N/url", 'N/email', 'N/log', 'N/search', 'N/record'], function (ui, crypto, https, runtime, encode, urlMod, email, log, search, record) { function execute(context) { // var body_mail = Procedimiento5_MX2020.html var body_mail = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'+ '<html xmlns:v="urn:schemas-microsoft-com:vml">'+ '<head>'+ ''+ '<!-- Define Charset -->'+ '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />'+ ''+ '<!-- Responsive Meta Tag -->'+ '<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0;" />'+ '<meta name="viewport" content="width=600,initial-scale = 2.3,user-scalable=no">'+ '<link href=\'https://fonts.googleapis.com/css?family=Work+Sans:300,400,500,600,700\' rel="stylesheet">'+ '<link href="https://fonts.googleapis.com/css?family=Poppins:300,400,500,600,700" rel="stylesheet">'+ '<title>Recordatorio cita de revisión de 3 meses</title>'+ '<style type="text/css">'+ 'body {'+ ' width: 100%;'+ ' background-color: #ffffff;'+ ' margin: 0;'+ ' padding: 0;'+ ' -webkit-font-smoothing: antialiased;'+ ' mso-margin-top-alt: 0px;'+ ' mso-margin-bottom-alt: 0px;'+ ' mso-padding-alt: 0px 0px 0px 0px;'+ '}'+ 'p, h1, h2, h3, h4 {'+ ' margin-top: 0;'+ ' margin-bottom: 0;'+ ' padding-top: 0;'+ ' padding-bottom: 0;'+ '}'+ 'span.preheader {'+ ' display: none;'+ ' font-size: 1px;'+ '}'+ 'html {'+ ' width: 100%;'+ '}'+ 'table {'+ ' font-size: 14px;'+ ' border: 0;'+ '}'+ 'a {'+ ' border-style: none!important;'+ ' border: 0!important;'+ ' text-decoration: none;'+ ' color: #456CB3;'+ ' }'+ 'b{'+ ' color: #456CB3;'+ ' }'+ '.sombra-01 {'+ ' -webkit-box-shadow: 0px 0px 6px 1px rgba(204,204,204,1);'+ ' -moz-box-shadow: 0px 0px 6px 1px rgba(204,204,204,1);'+ ' box-shadow: 0px 0px 6px 1px rgba(204,204,204,1);'+ '}'+ '.circle {'+ ' border-radius: 50%;'+ ' width: 100px;'+ ' height: 100px;'+ '}'+ '.circle-60 {'+ ' border-radius: 50%;'+ ' width: 15px;'+ ' height: 15px;'+ '}'+ ''+ '/* ----------- responsivity ----------- */'+ ' '+ '@media only screen and (max-width: 796px) {'+ 'body[yahoo].Medium-container590 {'+ ' width: 180px!important;'+ '}'+ 'body[yahoo].hide-800 {'+ ' display: none!important;'+ '}'+ 'body[yahoo].container800 {'+ ' width: 100%!important;'+ '}'+ 'body[yahoo].container780 {'+ ' width: 600px!important;'+ '}'+ 'body[yahoo].Bullets {'+ ' width: 500px!important;'+ '}'+ 'body[yahoo].container800_img {'+ ' width: 50%!important;'+ '}'+ 'body[yahoo].section800_img img {'+ ' width: 100%!important;'+ ' height: auto!important;'+ '}'+ 'body[yahoo].half-container800 {'+ ' width: 49%!important;'+ '}'+ 'body[yahoo].Medium-container800 {'+ ' width: 90%!important;'+ '}'+ '/* ====== divider ====== */'+ 'body[yahoo].divider img {'+ ' width: 30%!important;'+ '}'+ '}'+ ''+ '/* ----------- responsivity ----------- */'+ ' '+ '@media only screen and (max-width: 640px) {'+ '/*------ top header ------ */'+ 'body[yahoo].main-header {'+ ' font-size: 20px!important;'+ '}'+ 'body[yahoo].main-section-header {'+ ' font-size: 28px!important;'+ '}'+ 'body[yahoo].show {'+ ' display: block!important;'+ '}'+ 'body[yahoo].hide {'+ ' display: none!important;'+ '}'+ 'body[yahoo].align-center {'+ ' text-align: center!important;'+ '}'+ '/*----- main image -------*/'+ 'body[yahoo].main-img img {'+ ' width: 440px!important;'+ ' height: auto!important;'+ '}'+ '/* ====== divider ====== */'+ 'body[yahoo].divider img {'+ ' width: 250px!important;'+ '}'+ '/*-------- container --------*/'+ 'body[yahoo].container590 {'+ ' width: 440px!important;'+ '}'+ 'body[yahoo].container590-center {'+ ' width: 280px!important;'+ ' text-align: center!important;'+ '}'+ 'body[yahoo].container580 {'+ ' width: 400px!important;'+ '}'+ 'body[yahoo].container500 {'+ ' width: 320px!important;'+ '}'+ 'body[yahoo].container400 {'+ ' width: 290px!important;'+ '}'+ 'body[yahoo].container800 {'+ ' width: 440px!important;'+ '}'+ 'body[yahoo].container780 {'+ ' width: 440px!important;'+ '}'+ 'body[yahoo].Bullets {'+ ' width: 400px!important;'+ '}'+ 'body[yahoo].container800_img {'+ ' width: 100%!important;'+ '}'+ 'body[yahoo].section800_img img {'+ ' width: 100%!important;'+ '}'+ 'body[yahoo].section800_img1 img {'+ ' width: 60%!important;'+ ' height: auto!important;'+ '}'+ 'body[yahoo].half-container {'+ ' width: 200px!important;'+ '}'+ 'body[yahoo].Medium-container800 {'+ ' width: 80%!important;'+ '}'+ 'body[yahoo].main-button {'+ ' width: 200px!important;'+ '}'+ '/*-------- secions ----------*/'+ 'body[yahoo].container590 {'+ ' width: 440px!important;'+ '}'+ 'body[yahoo].section-img img {'+ ' width: 320px!important;'+ ' height: auto!important;'+ '}'+ 'body[yahoo].team-img img {'+ ' width: 100%!important;'+ ' height: auto!important;'+ '}'+ 'body[yahoo].text-space div{'+ ' line-height: 33px!important;'+ '}'+ '}'+ ''+ '@media only screen and (max-width: 479px) {'+ '/*------ top header ------ */'+ 'body[yahoo].main-header {'+ ' font-size: 20px!important;'+ '}'+ 'body[yahoo].main-section-header {'+ ' font-size: 24px!important;'+ '}'+ '/* ====== divider ====== */'+ 'body[yahoo].main-img img {'+ ' width: 280px!important;'+ '}'+ 'body[yahoo].divider img {'+ ' width: 220px!important;'+ '}'+ '/*-------- container --------*/'+ 'body[yahoo].container590 {'+ ' width: 280px!important;'+ '}'+ 'body[yahoo].container590-center {'+ ' width: 280px!important;'+ ' text-align: center;'+ '}'+ 'body[yahoo].container580 {'+ ' width: 260px!important;'+ '}'+ 'body[yahoo].container500 {'+ ' width: 280px!important;'+ '}'+ 'body[yahoo].container400 {'+ ' width: 260px!important;'+ '}'+ 'body[yahoo].container800 {'+ ' width: 100%!important;'+ '}'+ 'body[yahoo].container780 {'+ ' width: 280px!important;'+ '}'+ 'body[yahoo].Bullets {'+ ' width: 240px!important;'+ '}'+ 'body[yahoo].container800_img {'+ ' width: 100%!important;'+ '}'+ 'body[yahoo].Medium-container800 {'+ ' width: 95%!important;'+ '}'+ 'body[yahoo].section800_img img {'+ ' width: 100%!important;'+ ' height: auto!important;'+ '}'+ 'body[yahoo].section800_img1 img {'+ ' width: 50%!important;'+ ' height: auto!important;'+ '}'+ 'body[yahoo].half-container800 {'+ ' width: 100%!important;'+ '}'+ 'body[yahoo].half-container {'+ ' width: 130px!important;'+ '}'+ 'body[yahoo].container500 {'+ ' width: 280px!important;'+ '}'+ '/*-------- secions ----------*/'+ 'body[yahoo].container590 {'+ ' width: 280px!important;'+ '}'+ 'body[yahoo].section-img img {'+ ' width: 280px!important;'+ ' height: auto!important;'+ '}'+ 'body[yahoo].text-space div{'+ ' line-height: 30px!important;'+ '}'+ ' '+ '}'+ '</style>'+ '</head>'+ ''+ '<body yahoo="fix" leftmargin="0" topmargin="0" marginwidth="0" marginheight="0">'+ ''+ '<!-- ======= ENVÍO AL SALIR DE LA CITA DE 2 MESES (O AL DÍA 61 DESPUÉS DEL PROCEDIMIENTO) ======= -->'+ '<!-- ======= main section ======= -->'+ ''+ '<table border="0" width="100%" cellpadding="0" cellspacing="0" bgcolor="#001E66">'+ ' <tr>'+ ' <tr>'+ ' <td height="20" style="font-size: 20px; line-height: 20px;"> </td>'+ ' </tr>'+ ' <td align="center">'+ ' <table border="0" align="center" width="590" cellpadding="0" cellspacing="0" class="container590">'+ ' <tr>'+ ' <td><table border="0" align="left" cellpadding="0" cellspacing="0" style="border-collapse:collapse; mso-table-lspace:0pt; mso-table-rspace:0pt;" class="container590">'+ ' <tr>'+ ' <td height="5" style="font-size: 5px; line-height: 5px;"> </td>'+ ' </tr>'+ ' <tr>'+ ' <td align="center"><table border="0" cellpadding="0" cellspacing="0" align="center">'+ ' <tr>'+ ' <td align="center" style="color: #ffffff; font-size: 14px; font-family: \'Helvetica\', Calibri, sans-serif; line-height: 24px;"><div style=" line-height: 24px;"> <a href="https://3559763.app.netsuite.com/core/media/media.nl?id=3982533&c=3559763&h=888f5c1c23d9cc7afe6b&mv=k3f9u8nc&_xt=.html&fcts=20191125185909&whence=" style="color: #ffffff; text-decoration: none;">¿Problemas con las imágenes? Ver en línea</a> </div></td>'+ ' </tr>'+ ' </table></td>'+ ' </tr>'+ ' </table></td>'+ ' <td class="hide" class="align-center">'+ ' <table border="0" width="135" align="right" cellpadding="0" cellspacing="0" style="border-collapse:collapse; mso-table-lspace:0pt; mso-table-rspace:0pt;" class="hide">'+ ' <tr>'+ ' <td><table border="0" align="left" width="35" cellpadding="0" cellspacing="0" style="border-collapse:collapse; mso-table-lspace:0pt; mso-table-rspace:0pt;" class="container590 hide">'+ ' <tr>'+ ' <td width="10" height="10" style="font-size:10px; line-height: 10px;"> </td>'+ ' </tr>'+ ' </table></td>'+ ' </tr>'+ ' </table>'+ ' </td>'+ ' '+ ' <td class="hide" class="align-center">'+ ' '+ ' <table border="0" width="100" align="right" cellpadding="0" cellspacing="0" style="border-collapse:collapse; mso-table-lspace:0pt; mso-table-rspace:0pt;" class="container590">'+ ' <tr>'+ ' <td><table border="0" width="100" align="left" cellpadding="0" cellspacing="0" style="border-collapse:collapse; mso-table-lspace:0pt; mso-table-rspace:0pt;" class="container590">'+ ' <tr>'+ ' <td align="left" style="color: #f2d221; font-size: 14px; font-family: \'Helvetica\', Calibri, sans-serif; line-height: 20px;" class="align-center"><!-- ======= section subtitle ====== -->'+ ' '+ ' <table border="0" width="70" align="right" cellpadding="0" cellspacing="0" style="border-collapse:collapse; mso-table-lspace:0pt; mso-table-rspace:0pt;" class="container590">'+ ' <tr>'+ ' <td align="left"><table border="0" align="left" cellpadding="0" cellspacing="0" class="container590">'+ ' <tr>'+ ' <td align="center"><table border="0" align="center" width="130" cellpadding="0" cellspacing="0">'+ ' <tr>'+ ' <td height="8" style="font-size: 8px; line-height: 8px;"> </td>'+ ' </tr>'+ ' <tr>'+ ' <td align="left"><table align="center" border="0" cellpadding="0" cellspacing="0">'+ ' <tr>'+ ' <td align="center" style="color: #000; font-size: 14px; font-family: \'Helvetica\', Calibri, sans-serif; line-height: 16px;"><!-- ======= main section button ======= -->'+ ' '+ ' <div style="line-height: 26px;"> <a href="https://kaloni.mx/injerto-capilar.html" style="color: #ffffff; text-decoration: none; align: center;">Soluciones Kaloni</a> </div></td>'+ ' </tr>'+ ' </table></td>'+ ' </tr>'+ ' <tr>'+ ' <td height="8" style="font-size: 8px; line-height:8px;"> </td>'+ ' </tr>'+ ' </table></td>'+ ' </tr>'+ ' </table></td>'+ ' </tr>'+ ' </table></td>'+ ' </tr>'+ ' </table></td>'+ ' </tr>'+ ' </table>'+ ' </tr>'+ ' </table>'+ ' </td>'+ ' '+ ' </tr>'+ ' '+ ' <tr>'+ ' <td><table border="0" width="100%" cellpadding="0" cellspacing="0" bgcolor="#001E66">'+ ' <tr>'+ ' <td height="35" style="font-size: 35px; line-height: 35px;"> </td>'+ ' </tr>'+ ' <tr> '+ ' <!-- ======= divider ======= -->'+ ' <td align="center" class="divider"><img width="800" border="0" style="display: block; width: 230px; height: auto;" src="https://3559763.app.netsuite.com/core/media/media.nl?id=3981681&c=3559763&h=d76fb5ede3ce230551a4&fcts=20191125175924&whence=" alt="Logo Kaloni" /></td>'+ ' </tr>'+ ' </table></td>'+ ' </tr>'+ ' '+ ' <tr cellspacing="0" bgcolor="#0b2363" height="auto" style="background-image: url(https://3559763.app.netsuite.com/core/media/media.nl?id=3981042&c=3559763&h=90ab409d1cc1074e86b9&fcts=20191125173308&whence=); background-size: cover; background-position: bottom center; background-repeat: no-repeat;" background="https://3559763.app.netsuite.com/core/media/media.nl?id=3981042&c=3559763&h=90ab409d1cc1074e86b9&fcts=20191125173308&whence=">'+ ' <td align="center">'+ ' <table border="0" align="center" width="800" cellpadding="0" cellspacing="0" class="Medium-container800">'+ ' <tr>'+ ' <td><table border="0" width="100%" align="center" cellpadding="0" cellspacing="0" style="border-collapse:collapse; mso-table-lspace:0pt; mso-table-rspace:0pt;" class="Medium-container800">'+ ' <tr><td height="15" style="font-size: 15px; line-height: 15px;"> </td></tr>'+ ' '+ ' <tr>'+ ' <td><table border="0" width="100%" align="center" cellpadding="0" cellspacing="0" class="container800">'+ ' <tr>'+ ' <td align="center"><table border="0" width="100%" align="center" cellpadding="0" cellspacing="0" class="section800">'+ ' <tr><td height="20" class="hide" style="font-size: 20px; line-height: 20px;"> </td></tr>'+ ' '+ ' <tr>'+ ' <td align="center" class="section800_img"><a href="#" style=" border-style: none!important; border: 0!important;"><img src="https://3559763.app.netsuite.com/core/media/media.nl?id=3982509&c=3559763&h=672fba4dfdf45caf7490&fcts=20191125185638&whence=" style="display: block;" width="100%" border="0" alt="Has tomado la decisión correcta, sólo ten paciencia" /></a></td>'+ ' </tr>'+ ' '+ ' <tr><td height="100" class="hide" style="font-size: 5px; line-height: 5px;"> </td> </tr>'+ ' '+ ' </table></td>'+ ' </tr>'+ ' </table></td>'+ ' </tr>'+ ' '+ ' </table></td>'+ ' </tr>'+ ' </table>'+ ' </td>'+ ' </tr>'+ ' '+ '</table>'+ '</tr>'+ ''+ '<!-- ======= end section ======= --> '+ ''+ '<!-- ======= features section ======= -->'+ ''+ '<table border="0" width="100%" cellpadding="0" cellspacing="0" bgcolor="FFFFFF">'+ ' <tr>'+ ' <td height="20" style="font-size: 10px; line-height: 10px;"> </td>'+ ' </tr>'+ ' <tr align="center">'+ ' <td align="center"><table border="0" align="center" width="780" cellpadding="0" cellspacing="0" class="container780">'+ ' <tr>'+ ' <td align="center"><!-- SALUDO -->'+ ' '+ ' <table border="0" width="780" align="center" cellpadding="0" cellspacing="0" class="container780">'+ ' <tr>'+ ' <td align="left" style="color: #456cb3; font-size: 36px; font-family: \'Poppins\', Calibri, sans-serif; font-weight: 700;" class="main-section-header text-space"><div style="line-height: 40px; text-transform: uppercase;"> ¡Ánimo! Viene la etapa más compleja en este camino rumbo a tu objetivo para recuperar tu cabello. </div></td>'+ ' </tr>'+ ' '+ ' <tr><td height="5" style="font-size: 5px; line-height: 5px;"></td></tr>'+ ' '+ ' <tr><td><div style="color: #456cb3;font-size: 15px; font-family: \'Helvetica\', Calibri, sans-serif; font-weight: 500;line-height: 23px"> Han pasado ya más de 6 semanas desde que realizaste tu procedimiento y seguramente ya empiezas a notar algunos cambios importantes. </b></div></td></tr>'+ ' '+ ' <tr><td height="10" style="font-size: 10px; line-height: 10px;"></td></tr>'+ ' '+ ' <table align="left" width="100" border="0" cellpadding="0" cellspacing="0" bgcolor="#456cb3" style="border-radius: 5px;">'+ ' <tr><td height="4" style="font-size: 4px; line-height: 4px;"></td></tr>'+ ' </table>'+ ' </table>'+ ' '+ ' '+ ' <!-- FIN SALUDO --> '+ ' '+ ' <!-- TEXTOS en Bulets -->'+ ' '+ ' <table border="0" width="100%" cellpadding="0" cellspacing="0">'+ ' <tr>'+ ' <td height="10" style="font-size: 10px; line-height: 10px;"> </td>'+ ' </tr>'+ ' <tr align="center">'+ ' <td align="center"><table border="0" align="center" width="780" cellpadding="0" cellspacing="0" class="container780">'+ ' <tr>'+ ' <td align="center" style="color: #cccccc; font-size: 13px; font-family: \'Poppins\', Calibri, sans-serif; letter-spacing: 2px; line-height: 24px;" class="align-center"><!-- ======= section subtitle ====== -->'+ ' '+ ' <div style="line-height: 24px;"> </div></td>'+ ' </tr>'+ ' <tr>'+ ' <td height="20" style="font-size: 20px; line-height: 20px;"> </td>'+ ' </tr>'+ ' <tr>'+ ' <td align="center"><!--Tabla de Bulet 1 y 2-->'+ ' '+ ' <table border="0" width="780" align="center" cellpadding="0" cellspacing="0" class="container780">'+ ' <tr>'+ ' <td align="center" style="color: #333; font-size: 16px; font-family: \'Helvetica\', Calibri, sans-serif; line-height: 24px;"><!--Bulet 1-->'+ ' '+ ' <table border="0" width="50%" align="left" cellpadding="0" cellspacing="0" class="container780">'+ ' <tr>'+ ' <td align="left"><table border="0" width="40" align="left" cellpadding="0" cellspacing="0">'+ ' <tr>'+ ' <tr>'+ ' <td height="10" style="font-size: 10px; line-height: 10px;"> </td>'+ ' </tr>'+ ' <td align="center"><div class="circle-60" style="background-color: #456cb3;font-family: \'Poppins\', Calibri, sans-serif; font-size: 50px; font-weight: 700; line-height: 55px; text-align: center;"> </div></td>'+ ' </tr>'+ ' </table>'+ ' <table border="0" width="300" align="left" cellpadding="0" cellspacing="0" class="Bullets">'+ ' <tr>'+ ' <td width="10"> </td>'+ ' <td><div style="line-height: 20px; text-align: left; font-size: 14px;"> Notarás despoblada la zona injertada (fase de recambio). </div></td>'+ ' </tr>'+ ' <tr>'+ ' <td height="10" style="font-size: 10px; line-height: 10px;"> </td>'+ ' </tr>'+ ' </table></td>'+ ' </tr>'+ ' </table>'+ ' '+ ' <!--Bulet 2-->'+ ' '+ ' <table border="0" width="50%" align="right" cellpadding="0" cellspacing="0" class="container780">'+ ' <tr>'+ ' <td align="left"><table border="0" width="40" align="left" cellpadding="0" cellspacing="0">'+ ' <tr>'+ ' <tr>'+ ' <td height="10" style="font-size: 10px; line-height: 10px;"> </td>'+ ' </tr>'+ ' <td align="center"><div class="circle-60" style="background-color: #456cb3; color: #FFF; font-family: \'Poppins\', Calibri, sans-serif; font-size: 80px; font-weight: 700; line-height: 55px; text-align: center;"> </div></td>'+ ' </tr>'+ ' </table>'+ ' <table border="0" width="300" align="left" cellpadding="0" cellspacing="0" class="Bullets">'+ ' <tr>'+ ' <td width="10"> </td>'+ ' <td><div style="line-height: 20px; text-align: left; font-size: 14px;"> La irritación y zonas rojas ya habrán desaparecido.</div></td>'+ ' </tr>'+ ' <tr>'+ ' <td height="20" style="font-size: 10px; line-height: 10px;"> </td>'+ ' </tr>'+ ' </table></td>'+ ' </tr>'+ ' </table></td>'+ ' </tr>'+ ' </table>'+ ' '+ ' <!--Fin de Tabla de Bulet 1 y 2--> '+ ' <!-- Espacio -->'+ ' '+ ' <table border="0" width="780" align="center" cellpadding="0" cellspacing="0" class="container780">'+ ' <tr class="hide-800">'+ ' <td height="10" style="font-size: 10px; line-height: 10px;"> </td>'+ ' </tr>'+ ' </table>'+ ' '+ ' <!--Tabla de Bulet 3 y 4-->'+ ' '+ ' <table border="0" width="780" align="center" cellpadding="0" cellspacing="0" class="container780">'+ ' <tr>'+ ' <td align="center" style="color: #333; font-size: 16px; font-family: \'Helvetica\', Calibri, sans-serif; line-height: 24px;"><!--Bulet 3-->'+ ' '+ ' <table border="0" width="50%" align="left" cellpadding="0" cellspacing="0" class="container780">'+ ' <tr>'+ ' <td align="left"><table border="0" width="40" align="left" cellpadding="0" cellspacing="0">'+ ' <tr>'+ ' <td height="5" style="font-size: 5px; line-height: 5px;"> </td>'+ ' </tr>'+ ' <tr>'+ ' <td align="center"><div class="circle-60" style="background-color: #456cb3; color: #FFF; font-family: \'Poppins\', Calibri, sans-serif; font-size: 80px; font-weight: 700; line-height: 55px; text-align: center;"> </div></td>'+ ' </tr>'+ ' </table>'+ ' <table border="0" width="300" align="left" cellpadding="0" cellspacing="0" class="Bullets">'+ ' <tr>'+ ' <td width="10"> </td>'+ ' <td><div style="line-height: 20px; text-align: left; font-size: 14px;"> Pronto comenzarán a crecer poco a poco los nuevos cabellos.</div></td>'+ ' </tr>'+ ' <tr>'+ ' <td height="10" style="font-size: 10px; line-height: 10px;"> </td>'+ ' </tr>'+ ' </table></td>'+ ' </tr>'+ ' </table>'+ ' '+ ' <!--Bulet 4-->'+ ' '+ ' </td>'+ ' </tr>'+ ' </table>'+ ' '+ ' <!--Fin de la Tabla de Bulet 3 y 4--> '+ ' '+ ' <!-- Espacio -->'+ ' '+ ' <table border="0" width="780" align="center" cellpadding="0" cellspacing="0" class="container780">'+ ' <tr class="hide-800">'+ ' <td height="10" style="font-size: 10px; line-height: 10px;"> </td>'+ ' </tr>'+ ' </table>'+ ' '+ ' '+ ' <!-- Espacio -->'+ ' '+ ' <table border="0" width="780" align="center" cellpadding="0" cellspacing="0" class="container780">'+ ' <tr class="hide-800">'+ ' <td height="10" style="font-size: 10px; line-height: 10px;"> </td>'+ ' </tr>'+ ' </table>'+ ''+ ' </td></tr></table></td></tr>'+ ' </table>'+ ' <!-- FIN de los Bulets --> '+ ''+ ' <!-- TEXTO 01 -->'+ ' '+ ' <table border="0" width="780" align="center" cellpadding="0" cellspacing="0" class="container780">'+ ' <tr>'+ ' <td height="20" style="font-size: 20px; line-height: 20px;"> </td>'+ ' </tr>'+ ' <tr>'+ ' <td height="40" style="color: #333333; font-size: 15px; font-family: \'Helvetica\', Calibri, sans-serif; line-height: 25px;"> '+ ' Conoce más sobre los primeros signos de evolución del implante y los cuidados que debes tener en <a href="https://kaloni.mx/blog/injerto-capilar/injerto-capilar-3-meses-los-primeros-signos-de-evolucion/" style="font-weight: 800;">estos primeros 3 meses.</a>'+ ' <br><br>'+ ' Como puedes leer, la fase de recambio es completamente normal, de todas formas es importante que acudas a tu cita de revisión mensual para darte seguimiento y así asegurar los mejores resultados. '+ ' </td>'+ ' </tr>'+ ' <tr>'+ ' <td height="20" style="font-size: 20px; line-height: 20px;"> </td>'+ ' </tr>'+ ' </table>'+ ' '+ ' <!-- FIN TEXTO 01 --> '+ ''+ '<!-- Boton de TEXTO completo -->'+ ' '+ ' <table border="0" width="780" align="center" cellpadding="0" cellspacing="0" class="container780">'+ ' <tr>'+ ' <td height="20" style="font-size: 20px; line-height: 20px;"> </td>'+ ' </tr>'+ ' '+ ' <table border="0" width="400" align="center" cellpadding="0" cellspacing="0" class="container590" bgcolor="#456CB3"> '+ ' <tr>'+ ' <td height="40" style="color: #fff; font-size: 15px; font-family: \'Helvetica\', Calibri, sans-serif; line-height: 28px;text-align: center;font-weight:800; "> '+ ' AGENDA TU CITA DE REVISIÓN DE 3 MESES'+ ' </td>'+ ' </tr>'+ ' </table>'+ ' '+ ' </table>'+ ' '+ ' </td>'+ ' </tr>'+ ' </table></td>'+ ' </tr>'+ '</table>'+ ''+ '<!-- ======= end section ======= --> '+ ''+ '<table border="0" width="100%" cellpadding="0" cellspacing="0" bgcolor="ffffff">'+ ' '+ ' <tr><td height="20" style="font-size: 20px; line-height: 20px;"> </td></tr>'+ ' '+ ' <tr>'+ ' <td align="center">'+ ' <table border="0" align="center" width="640" cellpadding="0" cellspacing="0" class="container590">'+ ' '+ ' <tr><td height="20" style="font-size: 20px; line-height: 20px;"> </td></tr>'+ ' '+ ' <tr>'+ ' <td align="center" class="no-bg">'+ ' <table border="0" width="500" align="center" cellpadding="0" cellspacing="0" style="border-collapse:collapse; mso-table-lspace:0pt; mso-table-rspace:0pt;" class="container590">'+ ' <tr>'+ ' <td>'+ ' <a href="tel:5550221056" style=" border-style: none!important; display: block; border: 0!important;text-decoration: none;">'+ ' <table border="0" width="180" align="left" cellpadding="0" cellspacing="0" style="border-collapse:collapse; mso-table-lspace:0pt; mso-table-rspace:0pt;" class="container590">'+ ' <tr>'+ ' <!-- ======= image ======= -->'+ ' <td align="center">'+ ' <img src="https://3559763.app.netsuite.com/core/media/media.nl?id=3981726&c=3559763&h=a2aeb60ccfea691042e1&fcts=20191125180343&whence=" style="display: block;" width="70" border="0" alt="" />'+ ' </td>'+ ' </tr>'+ ' '+ ' <tr><td height="15" style="font-size: 15px; line-height: 15px;"> </td></tr>'+ ' '+ ' <tr>'+ ' <td align="center" style="color: #000000; font-size: 16px; font-family: \'Poppins\', Calibri, sans-serif; font-weight: 700; line-height: 24px; text-transform: uppercase;">'+ ' <!-- ======= section text ====== -->'+ ' '+ ' <div style="line-height: 23px">'+ ' '+ ' Teléfono'+ ' '+ ' </div>'+ ' </td> '+ ' </tr>'+ ' '+ ' '+ ' <a href="tel:5550221056" style=" border-style: none!important; display: block; border: 0!important;text-decoration: none;">'+ ' <tr>'+ ' <td align="center" style="color: #30497B; font-size: 16px; font-family: \'Poppins\', Calibri, sans-serif; font-weight: 700; line-height: 24px; text-transform: uppercase;">'+ ' <!-- ======= section subtitle ====== -->'+ ' <div style="line-height: 24px;">'+ ' '+ ' '+ ' (55) 5022 - 1056'+ ' '+ ' </div>'+ ' </td>'+ ' </tr>'+ ' </a>'+ ' '+ ' <tr><td height="10" style="font-size: 10px; line-height: 10px;"> </td></tr>'+ ' '+ ' </table></a>'+ ' '+ ' <table border="0" width="2" align="left" cellpadding="0" cellspacing="0" style="border-collapse:collapse; mso-table-lspace:0pt; mso-table-rspace:0pt;" class="container590">'+ ' <tr><td width="2" height="40" style="font-size: 40px; line-height: 40px;"></td></tr>'+ ' </table>'+ ' '+ ' <a href="https://api.whatsapp.com/send?phone=525566086038&text=Hola%20Kaloni" style=" text-decoration: none; align: center;">'+ ' '+ ' <table border="0" width="180" align="right" cellpadding="0" cellspacing="0" style="border-collapse:collapse; mso-table-lspace:0pt; mso-table-rspace:0pt;" class="container590">'+ ' <!-- ======= image ======= -->'+ ' <tr>'+ ' <a href="https://api.whatsapp.com/send?phone=525566086038&text=Hola%20Kaloni" style=" text-decoration: none; align: center;">'+ ' <td align="center">'+ ' <img src="https://3559763.app.netsuite.com/core/media/media.nl?id=3981727&c=3559763&h=a637c80cbbbc9f44a49f&fcts=20191125180355&whence=" style="display: block;" width="60" border="0" alt="Correo:<EMAIL>" />'+ ' </td>'+ ' </a>'+ ' </tr>'+ ' '+ ' <tr><td height="15" style="font-size: 15px; line-height: 15px;"> </td></tr>'+ ' '+ ' <tr>'+ ' '+ ' <td align="center" style="color: #000000; font-size: 16px; font-family: \'Poppins\', Calibri, sans-serif; font-weight: 700; line-height: 24px; text-transform: uppercase;">'+ ' <!-- ======= text ====== -->'+ ' <a href="https://api.whatsapp.com/send?phone=525566086038&text=Hola%20Kaloni" style="color: #000000; text-decoration: none; align: center;">'+ ' <div style="line-height: 23px">'+ ' '+ ' WhatsApp'+ ' '+ ' </div>'+ ' </a>'+ ' </td> '+ ' </tr>'+ ' '+ ' '+ ' '+ ' <tr>'+ ' <td align="center" style="color: #30497B; font-size: 16px; font-family: \'Poppins\', Calibri, sans-serif; font-weight: 700; line-height: 24px;">'+ ' <!-- ======= section subtitle ====== -->'+ ' <a href="https://api.whatsapp.com/send?phone=525566086038&text=Hola%20Kaloni" style="color: #244175; text-decoration: none; align: center;">'+ ' <div style="line-height: 24px;">'+ ' '+ ' (55) 6608 - 6038'+ ' '+ ' </div>'+ ' </a>'+ ' </td>'+ ' </tr>'+ ' '+ ' <tr><td height="10" style="font-size: 10px; line-height: 10px;"> </td></tr>'+ ' </table>'+ ' </a>'+ ' '+ ' </td>'+ ' </tr>'+ ' </table> '+ ' </td>'+ ' </tr>'+ ' '+ ' <tr><td height="30" style="font-size: 30px; line-height: 30px;"> </td></tr>'+ ' <table border="0" width="780" align="center" cellpadding="0" cellspacing="0" class="container780">'+ ' <tr>'+ ' <td height="40" style="color: #456CB3; font-size: 15px; font-family: \'Helvetica\', Calibri, sans-serif; line-height: 28px;text-align: center;font-weight:800;"> El tiempo a tu favor</div></td>'+ ' </tr>'+ ' </table>'+ ' '+ ' </table>'+ ' '+ ' </td>'+ ' </tr>'+ ' '+ ' <tr><td height="30" style="font-size: 30px; line-height: 30px;"> </td></tr>'+ ' '+ ' </table>'+ ''+ '<!-- ======= links and socials ======= -->'+ '<table border="0" width="100%" cellpadding="0" cellspacing="0" bgcolor="#FFFFFF">'+ ' <tr>'+ ' <td height="30" style="font-size: 30px; line-height: 30px;"> </td>'+ ' </tr>'+ ' <tr>'+ ' <td align="center"><table border="0" align="center" width="740" cellpadding="0" cellspacing="0" class="container780">'+ ' <tr>'+ ' <td><!-- Logotipo Footer -->'+ ' '+ ' <table border="0" width="300" align="left" cellpadding="0" cellspacing="0" style="border-collapse:collapse; mso-table-lspace:0pt; mso-table-rspace:0pt;" class="align-center container590">'+ ' <tr>'+ ' <td><table border="0" width="200" align="left" cellpadding="0" cellspacing="0" style="border-collapse:collapse; mso-table-lspace:0pt; mso-table-rspace:0pt;" class="container590 container590-center">'+ ' <tr>'+ ' <td align="left"><table border="0" cellpadding="0" cellspacing="0" align="left" class="container590">'+ ' <tr> '+ ' <!-- ======= logo ======= -->'+ ' <td align="center" class="align-center"><a href="https://kaloni.mx/index.html"><img width="60" border="0" style="width: 160px;" src="https://3559763.app.netsuite.com/core/media/media.nl?id=3981692&c=3559763&h=5d0c1375f8e99af681f3&fcts=20191125180002&whence=" alt="Logo-Hairrestoration" alt="Logo-Hairrestoration" /></a></td>'+ ' </tr>'+ ' </table></td>'+ ' </tr>'+ ' <tr>'+ ' <td height="10" style="font-size: 10px; line-height: 10px;"> </td>'+ ' </tr>'+ ' <tr>'+ ' <td align="left" style="color: #5C5D60; font-size: 14px; font-family: \'Helvetica\', Calibri, sans-serif; line-height: 25px;" class="text_color align-center"><!-- ======= section subtitle ====== -->'+ ' '+ ' <div class="container590 container590-center"style="line-height: 25px;text-align: left;width: 280px;"> Este correo te será enviado al dejar tus datos en nuestra página web, K- Center o página de Facebook. </div>'+ ' </tr>'+ ' </table>'+ ' <table border="0" width="2" align="left" cellpadding="0" cellspacing="0" style="border-collapse:collapse; mso-table-lspace:0pt; mso-table-rspace:0pt;" class="container590">'+ ' <tr>'+ ' <td width="2" height="10" style="font-size: 40px; line-height: 40px;"></td>'+ ' </tr>'+ ' </table></td>'+ ' </tr>'+ ' </table>'+ ' '+ ' <!-- End Logotipo Footer --> '+ ' '+ ' <!-- Agenda tu cita -->'+ ' '+ ' <table border="0" width="2" align="left" cellpadding="0" cellspacing="0" style="border-collapse:collapse; mso-table-lspace:0pt; mso-table-rspace:0pt;" class="container590 container590-center">'+ ' <tr class="hide-800">'+ ' <td width="2" height="40" style="font-size: 40px; line-height: 40px;"></td>'+ ' </tr>'+ ' </table>'+ ' <table border="0" width="120" align="right" cellpadding="0" cellspacing="0" style="border-collapse:collapse; mso-table-lspace:0pt; mso-table-rspace:0pt;" class="container590 align-center">'+ ' <tr>'+ ' <td><table border="0" width="100" align="center" cellpadding="0" cellspacing="0" style="border-collapse:collapse; mso-table-lspace:0pt; mso-table-rspace:0pt;" class="container590">'+ ' <tr>'+ ' <td align="left" style="color: #f2d221; font-size: 14px; font-family: \'Helvetica\', Calibri, sans-serif; line-height: 20px;" class="align-center"><!-- ======= section subtitle ====== -->'+ ' '+ ' <table border="0" width="70" align="right" cellpadding="0" cellspacing="0" style="border-collapse:collapse; mso-table-lspace:0pt; mso-table-rspace:0pt;" class="container590">'+ ' <tr>'+ ' <td align="left"><table border="0" align="center" cellpadding="0" cellspacing="0" class="container590">'+ ' </table></td>'+ ' </tr>'+ ' </table></td>'+ ' </tr>'+ ' </table></td>'+ ' </tr>'+ ' <tr class="hide-600">'+ ' <td width="2" height="10" style="font-size: 10px; line-height: 10px;"></td>'+ ' </tr>'+ ' <tr>'+ ' <td width="2" height="10" style="font-size: 10px; line-height: 10px;"></td>'+ ' </tr>'+ ' <!-- Social Media -->'+ ' <tr align="center">'+ ' <td align="center"><table border="0" align="center" cellpadding="0" cellspacing="0">'+ ' <tr> '+ ' <!-- Facebook -->'+ ' <td><a href="https://www.facebook.com/KaloniMx/" style="border-style: none!important; border: 0!important;" class="editable_img"><img width="25" border="0" style="display: block; width: auto;" src="https://3559763.app.netsuite.com/core/media/media.nl?id=3981775&c=3559763&h=5317375b219730a73cf5&fcts=20191125180541&whence=" alt="Facebook" /></a></td>'+ ' <!-- end Facebook -->'+ ' <td> </td>'+ ' '+ ' <!-- Instagram -->'+ ' <td><a href="https://www.instagram.com/kalonimx/?hl=es-la" style="border-style: none!important; border: 0!important;" class="editable_img"><img width="25" border="0" style="display: block; width: auto;" src="https://3559763.app.netsuite.com/core/media/media.nl?id=3981778&c=3559763&h=d15ca645ac66fc1110c1&fcts=20191125180546&whence=" alt="Twitter" /></a></td>'+ ' <!-- end Twitter -->'+ ' <td> </td>'+ ' '+ ' <!-- YouTube -->'+ ' <td><a href="https://www.youtube.com/user/KaloniHairChannel" style="border-style: none!important; border: 0!important;" class="editable_img"><img width="25" border="0" style="display: block; width: auto;" src="https://3559763.app.netsuite.com/core/media/media.nl?id=3981780&c=3559763&h=713a8875222a4199ae35&fcts=20191125180553&whence=" alt="Youtobe" /></a></td>'+ ' <!-- end YouTube --> '+ ' </tr>'+ ' </table></td>'+ ' </tr>'+ ' <!-- end Social Media -->'+ ' <tr>'+ ' <td width="2" height="20" style="font-size: 20px; line-height: 20px;"></td>'+ ' </tr>'+ ' </table>'+ ' '+ ' <!-- End agenda tu cita --> '+ ' '+ ' <!-- Legal -->'+ ' '+ ' <table border="0" width="160" align="center" cellpadding="0" cellspacing="0" style="border-collapse:collapse; mso-table-lspace:0pt; mso-table-rspace:0pt;" class="container590">'+ ' <tr>'+ ' <td><table border="0" width="250" align="center" cellpadding="0" cellspacing="0" style="border-collapse:collapse; mso-table-lspace:0pt; mso-table-rspace:0pt;" class="container590 Medium-container590">'+ ' <tr>'+ ' <td align="left" style="color: #456cb3; font-size: 22px; font-family: Poppins, Calibri, sans-serif; font-weight: 200; line-height: 30px;font-weight: 500;" class="align-center"><!-- ======= section text ====== -->'+ ' '+ ' <div class="edit_text" style="line-height: 30px"> LEGAL </div></td>'+ ' </tr>'+ ' <tr>'+ ' <td height="15" style="font-size: 15px; line-height: 15px;"> </td>'+ ' </tr>'+ ' <tr>'+ ' <td align="left" style="color: #5C5D60; font-size: 14px; font-family: \'Helvetica\', Calibri, sans-serif; line-height: 20px;" class="align-center"><!-- ======= section subtitle ====== -->'+ ' '+ ' <div><a href="https://kaloni.mx/legal.html" style="color: #5C5D60; text-decoration: none;"> Aviso de privacidad</a></div>'+ ' <div><a href="https://kaloni.mx/legal.html#descargo" style="color: #5C5D60; text-decoration: none;"> Descargo de responsabilidad médica</a></div>'+ ' <div><a href="https://kaloni.mx/legal.html#metodos" style="color: #5C5D60; text-decoration: none;"> Métodos de pago</a></div></td>'+ ' </tr>'+ ' <tr>'+ ' <td height="15" style="font-size: 15px; line-height: 15px;"> </td>'+ ' </tr>'+ ' </table>'+ ' <table border="0" width="2" align="left" cellpadding="0" cellspacing="0" style="border-collapse:collapse; mso-table-lspace:0pt; mso-table-rspace:0pt;" class="container590">'+ ' <tr class="hide-800">'+ ' <td width="30" height="10" style="font-size: 10px; line-height: 10px;"></td>'+ ' </tr>'+ ' </table></td>'+ ' </tr>'+ ' </table>'+ ' '+ ' <!-- end Legal --></td>'+ ' </tr>'+ ' <tr>'+ ' <td height="10" style="font-size: 10px; line-height: 10px;"> </td>'+ ' </tr>'+ ' <tr>'+ ' <td align="center" style="color: #aaaaaa; font-size: 14px; font-family: \'Helvetica\', Calibri, sans-serif; line-height: 24px;" class="align-center"><div class="edit_text" style="line-height: 24px;">Copyright KALONI 2019. Todos los derechos reservados.</div></td>'+ ' </tr>'+ ' <tr>'+ ' <td height="20" style="font-size: 20px; line-height: 20px;"> </td>'+ ' </tr>'+ ' </table></td>'+ ' </tr>'+ '</table>'+ '<!-- ======= end section ======= -->'+ ''+ '</body>'+ '</html>'; var result = get_saved_search('customsearch7090', body_mail); // Disparo mailing 61D log.debug('result: ', result); } function get_saved_search(idSearch, body_m) { try { var count = 0; log.debug('idSearch: ', idSearch); var mySearch = search.load({id: idSearch}); var myPagedData = mySearch.runPaged({"pageSize": 1000}); myPagedData.pageRanges.forEach(function(pageRange){ var myPage = myPagedData.fetch({index: pageRange.index}); myPage.data.forEach(function(result){ var parseJSONval = JSON.parse(JSON.stringify(result)); var correo = parseJSONval.values["attendeeCustomer.email"]; if(correo!= "" && correo!= null) { var customerId = ""; //var email = ""; search.create({ type: search.Type.CUSTOMER, filters: [search.createFilter({name: 'email', operator: search.Operator.IS, values: [correo]})], columns: ['internalid', 'email'] }).run().each(function(result){ //var jsonString = JSON.stringify(result); var obj = JSON.parse(jsonString); customerId = result.getValue({name: 'internalid'}); log.debug('customerId: ', customerId); /*email = result.getValue({name: 'email'}); log.debug('email: ', email);*/ return true; }); //var fieldLookUp = search.lookupFields({type: search.Type.CUSTOMER, id: customerId, columns: ['custentity386']}); var objRecord = record.load({type: record.Type.CUSTOMER, id: customerId, isDynamic: true}); var noVolverAcontactar = objRecord.getValue({fieldId: 'custentity386'}); log.debug('noVolverAcontactar: ', noVolverAcontactar); if(noVolverAcontactar == false) { var ccRecip = ['<EMAIL>']; email.send({author: 198528, recipients:correo, subject:'Recordatorio cita de revisión de 3 meses', body:body_m}); // 103204 198528, cc: ccRecip log.debug('Disparo mailing 61D to: ', correo); } } count++; }); }); return true; }catch(e){ log.debug('Exception: ', e); return false; } } return { execute: execute }; }); ======================= File: ue_HideFieldsCustomer2.js ======================= <filename>ue_HideFieldsCustomer2.js /** * @NApiVersion 2.x * @NScriptType UserEventScript * @NModuleScope Public */ define(['N/runtime', 'N/log'], function(runtime, log) { function beforeLoad(context) { if(context.type == "view" || context.type == "edit" || context.type == "create") { log.debug("ue_HideFieldsCustomer2.js", "Inicio beforeLoad("+context.type+")"); var userObj = runtime.getCurrentUser(); log.debug('current user: ', userObj); log.debug("current user role: ", userObj.role); if(userObj.role == "1187") // "1187 = <NAME> - Injerto KHG" { context.form.getField('phone').updateDisplayType({displayType:'hidden'}); context.form.getField('mobilephone').updateDisplayType({displayType:'hidden'}); context.form.getField('homephone').updateDisplayType({displayType:'hidden'}); context.form.getField('email').updateDisplayType({displayType:'hidden'}); } log.debug("ue_HideFieldsCustomer2.js", "Fin beforeLoad("+context.type+")"); } } return { beforeLoad: beforeLoad }; }); ======================= File: cs_precios_Items_SalesOrder.js ======================= <reponame>WizyOs/kaloniScripts /** * @NApiVersion 2.x * @NScriptType ClientScript * @NModuleScope SameAccount */ define(['N/record'],function(record){ function saveRecord(context) { var trandate = context.currentRecord.getText({fieldId: 'trandate'}); console.log('trandate:'+ trandate); if(trandate.indexOf("/")!= -1) { var dateTest_split = trandate.split('/'); var dateTest = dateTest_split[2] + '-' + dateTest_split[1] + '-' + dateTest_split[0]; var resultDate = TDate(dateTest); console.log('resultDate:'+ resultDate); if(resultDate) { var precio_base_Message = ""; var amount_Message = ""; var currentRecord = context.currentRecord; var item_Lines = currentRecord.getLineCount({sublistId : 'item'}); if(item_Lines > 0) { for(var i = 0; i < item_Lines; i++) { currentRecord.selectLine({sublistId: "item", line: i}); var current_quantity = currentRecord.getCurrentSublistText({sublistId: "item", fieldId: "quantity"}); console.log('for loop'+ i +'- current_quantity:' + current_quantity); var current_description = currentRecord.getCurrentSublistText({sublistId: "item", fieldId: "description"}); console.log('for loop'+ i +'- current_description:' + current_description); var current_precio_base = currentRecord.getCurrentSublistValue({sublistId: "item", fieldId: "rate"}); console.log('for loop'+ i +'- current_precio_base:' + current_precio_base); var current_amount = currentRecord.getCurrentSublistValue({sublistId: "item", fieldId: "amount"}); console.log('for loop'+ i +'- current_amount:' + current_amount); var amount_Aux = (current_quantity * current_precio_base).toFixed(2); console.log('for loop'+ i +'- amount_Aux:' + amount_Aux); if((current_description == "<NAME> KHG" || current_description == "PAQUETE BARBA COMPLETA KHG" || current_description == "PAQUETE BARBA DE CANDADO KHG" || current_description == "PAQUETE BIGOTE KHG" || current_description == "PAQUETE DE CEJAS KHG" || current_description == "PAQUETE PATILLA KHG") && (current_precio_base == null || current_precio_base == "" || current_precio_base == "0.00" || current_precio_base == 0 || current_precio_base < 0)) { console.log('current_precio_base es nulo, vacio, 0 o menor a 0'); alert('El campo Rate en los artículos no puede ser 0, vacio o negativo!!'); return false; }else if(current_description == "<NAME> KHG"){ if(current_precio_base < 63000) { precio_base_Message += 'El campo Rate en'+ current_description +'es incorrecto \n'; console.log('El campo Rate en'+ current_description +'no puede ser menor a 63,000'); } else { console.log('El valor Rate'+ current_precio_base +'asignado para'+ current_description +'es correcto!!'); } if(current_amount!= amount_Aux){ amount_Message += 'Amount es incorrecto en'+ current_description +'\n'; console.log('Amount es distinto al resultado de (quantity * rate) en:'+ current_description); } }else if(current_description == "PAQUETE BARBA COMPLETA KHG"){ if(current_precio_base < 60000) { precio_base_Message += 'El campo Rate en'+ current_description +'es incorrecto \n'; console.log('El campo Rate en'+ current_description +'no puede ser menor a 60,000'); } else { console.log('El valor Rate'+ current_precio_base +'asignado para'+ current_description +'es correcto!!'); } if(current_amount!= amount_Aux){ amount_Message += 'Amount es incorrecto en'+ current_description +'\n'; console.log('Amount es distinto al resultado de (quantity * rate) en:'+ current_description); } }else if(current_description == "PAQUETE BARBA DE CANDADO KHG"){ if(current_precio_base < 40000) { precio_base_Message += 'El campo Rate en'+ current_description +'es incorrecto \n'; console.log('El campo Rate en'+ current_description +'no puede ser menor a 40,000'); } else { console.log('El valor Rate'+ current_precio_base +'asignado para'+ current_description +'es correcto!!'); } if(current_amount!= amount_Aux){ amount_Message += 'Amount es incorrecto en'+ current_description +'\n'; console.log('Amount es distinto al resultado de (quantity * rate) en:'+ current_description); } }else if(current_description == "PAQUETE BIGOTE KHG"){ if(current_precio_base < 30000) { precio_base_Message += 'El campo Rate en'+ current_description +'es incorrecto \n'; console.log('El campo Rate en'+ current_description +'no puede ser menor a 30,000'); } else { console.log('El valor Rate'+ current_precio_base +'asignado para'+ current_description +'es correcto!!'); } if(current_amount!= amount_Aux){ amount_Message += 'Amount es incorrecto en'+ current_description +'\n'; console.log('Amount es distinto al resultado de (quantity * rate) en:'+ current_description); } }else if(current_description == "PAQUETE DE CEJAS KHG"){ if(current_precio_base < 30000) { precio_base_Message += 'El campo Rate en'+ current_description +'es incorrecto \n'; console.log('El campo Rate en'+ current_description +'no puede ser menor a 30,000'); } else { console.log('El valor Rate'+ current_precio_base +'asignado para'+ current_description +'es correcto!!'); } if(current_amount!= amount_Aux){ amount_Message += 'Amount es incorrecto en'+ current_description +'\n'; console.log('Amount es distinto al resultado de (quantity * rate) en:'+ current_description); } }else if(current_description == "PAQUETE PATILLA KHG"){ if(current_precio_base < 40000) { precio_base_Message += 'El campo Rate en'+ current_description +'es incorrecto \n'; console.log('El campo Rate en'+ current_description +'no puede ser menor a 40,000'); } else { console.log('El valor Rate'+ current_precio_base +'asignado para'+ current_description +'es correcto!!'); } if(current_amount!= amount_Aux){ amount_Message += 'Amount es incorrecto en'+ current_description +'\n'; console.log('Amount es distinto al resultado de (quantity * rate) en:'+ current_description); } } } } else { console.log('item_Lines:'+ item_Lines); return false; } if(precio_base_Message!= "" && precio_base_Message!= null){ alert(precio_base_Message); return false; } if(amount_Message!= "" && amount_Message!= null){ alert(amount_Message); return false; } } else { //alert("La fecha de creación de la orden de venta fue antes o igual que 2019-11-15"); console.log("La fecha de creación de la orden de venta fue antes o igual que 2019-11-15"); //return false; } } else { console.log("no hay fecha de creación!!"); } return true; } function TDate(UserDate){ if(new Date(UserDate).getTime() <= new Date('2019-11-15').getTime()) return false; return true; } return{ saveRecord:saveRecord }; }); ======================= File: SuiteScript 2.0 API/https/clientCertificate.js ======================= /** * SuiteScript module * * @module N/https/clientCertificate * @NApiVersion 2.x * */ function clientCertificate() {} /** * Sends ssl secured post to remote server * @governance 10 units * @param {Object} options * @param {String} options.url address of remote server * @param {String} options.certId id of client certificate * @param {String} options.body data to be sent to remote server * @param {Object} options.headers headers associated with the request * * @returns {ClientResponse} response from remote server */ function doPost() { } /** * Sends ssl secured get to remote server * @governance 10 units * @param {Object} options * @param {String} options.url address of remote server * @param {String} options.certId id of client certificate * @param {Object} options.headers headers associated with the request * * @returns {ClientResponse} response from remote server */ function doGet() { } /** * Sends ssl secured put to remote server * @governance 10 units * @param {Object} options * @param {String} options.url address of remote server * @param {String} options.certId id of client certificate * @param {String} options.body data to be sent to remote server * @param {Object} options.headers headers associated with the request * * @returns {ClientResponse} response from remote server */ function doPut() { } /** * Sends ssl secured delete to remote server * @governance 10 units * @param {Object} options * @param {String} options.url address of remote server * @param {String} options.certId id of client certificate * @param {Object} options.headers headers associated with the request * * @returns {ClientResponse} response from remote server */ function doDelete() { } /** * Sends ssl secured request to remote server * @governance 10 units * @param {Object} options * @param {String} options.url address of remote server * @param {String} options.certId id of client certificate * @param {String} options.body data to be sent to remote server * @param {Object} options.method http method to be used * @param {Object} options.headers headers associated with the request * * @returns {ClientResponse} response from remote server */ function request() { } clientCertificate = new clientCertificate(); var https = {}; /** * @type {https} */ N.prototype.https = https; /** * @type {clientCertificate} */ https.prototype.clientCertificate = clientCertificate; ======================= File: ScriptFactory/script_save_search/otrosDX.js ======================= <reponame>WizyOs/kaloniScripts<filename>ScriptFactory/script_save_search/otrosDX.js<gh_stars>0 function otrosDX(){ var sucursal1 = 'Santa Fe KHG'; var sucursal2 = 'Altavista KHG'; var sucursal3 = 'Guadalajara KHG'; var sucursal4 = 'Monterrey KHG'; var sucursal5 = 'Polanco KHG'; var sucursal6 = 'Satelite KHG'; var sucursal7 = 'Tijuana KHG'; var sucursal8 = 'Veracruz KHG'; var sucursal9 = 'Bogota'; var sucursal10 = 'São Paulo'; var sucursal11 = 'Can-Cun KHG'; var sucursal12 = 'Chihuahua KHG'; var sucursal13 = 'Puebla KHG'; var sucursal14 = 'Madrid'; var sucursal15 = 'Medellin'; var sucursal16 = 'Santo Domingo'; var sucursal17 = 'Velazquez'; var count=''; var location=''; /*BÚSQUEDA biopsia*/ var revresults = nlapiSearchRecord ('calendarevent','customsearch2979'); for(var z=0; z<revresults.length; z++) { var result1=revresults[z]; var column1=result1.getAllColumns(); var sucursal =result1.getText(column1[1]); count =result1.getValue(column1[0]); if(sucursal==sucursal1){ location = nlapiLoadRecord('location',21);//santa fe location.setFieldValue('custrecord13', count);//biopsia nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal2){ location = nlapiLoadRecord('location',22);//altavista location.setFieldValue('custrecord13', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal3){ location = nlapiLoadRecord('location',23);//guadalajara location.setFieldValue('custrecord13', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal4){ location = nlapiLoadRecord('location',24);//monterrey location.setFieldValue('custrecord13', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal5){ location = nlapiLoadRecord('location',25);//polanco location.setFieldValue('custrecord13', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal6){ location = nlapiLoadRecord('location',26);//satelite location.setFieldValue('custrecord13', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal7){ location = nlapiLoadRecord('location',27);//tijuana location.setFieldValue('custrecord13', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal8){ location = nlapiLoadRecord('location',28);//veracruz location.setFieldValue('custrecord13', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal9){ location = nlapiLoadRecord('location',31);//bogota location.setFieldValue('custrecord13', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal10){ location = nlapiLoadRecord('location',34);//Sao paulo location.setFieldValue('custrecord13', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal11){ location = nlapiLoadRecord('location',35);//can-cun location.setFieldValue('custrecord13', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal12){ location = nlapiLoadRecord('location',36);//chihuahua location.setFieldValue('custrecord13', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal13){ location = nlapiLoadRecord('location',37);//puebla location.setFieldValue('custrecord13', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal14){ location = nlapiLoadRecord('location',39);//madrid españa location.setFieldValue('custrecord13', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal15){ location = nlapiLoadRecord('location',42);//MEDELLIN location.setFieldValue('custrecord13', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal16){ location = nlapiLoadRecord('location',45);//Santo Domingo location.setFieldValue('custrecord13', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal17){ location = nlapiLoadRecord('location',46);//Velazquez location.setFieldValue('custrecord13', count); nlapiSubmitRecord(location, true); continue; } } /*BÚSQUEDA intensivo*/ var revresults = nlapiSearchRecord ('calendarevent','customsearch2983'); for(var z=0; z<revresults.length; z++) { var result1=revresults[z]; var column1=result1.getAllColumns(); var sucursal =result1.getText(column1[1]); count =result1.getValue(column1[0]); if(sucursal==sucursal1){ location = nlapiLoadRecord('location',21);//santa fe location.setFieldValue('custrecord16', count);//intensivo nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal2){ location = nlapiLoadRecord('location',22);//altavista location.setFieldValue('custrecord16', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal3){ location = nlapiLoadRecord('location',23);//guadalajara location.setFieldValue('custrecord16', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal4){ location = nlapiLoadRecord('location',24);//monterrey location.setFieldValue('custrecord16', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal5){ location = nlapiLoadRecord('location',25);//polanco location.setFieldValue('custrecord16', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal6){ location = nlapiLoadRecord('location',26);//satelite location.setFieldValue('custrecord16', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal7){ location = nlapiLoadRecord('location',27);//tijuana location.setFieldValue('custrecord16', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal8){ location = nlapiLoadRecord('location',28);//veracruz location.setFieldValue('custrecord16', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal9){ location = nlapiLoadRecord('location',31);//bogota location.setFieldValue('custrecord16', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal10){ location = nlapiLoadRecord('location',34);//Sao paulo location.setFieldValue('custrecord16', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal11){ location = nlapiLoadRecord('location',35);//can-cun location.setFieldValue('custrecord16', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal12){ location = nlapiLoadRecord('location',36);//chihuahua location.setFieldValue('custrecord16', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal13){ location = nlapiLoadRecord('location',37);//puebla location.setFieldValue('custrecord16', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal14){ location = nlapiLoadRecord('location',39);//madrid españa location.setFieldValue('custrecord16', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal15){ location = nlapiLoadRecord('location',42);//MEDELLIN location.setFieldValue('custrecord16', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal16){ location = nlapiLoadRecord('location',45);//Santo Domingo location.setFieldValue('custrecord16', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal17){ location = nlapiLoadRecord('location',46);//Velazquez location.setFieldValue('custrecord16', count); nlapiSubmitRecord(location, true); continue; } } /*BÚSQUEDA mantenimiento*/ var revresults = nlapiSearchRecord ('calendarevent','customsearch2980'); for(var z=0; z<revresults.length; z++) { var result1=revresults[z]; var column1=result1.getAllColumns(); var sucursal =result1.getText(column1[1]); count =result1.getValue(column1[0]); if(sucursal==sucursal1){ location = nlapiLoadRecord('location',21);//santa fe location.setFieldValue('custrecord17', count);//mantenimiento nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal2){ location = nlapiLoadRecord('location',22);//altavista location.setFieldValue('custrecord17', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal3){ location = nlapiLoadRecord('location',23);//guadalajara location.setFieldValue('custrecord17', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal4){ location = nlapiLoadRecord('location',24);//monterrey location.setFieldValue('custrecord17', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal5){ location = nlapiLoadRecord('location',25);//polanco location.setFieldValue('custrecord17', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal6){ location = nlapiLoadRecord('location',26);//satelite location.setFieldValue('custrecord17', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal7){ location = nlapiLoadRecord('location',27);//tijuana location.setFieldValue('custrecord17', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal8){ location = nlapiLoadRecord('location',28);//veracruz location.setFieldValue('custrecord17', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal9){ location = nlapiLoadRecord('location',31);//bogota location.setFieldValue('custrecord17', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal10){ location = nlapiLoadRecord('location',34);//Sao paulo location.setFieldValue('custrecord17', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal11){ location = nlapiLoadRecord('location',35);//can-cun location.setFieldValue('custrecord17', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal12){ location = nlapiLoadRecord('location',36);//chihuahua location.setFieldValue('custrecord17', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal13){ location = nlapiLoadRecord('location',37);//puebla location.setFieldValue('custrecord17', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal14){ location = nlapiLoadRecord('location',39);//madrid españa location.setFieldValue('custrecord17', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal15){ location = nlapiLoadRecord('location',42);//MEDELLIN location.setFieldValue('custrecord17', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal16){ location = nlapiLoadRecord('location',45);//Santo Domingo location.setFieldValue('custrecord17', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal17){ location = nlapiLoadRecord('location',46);//Velazquez location.setFieldValue('custrecord17', count); nlapiSubmitRecord(location, true); continue; } } /*BÚSQUEDA protesis*/ var revresults = nlapiSearchRecord ('calendarevent','customsearch2981'); for(var z=0; z<revresults.length; z++) { var result1=revresults[z]; var column1=result1.getAllColumns(); var sucursal =result1.getText(column1[1]); count =result1.getValue(column1[0]); if(sucursal==sucursal1){ location = nlapiLoadRecord('location',21);//santa fe location.setFieldValue('custrecord154', count);//mantenimiento nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal2){ location = nlapiLoadRecord('location',22);//altavista location.setFieldValue('custrecord154', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal3){ location = nlapiLoadRecord('location',23);//guadalajara location.setFieldValue('custrecord154', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal4){ location = nlapiLoadRecord('location',24);//monterrey location.setFieldValue('custrecord154', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal5){ location = nlapiLoadRecord('location',25);//polanco location.setFieldValue('custrecord154', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal6){ location = nlapiLoadRecord('location',26);//satelite location.setFieldValue('custrecord154', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal7){ location = nlapiLoadRecord('location',27);//tijuana location.setFieldValue('custrecord154', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal8){ location = nlapiLoadRecord('location',28);//veracruz location.setFieldValue('custrecord154', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal9){ location = nlapiLoadRecord('location',31);//bogota location.setFieldValue('custrecord154', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal10){ location = nlapiLoadRecord('location',34);//Sao paulo location.setFieldValue('custrecord154', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal11){ location = nlapiLoadRecord('location',35);//can-cun location.setFieldValue('custrecord154', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal12){ location = nlapiLoadRecord('location',36);//chihuahua location.setFieldValue('custrecord154', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal13){ location = nlapiLoadRecord('location',37);//puebla location.setFieldValue('custrecord154', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal14){ location = nlapiLoadRecord('location',39);//madrid españa location.setFieldValue('custrecord154', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal15){ location = nlapiLoadRecord('location',42);//MEDELLIN location.setFieldValue('custrecord154', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal16){ location = nlapiLoadRecord('location',45);//Santo Domingo location.setFieldValue('custrecord154', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal17){ location = nlapiLoadRecord('location',46);//Velazquez location.setFieldValue('custrecord154', count); nlapiSubmitRecord(location, true); continue; } } /*BÚSQUEDA txmedico*/ var revresults = nlapiSearchRecord ('calendarevent','customsearch2982'); for(var z=0; z<revresults.length; z++) { var result1=revresults[z]; var column1=result1.getAllColumns(); var sucursal =result1.getText(column1[1]); count =result1.getValue(column1[0]); if(sucursal==sucursal1){ location = nlapiLoadRecord('location',21);//santa fe location.setFieldValue('custrecord12', count);//tx medico nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal2){ location = nlapiLoadRecord('location',22);//altavista location.setFieldValue('custrecord12', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal3){ location = nlapiLoadRecord('location',23);//guadalajara location.setFieldValue('custrecord12', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal4){ location = nlapiLoadRecord('location',24);//monterrey location.setFieldValue('custrecord12', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal5){ location = nlapiLoadRecord('location',25);//polanco location.setFieldValue('custrecord12', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal6){ location = nlapiLoadRecord('location',26);//satelite location.setFieldValue('custrecord12', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal7){ location = nlapiLoadRecord('location',27);//tijuana location.setFieldValue('custrecord12', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal8){ location = nlapiLoadRecord('location',28);//veracruz location.setFieldValue('custrecord12', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal9){ location = nlapiLoadRecord('location',31);//bogota location.setFieldValue('custrecord12', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal10){ location = nlapiLoadRecord('location',34);//Sao paulo location.setFieldValue('custrecord12', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal11){ location = nlapiLoadRecord('location',35);//can-cun location.setFieldValue('custrecord12', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal12){ location = nlapiLoadRecord('location',36);//chihuahua location.setFieldValue('custrecord12', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal13){ location = nlapiLoadRecord('location',37);//puebla location.setFieldValue('custrecord12', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal14){ location = nlapiLoadRecord('location',39);//madrid españa location.setFieldValue('custrecord12', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal15){ location = nlapiLoadRecord('location',42);//MEDELLIN location.setFieldValue('custrecord12', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal16){ location = nlapiLoadRecord('location',45);//Santo Domingo location.setFieldValue('custrecord12', count); nlapiSubmitRecord(location, true); continue; } if(sucursal==sucursal17){ location = nlapiLoadRecord('location',46);//Velazquez location.setFieldValue('custrecord12', count); nlapiSubmitRecord(location, true); continue; } } } ======================= File: SuiteScript 2.0 API/format.js ======================= /** * SuiteScript format module * * @module N/format * @NApiVersion 2.x * */ function format() {} /** * Parse a value from the appropriate preference formatted-value to a raw value. * * @param {Object} options * @param {string} options.value the data you wish to parse * @param {string} options.type the field type i.e. DATE, CURRENCY, INTEGER * @param {string} options.timezone (optional & applicable to type DATETIME only) specifies which timezone the value is from. * default is the timezone set in the user's preferences * * @throws {SuiteScriptError} SSS_MISSING_REQD_ARGUMENT if either value or type is missing * * @return {Date|string|number} If parseable, the parsed value. If not or given an invalid Type, the value passed in options.value * * @since 2015.2 */ format.prototype.parse = function(options) {}; /** * Parse a value from the raw value to its appropriate preference formatted-value. * * @param {Object} options * @param {Date|string|number} options.value the data you wish to format * @param {string} options.type the field type i.e. DATE, CURRENCY, INTEGER * @param {string} options.timezone (optional & applicable to type DATETIME only) specifies which timezone to format to. * default is the timezone set in the user's preferences * * @throws {SuiteScriptError} SSS_MISSING_REQD_ARGUMENT if either value or type is missing * * @return {string} If format-able, the formatted value. If not or given an invalid Type, the value passed in options.value * * @since 2015.2 */ format.prototype.format = function(options) {}; /** * Enum for field types. * @enum {string} */ function formatType() { this.DATE = 'date'; this.TIME = 'time'; this.TIMETRACK = 'timetrack'; this.TIMEOFDAY = 'timeofday'; this.DATETIME = 'datetime'; this.DATETIMETZ = 'datetimetz'; this.INTEGER = 'integer'; this.POSINTEGER = 'posinteger'; this.PERCENT = 'percent'; this.RATE = 'rate'; this.RATEHIGHPRECISION = 'ratehighprecision'; this.DYNAMICPRECISION = 'dynamicprecision'; this.FLOAT = 'float'; this.POSFLOAT = 'posfloat'; this.NONNEGFLOAT = 'nonnegfloat'; this.POSCURRENCY = 'poscurrency'; this.NONNEGCURRENCY = 'nonnegcurrency'; this.CURRENCY = 'currency'; this.CURRENCY2 = 'currency2'; this.EMAIL = 'email'; this.EMAILS = 'emails'; this.URL = 'url'; this.CHECKBOX = 'checkbox'; this.CCNUMBER = 'ccnumber'; this.RADIO = 'radio'; this.PHONE = 'phone'; this.FULLPHONE = 'fullphone'; this.IDENTIFIER = 'identifier'; this.IDENTIFIERANYCASE = 'identifieranycase'; this.FUNCTION = 'function'; this.QUOTEDFUNCTION = ''function''; this.MMYYDATE ='mmyydate'; this.CCEXPDATE = 'ccexpdate'; this.CCVALIDFROM = 'ccvalidfrom'; this.COLOR = 'color'; this.PACKAGE = 'package'; this.FURIGANA = 'furigana'; this.ADDRESS = 'address'; this.TEXT = 'text'; this.TEXTAREA = 'textarea'; this.SELECT ='select'; this.DOCUMENT = 'document'; } format.prototype.Type = formatType; /** * Enum for Time Zones. * @enum {string} */ function formatTimezone() { this.ETC_GMT_PLUS_12 = 'Etc/GMT+12'; this.PACIFIC_SAMOA = 'Pacific/Samoa'; this.PACIFIC_HONOLULU = 'Pacific/Honolulu'; this.AMERICA_ANCHORAGE = 'America/Anchorage'; this.AMERICA_LOS_ANGELES = 'America/Los_Angeles'; this.AMERICA_TIJUANA = 'America/Tijuana'; this.AMERICA_DENVER = 'America/Denver'; this.AMERICA_PHOENIX = 'America/Phoenix'; this.AMERICA_CHIHUAHUA = 'America/Chihuahua'; this.AMERICA_CHICAGO = 'America/Chicago'; this.AMERICA_REGINA = 'America/Regina'; this.AMERICA_GUATEMALA = 'America/Guatemala'; this.AMERICA_MEXICO_CITY = 'America/Mexico_City'; this.AMERICA_NEW_YORK = 'America/New_York'; this.US_EAST_INDIANA = 'US/East-Indiana'; this.AMERICA_BOGOTA = 'America/Bogota'; this.AMERICA_CARACAS = 'America/Caracas'; this.AMERICA_HALIFAX = 'America/Halifax'; this.AMERICA_LA_PAZ = 'America/La_Paz'; this.AMERICA_MANAUS = 'America/Manaus'; this.AMERICA_SANTIAGO = 'America/Santiago'; this.AMERICA_ST_JOHNS = 'America/St_Johns'; this.AMERICA_SAO_PAULO = 'America/Sao_Paulo'; this.AMERICA_BUENOS_AIRES = 'America/Buenos_Aires'; this.ETC_GMT_PLUS_3 = 'Etc/GMT+3'; this.AMERICA_GODTHAB = 'America/Godthab'; this.AMERICA_MONTEVIDEO = 'America/Montevideo'; this.AMERICA_NORONHA = 'America/Noronha'; this.ETC_GMT_PLUS_1 = 'Etc/GMT+1'; this.ATLANTIC_AZORES = 'Atlantic/Azores'; this.EUROPE_LONDON = 'Europe/London'; this.GMT = 'GMT'; this.ATLANTIC_REYKJAVIK = 'Atlantic/Reykjavik'; this.EUROPE_WARSAW = 'Europe/Warsaw'; this.EUROPE_PARIS = 'Europe/Paris'; this.ETC_GMT_MINUS_1 = 'Etc/GMT-1'; this.EUROPE_AMSTERDAM = 'Europe/Amsterdam'; this.EUROPE_BUDAPEST = 'Europe/Budapest'; this.AFRICA_CAIRO = 'Africa/Cairo'; this.EUROPE_ISTANBUL = 'Europe/Istanbul'; this.ASIA_JERUSALEM = 'Asia/Jerusalem'; this.ASIA_AMMAN = 'Asia/Amman'; this.ASIA_BEIRUT = 'Asia/Beirut'; this.AFRICA_JOHANNESBURG = 'Africa/Johannesburg'; this.EUROPE_KIEV = 'Europe/Kiev'; this.EUROPE_MINSK = 'Europe/Minsk'; this.AFRICA_WINDHOEK = 'Africa/Windhoek'; this.ASIA_RIYADH = 'Asia/Riyadh'; this.EUROPE_MOSCOW = 'Europe/Moscow'; this.ASIA_BAGHDAD = 'Asia/Baghdad'; this.AFRICA_NAIROBI = 'Africa/Nairobi'; this.ASIA_TEHRAN = 'Asia/Tehran'; this.ASIA_MUSCAT = 'Asia/Muscat'; this.ASIA_BAKU = 'Asia/Baku'; this.ASIA_YEREVAN = 'Asia/Yerevan'; this.ETC_GMT_MINUS_3 = 'Etc/GMT-3'; this.ASIA_KABUL = 'Asia/Kabul'; this.ASIA_KARACHI = 'Asia/Karachi'; this.ASIA_YEKATERINBURG = 'Asia/Yekaterinburg'; this.ASIA_TASHKENT = 'Asia/Tashkent'; this.ASIA_CALCUTTA = 'Asia/Calcutta'; this.ASIA_KATMANDU = 'Asia/Katmandu'; this.ASIA_ALMATY = 'Asia/Almaty'; this.ASIA_DHAKA = 'Asia/Dhaka'; this.ASIA_RANGOON = 'Asia/Rangoon'; this.ASIA_BANGKOK = 'Asia/Bangkok'; this.ASIA_KRASNOYARSK = 'Asia/Krasnoyarsk'; this.ASIA_HONG_KONG = 'Asia/Hong_Kong'; this.ASIA_KUALA_LUMPUR = 'Asia/Kuala_Lumpur'; this.ASIA_TAIPEI = 'Asia/Taipei'; this.AUSTRALIA_PERTH = 'Australia/Perth'; this.ASIA_IRKUTSK = 'Asia/Irkutsk'; this.ASIA_MANILA = 'Asia/Manila'; this.ASIA_SEOUL = 'Asia/Seoul'; this.ASIA_TOKYO = 'Asia/Tokyo'; this.ASIA_YAKUTSK = 'Asia/Yakutsk'; this.AUSTRALIA_DARWIN = 'Australia/Darwin'; this.AUSTRALIA_ADELAIDE = 'Australia/Adelaide'; this.AUSTRALIA_SYDNEY = 'Australia/Sydney'; this.AUSTRALIA_BRISBANE = 'Australia/Brisbane'; this.AUSTRALIA_HOBART = 'Australia/Hobart'; this.PACIFIC_GUAM = 'Pacific/Guam'; this.ASIA_VLADIVOSTOK = 'Asia/Vladivostok'; this.PACIFIC_GUADALCANAL = 'Pacific/Guadalcanal'; this.PACIFIC_KWAJALEIN = 'Pacific/Kwajalein'; this.PACIFIC_AUCKLAND = 'Pacific/Auckland'; this.PACIFIC_TONGATAPU = 'Pacific/Tongatapu'; } format.prototype.Timezone = formatTimezone; format = new format(); /** * @type {format} */ N.prototype.format = format; ======================= File: SuiteScript 2.0 API/ui/dialog.js ======================= /** * SuiteScript Dialog Module (Client Side) * * @module N/ui/dialog * @suiteScriptVersion 2.x * */ function dialog() {} /** * Creates an Alert Dialog with an OK Button. * * @restriction Client SuiteScript only * * @param {Object} options * @param {string} [options.title] The title of the alert. Defaults to empty string. * @param {string} [options.message] The content of the alert. Defaults to empty string. * * @return {Promise} A Promise object. Pass a function into the then portion to fire a callback when the button is pressed. * The callback will be passed in a response object which contains the value of the button where: * OK returns true. * @since 2016.1 */ dialog.prototype.alert = function(options) {}; /** * Creates an Confirm Dialog with an OK and Cancel Button. * * @restriction Client SuiteScript only * * @param {Object} options * @param {string} [options.title] The title of the confirmation box. Defaults to empty string. * @param {string} [options.message] The content of the confirmation box. Defaults to empty string. * * @return {Promise} A Promise object. Pass a function into the then portion to fire a callback when the button is pressed. * The callback will be passed in a response object which contains the value of the button where: * OK returns true and Cancel returns false. * @since 2016.1 */ dialog.prototype.confirm = function(options) {}; /** * Creates an Dialog with the specified buttons. * * @restriction Client SuiteScript only * * @param {Object} options * @param {string} [options.title] The title of the dialog box. Defaults to empty string. * @param {string} [options.message] The content of the dialog box. Defaults to empty string. * @param {string} [options.buttons] The list of buttons to add. Each item in the list requires a label and value. * If empty, defaults to a button with label "OK" and value true. * * @return {Promise} A Promise object. Pass a function into the then portion to fire a callback when the button is pressed. * The callback will be passed in a response object which contains the value of the button where: * OK returns true and Cancel returns false. * @since 2016.1 * * @throws {SuiteScriptError} WRONG_PARAMETER_TYPE if options.buttons is specified and is not an array. * @throws {SuiteScriptError} BUTTONS_MUST_INCLUDE_BOTH_A_LABEL_AND_VALUE if options.buttons is specified and one or more items do not have a label and/or value. */ dialog.prototype.create = function(options) {}; dialog = new dialog(); var ui = {}; /** * @type {ui} */ N.prototype.ui = ui; /** * @type {dialog} */ ui.prototype.dialog = dialog; ======================= File: SuiteScript 2.0 API/sessionRecordHandler.js ======================= /** * SuiteScript module * * @module N/sessionRecordHandler * @public * @NApiVersion 2.x * */ function sessionRecordHandler() {} sessionRecordHandler = new sessionRecordHandler(); /** * @type {sessionRecordHandler} */ N.prototype.sessionRecordHandler = sessionRecordHandler; ======================= File: cs_precios_Items_Invoice_Esp.js ======================= <reponame>WizyOs/kaloniScripts<filename>cs_precios_Items_Invoice_Esp.js /** * @NApiVersion 2.x * @NScriptType ClientScript * @NModuleScope SameAccount */ define(['N/record', 'N/currentRecord', 'N/log'],function(record, currentRec, log){ function pageInit(context) { //context.currentRecord.setValue({fieldId: 'customform', value: '148', ignoreFieldChange: true}); /*alert(context.mode); var btnEdit = document.getElementById("secondaryedit").value; //var tranidVal = document.getElementById("id").value; console.log(btnEdit); alert(btnEdit); var cuRec = currentRec.get(); console.log('id1:'+ cuRec.id); log.debug('cuRec: ', cuRec); if(cuRec.type === "purchaseorder") { var tranid = currentRec.getValue({fieldId: 'tranid'}); log.debug('tranid1: ', tranid); }*/ } function saveRecord(context) { var createdfrom = context.currentRecord.getValue({fieldId: 'createdfrom'}); console.log('invoice from sales order id:'+ createdfrom); if(createdfrom!= null && createdfrom!= "") { var rec_SO = record.load({type:'salesorder', id: createdfrom}); var createdfrom_createddate_SO = rec_SO.getText({fieldId: 'createddate'}); console.log('createdfrom_createddate_SO:'+ createdfrom_createddate_SO); var dateTest_split = createdfrom_createddate_SO.split('/'); var dateTest = dateTest_split[2].substring(0, 4) + '-' + dateTest_split[1] + '-' + dateTest_split[0]; var resultDate = TDate(dateTest); console.log('resultDate:'+ resultDate); if(resultDate){ var subsidiary = context.currentRecord.getValue({fieldId:'subsidiary'}); console.log('subsidiary:'+ subsidiary); if(subsidiary == "12") { var final_Message = ""; var currentRecord = context.currentRecord; var item_Lines = currentRecord.getLineCount({sublistId : 'item'}); if(item_Lines > 0) { for(var i = 0; i < item_Lines; i++) { currentRecord.selectLine({sublistId: "item", line: i}); //log.debug('itemInfo: ', itemInfo); var current_concepto = currentRecord.getCurrentSublistText({sublistId: "item", fieldId: "description"}); console.log('for loop'+ i +'- current_concepto:' + current_concepto); var current_precio_unit = currentRecord.getCurrentSublistValue({sublistId: "item", fieldId: "rate"}); console.log('for loop'+ i +'- current_precio_unit:' + current_precio_unit); if(current_concepto == "HONORARIOS MICRO INJERTO DE CABELLO ESP" && (current_precio_unit == null || current_precio_unit == "" || current_precio_unit == "0.00" || current_precio_unit == 0 || current_precio_unit < 0)) { console.log('current_precio_unit es nulo, vacio, 0 o menor a 0'); alert('El precio unitario de'+ current_concepto +'no puede ser 0, vacio o negativo!!'); return false; }else if(current_concepto == "HONORARIOS MICRO INJERTO DE CABELLO ESP"){ if(current_precio_unit < 3200) { final_Message += 'El precio unitario de'+ current_concepto +'es incorrecto \n'; console.log('El precio unitario de'+ current_concepto +'no puede ser menor a 3,200'); } else { console.log('El precio'+ current_precio_unit +'asignado para'+ current_concepto +'es correcto!!'); //return false; } } } } else { console.log('No hay articulos:'+ item_Lines); return false; } if(final_Message!= "" && final_Message!= null){ alert(final_Message); return false; } } } else { console.log("La fecha de creación de la orden de venta fue antes o igual que 2019-12-31"); //return false; } } return true; } function TDate(UserDate){ if(new Date(UserDate).getTime() <= new Date('2019-12-31').getTime()) return false; return true; } return{ pageInit: pageInit, saveRecord:saveRecord }; }); ======================= File: cs_precios_Items_Invoice.js ======================= /** * @NApiVersion 2.x * @NScriptType ClientScript * @NModuleScope SameAccount */ define(['N/record', 'N/currentRecord'],function(record, currentRec){ function pageInit(context) { //context.currentRecord.setValue({fieldId: 'customform', value: '148', ignoreFieldChange: true}); /*alert(context.mode); var btnEdit = document.getElementById("secondaryedit").value; //var tranidVal = document.getElementById("id").value; console.log(btnEdit); alert(btnEdit); var cuRec = currentRec.get(); console.log('id1:'+ cuRec.id); log.debug('cuRec: ', cuRec); if(cuRec.type === "purchaseorder") { var tranid = currentRec.getValue({fieldId: 'tranid'}); log.debug('tranid1: ', tranid); }*/ } function saveRecord(context) { var createdfrom = context.currentRecord.getValue({fieldId: 'createdfrom'}); console.log('invoice from sales order id:'+ createdfrom); if(createdfrom!= null && createdfrom!= "") { var rec_SO = record.load({type:'salesorder', id: createdfrom}); var createdfrom_trandate_SO = rec_SO.getText({fieldId: 'trandate'}); console.log('createdfrom_trandate_SO:'+ createdfrom_trandate_SO); var dateTest_split = createdfrom_trandate_SO.split('/'); var dateTest = dateTest_split[2] + '-' + dateTest_split[1] + '-' + dateTest_split[0]; var resultDate = TDate(dateTest); console.log('resultDate:'+ resultDate); if(resultDate) { var final_Message = ""; var currentRecord = context.currentRecord; var item_Lines = currentRecord.getLineCount({sublistId : 'item'}); if(item_Lines > 0) { for(var i = 0; i < item_Lines; i++) { currentRecord.selectLine({sublistId: "item", line: i}); var current_description = currentRecord.getCurrentSublistText({sublistId: "item", fieldId: "description"}); console.log('for loop'+ i +'- current_description:' + current_description); var current_precio_unit = currentRecord.getCurrentSublistValue({sublistId: "item", fieldId: "rate"}); console.log('for loop'+ i +'- current_precio_unit:' + current_precio_unit); if((current_description == "H<NAME> KHG" || current_description == "PAQUETE BARBA COMPLETA KHG" || current_description == "PAQUETE BARBA DE CANDADO KHG" || current_description == "PAQUETE BIGOTE KHG" || current_description == "PAQUETE DE CEJAS KHG" || current_description == "PAQUETE PATILLA KHG") && (current_precio_unit == null || current_precio_unit == "" || current_precio_unit == "0.00" || current_precio_unit == 0 || current_precio_unit < 0)) { console.log('current_precio_unit es nulo, vacio, 0 o menor a 0'); alert('El precio unitario de los artículos no puede ser 0, vacio o negativo!!'); return false; }else if(current_description == "<NAME> CABELLO KHG"){ if(current_precio_unit < 63000) { final_Message += 'El precio unitario de'+ current_description +'es incorrecto \n'; console.log('El precio unitario de'+ current_description +'no puede ser menor a 63,000'); } else { console.log('El precio'+ current_precio_unit +'asignado para'+ current_description +'es correcto!!'); } }else if(current_description == "PAQUETE BARBA COMPLETA KHG"){ if(current_precio_unit < 60000) { final_Message += 'El precio unitario de'+ current_description +'es incorrecto \n'; console.log('El precio unitario de'+ current_description +'no puede ser menor a 60,000'); } else { console.log('El precio'+ current_precio_unit +'asignado para'+ current_description +'es correcto!!'); } }else if(current_description == "PAQUETE BARBA DE CANDADO KHG"){ if(current_precio_unit < 40000) { final_Message += 'El precio unitario de'+ current_description +'es incorrecto \n'; console.log('El precio unitario de'+ current_description +'no puede ser menor a 40,000'); } else { console.log('El precio'+ current_precio_unit +'asignado para'+ current_description +'es correcto!!'); } }else if(current_description == "PAQUETE BIGOTE KHG"){ if(current_precio_unit < 30000) { final_Message += 'El precio unitario de'+ current_description +'es incorrecto \n'; console.log('El precio unitario de'+ current_description +'no puede ser menor a 30,000'); } else { console.log('El precio'+ current_precio_unit +'asignado para'+ current_description +'es correcto!!'); } }else if(current_description == "PAQUETE DE CEJAS KHG"){ if(current_precio_unit < 30000) { final_Message += 'El precio unitario de'+ current_description +'es incorrecto \n'; console.log('El precio unitario de'+ current_description +'no puede ser menor a 30,000'); } else { console.log('El precio'+ current_precio_unit +'asignado para'+ current_description +'es correcto!!'); } }else if(current_description == "<NAME> KHG"){ if(current_precio_unit < 40000) { final_Message += 'El precio unitario de'+ current_description +'es incorrecto \n'; console.log('El precio unitario de'+ current_description +'no puede ser menor a 40,000'); } else { console.log('El precio'+ current_precio_unit +'asignado para'+ current_description +'es correcto!!'); } } } } else { console.log('item_Lines:'+ item_Lines); return false; } if(final_Message!= "" && final_Message!= null){ alert(final_Message); return false; } } else { //alert("La fecha de creación de la orden de venta fue antes o igual que 2019-11-15"); console.log("La fecha de creación de la orden de venta fue antes o igual que 2019-11-15"); //return false; } } return true; } function TDate(UserDate){ if(new Date(UserDate).getTime() <= new Date('2019-11-15').getTime()) return false; return true; } return{ pageInit: pageInit, saveRecord:saveRecord }; }); /* var item_Lines11 = invoice.getLineCount({sublistId : 'item'}); if(item_Lines11 > 0) { for(var i = 0; i < item_Lines11; i++) { var valor_codigo = invoice.getSublistValue({sublistId:'item', fieldId:'item', line:i}); // codigo item var valor_description = invoice.getSublistText({sublistId:'item', fieldId:'description', line:i}); //descripcion var valor_units_display = invoice.getSublistValue({sublistId:'item', fieldId:'units_display', line:i}); // unidades var valor_quantity = invoice.getSublistValue({sublistId:'item', fieldId:'quantity', line:i}); // cantidad if(valor_quantity == null || valor_quantity == "") valor_quantity = 1; var valor_rate = invoice.getSublistValue({sublistId:'item', fieldId:'rate', line:i}); // precio unitario item var valor_amount = invoice.getSublistValue({sublistId:'item', fieldId:'amount', line:i}); // precio total item (precio unitario item * cantidad) if(valor_amount == null || valor_amount == "") valor_amount = (valor_rate * valor_quantity); var valor_taxrate1 = invoice.getSublistValue({sublistId:'item', fieldId:'taxrate1', line:i}); // porcentaje impuesto aplicado var valor_tax1amt = invoice.getSublistValue({sublistId:'item', fieldId:'tax1amt', line:i}); // impuesto aplicado var valor_grossamt = invoice.getSublistValue({sublistId:'item', fieldId:'grossamt', line:i}); // (precio total item + impuesto aplicado) var valor_itemtype = invoice.getSublistValue({sublistId:'item', fieldId:'itemtype', line:i}); // itemtype */ /* function fieldChanged(context) { if(context.sublistId == 'item' && context.fieldId == 'amount') { var currentRecord = context.currentRecord; var sublist_amount = currentRecord.getCurrentSublistValue({sublistId:'item', fieldId:'amount'}); console.log('sublist_amount:'+ sublist_amount); var sublist_description = currentRecord.getCurrentSublistValue({sublistId:'item', fieldId:'description'}); console.log('sublist_description:'+ sublist_description); // HONORARIOS MICRO INJERTO DE CABELLO KHG if(sublist_description == "HONORARIOS MICRO INJERTO DE CABELLO KHG") { if(sublist_amount < 63000) { currentRecord.setCurrentSublistValue({sublistId:'item', fieldId:'amount', value:'0.00', ignoreFieldChange:true}); currentRecord.commitLine({sublistId:'item'}); console.log('El precio de'+ sublist_description +'no puede ser menor a 63,000'); } else { console.log('El precio'+ sublist_amount +'asignado para'+ sublist_description +'es correcto!!'); } } // PAQUETE BARBA COMPLETA KHG if(sublist_description == "PAQUETE BARBA COMPLETA KHG") { if(sublist_amount < 60000) { currentRecord.setCurrentSublistValue({sublistId:'item', fieldId:'amount', value:'0.00', ignoreFieldChange:true}); currentRecord.commitLine({sublistId:'item'}); console.log('El precio de'+ sublist_description +'no puede ser menor a 60,000'); //alert('El precio de'+ sublist_description +'no puede ser menor a 60,000'); } else { console.log('El precio'+ sublist_precio_base +'asignado para'+ sublist_description +'es correcto!!'); //alert('El precio'+ sublist_precio_base +'asignado para'+ sublist_description +'es correcto!!'); } } // PAQUETE BARBA DE CANDADO KHG if(sublist_description == "PAQUETE BARBA DE CANDADO KHG") { if(sublist_amount < 40000) { currentRecord.setCurrentSublistValue({sublistId:'item', fieldId:'amount', value:'0.00', ignoreFieldChange:true}); currentRecord.commitLine({sublistId:'item'}); console.log('El precio de'+ sublist_description +'no puede ser menor a 40,000'); //alert('El precio de'+ sublist_description +'no puede ser menor a 40,000'); } else { console.log('El precio'+ sublist_precio_base +'asignado para'+ sublist_description +'es correcto!!'); //alert('El precio'+ sublist_precio_base +'asignado para'+ sublist_description +'es correcto!!'); } } // PAQUETE BIGOTE KHG if(sublist_description == "PAQUETE BIGOTE KHG") { if(sublist_amount < 30000) { currentRecord.setCurrentSublistValue({sublistId:'item', fieldId:'amount', value:'0.00', ignoreFieldChange:true}); currentRecord.commitLine({sublistId:'item'}); console.log('El precio de'+ sublist_description +'no puede ser menor a 30,000'); //alert('El precio de'+ sublist_description +'no puede ser menor a 30,000'); } else { console.log('El precio'+ sublist_precio_base +'asignado para'+ sublist_description +'es correcto!!'); //alert('El precio'+ sublist_precio_base +'asignado para'+ sublist_description +'es correcto!!'); } } // PAQUETE DE CEJAS KHG if(sublist_description == "PAQUETE DE CEJAS KHG") { if(sublist_amount < 30000) { currentRecord.setCurrentSublistValue({sublistId:'item', fieldId:'amount', value:'0.00', ignoreFieldChange:true}); currentRecord.commitLine({sublistId:'item'}); console.log('El precio de'+ sublist_description +'no puede ser menor a 30,000'); //alert('El precio de'+ sublist_description +'no puede ser menor a 30,000'); } else { console.log('El precio'+ sublist_precio_base +'asignado para'+ sublist_description +'es correcto!!'); //alert('El precio'+ sublist_precio_base +'asignado para'+ sublist_description +'es correcto!!'); } } // PAQUETE PATILLA KHG if(sublist_description == "PAQUETE PATILLA KHG") { if(sublist_amount < 40000) { currentRecord.setCurrentSublistValue({sublistId:'item', fieldId:'amount', value:'0.00', ignoreFieldChange:true}); currentRecord.commitLine({sublistId:'item'}); console.log('El precio de'+ sublist_description +'no puede ser menor a 40,000'); //alert('El precio de'+ sublist_description +'no puede ser menor a 40,000'); } else { console.log('El precio'+ sublist_precio_base +'asignado para'+ sublist_description +'es correcto!!'); //alert('El precio'+ sublist_precio_base +'asignado para'+ sublist_description +'es correcto!!'); } } } if(context.sublistId == 'item' && context.fieldId == 'custcol_precio_base_pesos') { var currentRecord = context.currentRecord; var sublist_precio_base = currentRecord.getCurrentSublistValue({sublistId:'item', fieldId:'custcol_precio_base_pesos'}); console.log('sublist_precio_base:'+ sublist_precio_base); var sublist_description = currentRecord.getCurrentSublistValue({sublistId:'item', fieldId:'description'}); console.log('sublist_description:'+ sublist_description); // <NAME> KHG if(sublist_description == "<NAME> KHG") { if(sublist_precio_base < 63000) { currentRecord.setCurrentSublistValue({sublistId:'item', fieldId:'custcol_precio_base_pesos', value:'0.00', ignoreFieldChange:true}); currentRecord.commitLine({sublistId:'item'}); console.log('El precio de'+ sublist_description +'no puede ser menor a 63,000'); //alert('El precio de'+ sublist_description +'no puede ser menor a 63,000'); } else { console.log('El precio'+ sublist_precio_base +'asignado para'+ sublist_description +'es correcto!!'); //alert('El precio'+ sublist_precio_base +'asignado para'+ sublist_description +'es correcto!!'); } } // PAQUETE BARBA COMPLETA KHG if(sublist_description == "PAQUETE BARBA COMPLETA KHG") { if(sublist_precio_base < 60000) { currentRecord.setCurrentSublistValue({sublistId:'item', fieldId:'custcol_precio_base_pesos', value:'0.00', ignoreFieldChange:true}); currentRecord.commitLine({sublistId:'item'}); console.log('El precio de'+ sublist_description +'no puede ser menor a 60,000'); //alert('El precio de'+ sublist_description +'no puede ser menor a 60,000'); } else { console.log('El precio'+ sublist_precio_base +'asignado para'+ sublist_description +'es correcto!!'); //alert('El precio'+ sublist_precio_base +'asignado para'+ sublist_description +'es correcto!!'); } } // PAQUETE BARBA DE CANDADO KHG if(sublist_description == "PAQUETE BARBA DE CANDADO KHG") { if(sublist_precio_base < 40000) { currentRecord.setCurrentSublistValue({sublistId:'item', fieldId:'custcol_precio_base_pesos', value:'0.00', ignoreFieldChange:true}); currentRecord.commitLine({sublistId:'item'}); console.log('El precio de'+ sublist_description +'no puede ser menor a 40,000'); //alert('El precio de'+ sublist_description +'no puede ser menor a 40,000'); } else { console.log('El precio'+ sublist_precio_base +'asignado para'+ sublist_description +'es correcto!!'); //alert('El precio'+ sublist_precio_base +'asignado para'+ sublist_description +'es correcto!!'); } } // PAQUETE BIGOTE KHG if(sublist_description == "PAQUETE BIGOTE KHG") { if(sublist_precio_base < 30000) { currentRecord.setCurrentSublistValue({sublistId:'item', fieldId:'custcol_precio_base_pesos', value:'0.00', ignoreFieldChange:true}); currentRecord.commitLine({sublistId:'item'}); console.log('El precio de'+ sublist_description +'no puede ser menor a 30,000'); //alert('El precio de'+ sublist_description +'no puede ser menor a 30,000'); } else { console.log('El precio'+ sublist_precio_base +'asignado para'+ sublist_description +'es correcto!!'); //alert('El precio'+ sublist_precio_base +'asignado para'+ sublist_description +'es correcto!!'); } } // PAQUETE DE CEJAS KHG if(sublist_description == "PAQUETE DE CEJAS KHG") { if(sublist_precio_base < 30000) { currentRecord.setCurrentSublistValue({sublistId:'item', fieldId:'custcol_precio_base_pesos', value:'0.00', ignoreFieldChange:true}); currentRecord.commitLine({sublistId:'item'}); console.log('El precio de'+ sublist_description +'no puede ser menor a 30,000'); //alert('El precio de'+ sublist_description +'no puede ser menor a 30,000'); } else { console.log('El precio'+ sublist_precio_base +'asignado para'+ sublist_description +'es correcto!!'); //alert('El precio'+ sublist_precio_base +'asignado para'+ sublist_description +'es correcto!!'); } } // PAQUETE PATILLA KHG if(sublist_description == "PAQUETE PATILLA KHG") { if(sublist_precio_base < 40000) { currentRecord.setCurrentSublistValue({sublistId:'item', fieldId:'custcol_precio_base_pesos', value:'0.00', ignoreFieldChange:true}); currentRecord.commitLine({sublistId:'item'}); console.log('El precio de'+ sublist_description +'no puede ser menor a 40,000'); //alert('El precio de'+ sublist_description +'no puede ser menor a 40,000'); } else { console.log('El precio'+ sublist_precio_base +'asignado para'+ sublist_description +'es correcto!!'); //alert('El precio'+ sublist_precio_base +'asignado para'+ sublist_description +'es correcto!!'); } } } } */ ======================= File: ScriptFactory/sublista.js ======================= <reponame>WizyOs/kaloniScripts function beforeLoadSublist(type, form) { //Define the values of the beforeLoad type argument if (type == 'edit' || type == 'view') { //Add a new tab to the form var sampleTab = form.addTab('custpage_sample_tab', 'Sample Tab'); //Add a field to the new tab var newFieldEmail = form.addField('custpage_field_email', 'email', 'Alt Email', null, 'custpage_sample_tab'); //Add a second field to the new tab var newFieldText = form.addField('custpage_field_text', 'textarea', 'Details', null, 'custpage_sample_tab'); //Add a subtab to the first tab var sampleSubTab = form.addSubTab('custpage_sample_subtab', 'Sample Subtab', 'custpage_sample_tab'); //Add a select field to the subtab var newSubField = form.addField('custpage_sample_field','select', 'My Customers', 'customer', 'custpage_sample_subtab'); //Add a second subtab to the first tab var sampleSubTab = form.addSubTab('custpage_sample_subtab2', 'Second Sample Subtab', 'custpage_sample_tab'); //Add a field to the second subtab var newSubField = form.addField('custpage_sample_field2','select', 'My Employees', 'employee', 'custpage_sample_subtab2'); } } ======================= File: ue_UploadPdfSkin.js ======================= <gh_stars>0 //Define the User Event function for a beforeLoad operation. function beforeLoadUploadPdfSkin(type, form) { if(type == "view") { try { var customerRecord = nlapiLoadRecord(nlapiGetRecordType(), nlapiGetRecordId()); var urlSkin = customerRecord.getFieldValue('custentity368'); nlapiLogExecution('ERROR', 'urlSkin:'+ urlSkin); var hg = customerRecord.getFieldValue('entityid'); if(urlSkin!= "" && urlSkin!= null && urlSkin!= "http://NA") { if(hg.substring(0,3) == "HG-") { nlapiLogExecution('ERROR', 'HG:'+ hg); var hg_Split = hg.split(" "); hg = hg_Split[0]; var folderToFind = hg + "_FOLDER"; var filter = new nlobjSearchFilter('name', null, 'is', folderToFind); var searchResult = nlapiSearchRecord('folder', null, filter, null); var folderId = null; if(searchResult!= null) { for (var i = 0 ; i < searchResult.length; i++) { if(i >= 1) break; folderId = searchResult[i].getId(); nlapiLogExecution('ERROR', 'ue_UploadPdfSkin.js | beforeLoadUploadPdfSkin()', 'folderId _ var i position value:'+ folderId +'_'+ i); } if(folderId!= null) { var url = urlSkin; var pdfContent = nlapiRequestURL(url); var actualContent = pdfContent.getBody(); var file = nlapiCreateFile(hg+'_SKIN.pdf', 'PDF', actualContent); file.setFolder(folderId); // 1133040 var fileId = nlapiSubmitFile(file); var filePDF = nlapiLoadFile(fileId); var urlFile = filePDF.getURL(); nlapiLogExecution('ERROR', 'ue_UploadPdfSkin.js | beforeLoadUploadPdfSkin()', 'local urlFile:'+ urlFile); customerRecord.setFieldValue('custentity391', urlFile); nlapiSubmitRecord(customerRecord, false, true); } else { nlapiLogExecution('ERROR', 'ue_UploadPdfSkin.js | beforeLoadUploadPdfSkin()', 'El folderId encontrado es nulo:'+ folderId); } } else { nlapiLogExecution('ERROR', 'ue_UploadPdfSkin.js | beforeLoadUploadPdfSkin()', 'No se encontró la carpeta llamada:'+ folderToFind); } } } }catch(e){ nlapiLogExecution('ERROR', 'Exception: ', e); } } } ======================= File: ue_firmaCliente.js ======================= /** * @NApiVersion 2.x * @NScriptType UserEventScript * @NModuleScope SameAccount */ define(['N/redirect'], function(redirect) { function beforeLoad(context) { /* if(context.type == "edit") { context.form.addButton({id: 'custpage_firmaCliente', label: 'Firmar', functionName: 'firmar()'}); context.form.clientScriptField = '1977016'; // logging for test log.debug("title", "function beforeLoad(context)"); //context.newRecord.setValue({fieldId: 'comments', value: 'test nota'}); var fieldNota = context.form.getField({id: 'comments'}); log.debug("before load edit", "context.form.getField({id: 'comments'});" + fieldNota); var newField = context.form.addField({id: 'custpage_newfield', label: 'NEW FIELD TEST', type: 'text'}); newField.defaultValue = "default value test"; //fieldNota.updateDisplayType({displayType: 'disabled'}); }*/ //The page will redirect to Suitelet on After Submit function and pass the parameter/s to it /*redirect.toSuitelet({ scriptId: 'customscript_suitlet5027', deploymentId: 'customdeploy1', parameters: { 'recordId':'1273' } });*/ } return { beforeLoad: beforeLoad }; }); ======================= File: NSNotaCreditoEventsMX.js ======================= /** * @author AAVILA @One System * Fecha: Agosto'11 * Javascript para formularios Invoice: Documentos por Cobrar MX */ function pageInit(type, form) { /* * Generado desde la factura * Actualizado por AAvila el 10/Oct/2012 */ createfrom = nlapiGetFieldValue('createdfrom'); if (type=='copy' && createfrom!=null && createfrom!=''){ // Borra el contenido de campos personalizados nlapiSetFieldValue('custbody_estado_factelectronica', ''); nlapiSetFieldValue('custbody_mensaje_efactura', ''); } nlapiSetFieldValue('custbody_tipodoc_cxc', '4'); nlapiDisableField('custbody_tipodoc_cxc', true); nlapiSetFieldValue('custbody_tipo_comprobante', 2); nlapiDisableField('custbody_tipo_comprobante', true); // Desactiva campos personalizados nlapiDisableField('custbody_estado_factelectronica', true); nlapiDisableField('custbody_mensaje_efactura', true); nlapiDisableField('custbody_mensaje_interfactrura', true); // Aplica asignaciones metodopago = nlapiGetFieldValue('custbody_metodopago'); if (metodopago!=null && (metodopago=='9') || (metodopago=='1')) { nlapiSetFieldValue('custbody_cuenta_cliente', ''); nlapiDisableField('custbody_cuenta_cliente', true); } else { nlapiDisableField('custbody_cuenta_cliente', false); } return true; } function CambiaCampos(type,lblname) { if (lblname=='custbody_metodopago') { // Variable debe estar vacia metodopago = nlapiGetFieldValue('custbody_metodopago'); if ((metodopago=='9') || (metodopago=='1')) { nlapiSetFieldValue('custbody_cuenta_cliente', ''); nlapiDisableField('custbody_cuenta_cliente', true); } else { nlapiDisableField('custbody_cuenta_cliente', false); } } } function changebody(type,lblname) { if (lblname='custbody_cuenta_cliente') { var cuentab=nlapiGetFieldValue('custbody_cuenta_cliente'); if (nlapiGetFieldValue('custbody_cuenta_cliente')==""|nlapiGetFieldValue('custbody_cuenta_cliente')==null) { return true; } else { cuentab= cuentab.split(' ').join(''); if (cuentab.length!= 4 ) { alert('Debe ingresar 4 dígitos en Cuenta Bancaria'); return false; }else {return true;} } } // Mail de la Entity y Subsidiaria if (lblname=='entity') { // Customer centity = nlapiGetFieldValue('entity'); if (centity!=null && centity!=''){ var fieldname = [ 'email','altemail','subsidiary' ]; var transdata = nlapiLookupField('customer', centity, fieldname); var tranmail1 = ''; var tranmail2 = ''; var tranmail3 = ''; var trasubsid = ''; if (transdata!=null){ var tranmail1 = transdata.email; var tranmail3 = transdata.altemail; var trasubsid = transdata.subsidiary; } // Subsidiary if (trasubsid!=null && trasubsid!=''){ var fieldname = [ 'email' ]; var transdata = nlapiLookupField('subsidiary', trasubsid, fieldname); if (transdata!=null){ var tranmail2 = transdata.email; } } // Subsidiary // Concadena los emails if (tranmail1!='' && tranmail2!='' && tranmail3!=''){ nlapiSetFieldValue('custbody_emailtracking', tranmail1+', '+tranmail2+', '+tranmail3 ); } if (tranmail1!='' && tranmail2=='' && tranmail3!=''){ nlapiSetFieldValue('custbody_emailtracking', tranmail1 +', '+ tranmail3); } if (tranmail1!='' && tranmail2=='' && tranmail3==''){ nlapiSetFieldValue('custbody_emailtracking', tranmail1); } if (tranmail1=='' && tranmail2!='' && tranmail3==''){ nlapiSetFieldValue('custbody_emailtracking', tranmail2); } if (tranmail1=='' && tranmail2=='' && tranmail3!=''){ nlapiSetFieldValue('custbody_emailtracking', tranmail3); } if (tranmail1=='' && tranmail2!='' && tranmail3!=''){ nlapiSetFieldValue('custbody_emailtracking', tranmail2 +', '+ tranmail3); } if (tranmail1!='' && tranmail2!='' && tranmail3==''){ nlapiSetFieldValue('custbody_emailtracking', tranmail1 +', '+ tranmail2); } } // Customer } // Mail de la Entity y Subsidiaria // Desabilida control if (lblname=='custbody_metodopago') { // Variable debe estar vacia metodopago = nlapiGetFieldValue('custbody_metodopago'); if ((metodopago=='9') || (metodopago=='1')) { nlapiSetFieldValue('custbody_cuenta_cliente', ''); nlapiDisableField('custbody_cuenta_cliente', true); } else { nlapiDisableField('custbody_cuenta_cliente', false); } } if (lblname=='subsidiary') { cdepartment = nlapiGetFieldValue('department'); if (cdepartment ==null && cdepartment=='') { nlapiSetFieldValue('department', '3'); } } return true; } function saveRecord() { /* AAvila * Cambios realizados para desactivar el boton grabar * Fecha 10/Oct/2012 */ var estado = nlapiGetFieldValue('custbody_estado_factelectronica'); if (estado=='Generado') { alert('No se puede grabar el documento. Por que ya esta firmado electronicamente'); return false; } var metodopago = nlapiGetFieldValue('custbody_metodopago'); if ((metodopago!='9') && (metodopago!='1')) { var ctacliente = nlapiGetFieldValue('custbody_cuenta_cliente'); if (ctacliente == null || ctacliente == '' ) { alert('Debe ingresar valor en el campo: Cuenta Bancaria Cliente.'); return false; } else { var _longitud = ctacliente.length; if (_longitud>=5) { alert('La longitud del campo Cuenta Bancaria Cliente debe ser 4 caracteres.'); return false; } } } return true; } ======================= File: ScriptFactory/script_save_search/valAgenEmp.js ======================= <gh_stars>0 function valAgenEmp(){ var consultor1 = '<NAME> KHG'; var consultor2 = '<NAME>'; var consultor3 = '<NAME>'; var consultor4 = '<NAME>'; var consultor5 = '<NAME>'; var consultor6 = '<NAME> khg'; var consultor7 = '<NAME>'; var consultor8 = '<NAME> khg'; var consultor9 = '<NAME>'; var consultor10 = '<NAME>'; var consultor11 = '<NAME>'; var consultor12 = '<NAME>'; var consultor13 = '<NAME>'; var consultor14 = '<NAME>'; var consultor15 = '<NAME>'; var consultor16 = '<NAME>'; var consultor17 = '<NAME>'; var consultor18 = '<NAME>'; var consultor19 = '<NAME>'; var consultor20 = '<NAME>'; var consultor21 = '<NAME> ESP'; var consultor22 = '<NAME>'; var consultor23 = '<NAME>'; var empleado1 = '77721'; var empleado2 = '99005'; var empleado3 = '165101'; var empleado4 = '585340'; var empleado5 = '385113'; var empleado6 = '62854'; var empleado7 = '279069'; var empleado8 = '62853'; var empleado9 = '310228'; var empleado10 = '489559'; var empleado11 = '585337'; var empleado12 = '432739'; var empleado13 = '127021'; var empleado14 = '574785'; var empleado15 = '123407'; var empleado16 = '625788'; var empleado17 = '666006'; var empleado18 = '687412'; var empleado19 = '682835'; var empleado20 = '687195'; var empleado21 = '187309'; var empleado22 = '734394'; var empleado23 = '735184'; var count=''; var campo1='';var campo2='';var campo3='';var campo4='';var campo5='';var campo6='';var campo7='';var campo8='';var campo9='';var campo10='';var campo11='';var campo12='';var campo13='';var campo14=''; var campo15=''; var campo16='';var campo17='';var campo18='';var campo19='';var campo20='';var campo21='';var campo22='';var campo23=''; /*BÚSQUEDA Script ValSuc Emp*/ var revresults = nlapiSearchRecord('calendarevent','customsearch2976'); for(var z in revresults ) { var result1=revresults[z]; var column1=result1.getAllColumns(); var consultor =result1.getText(column1[1]); count =result1.getValue(column1[0]); if(consultor==consultor1){ campo1 = nlapiLoadRecord('employee', empleado1);//numero_empleado campo1.setFieldValue('custentity304', count);//vac nlapiSubmitRecord(campo1, true); continue; } if(consultor==consultor2){ campo2 = nlapiLoadRecord('employee', empleado2);//numero_empleado campo2.setFieldValue('custentity304', '0'); nlapiSubmitRecord(campo2, true); continue; } if(consultor==consultor3){ campo3 = nlapiLoadRecord('employee', empleado3);//numero_empleado campo3.setFieldValue('custentity304', count); nlapiSubmitRecord(campo3, true); continue; } if(consultor==consultor4){ campo4 = nlapiLoadRecord('employee', empleado4);//numero_empleado campo4.setFieldValue('custentity304', count); nlapiSubmitRecord(campo4, true); continue; } if(consultor==consultor5){ campo5 = nlapiLoadRecord('employee', empleado5);//numero_empleado campo5.setFieldValue('custentity304', count); nlapiSubmitRecord(campo5, true); continue; } if(consultor==consultor6){ campo6 = nlapiLoadRecord('employee', empleado6);//numero_empleado campo6.setFieldValue('custentity304', count); nlapiSubmitRecord(campo6, true); continue; } if(consultor==consultor7){ campo7 = nlapiLoadRecord('employee', empleado7);//numero_empleado campo7.setFieldValue('custentity304', count); nlapiSubmitRecord(campo7, true); continue; } if(consultor==consultor8){ campo8 = nlapiLoadRecord('employee', empleado8);//numero_empleado campo8.setFieldValue('custentity304', count); nlapiSubmitRecord(campo8, true); continue; } if(consultor==consultor9){ campo9 = nlapiLoadRecord('employee', empleado9);//numero_empleado campo9.setFieldValue('custentity304', count); nlapiSubmitRecord(campo9, true); continue; } if(consultor==consultor10){ campo10 = nlapiLoadRecord('employee', empleado10);//numero_empleado campo10.setFieldValue('custentity304', count); nlapiSubmitRecord(campo10, true); continue; } if(consultor==consultor11){ campo11 = nlapiLoadRecord('employee', empleado11);//numero_empleado campo11.setFieldValue('custentity304', count); nlapiSubmitRecord(campo11, true); continue; } if(consultor==consultor12){ campo12 = nlapiLoadRecord('employee', empleado12);//numero_empleado campo12.setFieldValue('custentity304', count); nlapiSubmitRecord(campo12, true); continue; } if(consultor==consultor13){ campo13 = nlapiLoadRecord('employee', empleado13);//numero_empleado campo13.setFieldValue('custentity304', count); nlapiSubmitRecord(campo13, true); continue; } if(consultor==consultor14){ campo14 = nlapiLoadRecord('employee', empleado14);//numero_empleado campo14.setFieldValue('custentity304', count); nlapiSubmitRecord(campo14, true); continue; } if(consultor==consultor15){ campo15 = nlapiLoadRecord('employee', empleado15);//numero_empleado campo15.setFieldValue('custentity304', count); nlapiSubmitRecord(campo15, true); continue; } if(consultor==consultor16){ campo16 = nlapiLoadRecord('employee', empleado16);//numero_empleado campo16.setFieldValue('custentity304', count); nlapiSubmitRecord(campo16, true); continue; } if(consultor==consultor17){ campo17 = nlapiLoadRecord('employee', empleado17);//numero_empleado campo17.setFieldValue('custentity304', count); nlapiSubmitRecord(campo17, true); continue; } if(consultor==consultor18){ campo18 = nlapiLoadRecord('employee', empleado18);//numero_empleado campo18.setFieldValue('custentity304', count); nlapiSubmitRecord(campo18, true); continue; } if(consultor==consultor19){ campo19 = nlapiLoadRecord('employee', empleado19);//numero_empleado campo19.setFieldValue('custentity304', count); nlapiSubmitRecord(campo19, true); continue; } if(consultor==consultor20){ campo20 = nlapiLoadRecord('employee', empleado20);//numero_empleado campo20.setFieldValue('custentity304', count); nlapiSubmitRecord(campo20, true); continue; } if(consultor==consultor21){ campo21 = nlapiLoadRecord('employee', empleado21);//numero_empleado campo21.setFieldValue('custentity304', count); nlapiSubmitRecord(campo21, true); continue; } if(consultor==consultor22){ campo22 = nlapiLoadRecord('employee', empleado22);//numero_empleado campo22.setFieldValue('custentity304', count); nlapiSubmitRecord(campo22, true); continue; } if(consultor==consultor23){ campo23 = nlapiLoadRecord('employee', empleado23);//numero_empleado campo23.setFieldValue('custentity304', count); nlapiSubmitRecord(campo23, true); continue; } } /*BÚSQUEDA Script ValEfec emp*/ var revresults = nlapiSearchRecord('calendarevent','customsearch2984'); for(var z in revresults ) { var result1=revresults[z]; var column1=result1.getAllColumns(); var consultor =result1.getText(column1[1]); count =result1.getValue(column1[0]); if(consultor==consultor1){ campo1 = nlapiLoadRecord('employee', empleado1);//numero_empleado campo1.setFieldValue('custentity305', count);//vae nlapiSubmitRecord(campo1, true); continue; } if(consultor==consultor2){ campo2 = nlapiLoadRecord('employee', empleado2);//numero_empleado campo2.setFieldValue('custentity305', "0"); nlapiSubmitRecord(campo2, true); continue; } if(consultor==consultor3){ campo3 = nlapiLoadRecord('employee', empleado3);//numero_empleado campo3.setFieldValue('custentity305', count); nlapiSubmitRecord(campo3, true); continue; } if(consultor==consultor4){ campo4 = nlapiLoadRecord('employee', empleado4);//numero_empleado campo4.setFieldValue('custentity305', count); nlapiSubmitRecord(campo4, true); continue; } if(consultor==consultor5){ campo5 = nlapiLoadRecord('employee', empleado5);//numero_empleado campo5.setFieldValue('custentity305', count); nlapiSubmitRecord(campo5, true); continue; } if(consultor==consultor6){ campo6 = nlapiLoadRecord('employee', empleado6);//numero_empleado campo6.setFieldValue('custentity305', count); nlapiSubmitRecord(campo6, true); continue; } if(consultor==consultor7){ campo7 = nlapiLoadRecord('employee', empleado7);//numero_empleado campo7.setFieldValue('custentity305', count); nlapiSubmitRecord(campo7, true); continue; } if(consultor==consultor8){ campo8 = nlapiLoadRecord('employee', empleado8);//numero_empleado campo8.setFieldValue('custentity305', count); nlapiSubmitRecord(campo8, true); continue; } if(consultor==consultor9){ campo9 = nlapiLoadRecord('employee', empleado9);//numero_empleado campo9.setFieldValue('custentity305', count); nlapiSubmitRecord(campo9, true); continue; } if(consultor==consultor10){ campo10 = nlapiLoadRecord('employee', empleado10);//numero_empleado campo10.setFieldValue('custentity305', count); nlapiSubmitRecord(campo10, true); continue; } if(consultor==consultor11){ campo11 = nlapiLoadRecord('employee', empleado11);//numero_empleado campo11.setFieldValue('custentity305', count); nlapiSubmitRecord(campo11, true); continue; } if(consultor==consultor12){ campo12 = nlapiLoadRecord('employee', empleado12);//numero_empleado campo12.setFieldValue('custentity305', count); nlapiSubmitRecord(campo12, true); continue; } if(consultor==consultor13){ campo13 = nlapiLoadRecord('employee', empleado13);//numero_empleado campo13.setFieldValue('custentity305', count); nlapiSubmitRecord(campo13, true); continue; } if(consultor==consultor14){ campo14 = nlapiLoadRecord('employee', empleado14);//numero_empleado campo14.setFieldValue('custentity305', count); nlapiSubmitRecord(campo14, true); continue; } if(consultor==consultor15){ campo15 = nlapiLoadRecord('employee', empleado15);//numero_empleado campo15.setFieldValue('custentity305', count); nlapiSubmitRecord(campo15, true); continue; } if(consultor==consultor16){ campo16 = nlapiLoadRecord('employee', empleado16);//numero_empleado campo16.setFieldValue('custentity305', count); nlapiSubmitRecord(campo16, true); continue; } if(consultor==consultor17){ campo17 = nlapiLoadRecord('employee', empleado17);//numero_empleado campo17.setFieldValue('custentity305', count); nlapiSubmitRecord(campo17, true); continue; } if(consultor==consultor18){ campo18 = nlapiLoadRecord('employee', empleado18);//numero_empleado campo18.setFieldValue('custentity305', count); nlapiSubmitRecord(campo18, true); continue; } if(consultor==consultor19){ campo19 = nlapiLoadRecord('employee', empleado19);//numero_empleado campo19.setFieldValue('custentity305', count); nlapiSubmitRecord(campo19, true); continue; } if(consultor==consultor20){ campo20 = nlapiLoadRecord('employee', empleado20);//numero_empleado campo20.setFieldValue('custentity305', count); nlapiSubmitRecord(campo20, true); continue; } if(consultor==consultor21){ campo21 = nlapiLoadRecord('employee', empleado21);//numero_empleado campo21.setFieldValue('custentity305', count); nlapiSubmitRecord(campo21, true); continue; } if(consultor==consultor22){ campo22 = nlapiLoadRecord('employee', empleado22);//numero_empleado campo22.setFieldValue('custentity305', count); nlapiSubmitRecord(campo22, true); continue; } if(consultor==consultor23){ campo23 = nlapiLoadRecord('employee', empleado23);//numero_empleado campo23.setFieldValue('custentity305', count); nlapiSubmitRecord(campo23, true); continue; } } /*BÚSQUEDA KPI-Consultor Cierres*/ var revresults = nlapiSearchRecord('transaction','customsearch1633'); for(var z in revresults ) { var result1=revresults[z]; var column1=result1.getAllColumns(); var consultor =result1.getText(column1[1]); count =result1.getValue(column1[0]); if(consultor==consultor1){ campo1 = nlapiLoadRecord('employee', empleado1);//numero_empleado campo1.setFieldValue('custentity306', count);//cc nlapiSubmitRecord(campo1, true); continue; } if(consultor==consultor2){ campo2 = nlapiLoadRecord('employee', empleado2);//numero_empleado campo2.setFieldValue('custentity306', 0); nlapiSubmitRecord(campo2, true); continue; } if(consultor==consultor3){ campo3 = nlapiLoadRecord('employee', empleado3);//numero_empleado campo3.setFieldValue('custentity306', count); nlapiSubmitRecord(campo3, true); continue; } if(consultor==consultor4){ campo4 = nlapiLoadRecord('employee', empleado4);//numero_empleado campo4.setFieldValue('custentity306', count); nlapiSubmitRecord(campo4, true); continue; } if(consultor==consultor5){ campo5 = nlapiLoadRecord('employee', empleado5);//numero_empleado campo5.setFieldValue('custentity306', 0); nlapiSubmitRecord(campo5, true); continue; } if(consultor==consultor6){ campo6 = nlapiLoadRecord('employee', empleado6);//numero_empleado campo6.setFieldValue('custentity306', count); nlapiSubmitRecord(campo6, true); continue; } if(consultor==consultor7){ campo7 = nlapiLoadRecord('employee', empleado7);//numero_empleado campo7.setFieldValue('custentity306', count); nlapiSubmitRecord(campo7, true); continue; } if(consultor==consultor8){ campo8 = nlapiLoadRecord('employee', empleado8);//numero_empleado campo8.setFieldValue('custentity306', count); nlapiSubmitRecord(campo8, true); continue; } if(consultor==consultor9){ campo9 = nlapiLoadRecord('employee', empleado9);//numero_empleado campo9.setFieldValue('custentity306', count); nlapiSubmitRecord(campo9, true); continue; } if(consultor==consultor10){ campo10 = nlapiLoadRecord('employee', empleado10);//numero_empleado campo10.setFieldValue('custentity306', count); nlapiSubmitRecord(campo10, true); continue; } if(consultor==consultor11){ campo11 = nlapiLoadRecord('employee', empleado11);//numero_empleado campo11.setFieldValue('custentity306', count); nlapiSubmitRecord(campo11, true); continue; } if(consultor==consultor12){ campo12 = nlapiLoadRecord('employee', empleado12);//numero_empleado campo12.setFieldValue('custentity306', count); nlapiSubmitRecord(campo12, true); continue; } if(consultor==consultor13){ campo13 = nlapiLoadRecord('employee', empleado13);//numero_empleado campo13.setFieldValue('custentity306', count); nlapiSubmitRecord(campo13, true); continue; } if(consultor==consultor14){ campo14 = nlapiLoadRecord('employee', empleado14);//numero_empleado campo14.setFieldValue('custentity306', count); nlapiSubmitRecord(campo14, true); continue; } if(consultor==consultor15){ campo15 = nlapiLoadRecord('employee', empleado15);//numero_empleado campo15.setFieldValue('custentity306', count); nlapiSubmitRecord(campo15, true); continue; } if(consultor==consultor16){ campo16 = nlapiLoadRecord('employee', empleado16);//numero_empleado campo16.setFieldValue('custentity306', count); nlapiSubmitRecord(campo16, true); continue; } if(consultor==consultor17){ campo17 = nlapiLoadRecord('employee', empleado17);//numero_empleado campo17.setFieldValue('custentity306', count); nlapiSubmitRecord(campo17, true); continue; } if(consultor==consultor18){ campo18 = nlapiLoadRecord('employee', empleado18);//numero_empleado campo18.setFieldValue('custentity306', count); nlapiSubmitRecord(campo18, true); continue; } if(consultor==consultor19){ campo19 = nlapiLoadRecord('employee', empleado19);//numero_empleado campo19.setFieldValue('custentity306', count); nlapiSubmitRecord(campo19, true); continue; } if(consultor==consultor20){ campo20 = nlapiLoadRecord('employee', empleado20);//numero_empleado campo20.setFieldValue('custentity306', count); nlapiSubmitRecord(campo20, true); continue; } if(consultor==consultor21){ campo21 = nlapiLoadRecord('employee', empleado21);//numero_empleado campo21.setFieldValue('custentity306', count); nlapiSubmitRecord(campo21, true); continue; } if(consultor==consultor22){ campo22 = nlapiLoadRecord('employee', empleado22);//numero_empleado campo22.setFieldValue('custentity306', count); nlapiSubmitRecord(campo22, true); continue; } if(consultor==consultor23){ campo23 = nlapiLoadRecord('employee', empleado23);//numero_empleado campo23.setFieldValue('custentity306', count); nlapiSubmitRecord(campo23, true); continue; } } /*BÚSQUEDA KPI-Consultor Promedios*/ var revresults = nlapiSearchRecord('transaction','customsearch2969'); for(var z in revresults ) { var result1=revresults[z]; var column1=result1.getAllColumns(); var consultor =result1.getText(column1[1]); count =result1.getValue(column1[0]); if(consultor==consultor1){ campo1 = nlapiLoadRecord('employee', empleado1);//numero_empleado campo1.setFieldValue('custentity116', count);//cp nlapiSubmitRecord(campo1, true); continue; } if(consultor==consultor2){ campo2 = nlapiLoadRecord('employee', empleado2);//numero_empleado campo2.setFieldValue('custentity116', ''); nlapiSubmitRecord(campo2, true); continue; } if(consultor==consultor3){ campo3 = nlapiLoadRecord('employee', empleado3);//numero_empleado campo3.setFieldValue('custentity116', count); nlapiSubmitRecord(campo3, true); continue; } if(consultor==consultor4){ campo4 = nlapiLoadRecord('employee', empleado4);//numero_empleado campo4.setFieldValue('custentity116', count); nlapiSubmitRecord(campo4, true); continue; } if(consultor==consultor5){ campo5 = nlapiLoadRecord('employee', empleado5);//numero_empleado campo5.setFieldValue('custentity116', count); nlapiSubmitRecord(campo5, true); continue; } if(consultor==consultor6){ campo6 = nlapiLoadRecord('employee', empleado6);//numero_empleado campo6.setFieldValue('custentity116', count); nlapiSubmitRecord(campo6, true); continue; } if(consultor==consultor7){ campo7 = nlapiLoadRecord('employee', empleado7);//numero_empleado campo7.setFieldValue('custentity116', count); nlapiSubmitRecord(campo7, true); continue; } if(consultor==consultor8){ campo8 = nlapiLoadRecord('employee', empleado8);//numero_empleado campo8.setFieldValue('custentity116', count); nlapiSubmitRecord(campo8, true); continue; } if(consultor==consultor9){ campo9 = nlapiLoadRecord('employee', empleado9);//numero_empleado campo9.setFieldValue('custentity116', count); nlapiSubmitRecord(campo9, true); continue; } if(consultor==consultor10){ campo10 = nlapiLoadRecord('employee', empleado10);//numero_empleado campo10.setFieldValue('custentity116', count); nlapiSubmitRecord(campo10, true); continue; } if(consultor==consultor11){ campo11 = nlapiLoadRecord('employee', empleado11);//numero_empleado campo11.setFieldValue('custentity116', count); nlapiSubmitRecord(campo11, true); continue; } if(consultor==consultor12){ campo12 = nlapiLoadRecord('employee', empleado12);//numero_empleado campo12.setFieldValue('custentity116', count); nlapiSubmitRecord(campo12, true); continue; } if(consultor==consultor13){ campo13 = nlapiLoadRecord('employee', empleado13);//numero_empleado campo13.setFieldValue('custentity116', count); nlapiSubmitRecord(campo13, true); continue; } if(consultor==consultor14){ campo14 = nlapiLoadRecord('employee', empleado14);//numero_empleado campo14.setFieldValue('custentity116', count); nlapiSubmitRecord(campo14, true); continue; } if(consultor==consultor15){ campo15 = nlapiLoadRecord('employee', empleado15);//numero_empleado campo15.setFieldValue('custentity116', count); nlapiSubmitRecord(campo15, true); continue; } if(consultor==consultor16){ campo16 = nlapiLoadRecord('employee', empleado16);//numero_empleado campo16.setFieldValue('custentity116', count); nlapiSubmitRecord(campo16, true); continue; } if(consultor==consultor17){ campo17 = nlapiLoadRecord('employee', empleado17);//numero_empleado campo17.setFieldValue('custentity116', count); nlapiSubmitRecord(campo17, true); continue; } if(consultor==consultor18){ campo18 = nlapiLoadRecord('employee', empleado18);//numero_empleado campo18.setFieldValue('custentity116', count); nlapiSubmitRecord(campo18, true); continue; } if(consultor==consultor19){ campo19 = nlapiLoadRecord('employee', empleado19);//numero_empleado campo19.setFieldValue('custentity116', count); nlapiSubmitRecord(campo19, true); continue; } if(consultor==consultor20){ campo20 = nlapiLoadRecord('employee', empleado20);//numero_empleado campo20.setFieldValue('custentity116', count); nlapiSubmitRecord(campo20, true); continue; } if(consultor==consultor21){ campo21 = nlapiLoadRecord('employee', empleado21);//numero_empleado campo21.setFieldValue('custentity116', count); nlapiSubmitRecord(campo21, true); continue; } if(consultor==consultor22){ campo22 = nlapiLoadRecord('employee', empleado22);//numero_empleado campo22.setFieldValue('custentity116', count); nlapiSubmitRecord(campo22, true); continue; } if(consultor==consultor23){ campo23 = nlapiLoadRecord('employee', empleado23);//numero_empleado campo23.setFieldValue('custentity116', count); nlapiSubmitRecord(campo23, true); continue; } } } ======================= File: cs_test_v2.0.js ======================= /** * @NApiVersion 2.x * @NScriptType ClientScript * @NModuleScope Public */ define(['require','N/record','N/url','N/https','N/log','N/runtime', 'N/currentRecord'], function(require, record, url, https, log, runtime, currentRecord) { function pageInit(context) { } function mostrarInfo() { var currentUrl = document.location.href; var paramsUrl = new URL(currentUrl); var mode = paramsUrl.searchParams.get("mode"); var recId = paramsUrl.searchParams.get("recId"); var rec = paramsUrl.searchParams.get("parentRecId"); var valImage1 = null; var currentRec = currentRecord.get(); alert(currentRec.id + recId + rec); if (mode == 'e') { } else if (mode == 'c') { } } return { pageInit: pageInit, mostrarInfo: mostrarInfo }; }); ======================= File: SuiteScript 2.0 API/util.js ======================= /** * SuiteScript 2.0 util global object * * @namespace * @global * @name util * @type {Object} */ var util = { /** * @memberof util * @name util.each * * @param {Object|Array} iterable * @param {Function} callback * @returns {Object|Array} iterable - original collection */ each: function (iterable, callback) {}, /** * @memberof util * @name util.extend * * @param {Object} receiver * @param {Object} contributor * @returns {Object} receiver */ extend: function (receiver, contributor) {}, /** * @memberof util * @name util.deepExtend * * @param {Object} receiver * @param {Object} contributor * @returns {Object} receiver */ deepExtend: function (receiver, contributor) {}, /** * Determines if a variable refers to an instance of Object.prototype (aka "Plain Object" aka {}) * * @memberof util * @name util.isObject * * @param {*} obj * @returns {boolean} */ isObject: function (obj) {}, /** * Determines if a variable refers to a Function * * @memberof util * @name util.isFunction * * @param {*} obj * @returns {boolean} */ isFunction: function (obj) {}, /** * Determines if a variable refers to an Array * * @memberof util * @name util.isArray * * @param {*} obj * @returns {boolean} */ isArray: function (obj) {}, /** * Determines if a variable refers to a boolean * * @memberof util * @name util.isBoolean * * @param {*} obj * @returns {boolean} */ isBoolean: function (obj) {}, /** * Determines if a variable refers to a string * * @memberof util * @name util.isString * * @param {*} obj * @returns {boolean} */ isString: function (obj) {}, /** * Determines if a variable refers to a number * * @memberof util * @name util.isNumber * * @param obj * @returns {boolean} */ isNumber: function (obj) {}, /** * * Determines if a variable refers to a Date * * @memberof util * @name util.isDate * * @param obj * @returns {boolean} */ isDate: function (obj) {}, /** * Determines if a variable refers to a RegExp * * @memberof util * @name util.isRegExp * * @param obj * @returns {boolean} */ isRegExp: function (obj) {}, /** * Determines if a variable refers to an Error * * @memberof util * @name util.isError * * @param obj * @returns {boolean} */ isError: function(obj) {}, /** * Remove leading and trailing whitespace from a string * * @memberof util * @name util.trim * * @param {string} str String to have leading/trailing whitespace extracted */ trim: function(str) {} }; ======================= File: SuiteScript 2.0 API/piremoval.js ======================= <gh_stars>0 /** * SuiteScript module * * @module N/piremoval * @NApiVersion 2.x * */ function piremoval() {} /** * Enum status values. * @readonly * @enum {string} */ function piremovalStatus() { this.CREATED = 'CREATED'; this.PENDING = 'PENDING'; this.COMPLETE = 'COMPLETE'; this.ERROR = 'ERROR'; this.DELETED = 'DELETED'; this.NOT_APPLIED = 'NOT_APPLIED'; } piremoval.prototype.Status = piremovalStatus; /** * @protected * @constructor */ function PiRemovalTaskLogItem() { /** * Type * @name PiRemovalTaskLogItem#type * @type string * @since 2019.2 */ this.prototype.type = undefined; /** * Status * @name PiRemovalTaskLogItem#status * @type string * @since 2019.2 */ this.prototype.status = undefined; /** * Message * @name PiRemovalTaskLogItem#message * @type string * @since 2019.2 */ this.prototype.message = undefined; /** * Exception * @name PiRemovalTaskLogItem#exception * @type string * @since 2019.2 */ this.prototype.exception = undefined; /** * get JSON format of the object * @returns {Object} */ this.prototype.toJSON = function() {}; /** * @returns {string} */ this.prototype.toString = function() {}; } /** * @protected * @constructor */ function PiRemovalTask() { /** * Task id * @name PiRemovalTask#id * @type string * @since 2019.2 */ this.prototype.id = undefined; /** * Record Type * @name PiRemovalTask#recordType * @type string * @since 2019.2 */ this.prototype.recordType = undefined; /** * Record Ids * @name PiRemovalTask#recordIds * @type string[] * @since 2019.2 */ this.prototype.recordIds = undefined; /** * Field Ids * @name PiRemovalTask#fieldIds * @type string[] * @since 2019.2 */ this.prototype.fieldIds = undefined; /** * Workflow ids * @name PiRemovalTask#workflowIds * @type string[] * @since 2019.2 */ this.prototype.workflowIds = undefined; /** * History Only flag * @name PiRemovalTask#historyOnly * @type boolean * @since 2019.2 */ this.prototype.historyOnly = undefined; /** * History Replacement * @name PiRemovalTask#historyReplacement * @type string * @since 2019.2 */ this.prototype.historyReplacement = undefined; /** * Status * @name PiRemovalTask#status * @type PiRemovalTaskStatus * @since 2019.2 */ this.prototype.status = undefined; /** * Save * @returns {undefined} * @since 2019.2 */ this.prototype.save = function() {}; /** * Delete * @returns {undefined} * @since 2019.2 */ this.prototype.deleteTask = function() {}; /** * Run * @returns {undefined} * @since 2019.2 */ this.prototype.run = function() {}; /** * get JSON format of the object * @returns {Object} */ this.prototype.toJSON = function() {}; /** * @returns {string} */ this.prototype.toString = function() {}; } /** * @protected * @constructor */ function PiRemovalTaskStatus() { /** * Status * @name PiRemovalTaskStatus#status * @type string * @since 2019.2 */ this.prototype.status = undefined; /** * Log List * @name PiRemovalTaskStatus#logList * @type list * @since 2019.2 */ this.prototype.logList = undefined; /** * get JSON format of the object * @returns {Object} */ this.prototype.toJSON = function() {}; /** * @returns {string} */ this.prototype.toString = function() {}; } piremoval = new piremoval(); /** * @type {piremoval} */ N.prototype.piremoval = piremoval; ======================= File: helloWorld.js ======================= <reponame>WizyOs/kaloniScripts<gh_stars>0 /** *@NApiVersion 2.0 *@NScriptType ClientScript */ define(['N/ui/dialog', 'N/https', 'N/record', 'N/currentRecord'], function (dialog, https, record, currentRecord) { function helloWorld(context) { /*var id = context.currentRecord.id; var cliente = record.load({ type: 'prospect', id: id}); var url = cliente.getValue({ fieldId: 'custentity368'}); var folderCliente = cliente.getText({ field: 'entityid'}); log.debug('idFolder', folderCliente);*/ /* search.create({ type: search.Type.FOLDER, filters: [search.createFilter({ name: 'name', operator: search.Operator.IS, values: folderCliente })], columns: ['internalid'] }).run().each(function (result) { folderId = result.getValue({ name: 'internalid' }); }); log.debug('idFolder', folderId); if(url.slice(0,4 == http)){ var response = https.get({ url: url }); var pdfContent = response.body; var createURLSkin = file.create({ name: idTextoCliente + "_SKIN.pdf", fyleType: file.Type.PDF, contents: pdfContent, folder: folderId }); var fileSkinPDFId = createURLSkin.save(); log.debug('id', fileSkinPDFId); var filePDFSkin = file.load({id: fileSkinPDFId}); var filePDFSkinURL = filePDFSkin.url; //cliente.setValue({ fieldId: 'custentity391', value: filePDFSkinURL}); //cliente.save({enableSourcing: true, ignoreMandatoryFields: false}); log.debug('id Folder creado y su URL NS', fileSkinPDFId +'' + filePDFSkinURL); } */ /* log.debug({ title: 'Client Response Body', details: response.body }); log.debug('url',url); log.debug('respuesta',response); var options = { title: 'Hello!', message: url }; try { dialog.alert(options); log.debug({ title: 'Success', details: 'Alert displayed successfully' }); } catch (e) { log.error({ title: e.name, details: e.message }); } */ } /* function helloWorld() { var options = { title: 'Hello!', message: 'Hello, World!' }; try { dialog.alert(options); log.debug ({ title: 'Success', details: 'Alert displayed successfully' }); } catch (e) { log.error ({ title: e.name, details: e.message }); } } */ return { pageInit: helloWorld }; }) ======================= File: ue_CaseEncryptedFields.js ======================= <reponame>WizyOs/kaloniScripts<filename>ue_CaseEncryptedFields.js /** * @NApiVersion 2.x * @NScriptType UserEventScript * @NModuleScope Public */ define(['N/record', 'N/runtime', 'N/encode'], function(record, runtime, encode) { function beforeLoad(context) { if(context.type == "edit") { var recordCaseId = context.newRecord.id; var objRecord = record.load({type: 'SUPPORTCASE', id: recordCaseId, isDynamic: false}); var customform_id = objRecord.getValue({fieldId: 'customform'}); var userObj = runtime.getCurrentUser(); if(userObj.role == "1139" || userObj.role == "1094") // 1097 = OSS Contabilidad KHG { if(customform_id == "14") // 14 = atención a cliente injerto { // ********************************** Primary Information var val_CUSTOM_FORM = objRecord.getText({fieldId: 'customform'}); if(val_CUSTOM_FORM!= null && val_CUSTOM_FORM!= "") { context.form.getField('customform').updateDisplayType({displayType:'hidden'}); context.form.getField('custevent350').updateDisplayType({displayType:'normal'}); context.form.getField('custevent350').updateDisplayType({displayType:'disabled'}); } var val_casenumber = objRecord.getValue({fieldId: 'casenumber'}); if(val_casenumber!= null && val_casenumber!= "") { context.form.getField('casenumber').updateDisplayType({displayType:'hidden'}); context.form.getField('custevent342').updateDisplayType({displayType:'normal'}); context.form.getField('custevent342').updateDisplayType({displayType:'disabled'}); } var val_title = objRecord.getValue({fieldId: 'title'}); if(val_title!= null && val_title!= "") { context.form.getField('title').updateDisplayType({displayType:'hidden'}); context.form.getField('custevent343').updateDisplayType({displayType:'normal'}); context.form.getField('custevent343').updateDisplayType({displayType:'disabled'}); } var val_company = objRecord.getText({fieldId: 'company'}); if(val_company!= null && val_company!= "") { context.form.getField('company').updateDisplayType({displayType:'hidden'}); context.form.getField('custevent344').updateDisplayType({displayType:'normal'}); context.form.getField('custevent344').updateDisplayType({displayType:'disabled'}); } var val_status = objRecord.getText({fieldId:'status'}); if(val_status!= null && val_status!= "") { context.form.getField('status').updateDisplayType({displayType:'hidden'}); context.form.getField('custevent345').updateDisplayType({displayType:'normal'}); context.form.getField('custevent345').updateDisplayType({displayType:'disabled'}); } var val_sucursal = objRecord.getText({fieldId: 'custevent2'}); if(val_sucursal!= null && val_sucursal!= "") { context.form.getField('custevent2').updateDisplayType({displayType:'hidden'}); context.form.getField('custevent346').updateDisplayType({displayType:'normal'}); context.form.getField('custevent346').updateDisplayType({displayType:'disabled'}); } // ********************************** Incident Information var val_INCIDENT_DATE = objRecord.getValue({fieldId:'startdate'}); if(val_INCIDENT_DATE!= null && val_INCIDENT_DATE!= "") { context.form.getField('startdate').updateDisplayType({displayType:'hidden'}); context.form.getField('custevent347').updateDisplayType({displayType:'normal'}); context.form.getField('custevent347').updateDisplayType({displayType:'disabled'}); } var val_starttime = objRecord.getText({fieldId:'starttime'}); if(val_starttime!= null && val_starttime!= "") { context.form.getField('starttime').updateDisplayType({displayType:'hidden'}); context.form.getField('custevent351').updateDisplayType({displayType:'normal'}); context.form.getField('custevent351').updateDisplayType({displayType:'disabled'}); } var val_ENFERMERIA_EXTRACCION = objRecord.getValue({fieldId: 'custevent71'}); if(val_ENFERMERIA_EXTRACCION!= null && val_ENFERMERIA_EXTRACCION!= "") { context.form.getField('custevent71').updateDisplayType({displayType:'hidden'}); context.form.getField('custevent348').updateDisplayType({displayType:'normal'}); context.form.getField('custevent348').updateDisplayType({displayType:'disabled'}); } var val_ENFERMERIA_IMPLANTACION = objRecord.getValue({fieldId: 'custevent72'}); if(val_ENFERMERIA_IMPLANTACION!= null && val_ENFERMERIA_IMPLANTACION!= "") { context.form.getField('custevent72').updateDisplayType({displayType:'hidden'}); context.form.getField('custevent349').updateDisplayType({displayType:'normal'}); context.form.getField('custevent349').updateDisplayType({displayType:'disabled'}); } // ********************************** Nota Post Procedimiento var val_RESPONSABLE_TRICOTOMIA = objRecord.getValue({fieldId: 'custevent75'}); if(val_RESPONSABLE_TRICOTOMIA!= null && val_RESPONSABLE_TRICOTOMIA!= "") { context.form.getField('custevent75').updateDisplayType({displayType:'hidden'}); context.form.getField('custevent352').updateDisplayType({displayType:'normal'}); context.form.getField('custevent352').updateDisplayType({displayType:'disabled'}); } var val_FECHA_POST_PRO = objRecord.getText({fieldId: 'custevent10'}); if(val_FECHA_POST_PRO!= null && val_FECHA_POST_PRO!= "") { context.form.getField('custevent10').updateDisplayType({displayType:'hidden'}); context.form.getField('custevent353').updateDisplayType({displayType:'normal'}); context.form.getField('custevent353').updateDisplayType({displayType:'disabled'}); } var val_TA_POST_PRO = objRecord.getValue({fieldId: 'custevent11'}); if(val_TA_POST_PRO!= null && val_TA_POST_PRO!= "") { context.form.getField('custevent11').updateDisplayType({displayType:'hidden'}); context.form.getField('custevent354').updateDisplayType({displayType:'normal'}); context.form.getField('custevent354').updateDisplayType({displayType:'disabled'}); } var val_FC_POST_PRO = objRecord.getValue({fieldId: 'custevent12'}); if(val_FC_POST_PRO!= null && val_FC_POST_PRO!= "") { context.form.getField('custevent12').updateDisplayType({displayType:'hidden'}); context.form.getField('custevent355').updateDisplayType({displayType:'normal'}); context.form.getField('custevent355').updateDisplayType({displayType:'disabled'}); } var val_FR_POST_PRO = objRecord.getValue({fieldId: 'custevent13'}); if(val_FR_POST_PRO!= null && val_FR_POST_PRO!= "") { context.form.getField('custevent13').updateDisplayType({displayType:'hidden'}); context.form.getField('custevent356').updateDisplayType({displayType:'normal'}); context.form.getField('custevent356').updateDisplayType({displayType:'disabled'}); } var val_INCIDENTES_DE_IMPORTANCIA = objRecord.getValue({fieldId: 'custevent14'}); if(val_INCIDENTES_DE_IMPORTANCIA!= null && val_INCIDENTES_DE_IMPORTANCIA!= "") { context.form.getField('custevent14').updateDisplayType({displayType:'hidden'}); context.form.getField('custevent357').updateDisplayType({displayType:'normal'}); context.form.getField('custevent357').updateDisplayType({displayType:'disabled'}); } var val_SANGRADO_DURANTE_PROCEDIMIENTO = objRecord.getText({fieldId: 'custevent17'}); if(val_SANGRADO_DURANTE_PROCEDIMIENTO!= null && val_SANGRADO_DURANTE_PROCEDIMIENTO!= "") { context.form.getField('custevent17').updateDisplayType({displayType:'hidden'}); context.form.getField('custevent358').updateDisplayType({displayType:'normal'}); context.form.getField('custevent358').updateDisplayType({displayType:'disabled'}); } var val_MEDICOS_PROCEDIMIENTO_CASO = objRecord.getText({fieldId: 'custevent28'}); if(val_MEDICOS_PROCEDIMIENTO_CASO!= null && val_MEDICOS_PROCEDIMIENTO_CASO!= "") { context.form.getField('custevent28').updateDisplayType({displayType:'hidden'}); context.form.getField('custevent359').updateDisplayType({displayType:'normal'}); context.form.getField('custevent359').updateDisplayType({displayType:'disabled'}); } var val_ENFERMEROS_PROCEDIMIENTO_CASO = objRecord.getText({fieldId: 'custevent29'}); if(val_ENFERMEROS_PROCEDIMIENTO_CASO!= null && val_ENFERMEROS_PROCEDIMIENTO_CASO!= "") { context.form.getField('custevent29').updateDisplayType({displayType:'hidden'}); context.form.getField('custevent360').updateDisplayType({displayType:'normal'}); context.form.getField('custevent360').updateDisplayType({displayType:'disabled'}); } // ********************************** Historial Fotografico var val_DISENO_IMG1 = objRecord.getText({fieldId: 'custevent82'}); if(val_DISENO_IMG1!= null && val_DISENO_IMG1!= "") { context.form.getField('custevent82').updateDisplayType({displayType:'hidden'}); context.form.getField('custevent361').updateDisplayType({displayType:'normal'}); context.form.getField('custevent361').updateDisplayType({displayType:'disabled'}); } var val_DISENO_IMG2 = objRecord.getText({fieldId: 'custevent83'}); if(val_DISENO_IMG2!= null && val_DISENO_IMG2!= "") { context.form.getField('custevent83').updateDisplayType({displayType:'hidden'}); context.form.getField('custevent362').updateDisplayType({displayType:'normal'}); context.form.getField('custevent362').updateDisplayType({displayType:'disabled'}); } var val_DISENO_IMG3 = objRecord.getText({fieldId: 'custevent84'}); if(val_DISENO_IMG3!= null && val_DISENO_IMG3!= "") { context.form.getField('custevent84').updateDisplayType({displayType:'hidden'}); context.form.getField('custevent363').updateDisplayType({displayType:'normal'}); context.form.getField('custevent363').updateDisplayType({displayType:'disabled'}); } var val_DISENO_IMG4 = objRecord.getText({fieldId: 'custevent85'}); if(val_DISENO_IMG4!= null && val_DISENO_IMG4!= "") { context.form.getField('custevent85').updateDisplayType({displayType:'hidden'}); context.form.getField('custevent364').updateDisplayType({displayType:'normal'}); context.form.getField('custevent364').updateDisplayType({displayType:'disabled'}); } var val_TEXTO_IMAGEN = objRecord.getValue({fieldId: 'custevent88'}); if(val_TEXTO_IMAGEN!= null && val_TEXTO_IMAGEN!= "") { context.form.getField('custevent88').updateDisplayType({displayType:'hidden'}); context.form.getField('custevent365').updateDisplayType({displayType:'normal'}); context.form.getField('custevent365').updateDisplayType({displayType:'disabled'}); } var val_IMAGEN_ANTES = objRecord.getText({fieldId: 'custevent76'}); if(val_IMAGEN_ANTES!= null && val_IMAGEN_ANTES!= "") { context.form.getField('custevent76').updateDisplayType({displayType:'hidden'}); context.form.getField('custevent366').updateDisplayType({displayType:'normal'}); context.form.getField('custevent366').updateDisplayType({displayType:'disabled'}); } var val_IMAGEN_DESPUES = objRecord.getText({fieldId: 'custevent77'}); if(val_IMAGEN_DESPUES!= null && val_IMAGEN_DESPUES!= "") { context.form.getField('custevent77').updateDisplayType({displayType:'hidden'}); context.form.getField('custevent367').updateDisplayType({displayType:'normal'}); context.form.getField('custevent367').updateDisplayType({displayType:'disabled'}); } var val_IMAGEN_FRONTAL = objRecord.getText({fieldId: 'custevent78'}); if(val_IMAGEN_FRONTAL!= null && val_IMAGEN_FRONTAL!= "") { context.form.getField('custevent78').updateDisplayType({displayType:'hidden'}); context.form.getField('custevent368').updateDisplayType({displayType:'normal'}); context.form.getField('custevent368').updateDisplayType({displayType:'disabled'}); } var val_EXTRA_IMG = objRecord.getText({fieldId: 'custevent81'}); if(val_EXTRA_IMG!= null && val_EXTRA_IMG!= "") { context.form.getField('custevent81').updateDisplayType({displayType:'hidden'}); context.form.getField('custevent369').updateDisplayType({displayType:'normal'}); context.form.getField('custevent369').updateDisplayType({displayType:'disabled'}); } var val_FIRMA_MEDICO_INJERTO = objRecord.getValue({fieldId: 'custevent87'}); if(val_FIRMA_MEDICO_INJERTO!= null && val_FIRMA_MEDICO_INJERTO!= "")
1,509
[callback](https://dom.spec.whatwg.org/#concept-mo-callback) to callback. The callback is invoked with a list of `[MutationRecord](https://dom.spec.whatwg.org/#mutationrecord)` objects as first argument and the constructed `[MutationObserver](https://dom.spec.whatwg.org/#mutationobserver)` object as second argument. It is invoked after [nodes](https://dom.spec.whatwg.org/#concept-node) registered with the `[observe()](https://dom.spec.whatwg.org/#dom-mutationobserver-observe)` method, are mutated. [MutationObserver/observe](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver/observe "The MutationObserver method observe() configures the MutationObserver callback to begin receiving notifications of changes to the DOM that match the given options.") In all current engines. Firefox14+Safari6+Chrome18+ ___ Opera15+Edge79+ ___ Edge (Legacy)12+IE11 ___ Firefox for Android14+iOS Safari6+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+ ``observer. `[observe(target, options)](https://dom.spec.whatwg.org/#dom-mutationobserver-observe)` `` Instructs the user agent to observe a given target (a [node](https://dom.spec.whatwg.org/#concept-node)) and report any mutations based on the criteria given by options (an object). The options argument allows for setting mutation observation options via object members. These are the object members that can be used: `[childList](https://dom.spec.whatwg.org/#dom-mutationobserverinit-childlist)` Set to true if mutations to target’s [children](https://dom.spec.whatwg.org/#concept-tree-child) are to be observed. `[attributes](https://dom.spec.whatwg.org/#dom-mutationobserverinit-attributes)` Set to true if mutations to target’s [attributes](https://dom.spec.whatwg.org/#concept-attribute) are to be observed. Can be omitted if `[attributeOldValue](https://dom.spec.whatwg.org/#dom-mutationobserverinit-attributeoldvalue)` or `[attributeFilter](https://dom.spec.whatwg.org/#dom-mutationobserverinit-attributefilter)` is specified. `[characterData](https://dom.spec.whatwg.org/#dom-mutationobserverinit-characterdata)` Set to true if mutations to target’s [data](https://dom.spec.whatwg.org/#concept-cd-data) are to be observed. Can be omitted if `[characterDataOldValue](https://dom.spec.whatwg.org/#dom-mutationobserverinit-characterdataoldvalue)` is specified. `[subtree](https://dom.spec.whatwg.org/#dom-mutationobserverinit-subtree)` Set to true if mutations to not just target, but also target’s [descendants](https://dom.spec.whatwg.org/#concept-tree-descendant) are to be observed. `[attributeOldValue](https://dom.spec.whatwg.org/#dom-mutationobserverinit-attributeoldvalue)` Set to true if `[attributes](https://dom.spec.whatwg.org/#dom-mutationobserverinit-attributes)` is true or omitted and target’s [attribute](https://dom.spec.whatwg.org/#concept-attribute) [value](https://dom.spec.whatwg.org/#concept-attribute-value) before the mutation needs to be recorded. `[characterDataOldValue](https://dom.spec.whatwg.org/#dom-mutationobserverinit-characterdataoldvalue)` Set to true if `[characterData](https://dom.spec.whatwg.org/#dom-mutationobserverinit-characterdata)` is set to true or omitted and target’s [data](https://dom.spec.whatwg.org/#concept-cd-data) before the mutation needs to be recorded. `[attributeFilter](https://dom.spec.whatwg.org/#dom-mutationobserverinit-attributefilter)` Set to a list of [attribute](https://dom.spec.whatwg.org/#concept-attribute) [local names](https://dom.spec.whatwg.org/#concept-attribute-local-name) (without [namespace](https://dom.spec.whatwg.org/#concept-attribute-namespace)) if not all [attribute](https://dom.spec.whatwg.org/#concept-attribute) mutations need to be observed and `[attributes](https://dom.spec.whatwg.org/#dom-mutationobserverinit-attributes)` is true or omitted. [MutationObserver/disconnect](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver/disconnect "The MutationObserver method disconnect() tells the observer to stop watching for mutations.") In all current engines. Firefox14+Safari6+Chrome18+ ___ Opera15+Edge79+ ___ Edge (Legacy)12+IE11 ___ Firefox for Android14+iOS Safari6+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+ ``observer. `[disconnect()](https://dom.spec.whatwg.org/#dom-mutationobserver-disconnect)` `` Stops observer from observing any mutations. Until the `[observe()](https://dom.spec.whatwg.org/#dom-mutationobserver-observe)` method is used again, observer’s [callback](https://dom.spec.whatwg.org/#concept-mo-callback) will not be invoked. [MutationObserver/takeRecords](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver/takeRecords "The MutationObserver method takeRecords() returns a list of all matching DOM changes that have been detected but not yet processed by the observer's callback function, leaving the mutation queue empty.") In all current engines. Firefox14+Safari6+Chrome18+ ___ Opera15+Edge79+ ___ Edge (Legacy)12+IE11 ___ Firefox for Android14+iOS Safari6+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+ ``observer. `[takeRecords()](https://dom.spec.whatwg.org/#dom-mutationobserver-takerecords)` `` Empties the [record queue](https://dom.spec.whatwg.org/#concept-mo-queue) and returns what was in there. The `new MutationObserver(callback)` constructor steps are: 1. Set [this](https://webidl.spec.whatwg.org/#this)’s [callback](https://dom.spec.whatwg.org/#concept-mo-callback) to callback. 2. [Append](https://infra.spec.whatwg.org/#set-append) [this](https://webidl.spec.whatwg.org/#this) to [this](https://webidl.spec.whatwg.org/#this)’s [relevant agent](https://html.spec.whatwg.org/multipage/webappapis.html#relevant-agent)’s [mutation observers](https://dom.spec.whatwg.org/#mutation-observer-list). The `observe(target, options)` method steps are: 1. If either options\["`[attributeOldValue](https://dom.spec.whatwg.org/#dom-mutationobserverinit-attributeoldvalue)`"\] or options\["`[attributeFilter](https://dom.spec.whatwg.org/#dom-mutationobserverinit-attributefilter)`"\] [exists](https://infra.spec.whatwg.org/#map-exists), and options\["`[attributes](https://dom.spec.whatwg.org/#dom-mutationobserverinit-attributes)`"\] does not [exist](https://infra.spec.whatwg.org/#map-exists), then set options\["`[attributes](https://dom.spec.whatwg.org/#dom-mutationobserverinit-attributes)`"\] to true. 2. If options\["`[characterDataOldValue](https://dom.spec.whatwg.org/#dom-mutationobserverinit-characterdataoldvalue)`"\] [exists](https://infra.spec.whatwg.org/#map-exists) and options\["`[characterData](https://dom.spec.whatwg.org/#dom-mutationobserverinit-characterdata)`"\] does not [exist](https://infra.spec.whatwg.org/#map-exists), then set options\["`[characterData](https://dom.spec.whatwg.org/#dom-mutationobserverinit-characterdata)`"\] to true. 3. If none of options\["`[childList](https://dom.spec.whatwg.org/#dom-mutationobserverinit-childlist)`"\], options\["`[attributes](https://dom.spec.whatwg.org/#dom-mutationobserverinit-attributes)`"\], and options\["`[characterData](https://dom.spec.whatwg.org/#dom-mutationobserverinit-characterdata)`"\] is true, then [throw](https://webidl.spec.whatwg.org/#dfn-throw) a `TypeError`. 4. If options\["`[attributeOldValue](https://dom.spec.whatwg.org/#dom-mutationobserverinit-attributeoldvalue)`"\] is true and options\["`[attributes](https://dom.spec.whatwg.org/#dom-mutationobserverinit-attributes)`"\] is false, then [throw](https://webidl.spec.whatwg.org/#dfn-throw) a `TypeError`. 5. If options\["`[attributeFilter](https://dom.spec.whatwg.org/#dom-mutationobserverinit-attributefilter)`"\] is present and options\["`[attributes](https://dom.spec.whatwg.org/#dom-mutationobserverinit-attributes)`"\] is false, then [throw](https://webidl.spec.whatwg.org/#dfn-throw) a `TypeError`. 6. If options\["`[characterDataOldValue](https://dom.spec.whatwg.org/#dom-mutationobserverinit-characterdataoldvalue)`"\] is true and options\["`[characterData](https://dom.spec.whatwg.org/#dom-mutationobserverinit-characterdata)`"\] is false, then [throw](https://webidl.spec.whatwg.org/#dfn-throw) a `TypeError`. 7. [For each](https://infra.spec.whatwg.org/#list-iterate) registered of target’s [registered observer list](https://dom.spec.whatwg.org/#registered-observer-list), if registered’s [observer](https://dom.spec.whatwg.org/#registered-observer-observer) is [this](https://webidl.spec.whatwg.org/#this): 1. [For each](https://infra.spec.whatwg.org/#list-iterate) node of [this](https://webidl.spec.whatwg.org/#this)’s [node list](https://dom.spec.whatwg.org/#mutationobserver-node-list), [remove](https://infra.spec.whatwg.org/#list-remove) all [transient registered observers](https://dom.spec.whatwg.org/#transient-registered-observer) whose [source](https://dom.spec.whatwg.org/#transient-registered-observer-source) is registered from node’s [registered observer list](https://dom.spec.whatwg.org/#registered-observer-list). 2. Set registered’s [options](https://dom.spec.whatwg.org/#registered-observer-options) to options. 8. Otherwise: 1. [Append](https://infra.spec.whatwg.org/#list-append) a new [registered observer](https://dom.spec.whatwg.org/#registered-observer) whose [observer](https://dom.spec.whatwg.org/#registered-observer-observer) is [this](https://webidl.spec.whatwg.org/#this) and [options](https://dom.spec.whatwg.org/#registered-observer-options) is options to target’s [registered observer list](https://dom.spec.whatwg.org/#registered-observer-list). 2. [Append](https://infra.spec.whatwg.org/#list-append) target to [this](https://webidl.spec.whatwg.org/#this)’s [node list](https://dom.spec.whatwg.org/#mutationobserver-node-list). The `disconnect()` method steps are: 1. [For each](https://infra.spec.whatwg.org/#list-iterate) node of [this](https://webidl.spec.whatwg.org/#this)’s [node list](https://dom.spec.whatwg.org/#mutationobserver-node-list), [remove](https://infra.spec.whatwg.org/#list-remove) any [registered observer](https://dom.spec.whatwg.org/#registered-observer) from node’s [registered observer list](https://dom.spec.whatwg.org/#registered-observer-list) for which [this](https://webidl.spec.whatwg.org/#this) is the [observer](https://dom.spec.whatwg.org/#registered-observer-observer). 2. [Empty](https://infra.spec.whatwg.org/#list-empty) [this](https://webidl.spec.whatwg.org/#this)’s [record queue](https://dom.spec.whatwg.org/#concept-mo-queue). The `takeRecords()` method steps are: 1. Let records be a [clone](https://infra.spec.whatwg.org/#list-clone) of [this](https://webidl.spec.whatwg.org/#this)’s [record queue](https://dom.spec.whatwg.org/#concept-mo-queue). 2. [Empty](https://infra.spec.whatwg.org/#list-empty) [this](https://webidl.spec.whatwg.org/#this)’s [record queue](https://dom.spec.whatwg.org/#concept-mo-queue). 3. Return records. #### 4.3.2. Queuing a mutation record[](https://dom.spec.whatwg.org/#queueing-a-mutation-record) To queue a mutation record of type for target with name, namespace, oldValue, addedNodes, removedNodes, previousSibling, and nextSibling, run these steps: 1. Let interestedObservers be an empty [map](https://infra.spec.whatwg.org/#ordered-map). 2. Let nodes be the [inclusive ancestors](https://dom.spec.whatwg.org/#concept-tree-inclusive-ancestor) of target. 3. For each node in nodes, and then [for each](https://infra.spec.whatwg.org/#list-iterate) registered of node’s [registered observer list](https://dom.spec.whatwg.org/#registered-observer-list): 1. Let options be registered’s [options](https://dom.spec.whatwg.org/#registered-observer-options). 2. If none of the following are true - node is not target and options\["`[subtree](https://dom.spec.whatwg.org/#dom-mutationobserverinit-subtree)`"\] is false - type is "`attributes`" and options\["`[attributes](https://dom.spec.whatwg.org/#dom-mutationobserverinit-attributes)`"\] either does not [exist](https://infra.spec.whatwg.org/#map-exists) or is false - type is "`attributes`", options\["`[attributeFilter](https://dom.spec.whatwg.org/#dom-mutationobserverinit-attributefilter)`"\] [exists](https://infra.spec.whatwg.org/#map-exists), and options\["`[attributeFilter](https://dom.spec.whatwg.org/#dom-mutationobserverinit-attributefilter)`"\] does not [contain](https://infra.spec.whatwg.org/#list-contain) name or namespace is non-null - type is "`characterData`" and options\["`[characterData](https://dom.spec.whatwg.org/#dom-mutationobserverinit-characterdata)`"\] either does not [exist](https://infra.spec.whatwg.org/#map-exists) or is false - type is "`childList`" and options\["`[childList](https://dom.spec.whatwg.org/#dom-mutationobserverinit-childlist)`"\] is false then: 1. Let mo be registered’s [observer](https://dom.spec.whatwg.org/#registered-observer-observer). 2. If interestedObservers\[mo\] does not [exist](https://infra.spec.whatwg.org/#map-exists), then [set](https://infra.spec.whatwg.org/#map-set) interestedObservers\[mo\] to null. 3. If either type is "`attributes`" and options\["`[attributeOldValue](https://dom.spec.whatwg.org/#dom-mutationobserverinit-attributeoldvalue)`"\] is true, or type is "`characterData`" and options\["`[characterDataOldValue](https://dom.spec.whatwg.org/#dom-mutationobserverinit-characterdataoldvalue)`"\] is true, then [set](https://infra.spec.whatwg.org/#map-set) interestedObservers\[mo\] to oldValue. 4. [For each](https://infra.spec.whatwg.org/#map-iterate) observer → mappedOldValue of interestedObservers: 1. Let record be a new `[MutationRecord](https://dom.spec.whatwg.org/#mutationrecord)` object with its `[type](https://dom.spec.whatwg.org/#dom-mutationrecord-type)` set to type, `[target](https://dom.spec.whatwg.org/#dom-mutationrecord-target)` set to target, `[attributeName](https://dom.spec.whatwg.org/#dom-mutationrecord-attributename)` set to name, `[attributeNamespace](https://dom.spec.whatwg.org/#dom-mutationrecord-attributenamespace)` set to namespace, `[oldValue](https://dom.spec.whatwg.org/#dom-mutationrecord-oldvalue)` set to mappedOldValue, `[addedNodes](https://dom.spec.whatwg.org/#dom-mutationrecord-addednodes)` set to addedNodes, `[removedNodes](https://dom.spec.whatwg.org/#dom-mutationrecord-removednodes)` set to removedNodes, `[previousSibling](https://dom.spec.whatwg.org/#dom-mutationrecord-previoussibling)` set to previousSibling, and `[nextSibling](https://dom.spec.whatwg.org/#dom-mutationrecord-nextsibling)` set to nextSibling. 2. [Enqueue](https://infra.spec.whatwg.org/#queue-enqueue) record to observer’s [record queue](https://dom.spec.whatwg.org/#concept-mo-queue). 5. [Queue a mutation observer microtask](https://dom.spec.whatwg.org/#queue-a-mutation-observer-compound-microtask). To queue a tree mutation record for target with addedNodes, removedNodes, previousSibling, and nextSibling, run these steps: 1. Assert: either addedNodes or removedNodes [is not empty](https://infra.spec.whatwg.org/#list-is-empty). 2. [Queue a mutation record](https://dom.spec.whatwg.org/#queue-a-mutation-record) of "`childList`" for target with null, null, null, addedNodes, removedNodes, previousSibling, and nextSibling. #### 4.3.3. Interface `[MutationRecord](https://dom.spec.whatwg.org/#mutationrecord)`[](https://dom.spec.whatwg.org/#interface-mutationrecord) [MutationRecord](https://developer.mozilla.org/en-US/docs/Web/API/MutationRecord "A MutationRecord represents an individual DOM mutation. It is the object that is inside the array passed to MutationObserver's callback.") In all current engines. Firefox14+Safari7+Chrome16+ ___ Opera15+Edge79+ ___ Edge (Legacy)12+IE11 ___ Firefox for Android14+iOS Safari7+Chrome for Android25+Android WebView37+Samsung Internet1.5+Opera Mobile14+ \[[Exposed](https://webidl.spec.whatwg.org/#Exposed)\=Window\] interface `MutationRecord` { readonly attribute [DOMString](https://webidl.spec.whatwg.org/#idl-DOMString) [type](https://dom.spec.whatwg.org/#dom-mutationrecord-type); \[[SameObject](https://webidl.spec.whatwg.org/#SameObject)\] readonly attribute [Node](https://dom.spec.whatwg.org/#node) [target](https://dom.spec.whatwg.org/#dom-mutationrecord-target); \[[SameObject](https://webidl.spec.whatwg.org/#SameObject)\] readonly attribute [NodeList](https://dom.spec.whatwg.org/#nodelist) [addedNodes](https://dom.spec.whatwg.org/#dom-mutationrecord-addednodes); \[[SameObject](https://webidl.spec.whatwg.org/#SameObject)\] readonly attribute [NodeList](https://dom.spec.whatwg.org/#nodelist) [removedNodes](https://dom.spec.whatwg.org/#dom-mutationrecord-removednodes); readonly attribute [Node](https://dom.spec.whatwg.org/#node)? [previousSibling](https://dom.spec.whatwg.org/#dom-mutationrecord-previoussibling); readonly attribute [Node](https://dom.spec.whatwg.org/#node)? [nextSibling](https://dom.spec.whatwg.org/#dom-mutationrecord-nextsibling); readonly attribute [DOMString](https://webidl.spec.whatwg.org/#idl-DOMString)? [attributeName](https://dom.spec.whatwg.org/#dom-mutationrecord-attributename); readonly attribute [DOMString](https://webidl.spec.whatwg.org/#idl-DOMString)? [attributeNamespace](https://dom.spec.whatwg.org/#dom-mutationrecord-attributenamespace); readonly attribute [DOMString](https://webidl.spec.whatwg.org/#idl-DOMString)? [oldValue](https://dom.spec.whatwg.org/#dom-mutationrecord-oldvalue); }; ``record. `[type](https://dom.spec.whatwg.org/#dom-mutationrecord-type)` `` Returns "`attributes`" if it was an [attribute](https://dom.spec.whatwg.org/#concept-attribute) mutation. "`characterData`" if it was a mutation to a `[CharacterData](https://dom.spec.whatwg.org/#characterdata)` [node](https://dom.spec.whatwg.org/#concept-node). And "`childList`" if it was a mutation to the [tree](https://dom.spec.whatwg.org/#concept-tree) of [nodes](https://dom.spec.whatwg.org/#concept-node). ``record. `[target](https://dom.spec.whatwg.org/#dom-mutationrecord-target)` `` Returns the [node](https://dom.spec.whatwg.org/#concept-node) the mutation affected, depending on the `[type](https://dom.spec.whatwg.org/#dom-mutationrecord-type)`. For "`attributes`", it is the [element](https://dom.spec.whatwg.org/#concept-element) whose [attribute](https://dom.spec.whatwg.org/#concept-attribute) changed. For "`characterData`", it is the `[CharacterData](https://dom.spec.whatwg.org/#characterdata)` [node](https://dom.spec.whatwg.org/#concept-node). For "`childList`", it is the [node](https://dom.spec.whatwg.org/#concept-node) whose [children](https://dom.spec.whatwg.org/#concept-tree-child) changed. ``record. `[addedNodes](https://dom.spec.whatwg.org/#dom-mutationrecord-addednodes)` `` ``record. `[removedNodes](https://dom.spec.whatwg.org/#dom-mutationrecord-removednodes)` `` Return the [nodes](https://dom.spec.whatwg.org/#concept-node) added and removed respectively. ``record. `[previousSibling](https://dom.spec.whatwg.org/#dom-mutationrecord-previoussibling)` `` ``record. `[nextSibling](https://dom.spec.whatwg.org/#dom-mutationrecord-nextsibling)` `` Return the [previous](https://dom.spec.whatwg.org/#concept-tree-previous-sibling) and [next sibling](https://dom.spec.whatwg.org/#concept-tree-next-sibling) respectively of the added or removed [nodes](https://dom.spec.whatwg.org/#concept-node); otherwise null. ``record. `[attributeName](https://dom.spec.whatwg.org/#dom-mutationrecord-attributename)` `` Returns the [local name](https://dom.spec.whatwg.org/#concept-attribute-local-name) of the changed [attribute](https://dom.spec.whatwg.org/#concept-attribute); otherwise null. ``record. `[attributeNamespace](https://dom.spec.whatwg.org/#dom-mutationrecord-attributenamespace)` `` Returns the [namespace](https://dom.spec.whatwg.org/#concept-attribute-namespace) of the changed [attribute](https://dom.spec.whatwg.org/#concept-attribute); otherwise null. ``record. `[oldValue](https://dom.spec.whatwg.org/#dom-mutationrecord-oldvalue)` `` The return value depends on `[type](https://dom.spec.whatwg.org/#dom-mutationrecord-type)`. For "`attributes`", it is the [value](https://dom.spec.whatwg.org/#concept-attribute-value) of the changed [attribute](https://dom.spec.whatwg.org/#concept-attribute) before the change. For "`characterData`", it is the [data](https://dom.spec.whatwg.org/#concept-cd-data) of the changed [node](https://dom.spec.whatwg.org/#concept-node) before the change. For "`childList`", it is null. The `type`, `target`, `addedNodes`, `removedNodes`, `previousSibling`, `nextSibling`, `attributeName`, `attributeNamespace`, and `oldValue` attributes must return the values they were initialized to. #### 4.3.4. Garbage collection[](https://dom.spec.whatwg.org/#garbage-collection) [Nodes](https://dom.spec.whatwg.org/#concept-node) have a strong reference to [registered observers](https://dom.spec.whatwg.org/#registered-observer) in their [registered observer list](https://dom.spec.whatwg.org/#registered-observer-list). [Registered observers](https://dom.spec.whatwg.org/#registered-observer) in a [node](https://dom.spec.whatwg.org/#concept-node)’s [registered observer list](https://dom.spec.whatwg.org/#registered-observer-list) have a weak reference to the [node](https://dom.spec.whatwg.org/#concept-node). ### 4.4. Interface `[Node](https://dom.spec.whatwg.org/#node)`[](https://dom.spec.whatwg.org/#interface-node) [Node](https://developer.mozilla.org/en-US/docs/Web/API/Node "The DOM Node interface is an abstract base class upon which many other DOM API objects are based, thus letting those object types to be used similarly and often interchangeably. As an abstract class, there is no such thing as a plain Node object. All objects that implement Node functionality are based on one of its subclasses. Most notable are Document, Element, and DocumentFragment.") In all current engines. Firefox1+Safari1+Chrome1+ ___ Opera7+Edge79+ ___ Edge (Legacy)12+IE5+ ___ Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+ \[[Exposed](https://webidl.spec.whatwg.org/#Exposed)\=Window\] interface `Node` : [EventTarget](https://dom.spec.whatwg.org/#eventtarget) { const [unsigned short](https://webidl.spec.whatwg.org/#idl-unsigned-short) [ELEMENT\_NODE](https://dom.spec.whatwg.org/#dom-node-element_node) = 1; const [unsigned short](https://webidl.spec.whatwg.org/#idl-unsigned-short) [ATTRIBUTE\_NODE](https://dom.spec.whatwg.org/#dom-node-attribute_node) = 2; const [unsigned short](https://webidl.spec.whatwg.org/#idl-unsigned-short) [TEXT\_NODE](https://dom.spec.whatwg.org/#dom-node-text_node) = 3; const [unsigned short](https://webidl.spec.whatwg.org/#idl-unsigned-short) [CDATA\_SECTION\_NODE](https://dom.spec.whatwg.org/#dom-node-cdata_section_node) = 4; const [unsigned short](https://webidl.spec.whatwg.org/#idl-unsigned-short) `ENTITY_REFERENCE_NODE`[](https://dom.spec.whatwg.org/#dom-node-entity_reference_node) = 5; // legacy const [unsigned short](https://webidl.spec.whatwg.org/#idl-unsigned-short) `ENTITY_NODE`[](https://dom.spec.whatwg.org/#dom-node-entity_node) = 6; // legacy const [unsigned short](https://webidl.spec.whatwg.org/#idl-unsigned-short) [PROCESSING\_INSTRUCTION\_NODE](https://dom.spec.whatwg.org/#dom-node-processing_instruction_node) = 7; const [unsigned short](https://webidl.spec.whatwg.org/#idl-unsigned-short) [COMMENT\_NODE](https://dom.spec.whatwg.org/#dom-node-comment_node) = 8; const [unsigned short](https://webidl.spec.whatwg.org/#idl-unsigned-short) [DOCUMENT\_NODE](https://dom.spec.whatwg.org/#dom-node-document_node) = 9; const [unsigned short](https://webidl.spec.whatwg.org/#idl-unsigned-short) [DOCUMENT\_TYPE\_NODE](https://dom.spec.whatwg.org/#dom-node-document_type_node) = 10; const [unsigned short](https://webidl.spec.whatwg.org/#idl-unsigned-short) [DOCUMENT\_FRAGMENT\_NODE](https://dom.spec.whatwg.org/#dom-node-document_fragment_node) = 11; const [unsigned short](https://webidl.spec.whatwg.org/#idl-unsigned-short) `NOTATION_NODE`[](https://dom.spec.whatwg.org/#dom-node-notation_node) = 12; // legacy readonly attribute [unsigned short](https://webidl.spec.whatwg.org/#idl-unsigned-short) [nodeType](https://dom.spec.whatwg.org/#dom-node-nodetype); readonly attribute [DOMString](https://webidl.spec.whatwg.org/#idl-DOMString) [nodeName](https://dom.spec.whatwg.org/#dom-node-nodename); readonly attribute [USVString](https://webidl.spec.whatwg.org/#idl-USVString) [baseURI](https://dom.spec.whatwg.org/#dom-node-baseuri); readonly attribute [boolean](https://webidl.spec.whatwg.org/#idl-boolean) [isConnected](https://dom.spec.whatwg.org/#dom-node-isconnected); readonly attribute [Document](https://dom.spec.whatwg.org/#document)? [ownerDocument](https://dom.spec.whatwg.org/#dom-node-ownerdocument); [Node](https://dom.spec.whatwg.org/#node) [getRootNode](https://dom.spec.whatwg.org/#dom-node-getrootnode)(optional [GetRootNodeOptions](https://dom.spec.whatwg.org/#dictdef-getrootnodeoptions) `options`[](https://dom.spec.whatwg.org/#dom-node-getrootnode-options-options) = {}); readonly attribute [Node](https://dom.spec.whatwg.org/#node)? [parentNode](https://dom.spec.whatwg.org/#dom-node-parentnode); readonly attribute [Element](https://dom.spec.whatwg.org/#element)? [parentElement](https://dom.spec.whatwg.org/#dom-node-parentelement); [boolean](https://webidl.spec.whatwg.org/#idl-boolean) [hasChildNodes](https://dom.spec.whatwg.org/#dom-node-haschildnodes)(); \[[SameObject](https://webidl.spec.whatwg.org/#SameObject)\] readonly attribute [NodeList](https://dom.spec.whatwg.org/#nodelist) [childNodes](https://dom.spec.whatwg.org/#dom-node-childnodes); readonly attribute [Node](https://dom.spec.whatwg.org/#node)? [firstChild](https://dom.spec.whatwg.org/#dom-node-firstchild); readonly attribute [Node](https://dom.spec.whatwg.org/#node)? [lastChild](https://dom.spec.whatwg.org/#dom-node-lastchild); readonly attribute [Node](https://dom.spec.whatwg.org/#node)? [previousSibling](https://dom.spec.whatwg.org/#dom-node-previoussibling); readonly attribute [Node](https://dom.spec.whatwg.org/#node)? [nextSibling](https://dom.spec.whatwg.org/#dom-node-nextsibling); \[[CEReactions](https://html.spec.whatwg.org/multipage/custom-elements.html#cereactions)\] attribute [DOMString](https://webidl.spec.whatwg.org/#idl-DOMString)? [nodeValue](https://dom.spec.whatwg.org/#dom-node-nodevalue); \[[CEReactions](https://html.spec.whatwg.org/multipage/custom-elements.html#cereactions)\] attribute [DOMString](https://webidl.spec.whatwg.org/#idl-DOMString)? [textContent](https://dom.spec.whatwg.org/#dom-node-textcontent); \[[CEReactions](https://html.spec.whatwg.org/multipage/custom-elements.html#cereactions)\] [undefined](https://webidl.spec.whatwg.org/#idl-undefined) [normalize](https://dom.spec.whatwg.org/#dom-node-normalize)(); \[[CEReactions](https://html.spec.whatwg.org/multipage/custom-elements.html#cereactions), [NewObject](https://webidl.spec.whatwg.org/#NewObject)\] [Node](https://dom.spec.whatwg.org/#node) [cloneNode](https://dom.spec.whatwg.org/#dom-node-clonenode)(optional [boolean](https://webidl.spec.whatwg.org/#idl-boolean) `deep`[](https://dom.spec.whatwg.org/#dom-node-clonenode-deep-deep) = false); [boolean](https://webidl.spec.whatwg.org/#idl-boolean) [isEqualNode](https://dom.spec.whatwg.org/#dom-node-isequalnode)([Node](https://dom.spec.whatwg.org/#node)? `otherNode`[](https://dom.spec.whatwg.org/#dom-node-isequalnode-othernode-othernode)); [boolean](https://webidl.spec.whatwg.org/#idl-boolean) [isSameNode](https://dom.spec.whatwg.org/#dom-node-issamenode)([Node](https://dom.spec.whatwg.org/#node)? `otherNode`[](https://dom.spec.whatwg.org/#dom-node-issamenode-othernode-othernode)); // legacy alias of === const [unsigned short](https://webidl.spec.whatwg.org/#idl-unsigned-short) [DOCUMENT\_POSITION\_DISCONNECTED](https://dom.spec.whatwg.org/#dom-node-document_position_disconnected) = 0x01; const [unsigned short](https://webidl.spec.whatwg.org/#idl-unsigned-short) [DOCUMENT\_POSITION\_PRECEDING](https://dom.spec.whatwg.org/#dom-node-document_position_preceding) = 0x02; const [unsigned short](https://webidl.spec.whatwg.org/#idl-unsigned-short) [DOCUMENT\_POSITION\_FOLLOWING](https://dom.spec.whatwg.org/#dom-node-document_position_following) = 0x04; const [unsigned short](https://webidl.spec.whatwg.org/#idl-unsigned-short) [DOCUMENT\_POSITION\_CONTAINS](https://dom.spec.whatwg.org/#dom-node-document_position_contains) = 0x08; const [unsigned short](https://webidl.spec.whatwg.org/#idl-unsigned-short) [DOCUMENT\_POSITION\_CONTAINED\_BY](https://dom.spec.whatwg.org/#dom-node-document_position_contained_by) = 0x10; const [unsigned short](https://webidl.spec.whatwg.org/#idl-unsigned-short) [DOCUMENT\_POSITION\_IMPLEMENTATION\_SPECIFIC](https://dom.spec.whatwg.org/#dom-node-document_position_implementation_specific) = 0x20; [unsigned short](https://webidl.spec.whatwg.org/#idl-unsigned-short) [compareDocumentPosition](https://dom.spec.whatwg.org/#dom-node-comparedocumentposition)([Node](https://dom.spec.whatwg.org/#node) `other`[](https://dom.spec.whatwg.org/#dom-node-comparedocumentposition-other-other)); [boolean](https://webidl.spec.whatwg.org/#idl-boolean) [contains](https://dom.spec.whatwg.org/#dom-node-contains)([Node](https://dom.spec.whatwg.org/#node)? `other`[](https://dom.spec.whatwg.org/#dom-node-contains-other-other)); [DOMString](https://webidl.spec.whatwg.org/#idl-DOMString)? [lookupPrefix](https://dom.spec.whatwg.org/#dom-node-lookupprefix)([DOMString](https://webidl.spec.whatwg.org/#idl-DOMString)? `namespace`[](https://dom.spec.whatwg.org/#dom-node-lookupprefix-namespace-namespace)); [DOMString](https://webidl.spec.whatwg.org/#idl-DOMString)? [lookupNamespaceURI](https://dom.spec.whatwg.org/#dom-node-lookupnamespaceuri)([DOMString](https://webidl.spec.whatwg.org/#idl-DOMString)? `prefix`[](https://dom.spec.whatwg.org/#dom-node-lookupnamespaceuri-prefix-prefix)); [boolean](https://webidl.spec.whatwg.org/#idl-boolean) [isDefaultNamespace](https://dom.spec.whatwg.org/#dom-node-isdefaultnamespace)([DOMString](https://webidl.spec.whatwg.org/#idl-DOMString)? `namespace`[](https://dom.spec.whatwg.org/#dom-node-isdefaultnamespace-namespace-namespace)); \[[CEReactions](https://html.spec.whatwg.org/multipage/custom-elements.html#cereactions)\] [Node](https://dom.spec.whatwg.org/#node) [insertBefore](https://dom.spec.whatwg.org/#dom-node-insertbefore)([Node](https://dom.spec.whatwg.org/#node) `node`[](https://dom.spec.whatwg.org/#dom-node-insertbefore-node-child-node), [Node](https://dom.spec.whatwg.org/#node)? `child`[](https://dom.spec.whatwg.org/#dom-node-insertbefore-node-child-child)); \[[CEReactions](https://html.spec.whatwg.org/multipage/custom-elements.html#cereactions)\] [Node](https://dom.spec.whatwg.org/#node) [appendChild](https://dom.spec.whatwg.org/#dom-node-appendchild)([Node](https://dom.spec.whatwg.org/#node) `node`[](https://dom.spec.whatwg.org/#dom-node-appendchild-node-node)); \[[CEReactions](https://html.spec.whatwg.org/multipage/custom-elements.html#cereactions)\] [Node](https://dom.spec.whatwg.org/#node) [replaceChild](https://dom.spec.whatwg.org/#dom-node-replacechild)([Node](https://dom.spec.whatwg.org/#node) `node`[](https://dom.spec.whatwg.org/#dom-node-replacechild-node-child-node), [Node](https://dom.spec.whatwg.org/#node) `child`[](https://dom.spec.whatwg.org/#dom-node-replacechild-node-child-child)); \[[CEReactions](https://html.spec.whatwg.org/multipage/custom-elements.html#cereactions)\] [Node](https://dom.spec.whatwg.org/#node) [removeChild](https://dom.spec.whatwg.org/#dom-node-removechild)([Node](https://dom.spec.whatwg.org/#node) `child`[](https://dom.spec.whatwg.org/#dom-node-removechild-child-child)); }; dictionary `GetRootNodeOptions` { [boolean](https://webidl.spec.whatwg.org/#idl-boolean) `composed` = false; }; `[Node](https://dom.spec.whatwg.org/#node)` is an abstract interface that is used by all [nodes](https://dom.spec.whatwg.org/#concept-node). You cannot get a direct instance of it. Each [node](https://dom.spec.whatwg.org/#concept-node) has an associated node document, set upon creation, that is a [document](https://dom.spec.whatwg.org/#concept-document). A [node](https://dom.spec.whatwg.org/#concept-node)’s [node document](https://dom.spec.whatwg.org/#concept-node-document) can be changed by the [adopt](https://dom.spec.whatwg.org/#concept-node-adopt) algorithm. A [node](https://dom.spec.whatwg.org/#concept-node)’s [get the parent](https://dom.spec.whatwg.org/#get-the-parent) algorithm, given an event, returns the [node](https://dom.spec.whatwg.org/#concept-node)’s [assigned slot](https://dom.spec.whatwg.org/#slotable-assigned-slot), if [node](https://dom.spec.whatwg.org/#concept-node) is [assigned](https://dom.spec.whatwg.org/#slotable-assigned); otherwise [node](https://dom.spec.whatwg.org/#concept-node)’s [parent](https://dom.spec.whatwg.org/#concept-tree-parent). Each [node](https://dom.spec.whatwg.org/#concept-node) also has a [registered observer list](https://dom.spec.whatwg.org/#registered-observer-list). ___ [Node/nodeType](https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType "The read-only nodeType property of a Node element is an integer that identifies what the node is. It distinguishes different kind of nodes from each other, such as elements, text and comments.") In all current engines. Firefox1+Safari1.1+Chrome1+ ___ Opera7+Edge79+ ___ Edge (Legacy)12+IE6+ ___ Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+ ``node. `[nodeType](https://dom.spec.whatwg.org/#dom-node-nodetype)` `` Returns a number appropriate for the type of node, as follows: `[Element](https://dom.spec.whatwg.org/#element)` `` `[Node](https://dom.spec.whatwg.org/#node)`. `[ELEMENT_NODE](https://dom.spec.whatwg.org/#dom-node-element_node)` `` (1). `[Attr](https://dom.spec.whatwg.org/#attr)` `` `[Node](https://dom.spec.whatwg.org/#node)`. `[ATTRIBUTE_NODE](https://dom.spec.whatwg.org/#dom-node-attribute_node)` `` (2). An [exclusive `Text` node](https://dom.spec.whatwg.org/#exclusive-text-node) `` `[Node](https://dom.spec.whatwg.org/#node)`. `[TEXT_NODE](https://dom.spec.whatwg.org/#dom-node-text_node)` `` (3). `[CDATASection](https://dom.spec.whatwg.org/#cdatasection)` `` `[Node](https://dom.spec.whatwg.org/#node)`. `[CDATA_SECTION_NODE](https://dom.spec.whatwg.org/#dom-node-cdata_section_node)` `` (4). `[ProcessingInstruction](https://dom.spec.whatwg.org/#processinginstruction)` `` `[Node](https://dom.spec.whatwg.org/#node)`. `[PROCESSING_INSTRUCTION_NODE](https://dom.spec.whatwg.org/#dom-node-processing_instruction_node)` `` (7). `[Comment](https://dom.spec.whatwg.org/#comment)` `` `[Node](https://dom.spec.whatwg.org/#node)`. `[COMMENT_NODE](https://dom.spec.whatwg.org/#dom-node-comment_node)` `` (8). `[Document](https://dom.spec.whatwg.org/#document)` `` `[Node](https://dom.spec.whatwg.org/#node)`. `[DOCUMENT_NODE](https://dom.spec.whatwg.org/#dom-node-document_node)` `` (9). `[DocumentType](https://dom.spec.whatwg.org/#documenttype)` `` `[Node](https://dom.spec.whatwg.org/#node)`. `[DOCUMENT_TYPE_NODE](https://dom.spec.whatwg.org/#dom-node-document_type_node)` `` (10). `[DocumentFragment](https://dom.spec.whatwg.org/#documentfragment)` `` `[Node](https://dom.spec.whatwg.org/#node)`. `[DOCUMENT_FRAGMENT_NODE](https://dom.spec.whatwg.org/#dom-node-document_fragment_node)` `` (11). [Node/nodeName](https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeName "The read-only nodeName property of Node returns the name of the current node as a string.") In all current engines. Firefox1+Safari7+Chrome1+ ___ Opera12.1+Edge79+ ___ Edge (Legacy)12+IE6+ ___ Firefox for Android4+iOS Safari7+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+ ``node. `[nodeName](https://dom.spec.whatwg.org/#dom-node-nodename)` `` Returns a string appropriate for the type of node, as follows: `[Element](https://dom.spec.whatwg.org/#element)` Its [HTML-uppercased qualified name](https://dom.spec.whatwg.org/#element-html-uppercased-qualified-name). `[Attr](https://dom.spec.whatwg.org/#attr)` Its [qualified name](https://dom.spec.whatwg.org/#concept-attribute-qualified-name). An [exclusive `Text` node](https://dom.spec.whatwg.org/#exclusive-text-node) "`#text`". `[CDATASection](https://dom.spec.whatwg.org/#cdatasection)` "`#cdata-section`". `[ProcessingInstruction](https://dom.spec.whatwg.org/#processinginstruction)` Its [target](https://dom.spec.whatwg.org/#concept-pi-target). `[Comment](https://dom.spec.whatwg.org/#comment)` "`#comment`". `[Document](https://dom.spec.whatwg.org/#document)` "`#document`". `[DocumentType](https://dom.spec.whatwg.org/#documenttype)` Its [name](https://dom.spec.whatwg.org/#concept-doctype-name). `[DocumentFragment](https://dom.spec.whatwg.org/#documentfragment)` "`#document-fragment`". The `nodeType` getter steps are to return the first matching statement, switching on the interface [this](https://webidl.spec.whatwg.org/#this) [implements](https://webidl.spec.whatwg.org/#implements): `[Element](https://dom.spec.whatwg.org/#element)` `ELEMENT_NODE` (1) `[Attr](https://dom.spec.whatwg.org/#attr)` `ATTRIBUTE_NODE` (2); An [exclusive `Text` node](https://dom.spec.whatwg.org/#exclusive-text-node) `TEXT_NODE` (3); `[CDATASection](https://dom.spec.whatwg.org/#cdatasection)` `CDATA_SECTION_NODE` (4); `[ProcessingInstruction](https://dom.spec.whatwg.org/#processinginstruction)` `PROCESSING_INSTRUCTION_NODE` (7); `[Comment](https://dom.spec.whatwg.org/#comment)` (8); `[Document](https://dom.spec.whatwg.org/#document)` `DOCUMENT_NODE` (9); `[DocumentType](https://dom.spec.whatwg.org/#documenttype)` `DOCUMENT_TYPE_NODE` (10); `[DocumentFragment](https://dom.spec.whatwg.org/#documentfragment)` `DOCUMENT_FRAGMENT_NODE` (11). The `nodeName` getter steps are to return the first matching statement, switching on the interface [this](https://webidl.spec.whatwg.org/#this) [implements](https://webidl.spec.whatwg.org/#implements): `[Element](https://dom.spec.whatwg.org/#element)` Its [HTML-uppercased qualified name](https://dom.spec.whatwg.org/#element-html-uppercased-qualified-name). `[Attr](https://dom.spec.whatwg.org/#attr)` Its [qualified name](https://dom.spec.whatwg.org/#concept-attribute-qualified-name). An [exclusive `Text` node](https://dom.spec.whatwg.org/#exclusive-text-node) "`#text`". `[CDATASection](https://dom.spec.whatwg.org/#cdatasection)` "`#cdata-section`". `[ProcessingInstruction](https://dom.spec.whatwg.org/#processinginstruction)` Its [target](https://dom.spec.whatwg.org/#concept-pi-target). `[Comment](https://dom.spec.whatwg.org/#comment)` "`#comment`". `[Document](https://dom.spec.whatwg.org/#document)` "`#document`". `[DocumentType](https://dom.spec.whatwg.org/#documenttype)` Its [name](https://dom.spec.whatwg.org/#concept-doctype-name). `[DocumentFragment](https://dom.spec.whatwg.org/#documentfragment)` "`#document-fragment`". ___ [Node/baseURI](https://developer.mozilla.org/en-US/docs/Web/API/Node/baseURI "The read-only baseURI property of the Node interface returns the absolute base URL of the document containing the node.") In all current engines. Firefox1+Safari7+Chrome1+ ___ Opera12.1+Edge79+ ___ Edge (Legacy)12+IENone ___ Firefox for Android4+iOS Safari7+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+ ``node. `[baseURI](https://dom.spec.whatwg.org/#dom-node-baseuri)` `` Returns node’s [node document](https://dom.spec.whatwg.org/#concept-node-document)’s [document base URL](https://html.spec.whatwg.org/multipage/urls-and-fetching.html#document-base-url). The `baseURI` getter steps are to return [this](https://webidl.spec.whatwg.org/#this)’s [node document](https://dom.spec.whatwg.org/#concept-node-document)’s [document base URL](https://html.spec.whatwg.org/multipage/urls-and-fetching.html#document-base-url), [serialized](https://url.spec.whatwg.org/#concept-url-serializer). ___ [Node/isConnected](https://developer.mozilla.org/en-US/docs/Web/API/Node/isConnected "The read-only isConnected property of the Node interface returns a boolean indicating whether the node is connected (directly or indirectly) to the context object, for example the Document object in the case of the normal DOM, or the ShadowRoot in the case of a shadow DOM.") In all current engines. Firefox49+Safari10+Chrome51+ ___ Opera38+Edge79+ ___ Edge (Legacy)NoneIENone ___ Firefox for Android49+iOS Safari10+Chrome for Android51+Android WebView51+Samsung Internet6.0+Opera Mobile41+ ``node. `[isConnected](https://dom.spec.whatwg.org/#dom-node-isconnected)` `` Returns true if node is [connected](https://dom.spec.whatwg.org/#connected); otherwise false. [Node/ownerDocument](https://developer.mozilla.org/en-US/docs/Web/API/Node/ownerDocument "The read-only ownerDocument property of the Node interface returns the top-level document object of the node.") In all current engines. Firefox9+Safari7+Chrome1+ ___ Opera12.1+Edge79+ ___ Edge (Legacy)12+IE6+ ___ Firefox for Android9+iOS Safari7+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+ ``node. `[ownerDocument](https://dom.spec.whatwg.org/#dom-node-ownerdocument)` `` Returns the [node document](https://dom.spec.whatwg.org/#concept-node-document). Returns null for [documents](https://dom.spec.whatwg.org/#concept-document). [Node/getRootNode](https://developer.mozilla.org/en-US/docs/Web/API/Node/getRootNode "The getRootNode() method of the Node interface returns the context object's root, which optionally includes the shadow root if it is available.") In all current engines. Firefox53+Safari10.1+Chrome54+ ___ Opera41+Edge79+ ___ Edge (Legacy)NoneIENone ___ Firefox for Android53+iOS Safari10.3+Chrome for Android54+Android WebView54+Samsung Internet6.0+Opera Mobile41+ ``node. `[getRootNode()](https://dom.spec.whatwg.org/#dom-node-getrootnode)` `` Returns node’s [root](https://dom.spec.whatwg.org/#concept-tree-root). `node. [getRootNode](https://dom.spec.whatwg.org/#dom-node-getrootnode)({ composed:true })` Returns node’s [shadow-including root](https://dom.spec.whatwg.org/#concept-shadow-including-root). [Node/parentNode](https://developer.mozilla.org/en-US/docs/Web/API/Node/parentNode "The read-only parentNode property of the Node interface returns the parent of the specified node in the DOM tree.") In all current engines. Firefox1+Safari1.1+Chrome1+ ___ Opera7+Edge79+ ___ Edge (Legacy)12+IE5.5+ ___ Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+ ``node. `[parentNode](https://dom.spec.whatwg.org/#dom-node-parentnode)` `` Returns the [parent](https://dom.spec.whatwg.org/#concept-tree-parent). [Node/parentElement](https://developer.mozilla.org/en-US/docs/Web/API/Node/parentElement "The read-only parentElement property of Node interface returns the DOM node's parent Element, or null if the node either has no parent, or its parent isn't a DOM Element.") In all current engines. Firefox9+Safari1.1+Chrome1+ ___ Opera7+Edge79+ ___ Edge (Legacy)12+IE9+ ___ Firefox for Android9+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+ ``node. `[parentElement](https://dom.spec.whatwg.org/#dom-node-parentelement)` `` Returns the [parent element](https://dom.spec.whatwg.org/#parent-element). [Node/hasChildNodes](https://developer.mozilla.org/en-US/docs/Web/API/Node/hasChildNodes "The hasChildNodes() method of the Node interface returns a boolean value indicating whether the given Node has child nodes or not.") In all current engines. Firefox1+Safari1+Chrome1+ ___ Opera12.1+Edge79+ ___ Edge (Legacy)12+IE6+ ___ Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+ ``node. `[hasChildNodes()](https://dom.spec.whatwg.org/#dom-node-haschildnodes)` `` Returns whether node has [children](https://dom.spec.whatwg.org/#concept-tree-child). [Node/childNodes](https://developer.mozilla.org/en-US/docs/Web/API/Node/childNodes "The read-only childNodes property of the Node interface returns a live NodeList of child nodes of the given element where the first child node is assigned index 0. Child nodes include elements, text and comments.") In all current engines. Firefox1+Safari1.2+Chrome1+ ___ Opera7+Edge79+ ___ Edge (Legacy)12+IE5+ ___ Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+ ``node. `[childNodes](https://dom.spec.whatwg.org/#dom-node-childnodes)` `` Returns the [children](https://dom.spec.whatwg.org/#concept-tree-child). [Node/firstChild](https://developer.mozilla.org/en-US/docs/Web/API/Node/firstChild "The read-only firstChild property of the Node interface returns the node's first child in the tree, or null if the node has no children.") In all current engines. Firefox1+Safari7+Chrome1+ ___ Opera12.1+Edge79+ ___ Edge (Legacy)12+IE6+ ___ Firefox for Android4+iOS Safari7+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+ ``node. `[firstChild](https://dom.spec.whatwg.org/#dom-node-firstchild)` `` Returns the [first child](https://dom.spec.whatwg.org/#concept-tree-first-child). [Node/lastChild](https://developer.mozilla.org/en-US/docs/Web/API/Node/lastChild "The read-only lastChild property of the Node interface returns the last child of the node. If its parent is an element, then the child is generally an element node, a text node, or a comment node. It returns null if there are no child elements.") In all current engines. Firefox1+Safari7+Chrome1+ ___ Opera12.1+Edge79+ ___ Edge (Legacy)12+IE6+ ___ Firefox for Android45+iOS Safari7+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+ ``node. `[lastChild](https://dom.spec.whatwg.org/#dom-node-lastchild)` `` Returns the [last child](https://dom.spec.whatwg.org/#concept-tree-last-child). [Node/previousSibling](https://developer.mozilla.org/en-US/docs/Web/API/Node/previousSibling "The read-only previousSibling property of the Node interface returns the node immediately preceding the specified one in its parent's childNodes list, or null if the specified node is the first in that list.") In all current engines. Firefox1+Safari7+Chrome1+ ___ Opera12.1+Edge79+ ___ Edge (Legacy)12+IE5.5+ ___ Firefox for Android4+iOS Safari7+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+ ``node. `[previousSibling](https://dom.spec.whatwg.org/#dom-node-previoussibling)` `` Returns the [previous sibling](https://dom.spec.whatwg.org/#concept-tree-previous-sibling). [Node/nextSibling](https://developer.mozilla.org/en-US/docs/Web/API/Node/nextSibling "The read-only nextSibling property of the Node interface returns the node immediately following the specified one in their parent's childNodes, or returns null if the specified node is the last child in the parent element.") In all current engines. Firefox1+Safari1.1+Chrome1+ ___ Opera7+Edge79+ ___ Edge (Legacy)12+IE5.5+ ___ Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+ ``node. `[nextSibling](https://dom.spec.whatwg.org/#dom-node-nextsibling)` `` Returns the [next sibling](https://dom.spec.whatwg.org/#concept-tree-next-sibling). The `isConnected` getter steps are to return true, if [this](https://webidl.spec.whatwg.org/#this) is [connected](https://dom.spec.whatwg.org/#connected); otherwise false. The `ownerDocument` getter steps are to return null, if [this](https://webidl.spec.whatwg.org/#this) is a [document](https://dom.spec.whatwg.org/#concept-document); otherwise [this](https://webidl.spec.whatwg.org/#this)’s [node document](https://dom.spec.whatwg.org/#concept-node-document). The [node document](https://dom.spec.whatwg.org/#concept-node-document) of a [document](https://dom.spec.whatwg.org/#concept-document) is that [document](https://dom.spec.whatwg.org/#concept-document) itself. All [nodes](https://dom.spec.whatwg.org/#concept-node) have a [node document](https://dom.spec.whatwg.org/#concept-node-document) at all times. The `getRootNode(options)` method steps are to return [this](https://webidl.spec.whatwg.org/#this)’s [shadow-including root](https://dom.spec.whatwg.org/#concept-shadow-including-root) if options\["`[composed](https://dom.spec.whatwg.org/#dom-getrootnodeoptions-composed)`"\] is true; otherwise [this](https://webidl.spec.whatwg.org/#this)’s [root](https://dom.spec.whatwg.org/#concept-tree-root). The `parentNode` getter steps are to return [this](https://webidl.spec.whatwg.org/#this)’s [parent](https://dom.spec.whatwg.org/#concept-tree-parent). The `parentElement` getter steps are to return [this](https://webidl.spec.whatwg.org/#this)’s [parent element](https://dom.spec.whatwg.org/#parent-element). The `hasChildNodes()` method steps are to return true if [this](https://webidl.spec.whatwg.org/#this) has [children](https://dom.spec.whatwg.org/#concept-tree-child); otherwise false. The `childNodes` getter steps are to return a `[NodeList](https://dom.spec.whatwg.org/#nodelist)` rooted at [this](https://webidl.spec.whatwg.org/#this) matching only [children](https://dom.spec.whatwg.org/#concept-tree-child). The `firstChild` getter steps are to return [this](https://webidl.spec.whatwg.org/#this)’s [first child](https://dom.spec.whatwg.org/#concept-tree-first-child). The `lastChild` getter steps are to return [this](https://webidl.spec.whatwg.org/#this)’s [last child](https://dom.spec.whatwg.org/#concept-tree-last-child). The `previousSibling` getter steps are to return [this](https://webidl.spec.whatwg.org/#this)’s [previous sibling](https://dom.spec.whatwg.org/#concept-tree-previous-sibling). The `nextSibling` getter steps are to return [this](https://webidl.spec.whatwg.org/#this)’s [next sibling](https://dom.spec.whatwg.org/#concept-tree-next-sibling). ___ [Node/nodeValue](https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeValue "The nodeValue property of the Node interface returns or sets the value of the current node.") In all current engines. Firefox1+Safari7+Chrome1+ ___ Opera12.1+Edge79+ ___ Edge (Legacy)12+IE6+ ___ Firefox for Android4+iOS Safari7+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+ The `nodeValue` getter steps are to return the following, switching on the interface [this](https://webidl.spec.whatwg.org/#this) [implements](https://webidl.spec.whatwg.org/#implements): `[Attr](https://dom.spec.whatwg.org/#attr)` [this](https://webidl.spec.whatwg.org/#this)’s [value](https://dom.spec.whatwg.org/#concept-attribute-value). `[CharacterData](https://dom.spec.whatwg.org/#characterdata)` [this](https://webidl.spec.whatwg.org/#this)’s [data](https://dom.spec.whatwg.org/#concept-cd-data). Otherwise Null. The `[nodeValue](https://dom.spec.whatwg.org/#dom-node-nodevalue)` setter steps are to, if the given value is null, act as if it was the empty string instead, and then do as described below, switching on the interface [this](https://webidl.spec.whatwg.org/#this) [implements](https://webidl.spec.whatwg.org/#implements): `[Attr](https://dom.spec.whatwg.org/#attr)` [Set an existing attribute value](https://dom.spec.whatwg.org/#set-an-existing-attribute-value) with [this](https://webidl.spec.whatwg.org/#this) and the given value. `[CharacterData](https://dom.spec.whatwg.org/#characterdata)` [Replace data](https://dom.spec.whatwg.org/#concept-cd-replace) with node [this](https://webidl.spec.whatwg.org/#this), offset 0, count [this](https://webidl.spec.whatwg.org/#this)’s [length](https://dom.spec.whatwg.org/#concept-node-length), and data the given value. Otherwise Do nothing. [Node/textContent](https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent "The textContent property of the Node interface represents the text content of the node and its descendants.") In all current engines. Firefox1+Safari3+Chrome1+ ___ Opera9+Edge79+ ___ Edge (Legacy)12+IE9+ ___ Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+ The `textContent` getter steps are to return the following, switching on the interface [this](https://webidl.spec.whatwg.org/#this) [implements](https://webidl.spec.whatwg.org/#implements): `[DocumentFragment](https://dom.spec.whatwg.org/#documentfragment)` `[Element](https://dom.spec.whatwg.org/#element)` The [descendant text content](https://dom.spec.whatwg.org/#concept-descendant-text-content) of [this](https://webidl.spec.whatwg.org/#this). `[Attr](https://dom.spec.whatwg.org/#attr)` [this](https://webidl.spec.whatwg.org/#this)’s [value](https://dom.spec.whatwg.org/#concept-attribute-value). `[CharacterData](https://dom.spec.whatwg.org/#characterdata)` [this](https://webidl.spec.whatwg.org/#this)’s [data](https://dom.spec.whatwg.org/#concept-cd-data). Otherwise Null. To string replace all with a string string within a [node](https://dom.spec.whatwg.org/#concept-node) parent, run these steps: 1. Let node be null. 2. If string is not the empty string, then set node to a new `[Text](https://dom.spec.whatwg.org/#text)` [node](https://dom.spec.whatwg.org/#concept-node) whose [data](https://dom.spec.whatwg.org/#concept-cd-data) is string and [node document](https://dom.spec.whatwg.org/#concept-node-document) is parent’s [node document](https://dom.spec.whatwg.org/#concept-node-document). 3. [Replace all](https://dom.spec.whatwg.org/#concept-node-replace-all) with node within parent. The `[textContent](https://dom.spec.whatwg.org/#dom-node-textcontent)` setter steps are to, if the given value is null, act as if it was the empty string instead, and then do as described below, switching on the interface [this](https://webidl.spec.whatwg.org/#this) [implements](https://webidl.spec.whatwg.org/#implements): `[DocumentFragment](https://dom.spec.whatwg.org/#documentfragment)` `[Element](https://dom.spec.whatwg.org/#element)` [String replace all](https://dom.spec.whatwg.org/#string-replace-all) with the given value within [this](https://webidl.spec.whatwg.org/#this). `[Attr](https://dom.spec.whatwg.org/#attr)` [Set an existing attribute value](https://dom.spec.whatwg.org/#set-an-existing-attribute-value) with [this](https://webidl.spec.whatwg.org/#this) and the given value. `[CharacterData](https://dom.spec.whatwg.org/#characterdata)` [Replace data](https://dom.spec.whatwg.org/#concept-cd-replace) with node [this](https://webidl.spec.whatwg.org/#this), offset 0, count [this](https://webidl.spec.whatwg.org/#this)’s [length](https://dom.spec.whatwg.org/#concept-node-length), and data the given value. Otherwise Do nothing. ___ [Node/normalize](https://developer.mozilla.org/en-US/docs/Web/API/Node/normalize "The normalize() method of the Node puts the specified node and all of its sub-tree into a normalized form. In a normalized sub-tree, no text nodes in the sub-tree are empty and there are no adjacent text nodes.") In all current engines. Firefox1+Safari1+Chrome1+ ___ Opera12.1+Edge79+ ___ Edge (Legacy)12+IE9+ ___ Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+ ``node. `[normalize()](https://dom.spec.whatwg.org/#dom-node-normalize)` `` Removes [empty](https://dom.spec.whatwg.org/#concept-node-empty) [exclusive `Text` nodes](https://dom.spec.whatwg.org/#exclusive-text-node) and concatenates the [data](https://dom.spec.whatwg.org/#concept-cd-data) of remaining [contiguous exclusive `Text` nodes](https://dom.spec.whatwg.org/#contiguous-exclusive-text-nodes) into the first of their [nodes](https://dom.spec.whatwg.org/#concept-node). The `normalize()` method steps are to run these steps for each [descendant](https://dom.spec.whatwg.org/#concept-tree-descendant) [exclusive `Text` node](https://dom.spec.whatwg.org/#exclusive-text-node) node of [this](https://webidl.spec.whatwg.org/#this): 1. Let length be node’s [length](https://dom.spec.whatwg.org/#concept-node-length). 2. If length is zero, then [remove](https://dom.spec.whatwg.org/#concept-node-remove) node and continue with the next [exclusive `Text` node](https://dom.spec.whatwg.org/#exclusive-text-node), if any. 3. Let data be the [concatenation](https://infra.spec.whatwg.org/#string-concatenate) of the [data](https://dom.spec.whatwg.org/#concept-cd-data) of node’s [contiguous exclusive `Text` nodes](https://dom.spec.whatwg.org/#contiguous-exclusive-text-nodes) (excluding itself), in [tree order](https://dom.spec.whatwg.org/#concept-tree-order). 4. [Replace data](https://dom.spec.whatwg.org/#concept-cd-replace) with node node, offset length, count 0, and data data. 5. Let currentNode be node’s [next sibling](https://dom.spec.whatwg.org/#concept-tree-next-sibling). 6. While currentNode is an [exclusive `Text` node](https://dom.spec.whatwg.org/#exclusive-text-node): 1. For each [live range](https://dom.spec.whatwg.org/#concept-live-range) whose [start node](https://dom.spec.whatwg.org/#concept-range-start-node) is currentNode, add length to its [start offset](https://dom.spec.whatwg.org/#concept-range-start-offset) and set its [start node](https://dom.spec.whatwg.org/#concept-range-start-node) to node. 2. For each [live range](https://dom.spec.whatwg.org/#concept-live-range) whose [end node](https://dom.spec.whatwg.org/#concept-range-end-node) is currentNode, add length to its [end offset](https://dom.spec.whatwg.org/#concept-range-end-offset) and set its [end node](https://dom.spec.whatwg.org/#concept-range-end-node) to node. 3. For each [live range](https://dom.spec.whatwg.org/#concept-live-range) whose [start node](https://dom.spec.whatwg.org/#concept-range-start-node) is currentNode’s [parent](https://dom.spec.whatwg.org/#concept-tree-parent) and [start offset](https://dom.spec.whatwg.org/#concept-range-start-offset) is currentNode’s [index](https://dom.spec.whatwg.org/#concept-tree-index), set its [start node](https://dom.spec.whatwg.org/#concept-range-start-node) to node and its [start offset](https://dom.spec.whatwg.org/#concept-range-start-offset) to length. 4. For each [live range](https://dom.spec.whatwg.org/#concept-live-range) whose [end node](https://dom.spec.whatwg.org/#concept-range-end-node) is currentNode’s [parent](https://dom.spec.whatwg.org/#concept-tree-parent) and [end offset](https://dom.spec.whatwg.org/#concept-range-end-offset) is currentNode’s [index](https://dom.spec.whatwg.org/#concept-tree-index), set its [end node](https://dom.spec.whatwg.org/#concept-range-end-node) to node and its [end offset](https://dom.spec.whatwg.org/#concept-range-end-offset) to length. 5. Add currentNode’s [length](https://dom.spec.whatwg.org/#concept-node-length) to length. 6. Set currentNode to its [next sibling](https://dom.spec.whatwg.org/#concept-tree-next-sibling). 7. [Remove](https://dom.spec.whatwg.org/#concept-node-remove) node’s [contiguous exclusive `Text` nodes](https://dom.spec.whatwg.org/#contiguous-exclusive-text-nodes) (excluding itself), in [tree order](https://dom.spec.whatwg.org/#concept-tree-order). ___ [Node/cloneNode](https://developer.mozilla.org/en-US/docs/Web/API/Node/cloneNode "The cloneNode() method of the Node interface returns a duplicate of the node on which this method was called. Its parameter controls if the subtree contained in a node is also cloned or not.") In all current engines. Firefox1+Safari1.1+Chrome1+ ___ Opera7+Edge79+ ___ Edge (Legacy)12+IE6+ ___ Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+ `node. [cloneNode([deep = false])](https://dom.spec.whatwg.org/#dom-node-clonenode)` Returns a copy of node. If deep is true, the copy also includes the node’s [descendants](https://dom.spec.whatwg.org/#concept-tree-descendant). [Node/isEqualNode](https://developer.mozilla.org/en-US/docs/Web/API/Node/isEqualNode "The isEqualNode() method of the Node interface tests whether two nodes are equal. Two nodes are equal when they have the same type, defining characteristics (for elements, this would be their ID, number of children, and so forth), its attributes match, and so on. The specific set of data points that must match varies depending on the types of the nodes.") In all current engines. Firefox2+Safari3+Chrome1+ ___ Opera12.1+Edge79+ ___ Edge (Legacy)12+IE9+ ___ Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+ ``node. `[isEqualNode(otherNode)](https://dom.spec.whatwg.org/#dom-node-isequalnode)` `` Returns whether node and otherNode have the same properties. [Specifications](https://dom.spec.whatwg.org/#other-applicable-specifications) may define cloning steps for all or some [nodes](https://dom.spec.whatwg.org/#concept-node). The algorithm is passed copy, node, document, and an optional _clone children flag_, as indicated in the [clone](https://dom.spec.whatwg.org/#concept-node-clone) algorithm. HTML defines [cloning steps](https://dom.spec.whatwg.org/#concept-node-clone-ext) for `[script](https://html.spec.whatwg.org/multipage/scripting.html#script)` and `[input](https://html.spec.whatwg.org/multipage/input.html#the-input-element)` elements. SVG ought to do the same for its `[script](https://html.spec.whatwg.org/multipage/scripting.html#script)` elements, but does not call this out at the moment. To clone a node, with an optional document and _clone children flag_, run these steps: 1. If document is not given, let document be node’s [node document](https://dom.spec.whatwg.org/#concept-node-document). 2. If node is an [element](https://dom.spec.whatwg.org/#concept-element), then: 1. Let copy be the result of [creating an element](https://dom.spec.whatwg.org/#concept-create-element), given document, node’s [local name](https://dom.spec.whatwg.org/#concept-element-local-name), node’s [namespace](https://dom.spec.whatwg.org/#concept-element-namespace), node’s [namespace prefix](https://dom.spec.whatwg.org/#concept-element-namespace-prefix), and node’s [`is` value](https://dom.spec.whatwg.org/#concept-element-is-value), with the synchronous custom elements flag unset. 2. [For each](https://infra.spec.whatwg.org/#list-iterate) attribute in node’s [attribute list](https://dom.spec.whatwg.org/#concept-element-attribute): 1. Let copyAttribute be a [clone](https://dom.spec.whatwg.org/#concept-node-clone) of attribute. 2. [Append](https://dom.spec.whatwg.org/#concept-element-attributes-append) copyAttribute to copy. 3. Otherwise, let copy be a [node](https://dom.spec.whatwg.org/#concept-node) that [implements](https://webidl.spec.whatwg.org/#implements) the same interfaces as node, and fulfills these additional requirements, switching on the interface node [implements](https://webidl.spec.whatwg.org/#implements): `[Document](https://dom.spec.whatwg.org/#document)` Set copy’s [encoding](https://dom.spec.whatwg.org/#concept-document-encoding), [content type](https://dom.spec.whatwg.org/#concept-document-content-type), [URL](https://dom.spec.whatwg.org/#concept-document-url), [origin](https://dom.spec.whatwg.org/#concept-document-origin), [type](https://dom.spec.whatwg.org/#concept-document-type), and [mode](https://dom.spec.whatwg.org/#concept-document-mode) to those of node. `[DocumentType](https://dom.spec.whatwg.org/#documenttype)` Set copy’s [name](https://dom.spec.whatwg.org/#concept-doctype-name), [public ID](https://dom.spec.whatwg.org/#concept-doctype-publicid), and [system ID](https://dom.spec.whatwg.org/#concept-doctype-systemid) to those of node. `[Attr](https://dom.spec.whatwg.org/#attr)` Set copy’s [namespace](https://dom.spec.whatwg.org/#concept-attribute-namespace), [namespace prefix](https://dom.spec.whatwg.org/#concept-attribute-namespace-prefix), [local name](https://dom.spec.whatwg.org/#concept-attribute-local-name), and [value](https://dom.spec.whatwg.org/#concept-attribute-value) to those of node. `[Text](https://dom.spec.whatwg.org/#text)` `[Comment](https://dom.spec.whatwg.org/#comment)` Set copy’s [data](https://dom.spec.whatwg.org/#concept-cd-data) to that of node. `[ProcessingInstruction](https://dom.spec.whatwg.org/#processinginstruction)` Set copy’s [target](https://dom.spec.whatwg.org/#concept-pi-target) and [data](https://dom.spec.whatwg.org/#concept-cd-data) to those of node. Otherwise Do nothing. 4. Set copy’s [node document](https://dom.spec.whatwg.org/#concept-node-document) and document to copy, if copy is a [document](https://dom.spec.whatwg.org/#concept-document), and set copy’s [node document](https://dom.spec.whatwg.org/#concept-node-document) to document otherwise. 5. Run any [cloning steps](https://dom.spec.whatwg.org/#concept-node-clone-ext) defined for node in [other applicable specifications](https://dom.spec.whatwg.org/#other-applicable-specifications) and pass copy, node, document and the _clone children flag_ if set, as parameters. 6. If the _clone children flag_ is set, [clone](https://dom.spec.whatwg.org/#concept-node-clone) all the [children](https://dom.spec.whatwg.org/#concept-tree-child) of node and append them to copy, with document as specified and the _clone children flag_ being set. 7. Return copy. The `cloneNode(deep)` method steps are: 1. If [this](https://webidl.spec.whatwg.org/#this) is a [shadow root](https://dom.spec.whatwg.org/#concept-shadow-root), then [throw](https://webidl.spec.whatwg.org/#dfn-throw) a "`[NotSupportedError](https://webidl.spec.whatwg.org/#notsupportederror)`" `[DOMException](https://webidl.spec.whatwg.org/#idl-DOMException)`. 2. Return a [clone](https://dom.spec.whatwg.org/#concept-node-clone) of [this](https://webidl.spec.whatwg.org/#this), with the _clone children flag_ set if deep is true. A [node](https://dom.spec.whatwg.org/#concept-node) A equals a [node](https://dom.spec.whatwg.org/#concept-node) B if all of the following conditions are true: - A and B [implement](https://webidl.spec.whatwg.org/#implements) the same interfaces. - The following are equal, switching on the interface A [implements](https://webidl.spec.whatwg.org/#implements): `[DocumentType](https://dom.spec.whatwg.org/#documenttype)` Its [name](https://dom.spec.whatwg.org/#concept-doctype-name), [public ID](https://dom.spec.whatwg.org/#concept-doctype-publicid), and [system ID](https://dom.spec.whatwg.org/#concept-doctype-systemid). `[Element](https://dom.spec.whatwg.org/#element)` Its [namespace](https://dom.spec.whatwg.org/#concept-element-namespace), [namespace prefix](https://dom.spec.whatwg.org/#concept-element-namespace-prefix), [local name](https://dom.spec.whatwg.org/#concept-element-local-name), and its [attribute list](https://dom.spec.whatwg.org/#concept-element-attribute)’s [size](https://infra.spec.whatwg.org/#list-size). `[Attr](https://dom.spec.whatwg.org/#attr)` Its [namespace](https://dom.spec.whatwg.org/#concept-attribute-namespace), [local name](https://dom.spec.whatwg.org/#concept-attribute-local-name), and [value](https://dom.spec.whatwg.org/#concept-attribute-value). `[ProcessingInstruction](https://dom.spec.whatwg.org/#processinginstruction)` Its [target](https://dom.spec.whatwg.org/#concept-pi-target) and [data](https://dom.spec.whatwg.org/#concept-cd-data). `[Text](https://dom.spec.whatwg.org/#text)` `[Comment](https://dom.spec.whatwg.org/#comment)` Its [data](https://dom.spec.whatwg.org/#concept-cd-data). Otherwise — - If A is an [element](https://dom.spec.whatwg.org/#concept-element), each [attribute](https://dom.spec.whatwg.org/#concept-attribute) in its [attribute list](https://dom.spec.whatwg.org/#concept-element-attribute) has an [attribute](https://dom.spec.whatwg.org/#concept-attribute) that [equals](https://dom.spec.whatwg.org/#concept-node-equals) an [attribute](https://dom.spec.whatwg.org/#concept-attribute) in B’s [attribute list](https://dom.spec.whatwg.org/#concept-element-attribute). - A and B have the same number of [children](https://dom.spec.whatwg.org/#concept-tree-child). - Each [child](https://dom.spec.whatwg.org/#concept-tree-child) of A [equals](https://dom.spec.whatwg.org/#concept-node-equals) the [child](https://dom.spec.whatwg.org/#concept-tree-child) of B at the identical [index](https://dom.spec.whatwg.org/#concept-tree-index). The `isEqualNode(otherNode)` method steps are to return true if otherNode is non-null and [this](https://webidl.spec.whatwg.org/#this) [equals](https://dom.spec.whatwg.org/#concept-node-equals) otherNode; otherwise false. [Node/isSameNode](https://developer.mozilla.org/en-US/docs/Web/API/Node/isSameNode "The isSameNode() method of the Node interface is a legacy alias the for the === strict equality operator. That is, it tests whether two nodes are the same (in other words, whether they reference the same object).") In all current engines. Firefox48+Safari3+Chrome1+ ___ Opera12.1+Edge79+ ___ Edge (Legacy)12+IE9+ ___ Firefox for Android48+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+ The `isSameNode(otherNode)` method steps are to return true if otherNode is [this](https://webidl.spec.whatwg.org/#this); otherwise false. ___ [Node/compareDocumentPosition](https://developer.mozilla.org/en-US/docs/Web/API/Node/compareDocumentPosition "The compareDocumentPosition() method of the Node interface reports the position of its argument node relative to the node on which it is called.") In all current engines. Firefox9+Safari4+Chrome1+ ___ Opera12.1+Edge79+ ___ Edge (Legacy)12+IE9+ ___ Firefox for Android9+iOS Safari3.2+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile12.1+ ``node. `[compareDocumentPosition(other)](https://dom.spec.whatwg.org/#dom-node-comparedocumentposition)` `` Returns a bitmask indicating the position of other relative to node. These are the bits that can be set: `` `[Node](https://dom.spec.whatwg.org/#node)`. `[DOCUMENT_POSITION_DISCONNECTED](https://dom.spec.whatwg.org/#dom-node-document_position_disconnected)` `` (1) Set when node and other are not in the same [tree](https://dom.spec.whatwg.org/#concept-tree). `` `[Node](https://dom.spec.whatwg.org/#node)`. `[DOCUMENT_POSITION_PRECEDING](https://dom.spec.whatwg.org/#dom-node-document_position_preceding)` `` (2) Set when other is [preceding](https://dom.spec.whatwg.org/#concept-tree-preceding) node. `` `[Node](https://dom.spec.whatwg.org/#node)`. `[DOCUMENT_POSITION_FOLLOWING](https://dom.spec.whatwg.org/#dom-node-document_position_following)` `` (4) Set when other is [following](https://dom.spec.whatwg.org/#concept-tree-following) node. `` `[Node](https://dom.spec.whatwg.org/#node)`. `[DOCUMENT_POSITION_CONTAINS](https://dom.spec.whatwg.org/#dom-node-document_position_contains)` `` (8) Set when other is an [ancestor](https://dom.spec.whatwg.org/#concept-tree-ancestor) of node. `` `[Node](https://dom.spec.whatwg.org/#node)`. `[DOCUMENT_POSITION_CONTAINED_BY](https://dom.spec.whatwg.org/#dom-node-document_position_contained_by)` `` (16, 10 in hexadecimal) Set when other is a [descendant](https://dom.spec.whatwg.org/#concept-tree-descendant) of node. [Node/contains](https://developer.mozilla.org/en-US/docs/Web/API/Node/contains "The contains() method of the Node interface returns a boolean value indicating whether a node is a descendant of a given node, that is the node itself, one of its direct children (childNodes), one of the children's direct children, and so on.") In all current engines. Firefox9+Safari1.1+Chrome16+ ___ Opera7+Edge79+ ___ Edge (Legacy)12+IENone ___ Firefox for Android9+iOS Safari1+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile10.1+ ``node. `[contains(other)](https://dom.spec.whatwg.org/#dom-node-contains)` `` Returns true if other is an [inclusive descendant](https://dom.spec.whatwg.org/#concept-tree-inclusive-descendant) of node; otherwise false. These are the constants `[compareDocumentPosition()](https://dom.spec.whatwg.org/#dom-node-comparedocumentposition)` returns as mask: - `DOCUMENT_POSITION_DISCONNECTED` (1); - `DOCUMENT_POSITION_PRECEDING` (2); - `DOCUMENT_POSITION_FOLLOWING` (4); - `DOCUMENT_POSITION_CONTAINS` (8); - `DOCUMENT_POSITION_CONTAINED_BY` (16, 10 in hexadecimal); - `DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC` (32, 20 in hexadecimal). The `compareDocumentPosition(other)` method steps are: 1. If [this](https://webidl.spec.whatwg.org/#this) is other, then return zero. 2. Let node1 be other and node2 be [this](https://webidl.spec.whatwg.org/#this). 3. Let attr1 and attr2 be null. 4. If node1 is an [attribute](https://dom.spec.whatwg.org/#concept-attribute), then set attr1 to node1 and node1 to attr1’s [element](https://dom.spec.whatwg.org/#concept-attribute-element). 5. If node2 is an [attribute](https://dom.spec.whatwg.org/#concept-attribute), then: 1. Set attr2 to node2 and node2 to attr2’s [element](https://dom.spec.whatwg.org/#concept-attribute-element). 2. If attr1 and node1 are non-null, and node2 is node1, then: 1. [For each](https://infra.spec.whatwg.org/#list-iterate) attr in node2’s [attribute list](https://dom.spec.whatwg.org/#concept-element-attribute): 1. If attr [equals](https://dom.spec.whatwg.org/#concept-node-equals) attr1, then return the result of adding `[DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC](https://dom.spec.whatwg.org/#dom-node-document_position_implementation_specific)` and `[DOCUMENT_POSITION_PRECEDING](https://dom.spec.whatwg.org/#dom-node-document_position_preceding)`. 2. If attr [equals](https://dom.spec.whatwg.org/#concept-node-equals) attr2, then return the result of adding `[DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC](https://dom.spec.whatwg.org/#dom-node-document_position_implementation_specific)` and `[DOCUMENT_POSITION_FOLLOWING](https://dom.spec.whatwg.org/#dom-node-document_position_following)`. 6. If node1 or node2 is null, or node1’s [root](https://dom.spec.whatwg.org/#concept-tree-root) is not node2’s [root](https://dom.spec.whatwg.org/#concept-tree-root), then return the result of adding `[DOCUMENT_POSITION_DISCONNECTED](https://dom.spec.whatwg.org/#dom-node-document_position_disconnected)`, `[DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC](https://dom.spec.whatwg.org/#dom-node-document_position_implementation_specific)`, and either `[DOCUMENT_POSITION_PRECEDING](https://dom.spec.whatwg.org/#dom-node-document_position_preceding)` or `[DOCUMENT_POSITION_FOLLOWING](https://dom.spec.whatwg.org/#dom-node-document_position_following)`, with the constraint that this is to be consistent, together. Whether to return `[DOCUMENT_POSITION_PRECEDING](https://dom.spec.whatwg.org/#dom-node-document_position_preceding)` or `[DOCUMENT_POSITION_FOLLOWING](https://dom.spec.whatwg.org/#dom-node-document_position_following)` is typically implemented via pointer comparison. In JavaScript implementations a cached `Math.random()` value can be used. 7. If node1 is an [ancestor](https://dom.spec.whatwg.org/#concept-tree-ancestor) of node2 and attr1 is null, or node1 is node2 and attr2 is non-null, then return the result of adding `[DOCUMENT_POSITION_CONTAINS](https://dom.spec.whatwg.org/#dom-node-document_position_contains)` to `[DOCUMENT_POSITION_PRECEDING](https://dom.spec.whatwg.org/#dom-node-document_position_preceding)`. 8. If node1 is a [descendant](https://dom.spec.whatwg.org/#concept-tree-descendant) of node2 and attr2 is null, or node1 is node2 and attr1 is non-null, then return the result of adding `[DOCUMENT_POSITION_CONTAINED_BY](https://dom.spec.whatwg.org/#dom-node-document_position_contained_by)` to `[DOCUMENT_POSITION_FOLLOWING](https://dom.spec.whatwg.org/#dom-node-document_position_following)`. 9. If node1 is [preceding](https://dom.spec.whatwg.org/#concept-tree-preceding) node2, then return `[DOCUMENT_POSITION_PRECEDING](https://dom.spec.whatwg.org/#dom-node-document_position_preceding)`. Due to the way [attributes](https://dom.spec.whatwg.org/#concept-attribute) are handled in this algorithm this results in a [node](https://dom.spec.whatwg.org/#concept-node)’s [attributes](https://dom.spec.whatwg.org/#concept-attribute) counting as [preceding](https://dom.spec.whatwg.org/#concept-tree-preceding) that [node](https://dom.spec.whatwg.org/#concept-node)’s [children](https://dom.spec.whatwg.org/#concept-tree-child), despite [attributes](https://dom.spec.whatwg.org/#concept-attribute) not [participating](https://dom.spec.whatwg.org/#concept-tree-participate) in the same [tree](https://dom.spec.whatwg.org/#concept-tree). 10. Return `[DOCUMENT_POSITION_FOLLOWING](https://dom.spec.whatwg.org/#dom-node-document_position_following)`. The `contains(other)` method steps are to return true if other is an [inclusive descendant](https://dom.spec.whatwg.org/#concept-tree-inclusive-descendant) of [this](https://webidl.spec.whatwg.org/#this); otherwise false (including when other is null). ___ To locate a namespace prefix for an element using namespace, run these steps: 1. If element’s [namespace](https://dom.spec.whatwg.org/#concept-element-namespace) is namespace and its [namespace prefix](https://dom.spec.whatwg.org/#concept-element-namespace-prefix) is non-null, then return its [namespace prefix](https://dom.spec.whatwg.org/#concept-element-namespace-prefix). 2. If element [has](https://dom.spec.whatwg.org/#concept-element-attribute-has) an [attribute](https://dom.spec.whatwg.org/#concept-attribute) whose [namespace prefix](https://dom.spec.whatwg.org/#concept-attribute-namespace-prefix) is "`xmlns`" and [value](https://dom.spec.whatwg.org/#concept-attribute-value) is namespace, then return element’s first such [attribute](https://dom.spec.whatwg.org/#concept-attribute)’s [local name](https://dom.spec.whatwg.org/#concept-attribute-local-name). 3. If element’s [parent element](https://dom.spec.whatwg.org/#parent-element) is not null, then return the result of running [locate a namespace prefix](https://dom.spec.whatwg.org/#locate-a-namespace-prefix) on that [element](https://dom.spec.whatwg.org/#concept-element) using namespace. 4. Return null. To locate a namespace for a node using prefix, switch on the interface node [implements](https://webidl.spec.whatwg.org/#implements): `[Element](https://dom.spec.whatwg.org/#element)` 1. If its [namespace](https://dom.spec.whatwg.org/#concept-element-namespace) is non-null and its [namespace prefix](https://dom.spec.whatwg.org/#concept-element-namespace-prefix) is prefix, then return [namespace](https://dom.spec.whatwg.org/#concept-element-namespace). 2. If it [has](https://dom.spec.whatwg.org/#concept-element-attribute-has) an [attribute](https://dom.spec.whatwg.org/#concept-attribute) whose [namespace](https://dom.spec.whatwg.org/#concept-attribute-namespace) is the [XMLNS namespace](https://infra.spec.whatwg.org/#xmlns-namespace), [namespace prefix](https://dom.spec.whatwg.org/#concept-attribute-namespace-prefix) is "`xmlns`", and [local name](https://dom.spec.whatwg.org/#concept-attribute-local-name) is prefix, or if prefix is null and it [has](https://dom.spec.whatwg.org/#concept-element-attribute-has) an [attribute](https://dom.spec.whatwg.org/#concept-attribute) whose [namespace](https://dom.spec.whatwg.org/#concept-attribute-namespace) is the [XMLNS namespace](https://infra.spec.whatwg.org/#xmlns-namespace), [namespace prefix](https://dom.spec.whatwg.org/#concept-attribute-namespace-prefix) is null, and [local name](https://dom.spec.whatwg.org/#concept-attribute-local-name) is "`xmlns`", then return its [value](https://dom.spec.whatwg.org/#concept-attribute-value) if it is not the empty string, and null otherwise. 3. If its [parent element](https://dom.spec.whatwg.org/#parent-element) is null, then return null. 4. Return the result of running [locate a namespace](https://dom.spec.whatwg.org/#locate-a-namespace) on its [parent element](https://dom.spec.whatwg.org/#parent-element) using prefix. `[Document](https://dom.spec.whatwg.org/#document)` 1. If its [document element](https://dom.spec.whatwg.org/#document-element) is null, then return null. 2. Return the result of running [locate a namespace](https://dom.spec.whatwg.org/#locate-a-namespace) on its [document element](https://dom.spec.whatwg.org/#document-element) using prefix. `[DocumentType](https://dom.spec.whatwg.org/#documenttype)` `[DocumentFragment](https://dom.spec.whatwg.org/#documentfragment)` Return null. `[Attr](https://dom.spec.whatwg.org/#attr)` 1. If its [element](https://dom.spec.whatwg.org/#concept-attribute-element) is null, then return null. 2. Return the result of running [locate a namespace](https://dom.spec.whatwg.org/#locate-a-namespace) on its [element](https://dom.spec.whatwg.org/#concept-attribute-element) using prefix. Otherwise 1. If its [parent element](https://dom.spec.whatwg.org/#parent-element) is null, then return null. 2. Return the result of running [locate a namespace](https://dom.spec.whatwg.org/#locate-a-namespace) on its [parent element](https://dom.spec.whatwg.org/#parent-element) using prefix. [Node/lookupPrefix](https://developer.mozilla.org/en-US/docs/Web/API/Node/lookupPrefix "The lookupPrefix() method of the Node interface returns a String containing the prefix for a given namespace URI, if present, and null if not. When multiple prefixes are possible, the first prefix is returned.") In all current engines. Firefox1+Safari3+Chrome1+ ___ Opera12.1+Edge79+ ___ Edge (Legacy)12+IE9+ ___ Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+ The `lookupPrefix(namespace)` method steps are: 1. If namespace is null or the empty string, then return null. 2. Switch on the interface [this](https://webidl.spec.whatwg.org/#this) [implements](https://webidl.spec.whatwg.org/#implements): `[Element](https://dom.spec.whatwg.org/#element)` Return the result of [locating a namespace prefix](https://dom.spec.whatwg.org/#locate-a-namespace-prefix) for it using namespace. `[Document](https://dom.spec.whatwg.org/#document)` Return the result of [locating a namespace prefix](https://dom.spec.whatwg.org/#locate-a-namespace-prefix) for its [document element](https://dom.spec.whatwg.org/#document-element), if its [document element](https://dom.spec.whatwg.org/#document-element) is non-null; otherwise null. `[DocumentType](https://dom.spec.whatwg.org/#documenttype)` `[DocumentFragment](https://dom.spec.whatwg.org/#documentfragment)` Return null. `[Attr](https://dom.spec.whatwg.org/#attr)` Return the result of [locating a namespace prefix](https://dom.spec.whatwg.org/#locate-a-namespace-prefix) for its [element](https://dom.spec.whatwg.org/#concept-attribute-element), if its [element](https://dom.spec.whatwg.org/#concept-attribute-element) is non-null; otherwise null. Otherwise Return the result of [locating a namespace prefix](https://dom.spec.whatwg.org/#locate-a-namespace-prefix) for its [parent element](https://dom.spec.whatwg.org/#parent-element), if its [parent element](https://dom.spec.whatwg.org/#parent-element) is non-null; otherwise null. [Node/lookupNamespaceURI](https://developer.mozilla.org/en-US/docs/Web/API/Node/lookupNamespaceURI "The lookupNamespaceURI() method of the Node interface takes a prefix as parameter and returns the namespace URI associated with it on the given node if found (and null if not).") In all current engines. Firefox1+Safari3+Chrome1+ ___ Opera12.1+Edge79+ ___ Edge (Legacy)12+IE9+ ___ Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+ The `lookupNamespaceURI(prefix)` method steps are: 1. If prefix is the empty string, then set it to null. 2. Return the result of running [locate a namespace](https://dom.spec.whatwg.org/#locate-a-namespace) for [this](https://webidl.spec.whatwg.org/#this) using prefix. [Node/isDefaultNamespace](https://developer.mozilla.org/en-US/docs/Web/API/Node/isDefaultNamespace "The isDefaultNamespace() method of the Node interface accepts a namespace URI as an argument. It returns a boolean value that is true if the namespace is the default namespace on the given node and false if not.") In all current engines. Firefox1+Safari3+Chrome1+ ___ Opera12.1+Edge79+ ___ Edge (Legacy)12+IE9+ ___ Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+ The `isDefaultNamespace(namespace)` method steps are: 1. If namespace is the empty string, then set it to null. 2. Let defaultNamespace be the result of running [locate a namespace](https://dom.spec.whatwg.org/#locate-a-namespace) for [this](https://webidl.spec.whatwg.org/#this) using null. 3. Return true if defaultNamespace is the same as namespace; otherwise false. ___ [Node/insertBefore](https://developer.mozilla.org/en-US/docs/Web/API/Node/insertBefore "The insertBefore() method of the Node interface inserts a node before a reference node as a child of a specified parent node.") In all current engines. Firefox3+Safari1.1+Chrome1+ ___ Opera7+Edge79+ ___ Edge (Legacy)12+IE6+ ___ Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+ The `insertBefore(node, child)` method steps are to return the result of [pre-inserting](https://dom.spec.whatwg.org/#concept-node-pre-insert) node into [this](https://webidl.spec.whatwg.org/#this) before child. [Node/appendChild](https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild "The appendChild() method of the Node interface adds a node to the end of the list of children of a specified parent node. If the given child is a reference to an existing node in the document, appendChild() moves it from its current position to the new position (there is no requirement to remove the node from its parent node before appending it to some other node).") In all current engines. Firefox1+Safari1.1+Chrome1+ ___ Opera7+Edge79+ ___ Edge (Legacy)12+IE5+ ___ Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+ The `appendChild(node)` method steps are to return the result of [appending](https://dom.spec.whatwg.org/#concept-node-append) node to [this](https://webidl.spec.whatwg.org/#this). [Node/replaceChild](https://developer.mozilla.org/en-US/docs/Web/API/Node/replaceChild "The replaceChild() method of the Node element replaces a child node within the given (parent) node.") In all current engines. Firefox1+Safari1.1+Chrome1+ ___ Opera7+Edge79+ ___ Edge (Legacy)12+IE6+ ___ Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+ The `replaceChild(node, child)` method steps are to return the result of [replacing](https://dom.spec.whatwg.org/#concept-node-replace) child with node within [this](https://webidl.spec.whatwg.org/#this). [Node/removeChild](https://developer.mozilla.org/en-US/docs/Web/API/Node/removeChild "The removeChild() method of the Node interface removes a child node from the DOM and returns the removed node.") In all current engines. Firefox1+Safari1.1+Chrome1+ ___ Opera7+Edge79+ ___ Edge (Legacy)12+IE5+ ___ Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+ The `removeChild(child)` method steps are to return the result of [pre-removing](https://dom.spec.whatwg.org/#concept-node-pre-remove) child from [this](https://webidl.spec.whatwg.org/#this). ___ The list of elements with qualified name qualifiedName for a [node](https://dom.spec.whatwg.org/#concept-node) root is the `[HTMLCollection](https://dom.spec.whatwg.org/#htmlcollection)` returned by the following algorithm: 1. If qualifiedName is U+002A (\*), then return a `[HTMLCollection](https://dom.spec.whatwg.org/#htmlcollection)` rooted at root, whose filter matches only [descendant](https://dom.spec.whatwg.org/#concept-tree-descendant) [elements](https://dom.spec.whatwg.org/#concept-element). 2. Otherwise, if root’s [node document](https://dom.spec.whatwg.org/#concept-node-document) is an [HTML document](https://dom.spec.whatwg.org/#html-document), return a `[HTMLCollection](https://dom.spec.whatwg.org/#htmlcollection)` rooted at root, whose filter matches the following [descendant](https://dom.spec.whatwg.org/#concept-tree-descendant) [elements](https://dom.spec.whatwg.org/#concept-element): - Whose [namespace](https://dom.spec.whatwg.org/#concept-element-namespace) is the [HTML namespace](https://infra.spec.whatwg.org/#html-namespace) and whose [qualified name](https://dom.spec.whatwg.org/#concept-element-qualified-name) is qualifiedName, in [ASCII lowercase](https://infra.spec.whatwg.org/#ascii-lowercase). - Whose [namespace](https://dom.spec.whatwg.org/#concept-element-namespace) is _not_ the [HTML namespace](https://infra.spec.whatwg.org/#html-namespace) and whose [qualified name](https://dom.spec.whatwg.org/#concept-element-qualified-name) is qualifiedName. 3. Otherwise, return a `[HTMLCollection](https://dom.spec.whatwg.org/#htmlcollection)` rooted at root, whose filter matches [descendant](https://dom.spec.whatwg.org/#concept-tree-descendant) [elements](https://dom.spec.whatwg.org/#concept-element) whose [qualified name](https://dom.spec.whatwg.org/#concept-element-qualified-name) is qualifiedName. When invoked with the same argument, and as long as root’s [node document](https://dom.spec.whatwg.org/#concept-node-document)’s [type](https://dom.spec.whatwg.org/#concept-document-type) has not changed, the same `[HTMLCollection](https://dom.spec.whatwg.org/#htmlcollection)` object may be returned as returned by an earlier call. The list of elements with namespace namespace and local name localName for a [node](https://dom.spec.whatwg.org/#concept-node) root is the `[HTMLCollection](https://dom.spec.whatwg.org/#htmlcollection)` returned by the following algorithm: 1. If namespace is the empty string, then set it to null. 2. If both namespace and localName are U+002A (\*), then return a `[HTMLCollection](https://dom.spec.whatwg.org/#htmlcollection)` rooted at root, whose filter matches [descendant](https://dom.spec.whatwg.org/#concept-tree-descendant) [elements](https://dom.spec.whatwg.org/#concept-element). 3. If namespace is U+002A (\*), then return a `[HTMLCollection](https://dom.spec.whatwg.org/#htmlcollection)` rooted at root, whose filter matches [descendant](https://dom.spec.whatwg.org/#concept-tree-descendant) [elements](https://dom.spec.whatwg.org/#concept-element) whose [local name](https://dom.spec.whatwg.org/#concept-element-local-name) is localName. 4. If localName is U+002A (\*), then return a `[HTMLCollection](https://dom.spec.whatwg.org/#htmlcollection)` rooted at root, whose filter matches [descendant](https://dom.spec.whatwg.org/#concept-tree-descendant) [elements](https://dom.spec.whatwg.org/#concept-element) whose [namespace](https://dom.spec.whatwg.org/#concept-element-namespace) is namespace. 5. Return a `[HTMLCollection](https://dom.spec.whatwg.org/#htmlcollection)` rooted at root, whose filter matches [descendant](https://dom.spec.whatwg.org/#concept-tree-descendant) [elements](https://dom.spec.whatwg.org/#concept-element) whose [namespace](https://dom.spec.whatwg.org/#concept-element-namespace) is namespace and [local name](https://dom.spec.whatwg.org/#concept-element-local-name) is localName. When invoked with the same arguments, the same `[HTMLCollection](https://dom.spec.whatwg.org/#htmlcollection)` object may be returned as returned by an earlier call. The list of elements with class names classNames for a [node](https://dom.spec.whatwg.org/#concept-node) root is the `[HTMLCollection](https://dom.spec.whatwg.org/#htmlcollection)` returned by the following algorithm: 1. Let classes be the result of running the [ordered set parser](https://dom.spec.whatwg.org/#concept-ordered-set-parser) on classNames. 2. If classes is the empty set, return an empty `[HTMLCollection](https://dom.spec.whatwg.org/#htmlcollection)`. 3. Return a `[HTMLCollection](https://dom.spec.whatwg.org/#htmlcollection)` rooted at root, whose filter matches [descendant](https://dom.spec.whatwg.org/#concept-tree-descendant) [elements](https://dom.spec.whatwg.org/#concept-element) that have all their [classes](https://dom.spec.whatwg.org/#concept-class) in classes. The comparisons for the [classes](https://dom.spec.whatwg.org/#concept-class) must be done in an [ASCII case-insensitive](https://infra.spec.whatwg.org/#ascii-case-insensitive) manner if root’s [node document](https://dom.spec.whatwg.org/#concept-node-document)’s [mode](https://dom.spec.whatwg.org/#concept-document-mode) is "`quirks`"; otherwise in an [identical to](https://infra.spec.whatwg.org/#string-is) manner. When invoked with the same argument, the same `[HTMLCollection](https://dom.spec.whatwg.org/#htmlcollection)` object may be returned as returned by an earlier call. ### 4.5. Interface `[Document](https://dom.spec.whatwg.org/#document)`[](https://dom.spec.whatwg.org/#interface-document) [Document](https://developer.mozilla.org/en-US/docs/Web/API/Document "The Document interface represents any web page loaded in the browser and serves as an entry point into the web page's content, which is the DOM tree.") In all current engines. Firefox1+Safari1+Chrome1+ ___ Opera3+Edge79+ ___ Edge (Legacy)12+IE4+ ___ Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+ [XMLDocument](https://developer.mozilla.org/en-US/docs/Web/API/XMLDocument "The XMLDocument interface represents an XML document. It inherits from the generic Document and does not add any specific methods or properties to it: nevertheless, several algorithms behave differently with the two types of documents.") In all current engines. Firefox1+Safari10+Chrome34+ ___ Opera21+Edge79+ ___ Edge (Legacy)12+IENone ___ Firefox for Android4+iOS Safari10+Chrome for Android34+Android WebView37+Samsung Internet2.0+Opera Mobile21+ \[[Exposed](https://webidl.spec.whatwg.org/#Exposed)\=Window\] interface `Document` : [Node](https://dom.spec.whatwg.org/#node) { [constructor](https://dom.spec.whatwg.org/#dom-document-document)(); \[[SameObject](https://webidl.spec.whatwg.org/#SameObject)\] readonly attribute [DOMImplementation](https://dom.spec.whatwg.org/#domimplementation) [implementation](https://dom.spec.whatwg.org/#dom-document-implementation); readonly attribute [USVString](https://webidl.spec.whatwg.org/#idl-USVString) [URL](https://dom.spec.whatwg.org/#dom-document-url); readonly attribute [USVString](https://webidl.spec.whatwg.org/#idl-USVString) [documentURI](https://dom.spec.whatwg.org/#dom-document-documenturi); readonly attribute [DOMString](https://webidl.spec.whatwg.org/#idl-DOMString) [compatMode](https://dom.spec.whatwg.org/#dom-document-compatmode); readonly attribute [DOMString](https://webidl.spec.whatwg.org/#idl-DOMString) [characterSet](https://dom.spec.whatwg.org/#dom-document-characterset); readonly attribute [DOMString](https://webidl.spec.whatwg.org/#idl-DOMString) [charset](https://dom.spec.whatwg.org/#dom-document-charset); // legacy alias of.characterSet readonly attribute [DOMString](https://webidl.spec.whatwg.org/#idl-DOMString) [inputEncoding](https://dom.spec.whatwg.org/#dom-document-inputencoding); // legacy alias of.characterSet readonly attribute [DOMString](https://webidl.spec.whatwg.org/#idl-DOMString) [contentType](https://dom.spec.whatwg.org/#dom-document-contenttype); readonly attribute [DocumentType](https://dom.spec.whatwg.org/#documenttype)? [doctype](https://dom.spec.whatwg.org/#dom-document-doctype); readonly attribute [Element](https://dom.spec.whatwg.org/#element)? [documentElement](https://dom.spec.whatwg.org/#dom-document-documentelement); [HTMLCollection](https://dom.spec.whatwg.org/#htmlcollection) [getElementsByTagName](https://dom.spec.whatwg.org/#dom-document-getelementsbytagname)([DOMString](https://webidl.spec.whatwg.org/#idl-DOMString) `qualifiedName`[](https://dom.spec.whatwg.org/#dom-document-getelementsbytagname-qualifiedname-qualifiedname)); [HTMLCollection](https://dom.spec.whatwg.org/#htmlcollection) [getElementsByTagNameNS](https://dom.spec.whatwg.org/#dom-document-getelementsbytagnamens)([DOMString](https://webidl.spec.whatwg.org/#idl-DOMString)? `namespace`[](https://dom.spec.whatwg.org/#dom-document-getelementsbytagnamens-namespace-localname-namespace), [DOMString](https://webidl.spec.whatwg.org/#idl-DOMString) `localName`[](https://dom.spec.whatwg.org/#dom-document-getelementsbytagnamens-namespace-localname-localname)); [HTMLCollection](https://dom.spec.whatwg.org/#htmlcollection) [getElementsByClassName](https://dom.spec.whatwg.org/#dom-document-getelementsbyclassname)([DOMString](https://webidl.spec.whatwg.org/#idl-DOMString) `classNames`[](https://dom.spec.whatwg.org/#dom-document-getelementsbyclassname-classnames-classnames)); \[[CEReactions](https://html.spec.whatwg.org/multipage/custom-elements.html#cereactions), [NewObject](https://webidl.spec.whatwg.org/#NewObject)\] [Element](https://dom.spec.whatwg.org/#element) [createElement](https://dom.spec.whatwg.org/#dom-document-createelement)([DOMString](https://webidl.spec.whatwg.org/#idl-DOMString) `localName`[](https://dom.spec.whatwg.org/#dom-document-createelement-localname-options-localname), optional ([DOMString](https://webidl.spec.whatwg.org/#idl-DOMString) or [ElementCreationOptions](https://dom.spec.whatwg.org/#dictdef-elementcreationoptions)) `options`[](https://dom.spec.whatwg.org/#dom-document-createelement-localname-options-options) = {}); \[[CEReactions](https://html.spec.whatwg.org/multipage/custom-elements.html#cereactions), [NewObject](https://webidl.spec.whatwg.org/#NewObject)\] [Element](https://dom.spec.whatwg.org/#element) [createElementNS](https://dom.spec.whatwg.org/#dom-document-createelementns)([DOMString](https://webidl.spec.whatwg.org/#idl-DOMString)? `namespace`[](https://dom.spec.whatwg.org/#dom-document-createelementns-namespace-qualifiedname-options-namespace), [DOMString](https://webidl.spec.whatwg.org/#idl-DOMString) `qualifiedName`[](https://dom.spec.whatwg.org/#dom-document-createelementns-namespace-qualifiedname-options-qualifiedname), optional ([DOMString](https://webidl.spec.whatwg.org/#idl-DOMString) or [ElementCreationOptions](https://dom.spec.whatwg.org/#dictdef-elementcreationoptions)) `options`[](https://dom.spec.whatwg.org/#dom-document-createelementns-namespace-qualifiedname-options-options) = {}); \[[NewObject](https://webidl.spec.whatwg.org/#NewObject)\] [DocumentFragment](https://dom.spec.whatwg.org/#documentfragment) [createDocumentFragment](https://dom.spec.whatwg.org/#dom-document-createdocumentfragment)(); \[[NewObject](https://webidl.spec.whatwg.org/#NewObject)\] [Text](https://dom.spec.whatwg.org/#text) [createTextNode](https://dom.spec.whatwg.org/#dom-document-createtextnode)([DOMString](https://webidl.spec.whatwg.org/#idl-DOMString) `data`[](https://dom.spec.whatwg.org/#dom-document-createtextnode-data-data)); \[[NewObject](https://webidl.spec.whatwg.org/#NewObject)\] [CDATASection](https://dom.spec.whatwg.org/#cdatasection) [createCDATASection](https://dom.spec.whatwg.org/#dom-document-createcdatasection)([DOMString](https://webidl.spec.whatwg.org/#idl-DOMString) `data`[](https://dom.spec.whatwg.org/#dom-document-createcdatasection-data-data)); \[[NewObject](https://webidl.spec.whatwg.org/#NewObject)\] [Comment](https://dom.spec.whatwg.org/#comment) [createComment](https://dom.spec.whatwg.org/#dom-document-createcomment)([DOMString](https://webidl.spec.whatwg.org/#idl-DOMString) ); \[[NewObject](https://webidl.spec.whatwg.org/#NewObject)\] [ProcessingInstruction](https://dom.spec.whatwg.org/#processinginstruction) [createProcessingInstruction](https://dom.spec.whatwg.org/#dom-document-createprocessinginstruction)([DOMString](https://webidl.spec.whatwg.org/#idl-DOMString) `target`[](https://dom.spec.whatwg.org/#dom-document-createprocessinginstruction-target-data-target), [DOMString](https://webidl.spec.whatwg.org/#idl-DOMString) `data`[](https://dom.spec.whatwg.org/#dom-document-createprocessinginstruction-target-data-data)); \[[CEReactions](https://html.spec.whatwg.org/multipage/custom-elements.html#cereactions), [NewObject](https://webidl.spec.whatwg.org/#NewObject)\] [Node](https://dom.spec.whatwg.org/#node) [importNode](https://dom.spec.whatwg.org/#dom-document-importnode)([Node](https://dom.spec.whatwg.org/#node) `node`[](https://dom.spec.whatwg.org/#dom-document-importnode-node-deep-node), optional [boolean](https://webidl.spec.whatwg.org/#idl-boolean) `deep`[](https://dom.spec.whatwg.org/#dom-document-importnode-node-deep-deep) = false); \[[CEReactions](https://html.spec.whatwg.org/multipage/custom-elements.html#cereactions)\] [Node](https://dom.spec.whatwg.org/#node) [adoptNode](https://dom.spec.whatwg.org/#dom-document-adoptnode)([Node](https://dom.spec.whatwg.org/#node) `node`[](https://dom.spec.whatwg.org/#dom-document-adoptnode-node-node)); \[[NewObject](https://webidl.spec.whatwg.org/#NewObject)\] [Attr](https://dom.spec.whatwg.org/#attr) [createAttribute](https://dom.spec.whatwg.org/#dom-document-createattribute)([DOMString](https://webidl.spec.whatwg.org/#idl-DOMString) `localName`[](https://dom.spec.whatwg.org/#dom-document-createattribute-localname-localname)); \[[NewObject](https://webidl.spec.whatwg.org/#NewObject)\] [Attr](https://dom.spec.whatwg.org/#attr) [createAttributeNS](https://dom.spec.whatwg.org/#dom-document-createattributens)([DOMString](https://webidl.spec.whatwg.org/#idl-DOMString)? `namespace`[](https://dom.spec.whatwg.org/#dom-document-createattributens-namespace-qualifiedname-namespace), [DOMString](https://webidl.spec.whatwg.org/#idl-DOMString) `qualifiedName`[](https://dom.spec.whatwg.org/#dom-document-createattributens-namespace-qualifiedname-qualifiedname)); \[[NewObject](https://webidl.spec.whatwg.org/#NewObject)\] [Event](https://dom.spec.whatwg.org/#event) [createEvent](https://dom.spec.whatwg.org/#dom-document-createevent)([DOMString](https://webidl.spec.whatwg.org/#idl-DOMString) `interface`[](https://dom.spec.whatwg.org/#dom-document-createevent-interface-interface)); // legacy \[[NewObject](https://webidl.spec.whatwg.org/#NewObject)\] [Range](https://dom.spec.whatwg.org/#range) [createRange](https://dom.spec.whatwg.org/#dom-document-createrange)(); // NodeFilter.SHOW\_ALL = 0xFFFFFFFF \[[NewObject](https://webidl.spec.whatwg.org/#NewObject)\] [NodeIterator](https://dom.spec.whatwg.org/#nodeiterator) [createNodeIterator](https://dom.spec.whatwg.org/#dom-document-createnodeiterator)([Node](https://dom.spec.whatwg.org/#node) `root`[](https://dom.spec.whatwg.org/#dom-document-createnodeiterator-root-whattoshow-filter-root), optional [unsigned long](https://webidl.spec.whatwg.org/#idl-unsigned-long) `whatToShow`[](https://dom.spec.whatwg.org/#dom-document-createnodeiterator-root-whattoshow-filter-whattoshow) = 0xFFFFFFFF, optional [NodeFilter](https://dom.spec.whatwg.org/#callbackdef-nodefilter)? `filter`[](https://dom.spec.whatwg.org/#dom-document-createnodeiterator-root-whattoshow-filter-filter) = null); \[[NewObject](https://webidl.spec.whatwg.org/#NewObject)\] [TreeWalker](https://dom.spec.whatwg.org/#treewalker) [createTreeWalker](https://dom.spec.whatwg.org/#dom-document-createtreewalker)([Node](https://dom.spec.whatwg.org/#node) `root`[](https://dom.spec.whatwg.org/#dom-document-createtreewalker-root-whattoshow-filter-root), optional [unsigned long](https://webidl.spec.whatwg.org/#idl-unsigned-long) `whatToShow`[](https://dom.spec.whatwg.org/#dom-document-createtreewalker-root-whattoshow-filter-whattoshow) = 0xFFFFFFFF, optional [NodeFilter](https://dom.spec.whatwg.org/#callbackdef-nodefilter)? `filter`[](https://dom.spec.whatwg.org/#dom-document-createtreewalker-root-whattoshow-filter-filter) = null); }; \[[Exposed](https://webidl.spec.whatwg.org/#Exposed)\=Window\] interface `XMLDocument` : [Document](https://dom.spec.whatwg.org/#document) {}; dictionary `ElementCreationOptions` { [DOMString](https://webidl.spec.whatwg.org/#idl-DOMString) `is`; }; `[Document](https://dom.spec.whatwg.org/#document)` [nodes](https://dom.spec.whatwg.org/#concept-node) are simply known as documents. Each [document](https://dom.spec.whatwg.org/#concept-document) has an associated encoding (an [encoding](https://encoding.spec.whatwg.org/#encoding)), content type (a string), URL (a [URL](https://url.spec.whatwg.org/#concept-url)), origin (an [origin](https://html.spec.whatwg.org/multipage/origin.html#concept-origin)), type ("`xml`" or "`html`"), and mode ("`no-quirks`", "`quirks`", or "`limited-quirks`"). [\[ENCODING\]](https://dom.spec.whatwg.org/#biblio-encoding) [\[URL\]](https://dom.spec.whatwg.org/#biblio-url) [\[HTML\]](https://dom.spec.whatwg.org/#biblio-html) Unless stated otherwise, a [document](https://dom.spec.whatwg.org/#concept-document)’s [encoding](https://dom.spec.whatwg.org/#concept-document-encoding) is the [utf-8](https://encoding.spec.whatwg.org/#utf-8) [encoding](https://encoding.spec.whatwg.org/#encoding), [content type](https://dom.spec.whatwg.org/#concept-document-content-type) is "`application/xml`", [URL](https://dom.spec.whatwg.org/#concept-document-url) is "`about:blank`", [origin](https://dom.spec.whatwg.org/#concept-document-origin) is an [opaque origin](https://html.spec.whatwg.org/multipage/origin.html#concept-origin-opaque), [type](https://dom.spec.whatwg.org/#concept-document-type) is "`xml`", and its [mode](https://dom.spec.whatwg.org/#concept-document-mode) is "`no-quirks`". A [document](https://dom.spec.whatwg.org/#concept-document) is said to be an XML document if its [type](https://dom.spec.whatwg.org/#concept-document-type) is "`xml`"; otherwise an HTML document. Whether a [document](https://dom.spec.whatwg.org/#concept-document) is an [HTML document](https://dom.spec.whatwg.org/#html-document) or an [XML document](https://dom.spec.whatwg.org/#xml-document) affects the behavior of certain APIs. A [document](https://dom.spec.whatwg.org/#concept-document) is said to be in no-quirks mode if its [mode](https://dom.spec.whatwg.org/#concept-document-mode) is "`no-quirks`", quirks mode[](https://dom.spec.whatwg.org/#concept-document-quirks) if its [mode](https://dom.spec.whatwg.org/#concept-document-mode) is "`quirks`", and limited-quirks mode if its [mode](https://dom.spec.whatwg.org/#concept-document-mode) is "`limited-quirks`". The [mode](https://dom.spec.whatwg.org/#concept-document-mode) is only ever changed from the default for [documents](https://dom.spec.whatwg.org/#concept-document) created by the [HTML parser](https://html.spec.whatwg.org/multipage/parsing.html#html-parser) based on the presence, absence, or value of the DOCTYPE string, and by a new [browsing context](https://html.spec.whatwg.org/multipage/browsers.html#browsing-context) (initial "`about:blank`"). [\[HTML\]](https://dom.spec.whatwg.org/#biblio-html) [No-quirks mode](https://dom.spec.whatwg.org/#concept-document-no-quirks) was originally known as "standards mode" and [limited-quirks mode](https://dom.spec.whatwg.org/#concept-document-limited-quirks) was once known as "almost standards mode". They have been renamed because their details are now defined by standards. (And because <NAME> vetoed their original names on the basis that they are nonsensical.) A [document](https://dom.spec.whatwg.org/#concept-document)’s [get the parent](https://dom.spec.whatwg.org/#get-the-parent) algorithm, given an event, returns null if event’s `[type](https://dom.spec.whatwg.org/#dom-event-type)` attribute value is "`load`" or [document](https://dom.spec.whatwg.org/#concept-document) does not have a [browsing context](https://html.spec.whatwg.org/multipage/browsers.html#concept-document-bc); otherwise the [document](https://dom.spec.whatwg.org/#concept-document)’s [relevant global object](https://html.spec.whatwg.org/multipage/webappapis.html#concept-relevant-global). ___ [Document/Document](https://developer.mozilla.org/en-US/docs/Web/API/Document/Document "The Document constructor creates a new Document object that is a web page loaded in the browser and serving as an entry point into the page's content.") In all current engines. Firefox20+Safari8+Chrome60+ ___ Opera47+Edge79+ ___ Edge (Legacy)17+IENone ___ Firefox for Android20+iOS Safari8+Chrome for Android60+Android WebView60+Samsung Internet8.0+Opera Mobile44+ ``document = new `[Document()](https://dom.spec.whatwg.org/#dom-document-document)` `` Returns a new [document](https://dom.spec.whatwg.org/#concept-document). [Document/implementation](https://developer.mozilla.org/en-US/docs/Web/API/Document/implementation "The Document.implementation property returns a DOMImplementation object associated with the current document.") In all current engines. Firefox1+Safari1+Chrome1+ ___ Opera12.1+Edge79+ ___ Edge (Legacy)12+IE6+ ___ Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+ ``document. `[implementation](https://dom.spec.whatwg.org/#dom-document-implementation)` `` Returns document’s `[DOMImplementation](https://dom.spec.whatwg.org/#domimplementation)` object. [Document/URL](https://developer.mozilla.org/en-US/docs/Web/API/Document/URL "The URL read-only property of the Document interface returns the document location as a string.") In all current engines. Firefox1+Safari1+Chrome1+ ___ Opera3+Edge79+ ___ Edge (Legacy)12+IE4+ ___ Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+ ``document. `[URL](https://dom.spec.whatwg.org/#dom-document-url)` `` [Document/documentURI](https://developer.mozilla.org/en-US/docs/Web/API/Document/documentURI "The documentURI read-only property of the Document interface returns the document location as a string.") In all current engines. Firefox1+Safari3+Chrome1+ ___ Opera12.1+Edge79+ ___ Edge (Legacy)17+IENone ___ Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+ ``document. `[documentURI](https://dom.spec.whatwg.org/#dom-document-documenturi)` `` Returns document’s [URL](https://dom.spec.whatwg.org/#concept-document-url). [Document/compatMode](https://developer.mozilla.org/en-US/docs/Web/API/Document/compatMode "The Document.compatMode read-only property indicates whether the document is rendered in Quirks mode or Standards mode.") In all current engines. Firefox1+Safari3.1+Chrome1+ ___ Opera12.1+Edge79+ ___ Edge (Legacy)12+IE6+ ___ Firefox for Android4+iOS Safari2+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+ ``document. `[compatMode](https://dom.spec.whatwg.org/#dom-document-compatmode)` `` Returns the string "`BackCompat`" if document’s [mode](https://dom.spec.whatwg.org/#concept-document-mode) is "`quirks`"; otherwise "`CSS1Compat`". [Document/characterSet](https://developer.mozilla.org/en-US/docs/Web/API/Document/characterSet "The Document.characterSet read-only property returns the character encoding of the document that it's currently rendered with.") In all current engines. Firefox1+Safari3+Chrome1+ ___ Opera12.1+Edge79+ ___ Edge (Legacy)12+IE9+ ___ Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera MobileYes ``document. `[characterSet](https://dom.spec.whatwg.org/#dom-document-characterset)` `` Returns document’s [encoding](https://dom.spec.whatwg.org/#concept-document-encoding). [Document/contentType](https://developer.mozilla.org/en-US/docs/Web/API/Document/contentType "The Document.contentType read-only property returns the MIME type that the document is being rendered as. This may come from HTTP headers or other sources of MIME information, and might be affected by automatic type conversions performed by either the browser or extensions.") In all current engines. Firefox1+Safari9+Chrome36+ ___ Opera23+Edge79+ ___ Edge (Legacy)17+IENone ___ Firefox for Android4+iOS Safari9+Chrome for Android36+Android WebView37+Samsung Internet3.0+Opera Mobile24+ ``document. `[contentType](https://dom.spec.whatwg.org/#dom-document-contenttype)` `` Returns document’s [content type](https://dom.spec.whatwg.org/#concept-document-content-type). The `new Document()` constructor steps are to set [this](https://webidl.spec.whatwg.org/#this)’s [origin](https://dom.spec.whatwg.org/#concept-document-origin) to the [origin](https://dom.spec.whatwg.org/#concept-document-origin) of [current global object](https://html.spec.whatwg.org/multipage/webappapis.html#current-global-object)’s [associated `Document`](https://html.spec.whatwg.org/multipage/window-object.html#concept-document-window). [\[HTML\]](https://dom.spec.whatwg.org/#biblio-html) Unlike `[createDocument()](https://dom.spec.whatwg.org/#dom-domimplementation-createdocument)`, this constructor does not return an `[XMLDocument](https://dom.spec.whatwg.org/#xmldocument)` object, but a [document](https://dom.spec.whatwg.org/#concept-document) (`[Document](https://dom.spec.whatwg.org/#document)` object). The `implementation` getter steps are to return the `[DOMImplementation](https://dom.spec.whatwg.org/#domimplementation)` object that is associated with [this](https://webidl.spec.whatwg.org/#this). The `URL` and `documentURI` getter steps are to return [this](https://webidl.spec.whatwg.org/#this)’s [URL](https://dom.spec.whatwg.org/#concept-document-url), [serialized](https://url.spec.whatwg.org/#concept-url-serializer). The `compatMode` getter steps are to return "`BackCompat`" if [this](https://webidl.spec.whatwg.org/#this)’s [mode](https://dom.spec.whatwg.org/#concept-document-mode) is "`quirks`"; otherwise "`CSS1Compat`". The `characterSet`, `charset`, and `inputEncoding` getter steps are to return [this](https://webidl.spec.whatwg.org/#this)’s [encoding](https://dom.spec.whatwg.org/#concept-document-encoding)’s [name](https://encoding.spec.whatwg.org/#name). The `contentType` getter steps are to return [this](https://webidl.spec.whatwg.org/#this)’s [content type](https://dom.spec.whatwg.org/#concept-document-content-type). ___ [Document/doctype](https://developer.mozilla.org/en-US/docs/Web/API/Document/doctype "Returns the Document Type Declaration (DTD) associated with current document. The returned object implements the DocumentType interface. Use DOMImplementation.createDocumentType() to create a DocumentType.") In all current engines. Firefox1+Safari1+Chrome1+ ___ Opera12.1+Edge79+ ___ Edge (Legacy)12+IE6+ ___ Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+ document. `[doctype](https://dom.spec.whatwg.org/#dom-document-doctype)` Returns the [doctype](https://dom.spec.whatwg.org/#concept-doctype) or null if there is none. [Document/documentElement](https://developer.mozilla.org/en-US/docs/Web/API/Document/documentElement "Document.documentElement returns the Element that is the root element of the document (for example, the <html> element for HTML documents).") In all current engines. Firefox1+Safari1+Chrome1+ ___ Opera7+Edge79+ ___ Edge (Legacy)12+IE5+ ___ Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+ document. `[documentElement](https://dom.spec.whatwg.org/#dom-document-documentelement)` Returns the [document element](https://dom.spec.whatwg.org/#document-element). [Document/getElementsByTagName](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByTagName "The getElementsByTagName method of Document interface returns an HTMLCollection of elements with the given tag name.") In all current engines. Firefox1+Safari1+Chrome1+ ___ Opera5.1+Edge79+ ___ Edge (Legacy)12+IE5+ ___ Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+ collection = document. `[getElementsByTagName(qualifiedName)](https://dom.spec.whatwg.org/#dom-document-getelementsbytagname)` If qualifiedName is "`*`" returns a `[HTMLCollection](https://dom.spec.whatwg.org/#htmlcollection)` of all [descendant](https://dom.spec.whatwg.org/#concept-tree-descendant) [elements](https://dom.spec.whatwg.org/#concept-element). Otherwise, returns a `[HTMLCollection](https://dom.spec.whatwg.org/#htmlcollection)` of all [descendant](https://dom.spec.whatwg.org/#concept-tree-descendant) [elements](https://dom.spec.whatwg.org/#concept-element) whose [qualified name](https://dom.spec.whatwg.org/#concept-element-qualified-name) is qualifiedName. (Matches case-insensitively against [elements](https://dom.spec.whatwg.org/#concept-element) in the [HTML namespace](https://infra.spec.whatwg.org/#html-namespace) within an [HTML document](https://dom.spec.whatwg.org/#html-document).) [Document/getElementsByTagNameNS](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByTagNameNS "Returns a list of elements with the given tag name belonging to the given namespace. The complete document is searched, including the root node.") In all current engines. Firefox1+Safari1+Chrome1+ ___ Opera12.1+Edge79+ ___ Edge (Legacy)12+IE9+ ___ Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+ collection = document. `[getElementsByTagNameNS(namespace, localName)](https://dom.spec.whatwg.org/#dom-document-getelementsbytagnamens)` If namespace and localName are "`*`" returns a `[HTMLCollection](https://dom.spec.whatwg.org/#htmlcollection)` of all [descendant](https://dom.spec.whatwg.org/#concept-tree-descendant) [elements](https://dom.spec.whatwg.org/#concept-element). If only namespace is "`*`" returns a `[HTMLCollection](https://dom.spec.whatwg.org/#htmlcollection)` of all [descendant](https://dom.spec.whatwg.org/#concept-tree-descendant) [elements](https://dom.spec.whatwg.org/#concept-element) whose [local name](https://dom.spec.whatwg.org/#concept-element-local-name) is localName. If only localName is "`*`" returns a `[HTMLCollection](https://dom.spec.whatwg.org/#htmlcollection)` of all [descendant](https://dom.spec.whatwg.org/#concept-tree-descendant) [elements](https://dom.spec.whatwg.org/#concept-element) whose [namespace](https://dom.spec.whatwg.org/#concept-element-namespace) is namespace. Otherwise, returns a `[HTMLCollection](https://dom.spec.whatwg.org/#htmlcollection)` of all [descendant](https://dom.spec.whatwg.org/#concept-tree-descendant) [elements](https://dom.spec.whatwg.org/#concept-element) whose [namespace](https://dom.spec.whatwg.org/#concept-element-namespace) is namespace and [local name](https://dom.spec.whatwg.org/#concept-element-local-name) is localName. [Document/getElementsByClassName](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName "The getElementsByClassName method of Document interface returns an array-like object of all child elements which have all of the given class name(s).") In all current engines. Firefox3+Safari3.1+Chrome1+ ___ Opera9.5+Edge79+ ___ Edge (Legacy)12+IE9+ ___ Firefox for Android4+iOS Safari2+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+ collection = document. `[getElementsByClassName(classNames)](https://dom.spec.whatwg.org/#dom-document-getelementsbyclassname)` [Element/getElementsByClassName](https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByClassName "The Element method getElementsByClassName() returns a live HTMLCollection which contains every descendant element which has the specified class name or names.") In all current engines. Firefox3+Safari6+Chrome1+ ___ Opera9.5+Edge79+ ___ Edge (Legacy)16+IENone ___ Firefox for Android4+iOS Safari6+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+ collection = element. `[getElementsByClassName(classNames)](https://dom.spec.whatwg.org/#dom-element-getelementsbyclassname)` Returns a `[HTMLCollection](https://dom.spec.whatwg.org/#htmlcollection)` of the [elements](https://dom.spec.whatwg.org/#concept-element) in the object on which the method was invoked (a [document](https://dom.spec.whatwg.org/#concept-document) or an [element](https://dom.spec.whatwg.org/#concept-element)) that have all the classes given by classNames. The classNames argument is interpreted as a space-separated list of classes. The `doctype` getter steps are to return the [child](https://dom.spec.whatwg.org/#concept-tree-child) of [this](https://webidl.spec.whatwg.org/#this) that is a [doctype](https://dom.spec.whatwg.org/#concept-doctype); otherwise null. The `documentElement` getter steps are to return [this](https://webidl.spec.whatwg.org/#this)’s [document element](https://dom.spec.whatwg.org/#document-element). The `getElementsByTagName(qualifiedName)` method steps are to return the [list of elements with qualified name qualifiedName](https://dom.spec.whatwg.org/#concept-getelementsbytagname) for [this](https://webidl.spec.whatwg.org/#this). Thus, in an [HTML document](https://dom.spec.whatwg.org/#html-document), `document.getElementsByTagName("FOO")` will match `<FOO>` elements that are not in the [HTML namespace](https://infra.spec.whatwg.org/#html-namespace), and `<foo>` elements that are in the [HTML namespace](https://infra.spec.whatwg.org/#html-namespace), but not `<FOO>` elements that are in the [HTML namespace](https://infra.spec.whatwg.org/#html-namespace). The `getElementsByTagNameNS(namespace, localName)` method steps are to return the [list of elements with namespace namespace and local name localName](https://dom.spec.whatwg.org/#concept-getelementsbytagnamens) for [this](https://webidl.spec.whatwg.org/#this). The `getElementsByClassName(classNames)` method steps are to return the [list of elements with class names classNames](https://dom.spec.whatwg.org/#concept-getelementsbyclassname) for [this](https://webidl.spec.whatwg.org/#this). [](https://dom.spec.whatwg.org/#example-5ffcda00)Given the following XHTML fragment: ``` <div id="example"> <p id="p1" class="aaa bbb"/> <p id="p2" class="aaa ccc"/> <p id="p3" class="bbb ccc"/> </div> ``` A call to `document.getElementById("example").getElementsByClassName("aaa")` would return a `[HTMLCollection](https://dom.spec.whatwg.org/#htmlcollection)` with the two paragraphs `p1` and `p2` in it. A call to `getElementsByClassName("ccc bbb")` would only return one node, however, namely `p3`. A call to `document.getElementById("example").getElementsByClassName("bbb  ccc ")` would return the same thing. A call to `getElementsByClassName("aaa,bbb")` would return no nodes; none of the elements above are in the `aaa,bbb` class. ___ [Document/createElement](https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement "In an HTML document, the document.createElement() method creates the HTML element specified by tagName, or an HTMLUnknownElement if tagName isn't recognized.") In all current engines. Firefox1+Safari1+Chrome1+ ___ Opera6+Edge79+ ___ Edge (Legacy)12+IE5+ ___ Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+ `element = document. [createElement(localName [, options])](https://dom.spec.whatwg.org/#dom-document-createelement)` Returns an [element](https://dom.spec.whatwg.org/#concept-element) with localName as [local name](https://dom.spec.whatwg.org/#concept-element-local-name) (if document is an [HTML document](https://dom.spec.whatwg.org/#html-document), localName gets lowercased). The [element](https://dom.spec.whatwg.org/#concept-element)’s [namespace](https://dom.spec.whatwg.org/#concept-element-namespace) is the [HTML namespace](https://infra.spec.whatwg.org/#html-namespace) when document is an [HTML document](https://dom.spec.whatwg.org/#html-document) or document’s [content type](https://dom.spec.whatwg.org/#concept-document-content-type) is "`application/xhtml+xml`"; otherwise null. If localName does not match the `[Name](https://www.w3.org/TR/xml/#NT-Name)` production an "`[InvalidCharacterError](https://webidl.spec.whatwg.org/#invalidcharactererror)`" `[DOMException](https://webidl.spec.whatwg.org/#idl-DOMException)` will be thrown. When supplied, options’s `[is](https://dom.spec.whatwg.org/#dom-elementcreationoptions-is)` can be used to create a [customized built-in element](https://html.spec.whatwg.org/multipage/custom-elements.html#customized-built-in-element). [Document/createElementNS](https://developer.mozilla.org/en-US/docs/Web/API/Document/createElementNS "Creates an element with the specified namespace URI and qualified name.") In all current engines. Firefox1+Safari1+Chrome1+ ___ Opera12.1+Edge79+ ___ Edge (Legacy)12+IE9+ ___ Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+ `element = document. [createElementNS(namespace, qualifiedName [, options])](https://dom.spec.whatwg.org/#dom-document-createelementns)` Returns an [element](https://dom.spec.whatwg.org/#concept-element) with [namespace](https://dom.spec.whatwg.org/#concept-element-namespace) namespace. Its [namespace prefix](https://dom.spec.whatwg.org/#concept-element-namespace-prefix) will be everything before U+003A (:) in qualifiedName or null. Its [local name](https://dom.spec.whatwg.org/#concept-element-local-name) will be everything after U+003A (:) in qualifiedName or qualifiedName. If qualifiedName does not match the `[QName](https://www.w3.org/TR/xml-names/#NT-QName)` production an "`[InvalidCharacterError](https://webidl.spec.whatwg.org/#invalidcharactererror)`" `[DOMException](https://webidl.spec.whatwg.org/#idl-DOMException)` will be thrown. If one of the following conditions is true a "`[NamespaceError](https://webidl.spec.whatwg.org/#namespaceerror)`" `[DOMException](https://webidl.spec.whatwg.org/#idl-DOMException)` will be thrown: - [Namespace prefix](https://dom.spec.whatwg.org/#concept-element-namespace-prefix) is not null and namespace is the empty string. - [Namespace prefix](https://dom.spec.whatwg.org/#concept-element-namespace-prefix) is "`xml`" and namespace is not the [XML namespace](https://infra.spec.whatwg.org/#xml-namespace). - qualifiedName or [namespace prefix](https://dom.spec.whatwg.org/#concept-element-namespace-prefix) is "`xmlns`" and namespace is not the [XMLNS namespace](https://infra.spec.whatwg.org/#xmlns-namespace). - namespace is the [XMLNS namespace](https://infra.spec.whatwg.org/#xmlns-namespace) and neither qualifiedName nor [namespace prefix](https://dom.spec.whatwg.org/#concept-element-namespace-prefix) is "`xmlns`". When supplied, options’s `[is](https://dom.spec.whatwg.org/#dom-elementcreationoptions-is)` can be used to create a [customized built-in element](https://html.spec.whatwg.org/multipage/custom-elements.html#customized-built-in-element). [Document/createDocumentFragment](https://developer.mozilla.org/en-US/docs/Web/API/Document/createDocumentFragment "Creates a new empty DocumentFragment into which DOM nodes can be added to build an offscreen DOM tree.") In all current engines. Firefox1+Safari1+Chrome1+ ___ Opera12.1+Edge79+ ___ Edge (Legacy)12+IE6+ ___ Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+ ``documentFragment = document. `[createDocumentFragment()](https://dom.spec.whatwg.org/#dom-document-createdocumentfragment)` `` Returns a `[DocumentFragment](https://dom.spec.whatwg.org/#documentfragment)` [node](https://dom.spec.whatwg.org/#concept-node). [Document/createTextNode](https://developer.mozilla.org/en-US/docs/Web/API/Document/createTextNode "Creates a new Text node. This method can be used to escape HTML characters.") In all current engines. Firefox1+Safari1+Chrome1+ ___ Opera7+Edge79+ ___ Edge (Legacy)12+IE5+ ___ Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+ ``text = document. `[createTextNode(data)](https://dom.spec.whatwg.org/#dom-document-createtextnode)` `` Returns a `[Text](https://dom.spec.whatwg.org/#text)` [node](https://dom.spec.whatwg.org/#concept-node) whose [data](https://dom.spec.whatwg.org/#concept-cd-data) is data. ``text = document. `[createCDATASection(data)](https://dom.spec.whatwg.org/#dom-document-createcdatasection)` `` Returns a `[CDATASection](https://dom.spec.whatwg.org/#cdatasection)` [node](https://dom.spec.whatwg.org/#concept-node) whose [data](https://dom.spec.whatwg.org/#concept-cd-data) is data. [Document/createCDATASection](https://developer.mozilla.org/en-US/docs/Web/API/Document/createCDATASection "createCDATASection() creates a new CDATA section node, and returns it.") In all current engines. Firefox1+Safari1+Chrome1+ ___ Opera12.1+Edge79+ ___ Edge (Legacy)12+IE9+ ___ Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+ [Document/createComment](https://developer.mozilla.org/en-US/docs/Web/API/Document/createComment "createComment() creates a new comment node, and returns it.") In all current engines. Firefox1+Safari1+Chrome1+ ___ Opera12.1+Edge79+ ___ Edge (Legacy)12+IE6+ ___ Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+ ``comment = document. `[createComment(data)](https://dom.spec.whatwg.org/#dom-document-createcomment)` `` Returns a `[Comment](https://dom.spec.whatwg.org/#comment)` [node](https://dom.spec.whatwg.org/#concept-node) whose [data](https://dom.spec.whatwg.org/#concept-cd-data) is data. [Document/createProcessingInstruction](https://developer.mozilla.org/en-US/docs/Web/API/Document/createProcessingInstruction "createProcessingInstruction() generates a new processing instruction node and returns it.") In all current engines. Firefox1+Safari1+Chrome1+ ___ Opera12.1+Edge79+ ___ Edge (Legacy)12+IE9+ ___ Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+ ``processingInstruction = document. `[createProcessingInstruction(target, data)](https://dom.spec.whatwg.org/#dom-document-createprocessinginstruction)` `` Returns a `[ProcessingInstruction](https://dom.spec.whatwg.org/#processinginstruction)` [node](https://dom.spec.whatwg.org/#concept-node) whose [target](https://dom.spec.whatwg.org/#concept-pi-target) is target and [data](https://dom.spec.whatwg.org/#concept-cd-data) is data. If target does not match the `[Name](https://www.w3.org/TR/xml/#NT-Name)` production an "`[InvalidCharacterError](https://webidl.spec.whatwg.org/#invalidcharactererror)`" `[DOMException](https://webidl.spec.whatwg.org/#idl-DOMException)` will be thrown. If data contains "`?>`" an "`[InvalidCharacterError](https://webidl.spec.whatwg.org/#invalidcharactererror)`" `[DOMException](https://webidl.spec.whatwg.org/#idl-DOMException)` will be thrown. The element interface for any name and namespace is `[Element](https://dom.spec.whatwg.org/#element)`, unless stated otherwise. The HTML Standard will, e.g., define that for `html` and the [HTML namespace](https://infra.spec.whatwg.org/#html-namespace), the `[HTMLHtmlElement](https://html.spec.whatwg.org/multipage/semantics.html#htmlhtmlelement)` interface is used. [\[HTML\]](https://dom.spec.whatwg.org/#biblio-html) The `createElement(localName, options)` method steps are: 1. If localName does not match the `[Name](https://www.w3.org/TR/xml/#NT-Name)` production, then [throw](https://webidl.spec.whatwg.org/#dfn-throw) an "`[InvalidCharacterError](https://webidl.spec.whatwg.org/#invalidcharactererror)`" `[DOMException](https://webidl.spec.whatwg.org/#idl-DOMException)`. 2. If [this](https://webidl.spec.whatwg.org/#this) is an [HTML document](https://dom.spec.whatwg.org/#html-document), then set localName to localName in [ASCII lowercase](https://infra.spec.whatwg.org/#ascii-lowercase). 3. Let is be null. 4. If options is a [dictionary](https://webidl.spec.whatwg.org/#dfn-dictionary) and options\["`[is](https://dom.spec.whatwg.org/#dom-elementcreationoptions-is)`"\] [exists](https://infra.spec.whatwg.org/#map-exists), then set is to it. 5. Let namespace be the [HTML namespace](https://infra.spec.whatwg.org/#html-namespace), if [this](https://webidl.spec.whatwg.org/#this) is an [HTML document](https://dom.spec.whatwg.org/#html-document) or [this](https://webidl.spec.whatwg.org/#this)’s [content type](https://dom.spec.whatwg.org/#concept-document-content-type) is "`application/xhtml+xml`"; otherwise null. 6. Return the result of [creating an element](https://dom.spec.whatwg.org/#concept-create-element) given [this](https://webidl.spec.whatwg.org/#this), localName, namespace, null, is, and with the synchronous custom elements flag set. The internal `createElementNS` steps, given document, namespace, qualifiedName, and options, are as follows: 1. Let namespace, prefix, and localName be the result of passing namespace and qualifiedName to [validate and extract](https://dom.spec.whatwg.org/#validate-and-extract). 2. Let is be null. 3. If options is a [dictionary](https://webidl.spec.whatwg.org/#dfn-dictionary) and options\["`[is](https://dom.spec.whatwg.org/#dom-elementcreationoptions-is)`"\] [exists](https://infra.spec.whatwg.org/#map-exists), then set is to it. 4. Return the result of [creating an element](https://dom.spec.whatwg.org/#concept-create-element) given document, localName, namespace, prefix, is, and with the synchronous custom elements flag set. The `createElementNS(namespace, qualifiedName, options)` method steps are to return the result of running the [internal `createElementNS` steps](https://dom.spec.whatwg.org/#internal-createelementns-steps), given [this](https://webidl.spec.whatwg.org/#this), namespace, qualifiedName, and options. `[createElement()](https://dom.spec.whatwg.org/#dom-document-createelement)` and `[createElementNS()](https://dom.spec.whatwg.org/#dom-document-createelementns)`'s options parameter is allowed to be a string for web compatibility. The `createDocumentFragment()` method steps are to return a new `[DocumentFragment](https://dom.spec.whatwg.org/#documentfragment)` [node](https://dom.spec.whatwg.org/#concept-node) whose [node document](https://dom.spec.whatwg.org/#concept-node-document) is [this](https://webidl.spec.whatwg.org/#this). The `createTextNode(data)` method steps are to return a new `[Text](https://dom.spec.whatwg.org/#text)` [node](https://dom.spec.whatwg.org/#concept-node) whose [data](https://dom.spec.whatwg.org/#concept-cd-data) is data and [node document](https://dom.spec.whatwg.org/#concept-node-document) is [this](https://webidl.spec.whatwg.org/#this). No check is performed that data consists of characters that match the `[Char](https://www.w3.org/TR/xml/#NT-Char)` production. The `createCDATASection(data)` method steps are: 1. If [this](https://webidl.spec.whatwg.org/#this) is an [HTML document](https://dom.spec.whatwg.org/#html-document), then [throw](https://webidl.spec.whatwg.org/#dfn-throw) a "`[NotSupportedError](https://webidl.spec.whatwg.org/#notsupportederror)`" `[DOMException](https://webidl.spec.whatwg.org/#idl-DOMException)`. 2. If data contains the string "`]]>`", then [throw](https://webidl.spec.whatwg.org/#dfn-throw) an "`[InvalidCharacterError](https://webidl.spec.whatwg.org/#invalidcharactererror)`" `[DOMException](https://webidl.spec.whatwg.org/#idl-DOMException)`. 3. Return a new `[CDATASection](https://dom.spec.whatwg.org/#cdatasection)` [node](https://dom.spec.whatwg.org/#concept-node) with its [data](https://dom.spec.whatwg.org/#concept-cd-data) set to data and [node document](https://dom.spec.whatwg.org/#concept-node-document) set to [this](https://webidl.spec.whatwg.org/#this). The method steps are to return a new `[Comment](https://dom.spec.whatwg.org/#comment)` [node](https://dom.spec.whatwg.org/#concept-node) whose [data](https://dom.spec.whatwg.org/#concept-cd-data) is data and [node document](https://dom.spec.whatwg.org/#concept-node-document) is [this](https://webidl.spec.whatwg.org/#this). No check is performed that data consists of characters that match the `[Char](https://www.w3.org/TR/xml/#NT-Char)` production or that it contains two adjacent hyphens or ends with a hyphen. The `createProcessingInstruction(target, data)` method steps are: 1. If target does not match the `[Name](https://www.w3.org/TR/xml/#NT-Name)` production, then [throw](https://webidl.spec.whatwg.org/#dfn-throw) an "`[InvalidCharacterError](https://webidl.spec.whatwg.org/#invalidcharactererror)`" `[DOMException](https://webidl.spec.whatwg.org/#idl-DOMException)`. 2. If data contains the string "`?>`", then [throw](https://webidl.spec.whatwg.org/#dfn-throw) an "`[InvalidCharacterError](https://webidl.spec.whatwg.org/#invalidcharactererror)`" `[DOMException](https://webidl.spec.whatwg.org/#idl-DOMException)`. 3. Return a new `[ProcessingInstruction](https://dom.spec.whatwg.org/#processinginstruction)` [node](https://dom.spec.whatwg.org/#concept-node), with [target](https://dom.spec.whatwg.org/#concept-pi-target) set to target, [data](https://dom.spec.whatwg.org/#concept-cd-data) set to data, and [node document](https://dom.spec.whatwg.org/#concept-node-document) set to [this](https://webidl.spec.whatwg.org/#this). No check is performed that target contains "`xml`" or "`:`", or that data contains characters that match the `[Char](https://www.w3.org/TR/xml/#NT-Char)` production. ___ [Document/importNode](https://developer.mozilla.org/en-US/docs/Web/API/Document/importNode "The Document object's importNode() method creates a copy of a Node or DocumentFragment from another document, to be inserted into the current document later.") In all current engines. Firefox1+Safari1+Chrome1+ ___ Opera9+Edge79+ ___ Edge (Legacy)12+IE9+ ___ Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+ clone = document. [importNode(node \[, deep = false\])](https://dom.spec.whatwg.org/#dom-document-importnode) Returns a copy of node. If deep is true, the copy also includes the node’s [descendants](https://dom.spec.whatwg.org/#concept-tree-descendant). If node is a [document](https://dom.spec.whatwg.org/#concept-document) or a [shadow root](https://dom.spec.whatwg.org/#concept-shadow-root), throws a "`[NotSupportedError](https://webidl.spec.whatwg.org/#notsupportederror)`" `[DOMException](https://webidl.spec.whatwg.org/#idl-DOMException)`. [Document/adoptNode](https://developer.mozilla.org/en-US/docs/Web/API/Document/adoptNode "Document.adoptNode() transfers a node from another document into the method's document. The adopted node and its subtree is removed from its original document (if any), and its ownerDocument is changed to the current document. The node can then be inserted into the current document.") In all current engines. Firefox1+Safari3+Chrome1+ ___ Opera12.1+Edge79+ ___ Edge (Legacy)12+IE9+ ___ Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+ node = document. `[adoptNode(node)](https://dom.spec.whatwg.org/#dom-document-adoptnode)` Moves node from another [document](https://dom.spec.whatwg.org/#concept-document) and returns it. If node is a [document](https://dom.spec.whatwg.org/#concept-document), throws a "`[NotSupportedError](https://webidl.spec.whatwg.org/#notsupportederror)`" `[DOMException](https://webidl.spec.whatwg.org/#idl-DOMException)` or, if node is a [shadow root](https://dom.spec.whatwg.org/#concept-shadow-root), throws a "`[HierarchyRequestError](https://webidl.spec.whatwg.org/#hierarchyrequesterror)`" `[DOMException](https://webidl.spec.whatwg.org/#idl-DOMException)`. The `importNode(node, deep)` method steps are: 1. If node is a [document](https://dom.spec.whatwg.org/#concept-document) or [shadow root](https://dom.spec.whatwg.org/#concept-shadow-root), then [throw](https://webidl.spec.whatwg.org/#dfn-throw) a "`[NotSupportedError](https://webidl.spec.whatwg.org/#notsupportederror)`" `[DOMException](https://webidl.spec.whatwg.org/#idl-DOMException)`. 2. Return a [clone](https://dom.spec.whatwg.org/#concept-node-clone) of node, with [this](https://webidl.spec.whatwg.org/#this) and the _clone children flag_ set if deep is true. [Specifications](https://dom.spec.whatwg.org/#other-applicable-specifications) may define adopting steps for all or some [nodes](https://dom.spec.whatwg.org/#concept-node). The algorithm is passed node and oldDocument, as indicated in the [adopt](https://dom.spec.whatwg.org/#concept-node-adopt) algorithm. To adopt a node into a document, run these steps: 1. Let oldDocument be node’s [node document](https://dom.spec.whatwg.org/#concept-node-document). 2. If node’s [parent](https://dom.spec.whatwg.org/#concept-tree-parent) is non-null, then [remove](https://dom.spec.whatwg.org/#concept-node-remove) node. 3. If document is not oldDocument, then: 1. For each inclusiveDescendant in node’s [shadow-including inclusive descendants](https://dom.spec.whatwg.org/#concept-shadow-including-inclusive-descendant): 1. Set inclusiveDescendant’s [node document](https://dom.spec.whatwg.org/#concept-node-document) to document. 2. If inclusiveDescendant is an [element](https://dom.spec.whatwg.org/#concept-element), then set the [node document](https://dom.spec.whatwg.org/#concept-node-document) of each [attribute](https://dom.spec.whatwg.org/#concept-attribute) in inclusiveDescendant’s [attribute list](https://dom.spec.whatwg.org/#concept-element-attribute) to document. 2. For each inclusiveDescendant in node’s [shadow-including inclusive descendants](https://dom.spec.whatwg.org/#concept-shadow-including-inclusive-descendant) that is [custom](https://dom.spec.whatwg.org/#concept-element-custom), [enqueue a custom element callback reaction](https://html.spec.whatwg.org/multipage/custom-elements.html#enqueue-a-custom-element-callback-reaction) with inclusiveDescendant, callback name "`adoptedCallback`", and an argument list containing oldDocument and document. 3. For each inclusiveDescendant in node’s [shadow-including inclusive descendants](https://dom.spec.whatwg.org/#concept-shadow-including-inclusive-descendant), in [shadow-including tree order](https://dom.spec.whatwg.org/#concept-shadow-including-tree-order), run the [adopting steps](https://dom.spec.whatwg.org/#concept-node-adopt-ext) with inclusiveDescendant and oldDocument. The `adoptNode(node)` method steps are: 1. If node is a [document](https://dom.spec.whatwg.org/#concept-document), then [throw](https://webidl.spec.whatwg.org/#dfn-throw) a "`[NotSupportedError](https://webidl.spec.whatwg.org/#notsupportederror)`" `[DOMException](https://webidl.spec.whatwg.org/#idl-DOMException)`. 2. If node is a [shadow root](https://dom.spec.whatwg.org/#concept-shadow-root), then [throw](https://webidl.spec.whatwg.org/#dfn-throw) a "`[HierarchyRequestError](https://webidl.spec.whatwg.org/#hierarchyrequesterror)`" `[DOMException](https://webidl.spec.whatwg.org/#idl-DOMException)`. 3. If node is a `[DocumentFragment](https://dom.spec.whatwg.org/#documentfragment)` [node](https://dom.spec.whatwg.org/#concept-node) whose [host](https://dom.spec.whatwg.org/#concept-documentfragment-host) is non-null, then return. 4. [Adopt](https://dom.spec.whatwg.org/#concept-node-adopt) node into [this](https://webidl.spec.whatwg.org/#this). 5. Return node. ___ [Document/createAttribute](https://developer.mozilla.org/en-US/docs/Web/API/Document/createAttribute "The Document.createAttribute() method creates a new attribute node, and returns it. The object created a node implementing the Attr interface. The DOM does not enforce what sort of attributes can be added to a particular element in this manner.") In all current engines. Firefox44+Safari1+Chrome1+ ___ Opera12.1+Edge79+ ___ Edge (Legacy)12+IE6+ ___ Firefox for Android44+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+ The `createAttribute(localName)` method steps are: 1. If localName does not match the `[Name](https://www.w3.org/TR/xml/#NT-Name)` production in XML, then [throw](https://webidl.spec.whatwg.org/#dfn-throw) an "`[InvalidCharacterError](https://webidl.spec.whatwg.org/#invalidcharactererror)`" `[DOMException](https://webidl.spec.whatwg.org/#idl-DOMException)`. 2. If [this](https://webidl.spec.whatwg.org/#this) is an [HTML document](https://dom.spec.whatwg.org/#html-document), then set localName to localName in [ASCII lowercase](https://infra.spec.whatwg.org/#ascii-lowercase). 3. Return a new [attribute](https://dom.spec.whatwg.org/#concept-attribute) whose [local name](https://dom.spec.whatwg.org/#concept-attribute-local-name) is localName and [node document](https://dom.spec.whatwg.org/#concept-node-document) is [this](https://webidl.spec.whatwg.org/#this). The `createAttributeNS(namespace, qualifiedName)` method steps are: 1. Let namespace, prefix, and localName be the result of passing namespace and qualifiedName to [validate and extract](https://dom.spec.whatwg.org/#validate-and-extract). 2. Return a new [attribute](https://dom.spec.whatwg.org/#concept-attribute) whose [namespace](https://dom.spec.whatwg.org/#concept-attribute-namespace) is namespace, [namespace prefix](https://dom.spec.whatwg.org/#concept-attribute-namespace-prefix) is prefix, [local name](https://dom.spec.whatwg.org/#concept-attribute-local-name) is localName, and [node document](https://dom.spec.whatwg.org/#concept-node-document) is [this](https://webidl.spec.whatwg.org/#this). ___ [Document/createEvent](https://developer.mozilla.org/en-US/docs/Web/API/Document/createEvent "Creates an event of the type specified. The returned object should be first initialized and can then be passed to EventTarget.dispatchEvent.") In all current engines. Firefox1+Safari1+Chrome1+ ___ Opera7+Edge79+ ___ Edge (Legacy)12+IE9+ ___ Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+ The `createEvent(interface)` method steps are: 1. Let constructor be null. 2. If interface is an [ASCII case-insensitive](https://infra.spec.whatwg.org/#ascii-case-insensitive) match for any of the strings in the first column in the following table, then set constructor to the interface in the second column on the same row as the matching string: String Interface Notes "`beforeunloadevent`" `[BeforeUnloadEvent](https://html.spec.whatwg.org/multipage/browsing-the-web.html#beforeunloadevent)` [\[HTML\]](https://dom.spec.whatwg.org/#biblio-html) "`compositionevent`" `[CompositionEvent](https://www.w3.org/TR/uievents/#compositionevent)` [\[UIEVENTS\]](https://dom.spec.whatwg.org/#biblio-uievents) "`customevent`" `[CustomEvent](https://dom.spec.whatwg.org/#customevent)` "`devicemotionevent`" `[DeviceMotionEvent](https://w3c.github.io/deviceorientation/spec-source-orientation.html#devicemotion)` [\[DEVICE-ORIENTATION\]](https://dom.spec.whatwg.org/#biblio-device-orientation) "`deviceorientationevent`" `[DeviceOrientationEvent](https://w3c.github.io/deviceorientation/spec-source-orientation.html#devicemotion)` "`dragevent`" `[DragEvent](https://html.spec.whatwg.org/multipage/dnd.html#dragevent)` [\[HTML\]](https://dom.spec.whatwg.org/#biblio-html) "`event`" `[Event](https://dom.spec.whatwg.org/#event)` "`events`" "`focusevent`" `[FocusEvent](https://www.w3.org/TR/uievents/#focusevent)` [\[UIEVENTS\]](https://dom.spec.whatwg.org/#biblio-uievents) "`hashchangeevent`" `[HashChangeEvent](https://html.spec.whatwg.org/multipage/browsing-the-web.html#hashchangeevent)` [\[HTML\]](https://dom.spec.whatwg.org/#biblio-html) "`htmlevents`" `[Event](https://dom.spec.whatwg.org/#event)` "`keyboardevent`" `[KeyboardEvent](https://www.w3.org/TR/uievents/#keyboardevent)` [\[UIEVENTS\]](https://dom.spec.whatwg.org/#biblio-uievents) "`messageevent`" `[MessageEvent](https://html.spec.whatwg.org/multipage/comms.html#messageevent)` [\[HTML\]](https://dom.spec.whatwg.org/#biblio-html) "`mouseevent`" `[MouseEvent](https://www.w3.org/TR/uievents/#mouseevent)` [\[UIEVENTS\]](https://dom.spec.whatwg.org/#biblio-uievents) "`mouseevents`" "`storageevent`" `[StorageEvent](https://html.spec.whatwg.org/multipage/webstorage.html#storageevent)` [\[HTML\]](https://dom.spec.whatwg.org/#biblio-html) "`svgevents`" `[Event](https://dom.spec.whatwg.org/#event)` "`textevent`" `[CompositionEvent](https://www.w3.org/TR/uievents/#compositionevent)` [\[UIEVENTS\]](https://dom.spec.whatwg.org/#biblio-uievents) "`touchevent`" `[TouchEvent](https://w3c.github.io/touch-events/#idl-def-touchevent)` [\[TOUCH-EVENTS\]](https://dom.spec.whatwg.org/#biblio-touch-events) "`uievent`" `[UIEvent](https://www.w3.org/TR/uievents/#uievent)` [\[UIEVENTS\]](https://dom.spec.whatwg.org/#biblio-uievents) "`uievents`" 3. If constructor is null, then [throw](https://webidl.spec.whatwg.org/#dfn-throw) a "`[NotSupportedError](https://webidl.spec.whatwg.org/#notsupportederror)`" `[DOMException](https://webidl.spec.whatwg.org/#idl-DOMException)`. 4. If the interface indicated by constructor is not exposed on the [relevant global object](https://html.spec.whatwg.org/multipage/webappapis.html#concept-relevant-global) of [this](https://webidl.spec.whatwg.org/#this), then [throw](https://webidl.spec.whatwg.org/#dfn-throw) a "`[NotSupportedError](https://webidl.spec.whatwg.org/#notsupportederror)`" `[DOMException](https://webidl.spec.whatwg.org/#idl-DOMException)`. Typically user agents disable support for touch events in some configurations, in which case this clause would be triggered for the interface `[TouchEvent](https://w3c.github.io/touch-events/#idl-def-touchevent)`. 5. Let event be the result of [creating an event](https://dom.spec.whatwg.org/#concept-event-create) given constructor. 6. Initialize event’s `[type](https://dom.spec.whatwg.org/#dom-event-type)` attribute to the empty string. 7. Initialize event’s `[timeStamp](https://dom.spec.whatwg.org/#dom-event-timestamp)` attribute to the result of calling [current high resolution time](https://w3c.github.io/hr-time/#dfn-current-high-resolution-time) with [this](https://webidl.spec.whatwg.org/#this)’s [relevant global object](https://html.spec.whatwg.org/multipage/webappapis.html#concept-relevant-global). 8. Initialize event’s `[isTrusted](https://dom.spec.whatwg.org/#dom-event-istrusted)` attribute to false. 9. Unset event’s [initialized flag](https://dom.spec.whatwg.org/#initialized-flag). 10. Return event. [Event](https://dom.spec.whatwg.org/#concept-event) constructors ought to be used instead. ___ [Document/createRange](https://developer.mozilla.org/en-US/docs/Web/API/Document/createRange "The Document.createRange() method returns a new Range object.") In all current engines. Firefox1+Safari1+Chrome1+ ___ Opera12.1+Edge79+ ___ Edge (Legacy)12+IE9+ ___ Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+ The `createRange()` method steps are to return a new [live range](https://dom.spec.whatwg.org/#concept-live-range) with ([this](https://webidl.spec.whatwg.org/#this), 0) as its [start](https://dom.spec.whatwg.org/#concept-range-start) an [end](https://dom.spec.whatwg.org/#concept-range-end). The `[Range()](https://dom.spec.whatwg.org/#dom-range-range)` constructor can be used instead. ___ [Document/createNodeIterator](https://developer.mozilla.org/en-US/docs/Web/API/Document/createNodeIterator "Returns a new NodeIterator object.") In all current engines. Firefox1+Safari3+Chrome1+ ___ Opera9+Edge79+ ___ Edge (Legacy)12+IE9+ ___ Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera MobileYes The `createNodeIterator(root, whatToShow, filter)` method steps are: 1. Let iterator be a new `[NodeIterator](https://dom.spec.whatwg.org/#nodeiterator)` object. 2. Set iterator’s [root](https://dom.spec.whatwg.org/#concept-traversal-root) and iterator’s [reference](https://dom.spec.whatwg.org/#nodeiterator-reference) to root. 3. Set iterator’s [pointer before reference](https://dom.spec.whatwg.org/#nodeiterator-pointer-before-reference) to true. 4. Set iterator’s [whatToShow](https://dom.spec.whatwg.org/#concept-traversal-whattoshow) to whatToShow. 5. Set iterator’s [filter](https://dom.spec.whatwg.org/#concept-traversal-filter) to filter. 6. Return iterator. [Document/createTreeWalker](https://developer.mozilla.org/en-US/docs/Web/API/Document/createTreeWalker "The Document.createTreeWalker() creator method returns a newly created TreeWalker object.") In all current engines. Firefox1+Safari3+Chrome1+ ___ Opera9+Edge79+ ___ Edge (Legacy)12+IE9+ ___ Firefox for Android4+iOS Safari3+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+ The `createTreeWalker(root, whatToShow, filter)` method steps are: 1. Let walker be a new `[TreeWalker](https://dom.spec.whatwg.org/#treewalker)` object. 2. Set walker’s [root](https://dom.spec.whatwg.org/#concept-traversal-root) and walker’s [current](https://dom.spec.whatwg.org/#treewalker-current) to root. 3. Set walker’s [whatToShow](https://dom.spec.whatwg.org/#concept-traversal-whattoshow) to whatToShow. 4. Set walker’s [filter](https://dom.spec.whatwg.org/#concept-traversal-filter) to filter. 5. Return walker. #### 4.5.1. Interface `[DOMImplementation](https://dom.spec.whatwg.org/#domimplementation)`[](https://dom.spec.whatwg.org/#interface-domimplementation) [DOMImplementation](https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation "The DOMImplementation interface represents an object providing methods which are not dependent on any particular document. Such an object is returned by the Document.implementation property.") In all current engines. Firefox1+Safari1+Chrome1+ ___ Opera12.1+Edge79+ ___ Edge (Legacy)12+IE6+ ___ Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+ User agents must create a `[DOMImplementation](https://dom.spec.whatwg.org/#domimplementation)` object whenever a [document](https://dom.spec.whatwg.org/#concept-document) is created and associate it with that [document](https://dom.spec.whatwg.org/#concept-document). \[[Exposed](https://webidl.spec.whatwg.org/#Exposed)\=Window\] interface `DOMImplementation` { \[[NewObject](https://webidl.spec.whatwg.org/#NewObject)\] [DocumentType](https://dom.spec.whatwg.org/#documenttype) [createDocumentType](https://dom.spec.whatwg.org/#dom-domimplementation-createdocumenttype)([DOMString](https://webidl.spec.whatwg.org/#idl-DOMString) `qualifiedName`[](https://dom.spec.whatwg.org/#dom-domimplementation-createdocumenttype-qualifiedname-publicid-systemid-qualifiedname), [DOMString](https://webidl.spec.whatwg.org/#idl-DOMString) `publicId`[](https://dom.spec.whatwg.org/#dom-domimplementation-createdocumenttype-qualifiedname-publicid-systemid-publicid), [DOMString](https://webidl.spec.whatwg.org/#idl-DOMString) `systemId`[](https://dom.spec.whatwg.org/#dom-domimplementation-createdocumenttype-qualifiedname-publicid-systemid-systemid)); \[[NewObject](https://webidl.spec.whatwg.org/#NewObject)\] [XMLDocument](https://dom.spec.whatwg.org/#xmldocument) [createDocument](https://dom.spec.whatwg.org/#dom-domimplementation-createdocument)([DOMString](https://webidl.spec.whatwg.org/#idl-DOMString)? `namespace`[](https://dom.spec.whatwg.org/#dom-domimplementation-createdocument-namespace-qualifiedname-doctype-namespace), \[[LegacyNullToEmptyString](https://webidl.spec.whatwg.org/#LegacyNullToEmptyString)\] [DOMString](https://webidl.spec.whatwg.org/#idl-DOMString) `qualifiedName`[](https://dom.spec.whatwg.org/#dom-domimplementation-createdocument-namespace-qualifiedname-doctype-qualifiedname), optional [DocumentType](https://dom.spec.whatwg.org/#documenttype)? `doctype`[](https://dom.spec.whatwg.org/#dom-domimplementation-createdocument-namespace-qualifiedname-doctype-doctype) = null); \[[NewObject](https://webidl.spec.whatwg.org/#NewObject)\] [Document](https://dom.spec.whatwg.org/#document) [createHTMLDocument](https://dom.spec.whatwg.org/#dom-domimplementation-createhtmldocument)(optional [DOMString](https://webidl.spec.whatwg.org/#idl-DOMString) `title`[](https://dom.spec.whatwg.org/#dom-domimplementation-createhtmldocument-title-title)); [boolean](https://webidl.spec.whatwg.org/#idl-boolean) [hasFeature](https://dom.spec.whatwg.org/#dom-domimplementation-hasfeature)(); // useless; always returns true }; [DOMImplementation/createDocumentType](https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/createDocumentType "The DOMImplementation.createDocumentType() method returns a DocumentType object which can either be used with DOMImplementation.createDocument upon document creation or can be put into the document via methods like Node.insertBefore() or Node.replaceChild().") In all current engines. Firefox1+Safari1+Chrome1+ ___ Opera12.1+Edge79+ ___ Edge (Legacy)12+IE9+ ___ Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+ ``doctype = document. `[implementation](https://dom.spec.whatwg.org/#dom-document-implementation)`. `[createDocumentType(qualifiedName, publicId, systemId)](https://dom.spec.whatwg.org/#dom-domimplementation-createdocumenttype)` `` Returns a [doctype](https://dom.spec.whatwg.org/#concept-doctype), with the given qualifiedName, publicId, and systemId. If qualifiedName does not match the `[Name](https://www.w3.org/TR/xml/#NT-Name)` production, an "`[InvalidCharacterError](https://webidl.spec.whatwg.org/#invalidcharactererror)`" `[DOMException](https://webidl.spec.whatwg.org/#idl-DOMException)` is thrown, and if it does not match the `[QName](https://www.w3.org/TR/xml-names/#NT-QName)` production, a "`[NamespaceError](https://webidl.spec.whatwg.org/#namespaceerror)`" `[DOMException](https://webidl.spec.whatwg.org/#idl-DOMException)` is thrown. [DOMImplementation/createDocument](https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/createDocument "The DOMImplementation.createDocument() method creates and returns an XMLDocument.") In all current engines. Firefox1+Safari1+Chrome1+ ___ Opera12.1+Edge79+ ___ Edge (Legacy)12+IE9+ ___ Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+ ``doc = document. `[implementation](https://dom.spec.whatwg.org/#dom-document-implementation)`. [createDocument(namespace, qualifiedName [, doctype = null])](https://dom.spec.whatwg.org/#dom-domimplementation-createdocument)`` Returns an `[XMLDocument](https://dom.spec.whatwg.org/#xmldocument)`, with a [document element](https://dom.spec.whatwg.org/#document-element) whose [local name](https://dom.spec.whatwg.org/#concept-element-local-name) is qualifiedName and whose [namespace](https://dom.spec.whatwg.org/#concept-element-namespace) is namespace (unless qualifiedName is the empty string), and with doctype, if it is given, as its [doctype](https://dom.spec.whatwg.org/#concept-doctype). This method throws the same exceptions as the `[createElementNS()](https://dom.spec.whatwg.org/#dom-document-createelementns)` method, when invoked with namespace and qualifiedName. [DOMImplementation/createHTMLDocument](https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/createHTMLDocument "The DOMImplementation.createHTMLDocument() method creates a new HTML Document.") In all current engines. Firefox4+Safari1+Chrome1+ ___ Opera12.1+Edge79+ ___ Edge (Legacy)12+IE9+ ___ Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+ ``doc = document. `[implementation](https://dom.spec.whatwg.org/#dom-document-implementation)`. [createHTMLDocument([title])](https://dom.spec.whatwg.org/#dom-domimplementation-createhtmldocument)`` Returns a [document](https://dom.spec.whatwg.org/#concept-document), with a basic [tree](https://dom.spec.whatwg.org/#concept-tree) already constructed including a `[title](https://html.spec.whatwg.org/multipage/semantics.html#the-title-element)` element, unless the title argument is omitted. The `createDocumentType(qualifiedName, publicId, systemId)` method steps are: 1. [Validate](https://dom.spec.whatwg.org/#validate) qualifiedName. 2. Return a new [doctype](https://dom.spec.whatwg.org/#concept-doctype), with qualifiedName as its [name](https://dom.spec.whatwg.org/#concept-doctype-name), publicId as its [public ID](https://dom.spec.whatwg.org/#concept-doctype-publicid), and systemId as its [system ID](https://dom.spec.whatwg.org/#concept-doctype-systemid), and with its [node document](https://dom.spec.whatwg.org/#concept-node-document) set to the associated [document](https://dom.spec.whatwg.org/#concept-document) of [this](https://webidl.spec.whatwg.org/#this). No check is performed that publicId code points match the `[PubidChar](https://www.w3.org/TR/xml/#NT-PubidChar)` production or that systemId does not contain both a '`"`' and a "`'`". The `createDocument(namespace, qualifiedName, doctype)` method steps are: 1. Let document be a new `[XMLDocument](https://dom.spec.whatwg.org/#xmldocument)`. 2. Let element be null. 3. If qualifiedName is not the empty string, then set element to the result of running the [internal `createElementNS` steps](https://dom.spec.whatwg.org/#internal-createelementns-steps), given document, namespace, qualifiedName, and an empty dictionary. 4. If doctype is non-null, [append](https://dom.spec.whatwg.org/#concept-node-append) doctype to document. 5. If element is non-null, [append](https://dom.spec.whatwg.org/#concept-node-append) element to document. 6. document’s [origin](https://dom.spec.whatwg.org/#concept-document-origin) is [this](https://webidl.spec.whatwg.org/#this)’s associated [document](https://dom.spec.whatwg.org/#concept-document)’s [origin](https://dom.spec.whatwg.org/#concept-document-origin). 7. document’s [content type](https://dom.spec.whatwg.org/#concept-document-content-type) is determined by namespace: [HTML namespace](https://infra.spec.whatwg.org/#html-namespace) `application/xhtml+xml` [SVG namespace](https://infra.spec.whatwg.org/#svg-namespace) `image/svg+xml` Any other namespace `application/xml` 8. Return document. The `createHTMLDocument(title)` method steps are: 1. Let doc be a new [document](https://dom.spec.whatwg.org/#concept-document) that is an [HTML document](https://dom.spec.whatwg.org/#html-document). 2. Set doc’s [content type](https://dom.spec.whatwg.org/#concept-document-content-type) to "`text/html`". 3. [Append](https://dom.spec.whatwg.org/#concept-node-append) a new [doctype](https://dom.spec.whatwg.org/#concept-doctype), with "`html`" as its [name](https://dom.spec.whatwg.org/#concept-doctype-name) and with its [node document](https://dom.spec.whatwg.org/#concept-node-document) set to doc, to doc. 4. [Append](https://dom.spec.whatwg.org/#concept-node-append) the result of [creating an element](https://dom.spec.whatwg.org/#concept-create-element) given doc, `[html](https://html.spec.whatwg.org/multipage/semantics.html#the-html-element)`, and the [HTML namespace](https://infra.spec.whatwg.org/#html-namespace), to doc. 5. [Append](https://dom.spec.whatwg.org/#concept-node-append) the result of [creating an element](https://dom.spec.whatwg.org/#concept-create-element) given doc, `[head](https://html.spec.whatwg.org/multipage/semantics.html#the-head-element)`, and the [HTML namespace](https://infra.spec.whatwg.org/#html-namespace), to the `[html](https://html.spec.whatwg.org/multipage/semantics.html#the-html-element)` element created earlier. 6. If title is given: 1. [Append](https://dom.spec.whatwg.org/#concept-node-append) the result of [creating an element](https://dom.spec.whatwg.org/#concept-create-element) given doc, `[title](https://html.spec.whatwg.org/multipage/semantics.html#the-title-element)`, and the [HTML namespace](https://infra.spec.whatwg.org/#html-namespace), to the `[head](https://html.spec.whatwg.org/multipage/semantics.html#the-head-element)` element created earlier. 2. [Append](https://dom.spec.whatwg.org/#concept-node-append) a new `[Text](https://dom.spec.whatwg.org/#text)` [node](https://dom.spec.whatwg.org/#concept-node), with its [data](https://dom.spec.whatwg.org/#concept-cd-data) set to title (which could be the empty string) and its [node document](https://dom.spec.whatwg.org/#concept-node-document) set to doc, to the `[title](https://html.spec.whatwg.org/multipage/semantics.html#the-title-element)` element created earlier. 7. [Append](https://dom.spec.whatwg.org/#concept-node-append) the result of [creating an element](https://dom.spec.whatwg.org/#concept-create-element) given doc, `[body](https://html.spec.whatwg.org/multipage/sections.html#the-body-element)`, and the [HTML namespace](https://infra.spec.whatwg.org/#html-namespace), to the `[html](https://html.spec.whatwg.org/multipage/semantics.html#the-html-element)` element created earlier. 8. doc’s [origin](https://dom.spec.whatwg.org/#concept-document-origin) is [this](https://webidl.spec.whatwg.org/#this)’s associated [document](https://dom.spec.whatwg.org/#concept-document)’s [origin](https://dom.spec.whatwg.org/#concept-document-origin). 9. Return doc. The `hasFeature()` method steps are to return true. `[hasFeature()](https://dom.spec.whatwg.org/#dom-domimplementation-hasfeature)` originally would report whether the user agent claimed to support a given DOM feature, but experience proved it was not nearly as reliable or granular as simply checking whether the desired objects, attributes, or methods existed. As such, it is no longer to be used, but continues to exist (and simply returns true) so that old pages don’t stop working. ### 4.6. Interface `[DocumentType](https://dom.spec.whatwg.org/#documenttype)`[](https://dom.spec.whatwg.org/#interface-documenttype) [DocumentType](https://developer.mozilla.org/en-US/docs/Web/API/DocumentType "The DocumentType interface represents a Node containing a doctype.") In all current engines. Firefox1+Safari3+Chrome1+ ___ Opera12.1+Edge79+ ___ Edge (Legacy)12+IE9+ ___ Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+ \[[Exposed](https://webidl.spec.whatwg.org/#Exposed)\=Window\] interface `DocumentType` : [Node](https://dom.spec.whatwg.org/#node) { readonly attribute [DOMString](https://webidl.spec.whatwg.org/#idl-DOMString) [name](https://dom.spec.whatwg.org/#dom-documenttype-name); readonly attribute [DOMString](https://webidl.spec.whatwg.org/#idl-DOMString) [publicId](https://dom.spec.whatwg.org/#dom-documenttype-publicid); readonly attribute [DOMString](https://webidl.spec.whatwg.org/#idl-DOMString) [systemId](https://dom.spec.whatwg.org/#dom-documenttype-systemid); }; `[DocumentType](https://dom.spec.whatwg.org/#documenttype)` [nodes](https://dom.spec.whatwg.org/#concept-node) are simply known as doctypes. [Doctypes](https://dom.spec.whatwg.org/#concept-doctype) have an associated name, public ID, and system ID. When a [doctype](https://dom.spec.whatwg.org/#concept-doctype) is created, its [name](https://dom.spec.whatwg.org/#concept-doctype-name) is always given. Unless explicitly given when a [doctype](https://dom.spec.whatwg.org/#concept-doctype) is created, its [public ID](https://dom.spec.whatwg.org/#concept-doctype-publicid) and [system ID](https://dom.spec.whatwg.org/#concept-doctype-systemid) are the empty string. The `name` getter steps are to return [this](https://webidl.spec.whatwg.org/#this)’s [name](https://dom.spec.whatwg.org/#concept-doctype-name). The `publicId` getter steps are to return [this](https://webidl.spec.whatwg.org/#this)’s [public ID](https://dom.spec.whatwg.org/#concept-doctype-publicid). The `systemId` getter steps are to return [this](https://webidl.spec.whatwg.org/#this)’s [system ID](https://dom.spec.whatwg.org/#concept-doctype-systemid). ### 4.7. Interface `[DocumentFragment](https://dom.spec.whatwg.org/#documentfragment)`[](https://dom.spec.whatwg.org/#interface-documentfragment) [DocumentFragment](https://developer.mozilla.org/en-US/docs/Web/API/DocumentFragment "The DocumentFragment interface represents a minimal document object that has no parent.") In all current engines. Firefox1+Safari3+Chrome1+ ___ Opera8+Edge79+ ___ Edge (Legacy)12+IE9+ ___ Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+ \[[Exposed](https://webidl.spec.whatwg.org/#Exposed)\=Window\] interface `DocumentFragment` : [Node](https://dom.spec.whatwg.org/#node) { [constructor](https://dom.spec.whatwg.org/#dom-documentfragment-documentfragment)(); }; A `[DocumentFragment](https://dom.spec.whatwg.org/#documentfragment)` [node](https://dom.spec.whatwg.org/#concept-node) has an associated host (null or an [element](https://dom.spec.whatwg.org/#concept-element) in a different [node tree](https://dom.spec.whatwg.org/#concept-node-tree)). It is null unless otherwise stated. An object A is a host-including inclusive ancestor of an object B, if either A is an [inclusive ancestor](https://dom.spec.whatwg.org/#concept-tree-inclusive-ancestor) of B, or if B’s [root](https://dom.spec.whatwg.org/#concept-tree-root) has a non-null [host](https://dom.spec.whatwg.org/#concept-documentfragment-host) and A is a [host-including inclusive ancestor](https://dom.spec.whatwg.org/#concept-tree-host-including-inclusive-ancestor) of B’s [root](https://dom.spec.whatwg.org/#concept-tree-root)’s [host](https://dom.spec.whatwg.org/#concept-documentfragment-host). The `[DocumentFragment](https://dom.spec.whatwg.org/#documentfragment)` [node](https://dom.spec.whatwg.org/#concept-node)’s [host](https://dom.spec.whatwg.org/#concept-documentfragment-host) concept is useful for HTML’s `[template](https://html.spec.whatwg.org/multipage/scripting.html#the-template-element)` element and for [shadow roots](https://dom.spec.whatwg.org/#concept-shadow-root), and impacts the [pre-insert](https://dom.spec.whatwg.org/#concept-node-pre-insert) and [replace](https://dom.spec.whatwg.org/#concept-node-replace) algorithms. [DocumentFragment/DocumentFragment](https://developer.mozilla.org/en-US/docs/Web/API/DocumentFragment/DocumentFragment "The DocumentFragment() constructor returns a new, empty DocumentFragment object.") In all current engines. Firefox24+Safari8+Chrome29+ ___ Opera16+Edge79+ ___ Edge (Legacy)17+IENone ___ Firefox for Android24+iOS Safari8+Chrome for Android29+Android WebView37+Samsung Internet2.0+Opera Mobile16+ ``tree = new `[DocumentFragment()](https://dom.spec.whatwg.org/#dom-documentfragment-documentfragment)` `` Returns a new `[DocumentFragment](https://dom.spec.whatwg.org/#documentfragment)` [node](https://dom.spec.whatwg.org/#concept-node). The `new DocumentFragment()` constructor steps are to set [this](https://webidl.spec.whatwg.org/#this)’s [node document](https://dom.spec.whatwg.org/#concept-node-document) to [current global object](https://html.spec.whatwg.org/multipage/webappapis.html#current-global-object)’s [associated `Document`](https://html.spec.whatwg.org/multipage/window-object.html#concept-document-window). ### 4.8. Interface `[ShadowRoot](https://dom.spec.whatwg.org/#shadowroot)`[](https://dom.spec.whatwg.org/#interface-shadowroot) [ShadowRoot](https://developer.mozilla.org/en-US/docs/Web/API/ShadowRoot "The ShadowRoot interface of the Shadow DOM API is the root node of a DOM subtree that is rendered separately from a document's main DOM tree.") In all current engines. Firefox63+Safari10.1+Chrome53+ ___ Opera40+Edge79+ ___ Edge (Legacy)NoneIENone ___ Firefox for Android63+iOS Safari10.3+Chrome for Android53+Android WebView53+Samsung Internet6.0+Opera Mobile41+ \[[Exposed](https://webidl.spec.whatwg.org/#Exposed)\=Window\] interface `ShadowRoot` : [DocumentFragment](https://dom.spec.whatwg.org/#documentfragment) { readonly attribute [ShadowRootMode](https://dom.spec.whatwg.org/#enumdef-shadowrootmode) [mode](https://dom.spec.whatwg.org/#dom-shadowroot-mode); readonly attribute [boolean](https://webidl.spec.whatwg.org/#idl-boolean) [delegatesFocus](https://dom.spec.whatwg.org/#dom-shadowroot-delegatesfocus); readonly attribute [SlotAssignmentMode](https://dom.spec.whatwg.org/#enumdef-slotassignmentmode) [slotAssignment](https://dom.spec.whatwg.org/#dom-shadowroot-slotassignment); readonly attribute [Element](https://dom.spec.whatwg.org/#element) [host](https://dom.spec.whatwg.org/#dom-shadowroot-host); attribute [EventHandler](https://html.spec.whatwg.org/multipage/webappapis.html#eventhandler) [onslotchange](https://dom.spec.whatwg.org/#dom-shadowroot-onslotchange); }; enum `ShadowRootMode` { `"open"`[](https://dom.spec.whatwg.org/#dom-shadowrootmode-open), `"closed"`[](https://dom.spec.whatwg.org/#dom-shadowrootmode-closed) }; enum `SlotAssignmentMode` { `"manual"`[](https://dom.spec.whatwg.org/#dom-slotassignmentmode-manual), `"named"`[](https://dom.spec.whatwg.org/#dom-slotassignmentmode-named) }; `[ShadowRoot](https://dom.spec.whatwg.org/#shadowroot)` [nodes](https://dom.spec.whatwg.org/#concept-node) are simply known as shadow roots. [Shadow roots](https://dom.spec.whatwg.org/#concept-shadow-root) have an associated mode ("`open`" or "`closed`"). [ShadowRoot/delegatesFocus](https://developer.mozilla.org/en-US/docs/Web/API/ShadowRoot/delegatesFocus "The delegatesFocus read-only property of the ShadowRoot interface returns true if the shadow root delegates focus, and false otherwise.") In all current engines. Firefox94+Safari15+Chrome53+ ___ Opera40+Edge79+ ___ Edge (Legacy)NoneIENone ___ Firefox for Android94+iOS Safari15+Chrome for Android53+Android WebView53+Samsung Internet6.0+Opera Mobile41+ [Shadow roots](https://dom.spec.whatwg.org/#concept-shadow-root) have an associated delegates focus. It is initially set to false. [Shadow roots](https://dom.spec.whatwg.org/#concept-shadow-root) have an associated available to element internals. It is initially set to false. [Shadow roots](https://dom.spec.whatwg.org/#concept-shadow-root)’s associated [host](https://dom.spec.whatwg.org/#concept-documentfragment-host) is never null. [Shadow roots](https://dom.spec.whatwg.org/#concept-shadow-root) have an associated slot assignment ("`manual`" or "`named`"). A [shadow root](https://dom.spec.whatwg.org/#concept-shadow-root)’s [get the parent](https://dom.spec.whatwg.org/#get-the-parent) algorithm, given an event, returns null if event’s [composed flag](https://dom.spec.whatwg.org/#composed-flag) is unset and [shadow root](https://dom.spec.whatwg.org/#concept-shadow-root) is the [root](https://dom.spec.whatwg.org/#concept-tree-root) of event’s [path](https://dom.spec.whatwg.org/#event-path)’s first struct’s [invocation target](https://dom.spec.whatwg.org/#event-path-invocation-target); otherwise [shadow root](https://dom.spec.whatwg.org/#concept-shadow-root)’s [host](https://dom.spec.whatwg.org/#concept-documentfragment-host). [ShadowRoot/mode](https://developer.mozilla.org/en-US/docs/Web/API/ShadowRoot/mode "The mode read-only property of the ShadowRoot specifies its mode — either open or closed. This defines whether or not the shadow root's internal features are accessible from JavaScript.") In all current engines. Firefox63+Safari10.1+Chrome53+ ___ Opera40+Edge79+ ___ Edge (Legacy)NoneIENone ___ Firefox for Android63+iOS Safari10.3+Chrome for Android53+Android WebView53+Samsung Internet6.0+Opera Mobile41+ The `mode` getter steps are to return [this](https://webidl.spec.whatwg.org/#this)’s [mode](https://dom.spec.whatwg.org/#shadowroot-mode). The `delegatesFocus` getter steps are to return [this](https://webidl.spec.whatwg.org/#this)’s [delegates focus](https://dom.spec.whatwg.org/#shadowroot-delegates-focus). The `slotAssignment` getter steps are to return [this](https://webidl.spec.whatwg.org/#this)’s [slot assignment](https://dom.spec.whatwg.org/#shadowroot-slot-assignment). [ShadowRoot/host](https://developer.mozilla.org/en-US/docs/Web/API/ShadowRoot/host "The host read-only property of the ShadowRoot returns a reference to the DOM element the ShadowRoot is attached to.") In all current engines. Firefox63+Safari10.1+Chrome53+ ___ Opera40+Edge79+ ___ Edge (Legacy)NoneIENone ___ Firefox for Android63+iOS Safari10.3+Chrome for Android53+Android WebView53+Samsung Internet6.0+Opera Mobile41+ The `host` getter steps are to return [this](https://webidl.spec.whatwg.org/#this)’s [host](https://dom.spec.whatwg.org/#concept-documentfragment-host). The `onslotchange` attribute is an [event handler IDL attribute](https://html.spec.whatwg.org/multipage/webappapis.html#event-handler-idl-attributes) for the `onslotchange`[](https://dom.spec.whatwg.org/#shadowroot-onslotchange) [event handler](https://html.spec.whatwg.org/multipage/webappapis.html#event-handlers), whose [event handler event type](https://html.spec.whatwg.org/multipage/webappapis.html#event-handler-event-type) is `[slotchange](https://html.spec.whatwg.org/multipage/indices.html#event-slotchange)`. ___ In shadow-including tree order is [shadow-including preorder, depth-first traversal](https://dom.spec.whatwg.org/#shadow-including-preorder-depth-first-traversal) of a [node tree](https://dom.spec.whatwg.org/#concept-node-tree). Shadow-including preorder, depth-first traversal of a [node tree](https://dom.spec.whatwg.org/#concept-node-tree) tree is preorder, depth-first traversal of tree, with for each [shadow host](https://dom.spec.whatwg.org/#element-shadow-host) encountered in tree, [shadow-including preorder, depth-first traversal](https://dom.spec.whatwg.org/#shadow-including-preorder-depth-first-traversal) of that [element](https://dom.spec.whatwg.org/#concept-element)’s [shadow root](https://dom.spec.whatwg.org/#concept-element-shadow-root)’s [node tree](https://dom.spec.whatwg.org/#concept-node-tree) just after it is encountered. The shadow-including root of an object is its [root](https://dom.spec.whatwg.org/#concept-tree-root)’s [host](https://dom.spec.whatwg.org/#concept-documentfragment-host)’s [shadow-including root](https://dom.spec.whatwg.org/#concept-shadow-including-root), if the object’s [root](https://dom.spec.whatwg.org/#concept-tree-root) is a [shadow root](https://dom.spec.whatwg.org/#concept-shadow-root); otherwise its [root](https://dom.spec.whatwg.org/#concept-tree-root). An object A is a shadow-including descendant of an object B, if A is a [descendant](https://dom.spec.whatwg.org/#concept-tree-descendant) of B, or A’s [root](https://dom.spec.whatwg.org/#concept-tree-root) is a [shadow root](https://dom.spec.whatwg.org/#concept-shadow-root) and A’s [root](https://dom.spec.whatwg.org/#concept-tree-root)’s [host](https://dom.spec.whatwg.org/#concept-documentfragment-host) is a [shadow-including inclusive descendant](https://dom.spec.whatwg.org/#concept-shadow-including-inclusive-descendant) of B. A shadow-including inclusive descendant is an object or one of its [shadow-including descendants](https://dom.spec.whatwg.org/#concept-shadow-including-descendant). An object A is a shadow-including ancestor of an object B, if and only if B is a [shadow-including descendant](https://dom.spec.whatwg.org/#concept-shadow-including-descendant) of A. A shadow-including inclusive ancestor is an object or one of its [shadow-including ancestors](https://dom.spec.whatwg.org/#concept-shadow-including-ancestor). A [node](https://dom.spec.whatwg.org/#concept-node) A is closed-shadow-hidden from a [node](https://dom.spec.whatwg.org/#concept-node) B if all of the following conditions are true: - A’s [root](https://dom.spec.whatwg.org/#concept-tree-root) is a [shadow root](https://dom.spec.whatwg.org/#concept-shadow-root). - A’s [root](https://dom.spec.whatwg.org/#concept-tree-root) is not a [shadow-including inclusive ancestor](https://dom.spec.whatwg.org/#concept-shadow-including-inclusive-ancestor) of B. - A’s [root](https://dom.spec.whatwg.org/#concept-tree-root) is a [shadow root](https://dom.spec.whatwg.org/#concept-shadow-root) whose [mode](https://dom.spec.whatwg.org/#shadowroot-mode) is "`closed`" or A’s [root](https://dom.spec.whatwg.org/#concept-tree-root)’s [host](https://dom.spec.whatwg.org/#concept-documentfragment-host) is [closed-shadow-hidden](https://dom.spec.whatwg.org/#concept-closed-shadow-hidden) from B. To retarget an object A against an object B, repeat these steps until they return an object: 1. If one of the following is true - A is not a [node](https://dom.spec.whatwg.org/#concept-node) - A’s [root](https://dom.spec.whatwg.org/#concept-tree-root) is not a [shadow root](https://dom.spec.whatwg.org/#concept-shadow-root) - B is a [node](https://dom.spec.whatwg.org/#concept-node) and A’s [root](https://dom.spec.whatwg.org/#concept-tree-root) is a [shadow-including inclusive ancestor](https://dom.spec.whatwg.org/#concept-shadow-including-inclusive-ancestor) of B then return A. 2. Set A to A’s [root](https://dom.spec.whatwg.org/#concept-tree-root)’s [host](https://dom.spec.whatwg.org/#concept-documentfragment-host). The [retargeting](https://dom.spec.whatwg.org/#retarget) algorithm is used by [event dispatch](https://dom.spec.whatwg.org/#concept-event-dispatch) as well as other specifications, such as Fullscreen. [\[FULLSCREEN\]](https://dom.spec.whatwg.org/#biblio-fullscreen) ### 4.9. Interface `[Element](https://dom.spec.whatwg.org/#element)`[](https://dom.spec.whatwg.org/#interface-element) [Element](https://developer.mozilla.org/en-US/docs/Web/API/Element "Element is the most general base class from which all element objects (i.e. objects that represent elements) in a Document inherit. It only has methods and properties common to all kinds of elements. More specific classes inherit from Element.") In all current engines. Firefox1+Safari1+Chrome1+ ___ Opera8+Edge79+ ___ Edge (Legacy)12+IE4+ ___ Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+ \[[Exposed](https://webidl.spec.whatwg.org/#Exposed)\=Window\] interface `Element` : [Node](https://dom.spec.whatwg.org/#node) { readonly attribute [DOMString](https://webidl.spec.whatwg.org/#idl-DOMString)? [namespaceURI](https://dom.spec.whatwg.org/#dom-element-namespaceuri); readonly attribute [DOMString](https://webidl.spec.whatwg.org/#idl-DOMString)? [prefix](https://dom.spec.whatwg.org/#dom-element-prefix); readonly attribute [DOMString](https://webidl.spec.whatwg.org/#idl-DOMString) [localName](https://dom.spec.whatwg.org/#dom-element-localname); readonly attribute [DOMString](https://webidl.spec.whatwg.org/#idl-DOMString) [tagName](https://dom.spec.whatwg.org/#dom-element-tagname); \[[CEReactions](https://html.spec.whatwg.org/multipage/custom-elements.html#cereactions)\] attribute [DOMString](https://webidl.spec.whatwg.org/#idl-DOMString) [id](https://dom.spec.whatwg.org/#dom-element-id); \[[CEReactions](https://html.spec.whatwg.org/multipage/custom-elements.html#cereactions)\] attribute [DOMString](https://webidl.spec.whatwg.org/#idl-DOMString) [className](https://dom.spec.whatwg.org/#dom-element-classname); \[[SameObject](https://webidl.spec.whatwg.org/#SameObject), [PutForwards](https://webidl.spec.whatwg.org/#PutForwards)\=[value](https://dom.spec.whatwg.org/#dom-domtokenlist-value)\] readonly attribute [DOMTokenList](https://dom.spec.whatwg.org/#domtokenlist) [classList](https://dom.spec.whatwg.org/#dom-element-classlist); \[[CEReactions](https://html.spec.whatwg.org/multipage/custom-elements.html#cereactions), [Unscopable](https://webidl.spec.whatwg.org/#Unscopable)\] attribute [DOMString](https://webidl.spec.whatwg.org/#idl-DOMString) [slot](https://dom.spec.whatwg.org/#dom-element-slot); [boolean](https://webidl.spec.whatwg.org/#idl-boolean) [hasAttributes](https://dom.spec.whatwg.org/#dom-element-hasattributes)(); \[[SameObject](https://webidl.spec.whatwg.org/#SameObject)\] readonly attribute [NamedNodeMap](https://dom.spec.whatwg.org/#namednodemap) [attributes](https://dom.spec.whatwg.org/#dom-element-attributes); [sequence](https://webidl.spec.whatwg.org/#idl-sequence)<[DOMString](https://webidl.spec.whatwg.org/#idl-DOMString)\> [getAttributeNames](https://dom.spec.whatwg.org/#dom-element-getattributenames)(); [DOMString](https://webidl.spec.whatwg.org/#idl-DOMString)? [getAttribute](https://dom.spec.whatwg.org/#dom-element-getattribute)([DOMString](https://webidl.spec.whatwg.org/#idl-DOMString) `qualifiedName`[](https://dom.spec.whatwg.org/#dom-element-getattribute-qualifiedname-qualifiedname)); [DOMString](https://webidl.spec.whatwg.org/#idl-DOMString)? [getAttributeNS](https://dom.spec.whatwg.org/#dom-element-getattributens)([DOMString](https://webidl.spec.whatwg.org/#idl-DOMString)? `namespace`[](https://dom.spec.whatwg.org/#dom-element-getattributens-namespace-localname-namespace), [DOMString](https://webidl.spec.whatwg.org/#idl-DOMString) `localName`[](https://dom.spec.whatwg.org/#dom-element-getattributens-namespace-localname-localname)); \[[CEReactions](https://html.spec.whatwg.org/multipage/custom-elements.html#cereactions)\] [undefined](https://webidl.spec.whatwg.org/#idl-undefined) [setAttribute](https://dom.spec.whatwg.org/#dom-element-setattribute)([DOMString](https://webidl.spec.whatwg.org/#idl-DOMString) `qualifiedName`[](https://dom.spec.whatwg.org/#dom-element-setattribute-qualifiedname-value-qualifiedname), [DOMString](https://webidl.spec.whatwg.org/#idl-DOMString) `value`[](https://dom.spec.whatwg.org/#dom-element-setattribute-qualifiedname-value-value)); \[[CEReactions](https://html.spec.whatwg.org/multipage/custom-elements.html#cereactions)\] [undefined](https://webidl.spec.whatwg.org/#idl-undefined) [setAttributeNS](https://dom.spec.whatwg.org/#dom-element-setattributens)([DOMString](https://webidl.spec.whatwg.org/#idl-DOMString)? `namespace`[](https://dom.spec.whatwg.org/#dom-element-setattributens-namespace-qualifiedname-value-namespace), [DOMString](https://webidl.spec.whatwg.org/#idl-DOMString) `qualifiedName`[](https://dom.spec.whatwg.org/#dom-element-setattributens-namespace-qualifiedname-value-qualifiedname), [DOMString](https://webidl.spec.whatwg.org/#idl-DOMString) `value`[](https://dom.spec.whatwg.org/#dom-element-setattributens-namespace-qualifiedname-value-value)); \[[CEReactions](https://html.spec.whatwg.org/multipage/custom-elements.html#cereactions)\] [undefined](https://webidl.spec.whatwg.org/#idl-undefined) [removeAttribute](https://dom.spec.whatwg.org/#dom-element-removeattribute)([DOMString](https://webidl.spec.whatwg.org/#idl-DOMString) `qualifiedName`[](https://dom.spec.whatwg.org/#dom-element-removeattribute-qualifiedname-qualifiedname)); \[[CEReactions](https://html.spec.whatwg.org/multipage/custom-elements.html#cereactions)\] [undefined](https://webidl.spec.whatwg.org/#idl-undefined) [removeAttributeNS](https://dom.spec.whatwg.org/#dom-element-removeattributens)([DOMString](https://webidl.spec.whatwg.org/#idl-DOMString)? `namespace`[](https://dom.spec.whatwg.org/#dom-element-removeattributens-namespace-localname-namespace), [DOMString](https://webidl.spec.whatwg.org/#idl-DOMString) `localName`[](https://dom.spec.whatwg.org/#dom-element-removeattributens-namespace-localname-localname)); \[[CEReactions](https://html.spec.whatwg.org/multipage/custom-elements.html#cereactions)\] [boolean](https://webidl.spec.whatwg.org/#idl-boolean) [toggleAttribute](https://dom.spec.whatwg.org/#dom-element-toggleattribute)([DOMString](https://webidl.spec.whatwg.org/#idl-DOMString) `qualifiedName`[](https://dom.spec.whatwg.org/#dom-element-toggleattribute-qualifiedname-force-qualifiedname), optional [boolean](https://webidl.spec.whatwg.org/#idl-boolean) `force`[](https://dom.spec.whatwg.org/#dom-element-toggleattribute-qualifiedname-force-force)); [boolean](https://webidl.spec.whatwg.org/#idl-boolean) [hasAttribute](https://dom.spec.whatwg.org/#dom-element-hasattribute)([DOMString](https://webidl.spec.whatwg.org/#idl-DOMString) `qualifiedName`[](https://dom.spec.whatwg.org/#dom-element-hasattribute-qualifiedname-qualifiedname)); [boolean](https://webidl.spec.whatwg.org/#idl-boolean) [hasAttributeNS](https://dom.spec.whatwg.org/#dom-element-hasattributens)([DOMString](https://webidl.spec.whatwg.org/#idl-DOMString)? `namespace`[](https://dom.spec.whatwg.org/#dom-element-hasattributens-namespace-localname-namespace), [DOMString](https://webidl.spec.whatwg.org/#idl-DOMString) `localName`[](https://dom.spec.whatwg.org/#dom-element-hasattributens-namespace-localname-localname)); [Attr](https://dom.spec.whatwg.org/#attr)? [getAttributeNode](https://dom.spec.whatwg.org/#dom-element-getattributenode)([DOMString](https://webidl.spec.whatwg.org/#idl-DOMString) `qualifiedName`[](https://dom.spec.whatwg.org/#dom-element-getattributenode-qualifiedname-qualifiedname)); [Attr](https://dom.spec.whatwg.org/#attr)? [getAttributeNodeNS](https://dom.spec.whatwg.org/#dom-element-getattributenodens)([DOMString](https://webidl.spec.whatwg.org/#idl-DOMString)? `namespace`[](https://dom.spec.whatwg.org/#dom-element-getattributenodens-namespace-localname-namespace), [DOMString](https://webidl.spec.whatwg.org/#idl-DOMString) `localName`[](https://dom.spec.whatwg.org/#dom-element-getattributenodens-namespace-localname-localname)); \[[CEReactions](https://html.spec.whatwg.org/multipage/custom-elements.html#cereactions)\] [Attr](https://dom.spec.whatwg.org/#attr)? [setAttributeNode](https://dom.spec.whatwg.org/#dom-element-setattributenode)([Attr](https://dom.spec.whatwg.org/#attr) `attr`[](https://dom.spec.whatwg.org/#dom-element-setattributenode-attr-attr)); \[[CEReactions](https://html.spec.whatwg.org/multipage/custom-elements.html#cereactions)\] [Attr](https://dom.spec.whatwg.org/#attr)? [setAttributeNodeNS](https://dom.spec.whatwg.org/#dom-element-setattributenodens)([Attr](https://dom.spec.whatwg.org/#attr) `attr`[](https://dom.spec.whatwg.org/#dom-element-setattributenodens-attr-attr)); \[[CEReactions](https://html.spec.whatwg.org/multipage/custom-elements.html#cereactions)\] [Attr](https://dom.spec.whatwg.org/#attr) [removeAttributeNode](https://dom.spec.whatwg.org/#dom-element-removeattributenode)([Attr](https://dom.spec.whatwg.org/#attr) `attr`[](https://dom.spec.whatwg.org/#dom-element-removeattributenode-attr-attr)); [ShadowRoot](https://dom.spec.whatwg.org/#shadowroot) [attachShadow](https://dom.spec.whatwg.org/#dom-element-attachshadow)([ShadowRootInit](https://dom.spec.whatwg.org/#dictdef-shadowrootinit) `init`[](https://dom.spec.whatwg.org/#dom-element-attachshadow-init-init)); readonly attribute [ShadowRoot](https://dom.spec.whatwg.org/#shadowroot)? [shadowRoot](https://dom.spec.whatwg.org/#dom-element-shadowroot); [Element](https://dom.spec.whatwg.org/#element)? [closest](https://dom.spec.whatwg.org/#dom-element-closest)([DOMString](https://webidl.spec.whatwg.org/#idl-DOMString) `selectors`[](https://dom.spec.whatwg.org/#dom-element-closest-selectors-selectors)); [boolean](https://webidl.spec.whatwg.org/#idl-boolean) [matches](https://dom.spec.whatwg.org/#dom-element-matches)([DOMString](https://webidl.spec.whatwg.org/#idl-DOMString) `selectors`[](https://dom.spec.whatwg.org/#dom-element-matches-selectors-selectors)); [boolean](https://webidl.spec.whatwg.org/#idl-boolean) [webkitMatchesSelector](https://dom.spec.whatwg.org/#dom-element-webkitmatchesselector)([DOMString](https://webidl.spec.whatwg.org/#idl-DOMString) `selectors`[](https://dom.spec.whatwg.org/#dom-element-webkitmatchesselector-selectors-selectors)); // legacy alias of.matches [HTMLCollection](https://dom.spec.whatwg.org/#htmlcollection) [getElementsByTagName](https://dom.spec.whatwg.org/#dom-element-getelementsbytagname)([DOMString](https://webidl.spec.whatwg.org/#idl-DOMString) `qualifiedName`[](https://dom.spec.whatwg.org/#dom-element-getelementsbytagname-qualifiedname-qualifiedname)); [HTMLCollection](https://dom.spec.whatwg.org/#htmlcollection) [getElementsByTagNameNS](https://dom.spec.whatwg.org/#dom-element-getelementsbytagnamens)([DOMString](https://webidl.spec.whatwg.org/#idl-DOMString)? `namespace`[](https://dom.spec.whatwg.org/#dom-element-getelementsbytagnamens-namespace-localname-namespace), [DOMString](https://webidl.spec.whatwg.org/#idl-DOMString) `localName`[](https://dom.spec.whatwg.org/#dom-element-getelementsbytagnamens-namespace-localname-localname)); [HTMLCollection](https://dom.spec.whatwg.org/#htmlcollection) [getElementsByClassName](https://dom.spec.whatwg.org/#dom-element-getelementsbyclassname)([DOMString](https://webidl.spec.whatwg.org/#idl-DOMString) `classNames`[](https://dom.spec.whatwg.org/#dom-element-getelementsbyclassname-classnames-classnames)); \[[CEReactions](https://html.spec.whatwg.org/multipage/custom-elements.html#cereactions)\] [Element](https://dom.spec.whatwg.org/#element)? [insertAdjacentElement](https://dom.spec.whatwg.org/#dom-element-insertadjacentelement)([DOMString](https://webidl.spec.whatwg.org/#idl-DOMString) `where`[](https://dom.spec.whatwg.org/#dom-element-insertadjacentelement-where-element-where), [Element](https://dom.spec.whatwg.org/#element) `element`[](https://dom.spec.whatwg.org/#dom-element-insertadjacentelement-where-element-element)); // legacy [undefined](https://webidl.spec.whatwg.org/#idl-undefined) [insertAdjacentText](https://dom.spec.whatwg.org/#dom-element-insertadjacenttext)([DOMString](https://webidl.spec.whatwg.org/#idl-DOMString) `where`[](https://dom.spec.whatwg.org/#dom-element-insertadjacenttext-where-data-where), [DOMString](https://webidl.spec.whatwg.org/#idl-DOMString) `data`[](https://dom.spec.whatwg.org/#dom-element-insertadjacenttext-where-data-data)); // legacy }; dictionary `ShadowRootInit` { required [ShadowRootMode](https://dom.spec.whatwg.org/#enumdef-shadowrootmode) `mode`; [boolean](https://webidl.spec.whatwg.org/#idl-boolean) `delegatesFocus` = false; [SlotAssignmentMode](https://dom.spec.whatwg.org/#enumdef-slotassignmentmode) `slotAssignment` = "named"; }; `[Element](https://dom.spec.whatwg.org/#element)` [nodes](https://dom.spec.whatwg.org/#concept-node) are simply known as elements. [Elements](https://dom.spec.whatwg.org/#concept-element) have an associated namespace, namespace prefix, local name, custom element state, custom element definition, `is` value. When an [element](https://dom.spec.whatwg.org/#concept-element) is [created](https://dom.spec.whatwg.org/#concept-create-element), all of these values are initialized. An [element](https://dom.spec.whatwg.org/#concept-element)’s [custom element state](https://dom.spec.whatwg.org/#concept-element-custom-element-state) is one of "`undefined`", "`failed`", "`uncustomized`", "`precustomized`", or "`custom`". An [element](https://dom.spec.whatwg.org/#concept-element) whose [custom element state](https://dom.spec.whatwg.org/#concept-element-custom-element-state) is "`uncustomized`" or "`custom`" is said to be defined. An [element](https://dom.spec.whatwg.org/#concept-element) whose [custom element state](https://dom.spec.whatwg.org/#concept-element-custom-element-state) is "`custom`" is said to be custom. Whether or not an element is [defined](https://dom.spec.whatwg.org/#concept-element-defined) is used to determine the behavior of the [:defined](https://drafts.csswg.org/selectors-4/#defined-pseudo) pseudo-class. Whether or not an element is [custom](https://dom.spec.whatwg.org/#concept-element-custom) is used to determine the behavior of the [mutation algorithms](https://dom.spec.whatwg.org/#mutation-algorithms). The "`failed`" and "`precustomized`" states are used to ensure that if a [custom element constructor](https://html.spec.whatwg.org/multipage/custom-elements.html#custom-element-constructor) fails to execute correctly the first time, it is not executed again by an [upgrade](https://html.spec.whatwg.org/multipage/custom-elements.html#concept-upgrade-an-element). The following code illustrates elements in each of these four states: ``` <!DOCTYPE html> <script> window.customElements.define("sw-rey", class extends HTMLElement {}) window.customElements.define("sw-finn", class extends HTMLElement {}, { extends: "p" }) window.customElements.define("sw-kylo", class extends HTMLElement { constructor() { // super() intentionally omitted for this example } }) </script> <!-- "undefined" (not defined, not custom) --> <sw-han></sw-han> <p is="sw-luke"></p> <p is="asdf"></p> <!-- "failed" (not defined, not custom) --> <sw-kylo></sw-kylo> <!-- "uncustomized" (defined, not custom) --> <p></p> <asdf></asdf> <!-- "custom" (defined, custom) --> <sw-rey></sw-rey> <p is="sw-finn"></p> ``` [Elements](https://dom.spec.whatwg.org/#concept-element) also have an associated shadow root (null or a [shadow root](https://dom.spec.whatwg.org/#concept-shadow-root)). It is null unless otherwise stated. An [element](https://dom.spec.whatwg.org/#concept-element) is a shadow host if its [shadow root](https://dom.spec.whatwg.org/#concept-element-shadow-root) is non-null. An [element](https://dom.spec.whatwg.org/#concept-element)’s qualified name is its [local name](https://dom.spec.whatwg.org/#concept-element-local-name) if its [namespace prefix](https://dom.spec.whatwg.org/#concept-element-namespace-prefix) is null; otherwise its [namespace prefix](https://dom.spec.whatwg.org/#concept-element-namespace-prefix), followed by "`:`", followed by its [local name](https://dom.spec.whatwg.org/#concept-element-local-name). An [element](https://dom.spec.whatwg.org/#concept-element)’s HTML-uppercased qualified name is the return value of these steps: 1. Let qualifiedName be [this](https://webidl.spec.whatwg.org/#this)’s [qualified name](https://dom.spec.whatwg.org/#concept-element-qualified-name). 2. If [this](https://webidl.spec.whatwg.org/#this) is in the [HTML namespace](https://infra.spec.whatwg.org/#html-namespace) and its [node document](https://dom.spec.whatwg.org/#concept-node-document) is an [HTML document](https://dom.spec.whatwg.org/#html-document), then set qualifiedName to qualifiedName in [ASCII uppercase](https://infra.spec.whatwg.org/#ascii-uppercase). 3. Return qualifiedName. User agents could optimize [qualified name](https://dom.spec.whatwg.org/#concept-element-qualified-name) and [HTML-uppercased qualified name](https://dom.spec.whatwg.org/#element-html-uppercased-qualified-name) by storing them in internal slots. To create an element, given a document, localName, namespace, and optional prefix, is, and synchronous custom elements flag, run these steps: 1. If prefix was not given, let prefix be null. 2. If is was not given, let is be null. 3. Let result be null. 4. Let definition be the result of [looking up a custom element definition](https://html.spec.whatwg.org/multipage/custom-elements.html#look-up-a-custom-element-definition) given document, namespace, localName, and is. 5. If definition is non-null, and definition’s [name](https://html.spec.whatwg.org/multipage/custom-elements.html#concept-custom-element-definition-name) is not equal to its [local name](https://html.spec.whatwg.org/multipage/custom-elements.html#concept-custom-element-definition-local-name) (i.e., definition represents a [customized built-in element](https://html.spec.whatwg.org/multipage/custom-elements.html#customized-built-in-element)), then: 1. Let interface be the [element interface](https://dom.spec.whatwg.org/#concept-element-interface) for localName and the [HTML namespace](https://infra.spec.whatwg.org/#html-namespace). 2. Set result to a new [element](https://dom.spec.whatwg.org/#concept-element) that implements interface, with no attributes, [namespace](https://dom.spec.whatwg.org/#concept-element-namespace) set to the [HTML namespace](https://infra.spec.whatwg.org/#html-namespace), [namespace prefix](https://dom.spec.whatwg.org/#concept-element-namespace-prefix) set to prefix, [local name](https://dom.spec.whatwg.org/#concept-element-local-name) set to localName, [custom element state](https://dom.spec.whatwg.org/#concept-element-custom-element-state) set to "`undefined`", [custom element definition](https://dom.spec.whatwg.org/#concept-element-custom-element-definition) set to null, [`is` value](https://dom.spec.whatwg.org/#concept-element-is-value) set to is, and [node document](https://dom.spec.whatwg.org/#concept-node-document) set to document. 3. If the synchronous custom elements flag is set, then run this step while catching any exceptions: 1. [Upgrade](https://html.spec.whatwg.org/multipage/custom-elements.html#concept-upgrade-an-element) element using definition. If this step threw an exception, then: 1. [Report the exception](https://html.spec.whatwg.org/multipage/webappapis.html#report-the-exception). 2. Set result’s [custom element state](https://dom.spec.whatwg.org/#concept-element-custom-element-state) to "`failed`". 4. Otherwise, [enqueue a custom element upgrade reaction](https://html.spec.whatwg.org/multipage/custom-elements.html#enqueue-a-custom-element-upgrade-reaction) given result and definition. 6. Otherwise, if definition is non-null, then: 1. If the synchronous custom elements flag is set, then run these steps while catching any exceptions: 1. Let C be definition’s [constructor](https://html.spec.whatwg.org/multipage/custom-elements.html#concept-custom-element-definition-constructor). 2. Set result to the result of [constructing](https://webidl.spec.whatwg.org/#construct-a-callback-function) C, with no arguments. 3. Assert: result’s [custom element state](https://dom.spec.whatwg.org/#concept-element-custom-element-state) and [custom element definition](https://dom.spec.whatwg.org/#concept-element-custom-element-definition) are initialized. 4. Assert: result’s [namespace](https://dom.spec.whatwg.org/#concept-element-namespace) is the [HTML namespace](https://infra.spec.whatwg.org/#html-namespace). IDL enforces that result is an `[HTMLElement](https://html.spec.whatwg.org/multipage/dom.html#htmlelement)` object, which all use the [HTML namespace](https://infra.spec.whatwg.org/#html-namespace). 5. If result’s [attribute list](https://dom.spec.whatwg.org/#concept-element-attribute) [is not empty](https://infra.spec.whatwg.org/#list-is-empty), then [throw](https://webidl.spec.whatwg.org/#dfn-throw) a "`[NotSupportedError](https://webidl.spec.whatwg.org/#notsupportederror)`" `[DOMException](https://webidl.spec.whatwg.org/#idl-DOMException)`. 6. If result has [children](https://dom.spec.whatwg.org/#concept-tree-child), then [throw](https://webidl.spec.whatwg.org/#dfn-throw) a "`[NotSupportedError](https://webidl.spec.whatwg.org/#notsupportederror)`" `[DOMException](https://webidl.spec.whatwg.org/#idl-DOMException)`. 7. If result’s [parent](https://dom.spec.whatwg.org/#concept-tree-parent) is not null, then [throw](https://webidl.spec.whatwg.org/#dfn-throw) a "`[NotSupportedError](https://webidl.spec.whatwg.org/#notsupportederror)`" `[DOMException](https://webidl.spec.whatwg.org/#idl-DOMException)`. 8. If result’s [node document](https://dom.spec.whatwg.org/#concept-node-document) is not document, then [throw](https://webidl.spec.whatwg.org/#dfn-throw) a "`[NotSupportedError](https://webidl.spec.whatwg.org/#notsupportederror)`" `[DOMException](https://webidl.spec.whatwg.org/#idl-DOMException)`. 9. If result’s [local name](https://dom.spec.whatwg.org/#concept-element-local-name) is not equal to localName, then [throw](https://webidl.spec.whatwg.org/#dfn-throw) a "`[NotSupportedError](https://webidl.spec.whatwg.org/#notsupportederror)`" `[DOMException](https://webidl.spec.whatwg.org/#idl-DOMException)`. 10. Set result’s [namespace prefix](https://dom.spec.whatwg.org/#concept-element-namespace-prefix) to prefix. 11. Set result’s [`is` value](https://dom.spec.whatwg.org/#concept-element-is-value) to null. If any of these steps threw an exception, then: 1. [Report the exception](https://html.spec.whatwg.org/multipage/webappapis.html#report-the-exception). 2. Set result to a new [element](https://dom.spec.whatwg.org/#concept-element) that implements the `[HTMLUnknownElement](https://html.spec.whatwg.org/multipage/dom.html#htmlunknownelement)` interface, with no attributes, [namespace](https://dom.spec.whatwg.org/#concept-element-namespace) set to the [HTML namespace](https://infra.spec.whatwg.org/#html-namespace), [namespace prefix](https://dom.spec.whatwg.org/#concept-element-namespace-prefix) set to prefix, [local name](https://dom.spec.whatwg.org/#concept-element-local-name) set to localName, [custom element state](https://dom.spec.whatwg.org/#concept-element-custom-element-state) set to "`failed`", [custom element definition](https://dom.spec.whatwg.org/#concept-element-custom-element-definition) set to null, [`is` value](https://dom.spec.whatwg.org/#concept-element-is-value) set to null, and [node document](https://dom.spec.whatwg.org/#concept-node-document) set to document. 2. Otherwise: 1. Set result to a new [element](https://dom.spec.whatwg.org/#concept-element) that implements the `[HTMLElement](https://html.spec.whatwg.org/multipage/dom.html#htmlelement)` interface, with no attributes, [namespace](https://dom.spec.whatwg.org/#concept-element-namespace) set to the [HTML namespace](https://infra.spec.whatwg.org/#html-namespace), [namespace prefix](https://dom.spec.whatwg.org/#concept-element-namespace-prefix) set to prefix, [local name](https://dom.spec.whatwg.org/#concept-element-local-name) set to localName, [custom element state](https://dom.spec.whatwg.org/#concept-element-custom-element-state) set to "`undefined`", [custom element definition](https://dom.spec.whatwg.org/#concept-element-custom-element-definition) set to null, [`is` value](https://dom.spec.whatwg.org/#concept-element-is-value) set to null, and [node document](https://dom.spec.whatwg.org/#concept-node-document) set to document. 2. [Enqueue a custom element upgrade reaction](https://html.spec.whatwg.org/multipage/custom-elements.html#enqueue-a-custom-element-upgrade-reaction) given result and definition. 7. Otherwise: 1. Let interface be the [element interface](https://dom.spec.whatwg.org/#concept-element-interface) for localName and namespace. 2. Set result to a new [element](https://dom.spec.whatwg.org/#concept-element) that implements interface, with no attributes, [namespace](https://dom.spec.whatwg.org/#concept-element-namespace) set to namespace, [namespace prefix](https://dom.spec.whatwg.org/#concept-element-namespace-prefix) set to prefix, [local name](https://dom.spec.whatwg.org/#concept-element-local-name) set to localName, [custom element state](https://dom.spec.whatwg.org/#concept-element-custom-element-state) set to "`uncustomized`", [custom element definition](https://dom.spec.whatwg.org/#concept-element-custom-element-definition) set to null, [`is` value](https://dom.spec.whatwg.org/#concept-element-is-value) set to is, and [node document](https://dom.spec.whatwg.org/#concept-node-document) set to document. 3. If namespace is the [HTML namespace](https://infra.spec.whatwg.org/#html-namespace), and either localName is a [valid custom element name](https://html.spec.whatwg.org/multipage/custom-elements.html#valid-custom-element-name) or is is non-null, then set result’s [custom element state](https://dom.spec.whatwg.org/#concept-element-custom-element-state) to "`undefined`". 8. Return result. [Elements](https://dom.spec.whatwg.org/#concept-element) also have an attribute list, which is a [list](https://infra.spec.whatwg.org/#list) exposed through a `[NamedNodeMap](https://dom.spec.whatwg.org/#namednodemap)`. Unless explicitly given when an [element](https://dom.spec.whatwg.org/#concept-element) is created, its [attribute list](https://dom.spec.whatwg.org/#concept-element-attribute) [is empty](https://infra.spec.whatwg.org/#list-is-empty). An [element](https://dom.spec.whatwg.org/#concept-element) has an [attribute](https://dom.spec.whatwg.org/#concept-attribute) A if its [attribute list](https://dom.spec.whatwg.org/#concept-element-attribute) [contains](https://infra.spec.whatwg.org/#list-contain) A. This and [other specifications](https://dom.spec.whatwg.org/#other-applicable-specifications) may define attribute change steps for [elements](https://dom.spec.whatwg.org/#concept-element). The algorithm is passed element, localName, oldValue, value, and namespace. To handle attribute changes for an [attribute](https://dom.spec.whatwg.org/#concept-attribute) attribute with element, oldValue, and newValue, run these steps: 1. [Queue a mutation record](https://dom.spec.whatwg.org/#queue-a-mutation-record) of "`attributes`" for element with attribute’s [local name](https://dom.spec.whatwg.org/#concept-attribute-local-name), attribute’s [namespace](https://dom.spec.whatwg.org/#concept-attribute-namespace), oldValue, « », « », null, and null. 2. If element is [custom](https://dom.spec.whatwg.org/#concept-element-custom), then [enqueue a custom element callback reaction](https://html.spec.whatwg.org/multipage/custom-elements.html#enqueue-a-custom-element-callback-reaction) with element, callback name "`attributeChangedCallback`", and an argument list containing attribute’s [local name](https://dom.spec.whatwg.org/#concept-attribute-local-name), oldValue, newValue, and attribute’s [namespace](https://dom.spec.whatwg.org/#concept-attribute-namespace). 3. Run the [attribute change steps](https://dom.spec.whatwg.org/#concept-element-attributes-change-ext) with element, attribute’s [local name](https://dom.spec.whatwg.org/#concept-attribute-local-name), oldValue, newValue, and attribute’s [namespace](https://dom.spec.whatwg.org/#concept-attribute-namespace). To change an [attribute](https://dom.spec.whatwg.org/#concept-attribute) attribute to value, run these steps: 1. [Handle attribute changes](https://dom.spec.whatwg.org/#handle-attribute-changes) for attribute with attribute’s [element](https://dom.spec.whatwg.org/#concept-attribute-element), attribute’s [value](https://dom.spec.whatwg.org/#concept-attribute-value), and value. 2. Set attribute’s [value](https://dom.spec.whatwg.org/#concept-attribute-value) to value. To append an [attribute](https://dom.spec.whatwg.org/#concept-attribute) attribute to an [element](https://dom.spec.whatwg.org/#concept-element) element, run these steps: 1. [Handle attribute changes](https://dom.spec.whatwg.org/#handle-attribute-changes) for attribute with element, null, and attribute’s [value](https://dom.spec.whatwg.org/#concept-attribute-value). 2. [Append](https://infra.spec.whatwg.org/#list-append) attribute to element’s [attribute list](https://dom.spec.whatwg.org/#concept-element-attribute). 3. Set attribute’s [element](https://dom.spec.whatwg.org/#concept-attribute-element) to element. To remove an [attribute](https://dom.spec.whatwg.org/#concept-attribute) attribute, run these steps: 1. [Handle attribute changes](https://dom.spec.whatwg.org/#handle-attribute-changes) for attribute with attribute’s [element](https://dom.spec.whatwg.org/#concept-attribute-element), attribute’s [value](https://dom.spec.whatwg.org/#concept-attribute-value), and null. 2. [Remove](https://infra.spec.whatwg.org/#list-remove) attribute from attribute’s [element](https://dom.spec.whatwg.org/#concept-attribute-element)’s [attribute list](https://dom.spec.whatwg.org/#concept-element-attribute). 3. Set attribute’s [element](https://dom.spec.whatwg.org/#concept-attribute-element) to null. To replace an [attribute](https://dom.spec.whatwg.org/#concept-attribute) oldAttr with an [attribute](https://dom.spec.whatwg.org/#concept-attribute) newAttr, run these steps: 1. [Handle attribute changes](https://dom.spec.whatwg.org/#handle-attribute-changes) for oldAttr with oldAttr’s [element](https://dom.spec.whatwg.org/#concept-attribute-element), oldAttr’s [value](https://dom.spec.whatwg.org/#concept-attribute-value), and newAttr’s [value](https://dom.spec.whatwg.org/#concept-attribute-value). 2. [Replace](https://infra.spec.whatwg.org/#list-replace) oldAttr by newAttr in oldAttr’s [element](https://dom.spec.whatwg.org/#concept-attribute-element)’s [attribute list](https://dom.spec.whatwg.org/#concept-element-attribute). 3. Set newAttr’s [element](https://dom.spec.whatwg.org/#concept-attribute-element) to oldAttr’s [element](https://dom.spec.whatwg.org/#concept-attribute-element). 4. Set oldAttr’s [element](https://dom.spec.whatwg.org/#concept-attribute-element) to null. ___ To get an attribute by name given a qualifiedName and [element](https://dom.spec.whatwg.org/#concept-element) element, run these steps: 1. If element is in the [HTML namespace](https://infra.spec.whatwg.org/#html-namespace) and its [node document](https://dom.spec.whatwg.org/#concept-node-document) is an [HTML document](https://dom.spec.whatwg.org/#html-document), then set qualifiedName to qualifiedName in [ASCII lowercase](https://infra.spec.whatwg.org/#ascii-lowercase). 2. Return the first [attribute](https://dom.spec.whatwg.org/#concept-attribute) in element’s [attribute list](https://dom.spec.whatwg.org/#concept-element-attribute) whose [qualified name](https://dom.spec.whatwg.org/#concept-attribute-qualified-name) is qualifiedName; otherwise null. To get an attribute by namespace and local name given a namespace, localName, and [element](https://dom.spec.whatwg.org/#concept-element) element, run these steps: 1. If namespace is the empty string, then set it to null. 2. Return the [attribute](https://dom.spec.whatwg.org/#concept-attribute) in element’s [attribute list](https://dom.spec.whatwg.org/#concept-element-attribute) whose [namespace](https://dom.spec.whatwg.org/#concept-attribute-namespace) is namespace and [local name](https://dom.spec.whatwg.org/#concept-attribute-local-name) is localName, if any; otherwise null. To get an attribute value given an [element](https://dom.spec.whatwg.org/#concept-element) element, localName, and optionally a namespace (null unless stated otherwise), run these steps: 1. Let attr be the result of [getting an attribute](https://dom.spec.whatwg.org/#concept-element-attributes-get-by-namespace) given namespace, localName, and element. 2. If attr is null, then return the empty string. 3. Return attr’s [value](https://dom.spec.whatwg.org/#concept-attribute-value). To set an attribute given an attr and element, run these steps: 1. If attr’s [element](https://dom.spec.whatwg.org/#concept-attribute-element) is neither null nor element, [throw](https://webidl.spec.whatwg.org/#dfn-throw) an "`[InUseAttributeError](https://webidl.spec.whatwg.org/#inuseattributeerror)`" `[DOMException](https://webidl.spec.whatwg.org/#idl-DOMException)`. 2. Let oldAttr be the result of [getting an attribute](https://dom.spec.whatwg.org/#concept-element-attributes-get-by-namespace) given attr’s [namespace](https://dom.spec.whatwg.org/#concept-attribute-namespace), attr’s [local name](https://dom.spec.whatwg.org/#concept-attribute-local-name), and element. 3. If oldAttr is attr, return attr. 4. If oldAttr is non-null, then [replace](https://dom.spec.whatwg.org/#concept-element-attributes-replace) oldAttr with attr. 5. Otherwise, [append](https://dom.spec.whatwg.org/#concept-element-attributes-append) attr to element. 6. Return oldAttr. To set an attribute value for an [element](https://dom.spec.whatwg.org/#concept-element) element, using a localName and value, and an optional prefix, and namespace, run these steps: 1. If prefix is not given, set it to null. 2. If namespace is not given, set it to null. 3. Let attribute be the result of [getting an attribute](https://dom.spec.whatwg.org/#concept-element-attributes-get-by-namespace) given namespace, localName, and element. 4. If attribute is null, create an [attribute](https://dom.spec.whatwg.org/#concept-attribute) whose [namespace](https://dom.spec.whatwg.org/#concept-attribute-namespace) is namespace, [namespace prefix](https://dom.spec.whatwg.org/#concept-attribute-namespace-prefix) is prefix, [local name](https://dom.spec.whatwg.org/#concept-attribute-local-name) is localName, [value](https://dom.spec.whatwg.org/#concept-attribute-value) is value, and [node document](https://dom.spec.whatwg.org/#concept-node-document) is element’s [node document](https://dom.spec.whatwg.org/#concept-node-document), then [append](https://dom.spec.whatwg.org/#concept-element-attributes-append) this [attribute](https://dom.spec.whatwg.org/#concept-attribute) to element, and then return. 5. [Change](https://dom.spec.whatwg.org/#concept-element-attributes-change) attribute to value. To remove an attribute by name given a qualifiedName and [element](https://dom.spec.whatwg.org/#concept-element) element, run these steps: 1. Let attr be the result of [getting an attribute](https://dom.spec.whatwg.org/#concept-element-attributes-get-by-name) given qualifiedName and element. 2. If attr is non-null, then [remove](https://dom.spec.whatwg.org/#concept-element-attributes-remove) attr. 3. Return attr. To remove an attribute by namespace and local name given a namespace, localName, and [element](https://dom.spec.whatwg.org/#concept-element) element, run these steps: 1. Let attr be the result of [getting an attribute](https://dom.spec.whatwg.org/#concept-element-attributes-get-by-namespace) given namespace, localName, and element. 2. If attr is non-null, then [remove](https://dom.spec.whatwg.org/#concept-element-attributes-remove) attr. 3. Return attr. ___ An [element](https://dom.spec.whatwg.org/#concept-element) can have an associated unique identifier (ID) Historically [elements](https://dom.spec.whatwg.org/#concept-element) could have multiple identifiers e.g., by using the HTML `id` [attribute](https://dom.spec.whatwg.org/#concept-attribute) and a DTD. This specification makes [ID](https://dom.spec.whatwg.org/#concept-id) a concept of the DOM and allows for only one per [element](https://dom.spec.whatwg.org/#concept-element), given by an [`id` attribute](https://dom.spec.whatwg.org/#concept-named-attribute). Use these [attribute change steps](https://dom.spec.whatwg.org/#concept-element-attributes-change-ext) to update an [element](https://dom.spec.whatwg.org/#concept-element)’s [ID](https://dom.spec.whatwg.org/#concept-id): 1. If localName is `id`, namespace is null, and value is null or the empty string, then unset element’s [ID](https://dom.spec.whatwg.org/#concept-id). 2. Otherwise, if localName is `id`, namespace is null, then set element’s [ID](https://dom.spec.whatwg.org/#concept-id) to value. While this specification defines requirements for `class`, `id`, and `slot` [attributes](https://dom.spec.whatwg.org/#concept-attribute) on any [element](https://dom.spec.whatwg.org/#concept-element), it makes no claims as to whether using them is conforming or not. ___ A [node](https://dom.spec.whatwg.org/#concept-node)’s [parent](https://dom.spec.whatwg.org/#concept-tree-parent) of type `[Element](https://dom.spec.whatwg.org/#element)` is known as its parent element. If the [node](https://dom.spec.whatwg.org/#concept-node) has a [parent](https://dom.spec.whatwg.org/#concept-tree-parent) of a different type, its [parent element](https://dom.spec.whatwg.org/#parent-element) is null. ___ [Element/namespaceURI](https://developer.mozilla.org/en-US/docs/Web/API/Element/namespaceURI "The Element.namespaceURI read-only property returns the namespace URI of the element, or null if the element is not in a namespace.") In all current engines. Firefox1+Safari1+Chrome1+ ___ Opera12.1+Edge79+ ___ Edge (Legacy)12+IE9+ ___ Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+ namespace = element. `[namespaceURI](https://dom.spec.whatwg.org/#dom-element-namespaceuri)` Returns the [namespace](https://dom.spec.whatwg.org/#concept-element-namespace). [Element/prefix](https://developer.mozilla.org/en-US/docs/Web/API/Element/prefix "The Element.prefix read-only property returns the namespace prefix of the specified element, or null if no prefix is specified.") In all current engines. Firefox1+Safari1+Chrome1+ ___ Opera12.1+Edge79+ ___ Edge (Legacy)12+IE9+ ___ Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+ prefix = element. `[prefix](https://dom.spec.whatwg.org/#dom-element-prefix)` Returns the [namespace prefix](https://dom.spec.whatwg.org/#concept-element-namespace-prefix). [Element/localName](https://developer.mozilla.org/en-US/docs/Web/API/Element/localName "The Element.localName read-only property returns the local part of the qualified name of an element.") In all current engines. Firefox1+Safari1+Chrome1+ ___ Opera12.1+Edge79+ ___ Edge (Legacy)12+IE9+ ___ Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+ localName = element. `[localName](https://dom.spec.whatwg.org/#dom-element-localname)` Returns the [local name](https://dom.spec.whatwg.org/#concept-element-local-name). [Element/tagName](https://developer.mozilla.org/en-US/docs/Web/API/Element/tagName "The tagName read-only property of the Element interface returns the tag name of the element on which it's called.") In all current engines. Firefox1+Safari1+Chrome1+ ___ Opera8+Edge79+ ___ Edge (Legacy)12+IE5+ ___ Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+ qualifiedName = element. `[tagName](https://dom.spec.whatwg.org/#dom-element-tagname)` Returns the [HTML-uppercased qualified name](https://dom.spec.whatwg.org/#element-html-uppercased-qualified-name). The `namespaceURI` getter steps are to return [this](https://webidl.spec.whatwg.org/#this)’s [namespace](https://dom.spec.whatwg.org/#concept-element-namespace). The `prefix` getter steps are to return [this](https://webidl.spec.whatwg.org/#this)’s [namespace prefix](https://dom.spec.whatwg.org/#concept-element-namespace-prefix). The `localName` getter steps are to return [this](https://webidl.spec.whatwg.org/#this)’s [local name](https://dom.spec.whatwg.org/#concept-element-local-name). The `tagName` getter steps are to return [this](https://webidl.spec.whatwg.org/#this)’s [HTML-uppercased qualified name](https://dom.spec.whatwg.org/#element-html-uppercased-qualified-name). ___ [Element/id](https://developer.mozilla.org/en-US/docs/Web/API/Element/id "The id property of the Element interface represents the element's identifier, reflecting the id global attribute.") In all current engines. Firefox1+Safari1+Chrome23+ ___ Opera12.1+Edge79+ ___ Edge (Legacy)12+IE5+ ___ Firefox for Android4+iOS Safari1+Chrome for Android25+Android WebView37+Samsung Internet1.5+Opera Mobile12.1+ `element. [id](https://dom.spec.whatwg.org/#dom-element-id) [ = value ]` Returns the value of element’s `id` content attribute. Can be set to change it. [Element/className](https://developer.mozilla.org/en-US/docs/Web/API/Element/className "The className property of the Element interface gets and sets the value of the class attribute of the specified element.") In all current engines. Firefox1+Safari1+Chrome22+ ___ Opera8+Edge79+ ___ Edge (Legacy)12+IE5+ ___ Firefox for Android4+iOS Safari1+Chrome for Android25+Android WebView37+Samsung Internet1.5+Opera Mobile10.1+ `element. [className](https://dom.spec.whatwg.org/#dom-element-classname) [ = value ]` Returns the value of element’s `class` content attribute. Can be set to change it. [Element/classList](https://developer.mozilla.org/en-US/docs/Web/API/Element/classList "The Element.classList is a read-only property that returns a live DOMTokenList collection of the class attributes of the element. This can then be used to manipulate the class list.") In all current engines. Firefox3.6+Safari7+Chrome22+ ___ Opera11.5+Edge79+ ___ Edge (Legacy)16+IENone ___ Firefox for Android4+iOS Safari7+Chrome for Android25+Android WebView4.4+Samsung Internet1.5+Opera Mobile11.5+ `element. [classList](https://dom.spec.whatwg.org/#dom-element-classlist)` Allows for manipulation of element’s `class` content attribute as a set of whitespace-separated tokens through a `[DOMTokenList](https://dom.spec.whatwg.org/#domtokenlist)` object. [Element/slot](https://developer.mozilla.org/en-US/docs/Web/API/Element/slot "The slot property of the Element interface returns the name of the shadow DOM slot the element is inserted in.") In all current engines. Firefox63+Safari10+Chrome53+ ___ Opera40+Edge79+ ___ Edge (Legacy)NoneIENone ___ Firefox for Android63+iOS Safari10+Chrome for Android53+Android WebView53+Samsung Internet6.0+Opera Mobile41+ [Global\_attributes/slot](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/slot "The slot global attribute assigns a slot in a shadow DOM shadow tree to an element: An element with a slot attribute is assigned to the slot created by the <slot> element whose name attribute's value matches that slot attribute's value.") In all current engines. Firefox63+Safari10+Chrome53+ ___ Opera40+Edge79+ ___ Edge (Legacy)NoneIE? ___ Firefox for Android63+iOS Safari10+Chrome for Android53+Android WebView53+Samsung Internet6.0+Opera Mobile41+ `element. [slot](https://dom.spec.whatwg.org/#dom-element-slot) [ = value ]` Returns the value of element’s `slot` content attribute. Can be set to change it. IDL attributes that are defined to reflect a content [attribute](https://dom.spec.whatwg.org/#concept-attribute) of a given name, must have a getter and setter that follow these steps: getter Return the result of running [get an attribute value](https://dom.spec.whatwg.org/#concept-element-attributes-get-value) given [this](https://webidl.spec.whatwg.org/#this) and name. setter [Set an attribute value](https://dom.spec.whatwg.org/#concept-element-attributes-set-value) for [this](https://webidl.spec.whatwg.org/#this) using name and the given value. The `id` attribute must [reflect](https://dom.spec.whatwg.org/#concept-reflect) the "`id`" content attribute. The `className` attribute must [reflect](https://dom.spec.whatwg.org/#concept-reflect) the "`class`" content attribute. The `classList` getter steps are to return a `[DOMTokenList](https://dom.spec.whatwg.org/#domtokenlist)` object whose associated [element](https://dom.spec.whatwg.org/#concept-element) is [this](https://webidl.spec.whatwg.org/#this) and whose associated [attribute](https://dom.spec.whatwg.org/#concept-attribute)’s [local name](https://dom.spec.whatwg.org/#concept-attribute-local-name) is `class`. The [token set](https://dom.spec.whatwg.org/#concept-dtl-tokens) of this particular `[DOMTokenList](https://dom.spec.whatwg.org/#domtokenlist)` object are also known as the [element](https://dom.spec.whatwg.org/#concept-element)’s classes. The `slot` attribute must [reflect](https://dom.spec.whatwg.org/#concept-reflect) the "`slot`" content attribute. `id`, `class`, and `slot` are effectively superglobal attributes as they can appear on any element, regardless of that element’s namespace. ___ [Element/hasAttributes](https://developer.mozilla.org/en-US/docs/Web/API/Element/hasAttributes "The hasAttributes() method of the Element interface returns a boolean value indicating whether the current element has any attributes or not.") In all current engines. Firefox1+Safari1+Chrome1+ ___ Opera12.1+Edge79+ ___ Edge (Legacy)12+IE8+ ___ Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+ `element. [hasAttributes](https://dom.spec.whatwg.org/#dom-element-hasattributes)()` Returns true if element has attributes; otherwise false. [Element/getAttributeNames](https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttributeNames "The getAttributeNames() method of the Element interface returns the attribute names of the element as an Array of strings. If the element has no attributes it returns an empty array.") In all current engines. Firefox45+Safari10.1+Chrome61+ ___ Opera48+Edge79+ ___ Edge (Legacy)18IENone ___ Firefox for Android45+iOS Safari10.3+Chrome for Android61+Android WebView61+Samsung Internet8.0+Opera Mobile45+ `element. [getAttributeNames](https://dom.spec.whatwg.org/#dom-element-getattributenames)()` Returns the [qualified names](https://dom.spec.whatwg.org/#concept-attribute-qualified-name) of all element’s [attributes](https://dom.spec.whatwg.org/#concept-attribute). Can contain duplicates. [Element/getAttribute](https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute "The getAttribute() method of the Element interface returns the value of a specified attribute on the element.") In all current engines. Firefox1+Safari1+Chrome1+ ___ Opera8+Edge79+ ___ Edge (Legacy)12+IE5+ ___ Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+ `element. [getAttribute](https://dom.spec.whatwg.org/#dom-element-getattribute)(qualifiedName)` Returns element’s first [attribute](https://dom.spec.whatwg.org/#concept-attribute) whose [qualified name](https://dom.spec.whatwg.org/#concept-attribute-qualified-name) is qualifiedName, and null if there is no such [attribute](https://dom.spec.whatwg.org/#concept-attribute) otherwise. [Element/getAttributeNS](https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttributeNS "The getAttributeNS() method of the Element interface returns the string value of the attribute with the specified namespace and name. If the named attribute does not exist, the value returned will either be null or "" (the empty string); see Notes for details.") In all current engines. Firefox1+Safari1+Chrome1+ ___ Opera12.1+Edge79+ ___ Edge (Legacy)12+IE9+ ___ Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+ `element. [getAttributeNS](https://dom.spec.whatwg.org/#dom-element-getattributens)(namespace, localName)` Returns element’s [attribute](https://dom.spec.whatwg.org/#concept-attribute) whose [namespace](https://dom.spec.whatwg.org/#concept-attribute-namespace) is namespace and [local name](https://dom.spec.whatwg.org/#concept-attribute-local-name) is localName, and null if there is no such [attribute](https://dom.spec.whatwg.org/#concept-attribute) otherwise. [Element/setAttribute](https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute "Sets the value of an attribute on the specified element. If the attribute already exists, the value is updated; otherwise a new attribute is added with the specified name and value.") In all current engines. Firefox1+Safari1+Chrome1+ ___ Opera8+Edge79+ ___ Edge (Legacy)12+IE5+ ___ Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+ `element. [setAttribute](https://dom.spec.whatwg.org/#dom-element-setattribute)(qualifiedName, value)` Sets the [value](https://dom.spec.whatwg.org/#concept-attribute-value) of element’s first [attribute](https://dom.spec.whatwg.org/#concept-attribute) whose [qualified name](https://dom.spec.whatwg.org/#concept-attribute-qualified-name) is qualifiedName to value. [Element/setAttributeNS](https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttributeNS "setAttributeNS adds a new attribute or changes the value of an attribute with the given namespace and name.") In all current engines. Firefox1+Safari1+Chrome1+ ___ Opera12.1+Edge79+ ___ Edge (Legacy)12+IE9+ ___ Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+ `element. [setAttributeNS](https://dom.spec.whatwg.org/#dom-element-setattributens)(namespace, localName, value)` Sets the [value](https://dom.spec.whatwg.org/#concept-attribute-value) of element’s [attribute](https://dom.spec.whatwg.org/#concept-attribute) whose [namespace](https://dom.spec.whatwg.org/#concept-attribute-namespace) is namespace and [local name](https://dom.spec.whatwg.org/#concept-attribute-local-name) is localName to value. [Element/removeAttribute](https://developer.mozilla.org/en-US/docs/Web/API/Element/removeAttribute "The Element method removeAttribute() removes the attribute with the specified name from the element.") In all current engines. Firefox1+Safari1+Chrome1+ ___ Opera8+Edge79+ ___ Edge (Legacy)12+IE5+ ___ Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+ `element. [removeAttribute](https://dom.spec.whatwg.org/#dom-element-removeattribute)(qualifiedName)` Removes element’s first [attribute](https://dom.spec.whatwg.org/#concept-attribute) whose [qualified name](https://dom.spec.whatwg.org/#concept-attribute-qualified-name) is qualifiedName. [Element/removeAttributeNS](https://developer.mozilla.org/en-US/docs/Web/API/Element/removeAttributeNS "The removeAttributeNS() method of the Element interface removes the specified attribute from an element.") In all current engines. Firefox1+Safari1+Chrome1+ ___ Opera12.1+Edge79+ ___ Edge (Legacy)12+IE9+ ___ Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+ `element. [removeAttributeNS](https://dom.spec.whatwg.org/#dom-element-removeattributens)(namespace, localName)` Removes element’s [attribute](https://dom.spec.whatwg.org/#concept-attribute) whose [namespace](https://dom.spec.whatwg.org/#concept-attribute-namespace) is namespace and [local name](https://dom.spec.whatwg.org/#concept-attribute-local-name) is localName. [Element/toggleAttribute](https://developer.mozilla.org/en-US/docs/Web/API/Element/toggleAttribute "The toggleAttribute() method of the Element interface toggles a Boolean attribute (removing it if it is present and adding it if it is not present) on the given element.") In all current engines. Firefox63+Safari12+Chrome69+ ___ Opera56+Edge79+ ___ Edge (Legacy)18IENone ___ Firefox for Android63+iOS Safari12+Chrome for Android69+Android WebView69+Samsung Internet10.0+Opera Mobile48+ `element. [toggleAttribute](https://dom.spec.whatwg.org/#dom-element-toggleattribute)(qualifiedName [, force])` If force is not given, "toggles" qualifiedName, removing it if it is present and adding it if it is not present. If force is true, adds qualifiedName. If force is false, removes qualifiedName. Returns true if qualifiedName is now present; otherwise false. [Element/hasAttribute](https://developer.mozilla.org/en-US/docs/Web/API/Element/hasAttribute "The Element.hasAttribute() method returns a Boolean value indicating whether the specified element has the specified attribute or not.") In all current engines. Firefox1+Safari1+Chrome1+ ___ Opera8+Edge79+ ___ Edge (Legacy)12+IE8+ ___ Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+ `element. [hasAttribute](https://dom.spec.whatwg.org/#dom-element-hasattribute)(qualifiedName)` Returns true if element has an [attribute](https://dom.spec.whatwg.org/#concept-attribute) whose [qualified name](https://dom.spec.whatwg.org/#concept-attribute-qualified-name) is qualifiedName; otherwise false. [Element/hasAttributeNS](https://developer.mozilla.org/en-US/docs/Web/API/Element/hasAttributeNS "hasAttributeNS returns a boolean value indicating whether the current element has the specified attribute.") In all current engines. Firefox1+Safari1+Chrome1+ ___ Opera12.1+Edge79+ ___ Edge (Legacy)12+IE9+ ___ Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+ `element. [hasAttributeNS](https://dom.spec.whatwg.org/#dom-element-hasattributens)(namespace, localName)` Returns true if element has an [attribute](https://dom.spec.whatwg.org/#concept-attribute) whose [namespace](https://dom.spec.whatwg.org/#concept-attribute-namespace) is namespace and [local name](https://dom.spec.whatwg.org/#concept-attribute-local-name) is localName. The `hasAttributes()` method steps are to return false if [this](https://webidl.spec.whatwg.org/#this)’s [attribute list](https://dom.spec.whatwg.org/#concept-element-attribute) [is empty](https://infra.spec.whatwg.org/#list-is-empty); otherwise true. [Element/attributes](https://developer.mozilla.org/en-US/docs/Web/API/Element/attributes "The Element.attributes property returns a live collection of all attribute nodes registered to the specified node. It is a NamedNodeMap, not an Array, so it has no Array methods and the Attr nodes' indexes may differ among browsers. To be more specific, attributes is a key/value pair of strings that represents any information regarding that attribute.") In all current engines. Firefox1+Safari1+Chrome1+ ___ Opera8+Edge79+ ___ Edge (Legacy)12+IE5.5+ ___ Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+ The `attributes` getter steps are to return the associated `[NamedNodeMap](https://dom.spec.whatwg.org/#namednodemap)`. The `getAttributeNames()` method steps are to return the [qualified names](https://dom.spec.whatwg.org/#concept-attribute-qualified-name) of the [attributes](https://dom.spec.whatwg.org/#concept-attribute) in [this](https://webidl.spec.whatwg.org/#this)’s [attribute list](https://dom.spec.whatwg.org/#concept-element-attribute), in order; otherwise a new [list](https://infra.spec.whatwg.org/#list). These are not guaranteed to be unique. The `getAttribute(qualifiedName)` method steps are: 1. Let attr be the result of [getting an attribute](https://dom.spec.whatwg.org/#concept-element-attributes-get-by-name) given qualifiedName and [this](https://webidl.spec.whatwg.org/#this). 2. If attr is null, return null. 3. Return attr’s [value](https://dom.spec.whatwg.org/#concept-attribute-value). The `getAttributeNS(namespace, localName)` method steps are: 1. Let attr be the result of [getting an attribute](https://dom.spec.whatwg.org/#concept-element-attributes-get-by-namespace) given namespace, localName, and [this](https://webidl.spec.whatwg.org/#this). 2. If attr is null, return null. 3. Return attr’s [value](https://dom.spec.whatwg.org/#concept-attribute-value). The `setAttribute(qualifiedName, value)` method steps are: 1. If qualifiedName does not match the `[Name](https://www.w3.org/TR/xml/#NT-Name)` production in XML, then [throw](https://webidl.spec.whatwg.org/#dfn-throw) an "`[InvalidCharacterError](https://webidl.spec.whatwg.org/#invalidcharactererror)`" `[DOMException](https://webidl.spec.whatwg.org/#idl-DOMException)`. 2. If [this](https://webidl.spec.whatwg.org/#this) is in the [HTML namespace](https://infra.spec.whatwg.org/#html-namespace) and its [node document](https://dom.spec.whatwg.org/#concept-node-document) is an [HTML document](https://dom.spec.whatwg.org/#html-document), then set qualifiedName to qualifiedName in [ASCII lowercase](https://infra.spec.whatwg.org/#ascii-lowercase). 3. Let attribute be the first [attribute](https://dom.spec.whatwg.org/#concept-attribute) in [this](https://webidl.spec.whatwg.org/#this)’s [attribute list](https://dom.spec.whatwg.org/#concept-element-attribute) whose [qualified name](https://dom.spec.whatwg.org/#concept-attribute-qualified-name) is qualifiedName, and null otherwise. 4. If attribute is null, create an [attribute](https://dom.spec.whatwg.org/#concept-attribute) whose [local name](https://dom.spec.whatwg.org/#concept-attribute-local-name) is qualifiedName, [value](https://dom.spec.whatwg.org/#concept-attribute-value) is value, and [node document](https://dom.spec.whatwg.org/#concept-node-document) is [this](https://webidl.spec.whatwg.org/#this)’s [node document](https://dom.spec.whatwg.org/#concept-node-document), then [append](https://dom.spec.whatwg.org/#concept-element-attributes-append) this [attribute](https://dom.spec.whatwg.org/#concept-attribute) to [this](https://webidl.spec.whatwg.org/#this), and then return. 5. [Change](https://dom.spec.whatwg.org/#concept-element-attributes-change) attribute to value. The `setAttributeNS(namespace, qualifiedName, value)` method steps are: 1. Let namespace, prefix, and localName be the result of passing namespace and qualifiedName to [validate and extract](https://dom.spec.whatwg.org/#validate-and-extract). 2. [Set an attribute value](https://dom.spec.whatwg.org/#concept-element-attributes-set-value) for [this](https://webidl.spec.whatwg.org/#this) using localName, value, and also prefix and namespace. The `removeAttribute(qualifiedName)` method steps are to [remove an attribute](https://dom.spec.whatwg.org/#concept-element-attributes-remove-by-name) given qualifiedName and [this](https://webidl.spec.whatwg.org/#this), and then return undefined. The `removeAttributeNS(namespace, localName)` method steps are to [remove an attribute](https://dom.spec.whatwg.org/#concept-element-attributes-remove-by-namespace) given namespace, localName, and [this](https://webidl.spec.whatwg.org/#this), and then return undefined. The `hasAttribute(qualifiedName)` method steps are: 1. If [this](https://webidl.spec.whatwg.org/#this) is in the [HTML namespace](https://infra.spec.whatwg.org/#html-namespace) and its [node document](https://dom.spec.whatwg.org/#concept-node-document) is an [HTML document](https://dom.spec.whatwg.org/#html-document), then set qualifiedName to qualifiedName in [ASCII lowercase](https://infra.spec.whatwg.org/#ascii-lowercase). 2. Return true if [this](https://webidl.spec.whatwg.org/#this) [has](https://dom.spec.whatwg.org/#concept-element-attribute-has) an [attribute](https://dom.spec.whatwg.org/#concept-attribute) whose [qualified name](https://dom.spec.whatwg.org/#concept-attribute-qualified-name) is qualifiedName; otherwise false. The `toggleAttribute(qualifiedName, force)` method steps are: 1. If qualifiedName does not match the `[Name](https://www.w3.org/TR/xml/#NT-Name)` production in XML, then [throw](https://webidl.spec.whatwg.org/#dfn-throw) an "`[InvalidCharacterError](https://webidl.spec.whatwg.org/#invalidcharactererror)`" `[DOMException](https://webidl.spec.whatwg.org/#idl-DOMException)`. 2. If [this](https://webidl.spec.whatwg.org/#this) is in the [HTML namespace](https://infra.spec.whatwg.org/#html-namespace) and its [node document](https://dom.spec.whatwg.org/#concept-node-document) is an [HTML document](https://dom.spec.whatwg.org/#html-document), then set qualifiedName to qualifiedName in [ASCII lowercase](https://infra.spec.whatwg.org/#ascii-lowercase). 3. Let attribute be the first [attribute](https://dom.spec.whatwg.org/#concept-attribute) in [this](https://webidl.spec.whatwg.org/#this)’s [attribute list](https://dom.spec.whatwg.org/#concept-element-attribute) whose [qualified name](https://dom.spec.whatwg.org/#concept-attribute-qualified-name) is qualifiedName, and null otherwise. 4. If attribute is null, then: 1. If force is not given or is true, create an [attribute](https://dom.spec.whatwg.org/#concept-attribute) whose [local name](https://dom.spec.whatwg.org/#concept-attribute-local-name) is qualifiedName, [value](https://dom.spec.whatwg.org/#concept-attribute-value) is the empty string, and [node document](https://dom.spec.whatwg.org/#concept-node-document) is [this](https://webidl.spec.whatwg.org/#this)’s [node document](https://dom.spec.whatwg.org/#concept-node-document), then [append](https://dom.spec.whatwg.org/#concept-element-attributes-append) this [attribute](https://dom.spec.whatwg.org/#concept-attribute) to [this](https://webidl.spec.whatwg.org/#this), and then return true. 2. Return false. 5. Otherwise, if force is not given or is false, [remove an attribute](https://dom.spec.whatwg.org/#concept-element-attributes-remove-by-name) given qualifiedName and [this](https://webidl.spec.whatwg.org/#this), and then return false. 6. Return true. The `hasAttributeNS(namespace, localName)` method steps are: 1. If namespace is the empty string, then set it to null. 2. Return true if [this](https://webidl.spec.whatwg.org/#this) [has](https://dom.spec.whatwg.org/#concept-element-attribute-has) an [attribute](https://dom.spec.whatwg.org/#concept-attribute) whose [namespace](https://dom.spec.whatwg.org/#concept-attribute-namespace) is namespace and [local name](https://dom.spec.whatwg.org/#concept-attribute-local-name) is localName; otherwise false. ___ [Element/getAttributeNode](https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttributeNode "Returns the specified attribute of the specified element, as an Attr node.") In all current engines. Firefox1+Safari1+Chrome1+ ___ Opera12.1+Edge79+ ___ Edge (Legacy)12+IE6+ ___ Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+ The `getAttributeNode(qualifiedName)` method steps are to return the result of [getting an attribute](https://dom.spec.whatwg.org/#concept-element-attributes-get-by-name) given qualifiedName and [this](https://webidl.spec.whatwg.org/#this). [Element/getAttributeNodeNS](https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttributeNodeNS "Returns the Attr node for the attribute with the given namespace and name.") In all current engines. Firefox1+Safari1+Chrome1+ ___ Opera12.1+Edge79+ ___ Edge (Legacy)12+IE9+ ___ Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+ The `getAttributeNodeNS(namespace, localName)` method steps are to return the result of [getting an attribute](https://dom.spec.whatwg.org/#concept-element-attributes-get-by-namespace) given namespace, localName, and [this](https://webidl.spec.whatwg.org/#this). [Element/setAttributeNode](https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttributeNode "The setAttributeNode() method adds a new Attr node to the specified element.") In all current engines. Firefox1+Safari1+Chrome1+ ___ Opera12.1+Edge79+ ___ Edge (Legacy)12+IE6+ ___ Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+ [Element/setAttributeNodeNS](https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttributeNodeNS "setAttributeNodeNS adds a new namespaced attribute node to an element.") In all current engines. Firefox1+Safari1+Chrome1+ ___ Opera12.1+Edge79+ ___ Edge (Legacy)12+IE9+ ___ Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+ The `setAttributeNode(attr)` and `setAttributeNodeNS(attr)` methods steps are to return the result of [setting an attribute](https://dom.spec.whatwg.org/#concept-element-attributes-set) given attr and [this](https://webidl.spec.whatwg.org/#this). [Element/removeAttributeNode](https://developer.mozilla.org/en-US/docs/Web/API/Element/removeAttributeNode "The removeAttributeNode() method of the Element object removes the specified attribute from the current element.") In all current engines. Firefox1+Safari1+Chrome1+ ___ Opera12.1+Edge79+ ___ Edge (Legacy)12+IE6+ ___ Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+ The `removeAttributeNode(attr)` method steps are: 1. If [this](https://webidl.spec.whatwg.org/#this)’s [attribute list](https://dom.spec.whatwg.org/#concept-element-attribute) does not [contain](https://infra.spec.whatwg.org/#list-contain) attr, then [throw](https://webidl.spec.whatwg.org/#dfn-throw) a "`[NotFoundError](https://webidl.spec.whatwg.org/#notfounderror)`" `[DOMException](https://webidl.spec.whatwg.org/#idl-DOMException)`. 2. [Remove](https://dom.spec.whatwg.org/#concept-element-attributes-remove) attr. 3. Return attr. ___ [Element/attachShadow](https://developer.mozilla.org/en-US/docs/Web/API/Element/attachShadow "The Element.attachShadow() method attaches a shadow DOM tree to the specified element and returns a reference to its ShadowRoot.") In all current engines. Firefox63+Safari10+Chrome53+ ___ Opera40+Edge79+ ___ Edge (Legacy)NoneIENone ___ Firefox for Android63+iOS Safari10+Chrome for Android53+Android WebView53+Samsung Internet6.0+Opera Mobile41+ ``var shadow = element. `[attachShadow(init)](https://dom.spec.whatwg.org/#dom-element-attachshadow)` `` Creates a [shadow root](https://dom.spec.whatwg.org/#concept-shadow-root) for element and returns it. [Element/shadowRoot](https://developer.mozilla.org/en-US/docs/Web/API/Element/shadowRoot "The Element.shadowRoot read-only property represents the shadow root hosted by the element.") In all current engines. Firefox63+Safari10+Chrome35+ ___ Opera22+Edge79+ ___ Edge (Legacy)NoneIENone ___ Firefox for Android63+iOS Safari10+Chrome for Android35+Android WebView37+Samsung Internet3.0+Opera Mobile22+ ``var shadow = element. `[shadowRoot](https://dom.spec.whatwg.org/#dom-element-shadowroot)` `` Returns element’s [shadow root](https://dom.spec.whatwg.org/#concept-element-shadow-root), if any, and if [shadow root](https://dom.spec.whatwg.org/#concept-shadow-root)’s [mode](https://dom.spec.whatwg.org/#shadowroot-mode) is "`open`", and null otherwise. The `attachShadow(init)` method steps are: 1. If [this](https://webidl.spec.whatwg.org/#this)’s [namespace](https://dom.spec.whatwg.org/#concept-element-namespace) is not the [HTML namespace](https://infra.spec.whatwg.org/#html-namespace), then [throw](https://webidl.spec.whatwg.org/#dfn-throw) a "`[NotSupportedError](https://webidl.spec.whatwg.org/#notsupportederror)`" `[DOMException](https://webidl.spec.whatwg.org/#idl-DOMException)`. 2. If [this](https://webidl.spec.whatwg.org/#this)’s [local name](https://dom.spec.whatwg.org/#concept-element-local-name) is not one of the following: - a [valid custom element name](https://html.spec.whatwg.org/multipage/custom-elements.html#valid-custom-element-name) - "`article`", "`aside`", "`blockquote`", "`body`", "`div`", "`footer`", "`h1`", "`h2`", "`h3`", "`h4`", "`h5`", "`h6`", "`header`", "`main`", "`nav`", "`p`", "`section`", or "`span`" then [throw](https://webidl.spec.whatwg.org/#dfn-throw) a "`[NotSupportedError](https://webidl.spec.whatwg.org/#notsupportederror)`" `[DOMException](https://webidl.spec.whatwg.org/#idl-DOMException)`. 3. If [this](https://webidl.spec.whatwg.org/#this)’s [local name](https://dom.spec.whatwg.org/#concept-element-local-name) is a [valid custom element name](https://html.spec.whatwg.org/multipage/custom-elements.html#valid-custom-element-name), or [this](https://webidl.spec.whatwg.org/#this)’s [`is` value](https://dom.spec.whatwg.org/#concept-element-is-value) is not null, then: 1. Let definition be the result of [looking up a custom element definition](https://html.spec.whatwg.org/multipage/custom-elements.html#look-up-a-custom-element-definition) given [this](https://webidl.spec.whatwg.org/#this)’s [node document](https://dom.spec.whatwg.org/#concept-node-document), its [namespace](https://dom.spec.whatwg.org/#concept-element-namespace), its [local name](https://dom.spec.whatwg.org/#concept-element-local-name), and its [`is` value](https://dom.spec.whatwg.org/#concept-element-is-value). 2. If definition is not null and definition’s [disable shadow](https://html.spec.whatwg.org/multipage/custom-elements.html#concept-custom-element-definition-disable-shadow) is true, then [throw](https://webidl.spec.whatwg.org/#dfn-throw) a "`[NotSupportedError](https://webidl.spec.whatwg.org/#notsupportederror)`" `[DOMException](https://webidl.spec.whatwg.org/#idl-DOMException)`. 4. If [this](https://webidl.spec.whatwg.org/#this) is a [shadow host](https://dom.spec.whatwg.org/#element-shadow-host), then [throw](https://webidl.spec.whatwg.org/#dfn-throw) an "`[NotSupportedError](https://webidl.spec.whatwg.org/#notsupportederror)`" `[DOMException](https://webidl.spec.whatwg.org/#idl-DOMException)`. 5. Let shadow be a new [shadow root](https://dom.spec.whatwg.org/#concept-shadow-root) whose [node document](https://dom.spec.whatwg.org/#concept-node-document) is [this](https://webidl.spec.whatwg.org/#this)’s [node document](https://dom.spec.whatwg.org/#concept-node-document), [host](https://dom.spec.whatwg.org/#concept-documentfragment-host) is [this](https://webidl.spec.whatwg.org/#this), and [mode](https://dom.spec.whatwg.org/#shadowroot-mode) is init\["`[mode](https://dom.spec.whatwg.org/#dom-shadowrootinit-mode)`"\]. 6. Set shadow’s [delegates focus](https://dom.spec.whatwg.org/#shadowroot-delegates-focus) to init\["`[delegatesFocus](https://dom.spec.whatwg.org/#dom-shadowrootinit-delegatesfocus)`"\]. 7. If [this](https://webidl.spec.whatwg.org/#this)’s [custom element state](https://dom.spec.whatwg.org/#concept-element-custom-element-state) is "`precustomized`" or "`custom`", then set shadow’s [available to element internals](https://dom.spec.whatwg.org/#shadowroot-available-to-element-internals) to true. 8. Set shadow’s [slot assignment](https://dom.spec.whatwg.org/#shadowroot-slot-assignment) to init\["`[slotAssignment](https://dom.spec.whatwg.org/#dom-shadowrootinit-slotassignment)`"\]. 9. Set [this](https://webidl.spec.whatwg.org/#this)’s [shadow root](https://dom.spec.whatwg.org/#concept-element-shadow-root) to shadow. 10. Return shadow. The `shadowRoot` getter steps are: 1. Let shadow be [this](https://webidl.spec.whatwg.org/#this)’s [shadow root](https://dom.spec.whatwg.org/#concept-element-shadow-root). 2. If shadow is null or its [mode](https://dom.spec.whatwg.org/#shadowroot-mode) is "`closed`", then return null. 3. Return shadow. ___ [Element/closest](https://developer.mozilla.org/en-US/docs/Web/API/Element/closest "The closest() method traverses the Element and its parents (heading toward the document root) until it finds a node that matches the provided selector string. Will return itself or the matching ancestor. If no such element exists, it returns null.") In all current engines. Firefox35+Safari6+Chrome41+ ___ Opera28+Edge79+ ___ Edge (Legacy)15+IENone ___ Firefox for Android35+iOS Safari9+Chrome for Android41+Android WebView41+Samsung Internet4.0+Opera Mobile28+ ``element. `[closest(selectors)](https://dom.spec.whatwg.org/#dom-element-closest)` `` Returns the first (starting at element) [inclusive ancestor](https://dom.spec.whatwg.org/#concept-tree-inclusive-ancestor) that matches selectors, and null otherwise. [Element/matches](https://developer.mozilla.org/en-US/docs/Web/API/Element/matches "The matches() method checks to see if the Element would be selected by the provided selectorString -- in other words -- checks if the element "is" the selector.") In all current engines. Firefox34+Safari7+Chrome33+ ___ Opera21+Edge79+ ___ Edge (Legacy)15+IENone ___ Firefox for Android34+iOS Safari8+Chrome for Android33+Android WebView4.4+Samsung Internet2.0+Opera Mobile21+ ``element. `[matches(selectors)](https://dom.spec.whatwg.org/#dom-element-matches)` `` Returns true if matching selectors against element’s [root](https://dom.spec.whatwg.org/#concept-tree-root) yields element; otherwise false. The `closest(selectors)` method steps are: 1. Let s be the result of [parse a selector](https://drafts.csswg.org/selectors-4/#parse-a-selector) from selectors. [\[SELECTORS4\]](https://dom.spec.whatwg.org/#biblio-selectors4) 2. If s is failure, [throw](https://webidl.spec.whatwg.org/#dfn-throw) a "`[SyntaxError](https://webidl.spec.whatwg.org/#syntaxerror)`" `[DOMException](https://webidl.spec.whatwg.org/#idl-DOMException)`. 3. Let elements be [this](https://webidl.spec.whatwg.org/#this)’s [inclusive ancestors](https://dom.spec.whatwg.org/#concept
1,510
Repo: Yoojin99/Yoojin99.github.io ======================= File: _posts/App/swift/2021-05-09-MVC MVVM 패턴.md ======================= --- layout: post title: "Swift - MVC, MVVM 패턴" subtitle: "" categories: app tags: app-swift, mvvm, mvc comments: true header-img: --- > `MVC와 MVVM 패턴이 무엇인지 알아보자.` --- MVC, MVVM 등 개발할 때 많이 듣는 얘네들은 디자인 패턴이다. 디자인 패턴은 **공통으로 발생하는 문제에 대한 재사용 가능한 해결책**으로, 일반적인 문제에 대한 해결책들이 패턴화 되어 있기 때문이 디자인 패턴을 이용하면 더 효율적이고 빠르게 개발을 할 수 있는 것이다. 프레임워크와 라이브러리도 하나의 디자인 패턴으로 볼 수 있다. 참고로 디자인 패턴은 오래전부터 연구되던 소프트웨어 공학 분야이기 때문에 종류가 다양하다. ![image](https://user-images.githubusercontent.com/41438361/137414420-59dc607f-c9b3-443e-af57-76a7ef9463e7.png) 위와 같이 굉장히 다양한 패턴들이 많이 있는데, 이 중에서도 MVC 패턴은 Observer 패턴과 Mediator 패턴을 섞어놓은 패턴이다. ## MVC MVC는 Model + View + Controller를 합친 말로, observer pattern과 mediator pattern을 섞어놓은 것으로 알려져 있다. * observer pattern: 하나의 model에 다양한 view를 둬서 상태가 변할 때 그 모델을 구독하는 객체(observer)가 자동으로 갱신 됨 * mediator pattern: Observer pattern에서 M:N 관계가 많이 생성되면 전체가 복잡해지기 때문에 중간에 중재자(mediator)를 둬서 이벤트가 발생하고 전달하는 것을 단순화 함 그래서 Presentation 부분과 logic이 분리되어 앱의 여러 부분들을 간결하게 볼 수 있다는 이유로 버그 픽스에 유리하다. 핵심은 비즈니스 로직과 presentation layer를 분리해놓은 것이다. 이 패턴은 데스크탑 GUI(graphical user interface)에서 주로 사용된다. ### 구조 <img width="435" alt="스크린샷 2021-05-09 오후 2 18 14" src="https://user-images.githubusercontent.com/41438361/117561396-65f2da80-b0d1-11eb-9d70-61adec240d4a.png"> * Model : 어플리케이션에서 사용되는 **데이터**와 **데이터를 처리하는 부분이다.** 데이터, 알고리즘, DB 등을 Model이라 하는데, 앱이 **무엇**을 처리할 것인지를 정의한다. * View : 사용자에게 **보여지는 UI 부분**이다. 사용자에게 보여 줄 정보들을 Controller, Model에서 가져와서 보여주고, 입력을 받을 수 있다. * Controller : 사용자의 **입력(Action)을 받고 처리**하는 부분이다. Model이나 View의 요소들을 유저의 요청에 맞게 **어떻게** 처리 할 것인지를 정의한다. 위의 내용을 다시 말하자면 아래와 같다. * Model은 어떻게 보일지(View)나 어떻게 처리할지(Controller)에 대해 신경쓰지 않아도 된다. 데이터는 그 자체로 존재한다. * View는 데이터(Model)나 로직(Controller)를 신경쓰지 않고 이를 출력하는데만 관심 있다. * Controller는 무엇을 처리할지나 어떻게 출력할지는 관심이 없다. 그래서 각각 역할이 분리되어 있는데, 이렇게 역할이 확실히 분리될 수록 디자인 패턴이 잘 적용됐다고 할 수 있다. ### 동작 1. 사용자가 view와 상호작용한다. 2. View는 특정 이벤트를 controller에게 알린다. 3. Controller가 Model을 update한다. 4. Model이 자기가 바뀐 걸 Model에게 알린다. 5. View는 모델 데이터를 가져와서 자기 자신을 업데이트 한다. 참고로 View가 업데이트 되는 방법은 아래와 같이 세 가지 정도가 있다. * View가 Model을 이용해서 직접 업데이트 하는 방법 * Model에서 View에게 notify 해서 업데이트 하는 방법 * View가 Polling으로 주기적으로 Model의 변경을 감지해서 업데이트 ### 특징 Controller는 여러개의 View를 선택할 수 있는 1:n구조이다. Controller는 View를 선택할 뿐 직접 업데이트 하지 않는다. 여기서 View는 Controller를 모른다. ### 장점 가장 단순하고, 많이 사용되는 디자인 패턴이다. ### 단점 View-Model 간 의존성이 높다. 이렇게 의존성이 높아지면 어플리케이션이 커질수록 복잡해지고 유지보수를 어렵게 한다. ## MVP MVP는 Model + View + Presenter를 합친 용어다. Model과 View는 MVC 패턴과 동일하며, Controller대신 Presenter가 존재한다. <img width="442" alt="스크린샷 2021-05-09 오후 2 24 16" src="https://user-images.githubusercontent.com/41438361/117561489-3db7ab80-b0d2-11eb-82b0-44ee50e8fd93.png"> * Model : MVC와 동일하게 데이터와 데이터를 처리하는 부분이다. * View : MVC와 동일하게 사용자에게 보여지는 UI부분이다. * Presenter : View에서 요청한 정보로 Model을 가공해 View에 전달해주는 부분이다. View와 Model을 연결해주는 역할을 한다. ### 동작 1. Action은 View를 통해 들어간다. 2. View는 데이터를 Presenter에 요청한다. 3. Presenter는 Model에게 데이터를 요청한다. 4. Model은 Presenter에게 요청받은 데이터를 응답한다. 5. Presenter는 View에게 데이터를 응답한다. 6. View는 Presenter가 응답한 데이터를 이용해서 화면에 출력한다. ### 특징 Presenter가 View와 Model을 이어주는 중개자 역할을 한다. Presenter와 View는 1:1 관계다. 위의 MVC 패턴에서 View와 Controller의 관계는 n:1이었다. ### 장점 View와 Model의 의존성이 없다. MVP 패턴은 MVC 패턴의 단점이었던 View와 Model의 의존성을 해결했다. (Presenter를 통해서만 데이터를 전달받았기 떄문에) ### 단점 View와 Model 사이의 의존성은 해결되었지만 View-Presenter 사이의 의존성이 높게 된다. 어플리케이션이 복잡해질수록 View-Presenter 의 의존성이 강해진다. ## MVVM MVVM은 Model + View + ViewModel을 합친 용어다. MVVM은 MVC가 있는데 왜 등장한 것일까? 모든 것에 한계가 있듯이, MVC도 시스템의 규모가 커질수록 한계가 드러났다. * Model과 View가 M:N 관계로 복잡해진다. 의존성 문제가 생긴다. * 모든 로직, 처리가 Controller에게 전가 될 수 있다. 이럴 경우 controller의 역할이 매우 커져서 필요에 따라서는 model 쪽에 이런 로직들을 분산시켜 처리해야 한다. MVVM의 view model은 value converter로, 모델의 데이터 객체들을 관리하고 보여주기 쉽게 출력해야 한다는 역할을 가지고 있다. ### MVC vs MVVM? 이와 관련해서 [stackoverflow](https://stackoverflow.com/questions/667781/what-is-the-difference-between-mvc-and-mvvm)에서 굉장히 투표를 많이 받은 글이 있어서 가져와봤다. 일단 MVC/MVVM은 선택의 문제가 아니다. 두 패턴은 ASP.Net과 Silverlight/WPF 개발 모두에서 다른 방식으로 나타난다. ASP.Net에서 MVVM은 데이터와 뷰를 two-way binding을 하기 위해 사용된다. 참고로 two-way binding은 1. Model의 프로퍼티가 업데이트 되면, UI도 업데이트 된다. 2. UI 요소가 업데이트 되면, 이 변화가 model에 전달된다. 를 의미한다. ![image](https://user-images.githubusercontent.com/41438361/137417326-c2bc5edd-e834-4bec-a6bf-bebb24b7aa5e.png) 그림으로 나타내면 위와 같다. 그리고 MVC는 서버 단의 여러 문제들을 분리하기 위한 다른 방법이다. Silverlight와 WPF에서 MVVM 패턴은 MVC에 비해 포괄적이고, MVC의 대체재처럼 보일 수 있다. 이 패턴의 viewModel은 단순히 MVC의 controller 를 대체했다는 가정도 있다. **ViewModel이 별도의 Controller의 필요성을 꼭 대체하는 것은 아니다.** 즉 Controller 대신에 꼭 vm을 써야 하는 법은 없다는 소리다. 문제는 개별로 테스트가 가능해야 하고, 필요할 때 재사용 되기 위해 viewModel은 어떤 뷰가 출력하는지, 어디에서 데이터가 오는 지 알면 안된다. 보통 controller들은 unit test를 요구하는 로직들을 vm에서 제거한다. 이러면 vm은 굉장히 적은 양의 test를 요구하는 "멍청한" 컨테이너가 된다. 이는 vm을 디자이너와 코더 사이의 연결 고리로 만드는 좋은 경우가 되기 때문에 단순하게 만드는 것이 좋다. 하지만 여전히 컨트롤러를 만들어서 앱의 로직을 다루게 된다. **우리가 따르는 기본적인 MVCVM 가이드는 아래와 같다.** * 뷰는 데이터의 특정 형태를 출력한다. 데이터가 어디에서 오는지는 관심없다. * 뷰모델은 데이터와 커맨드의 특정 형태를 가지고 있고, 데이터나 코드가 어디에서 오는 지, 어떻게 출력되는지 모른다. * 모델은 실제 데이터를 가지고 있다. * 컨트롤러는 이벤트를 기다리고, 발생시킨다. 컨트롤러는 데이터를 다루는 로직을 제공한다. 또한 VM에 command code를 제공해서 VM이 재사용 가능하게끔 한다. MVVM이 MVC와 비교했을 때 C가 빠졌다고 해서 컨트롤러가 없어진 건 아니다. 컨트롤러는 그대로 있다. 오직 하나만이 추가됐는데, 바로 "상태"라는 것이다. 데이터는 클라이언트에 캐시되고, 이 데이터를 다룰 수 있게 되었다. 그리고 이제 이 클라이언트 쪽에 캐시된 데이터가 vm이라고 불리는 것이다. * MVC = model, controller, view = 단방향 커뮤니케이션 = poor interactivity * MVVM = model, controller, cache, view = 양방향 커뮤니케이션 = rich interacitivit ### 구조 <img width="432" alt="스크린샷 2021-05-09 오후 2 32 16" src="https://user-images.githubusercontent.com/41438361/117561628-5bd1db80-b0d3-11eb-9f09-73b27b0cd498.png"> * View Model : View를 표현하기 위해 만든 View를 위한 model이다. View를 나타내주기 위한 model이자 View를 나타내기 위한 데이터 처리를 하는 부분이다. ### 동작 1. Action은 View를 통해 들어온다. 2. View에 Action이 들어오면, Command 패턴으로 View Model에 Action이 전달된다. 3. View Model은 Model에게 데이터를 요청한다. 4. Model은 View Model에게 요청받은 데이터를 응답한다. 5. View Model은 응답 받은 데이터를 가공해 저장한다. 6. View는 View Model과 Data Binding해 화면을 나타낸다. ### 특징 MVVM 패턴은 Command 패턴과 Data Binding 패턴을 사용해 구현되었다. Command 패턴과 Data Binding을 이용해 View와 View Model간의 의존성을 없앴다. View Model과 View는 1:n 관계다. ### 장점 View - Model간의 의존성이 없다. 또한 Command / Data Binding을 사용해 View-View Model 의 의존성도 없앴다. 각 부분은 독립적이라 모듈화해서 개발할 수 있다. ### 단점 View Model의 설계가 쉽지 않다. 이제 MVVM이 대략적으로 무엇인지는 알았다. 그렇다면 이 MVVM을 왜 사용해야 하는가? 1. 가장 핵심적인 장점은 바로 `view`와 `model`의 분리다. 이거는 model에 변경을 가할 때도, view에는 영향이 가지 않는다는 소리가 된다. 2. 두번 째로, `model`이 `view`에서 필요한 모든 데이터를 보유하고 있는 동안, `model`이 지원하지 않는 방법으로 해당 데이터를 추출하고 싶을 수 있다. 예를 들어, model이 date 프로퍼티를 가진다고 해보자. 모델에서는 `DateTime`이라는 객체를 가지고 있을 수 있지만 view는 완전히 다른 방법으로 이것을 출력하고 싶다. `viewmodel` 없이는 view를 지원하거나 자칫'model'을 당황하게 만들 수 있는 해당 프로퍼티를 수정하는 작업을 위해 프로퍼티 위해 이 프로퍼티를 `model`에 중복되게 저장해야 한다. 3. 또한 `viewmodel`을 `view`가 처리할 수 있는 더 유연한 인터페이스를 활성화하기 위해 여러 클래스/라이브러리에 퍼져 있는 모델들을 종합할 수 있다. 이를 위해, `view`와 `viewmodel`간의 양방향 데이터 바인딩을 통해 이를 해결할 수 있다. 추가로 Stack Overflow에 이에 대한 좋은 글이 있어서 이를 번역해봤다. --- ### 요약 * 모든 패턴의 사용은 상황에 따라 다르며, 장점은 항상 얼마나 복잡성이 줄어들었는지에 따라 판단할 수 있다. * MVVM은 GUI 어플리케이션에서 클래스들 간 책임을 어떻게 분산 시키는지 가이드를 해준다. * ViewModel 은 Model의 데이터를 View에 적합한 형태로 가공한다. * '하찮은' 프로젝트에서 MVVM은 불필요하고, View를 사용하는 것으로 충분하다. * 간단한 몇몇 프로젝트에서 ViewModel/Model의 분리는 불필요하고, 오로지 Model과 View를 사용하는 것이 좋다. * Model과 ViewModel은 처음부터 있을 필요는 없고 필요할 때 도입되어도 된다. ### 언제 패턴을 사용하고 언제 사용하지 말지 간단한 어플리케이션에 디자인패턴을 적용하는 것은 과도한 일일 수 있다. 하나의 버튼이 있고 이를 누르면 "Hello World"를 띄우는 GUI 앱을 개발한다고 가정해보자. 이 경우네서는 MVC, MVP, MVVM과 같은 디자인 패턴은 오히려 복잡성을 더한다. 보통, 단순히 적용이 가능하다고 디자인 패턴을 적용하는 것은 항상 좋지 않은 결정이다. 디자인 패턴은 전체의 복잡성을 주림으로써 복잡도를 줄이거나, 별로 익숙하지 않은 복잡한 상황을 익순한 복잡한 상황으로 바꿔서 복잡도를 낮춰준다. 만약 앞의 이 2가지 방법 중 어느 것으로도 복잡도를 줄여주지 않는다면 디자인 패턴을 사용하지 말라. 익숙하고 익숙하지 않은 복잡도를 설명하기 위해, 아래의 두 문자열을 보도록 하자. * "D.€|Ré%dfà?c" * "CorrectHorseBatteryStaple" 아래의 문자열이 첫 번째 문자열보다 두 배의 길이지만, 우리에게 더 익숙하기 떄문에 더 읽기 쉽고, 쓰기 쉽고, 첫 번째 문자열보다 기억하기 쉽다. 이런 문제는 읽는 사람에 따라 익숙함의 정도가 다르다는 것을 고려할 때 다른 차원의 문제를 갖게 된다. 어떤 사람들은 위의 두 경우보다 "3.14159265358979323846264338327950"를 더 읽기 쉽다고 느낄 수 있지만, 그렇지 않은 사람도 있을 것이다. 그래서 만약 MVVM을 사용하고 싶으면, 사용하고 있는 특정 언와 픞레임 워크에서 가장 많이 쓰이는 형태를 미러링하는(표현하는)것을 사용하도록 해라. ### MVVM MVVM은 GUI 어플리케이션에서 각 클래스의 크기가 작고 잘 정의되어 있으면서 이런 클래스들의 수를 적게 유지한 상태에서 클래스들 간의 책임을 분산하는 것을 가이드 해준다. '적절한' MVVM은 최소한 "어딘가"에서 데이터를 가져와서 처리하는 복잡한 어플리케이션임을 가정하는 상황에서 출발한다. 데이터베이스, 파일, 웹 서비스 등에서 데이터를 가져올 수 있다. #### 예시 `View`와 `Model`의 클래스 두 개가 있다. `Model`은 처음에 csv 파일을 읽고 앱이 종료되면 유저가 변경한 사항을 저장한다. `View`는 `Model`에서 데이터를 가져오고 데이터를 수정할 수 있게 해주는 윈도우 class다. csv는 아래와 같은 내용일 수 있다. ``` ID, Name, Price 1, Stick, 5$ 2, Big Box, 10$ 3, Wheel, 20$ 4, Bottle, 3$ ``` 그런데 새로운 요구사항이 들어왔다 : 가격을 유로로 표시하는 것이다. 이제 앱에 변화를 줘야 한다. 데이터는 이미 USD로 가격을 표시하는 "가격" 열이 있다. 우리는 USD에 이어서 미리 정의된 환율로 유로로 가격을 표시하는 새로운 열을 추가해야 한다. csv 파일의 형태는 우리가 통제할 수 없는 다른 앱에서도 이 파일을 이용하기 때문에 변경되면 안된다. 이 문제를 해결하는 방법 중 하나는 단순히 `Model` 클래스에 새로운 열을 추가하는 것이다. 이것은 `Model`이 csv의 모든 데이터를 저장하고 있고 우리는 새로운 유로 가격에 대한 열이 csv에 포함되는 것을 원하지 않기 때문에 좋은 해결책이 아니다. 그래서 `Model`을 변경하는 것은 별로 좋은 방법이 아니고, 모델이 어떤 역할을 하는지 설명해지기 어렵기 때문에 code smell 에 해당한다. 우리는 `View`를 변경할 수도 있다. 하지만 우리의 어플리케이션이 --- ## 코드로 MVVM 구현하기 먼저 Model은 Class, Struct 등으로 정의된다. 코드를 작성하기 앞서 먼저 playground 에 아래와 같이 두 줄의 Import 문을 추가해준다. ```swift import PlaygroundSupport import UIKit ``` ### Model 구현하기 ```swift public class Pet { public enum Cuteness { case cute case veryCute case veryVeryCute } public let name: String public let birthday: Date public let cuteness: Cuteness public let image: UIImage public init(name: String, birthday: Date, cuteness: Cuteness, image: UIImage) { self.name = name self.birthday = birthday self.cuteness = cuteness self.image = image } } ``` 위와 같이 Pet 모델을 정의했다. Pet은 이름, 생일, 귀여움, 이미지를 프로퍼티로 갖고 있고, 이 값들을 생성자로 받아 초기화된다. **Pet 모델은 View에 독자적으로 출력될 수 없다. Model은 ViewModel을 거쳐 View에 출력된다. ViewModel을 통해 View에 출력될 값으로 변환되어 사용된다.** ### ViewModel 구성하기 ViewModel은 Pet Model을 View에 출력할 수 있는 값으로 변환해준다. ```swift public class PetViewModel { // 1. pet 객체 생성, 나이 연산 위한 Calendar도 생성 private let pet: Pet private let calendar: Calendar public init(pet: Pet) { self.pet = pet calendar = Calendar(identifier:.gregorian) } // 2. name : pet 이름을 반환한다. public var name: String { return pet.name } // 3. image : pet 이미지를 반환한다. public var image: UIImage { return pet.image } // 4. ageText : pet 나이를 연산해 반환한다. public var ageText: String { let today = calendar.startOfDay(for: Date()) let birthday = calendar.startOfDay(for: pet.birthday) let components = calendar.dateComponents([.year], from: birthday, to: today) let age = components.year! return "\(age) years old" } // 5. cuteText: 해당 펫의 귀염도에 따라 얼마나 귀여운지 text를 반환한다. public var cuteText: String { switch pet.cuteness { case.cute: return "Cute" case.veryCute: return "Very Cute" case.veryVeryCute: return "Very Very Cute" } } } ``` 위 코드는 Model, pet이 거치는 viewModel, PetViewModel을 정의하고 있다. ### View 구성하기 ```swift public class PetVIew: UIView { public let imageVIew: UIImageView public let nameLabel: UILabel public let ageLabel: UILabel public let cuteLabel: UILabel public override init(frame: CGRect) { var childFrame = CGRect(x : 0, y: 16, width: frame.width, height: frame.height / 2) imageVIew = UIImageView(frame: childFrame) imageVIew.contentMode =.scaleAspectFit childFrame.origin.y += childFrame.height + 16 childFrame.size.height = 30 nameLabel = UILabel(frame: childFrame) nameLabel.textAlignment =.center nameLabel.textAlignment =.center childFrame.origin.y += childFrame.height ageLabel = UILabel(frame: childFrame) ageLabel.textAlignment =.center childFrame.origin.y += childFrame.height cuteLabel = UILabel(frame: childFrame) cuteLabel.textAlignment =.center super.init(frame: frame) backgroundColor =.white addSubview(imageVIew) addSubview(nameLabel) addSubview(ageLabel) addSubview(cuteLabel) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } ``` 출처 * https://beomy.tistory.com/43 * https://0urtrees.tistory.com/112 * https://stackoverflow.com/questions/1644453/why-mvvm-and-what-are-its-core-benefits/1644955#1644955 * https://stackoverflow.com/questions/2653096/why-use-mvvm * https://samslow.github.io/development/2020/06/16/Design_pattern-MVC/ ======================= File: _posts/CS/컴네/2020-09-25-http 상태 코드.md ======================= --- title: "HTTP 상태 코드" excerpt: "" toc: true toc_sticky: true toc_label: "페이지 주요 목차" header: teaser: categories: - Network tags: - cs-cn - http - 상태태그 last_modified_at: --- [HTTP 상태 코드 설명 사이트](https://developer.mozilla.org/ko/docs/Web/HTTP/Status) HTTP 응답 상태 코드는 특정 HTTP 요청이 성공적으로 완료되었는지 알려준다. 응답은 5개의 그룹으로 나누어진다. 1. 정보를 제공하는 응답 2. 성공적인 응답 3. 리다이렉트 4. 클라이언트 에러 5. 서버 에러 ## 1. 정보 응답 `100 Continue` 이 응답은 지금까지의 상태가 괜찮으며 클라이언트가 계속해서 요청을 하거나 이미 요청을 완료한 경우에는 무시해도 되는 것을 알려준다. `101 Switching Protocol` 클라이언트가 보낸 `Upgrade` 요청 헤더에 대한 응답에 들어가며 서버에서 프로토콜을 변경할 것임을 알려준다. `102 Processing` (WebDAV) 서버가 요청을 수신했고 처리하고 있지만, 아직 제대로 된 응답을 알려줄 수 없음을 나타낸다. `103 Early Hints` 주로 `Link` 헤더와 함께 사용되어 서버가 응답을 준비하는 동안 사용자 에이전트가 사전 로딩(preloading)을 시작할 수 있게 해준다. ## 2. 성공 응답 `200 OK` 요청이 성공적으로 처리되었다. 성공의 의미는 HTTP 메소드에 따라 달라진다. * GET : 리소스를 불러와서 메세지 바디에 전송하였다. * HEAD : 개체 헤더가 메세지 바디에 있다. * PUT/POST : 수행 결과에 대한 리소스가 메세지 바디에 전송되었다. * TRACE : 메세지 바디가 서버에서 수신한 요청 메세지를 포함하고 있다. `201 Created` 요청이 성공적이었고 그 결과로 새로운 리소스가 생성되었다. 일반적으로 POST 요청 또는 일부 PUT 요청 이후에 따라온다. `202 Accepted` 요청을 수신했지만 그에 응해 행동할 수 없다. 이 응답은 요청 처리에 대한 결과를 이후에 HTTP로 비동기 응답을 보내는 것에 대해 명확하게 명시하지 않는다. 이것은 다른 프로세스에서 처리 또는 서버가 요청을 다루고 있거나 배치 프로세스를 하고 있는 경우를 위해 만들어졌다. `` ======================= File: _posts/App/iOS/2021-07-21-Diff 사용하기.md ======================= <filename>_posts/App/iOS/2021-07-21-Diff 사용하기.md --- layout: post title: "[iOS] - Diff 사용해서 UICollectionView data reload하기" subtitle: "" categories: app tags: app-ios comments: true header-img: --- > `Ordered collection diffing을 사용해서 UICollectionView의 데이터를 효율적으로 reload하자.` --- # Diff ## Diff란? 한 collection에서 다른 collection으로의 변환을 도와주는 기능 * 기존의 문제점 : 상태를 표현하고, 구성하고, 두 상태 간의 transaction을 적용하는 코드는 복잡하고, 에러가 발생할 확률이 높다. ➡️ diff를 이용해서 collection 타입에 변화를 적용하기 쉬워졌다. * iOS -> iOS 13.0, swift 5.1 \~ * [diff](https://github.com/apple/swift-evolution/blob/master/proposals/0240-ordered-collection-diffing.md) *![image](https://user-images.githubusercontent.com/41438361/126445675-f11d5745-5976-4b30-9915-c88fdd41dbb3.png) *![image](https://user-images.githubusercontent.com/41438361/126445692-185992a7-8d8b-400f-80a3-ed6b8b83ef9f.png) ## Diff ![image](https://user-images.githubusercontent.com/41438361/126445715-7f02053b-59c5-43c5-858f-aa8e47db923b.png) "BEAR" -> "BIRD" ![image](https://user-images.githubusercontent.com/41438361/126445729-aa075011-37b4-42da-864f-32d0444ddd5c.png) * "E", "A" remove * "I", "D" insert **기존(예시)** 1. "BEAR", "BIRD" 비교 2. "BEAR"에서 remove 해야 하는 부분 찾아서 index를 이용해 삭제 3. "BIRD"가 되기 위해 insert 해야 하는 부분 찾아서 올바른 index에 추가 👎 지금은 간단한 문자열, 데이터가 복잡하지 않아서 쉬운 작업일 수 있으나, 데이터가 복잡한 경우 이런 작업들이 쉽지 않음. index를 일일이 찾아서 remove, insert를 하는 작업도 귀찮고, 올바르지 않은 index를 대입하게 될 가능성 있음 **diff를 사용한다면?** *ios* ![image](https://user-images.githubusercontent.com/41438361/126445745-b1c79a54-fc59-422c-85e0-32e6be11ee93.png) 1. 두 collection(여기서는 글자의 collection인 문자열)의 차이 받기 2. 차이(변화) 적용하기 👍어떤 `index`의 어떤 `element`에 어떤 `operation`을 해야 하는지 직접 계산할 필요 없음, 코드도 간단해짐 여기에서 diff를 출력하면 아래와 같이 나오는데, 즉 필요한 최소한의 연산들을 수행해야 하는 인덱스와 함께 보여준다. ![image](https://user-images.githubusercontent.com/41438361/126598038-68fa4fb5-0e4a-481e-a3b9-3d446515bb9e.png) **적용할 수 있는 element의 조건?** * [swift github](https://github.com/apple/swift/blob/7123d2614b5f222d03b3762cb110d27a9dd98e24/stdlib/public/core/Diffing.swift) ![image](https://user-images.githubusercontent.com/41438361/126445771-300d7c50-fa36-4e1d-84ed-53f130e81188.png) ![image](https://user-images.githubusercontent.com/41438361/126445783-01d5ca7d-ffb6-4b81-92f4-3ea3e50b2a36.png) ![image](https://user-images.githubusercontent.com/41438361/126446560-b7dde81c-0ba6-465c-af96-d59ae2ea4514.png) * `Equatable`을 따르는 타입의 element에 적용가능 *![image](https://user-images.githubusercontent.com/41438361/126445792-9da8ac4f-0859-4317-a195-cc268a06c608.png) 객체간 동일성 체크를 해야 하는데, 객체가 복잡할 경우 Equatable 함수를 실행하는 데 시간이 오래 걸릴 수 있음. `Equatable`을 따르는 `Hashable`을 element가 따르게 해서 hash value로 비교하게 해서 실행 시간을 줄일 수 있다. [출처](https://medium.com/flawless-app-stories/a-better-way-to-update-uicollectionview-data-in-swift-with-diff-framework-924db158db86) **diff의 원리?** 알고리즘까지 설명하기에는 글이 너무 길어져서 [이 글](https://yoojin99.github.io/app/Diff-%EC%9B%90%EB%A6%AC/)을 통해 따로 작성했다. 추가로 diff에 대한 간단한 사용법, 설명을 보려면 [이 글](https://yoojin99.github.io/app/Ordered-Collection-Diffing/)을 참고하면 된다. ### 어디에 사용할까? CollectionView와 함께 사용하면 유용하다. CollectionView에 데이터를 출력하기 위해 백엔드에서 데이터를 불러오고, 데이터에 변화가 생겼을 때 이 변화(특정 아이템이 추가/삭제됨)를 인터페이스에 반영하기 위해 인터페이스를 업데이트한다. iOS의 경우, 여기에서 전체 리스트를 새로운 데이터로 새로고침하는 `reloadData`를 사용하기 쉽다. 하지만 `reloadData`를 사용해서 전체 데이터를 새로고침하면 아래와 같은 문제점이 있다. 1. `UITableView`의 경우 cell size를 다시 계산해야 하므로 성능을 저하시킨다. 2. 모든 cell, header, footer에 변화가 없다 해도 reload를 하므로 비효율적이다. 3. `reloadData`는 세부적인 컨트롤이나 일어나는 변화를 애니메이션으로 보여주지 않는다. 따라서 변화가 일어나는 것을 사용자에게 보여주기 위해서 직접 CollectionView에 행을 추가하고 삭제하는 편이 선호된다. ## CollectionView 아래와 같이 여러 사진이 있고, 하단의 reload data 버튼을 누르면 랜덤으로 출력해야 하는 이미지들의 개수, 순서가 바뀌는 화면이 있다. 전체 프로젝트의 코드를 보려면 [여기](https://github.com/Yoojin99/Diff-With-CollectionView)를 참고하면 된다. ![image](https://user-images.githubusercontent.com/41438361/126445814-f0c75c3f-a260-4763-9b19-bf60bc60ffdd.png) ### 데이터가 적고 간단한 경우 * 최대 데이터 개수가 3개임을 가정 **`reloadData`로 데이터를 reload할 때** * 코드 ![image](https://user-images.githubusercontent.com/41438361/126445834-abca5b29-fb66-411c-98ec-21b04e013cd7.png) * 실행화면 *![simpleReload](https://user-images.githubusercontent.com/41438361/126445872-7bbb351a-dc69-491f-916c-a15c9d462c26.gif) * 애니메이션이 보여지지 않음 * 비효율적인 방법(그나마 데이터가 적어서 괜찮음) **직접 로직을 짜서 데이터를 reload 할 때** * 데이터 전체를 새로운 데이터로 Reload하는 작업은 비효율적이므로 모든 데이터를 reload하지 않고 특정 item을 삭제, 추가해서 Reload할 경우 * 코드 ![image](https://user-images.githubusercontent.com/41438361/126445895-5c2269ad-b862-4898-9b6e-1651b88d62e0.png) * 원래 데이터에서 삭제 되어야 하는 item, 변할 데이터에서 새로 추가되는 item들을 모두 계산하고 이 새로운 item들을 추가해야 하는 index를 계산하기도 쉽지 않음 ❗️또 다른 문제는 데이터가 많고 데이터가 변하는 과정이 복잡해질 때 발생 ### 데이터가 많고 변하는 과정이 복잡한 경우 **`reloadData`로 데이터를 reload할 때** * 실행화면 ![complexReload](https://user-images.githubusercontent.com/41438361/126445932-03d18a16-a7f8-48ae-b9b8-df2b80e05fe8.gif) * 빨라서 잘 보이지 않지만, 모든 이미지가 완전히 다시 로딩되는 것을 볼 수 있음. cell을 재활용하는데 이미지를 다시 다운 받을 필요는 없는데 이런 작업이 수행되고 있음을 확인할 수 있음 * 지금도 데이터의 개수가 충분히 많지 않아 빠른 시간 내 reload가 수행이 되지만, 한 cell을 출력하기 위해 오래 다운로드를 수행하는 작업이 있을 경우 한 번 reload 해서 모든 cell을 보기까지 굉장히 오래 걸릴 것임. **diff를 사용해서 데이터를 reload 할 때** * 코드 *![image](https://user-images.githubusercontent.com/41438361/126445953-b3d47b9d-f38b-4eb4-95d9-e162c956add2.png) * diff가 삭제되어야 하는 item들, 추가되어야 하는 item들이 어떤 index에서 연산이 일어나야 하는지까지 모두 계산해서 알려줌 * 따라서 UI를 업데이트 해야 하는 부분에서 삭제되어야 하는 item들은 삭제하고, 추가되어야 하는 item들을 추가하는 작업을 수행하는 코드를 작성하면 끝이다. * 실행화면 ![complexReloadDiff](https://user-images.githubusercontent.com/41438361/126445983-b966b084-cea7-41f0-8864-122c668eb143.gif) * 재사용되는 cell들을 제외하고 새롭게 추가되는 item들에만 이미지가 다운로드 되는 것을 확인할 수 있다. * 애니메이션도 잘 보여진다. ## 결론 * CollectionView에서 데이터를 reload 할 때, diff를 사용하면 효율적으로 데이터를 Reload할 수 있다. * 데이터가 많고, 데이터가 변하는 과정이 복잡하다면 diff를 사용하는 것이 효율적이다. ======================= File: _featured_tags/game-unity.md ======================= <gh_stars>1-10 --- layout: tag-blog title: Unity slug: game-unity category: game menu: false order: 1 --- Unity ======================= File: _posts/soso/2020-11-13-비즈니스 로직.md ======================= <gh_stars>1-10 --- title: "비즈니스 로직" excerpt: "" categories: - soso tags: - 비즈니스 로직 last_modified_at: 2020-11-13 --- 비즈니스 로직(Buisness logic)이란 무엇일까? 비즈니스 로직을 설명하기 위해 3가지 방법으로 말 할 수 있다. 1. 데이터베이스와 사용자 인터페이스 사이의 정보 교환을 처리하는 알고리즘을 설명하는데 사용하는 비기술적 용어 2. 필요한 데이터처리를 수행하는 응용 프로그램의 일부. 데이터 입력, 수정, 조회, 보고서 처리 등을 수행하는 루틴, 더 자세히 말하면 보이는 것의 그 뒤에서 일어나는 각종 처리를 의미한다. 일반적으로 클라이언트 프로그램은 사용자 인터페이스와 비즈니스 로직으로 구성되고, 서버 프로그램은 대부분 비즈니스 로직만으로 되어 있다. 클라이언트/서버모델인 경우에는 통신링크가 추가되지만, 통신과 관련된 infrastructure는 사용자 인터페이스처럼 비즈니스 로직의 일부는 아니다. 3. 하나의 프로젝트나 프로그램 중 업무와 관련된 처리를 하는 일부분을 말한다. 프로젝트를 하면서 데이터베이스에서 어떤 자료를 가져와서 웹에 출력을 할 때 데이터베이스 연결, 통신, 자료가공, 페이지 구성 등 여러가지 작업을 하지만 그 중에서 사용자가 원하는 자료의 가공 부분을 의미한다. 예를 들어 자료를 저장할 때는 부가세가 포함되지 않고 자료가 저장되어 있는데, 사용자에게 부가세가 포함된 자료를 디스플레이 해야 하는 업무를 처리해야 한다고 할 때 이를 처리하는 과정을 의미한다. ======================= File: _posts/CS/2020-07-13-깊은복사얕은복사.md ======================= --- title: "얕은 복사(shallow copy) vs 깊은 복사(deep copy)" excerpt: "" toc: true toc_sticky: true toc_label: "페이지 주요 목차" header: teaser: categories: - cs tags: - 공부 - 얕은 복사 - 깊은 복사 last_modified_at: --- 얕은 복사(shallow copy) vs 깊은 복사(deep copy) ======================== 객체의 복사는 얕은 복사와 깊은 복사로 나뉜다. ## 1. 단순 객체 복제 변수만 복사하면 변수가 가리키는 객체는 당연 동일할 것이다. 즉, 두 개의 변수 중 하나만 변경 되어도 나머지 하나도 동일하게 수정된다. ```python a = [1, 2, 3, 4] b = a # shallow copy print(b) # [1, 2, 3, 4] b[2] = 100 # b의 item 변경 print(b) # [1, 2, 100, 4] print(a) # [1, 2, 100, 4], a의 item도 수정됨!! ``` 리스트를 만들어서 변수 a에 할당하였다. 그러면 a는 리스트 객체의 주소를 바라보는 변수가 된다. 그 다음 a를 b에 할당했다. 이러면 b가 a와 같은 객체의 주소를 바라보게 되는 것이다. 만약 a나 b를 이용해서 수정을 하면 어떻게 되는지 보자. 중간에 b의 2번째 인덱스에 접근하여 100으로 바꿔주었다. 이러면 a까지 b처럼 2번째 인덱스의 값이 100으로 바뀌게 된다. 이런 문제는 a와 b가 동일한 객체를 참조하기 떄문에 발생한다. 이때 주의할 점은 위처럼 복사된 참조 변수를 수정했을 때, 처음에 할당한 참조 변수의 값 역시 똑같이 수정되는 거는 변경가능(mutable) 객체일 때만 해당된다. 숫자나 문자열과 같이 불변의(immutable) 객체일 때는 이렇게 되지 않는다. ```python a = 10 b = a print(b) # 10 출력 b = "abc" print(b) # abc 출력 print(a) # 10 출력 ``` 이 경우는 string이 immutable에 해당하기 때문에 이렇게 된다. 불변의 객체는 값이 바뀌지 않는 객체를 말한다. 따라서 참조변수를 수정한다는 것은 주소의 값(value)가 바뀌는 것이 아니라 그 변수에 새로운 객체가 할당되는 것을 의미한다. ## 2. 얕은 복사 단순복사와 구별되는 얕은 복사의 차이점은 복합객체(리스트)는 별도로 생성하지만 그 안에 들어가는 내용은 원래와 같은 객체라는 점이다. ```python import copy a = [1, [1, 2, 3]] b = copy.copy(a) # shallow copy 발생 print(b) # [1, [1, 2, 3]] 출력 b[0] = 100 print(b) # [100, [1, 2, 3]] 출력, print(a) # [1, [1, 2, 3]] 출력, shallow copy 가 발생해 복사된 리스트는 별도의 객체이므로 item을 수정하면 복사본만 수정된다. (immutable 객체의 경우) c = copy.copy(a) c[1].append(4) # 리스트의 두번째 item(내부리스트)에 4를 추가 print(c) # [1, [1, 2, 3, 4]] 출력 print(a) # [1, [1, 2, 3, 4]] 출력, a가 c와 똑같이 수정된 이유는 리스트의 item 내부의 객체는 동일한 객체이므로 mutable한 리스트를 수정할때는 둘다 값이 변경됨 ``` 리스트 내에 리스트가 있는 경우에 얕은 복사(b = copy.copy(a))가 이뤄지더라도 리스트 내의 내부 리스트까지 별도의 객체로 복사가 되는 것은 아니다. 위에서 b에서 첫번째 인덱스의 숫자를 변경했을 때 a가 바뀌지 않은 것은 그 요소가 immutable하기 때문이다. 그래서 요소가 수정이 되는 것이 아니라 그냥 다른 값으로 대체가 되는 것이다. 그래서 b에서 변경한 요소가 a에는 반영이 되어 있지 않은 것이다. 하지만 c를 보면 얘는 얘기가 다르다. a를 복사해서 c를 만들고, c의 두번째 요소(리스트)에 새로운 값을 출력했다. c의 내부리스트를 수정하게 되면 a의 내부 리스트 또한 바뀌는 것을 확인할 수 있는데, 그 이유는 a와 c의 내부리스트는 같은 객체를 참조하고 있기 때문이다. b의 경우에도 같은 객체라고 할 수 있지만, 객체가 mutable하냐 immutable 하냐의 차이로 결과가 갈리게 된다. mutable한 경우에는 값이 수정될 수 있지만, immutable한 경우에는 값이 수정되는 것이 아니라 아예 새로운 객체로 변경이 되는 것이다. ## 3. 깊은 복사 mutable한 내부객체(내부리스트)의 문제를 해결하기 위해서는 얕은 복사가 아니라 깊은 복사를 해야 한다. 얕은 복사가 복합객체(리스트)만 복사되고 그 안의 내용은 동일한 객체를 참조한다면, 깊은 복사에서는 복합객체를 새롭게 생성하고 그 안의 내용까지 재귀적으로 새롭게 생성하게 된다. 그래서 깊은 복사를 하게 되면 처음에 만든 객체와 복사된 객체가 아예 다른 객체이기 때문에 한쪽을 수정한다고 다른 쪽이 영향 받는 일은 없다. ```python import copy a = [1, [1, 2, 3]] b = copy.deepcopy(a) # deep copy 실행 print(b) # [1, [1, 2, 3]] 출력 b[0] = 100 b[1].append(4) print(b) # [100, [1, 2, 3, 4]] 출력 print(a) # [1, [1, 2, 3]] 출력 ``` 정리하면 다음과 같다. 1.단순복제는 완전히 동일한 객체, 2. 얕은복사(shallow copy)는 복합객체(껍데기)만 복사, 그 내용은 동일한 객체 3. 깊은복사(deep copy)는 복합객체 복사 + 그 내용도 재귀적으로 복사 ======================= File: _featured_tags/cs-dp.md ======================= --- layout: tag-blog title: Design Pattern slug: cs-dp category: cs menu: false order: 2 --- 디자인 패턴 ======================= File: _posts/JS/2020-08-21-7. for에서의 주의사항.md ======================= <reponame>Yoojin99/Yoojin99.github.io<gh_stars>1-10 --- title: "JavaScript - for문에서의 주의사항" excerpt: "" toc: true toc_sticky: true toc_label: "페이지 주요 목차" header: teaser: categories: - js tags: - 공부 - JavaScript - let last_modified_at: --- ```javascript var obj = { prop1 : 1, prop2 : 2, prop3 : 3 } for(const prop in obj){ console.log(prop) } // prop -> prop1 // prop -> prop2 // prop -> prop3 for(const i = 0; i < 5; i++){ console.log(i) } // 에러가 난다. 계속 i를 재할당하려고 해서 문제가 된다. ``` for in 문만 특이하다. ======================= File: _featured_tags/cs-cs.md ======================= <filename>_featured_tags/cs-cs.md --- layout: tag-blog title: Computer Structure slug: cs-cs category: cs menu: false order: 5 --- 컴퓨터구조 ======================= File: _posts/App/swift/2020-11-17-Swift란.md ======================= --- title: "" excerpt: "" toc: true toc_sticky: true toc_label: "페이지 주요 목차" header: teaser: categories: - app tags: - app-swift - iOS - Swift last_modified_at: 2020-10-18 --- Swift는 안정성, 성능, 그리고 소프트웨어 디자인 패턴에 현대적 접근법을 사용해 만든 일반-목적 프로그래밍 언어이다. Swift 프로젝트의 목표는 시스템 프로그래밍, 모바일 테스크탑 앱부터 클라우드 서비스까지 어우르는 가장 좋은 언어를 만드는 것이다. 가장 중요한 것은, Swift는 개발자가 올바른 프로그램을 만들고 유지하는데 쉽게 하기 위해 디자인 되었다. 이 목표를 달성하기 위해, 우리는 Swift 코드를 작성하는게 다음과 같다는 것을 믿어야 한다.(알아야 한다.) ## Safe 정의되지 않은 행동들은 안정성의 적이고, 이런 개발자들의 실수는 소프트웨어의 발행 전에 잡혀야 한다. 안전을 선택하는 것은 Swift가 엄격하게 느껴질 수 있게 하는 것이지만, 우리는 이런 명확성이 오랜 시간 개발하는 것에서 시간을 절약해준다고 믿는다. ## Fast Swift는 C 기반 언어의 대체재로 의도되어 만들어졌다(C, C++, Objective-C). Swift는 성능면에서 이런 언어들에 뒤쳐지지 않아야 한다. 성능은 일정하고 예측이 가능해야 한다. 단순히 빠르고 후에 수습할게 많은 이런 것은 안된다. ## Expressive Swift는 개발자들이 기대하는 현대적인 특징들과 함께 사용하기 좋은 문법을 제공한다. ======================= File: _posts/ChatBot/MSAzure/2020-07-10-사용자환영하기.md ======================= --- title: "Chatbot - 사용자 환영하기" excerpt: "사용자에게 환영 메세지 보내기" toc: true toc_sticky: true toc_label: "페이지 주요 목차" header: teaser: categories: - cb tags: - cb-ma - 공부 - Azure last_modified_at: --- 사용자에게 환영 메세지 보내기 ========== 봇 예제에서는 아래 그림과 같이 플로우가 발생한다. ![welcome-user-flow](https://user-images.githubusercontent.com/41438361/87150471-12670300-c2ed-11ea-81dc-f1053d341dca.png) * OnMembersAddedAsync : 봇에 새 사용자가 연결될 때마다 호출 * OnMessageActivityAsync : 새 사용자 입력이 수신될때마다 호출. message 작업을 처리하도록 한다. 새 사용자가 연결될 떄마다 봇이 WelcomMessage, InfoMessage, PatternMessage를 표시한다. 새로운 사용자 입력이 들어오면 봇이 WelcomeUsertate의 DidBotWelcomeUser를 체크한다. 만약 false이면 환영 메세지를 보낸다. ## 사용자 상태 만들기 사용자 상태 개체는 시작시 만들어지고 종속성이 봇 생성자에 들어간다. **Startup.cs** ```C# // Create the storage we'll be using for User and Conversation state. (Memory is great for testing purposes.) services.AddSingleton<IStorage, MemoryStorage>(); // Create the User state. services.AddSingleton<UserState>(); ``` **Bots/WelcomeUserBot.cs** ```C# private BotState _userState; // Initializes a new instance of the "WelcomeUserBot" class. public WelcomeUserBot(UserState userState) { _userState = userState; } ``` ## 속성 접근자 만들기 OnMessageActivityAsync method에서 WelcomeUserState 에 대한 핸들을 제공하는 속성 접근자를 만든다. 이 속성 접근자를 만드는 거는 대화 및 상태 저장에서 다뤘었다. 속성 접근자를 만든다음, GetAsync method를 호출하여(getasync를 사용해서 상태 속성과 연결된 올바른 범위의 키를 가져온다고 했었다.) 올바른 범위로 저장된 키를 가져온다. 그리고 SaveChangesAsync method를 사용하여 상태 데이터를 저장한다. **Bots/WelcomeUserBot.cs** ```C# protected override async Task OnMessageActivityAsync(ITurnContext<IMessageActivity> turnContext, CancellationToken cancellationToken) { var welcomeUserStateAccessor = _userState.CreateProperty<WelcomeUserState>(nameof(WelcomeUserState)); var didBotWelcomeUser = await welcomeUserStateAccessor.GetAsync(turnContext, () => new WelcomeUserState()); // Save any state changes. await _userState.SaveChangesAsync(turnContext); } ``` ## 새로 연결된 사용자 감지 및 인사하기 WelcomeUserBot에서 OnMembersAddedAsync()를 통해 활동 업데이트를 확인하여 새로운 사용자가 대화에 추가되었는지 본 다음, 초기에 환영 메세지 3개(WelcomMessage, InfoMessage, PatternMessage)를 전송한다. **Bots/WelcomeUserBot.cs** ```C# protected override async Task OnMembersAddedAsync(IList<ChannelAccount> membersAdded, ITurnContext<IConversationUpdateActivity> turnContext, CancellationToken cancellationToken) { foreach (var member in membersAdded) { if (member.Id!= turnContext.Activity.Recipient.Id) { await turnContext.SendActivityAsync($"Hi there - {member.Name}. {WelcomeMessage}", cancellationToken: cancellationToken); await turnContext.SendActivityAsync(InfoMessage, cancellationToken: cancellationToken); await turnContext.SendActivityAsync(PatternMessage, cancellationToken: cancellationToken); } } } ``` ## 새 사용자를 환영하고 초기 입력 무시 사용자 입력에 유용한 정보가 포함되었는지 확인하는 것도 중요하다. didBotWelcomeUser 상태 플래그를 확인해서 "False"인 경우 초기 사용자 입력을 처리하지 않고, 대신 초기 환영 메세지를 전송한다. 전송 후에는 welcomedUserProperty bool값이 "true"로 설정되어 UserState에 저장된다. 그리고 사용자 입력을 처리할 수 있게 하는 것 같다. **Bots/WelcomeUserBot.cs** ``` protected override async Task OnMessageActivityAsync(ITurnContext<IMessageActivity> turnContext, CancellationToken cancellationToken) { var welcomeUserStateAccessor = _userState.CreateProperty<WelcomeUserState>(nameof(WelcomeUserState)); var didBotWelcomeUser = await welcomeUserStateAccessor.GetAsync(turnContext, () => new WelcomeUserState()); if (didBotWelcomeUser.DidBotWelcomeUser == false) { didBotWelcomeUser.DidBotWelcomeUser = true; // the channel should sends the user name in the 'From' object var userName = turnContext.Activity.From.Name; await turnContext.SendActivityAsync($"You are seeing this message because this was your first message ever to this bot.", cancellationToken: cancellationToken); await turnContext.SendActivityAsync($"It is a good practice to welcome the user and provide personal greeting. For example, welcome {userName}.", cancellationToken: cancellationToken); } else { } // Save any state changes. await _userState.SaveChangesAsync(turnContext); } ## 추가 입력 처리 사용하자한테 환영 메세지를 보낸 후에는 봇이 사용자 입력에 따라 응답을 제공한다. "intro"나 "help"를 입력하면 SendIntroCardAsync method가 호출되고 herocard를 보여준다. ```C# // This example hardcodes specific utterances. You should use LUIS or QnA for more advance language understanding. var text = turnContext.Activity.Text.ToLowerInvariant(); switch (text) { case "hello": case "hi": await turnContext.SendActivityAsync($"You said {text}.", cancellationToken: cancellationToken); break; case "intro": case "help": await SendIntroCardAsync(turnContext, cancellationToken); break; default: await turnContext.SendActivityAsync(WelcomeMessage, cancellationToken: cancellationToken); break; } ``` ## Herocard 사용 ```C# private static async Task SendIntroCardAsync(ITurnContext turnContext, CancellationToken cancellationToken) { var card = new HeroCard(); card.Title = "Welcome to Bot Framework!"; card.Text = @"Welcome to Welcome Users bot sample! This Introduction card is a great way to introduce your Bot to the user and suggest some things to get them started. We use this opportunity to recommend a few next steps for learning more creating and deploying bots."; card.Images = new List<CardImage>() { new CardImage("https://aka.ms/bf-welcome-card-image") }; card.Buttons = new List<CardAction>() { new CardAction(ActionTypes.OpenUrl, "Get an overview", null, "Get an overview", "Get an overview", "https://docs.microsoft.com/en-us/azure/bot-service/?view=azure-bot-service-4.0"), new CardAction(ActionTypes.OpenUrl, "Ask a question", null, "Ask a question", "Ask a question", "https://stackoverflow.com/questions/tagged/botframework"), new CardAction(ActionTypes.OpenUrl, "Learn how to deploy", null, "Learn how to deploy", "Learn how to deploy", "https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-howto-deploy-azure?view=azure-bot-service-4.0"), }; var response = MessageFactory.Attachment(card.ToAttachment()); await turnContext.SendActivityAsync(response, cancellationToken); } ``` 처음에 사용자가 입장했을때 바로 환영 인사를 띄우는 거에 이거를 사용해야겠다. ======================= File: _posts/React/React/2020-08-28-input 상태 관리하기.md ======================= --- title: "React - Input 상태 관리하기" excerpt: "" toc: true toc_sticky: true toc_label: "페이지 주요 목차" header: teaser: categories: - react tags: - react-react - React last_modified_at: --- //rcc, rcs import React, { Component } from'react'; class PhoneForm extends Component { state = { name : '', phone: '', } handleChange = (e) =>{ //e는 이벤트 객체 this.setState({ [e.target.name]: e.target.value //input이 event.target }) } render() { return ( <div> 이것은 PhoneForm 이라네. <input name="name" placeholder="기본값.이름" onChange={this.handleChange} value={this.state.name} /> <input name="phone" placeholder="전화번호" onChange={this.handleChange} value={this.state.phone} /> <div> {this.state.name} {this.state.phone} </div> </div> ); } } export default PhoneForm; ======================= File: _featured_categories/cs.md ======================= <gh_stars>1-10 --- layout: list title: CS slug: cs menu: true submenu: true order: 2 description: > 컴퓨터공학 💻 --- ======================= File: _posts/C#/2020-07-17-base.md ======================= --- title: "[C#] base 키워드" excerpt: "Chatbot 공부 시작" toc: true toc_sticky: true toc_label: "페이지 주요 목차" header: teaser: categories: - csharp tags: - 공부 - C# - base last_modified_at: --- ## base 키워드 **해당 키워드를 사용하는 클래스의 부모 클래스를 가리키는 것이다** ``` class Fruit { string g_name; int g_grade; int g_price; public Fruit(string name, int grade, int price) { g_name = name; g_grade = grade; g_price = price; } public void Sell() { Console.WriteLine("과일 {0}을(를) {1}원에 팔았습니다.", g_name, g_price); } public void Info() { Console.WriteLine("과일 이름: {0}", g_name); Console.WriteLine("과일 등급: {0}등급", g_grade); Console.WriteLine("과일 가격: {0}원", g_price); } public int Price { get { return g_price; } } public int Grade { get { return g_grade; } } public string Name { get { return g_name; } } } ``` 위에는 Fruit 클래스가 선언되어 있다. 이를 상속한 Apple 클래스를 선언해보도록 한다. ``` class Apple : Fruit { public Apple(int grade, int price) : base("사과", grade, price) { } public void SellCustom() { Console.WriteLine("사과를 {0}원에 팔았습니다.", Price); } public void SellBase() { base.Sell(); } public int Price { get { return 0; } } } ``` base 키워드를 사용하는지 아나는지에 따라 어떤 클래스에 접근하는지가 달라진다. ``` int priceBase = base.Price; // Fruit 클래스의 Price 속성 값 int priceThis = this.Price; // Apple 클래스의 Price 속성 값 (this. 는 생략 가능합니다) ``` base 키워드를 사용하게 되면 부모 클래스의 것에 접근하게 되고, 쓰지 않는다면 본인 클래스의 것에 접근하게 다. ======================= File: _posts/soso/2020-09-14-Github pull.md ======================= <reponame>Yoojin99/Yoojin99.github.io<filename>_posts/soso/2020-09-14-Github pull.md --- title: "Github - pull, 원격 로컬 저장소 동기화" excerpt: "" categories: - soso tags: - Github --- 하나의 프로젝트로 여러 명이 협업할 때 보통 Github를 많이 사용한다. Turtoise svn, gitlab도 사용해봤지만 github가 가장 사용성이 좋은 것 같다. 프로젝트를 협업할 때 보통 원격에 있는 저장소(repository)를 fork 해서 복사본을 만든다. 그리고 작업을 할 때는 fork를 해서 복사되어 새로 생긴 그 저장소에서 branch를 여러개 만들어서 작업하는 방식을 취한다. 작업이 끝나고 나면, pull request를 하고, 원래 저장소에는 merge가 되었을 것이다. 그런데 이 상태에서 와 머지됐네 이제 마저 작업해야지 하면 안된다. 원격 저장소에는 내가 작업하는 동안 다른 사람들이 또 작업을 하고, commit을 하고, merge를 했을 것이다. 그러므로 원격 저장소(기본 프로젝트)에 A, B, C가 추가될 동안 나는 D만 추가해서 풀 리퀘를 했을 때 내 로컬 저장소에는 A, B, C라는 내용이 없는 것이다. 이때 git pull 명령어를 통해 원격 저장소와 내 저장소를 동기화 한다. ``` git pull upstream (기본 저장소의 branch 이름) ``` 을 해주면 동기화가 된다. 1. 만약 github 웹 페이지에서 `This branch is X commits behind ~`라고 뜰 경우 그냥 위에 쓴 커맨드를 입력해주면 문제는 해결된다. 이후 다시 github 페이지에서 확인하면 `This branch is even ~`라고 뜬다. 2. 만약 github 웹 페이지에서 `This branch is X commits ahead, Y commits behind ~`라고 뜰 경우 ``` git pull --reabse upstream (기본 저장소의 branch 이름) ``` 을 해주면 된다. 만약 conflict가 났다 어쩌구 저쩌구 뜨면 그거는 직접 보면서 conflict 나는 부분을 해결하고, 다시 commit, push, pull 해야 할 것이다. ======================= File: _posts/App/objc/2020-04-04-프로젝트 생성.md ======================= <reponame>Yoojin99/Yoojin99.github.io<filename>_posts/App/objc/2020-04-04-프로젝트 생성.md --- layout: post title: "[Objective C로 앱 만들기 - 1. Project 생성]" subtitle: "" categories: app tags: app-objc comments: true header-img: --- > `Obejctive-c로 동작하는 앱을 만들 것이다.` --- Objective-c는 분명 현재 Swift로 대체되고 있는 비교적 오래된 언어이다. Objective-c의 많은 불편한 부분이 swift로 개선되었고, objective-c로 작성된 많은 코드들이 swift로 바뀌고 있는 상황이다. 하지만 Objective-c를 이해하지 않고 바로 swift로 넘어가면 기존의 obj-c로 작성된 코드들을 이해할 수 없으면 어째서 obj-c에서 swift로 전환이 이루어지고 있는지 이해하기 어렵다. 그런 의미에서 obj-c로 앱 프로젝트를 작성하며 Obj-c의 문법을 익히고, obj-c의 불편한 점들을 몸소 체감하며 swift에서는 어떻게 편리하게 바뀌었는지 알아보려고 한다. 본격적으로 시작하기 전에, 만드려는 앱은 유튜브 채널 haha ha님의 고양이들을 확인할 수 있는 앱을 만들어 보려고 한다. 앱을 실행하자마자 로고와 함께 메인화면이 뜬 다음, 바로 고양이들의 목록을 확인할 수 있는 목록 화면이 나온다. 그리고 목록의 고양이들을 터치하면 상세 고양이 페이지를 확인할 수 있게 할 예정이다. ## 1. Xcode 설치 iOS 앱을 개발하려면 무조건 맥북이 있어야 한다. 개발을 위해서는 맥북에서 지원하는 앱 스토어에서 다운받을 수 있는 `Xcode` 라는 앱이 필요하다. ![image](https://user-images.githubusercontent.com/41438361/113509373-28f66e00-9590-11eb-9349-cd09a1b7a8ef.png) 이 Xcode에 대한 자세한 내용은 다른 글에서 작성하도록 하겠다. 이 평점이 아주 낮은 Xcode를 설치해준다.(시간이 은근 오래 걸린다.) ## 2. 프로젝트 생성 File > New > new Project를 선택한다. ![image](https://user-images.githubusercontent.com/41438361/113509435-84286080-9590-11eb-9c71-5b64c524cd5c.png) 선택하면 아래와 같이 무엇을 개발할지 선택할 수 있는데, 앱을 개발할 것이므로 App을 선택하고 Next를 눌러준다. ![image](https://user-images.githubusercontent.com/41438361/113509418-6955ec00-9590-11eb-9ab5-dd97f6650caa.png) 프로젝트의 옵션을 지정할 수 있는 창이 나온다. Product Name과 Organization Identifier에 아무 이름이나 적고, 아래의 설정들은 그림과 같이 설정해주고 Next를 누른다. 이 설정 들에 대한 자세한 설명도 다른 글에 작성하도록 할 것이다. ![image](https://user-images.githubusercontent.com/41438361/113509540-2d6f5680-9591-11eb-83d0-bd9d341bd9d0.png) 다음에는 어디에 저장할 것인지 설정할 수 있는 창이 뜰 텐데, 아무데나 설정하고 저장을 누른다. 이제 다음과 같이 프로젝트 파일이 만들어졌다. ![image](https://user-images.githubusercontent.com/41438361/113509642-b1294300-9591-11eb-98fb-c04f3716023f.png) ## 3. 실행시켜보기 * `Command + B` : 빌드 * `Command + R` : 실행 프로젝트를 실행시키기 전에, 이 앱을 구동시킬 기기를 설정해야 한다. 테스트 기기(실제 기기)가 없다고 가정하고, 나는 Xcode의 시뮬레이터를 이용해 앱을 돌려보려고 한다. Xcode의 왼쪽 상단을 보면 아래 화면과 같이 시뮬레이터를 지정할 수 있는 탭을 열 수 있다. 기기들 중에 원하는 기기를 선택하자. 참고로 나는 iphone 12 Pro를 골랐다. ![image](https://user-images.githubusercontent.com/41438361/113509731-2ac13100-9592-11eb-9867-4fbeffe73928.png) 실행시키면 잠시 후 아래와 같이 시뮬레이터에 앱이 구동된 것을 확인할 수 있다. 흰 화면이 뜨는 이유는 빈 프로젝트를 실행했기 때문이다. 참고로 ![image](https://user-images.githubusercontent.com/41438361/113509813-868bba00-9592-11eb-9446-eb2b0d70c70c.png) 시뮬레이터의 메뉴바의 세 개의 메뉴들은 순서대로 스크린샷 찍기, 핸드폰의 홈 화면으로 가기, 회전시키기 이다. 직접 하나씩 눌려보면서 해보면 재미있다. ![image](https://user-images.githubusercontent.com/41438361/113509860-b9ce4900-9592-11eb-9ecb-5e2aabc5df27.png) 이제 다음에는 앱 아이콘을 등록해서 앱을 처음에 딱 실행했을 때 로고가 천천히 뜨게끔 만들 것이다. ======================= File: _posts/JS/2020-08-20-1.Scope와 Hoisting.md ======================= <filename>_posts/JS/2020-08-20-1.Scope와 Hoisting.md --- title: "JavaScript - Scope와 Hoisting" excerpt: "" categories: - js tags: - Scope - Hoisting last_modified_at: --- Block Scope는 ES6에서 처음 등장하는 Scope이다. JavaScript에는 원래 함수 Scope가 존재했다. **Scope : 범위. 유효공간. 살수 있는 공간. 허용공간, 허용범위** 함수 스코프는 즉 함수에 의해서 생기는 범위이다. 이 범위는 변수의 유효범위이다. 원래 ES5까지는 여기까지 존재했다. 이 스코프가 생기는 것이 함수에 의해서만 생긴다는 뜻이다. 근데 이제는 블락스코프가 생겼다. Block Scope는 block에 의해 생기는 유효범위이다. 이 블락은 `{}`을 의미한다. 즉 `{}`에 의해서 변수의 유효범위까지 결정된다는 것이다. ## Block Scope 기존에는 var를 썼지만 ES6부터는 `let`, `const`와 같이 변수 선언하는 애들이 더 많이 생겼다. 만약 ```javascript { let a = 10 } console.log(a) ``` 가 된다면 결과는 `a is not defined`라고 뜬다. 왜냐하면 a는 블락 스코프(유효범위)안에서 선언이 되었기 때문이다. 근데 만약 ```javascript { var v = 'blue' } console.log(v) ``` 라고 하면 v는 blue라고 출력된다. `var`는 스코프의 영향을 받지 않기 때문이다. `let`만 블락스코프의 영향을 받는다. ### `let`, `const`만 블럭스코프의 영향을 받는다. var는 영향을 받지 않는다. ### Hoisting 스코프는 중괄호에 의해 영향을 받는다. ```javascript if(true){ } for(var i=0; i<10; i++){ } while(true){ } switch(a){ case: break; } ``` 위에 있는 애들은 if 문, for 문과 같이 ~~문이라 부른다. 이 문은 '문단'을 의미한다. 문단과 반대되는 거는 식(expressiont)으로 값이 될 수 있는 경우가 된다. 예로는 10+20, 'a'+'b'와 같이 값이 될 수 있는 것들이 여기에 해당된다. 모든 데이터는 값, 식, 문 중에 하나이다. 값과 식은 동일하게 간주가 된다. 문단은 결과를 리턴하지 않는다. 그니까 if 문같은 것들을 실행하고 끝이고 반환해주는 값 같은 거는 없다. 따라서 **문단 자체가 하나의 block-scope가 된다.** ```javascript if(true){ let a = 10 if(true){ console.log(a) const a = 20 } console.log(a) } ``` 위의 코드에서 만약 hoisting이 된다면 a는 undefined가 출력될 것이다. hoisting이 안된다면 a는 10이 나올 것이다. 결과로는 undefined가 나온다. 이와 관련된 것으로 TDZ(Temporal Dead Zone. 임시 사각지대)를 얘기할 수 있다. 위의 코드는 TDZ에 걸린다. let이나 const에 대해서 이 변수를 실제 선언한 위치에 오기까지는 그 변수를 호출할 수 없다. 위에서부터 아래로 내려가야 하는데 실수로 아래서 `var`로 써놓은 변수를 위에서 호출했는데 오류가 안나는 상황이 생길 수 있으므로 hoisting은 중요하다. Hoisting을 다시 정리하면 다음과 같다. 기존 var 시스템에서는 **변수명만 위로 끌어올리고 -> undefined를 할당한다.** 근데 let 이나 const를 쓰면 **변수명만 위로 끌어올리고 -> 끝이다.** 즉 hoisting을 해서 a의 존재를 블럭 스코프 안에서 인식하고 있지만, undefined 할당하는 과정이 빠진 것이다. Hoisting을 하지만, TDZ라는 것이 존재하여 할당을 하지 않는 것으로 이해하면 될 것 같다. ======================= File: _posts/soso/2020-11-30-react의 쓸모가 없어지는가.md ======================= --- title: "react의 쓸모가 없어지는가?" excerpt: "" toc: true toc_sticky: true toc_label: "페이지 주요 목차" header: teaser: categories: - soso tags: - 총정리 last_modified_at: 2020-11-30 --- https://seokjun.kim/time-to-stop-react/ 링크를 보면 React가 점점 쓸모가 없어진다는 얘기를 하고 있다. 정리하면 1. React는 UI 라이브러리였지만 SSR덕분에 SEO가 가능한 SPA로 사용하면서 문제가 시작되었다. 2. hooks는 멍청한 선택 3. SSR은 느리고, 반대로 검색 엔진이 똑똑해졌다 4. 좋은 대체품들이 많이 나왔다. 하지만 GeekNews에서는 이에 대해 약간 상반되는 댓글이 있었다. 1. svelt가 좋은 기술인 것은 맞지만, 또 그렇다고 그렇게 위상을 높일만한 기술도 아니다. 2. react가 점점 쓸모가 없어진다는 것에는 동감하지만 svelt, elm로 꼭 대체를 해야하는지는 모르겠다. 3. 아마 C# blazor, rust wasm이 프론트엔드의 다음 세대를 이끌 수도 있을 것이다. ======================= File: _featured_tags/cs-cn.md ======================= --- layout: tag-blog title: Computer Network slug: cs-cn category: cs menu: false order: 7 --- 컴퓨터 네트워크 ======================= File: _posts/C++/2020-10-18-bool.md ======================= --- title: "[C++] bool 자료형" excerpt: "" toc: true toc_sticky: true toc_label: "페이지 주요 목차" header: teaser: categories: - cpp tags: - 공부 - C++ - bool last_modified_at: 2020-10-18 --- ======================= File: _posts/ChatBot/MSAzure/2020-07-17-고급대화흐름 만들기.md ======================= --- title: "Chatbot - 분기 및 루프를 사용하여 고급 대화 흐름 만들기(multi-dialog)" excerpt: "" toc: true toc_sticky: true toc_label: "페이지 주요 목차" header: teaser: categories: - cb tags: - cb-ma - 공부 - Azure - dialog - multi dialog last_modified_at: --- 공식 문서에서 나온 샘플은 최대 2개의 회사를 검토하기 위해 사용자가 가입할 수 있는 봇을 보여준다. 봇은 3개의 구성 요소 대화르 사용하여 대화 흐름을 관리한다. 각 구성 요소 대화(아마 dialog를 말하는 것 같다)에는 폭포 대화와 사용자 입력을 수집하는 데 필요한 프롬프트가 포함된다. 대화 상태를 사용하여 해당 대화를 관리하고 사용자 상태를 사용해서 사용자, 사용자가 검토하려는 회사에 대한 정보를 저장한다. ![complex-conversation-flow](https://user-images.githubusercontent.com/41438361/87760806-4d1bee80-c84b-11ea-8dcb-ce7d12b14de7.png) ## 사용자 프로필 정의 사용자 프로필에는 대화, 사용자의 이름, 나이와 검토하도록 선택한 회사에서 수집한 정보가 포함된다. **UserProfile.cs** ``` /// <summary>Contains information about a user.</summary> public class UserProfile { public string Name { get; set; } public int Age { get; set; } // The list of companies the user wants to review. public List<string> CompaniesToReview { get; set; } = new List<string>(); } ``` ## 대화 만들기 이 봇에는 3개의 대화가 포함되어 있다. * 기본 대화는 전체 프로세스를 시작한 다음, 수집된 정보를 요약합니다. * 최상위 대화는 사용자 정보를 수집하고 사용자의 나이를 기준으로 분기 논리를 포함합니다. * 검토 선택 대화를 통해 사용자는 검토할 회사를 반복적으로 선택할 수 있습니다. 이 작업에는 반복되는 논리가 사용됩니다. ### 기본 대화 기본 대화는 다음 2단계로 이루어진다. 1. 최상위 대화를 시작한다. 2. 최상위 대화에서 수집한 사용자 프로필을 검색, 요약하고 사용자 상태에 해당 정보를 저장한 다음, 기본 대화의 끝을 알린다. **Dialogs/MainDialog.cs** ``` private async Task<DialogTurnResult> InitialStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken) { return await stepContext.BeginDialogAsync(nameof(TopLevelDialog), null, cancellationToken); } private async Task<DialogTurnResult> FinalStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken) { var userInfo = (UserProfile)stepContext.Result; string status = "You are signed up to review " + (userInfo.CompaniesToReview.Count is 0? "no companies" : string.Join(" and ", userInfo.CompaniesToReview)) + "."; await stepContext.Context.SendActivityAsync(status); var accessor = _userState.CreateProperty<UserProfile>(nameof(UserProfile)); await accessor.SetAsync(stepContext.Context, userInfo, cancellationToken); return await stepContext.EndDialogAsync(null, cancellationToken); } ``` ### 최상위 대화 최상위 대화는 다음 4단계로 이루어진다. 1. 사용자의 이름을 요청합니다. 2. 사용자의 나이를 요청합니다. 3. 사용자의 나이를 기준으로 검토 선택 대화를 시작하거나 다음 단계로 진행합니다. 4. 마지막으로 사용자의 참여에 대한 감사 인사를 보내고, 수집된 정보를 반환합니다. 첫번째 단계에서는 대화 상태의 일부로 빈 사용자 프로필을 만든다. 빈 프로필로 대화가 시작되고 진행되면서 프로필에 정보가 추가된다. 대화가 끝나면 마지막 단계가 수집된 정보를 반환한다. 세번째 단계(선택 시작)에서는 사용자의 나이에 따라 대화 흐름이 나눠진다. **Dialogs/TopLevelDialog.cs** ``` private static async Task<DialogTurnResult> NameStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken) { // Create an object in which to collect the user's information within the dialog. stepContext.Values[UserInfo] = new UserProfile(); var promptOptions = new PromptOptions { Prompt = MessageFactory.Text("Please enter your name.") }; // Ask the user to enter their name. return await stepContext.PromptAsync(nameof(TextPrompt), promptOptions, cancellationToken); } private async Task<DialogTurnResult> AgeStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken) { // Set the user's name to what they entered in response to the name prompt. var userProfile = (UserProfile)stepContext.Values[UserInfo]; userProfile.Name = (string)stepContext.Result; var promptOptions = new PromptOptions { Prompt = MessageFactory.Text("Please enter your age.") }; // Ask the user to enter their age. return await stepContext.PromptAsync(nameof(NumberPrompt<int>), promptOptions, cancellationToken); } private async Task<DialogTurnResult> StartSelectionStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken) { // Set the user's age to what they entered in response to the age prompt. var userProfile = (UserProfile)stepContext.Values[UserInfo]; userProfile.Age = (int)stepContext.Result; //나이를 물어보는 부분 if (userProfile.Age < 25) { // If they are too young, skip the review selection dialog, and pass an empty list to the next step. await stepContext.Context.SendActivityAsync( MessageFactory.Text("You must be 25 or older to participate."), cancellationToken); return await stepContext.NextAsync(new List<string>(), cancellationToken); } else { // Otherwise, start the review selection dialog. return await stepContext.BeginDialogAsync(nameof(ReviewSelectionDialog), null, cancellationToken); } //여기까지 } private async Task<DialogTurnResult> AcknowledgementStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken) { // Set the user's company selection to what they entered in the review-selection dialog. var userProfile = (UserProfile)stepContext.Values[UserInfo]; userProfile.CompaniesToReview = stepContext.Result as List<string>?? new List<string>(); // Thank them for participating. await stepContext.Context.SendActivityAsync( MessageFactory.Text($"Thanks for participating, {((UserProfile)stepContext.Values[UserInfo]).Name}."), cancellationToken); // Exit the dialog, returning the collected user information. return await stepContext.EndDialogAsync(stepContext.Values[UserInfo], cancellationToken); } ``` ### 검토 선택 대화 검토 선택 대화는 다음 2단계로 이루어진다. 1. 사용자에게 검토할 회사를 선택하도록 요청하거나 done을 선택하여 완료한다. * 대화가 초기 정보로 시작된 경우 폭포 단계 컨텍스트의 옵션 속성을 통해 정보를 사용할 수 있습니다. 검토 선택 대화가 다시 시작될 수 있으며 이는 사용자가 검토할 회사를 여러 개 선택할 수 있도록 하는 데 사용됩니다. * 사용자가 검토할 회사를 이미 선택한 경우 해당 회사는 사용 가능한 선택 항목에서 제거됩니다. * 사용자가 루프를 일찍 종료할 수 있도록 done 선택 항목이 추가됩니다. 2. 이 대화를 반복하거나 적절하게 종료합니다. * 사용자가 검토할 회사를 선택한 경우 목록에 추가합니다. * 사용자가 2개의 회사를 선택했거나 종료하도록 선택한 경우 대화를 끝내고 수집된 목록을 반환합니다. * 그렇지 않으면 대화를 다시 시작하여 목록의 내용으로 초기화합니다. **Dialogs/ReviewSelectionDialog.cs** ``` private async Task<DialogTurnResult> SelectionStepAsync( WaterfallStepContext stepContext, CancellationToken cancellationToken) { // Continue using the same selection list, if any, from the previous iteration of this dialog. var list = stepContext.Options as List<string>?? new List<string>(); stepContext.Values[CompaniesSelected] = list; // Create a prompt message. string message; if (list.Count is 0) { message = $"Please choose a company to review, or `{DoneOption}` to finish."; } else { message = $"You have selected **{list[0]}**. You can review an additional company, " + $"or choose `{DoneOption}` to finish."; } // Create the list of options to choose from. var options = _companyOptions.ToList(); options.Add(DoneOption); if (list.Count > 0) { options.Remove(list[0]); } var promptOptions = new PromptOptions { Prompt = MessageFactory.Text(message), RetryPrompt = MessageFactory.Text("Please choose an option from the list."), Choices = ChoiceFactory.ToChoices(options), }; // Prompt the user for a choice. return await stepContext.PromptAsync(nameof(ChoicePrompt), promptOptions, cancellationToken); } private async Task<DialogTurnResult> LoopStepAsync( WaterfallStepContext stepContext, CancellationToken cancellationToken) { // Retrieve their selection list, the choice they made, and whether they chose to finish. var list = stepContext.Values[CompaniesSelected] as List<string>; var choice = (FoundChoice)stepContext.Result; var done = choice.Value == DoneOption; if (!done) { // If they chose a company, add it to the list. list.Add(choice.Value); } //이부분부터 if (done || list.Count >= 2) { // If they're done, exit and return their list. return await stepContext.EndDialogAsync(list, cancellationToken); } else { // Otherwise, repeat this dialog, passing in the list from this iteration. return await stepContext.ReplaceDialogAsync(nameof(ReviewSelectionDialog), list, cancellationToken); } //여기까지 } ``` ## 대화 실행 대화 봇 클래스는 작업 처리기를 확장하며 대화 실행을 위한 논리를 포함한다. 대화 및 환 영 봇 클래스는 대화 봇을 확장하여 대화 참여 시 사용자를 환영한다. 봇의 순서 처리기는 3개의 대화로 정의되는 대화 흐름을 반복한다. 사용자로부터 메세지를 받는 경우 1. 기본 대화를 실행합니다. * 대화 스택이 비어 있으면 기본 대화가 시작됩니다. * 그렇지 않으면 대화가 아직 진행 중인 것이므로 활성 대화가 계속됩니다. 2. 사용자, 대화 및 대화 상태에 대한 모든 업데이트가 유지되도록 상태가 저장됩니다. **Bots/DialogBot.cs** ``` public override async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken = default(CancellationToken)) { await base.OnTurnAsync(turnContext, cancellationToken); // Save any state changes that might have occurred during the turn. await ConversationState.SaveChangesAsync(turnContext, false, cancellationToken); await UserState.SaveChangesAsync(turnContext, false, cancellationToken); } protected override async Task OnMessageActivityAsync(ITurnContext<IMessageActivity> turnContext, CancellationToken cancellationToken) { Logger.LogInformation("Running dialog with Message Activity."); // Run the Dialog with the new message Activity. await Dialog.RunAsync(turnContext, ConversationState.CreateProperty<DialogState>(nameof(DialogState)), cancellationToken); } ``` ## 봇용 서비스 등록 필요에 따라 서비스를 만들고 등록한다. * 봇에 대한 기본 서비스 : 어댑터 및 봇 구현 * 상태 관리 서비스 : 스토리지, 사용자 상태 및 대화 상태 * 봇이 사용할 루트 대회 **Startup.cs** ``` public void ConfigureServices(IServiceCollection services) { services.AddControllers().AddNewtonsoftJson(); // Create the Bot Framework Adapter with error handling enabled. services.AddSingleton<IBotFrameworkHttpAdapter, AdapterWithErrorHandler>(); // Create the storage we'll be using for User and Conversation state. (Memory is great for testing purposes.) services.AddSingleton<IStorage, MemoryStorage>(); // Create the User state. (Used in this bot's Dialog implementation.) services.AddSingleton<UserState>(); // Create the Conversation state. (Used by the Dialog system itself.) services.AddSingleton<ConversationState>(); services.AddSingleton<MainDialog>(); // Create the bot as a transient. In this case the ASP Controller is expecting an IBot. services.AddTransient<IBot, DialogAndWelcomeBot<MainDialog>>(); } ``` ======================= File: _posts/React/ReactNative/2020-08-31-Interaction_Navigating Between Screens.md ======================= --- title: "React Native - Design - Screen 사이 이동하기" excerpt: "" toc: true toc_sticky: true toc_label: "페이지 주요 목차" header: teaser: categories: - react tags: - react-rn - React Native last_modified_at: --- 모바일앱이 단일 화면으로 만들어진 경우는 드물다. 여러 스크린을 출력하고 이동할 수 있게 하는 거는 네비게이터에 의해 관리된다. React Navigation은 안드로이드와 iOS 모두에서 일반적인 stack navigation과 tabbed navigation pattern과 함께 직접적인 네비게이션 해결책을 제시한다. 만약 안드로이드와 iOS 모두에서 native look을 보여지게 하고 싶거나, 이미 네비게이션을 natively하게 관리학 있는 앱에 RN을 통합하고 있다면, react-native-navigation 라이브러리가 두 플랫폼 모두에 native navigation을 제공할 수 있다. ## React Navigation Navigation을 하기 위한 커뮤니티의 해결책은 개발자가 몇줄의 코드로 앱의 스크린을 설정할 수 있는 독립적인 라이브러리를 사용하는 것이다. ### 설치와 설정 먼저, 프로젝트에 다운받아야 한다. ``` npm install @react-navigation/native @react-navigation/stack ``` 그리고 관련있는 것들을 다운받아라. 프로젝트가 Expo 관리 프로젝트인지 아니면 그냥 없는 RN 프로젝트인지에 따라 다른 커맨드를 입력해야 한다. * 만약 Expo managed project라면, `expo`와 관련있는 것들을 다운받아라: `expo install react-native-reanimated react-native-gesture-handler react-native-screens react-native-safe-area-context @react-native-community/masked-view` * 만약 없는 RN 프로젝트라면 `npm`과 관련 있는 것을 다운받아라: `npm install react-native-reanimated react-native-gesture-handler react-native-screens react-native-safe-area-context @react-native-community/masked-view` bare RN project를 iOS로 하려면, Cocoapods를 다운 받아야 한다. pds는 다음과 같이 다운받을 수 있다. ``` cd ios pod install cd.. ``` `react-native-gesture-handler` 설치를 마치기 위해, 아래의 코드를 entry 파일(`index.js`나 `App.js`)맨 위에(가장 위에!!) 붙여라. ```js import'react-native-gesture-handler'; ``` 그리고 앱을 통째로 `NavigationContainer`에 넣어라. 주로 이거는 `index.js`나 `App.js`같은 entry 파일에 한다. ```js import'react-native-gesture-handler'; import * as React from'react'; import { NavigationContainer } from '@react-navigation/native'; const App = () => { return ( <NavigationContainer> {/* Rest of your app code */} </NavigationContainer> ); }; export default App; ``` 이제 기기/시뮬레이터에서 실행할 준비가 되었다. ### 사용 이제 홈화면과 프로필 화면으로 구성된 앱을 만들 수 있다. ```js import * as React from'react'; import { NavigationContainer } from '@react-navigation/native'; import { createStackNavigator } from '@react-navigation/stack'; const Stack = createStackNavigator(); const MyStack = () => { return ( <NavigationContainer> <Stack.Navigator> <Stack.Screen name="Home" component={HomeScreen} options={{ title: 'Welcome' }} /> <Stack.Screen name="Profile" component={ProfileScreen} /> </Stack.Navigator> </NavigationContainer> ); }; ``` 이 예제에서는 `Stack.Screen` component를 이용해서 2개의 화면(`Home`과 `Profile`)을 만들었다. 비슷하게, 얼마든지 많은 화면을 만들 수 있다. 각 화면의 이름을 `Stack.Screen`의 `options` prop을 설정할 수도 있다. 각 화면은 React component인 `component` prop을 가지고 있다. 이 component들은 다른 스크린으로 링크할 수 있는 메소들을 많이 가진 `navigation`이라는 prop을 받는다. 예를 들어, `navigation.navigate`를 이용해서 `Profile` 화면으로 넘어갈 수 있다: ```js const HomeScreen = ({ navigation }) => { return ( <Button title="Go to Jane's profile" onPress={() => navigation.navigate('Profile', { name: 'Jane' }) } /> ); }; const ProfileScreen = () => { return <Text>This is Jane's profile</Text>; }; ``` stack navigator에 있는 view들은 native component과 native thread에서 동작하고 있는 60fps 애니메이션을 전달하기 위해 Animated 라이브러리를 사용한다. 추가로, 애니메이션과 제스쳐도 커스터마이징이 가능하다. RN은 tab과 drawer같이 다양한 종류의 네비게이터를 위한 패키지를 가지고 있다. ======================= File: _posts/CS/자료구조/2020-11-02-Array.md ======================= <reponame>Yoojin99/Yoojin99.github.io --- title: "Array" excerpt: "" toc: true toc_sticky: true toc_label: "페이지 주요 목차" header: teaser: categories: - cs tags: - cs-ds last_modified_at: 2020-11-03 --- Array는 가장 기본적인 자료구조이다. ## 1. 장점 및 특징 **논리적 저장 순서 == 물리적 저장 순서** 가 특징이다. 따라서 `index`로 원소(element)에 접근할 수 있다. 따라서 찾고자 하는 원소의 인덱스 값을 알고 있으면 `Big-O(1)`에 해당 원소로 접근할 수 있다. 즉 **random access**가 가능하다는 장점이있다. ## 2. 단점 하지만 삭제, 삽입을 할 때는 해당 원소에 접근한 뒤(O(1)) 추가적으로 작업을 해줘야 하기 때문에 시간이 더 걸린다. 만약 배열의 원소 중 어떤 원소를 삭제했다고 하면, 배열의 연속적인 특징이 깨진다. 빈 공간이 생기는 것이다. 따라서 삭제한 원소보다 큰 인덱스를 갖는 원소들을 왼쪽으로(낮은 인덱스 값으로) shift 해줘야 하는 비용(cost)이 발생한다. 이 경우 시간 복잡도는 O(n)이 된다. 따라서 Array 자료구조에서 삭제 기능에 대한 time complexity의 worst case는 O(n)이 된다. 삽입도 마찬가지인데, 얘도 예를 들어 첫 번째 자리에 새로운 원소를 추가하면 그 뒤에 있는 모든 원소들의 인덱스를 큰 값으로 1씩 shift 해줘야 하므로 이 경우도 O(n)의 시간이 걸린다. ## 시간복잡도 배열 연산의 시간복잡도를 계산하면 다음과 같다. 1. 검색 : O(1) - 주소 값을 모르더라도 인덱스로 바로 접근할 수 있다. 2. 갱신 : O(1) 3. 삽입 : O(n) 4. 삭제 : O(n) ## c++에서의 array array에는 1. 고정 배열(fixed array) / 정적 배열 2. 동적 배열(dynamic array) 가 있다. 이 두 배열 모두 C++에 내장되어 있지만, 포인터로 형변환이 되었을 때 배열 길이 정보가 손실되고, 동적 배열은 지저분한 할당 해제 문제가 있다. 이런 문제를 해결하기 위해 C++ 표준라이브러리에서는 배열 관리를 쉽게 해주는 `std::array`와 `std::vector`가 있다. ### std::array `std:array`는 함수에 전달할 때 포인터로 형 변환되지 않는 고정 길이 배열이다. std::array는 `<array>` 헤더의 `std` 네임 스페이스 내부에 정의되어 있다. 변수 선언은 다음과 같이 하면 된다. ```c++ #include <array> std::array<int, 3> arr; //길이 3짜리의 정수형 배열 선언 ``` 정적 배열 선언처럼 array의 길이는 컴파일 타임에 설정해야 한다. std::array는 초기화 리스트(initializer list) 또는 유니폼 초기화(uniform initialization)을 사용해서 초기화 할 수 있다. ```c++ std::array<int, 5> arr = {1,2,3,4}; //초기화 리스트 std::array<int, 5> arr1 {1,2,3,4}; //유니폼 초기화 ``` 내장된 고정 배열과 다르게, std::array에서는 배열 길이를 생략할 수 없다. ```c++ std::array<int, > arr {1,2,3,4} // 불가 ``` 초기화 리스트를 사용해서 배열에 값을 할당할 수 있다. ```c++ std::array<int, 5> arr; arr = {1,2,3,4,5} //ok arr = {1,2,3} // 4, 5번째 원소는 0이 될 것이다. arr = {1,2,3,4,5,6} // 원소의 개수가 담을 수 있는 원소의 개수보다 많기 때문에 안된다. ``` 일반 배열처럼 첨자 연산자(`[]`)를 사용해서 배열의 요소 값에 접근할 수 있다. ```c++ std::cout << arr[1]; arr[2] = 6; ``` 또한 첨자 연산자는 유효 범위 검사를 하지 않으므로 잘못된 index가 주어지면 나쁜 일이 발생한다. 하지만 std::array는 유효 범위 검사를 수행하는 배열 요소에 접근하는 방법 `at()` 함수를 지원한다. ```c++ std::array<int, 5> arr {1,2,3,4,5}; arr.at(1) = 6; arr.at(7) = 10; // throws error ``` array.at(9)를 호출하면 9는 배열의 범위를 벗어나는 인덱스 값으로 검사되어 array.at(9)는 실패한다. 이때 참조를 반환하는 대신 예외를 throw한다. (std::out_of_range) `at()`함수는 유효 범위 검사를 하므로 `operator[]` 보다는 느리지만, 안전하다. ## Size와 sorting `size()`함수를 사용해서 배열의 길이를 알 수 있다. ```c++ std::array<double, 5> arr {1.0, 7.2, 4.5, 1.2, 1.9}; std::cout << "length: " << arr.size(); ``` 참고로 일반적인 정적 배열을 선언하고 나서 이 배열의 길이를 구하는 법은 c++에서는 ```c++ int arr[] = new int[5]; int size = sizeof(arr) / sizeof(arr[0]) //4byte * 5 / 4byte = 5 ``` c#에서는 ```c# int arr[] = new int[5]; int size = arr.Length; ``` 참고로 자바에서 배열 길이는 `arr.length`로, 문자열의 길이는 `str.length()`였다. `std::array`는 함수에 전달될 때 포인터로 형 변환이 되지 않기 때문에 `size()`함수는 함수 내에서 호출하더라도 정상적으로 작동한다. ```c++ #include <iostream> #include <array> void printLength(const std::array<double, 5>& arr) { std::cout << "length: " << arr.size(); } int main() { std::array<double, 5> arr {1.0, 1.2, 1.4, 1.6, 1.8}; printLength(arr); return 0; } ``` 표준 라이브러리에서 "size"라는 용어는 배열 길이를 의미하기 때문에 `sizeof()` 와 혼동하기 쉽다. (sizeof()의 결과는 배열 요소 자료형의 크기 * 배열 길이이다.) 위의 예제에서 `printLength()` 함수에서는 매개 변수로 `std::array`를 참조형(reference)로 받고 있다. 이는 std::array가 함수로 전달될 때 (성능상의 이유)로 컴파일러가 배열의 복사본을 만드는 것을 방지하기 위해서이다. 따라서 std::array는 **무조건 참조로 전달해야 한다.** std::array의 길이는 알려져 이기 때문에 range-base for 루프와 함께 사용할 수 있다. ```c++ std::array<int, 5> arr {1,2,3,4,5}; for (auto &element : arr) { std::cout << element << ''; } ``` `<algorithm>`헤더에 있는 std::sort를 사용해서 std::array를 정렬할 수 있다. ```c++ #include <iostream> #include <array> #include <algorithm> int main() { std::array<int, 5> arr {1,2,3,4,5}; std::sort(arr.begin(), arr.end()); } ``` 이 sort() 함수는 이터레이터(iterator)를 사용한다. ======================= File: _posts/ChatBot/MSAzure/2020-07-09-메세지 보내기 및 받기.md ======================= --- title: "Chatbot - 메세지 보내기 및 받기" excerpt: "" toc: true toc_sticky: true toc_label: "페이지 주요 목차" header: teaser: categories: - cb tags: - cb-ma - 공부 - Azure last_modified_at: --- 문자 메시지 보내기 및 받기 ========================= 봇이 사용자와 커뮤니케이션 하는 수단은 ** 메세지 ** 이다. 메세지는 보통 일반 텍스트로 구성되지만 일부 메세지는 카드나 첨부 파일처럼 다양한 서식과 콘텐츠를 포함할 수 있다. ## 텍스트 메세지 보내기 단문 메세지를 보내려면 보낼 문자열을 지정하여 보낸다. 봇의 작업처리기에서 순서 컨텍스트 개체의 "SendActivityAsync" method를 이용하여 단문 메세지를 보낸다. "SendActivitiesAsync"를 사용하면 한 번에 여러 메세지를 보낼 수도 있다. ~~~ await turnContext.SendActivityAsync($"Welcome!"); ~~~ ## 텍스트 메세지 수신 단문 메세지를 수신하려면 작업 개체의 텍스트 속성을 이용한다. 봇의 작업 처리기에서 아래 코드를 이용하여 메세지를 수신한다. ~~~ var responseMessage = turnContext.Activity.Text; ~~~ ## Typing 표시기 보내기 사용자는 자기가 메세지를 보내면 봇이 제때제때 응답할 것을 기대한다. 당연한 얘기지만 봇이 사용자가 메세지를 보냈는데도 메세지를 받았다는 표시를 안하고 서버를 호출하거나 쿼리를 실행하는 것과 같이 장시간 실행되는 작업을 수행할 경우, 사용자가 봇에 문제가 있다고 여기거나 추가로 메세지를 보낼 수도 있다. 웹 채팅 및 Direct Line 채널 봇이 메세지가 수신돼서 처리되고 있다는 것을 사용자에게 "타이핑 표시 전송"을 통해 보여줄 수도 있다. 단 봇이 15초 이내에 답을 해야 한다. 그렇지 않으면 커넥터 서비스가 시간이 초과된다. ~~~ protected override async Task OnMessageActivityAsync(ITurnContext<IMessageActivity> turnContext, CancellationToken cancellationToken) { if (string.Equals(turnContext.Activity.Text, "wait", System.StringComparison.InvariantCultureIgnoreCase)) { await turnContext.SendActivitiesAsync( new Activity[] { new Activity { Type = ActivityTypes.Typing }, new Activity { Type = "delay", Value= 3000 }, MessageFactory.Text("Finished typing", "Finished typing"), }, cancellationToken); } else { var replyText = $"Echo: {turnContext.Activity.Text}. Say 'wait' to watch me type."; await turnContext.SendActivityAsync(MessageFactory.Text(replyText, replyText), cancellationToken); } } ~~~ => 이거 한 번 실습 해봐야겠다 ======================= File: _posts/JS/2020-08-21-4. let.md ======================= <reponame>Yoojin99/Yoojin99.github.io --- title: "JavaScript - let" excerpt: "" toc: true toc_sticky: true toc_label: "페이지 주요 목차" header: teaser: categories: - js tags: - 공부 - JavaScript - let last_modified_at: --- ```javascript let a = 1 function f(){ console.log(a, b, c) // a=1, b는 hoisting으로 끌어올려진 상태에서 tdz에 걸리고, not defined, c error let b = 2 console.log(a, b, c) // c error if(true){ let c = 3 console.log(a, b, c) } console.log(a, b, c) //c error } ``` let은 var와 다르게 블럭 스코프에 갇히고, TDZ가 있다. ## 재할당 가능 ```javascript let a =1 a = 2 ``` ## 반복문 내에서의 함수 실행시 ```javascript var funcs = [] for(var i=0; i<10; i++){ funcs.push(function(){ console.log(i) }) } funcs.forEach(function(f){ f() }) ``` 위의 코드는 10이 10번 나온다. 배열에는 아래와 같이 들어간다. ``` [ function(){ console.log(i); }, ... ] ``` 위의 애는 `forEach`를 할 때 실행이 된다. 실행 컨텍스트는 실행할 때 열린다. 그래서 i가 10이 된 상태에서 10번 실행되는 것이다. 그러면 0부터 9까지 나오게 하려면 각 for문 안에서 i, 값을 살아있게 해줘야 한다. ```javascript var funcs = [] for(var i=0; i<10; i++){ funcs.push(function(v){ return function(){ //즉시 실행함수를 만들어 버린다. console.log(v) } }){i} //i를 미리 넘겨준다. } funcs.forEach(function(f){ f() }) ``` 근데 아래와 같이 해줘도 같은 결과가 나온다. ```javascript let funcs = [] for(var i=0; i<10; i++){ //자체가 블록 스코프 funcs.push(function(){ //각각의 i마다 별도로 존재 console.log(i) }) } funcs.forEach(function(f){ f() }) ``` 메모리 소모를 덜 하게 된 것이다. ======================= File: _posts/soso/2020-08-20-LGgram오디오문제.md ======================= <reponame>Yoojin99/Yoojin99.github.io<filename>_posts/soso/2020-08-20-LGgram오디오문제.md --- title: "LG gram 오디오 안 나오는 문제 해결" excerpt: "" categories: - soso tags: - image upload last_modified_at: --- 그램을 4년쨰 쓰고 있는데, 2년 전인가 어느 순간부터 오디오가 안되기 시작했다. 정확하게는 오디오 드라이버가 없는 문제 같았는데, 소리 버튼을 클릭할때마다 문제 검색 중..만 엄청 길게 뜨지 해결하지도 못했다. 단순히 내가 뭘 잘못 조작하다가 오디오 드라이버를 삭제했겠거니 하고 LG 공식 사이트에서 하라는 대로도 오디오 드라이버도 설치해보고, 그게 안돼서 LG DNA plus center 등등 안해본게 없었는데, 어떤 네이버 블로그 글을 보니까 나만 이렇게 삽질했던게 아닌 것 같다. 나랑 같은 문제로 오디오가 안되셨는데 해결한 방법을 굉장히 친절하게 적어주셨다. 얼마 걸리지도 않는데 하고 나니까 정말 거짓말같이 소리가 아주 잘 나온다,,,,^^ 그동안 엄청 긴 시간동안 삽질했던게 억울할 정도다. **[해결 방법 네이버 블로그 링크](https://m.blog.naver.com/PostView.nhn?blogId=lena_nyang&logNo=221136375575&proxyReferer=https:%2F%2Fwww.google.com%2F)** ======================= File: _posts/App/iOS/2021-09-13-UICollectionVIew.md ======================= --- layout: post title: "[iOS] - UICollectionView란?" subtitle: "" categories: app tags: app-ios uicollectionview comments: true header-img: --- > `UICollectionView에 대해 자세히 알고 넘어가자` --- UICollectionView 없이 근사한 UI를 가진 앱을 만들기가 힘들다. UICollectionView를 이용해서 화면을 구현하는 데 헷갈리는 점도 많고 막히는 점도 많아 이 기회에 개념과 막히는 부분들을 중점으로 짚고 넘어가 보려고 한다. # [UICollectionView](https://developer.apple.com/documentation/uikit/uicollectionview?language=objc) https://developer.apple.com/documentation/uikit/uicollectionview?language=objc 공식문서에 따르면, UICollectionView는 데이터 아이템들의 순서가 있는 컬렉션을 관리하고, 이들을 커스터마이징이 가능한 레이아웃을 사용해서 출력하는 객체다. 즉 순서 개념이 있는 아이템들을 관리하고, 레이아웃을 통해 출력하는데 이 레이아웃을 사용자가 마음대로 구현할 수 있다는 뜻이다. 컬렉션 뷰를 사용자 인터페이스에 추가할 때, 앱이 해야 하는 주요 작업은 컬렉션 뷰와 관련있는 데이터를 관리하는 것이다. 컬렉션 뷰는 자신의 [`dataSource`](https://developer.apple.com/documentation/uikit/uicollectionview/1618091-datasource?language=objc) 프로퍼티에 저장된 데이터들을 가져온다. Data source에는 [`UICollectionViewDiffableDataSource`](https://developer.apple.com/documentation/uikit/uicollectionviewdiffabledatasource?language=objc)를 사용할 수 있는데, 이 `DiffableDataSource` 객체는 iOS 13 이상부터 사용이 가능하다. 이 객체는 컬렉션 뷰의 데이터에 변경사항이 생겼을 때 뷰의 데이터와 사용자 인터페이스에 생기는 변화를 효과적으로 관리하게 해준다. 대신, `UICollectionViewDataSource` 프로토콜을 채택해서 커스텀 data source 객체를 만들 수 있다. 컬렉션 뷰의 데이터는 화면에 출력할 때 섹션으로 묶어 그룹으로 나눌 수 있는 개별 아이템으로 구성된다. 아이템은 출려가고 싶은 데이터의 가장 작은 단위이다. 예를 들어 사진 앨범과 같은 앱에서 아이템은 사진이 될 것이다. 컬렉션 뷰는 data source가 구성하고 제공하는 `UICollectionViewCell`의 인스턴스인 cell을 사용해서 아이템을 화면에 출력한다. ![image](https://user-images.githubusercontent.com/41438361/133023765-c68e97a7-366c-482e-938e-b4c59f6916a2.png) Cell에 추가로, 컬렉션 뷰는 다른 타입의 뷰를 사용해서 데이터를 출력할 수도 있다. 이런 보조적인 뷰(위의 사진에서 supplementary view로 나와있는 부분이다.)들은 예를 들어 개별 cell과는 다르지만 여전히 정보를 포함하고 있는 섹션 헤더와 푸터가 될 수 있다. 위의 그림에서도 사진들은 개별 아이템인 cell로 출력이 되고 있고, 금색 제목 영역인 characters 나 items는 섹션 헤더로 보조적인 역할을 수행하는 뷰라고 할 수 있다. 이런 보조적인 뷰를 지원하는 것은 선택적이며 컬렉션 뷰의 레이아웃 객체에 의해 정의된다. 이 레이아웃 객체는 이런 뷰들의 배치까지도 정의한다. ![image](https://user-images.githubusercontent.com/41438361/133024739-e953e73a-9c2c-4de7-8b48-8777adc8341f.png) `UICollectionView`를 사용자 인터페이스에 임베딩할 때, 화면에 출력되는 아이템의 순서가 data source 객체에 있는 순서와 일치하는 것을 보장하게 컬렉션 뷰의 메서드를 구현해야 한다. `UICollectionViewDiffableDataSource`(앞에서 나온 iOS13 이상부터 쓸 수 있었던 data source) 객체는 이런 작업을 자동으로 해준다. 만약 커스텀 data source를 사용하고 있다면, 컬렉션의 데이터를 추가하고, 삭제하거나 재배치를 할 때, `UICollectionView`의 메서드를 사용해서 일치하는 셀들을 삽입, 삭제, 그리고 재배치해야 한다는 것이다. 이게 정확히 무슨 말이냐면, data source에서 컬렉션 뷰가 데이터를 가져오고 이를 바탕으로 화면에 실제로 출력하는 작업을 하기 때문에 data source가 변경되면 컬렉션 뷰는 변경사항을 화면에 업데이트 해줘야 한다. ![image](https://user-images.githubusercontent.com/41438361/133025364-cc68ee4e-97bc-41aa-89f3-66e545505439.png) 추가로 아이템들을 선택하는 행위는 [`delegate`](https://developer.apple.com/documentation/uikit/uicollectionview/1618033-delegate?language=objc)객체를 통해 관리하지만, 선택된 객체를 관리하는 작업은 컬렉션 뷰 객체를 이용해 관리한다. ## Layout 위에서 보조적인 뷰를 지원하고 뷰들의 배치를 레이아웃 객체가 관리한다고 했을 때 잠깐 레이아웃에 대한 얘기가 나왔다. 레이아웃 객체는 이름에서도 알 수 있듯이 컬렉션 뷰에 있는 컨텐츠의 시각적인 배치를 정의한다. [`UICollectionViewLayout`](https://developer.apple.com/documentation/uikit/uicollectionviewlayout?language=objc)의 하위 크래스인 레이아웃 객체는 컬렉션 뷰 내의 모든 셀과 보조적인 뷰의 구성과 위치를 정의한다. 컬렉션 뷰는 셀들과 보조적인 뷰들의 생성이 컬렉션 뷰와 data source 객체 사이의 연결하는 과정에 개입하기 때문에 레이아웃 정보를 레이아웃을 적용할 적절한 뷰들에 적용한다. 레이아웃 객체는 다른 data source와 비슷하지만, 아이템의 데이터 대신에 시각적인 정보를 제공한다는 점에서 다르다. 일반적으로 컬렉션 뷰를 생성할 때 레이아웃 객체를 생성하지만, 컬렉션 뷰의 레이아웃을 동적으로 변경할 수도 있다. 레이아웃 객체는 [`collectionViewLayout`](https://developer.apple.com/documentation/uikit/uicollectionview/1618047-collectionviewlayout?language=objc)에 저장되어 있다. 이 프로퍼티를 직접 설정하면 애니메이션을 적용하지 않고 레이아웃을 즉각적으로 업데이트 한다. 만약 변화를 애니메이션을 통해 보여주고 싶다면 [`setCollectionViewLayout:animated:completion:`](https://developer.apple.com/documentation/uikit/uicollectionview/1618017-setcollectionviewlayout?language=objc)메서드를 호출하면 된다. Gesture recognizer나 터치 이벤트에 의한 상호작용 transition을 생성하려면 [`startInteractiveTransitionToCollectionViewLayout:completion:`](https://developer.apple.com/documentation/uikit/uicollectionview/1618098-startinteractivetransitiontocoll?language=objc) 메서드를 사용해서 레이아웃 객체를 변화시키면 된다. 이 메서드는 transition progress를 추적하기 위한 gesture recognizer나 event-handling 코드와 함께 작동하는 중간의 레이아웃 객체를 설치한다. 이벤트 핸들링 코드가 transition이 끝났음을 알게 되면, 앞서 받았던 이 중간의 객체를 삭제하고 intented target layout 객체를 설치하기 위해 [`finishInteractiveTransition`](https://developer.apple.com/documentation/uikit/uicollectionview/1618080-finishinteractivetransition?language=objc)나 [`cancelInteractiveTransition`] 메서드를 호출한다. 더 많은 것을 보려면 [`Layouts`](https://developer.apple.com/documentation/uikit/views_and_controls/collection_views/layouts?language=objc)를 참고하면 된다. ## Cell과 Supplementary View 컬렉션 뷰의 data source 객체는 아이템을 위한 컨텐츠와 이 컨텐츠를 출력하기 위해 사용되는 뷰를 같이 제공한다. 컬렉션뷰가 컨텐츠를 처음 로딩했을 때, data source에게 각각의 화면에 보여져야 할 아이템을 위한 뷰를 제공해달라고 요청한다. 컬렉션 뷰는 data source가 재사용하겠다고 마크한 뷰 객체들의 큐나 리스트를 관리한다. 코드에서 명시적으로 새로운 뷰들을 생성하는 것 대신에, deque된 뷰를 사용하는 것이 좋다. 즉 컬렉션 뷰는 cell에 해당하는 뷰를 재사용하는데, 이 뷰들을 관리하는 큐/리스트를 가지고 있다는 소리다. 재사용할 뷰를 dequeing 하는 두 가지의 메서드가 있다. 요청된 뷰가 어떤 타입인지에 따라서 다른 메서드를 요청하면 된다. * 컬렉션 뷰의 아이템의 cell을 가져오려면 [`dequeueReusableCellWithReuseIdentifier:forIndexPath:`](https://developer.apple.com/documentation/uikit/uicollectionview/1618063-dequeuereusablecellwithreuseiden?language=objc)를 사용하면 된다. * 레이아웃 객체에 의해 요청된 supplementary view를 가져오기 위해 [`dequeueReusableSupplementaryViewOfKind:withReuseIdentifier:forIndexPath:`](https://developer.apple.com/documentation/uikit/uicollectionview/1618068-dequeuereusablesupplementaryview?language=objc)를 사용하면 된다. 이 메서드들을 호출하기 이전에, 만약 뷰가 존재하지 않는 상태였다면 이 뷰를 어떻게 생성하는지 컬렉션 뷰에 알려줘야 한다. 이를 위해서 컬렉션 뷰에 클래스나 nib 파일을 등록해야 한다. 예를 들어 cell을 등록할 때, 클래스를 등록하기 위해서 [`registerClass:forCellWithReuseIdentifier:`](https://developer.apple.com/documentation/uikit/uicollectionview/1618089-registerclass?language=objc) 메서드를 사용하고, nib 파일을 등록하려면 [`registerNib:forCellWithReuseIdentifier:`](https://developer.apple.com/documentation/uikit/uicollectionview/1618083-registernib?language=objc)를 사용하면 된다. 등록하는 과정의 일부로, 뷰의 목적을 잘 나타내는 reuse identifier를 정의해야 한다. 이 identifier를 이용해서 나중에 뷰를 dequeing한다. Data source 메서드에서 적절한 뷰를 dequeueing핬다면, 이 뷰의 컨텐츠를 채우고, 이를 컬렉션 뷰에 리턴해서 사용하게 한다. 레이아웃 객체에서 레이아웃 정보를 얻은 후, 컬렉션 뷰가 뷰에 적용해서 출력할 것이다. ![image](https://user-images.githubusercontent.com/41438361/133027949-ab6732be-64ef-462f-a531-d9c1575648b9.png) ## Data Prefetching 컬렉션 뷰는 반응성을 향상시키기 위해 두 가지의 prefetching 기술을 제공한다. 하나는 뷰를, 하나는 데이터를 미리 불러오는 기술이다. * Cell prefetching은 셀이 요청되기 이전에 cell을 항상 준비해 놓는 것이다. 컬렉션 뷰가 많은 수의 셀들을 갑자기 한 번에 요청할 때, 예를 들어 grid layout의 새로운 행의 cell들은 display를 위해 요청된 때보다 더 먼저 요청된다. 셀 렌더링은 그래서 여러 레이아웃을 통해 전달되고, 더 스크롤링이 부드럽게 될 수 있다. 이 Cell prefetching은 기본적으로 활성화 되어 있는 상태이다. * Data prefetching은 셀을 요청하기 앞서서 컬렉션 뷰에 데이터 요청이 들어왔을 때 일어난다. 셀의 컨텐츠가 굉장히 오래걸리는 데이터 로딩 프로세스(네트워크 프로세스같은 애들)에 의존할 때 유용하다. 셀을 위한 데이터를 언제 prefetch할 지 알림을 받고 싶다면 [`UICollectionViewDataSourcePrefetching`](https://developer.apple.com/documentation/uikit/uicollectionviewdatasourceprefetching?language=objc)프로토콜을 채택한 객체를 [`prefetchDataSource`](https://developer.apple.com/documentation/uikit/uicollectionview/1771768-prefetchdatasource?language=objc) 프로퍼티에 할당한다. 이 cell prefetching과 data prefetching도 별개로 설명하고 있는 애플 공식문서가 있으니 참고해봐도 좋을 것 같다. https://developer.apple.com/documentation/uikit/uicollectionviewdatasourceprefetching/prefetching_collection_view_data?language=objc ## 상호작용으로 아이템 재배치하기 컬렉션 뷰는 사용자 상호작용에 따라서 아이템을 이동할 수 있게 한다. 보통 컬렉션 뷰의 아이템의 순서는 data source에서 결정된다. 만약 사용자가 아이템을 재배치하게 했다면, 컬렉션 뷰의 아이템과 사용자의 상호작용을 추적할 수 있는 gesture recognizer를 구성하고 아이템의 위치를 업데이트 할 수 있다. 아이템을 상호작용하는 것으로 재배치하기 위해, 컬렉션 뷰의 [`beginInteractiveMovementForItemAtIndexPath:`](https://developer.apple.com/documentation/uikit/uicollectionview/1618019-begininteractivemovementforitema?language=objc)를 호출한다. Gesture recognizer가 터치 이벤트를 추적할 때, 터치하는 위치의 변화를 알리기 위해 [`updateInteractiveMovementTargetPosition:`](https://developer.apple.com/documentation/uikit/uicollectionview/1618079-updateinteractivemovementtargetp?language=objc) 메서드를 호출한다. Gesture를 추적하는 것을 마쳤다면 상호작용을 종료하고 컬렉션 뷰를 업데이트 하기위해 [`endInteractiveMovement`](https://developer.apple.com/documentation/uikit/uicollectionview/1618082-endinteractivemovement?language=objc)나 [`cancelInteractiveMovement`](https://developer.apple.com/documentation/uikit/uicollectionview/1618076-cancelinteractivemovement?language=objc) 메서드를 호출한다. 상호작용 도중에, 컬렉션 뷰는 아이템의 현재 위치를 반영하기 위해 레이아웃을 동적으로 비활성화한다. 만약 아무것도 하지 않으면, 기본 레이아웃 변경이 아이템에 적용될 것이지만 원한다면 레이아웃 애니메이션을 커스터마이징 할 수 있다. 만약 상호작용이 끝나면, 컬렉션 뷰는 아이템의 새로운 위치와 함께 data source를 업데이트 한다. `UICollectionViewController` 클래스는 관리되는 컬렉션 뷰 내의 아이템을 재배치하는데 사용할 수 있는 기본 gesture recognizer를 제공한다. 이 gesture recognizer를 설치하려면 컬렉션 뷰의 `installsStandardGestureForInteractiveMovement` 프로퍼티를 YES로 설정한다. # [UICollectionViewFlowLayout](https://developer.apple.com/documentation/uikit/uicollectionviewflowlayout?language=objc) UICollectionView의 레이아웃을 정의할 때 `UICollectionViewFlowLayout`을 자주 사용한다. `UICollectionViewFlowLayout`은 각 섹션에 아이템들을 그리드로 구성한다. 여기에 헤더와 푸터 뷰가 추가될 수 있다. Flow layout은 collection view layout의 한 타입이다. 컬렉션 뷰 안에 있는 아이템들은 scrolling direction에 따라 한 행이나 열 내에 나열되고, 각 행은 최대한 많은 셀들로 채워진다. 셀들은 같은 사이즈일 수 있고, 다른 사이즈일 수 있다. Flow layout은 각 섹션과 그리드에서 아이템, 헤더, 푸터의 사이즈를 결정하기 위해 컬렉션 뷰의 delegate 객체와 같이 작동한다. 이 Delegate 객체는 꼭 `UICollectionViewDelegateFlowLayout` 프로토콜을 채택하고 있어야 한다. 이 delegate를 사용하면 레이아웃 정보를 동적으로 적용할 수 있게 된다. 예를 들어, delegate 객체를 사용해서 그리드에 있는 아이템들에 각각 다른 사이즈를 적용할 수 있다. 만약 delegate를 제공하지 않으면 flow layout은 클래스의 프로퍼티에 설정한 기본 값을 사용하게 된다. Flow layout은 한 방향에서의 고정된 거리와 다른 쪽의 scrollable 거리를 이용해서 컨텐츠를 배치한다. 예를 들어 수직으로 스크롤할 수 있는 그리드라면, 그리드 컨텐츠의 너비는 컬렉션 뷰의 너비에 맞춰질 것이고, 높이는 그리드에 있는 섹션과 아이템의 개수에 따라 동적으로 조정될 것이다. 레이아웃은 기본적으로 수직으로 스크롤링 되지만, `scrollDirection` 프로퍼티를 사용해서 스크롤링되는 방향을 조정할 수 있다. Flow layout에 있는 각 섹션은 커스텀 헤더와 푸터를 가질 수 있다. 뷰의 헤더와 푸터를 구성하기 위해서, 헤더와 푸터의 사이즈를 non-zero 값으로 조정해야 한다. ## [UICollectionViewFlowLayoutAutomaticSize](https://developer.apple.com/documentation/uikit/uicollectionviewflowlayoutautomaticsize?language=objc) `estimatedItemSize` 프로퍼티를 이 값으로 설정해서 컬렉션 뷰에서 셀들이 알아서 사이즈가 정해질 수 있도록 한다. 이 값은 non-zero이고, 컬렉션 뷰가 셀의 실제 사이즈를 얻기 위해 셀의 [`preferredLayoutAttributesFittingAttributes:`](https://developer.apple.com/documentation/uikit/uicollectionreusableview/1620132-preferredlayoutattributesfitting?language=objc) 메서드를 사용하게 하는 placeholder 값이다. ======================= File: _posts/C#/2020-11-19-Delegate.md ======================= <filename>_posts/C#/2020-11-19-Delegate.md --- title: "[C#] Delegate - 콜백, 체인" excerpt: "" toc: true toc_sticky: true toc_label: "페이지 주요 목차" header: teaser: categories: - csharp tags: - 공부 - C# - delegate - callback - chain last_modified_at: 2020-11-19 --- ## Delegate(델리게이트) Delegate의 사전적 의미는 '대리인'이다. c++의 포인터와 비슷하게 생각하면 된다. 이 대리인이라는 것은 내가 할 일을 다른 사람에게 위임하는 것이다. 프로그래밍에서도 이런 대리인 역할을 해주는게 존재하는데, 그게 Delegate이다. 델리게이트는 **메소드를 대신해서 호출하는 역할**을 한다. 즉 메소드의 대리인 역할을 하는 것이다. 원래는 특정 메소드를 처리할 때 그 메소드를 직접 호출해서 실행시켜야 했지만, 델리게이트를 사용하면 그 메소드를 대신해서 호출할 수 있다. ## Delegate 선언, 참조 Delegate로 특정 메소드를 대신 호출하려면 1. 해당 메소드와 동일한 타입의 델리게이트 타입을 선언 2. 선언한 델리게이트 타입으로 델리게이트 변수를 생성하고, 생성한 델리게이트 변수에 해당 메소드를 참조시킨다.(포인터와 유사하다) 먼저 동일한 타입의 델리게이트 타입을 선언한다. ```c# // delegate 리턴타입 이름(매개 변수); delegate void typeA(void); // void funcA(void) delegate void typeB(int); // void funcB(int) delegate float typeC(float); // float funcC(float) ``` 타입으로 델리게이트 변수를 생성해서 그 변수에 메소드를 참조시킨다. ```c# // 변수 생성 typeA delegate_a; typeB delegate_b; typeC delegate_c; // 메소드 참조 delegate_a = new typeA(funcA); delegate_b = new typeB(funcB); delegate_c = new typeC(funcC); ``` 이 방법을 적용하여 덧셈과 뺄셈을 하는 코드를 작성해보자. ```c# namespace Sample { delegate int DelegateType(int a, int b); class MainApp { public static int Plus(int a, int b){ return a + b; } public static int Sub(int a, int b){ return a - b; } static void Main(string[] args){ DelegateType delegateVar; delegateVar = new DelegateType(Plus); int sum = delegateVar(11, 12); Console.WriteLine("11 + 12 - {0}", sum); delegateVar = new DelegateType(Sub); int sub = delegateVar(11, 12); Console.WriteLine("11 - 12 - {0}", sub); } } } ``` ## Callback method 위의 더하기 빼기 코드를 보면 한 델리게이트 변수에 한 함수를 참조하게 하고 다음에 바로 참조 위치를 바꿔버린다. 그런데 이렇게 델리게이트를 쓰는 것은 정말 의미가 없다. 메소드를 직접 호출하면 되고, 굳이 델리게이트를 쓸 이유가 없어지는 것이다. 델리게이트는 **콜백 메소드**를 구현할 때 진가를 발휘한다. 콜백(Callback)이란 A라는 메서드를 호출할 때 B라는 메서드를 넘겨줘서 A가 B 메서드를 호출하도록 하는 것이고, 이때 A를 콜백 메서드라고 한다. 구조를 보면 A 메서드 안에 Delegate를 선언하고, 이 Delegate로 다른 함수를 호출할 수 있는데 이게 B 메서드를 참조하는 것이다. 예제는 아래와 같다. ```c# namespace Sample { delegate int DelegateType(int a, int b); class MainApp { public static void Calculator(int a, int b, DelegateType delegateVar){ Console.WriteLine(delegateVar(a,b)); } public static int Plus(int a, int b){ return a + b; } public static int Sub(int a, int b){ return a - b; } static void Main(string[] args){ DelegateType plus = new DelegateType(Plus); DelegateType sub = new DelegateType(Sub); Calculator(11, 12, plus); Calculator(11, 12, sub); } } } ``` 정말 간편하다. 계산기 함수를 호출할때마다 원하는 연산(메소드)를 넘겨줘서 계산기가 기능을 하도록 하고 있다. ## Delegate 일반화 위에서는 Delegate의 타입을 선언할 때 참조할 수 있는 메서드 타입을 지정했지만, 이를 일반화하면 타입과 상관 없이 메소드를 참조할 수 있다. ```c# namespace Sample { delegate T DelegateType<T>(T a, T b); class MainApp { public static void Calculator<T>(T a, T b, DelegateType<T> delegateVar){ Console.WriteLine(delegateVar(a,b)); } public static int PlusInt(int a, int b){ return a + b; } public static float PlusFloat(float a, float b){ return a + b; } static void Main(string[] args){ DelegateType plusInt = new DelegateType(PlusInt); DelegateType plusFloat = new DelegateType(PlusFloat); Calculator(11, 12, plusInt); Calculator(1.1f, 2.2f, plusFloat); } } } ``` ## Delegate Chain 위에서는 하나의 델리게이트가 하나의 메소드를 참조할 수 있게 했다. 그런데 델리게이트는 여러개의 메소드도 참조할 수 있다. 아주 간편한게, 아래와 같이 +, += 연산자로 새로운 메소드를 추가해주면 된다. ```c# DelegateType delegateVar; delegateVar = new DelegateType(func1); delegateVar += func1; delegateVar += func2; ``` 이제 델리게이트를 호출하면 참조된 메소드들을 차례대로 호출한다. 이렇게 하나의 델리게이트에 여러 메소드를 연결시키는 것을 **델리게이트 체인**이라고 한다. 반대로 델리게이트에 연결된 메소드를 끊고 싶으면 -=를 해주면 된다. ```c# namespace Sample { delegate void delType(); class MainApp { public static void func1() { Console.Write("first"); } public static void func2() { Console.Write("second"); } public static void func3() { Console.Write("third"); } static void Main(string[] args){ delType delVar; delVar = new delType(func1); delVar += func2; delVar += func3; delVar(); delVar -= func1; delVar -= func2; delVar(); } } } ``` [출처 및 참고](https://mrw0119.tistory.com/19) ======================= File: _posts/App/iOS/2021-10-19-idfa att.md ======================= <filename>_posts/App/iOS/2021-10-19-idfa att.md --- layout: post title: "[iOS] - IDFA, AppTrackingTransparency ATT란?" subtitle: "" categories: app tags: app-ios idfa att comments: true header-img: --- > `` --- ## IDFA란? IDFA(광고주 식별자)는 Apple에서 사용자의 기기에 할당한 임의 기기 식별자다. 광고주는 이를 사용해서 데이터를 추적하고 맞춤형 광고를 하는 것이다. IDFA는 개인 정보를 노출하지 않고 사용자를 추적하고 식별하는 데 사용된다. 이 IDFA는 기기마다 내장된 고유한 값이어서 사용자가 여러 앱들을 사용한다고 해도 사용되는 건 기기가 갖고 있는 하나의 고유한 식별자가 된다. 그래서 사용자는 광고 추적 제한 기능을 활성화하지 않는 한 여러 회사에서 트래킹 당하게 된다. 원래는 iOS 13 이하에서는 사용자가 직접 설정 - 개인 정보 보호 - 광고 메뉴에서 광고 추적 제한 옵션을 활성화 해야 했는데, iOS 14부터는 아래 화면 처럼 사용자에게 트래킹 권한을 요청하는 방식으로 바뀌게 되었다. ![image](https://user-images.githubusercontent.com/41438361/137869373-6b0e3343-df1b-4d14-9a2c-3234d8d63956.png) 그런데 iOS 14에 추가된 개인 정보 보호 기능들 때문에 애플의 광고 식별자(IDFA) 정책도 바뀌게 되었다. 또한 iOS 14.5 버전부터 AppTrackingTransparency를 강제하게 바뀌었다. App Tracking Transparency는 ATT로, 앱 추적 투명성을 의미한다. ## ATT란? App Tracking Transparency는 사용자가 Opt-In 않으면 iOS 광고 ID인 IDFA에 접근할 수 없게 되는 것이다. 일반적으로 광고 리타겟팅은 광고 ID를 기반으로 하기 때문에 Opt-In하지 않는 비율이 높아질 수록 리타겟팅은 정확도가 떨어지게 된다. 참고로 이 Opt-In과 Opt-out은 iOS 14.5 이상 버전에서 나온 것으로 IDFA 수집 방식이 이 두 방법으로 강제된다. * Opt-out : 기본적으로 수집할 수 있으나, 사용자가 수집 거부할 수 있다. * Opt-In : 기본적으로 수집을 할 수 없고, 사용자의 동의를 통해서만 수집이 허용된다. * 참고 * https://www.adjust.com/ko/glossary/idfa/ * https://archivers.tistory.com/58 * https://brunch.co.kr/@hae-ra/33 ======================= File: _posts/ChatBot/MSAzure/2020-07-10-사용자 입력 수집위한 고유 메세지 만들기.md ======================= <reponame>Yoojin99/Yoojin99.github.io<filename>_posts/ChatBot/MSAzure/2020-07-10-사용자 입력 수집위한 고유 메세지 만들기.md --- title: "Chatbot - 사용자 입력 수집 위한 고유 메세지 만들기" excerpt: "사용자 입력을 수집하도록 고유한 메세지 만들기" toc: true toc_sticky: true toc_label: "페이지 주요 목차" header: teaser: categories: - cb tags: - cb-ma - 공부 - Azure last_modified_at: --- 사용자 입력을 수집하도록 고유한 메세지 만들기 ============================================= 공식 문서에서 든 예시는 아래와 같다. 샘플 봇은 사용자에게 일련의 질문을 하고, 답변이 유효한지 검사해서 입력을 저장한다. 밑에 있는 그림은 봇과 사용자 프로필, 대화 흐름 클래스의 관계를 나타낸 그림이다. ![custompromptbotsample-overview](https://user-images.githubusercontent.com/41438361/87068679-e8f89980-c250-11ea-9338-14d377d01ed8.png) * UserProfile : 봇에서 수집할 사용자 정보에 대한 클래스 * ConversationFlow : 사용자 정보를 수집하는 동안 대화 상태를 제어하는 클래스 * ConversationFlow.Question : 대화 중인 위치를 추적하는 열거형 사용자 상태에서는 사용자 정보(이름, 나이, 선택한 날짜)를 추적하고 대화 상태에서는 사용자에게 질문한 내용을 추적한다. 여기서는 봇을 배포하지 않으므로 메모리 스토리지를 사용하도록 사용자 및 대화 상태를 모두 구성한다. ## 대화 및 사용자 개체 만들기 시작 시 사용자 및 대화 상태 개체를 만들고 봇 생성자에서 종속성 주입을 통해 해당 개체를 사용합니다. **Startup.cs[!code-csharpStartup.cs]** **Bots/CustomPromptBot.cs[!code-csharpconstructor]** 이 대괄호 안에 나오는 저게 대체 무슨 말인지 모르겠어서 찾아봤는데 잘 나오지 않는다...ㅠㅠ ## 속성 접근자 만들기 사용자 프로필 및 대화 흐름 속성에 대한 속성 접근자를 만든 다음, GetAsync을 호출하여 상태에서 속성 값을 검색한다. **Bots/CustomPromptBot.cs** ```C# protected override async Task OnMessageActivityAsync(ITurnContext<IMessageActivity> turnContext, CancellationToken cancellationToken) { var conversationStateAccessors = _conversationState.CreateProperty<ConversationFlow>(nameof(ConversationFlow)); var flow = await conversationStateAccessors.GetAsync(turnContext, () => new ConversationFlow(), cancellationToken); var userStateAccessors = _userState.CreateProperty<UserProfile>(nameof(UserProfile)); var profile = await userStateAccessors.GetAsync(turnContext, () => new UserProfile(), cancellationToken); ``` 이거는 전에 포스팅했던 사용자 대화 및 상태 저장에서도 나온 것이다. turn이 끝나기 전에 SaveChangesAsync를 호출해서 스토리지에 상태 변경 내용을 작성한다. ```C# // Save changes. await _conversationState.SaveChangesAsync(turnContext, false, cancellationToken); await _userState.SaveChangesAsync(turnContext, false, cancellationToken); } ``` ## 봇의 메세지 턴 처리기 메세지 작업을 처리할 때 메세지 처리기는 도우미 메서드를 사용하여 대화를 관리하고 사용자에게 메세지를 표시한다. ## 사용자 프로필 작성 봇은 이전 턴에서 요청된 봇의 질문에 따라 정보를 묻는 메세지를 사용자에게 표시한다. [https://github.com/microsoft/BotBuilder-Samples/blob/master/samples/csharp_dotnetcore/44.prompt-users-for-input/Bots/CustomPromptBot.cs](https://github.com/microsoft/BotBuilder-Samples/blob/master/samples/csharp_dotnetcore/44.prompt-users-for-input/Bots/CustomPromptBot.cs) ======================= File: _posts/React/ReactNative/2020-08-31-Design_Color Reference.md ======================= <gh_stars>1-10 --- title: "React Native - Design - Color Reference" excerpt: "" toc: true toc_sticky: true toc_label: "페이지 주요 목차" header: teaser: categories: - react tags: - react-rn - React Native last_modified_at: --- RN에서의 component들은 JavaScript를 이용해서 스타일링 된다. 색깔 property들은 CSS가 웹에서 동작하는 방식과 비슷하다. ## Color API RN는 여러 색깔 API를 제공한다. * PlatformColor는 플랫폼의 색깔 시스템을 참조할 수 있게 한다. * DynamicColorIOS는 iOS 특정적이고 light와 dark 모드에서 어떤 색깔을 사용할 지 결정할 수 있게 한다. ## 색깔 표기법 ### RGB RN은 16진법과 함수 표기법 모두를 `rgb()`와 `rgba()`로 지원한다. * `#f0f` (#rgb) * `#ff00ff` (#rrggbb) * `#f0ff` (#rgba) * `#ff00ff00` (#rrggbbaa) * `rgb(255, 0,255)` * `rgba(255,0,255, 1.0)` ### Hue Saturation Lightness (HSL) RN는 함수 표기법으로 `hsl()`과 `hsla()`를 지원한다. * `hsl(360, 100%, 100%)` * `hsla(360, 100%, 100%, 1.0)` ### Color ints RN은 또한 `int` 값으로 색을 지원한다. * `0xff00ff00` ### Named colors RN에서 색의 이름 문자열을 값으로 사용할 수도 있다. RN은 오직 소문자 이름만 취급한다. `transparent`는 `rgba(0,0,0,0)`의 줄임말이다. #### Color keywords 이름이 있는 색은 CSS3/SVG 명시를 따른다. ======================= File: _posts/App/iOS/2021-06-15-ContentOffset, ContentInset, ContentSize.md ======================= <reponame>Yoojin99/Yoojin99.github.io --- layout: post title: "[iOS] - UIScrollView의 ContentOffset, ContentInset, ContentSize" subtitle: "" categories: app tags: app-ios comments: true header-img: img/dev/app/ios/XcodeImg.png --- > `ContentOffset, ContentInset, ContentSize 차이에 대해 알아보자.` --- UIScrollView의 프로퍼티 중 `contentInset`, `contentOffset`, `contentSize`가 가장 많이 사용되는 것들 중 하나일 것이다. ## [contentOffset](https://developer.apple.com/documentation/uikit/uiscrollview/1619404-contentoffset) 정의 : scroll view 의 origin에서 content view의 origin까지 얼마나 떨어졌는지를 나타내는 포인트 즉 사용자가 영역을 스크롤 한 후에 있는 지점을 의미한다. 그래서 사용자가 스크롤을 할 때마다 이 지점이 바뀌게 된다. 만약 주어진 포지션이 존재할 때, 해당 위치로 스크롤하기 위해서 코드 상으로 설정될 수 있다. ```swift scrollView.setContentOffset(CGPoint(x: 50, y: 50), animated: true) ``` ## [contentInset](https://developer.apple.com/documentation/uikit/uiscrollview/1619406-contentinset) 정의 : content view의 Inset이 safe area 나 scroll view에서 얼마나 떨어졌는지를 의미한다. 즉 `contentInset`은 UIScrollView에서 `innnerView`까지 얼마나 마진이 떨어져있는지를 의미한다. `childView`에 내부 여백을 준다고 생각하면 된다. 이 프로퍼티는 오로지 코드 상으로만 설정될 수 있다. ```swift scrollView.contentInset = UIEdgeInsets(top: 7, left: 7, bottom: 7, right: 7) ``` ## [contentSize](https://developer.apple.com/documentation/uikit/uiscrollview/1619399-contentsize) 정의 : 컨텐츠 뷰의 사이즈 `contentSize`는 `UIScrollView`의 컨텐츠의 사이즈이고, `scrollView`가 얼마나 길어질 수 있는지를 나타낸다. 이것은 pagination처럼 동적이 될 수도 있고 contact list처럼 정적이 될 수도 있다. 런타임에서 값이 바뀔 수도 있다. ```swift scrollView.contentSize = CGSize(width: self.view.frame.size.width, height: 500) ``` ![image](https://user-images.githubusercontent.com/41438361/121978571-73337100-cdc3-11eb-853b-1f78d3bb086c.png) 출처 * https://betterprogramming.pub/contentoffset-contentinset-and-contentsize-of-a-uiscrollview-5ae8beb0f1db * ======================= File: _featured_tags/app-objc.md ======================= <reponame>Yoojin99/Yoojin99.github.io<gh_stars>1-10 --- layout: tag-blog title: Objective-c slug: app-objc category: app menu: false order: 3 --- Objective-c ======================= File: _posts/React/ReactNative/2020-08-28-Handling Text Input.md ======================= --- title: "React Native - Text Input 다루기" excerpt: "" toc: true toc_sticky: true toc_label: "페이지 주요 목차" header: teaser: categories: - react tags: - react-rn - React Native last_modified_at: --- ![image](https://user-images.githubusercontent.com/41438361/90485901-2404bb80-e173-11ea-8aaf-141b0555134b.png) TextInput은 사용자가 텍스트를 칠 수 있게 해주는 Core component이다. 매번 텍스트가 바뀌었을 때마다 호출되는 `onChangeText` prop과 매번 text가 submit되었을 때마다 호출되는 `onSumbitEditing` prop을 가지고 있다. 예를 들어, 유저가 타이핑 한 거를 다른 언어로 번역하려고 해본다고 하자. 이 새로운 언어에서는, 하나 하나의 단어가 🍕로 쓰인다. 그래서 "Hello there Bob"은 "🍕🍕🍕"으로 번역될 것이다. ```js import React, { useState } from'react'; import { Text, TextInput, View } from'react-native'; const PizzaTranslator = () =>{ const [text, setText] = useState(''); return( <View style={{padding: 10}}> <TextInput style={{height: 40}} placeholder="Type here to translate!" onChangeText={text=>setText(text)} defaultValue={text} /> <Text style={{padding: 10, fontSize: 42}}> {text.split(' ').map((word)=> word && '🍕').join(' ')} </Text> </View> ); } export default PizzaTranslator; ``` 이 예제에서 우리는 `text`를 state에 저장한다. (시간에 따라 바뀌기 때문) Text input을 가지고 굉장히 많은 것들을 할 수 있다. ======================= File: _posts/App/iOS/2021-06-19-APNS test.md ======================= <filename>_posts/App/iOS/2021-06-19-APNS test.md<gh_stars>1-10 --- layout: post title: "[iOS] - Push 알림, APNS 테스트를 위해 설정해야 하는 것들" subtitle: "" categories: app tags: app-ios comments: true header-img: img/dev/app/ios/XcodeImg.png --- > `실제 기기에서 push 알림을 테스트하기 위해 설정해야 하는 것들을 알아보자.` --- ## 1. 테스트 폰이 네트워크에 연결되어 있는가 테스트 폰이 네트워크에 연결되어 있지 않으면 `UIApplication.shared.registerForRemoteNotifications()` 이후에 register가 성공했는지 실패했는지에 따라 `func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)` 메서드나 `func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error)` 메서드가 실행이 되는데, 이것들이 제대로 실행되지 않는다. 따라서 먼저 테스트 기기가 네트워크에 잘 연결되어 있는지 확인해야 한다. ## 2. Info.plist의 bundle identifier 설정 ![image](https://user-images.githubusercontent.com/41438361/122646365-b8f09080-d159-11eb-884c-7e8bae98cf01.png) `Info.plist`에 `Bundle Identifier` 부분이 있는데, 이 부분이 앱의 bundle identifier로 잘 설정이 되었는지 확인해야 한다. ## 3. Signing & Capability가 제대로 설정되어 있는지 확인하기 ![image](https://user-images.githubusercontent.com/41438361/122646398-e5a4a800-d159-11eb-8504-e5e1aca8d0b0.png) 프로젝트 설정의 Signing & Capability에 1. push notifications 권한이 추가되어 있는지, (위 사진처럼) 2. 이 권한을 포함하는 provisioning profile이 적용이 잘 되었는지 를 확인하면 된다. 위의 세 가지 내용을 제대로 설정했다면 push 알림을 테스트 기기에서 테스트하기 위한 환경이 설정되었다. ======================= File: _posts/App/swift/2021-06-08-Swift Documentation.md ======================= --- layout: post title: "Swift - Documentation, 문서화하기" subtitle: "" categories: app tags: app-swift comments: true header-img: --- > `Swift의 문법을 이용해서 코드를 문서화 하는 방법을 알아보자.` --- ## 문서화 주석(Documentation Comments) & Swift에 맞는 Markdown 만약 이전에 Markdown 형식으로 문서를 작성해보지 않았더라고, 몇 분만에 이를 익힐 수 있다. ### 기본 Markup 문서화 주석은 일반 주석과 비슷해 보이지만, 추가적인 부분이 더 있다. 한 줄의 문서화 주석은 슬래시가 세 개로 구성된다. (`///`) 반면 여러 줄의 문서화 주석은 여는 구분 기호에 추가적인 별표 문자가 붙는다. (`/**... */`) 표준 마크다운은 문서화 주석의 규칙을 아래와 같이 적용한다. * 문단은 빈 줄로 구분한다. * 순서가 없는 리스트는 칸 문자(bullet characters)로 표시된다. (`-`, `+`, `*`, `•`) * 순서가 있는 리스트는 숫자(1, 2, 3,...) 뒤에 온점을 붙이거나(`1.`) 오른쪽 괄호를 붙여서(`1)`) 표시한다. * 헤더는 `#` 기호 뒤에 붙여서 표시하거나 아래 줄에 `=`나 `-`를 붙여서 표시한다. * 링크와 이미지도 붙일 수 있고, 웹을 기반으로 하는 이미지는 Xcode에서 바로 보여진다. ``` swift /** # Lists You can apply *italic*, **bold**, or `code` inline styles. ## Unordered Lists - Lists are great, - but perhaps don't nest; - Sub-list formatting... -...isn't the best. ## Ordered Lists 1. Ordered lists, too, 2. for things that are sorted; 3. Arabic numerals 4. are the only kind supported. */ ``` 문단 나누는 것을 더 보면, 아래의 코드는 한 문단으로 구성되지만, ``` swift /** This is your User documentation. A very long one. */ ``` 아래의 코드는 두 문단으로 구성된다. ``` swift /** This is your User documentation (This is summary). A very long one (This will be shown in the discussion section). */ ``` ### 요약 & 설명 문서화 주석 앞에 나오는 문단(paragraph)는 문서의 요약(Summary) 부분이 된다. 추가 컨텐츠는 `Discussion` 섹션으로 묶이게 된다. *만약 문서화 주석이 문단이 아닌 다른 것에 의해 시작된다면, 모든 컨텐츠는 Discussion에 속하게 된다. 또한 Discussion 부분에 추가를 하고 싶다면 새로운 문단을 작성하면 된다. 첫 번째 문단 아래에 오는 다른 것들은 다 discussion 부분에 속한다.* ``` swift /** This is your User documentation. A very long one. */ struct User { let firstName: String let lastName: String } ``` 위의 코드는 아래와 같이 요약 부분이 있는 문서를 생성한다. ![image](https://user-images.githubusercontent.com/41438361/121201535-90da7500-c8af-11eb-9399-42ccafcb1536.png) ### 파라미터 & 리턴 값 Xcode는 몇 개의 특별한 필드를 인식해서 이를 심볼의 설명과는 분리시켜 놓는다. 파라미터, 리턴 값, 그리고 throws 부분은 글머리 기호 뒤에 콜론(`:`)을 붙일 때 Quick Help 팝업과 inspector에서 구분 되어서 나온다. * 파라미터: `Parameter <param name>:`으로 시작하며 파라미터의 설명이 이어서 나온다. * 리턴 값: `Returns:` 로 시작하며 리턴 값에 대한 정보가 이어서 나온다. * 던져진 에러들: `Throws:`로 시작하며 throw될 수 있는 에러에 대한 설명이 이어서 나온다. Swift가 `Error` 규정에서 벗어나는 에러들은 타입을 체크하지 않기 때문에, 에러에 대해 문서화를 올바르게 하는 것은 중요하다. ``` swift /** Creates a personalized greeting for a recipient. - Parameter recipient: The person being greeted. - Throws: `MyError.invalidRecipient` if `recipient` is "Derek" (he knows what he did). - Returns: A new string saying hello to `recipient`. */ func greeting(to recipient: String) throws -> String { guard recipient!= "Derek" else { throw MyError.invalidRecipient } return "Greetings, \(recipient)!" } ``` Hacker News의 "tabs vs.spaces?"의 쓰레드보다 더 많은 인자를 포함하는 메서드를 문서화하고 있는가? `Parameters:` 를 적고 아래에 파라미터를 글머리표로 구분한 리스트로 구성해라. ``` swift /// Returns the magnitude of a vector in three dimensions /// from the given components. /// /// - Parameters: /// - x: The *x* component of the vector. /// - y: The *y* component of the vector. /// - z: The *z* component of the vector. func magnitude3D(x: Double, y: Double, z: Double) -> Double { return sqrt(pow(x, 2) + pow(y, 2) + pow(z, 2)) } ``` 참고로 파라피터를 개별로 다 작성할 수도 있다. ``` swift - Parameter x:... - Parameter y:... ``` Throws 부분을 작성한 예시는 아래와 같다. ``` swift /// A way that this user greets others. /// /// Use this method to get the greeting for the user. The person you specify don't affect the way user greet, just the first name, and last name will be used. /// - Warning: The greeting is always in the caller localization. /// - Throws: /// - `MyError.invalidPerson` /// if `person` is not known by the caller. /// - `MyError.hardToPronounce` /// if `person` name is longer than 20 characters. /// - Parameter person: `User` you want to greet /// - Returns: A greeting of the current `User`. func greeting(person: User) throws -> String { return "Hello \(person.firstName) \(person.lastName)" } ``` 화면 상에서는 아래와 같이 나온다. ![image](https://user-images.githubusercontent.com/41438361/121201623-9fc12780-c8af-11eb-8540-87e99aff2b74.png) 참고로 Throws 같은 경우는 구분자가 하나만 있을 수 있고, 여러개가 존재할 수 없다. ### 추가 필드 `Parameters`, `Throws`, `Returns`에 추가로, Swift에 맞는 마크다운은 아래와 같이 대강 구성될 수 있는 다른 필드들을 정의한다. **Algorithm/Safety Information** * `Precondition` : 전제조건 * `Postcondition` : 이후에 성립되어야 하는 조건 * `Requires` : 요구사항 * `Invariant` : 변형성 * `Complexity` : 복잡도 * `Important` : 중요한 점 * `Warning` : 경고 **Metadata** * `Author` : 저자 * `Authors` : 저자들 * `Copyright` : 저작권 * `Date` : 날짜 * `SeeAlso` : 추가로 봐야할 점들 * `Since` : 생성된 때 * `Version` : 버전 **General Notes & Exhortation** * `Attention` : 주의할 점 * `Bug` : 버그 * `Experiment` : 실험 * `Note` : 참고 * `Remark` : 비고 * `ToDo` : 해야 할 것 위의 각 필드들은 두꺼운 글씨의 헤더에 텍스트 블럭으로 Quick Help에 아래와 같이 표시된다. ![image](https://user-images.githubusercontent.com/41438361/121201671-a9e32600-c8af-11eb-8b66-f93c5e321f56.png) ### Code blocks 코드 블럭을 써서 함수의 적절한 사용이나 구현할 때 세부적인 내용을 보여준다. 코드 블럭은 최소 4개의 공백으로 만든다. ``` swift /** The area of the `Shape` instance. Computation depends on the shape of the instance. For a triangle, `area` is equivalent to: let height = triangle.calculateHeight() let area = triangle.base * height / 2 */ var area: CGFloat { get } ``` 세개의 백틱(\`\`)이나 물결표(`~`)로 코드를 감싸서 코드 불럭을 만들 수 있다. ``` swift /** The perimeter of the `Shape` instance. Computation depends on the shape of the instance, and is equivalent to: ~~~ // Circles: let perimeter = circle.radius * 2 * Float.pi // Other shapes: let perimeter = shape.sides.map { $0.length } .reduce(0, +) ~~~ */ var perimeter: CGFloat { get } ``` ## 실제 구현 예제 전체 클래스에 이를 적용해본 예제는 아래와 같다. ``` swift /// 🚲 A two-wheeled, human-powered mode of transportation. class Bicycle { /// Frame and construction style. enum Style { /// A style for streets or trails. case road /// A style for long journeys. case touring /// A style for casual trips around town. case cruiser /// A style for general-purpose transportation. case hybrid } /// Mechanism for converting pedal power into motion. enum Gearing { /// A single, fixed gear. case fixed /// A variable-speed, disengageable gear. case freewheel(speeds: Int) } /// Hardware used for steering. enum Handlebar { /// A casual handlebar. case riser /// An upright handlebar. case café /// A classic handlebar. case drop /// A powerful handlebar. case bullhorn } /// The style of the bicycle. let style: Style /// The gearing of the bicycle. let gearing: Gearing /// The handlebar of the bicycle. let handlebar: Handlebar /// The size of the frame, in centimeters. let frameSize: Int /// The number of trips traveled by the bicycle. private(set) var numberOfTrips: Int /// The total distance traveled by the bicycle, in meters. private(set) var distanceTraveled: Double /** Initializes a new bicycle with the provided parts and specifications. - Parameters: - style: The style of the bicycle - gearing: The gearing of the bicycle - handlebar: The handlebar of the bicycle - frameSize: The frame size of the bicycle, in centimeters - Returns: A beautiful, brand-new bicycle, custom-built just for you. */ init(style: Style, gearing: Gearing, handlebar: Handlebar, frameSize centimeters: Int) { self.style = style self.gearing = gearing self.handlebar = handlebar self.frameSize = centimeters self.numberOfTrips = 0 self.distanceTraveled = 0 } /** Take a bike out for a spin. Calling this method increments the `numberOfTrips` and increases `distanceTraveled` by the value of `meters`. - Parameter meters: The distance to travel in meters. - Precondition: `meters` must be greater than 0. */ func travel(distance meters: Double) { precondition(meters > 0) distanceTraveled += meters numberOfTrips += 1 } } ``` <kbd>⌥ – Option</kbd>을 누른 상태에서 이니셜라이저 선언 부분을 클릭하면, 설명이 말머리표로 구분되어 예쁘게 나온다. ![image](https://user-images.githubusercontent.com/41438361/121201751-b8314200-c8af-11eb-8607-ddfe74e69fd3.png) 그리고 마찬가지로 `travel`에 대한 Quick Documentation을 열면 파라미터는 별도의 필드로 구분되어 나오는 것을 확인할 수 있다. ![image](https://user-images.githubusercontent.com/41438361/121201778-bebfb980-c8af-11eb-9007-9152a83f591b.png) 추가로 또 다른 예제는 아래와 같다. ``` swift /** This is your User documentation. A very long one. # Text It's very easy to make some words **bold** and other words *italic* with Markdown. You can even [link to Google!](http://google.com) # Lists Sometimes you want numbered lists: 1. One 2. Two 3. Three Sometimes you want bullet points: * Start a line with a star * Profit! Alternatively, - Dashes work just as well - And if you have sub points, put two spaces before the dash or star: - Like this - And this # Code if (isAwesome){ return true } */ struct User { let firstName: String let lastName: String } ``` 위 코드는 아래와 같이 표시된다. ![image](https://user-images.githubusercontent.com/41438361/121201853-cc753f00-c8af-11eb-8952-bc1962bb0712.png) ## MARK / TODO / FIXME Objective-C에서 전처리기 지시문 `#pragma mark`는 기능을 의미있고 쉽게 찾을 수 있는 섹션으로 나누기 위해 사용되었다. Swift에서는 이를 `// MARK:`를 이용해서 같은 작업을 할 수 있다. 아래의 주석들은 Xcode source navigator에 노출된다. * `// MARK:` * `// TODO:` * `// FIXME:` 기존에 사용되었던 `NOTE`나 `XXX`와 같은 주석들은 Xcode에서 인식되지 않는다. *`#pragma`와 같이, 하나의 대시(`-`)가 뒤에 붙여진 마크들은 앞에 수평 분할기가 표시된다.* 이게 실제로 작동하는 것을 보기 위해, 위의 `Bicycle` 클래스가 `CustomStringConvertible` 프로토콜을 채택하고, `description` 프로퍼티를 구현해서 확장하는 방법은 아래와 같다. ![image](https://user-images.githubusercontent.com/41438361/121201886-d4cd7a00-c8af-11eb-8073-b40096418345.png) ``` swift // MARK: - CustomStringConvertible extension Bicycle: CustomStringConvertible { public var description: String { var descriptors: [String] = [] switch self.style { case.road: descriptors.append("A road bike for streets or trails") case.touring: descriptors.append("A touring bike for long journeys") case.cruiser: descriptors.append("A cruiser bike for casual trips around town") case.hybrid: descriptors.append("A hybrid bike for general-purpose transportation") } switch self.gearing { case.fixed: descriptors.append("with a single, fixed gear") case.freewheel(let n): descriptors.append("with a \(n)-speed freewheel gear") } switch self.handlebar { case.riser: descriptors.append("and casual, riser handlebars") case.café: descriptors.append("and upright, café handlebars") case.drop: descriptors.append("and classic, drop handlebars") case.bullhorn: descriptors.append("and powerful bullhorn handlebars") } descriptors.append("on a \(frameSize)\" frame") // FIXME: Use a distance formatter descriptors.append("with a total of \(distanceTraveled) meters traveled over \(numberOfTrips) trips.") // TODO: Allow bikes to be named? return descriptors.joined(separator: ", ") } } ``` 이를 코드에서 모두 보여준다. ``` swift var bike = Bicycle(style:.road, gearing:.freewheel(speeds: 8), handlebar:.drop, frameSize: 53) bike.travel(distance: 1_500) // Trip around the town bike.travel(distance: 200) // Trip to the store print(bike) // "A road bike for streets or trails, with a 8-speed freewheel gear, and classic, drop handlebars, on a 53" frame, with a total of 1700.0 meters traveled over 2 trips." ``` ## Quick help popover 위에서도 잠깐 언급했는데,<kbd>⌥ – Option</kbd>를 눌러서 quick help를 열 수 있다. ![image](https://user-images.githubusercontent.com/41438361/121201921-ddbe4b80-c8af-11eb-999c-391c4f25f259.png) 또한 Quick help는 Quick Help inspector 패널에서도 확인할 수 있다. ![image](https://user-images.githubusercontent.com/41438361/121201977-e747b380-c8af-11eb-8577-c212dbde3a52.png) ### Quick Help documentation 자동 생성 문서를 더 쉽게 생성할 수 있다.<kbd>⌥ – Option</kbd>+<kbd>⌘ - command</kbd>+<kbd>/</kbd>를 누르거나 Xcode 메뉴의 Editor > Structure > Add documentation 를 선택하면 문서 템플릿을 만들 수 있다. ``` swift /// <#Description#> /// - Parameter person: <#person description#> ``` *이 기능은 Xcode 버전에 따라 다를 수 있다.* ## Code completion hint 타이핑을 시작할 때, Xcode는 해당 클래스에서 추천하는 함수/프로퍼티/열거형의 리스트와 맨 아래에 해당 작업으로 어떤 일을 할 수 있는지 힌트를 준다. ![image](https://user-images.githubusercontent.com/41438361/121202015-ee6ec180-c8af-11eb-88d4-8d845b0f3b3f.png) 출처 * 원문 : [Swift Documentation](https://nshipster.com/swift-documentation/) * 추가로 참고해 덧붙인 내용 : [Swift Documentation](https://sarunw.com/posts/swift-documentation/) ======================= File: _posts/App/swift/2021-04-30-inout 파라미터와 willSet didSet.md ======================= --- layout: post title: "Swift - 프로퍼티 감시자가 있는 프로퍼티를 inout으로 전달했을때 항상 willSet didSet이 호출되는 이유" subtitle: "" categories: app tags: app-swift comments: true header-img: --- > `프로퍼티 감시자가 있는 프로퍼티를 함수의 입출력 매개변수(inout)로 전달했을 때 왜 항상 willSet과 didSet 감시자를 호출하는가?` --- 결론부터 얘기하자면 함수 내부에서 값이 변경되든 그렇지 않든 함수가 종료되는 시점에 값을 다시 쓰기 때문이다. 먼저 in-Out 파라미터에 대해 보도록 하겠다. ## In-Out 파라미터 In-out 파라미터는 아래와 같이 전달된다. 1. 함수가 호출되었을 때, 변수의 값이 복사된다. 2. 함수 내에서 변수의 값이 수정된다.(아닐 수도 있다. 그런데 내부에서 값을 수정하지 않는다면 in-out을 굳이 사용할 필요가 없을 것이다.) 3. 함수가 return할 때, 함수의 복사한 값을 원래의 변수에 할당한다. 이런 동작들은 copy-in-copy-out이나 call by value result(값으로 호출)로 알려져 있다. 예를 들어 연산 프로퍼티나 감시자가 있는 프로퍼티를 in-out 파라미터로 넘겨주게 된다면, getter는 함수 호출의 일부로 같이 불려질 것이고 setter는 함수 return의 일부로 같이 불려질 것이다. 최적화를 위해, 만약 변수가 메모리의 물리적 주소에 저장된 값이라면 같은 메모리 주소는 함수 내부와 밖에서 동시에 사용된다. 즉 주소를 함수 외부, 내부에서 공유한다는 소리다. 이런 최적화 된 행위는 call by reference로 알려져 있고, 이는 복사하는 것의 오버헤드를 없애면서 copy-in-copy-out 모델의 요구사항을 충족한다. 함수에서 in-out 변수로 전달된 값을 원래의 값이 현재의 스코프에서 접근이 가능하다 하더라도 접근하지 말아야 한다. 원래의 값에 접근하는 것은 값에 동시 접근하는 것이고, 이것은 스위프트의 메모리 배제 보장을 위반하는 것이다. 같은 이유로, 여러개의 In-out 파라미터로 같은 값을 전달하면 안된다. 참고 * https://docs.swift.org/swift-book/ReferenceManual/Declarations.html#ID545 ======================= File: _posts/JS/2020-08-22-10. forEach, map, reduce.md ======================= --- title: "JavaScript - forEach, map, reduce" excerpt: "" toc: true toc_sticky: true toc_label: "페이지 주요 목차" header: teaser: categories: - js tags: - 공부 - JavaScript last_modified_at: --- ## forEach for문 편하게 돌리게 하기 위해서이다. `Array.prototype.forEach(callback[, thisArg])` => dd표기법이다. `[]`안에 있는 애는 생략 가능하다. callback 인자는 필수로 받는 것이다. - callback : function(currentValue[, index[, originalArray]]) - currentValue : 현재값 - index : 현재 인덱스 - originalArray : 원본 배열 - thisArg : this에 할당할 대상. 생략시 global 객체 ```javascript const a = [1, 2, 3] a.forEach(function(v, i, arr){ console.log(v, i, arr, this) }, [10,11,12]) ``` 1 0 [1,2,3] [10,11,12] 2 1 [1,2,3] [10,11,12] 3 2 [1,2,3] [10,11,12] 위처럼 결과가 나올 것이다. **currentValue** 중요. for문 돌리는 거랑 같은 개념 ```javascript const a = [1, 2, 3] const b = a.map(function(v, i, arr){ console.log(v, i, arr, this) return this[0]+v //새로운 무언가를 만드는 거니까 무조건 return을 해줘야 한다. }, [10]) ``` [11, 12, 13]이 될 것이다. ## map for문을 돌려서 새로운 배열을 만드는 목적이다. ## reduce Es5에서 동작한다. for문을 돌려서 최종적으로 다른 무언가를 만드는 목적이다. ```javascript const a = [1, 2, 3] const res = arr.reduce(function(p, c, i){ console.log(p, c, i) return p + c }, 10) ``` 10 1 0 11 2 1 13 3 2 res = 16 = 10 + 1 + 2 + 3 가 된다. p = 누적된 결과값. 처음에 10이 있다가 11이 반환되어서 두번째 accumulator로 다시 들어가서 11+2, 13+3이 되어 16이 된다. ```javascript const a = [1, 2, 3] const res = arr.reduce(function(p, c, i){ console.log(p, c, i) return p + c }) ``` 1 2 1 3 3 2 res = 6 initial value가 없으면 첫번째 값이 들어가고 순회는 2번째부터 한다. ======================= File: _posts/JS/2020-09-07-Async, 비동기, 동기, promise에서 await.md ======================= --- title: "JavaScript - Async, 비동기, 동기, promise에서 await까지" excerpt: "" categories: - js tags: - Async - 비동기 - 동기 - promise - await last_modified_at: --- ## 동기 vs 비동기 동기와 비동기의 차이는 요청하고 응답받는 시간의 차이이다. 동기는 내가 요청한 것에 대한 응답이 올때까지 기다리고, 비동기는 그냥 응답이 오든 말든 무시한다. * 동기 : 요청에 대해 응답이 완료되기까지 프로그램이 정지한다. 응답이 오면 다시 진행된다. * 비동기 : 응답받기까지 대기하지 않고 다음 부분을 실행한다. 언젠가 응답받겠지 마인드. ## 동기 요청을 하는 시기와 응답 ======================= File: _posts/App/iOS/2021-06-04-Push 알림 띄우기.md ======================= <filename>_posts/App/iOS/2021-06-04-Push 알림 띄우기.md --- layout: post title: "[iOS] - Push 알림, Notification 시뮬레이터에서 띄우기" subtitle: "" categories: app tags: app-ios comments: true header-img: img/dev/app/ios/XcodeImg.png --- > `iOS에서 push 알림을 띄우는 방법을 알아보자.` --- ![image](https://user-images.githubusercontent.com/41438361/120766969-b7b64580-c555-11eb-8b0a-90c4e4e0cf6b.png) 위와 같은 알림을 띄워보자. Xcode를 simulator로 실행시킬 때 device token이 발행이 되지 않기 때문에 push 알림을 simulator에 띄울 수 없을 것처럼 보이지만 테스트 하는 방법이 있었다🎉 먼저 push 알림을 띄우는데 가장 중요한 것은 아래 3가지이며, 다 굉장히 간단하므로 쉽게 push 알림을 테스트 할 수 있다. 1. 사용자에게 알림을 띄울 권한 요청하기 2. apns 파일 생성하기 3. UNUserNotificationCenterDelegate 구현해서 알림에 대한 동작 처리하기 (생략해도 되긴 하다.) 먼저 Simulator에서도 Push 기능을 테스트하려면 Xcode 11.4버전 이상이 설치되어 있어야 한다. 만약 Xcode 버전이 11.4 이상이면 아래의 과정들을 따라해보자. ## 1. 사용자에게 알림을 띄울 권한 요청하기 iOS 배포 버전이 13 이상이면 AppDelegate에 추가로 SceneDelegate가 Xcode 프로젝트에 추가가 되어 있는 상태일텐데, 나는 AppDelegate에 push 알림과 관련된 코드를 작성했다. `AppDelegate.swift`에서 앱이 실행되면 호출되는 `func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool` 함수 안에 아래와 같이 작성한다. ```swift func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. let center = UNUserNotificationCenter.current() center.requestAuthorization(options: [.alert,.sound,.badge]) { granted, error in // 알림을 띄울 때 alert, sound, badge를 띄울 권한을 사용자에게 요청한다. print("Permission granted : \(granted)") // 만약 사용자가 권한을 허용했다면 granted는 true로, 그렇지 않으면 false로 출력된다. } UIApplication.shared.registerForRemoteNotifications() return true } ``` 이 상태에서 앱을 실행시키면 아래와 같이 앱 권한을 요청하는 팝업이 뜰 것이다. 우리는 알림을 띄울 것이므로 권한을 허용해주면 된다. ![image](https://user-images.githubusercontent.com/41438361/120768674-6018d980-c557-11eb-8405-4f25f977d2b4.png) 여기서 한 번 선택하면 시스템은 이 사용자의 선택을 기억하기 때문에 다음부터 앱에 대한 알림을 띄울 권한을 또 요청하지 않는다. 만약 이 알림을 띄울 권한을 수정하거나 재 요청하려면 시뮬레이터의 설정의 알림에 대한 권한을 수정하거나 Xcode에서 앱을 삭제하고 다시 실행시킨다. 여기까지 잘 떴다면 앱이 알림을 띄울 권한을 사용자에게 요청하는 부분은 잘 설정이 되었다. ## 2. apns 파일 생성하기 APNs는 Apple Push Notification service의 약자로, 앱 외부에서 보내는 알림을 사용자 기기에 전달하는 것을 관리하는 곳이라고 생각하면 된다. 자세한 개념은 [여기](https://yoojin99.github.io/app/User-Notifications/)에서 확인할 수 있다 외부에서 기기에 push notification을 보낼 때는 json 형식의 payload를 작성하는데, 여기서도 같은 작업을 해준다고 생각하면 된다. 하여간 simulator에서 apns 라는 확장자를 가진 파일을 생성한 후, 이를 Xcode simulator에 드래그-드랍하면 알림을 띄울 수 있다. 먼저 아래와 같이 확장자가 apns인 파일을 만든다. 이를 만드는 방법은 텍스트 편집기를 열어 아무말이나 입력하고 나서 저장 후, 파일 아이콘에서 우클릭 > 정보 더 가져오기 > 이름 및 확장자 부분에서 `~~.apns`로 수정한다. 파일 이름은 상관 없고, 확장자가 apns이기만 하면 된다. ![image](https://user-images.githubusercontent.com/41438361/120769685-5479e280-c558-11eb-9920-aa10e47b15da.png) 그리고 나서 파일을 연 다음, 내용을 아래와 같이 json 형식의 텍스트로 수정한다. ```json { "aps": { "alert": { "title": "Push 테스트", "body": "🥳 Woohoo! Push notification in simulator! 🎉", "sound": "default" }, "badge": 10 }, "Simulator Target Bundle": "여기에 자신 앱의 Bundle Identifier를 넣는다." } ``` 위에도 적어놨지만 Simulator Target Bundle 부분에는 자신 앱의 Bundle Identifier를 넣어줘야 한다. 내 앱의 Bundle Identifier는 Xcode의 프로젝트 설정 > General > Identity에서 확인할 수 있다. 아래의 파란색으로 하이라이트 된 부분이 내 앱의 Bundle Identifier다. ![image](https://user-images.githubusercontent.com/41438361/120770299-f4d00700-c558-11eb-81ae-1085fe0562e6.png) 다 입력했으면 저장을 눌러 파일을 저장한다. 굳이 이렇게 apns 파일을 만드는 이유는 텍스트 편집기에서 바로 위의 Json 텍스트를 입력하고 저장 후 확장자를 apns로 바꾸면 아래와 같이 기괴하게 파일의 내용이 바뀌기 때문이다. ![image](https://user-images.githubusercontent.com/41438361/120770668-5b552500-c559-11eb-9190-2b49c186fabb.png) 정상적으로 apns 파일이 만들어졌다면 파일을 열었을 때 아래와 같이 나와야 한다. ![image](https://user-images.githubusercontent.com/41438361/120770852-8e97b400-c559-11eb-859a-bf683c32ae7f.png) 이제 시뮬레이터를 실행시키고, <kbd>command</kbd> + <kbd>shift</kbd> + <kbd>h</kbd>를 누르거나 시뮬레이터 상단의 홈 화면 버튼을 눌러 앱을 background로 보내준다. 그리고 방금 생성한 apns 파일을 시뮬레이터의 화면으로 드래그-드롭한다. 그럼 아래와 같이 Push 알림이 잘 뜨는 것을 확인할 수 있다!🥳 ![image](https://user-images.githubusercontent.com/41438361/120771453-2eedd880-c55a-11eb-9705-bb10592aac5f.png) 여기까지만 하면 앱이 background, 즉 화면에서 꺼졌을 때 알림을 띄우는 것을 해본 것이다. 이제는 앱이 화면에 떠 있을때 알림을 띄우는 것과, Push 알림을 터치했을 때 request로 들어오는 payload의 값을 추출해 특정 동작을 하게 하는 것도 구현해보자. ## 3. UNUserNotificationCenterDelegate 구현해서 알림에 대한 동작 처리하기 바로 위에서 말한 앱이 화면에 떠 있을 때(foreground) 알림이 오면 push 알림을 띄우는 것, 그리고 push 알림을 터치했을 때 특정 동작을 하게끔 하려면 UNUserNotificationCenterDelegate를 구현해야 한다. 먼저 1번에서 작성한 `func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool` 함수 안에 다음과 같이 delegate를 설정하는 부분을 추가해준다. ```swift func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. let center = UNUserNotificationCenter.current() center.delegate = self // 여기 추가 center.requestAuthorization(options: [.alert,.sound,.badge]) { granted, error in print("Permission granted : \(granted)") } UIApplication.shared.registerForRemoteNotifications() return true } ``` 그리고 AppDelegate가 UNUserNotificationCenterDelegate 프로토콜을 따르도록 구현한다. 나는 extension으로 구현했다. ```swift extension AppDelegate: UNUserNotificationCenterDelegate { func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { // 앱이 foreground에 있을 때 push 알림이 오면 이 메서드가 호출된다. } func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { // 사용자가 push 알림을 터치하면 이 메서드가 호출된다. } } ``` ### 앱이 foreground에 있을 때 push 알림 뜨게 하기 위의 코드의 첫 번째 메서드를 아래와 같이 구현한다. ```swift func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { // 앱이 foregorund일 때 푸시가 오면 banner, badge, sound표시를 하라는 의미. 참고로.alert은 ios 14에서 deprecated 되었다. completionHandler([.banner,.badge,.sound]) } ``` 그리고 시뮬레이터를 실행시키고, 앱이 화면에 떠 있는 상태에서 위에서 만든 apns 파일을 시뮬레이터의 화면으로 드래그-드롭 하면 아래와 같이 push 알림이 뜨는 것을 확인할 수 있다. ![image](https://user-images.githubusercontent.com/41438361/120772905-c0aa1580-c55b-11eb-81b9-0bfe83808135.png) ### 앱의 push 알림을 터치했을 때 특정 동작 처리하기 두 번째 메서드를 구현할 때 하고 싶은 동작을 하도록 구현하면 된다. apns 파일에 작성했던 json의 형식을 좀 더 다르게 해서 request를 보내고, 이를 앱에서 받아서 처리할 수도 있다. 예를 들어 내가 apns 파일을 아래와 같이 작성했다고 해보자. ```json { "aps": { "alert": { "title": "Push 테스트", "body": "🥳 Woohoo! Push notification in simulator! 🎉", "sound": "default" }, "badge": 10 }, "Simulator Target Bundle": "내 앱의 Bundle Identifier", "url" : "text인데요~" } ``` 임의로 url이라는 필드를 추가했다. 어떤 값을 추가할 지는 마음대로 설정해도 된다. 그리고 메서드를 아래와 같이 구현하고 시뮬레이터에서 push 알림이 떴을 때 push 알림을 클릭하면 Xcode의 콘솔에 `Optional("text인데요~")`라고 뜨게 된다. ```swift func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { // 사용자의 push 알림에 대한 response 처리 let url = response.notification.request.content.userInfo["url"] // 여기에서 내가 원하는 키 값으로 값을 불러올 수 있다. print(url) } ``` 이렇게 json의 Payload에 원하는 값을 맘대로 구성해서 이에 따라 앱에서 push를 클릭했을 때 앱이 다르게 동작하도록 구현할 수도 있다. ======================= File: _posts/CS/컴구/2020-10-25-고정 소수점, 부동 소수점.md ======================= <reponame>Yoojin99/Yoojin99.github.io<filename>_posts/CS/컴구/2020-10-25-고정 소수점, 부동 소수점.md --- title: "고정 소수점 & 부동 소수점" excerpt: "" toc: true toc_sticky: true toc_label: "페이지 주요 목차" header: teaser: categories: - cs tags: - cs-cs last_modified_at: 2020-10-25 --- 컴퓨터에서 실수를 표현하는 방법은 고정 소수점, 부동 소수점 두 가지 방식이 존재한다. ## 1. 고정 소수점(Fixed Point) 소수점이 찍힐 위치를 미리 정해놓고 소수를 표현하는 방식이다. (정수 + 소수) -3.141592 => 부호(-), 정수부(3), 소수부(0.141592)로 이루어진다. * 장점 : 실수를 정수부+소수부로 표현하여 단순하다. * 표현의 범위가 적어서 활용하기 힘들다. (부호 1bit, 정수 15bit, 소수 16bit) ## 2. 부동 소수점(Floating Point) 지수에 값에 따라 소수점이 움직이는 방식을 활용한 실수 표현 방법이다. 즉 소수점의 위치가 고정되어 있지 않다. 실수를 가수부 + 지수부로 표현한다. * 가수 : 실수의 실제값 표현 * 지수 : 크기를 표현함. 가수에 소수점이 위치하는 곳을 나타낸다. (부호 1bit, 지수 8bit, 가수 23bit) 예시) -142.5625를 부동 소수점으로 표현한다면 1. 부호부를 1로 지정한다 (음수 1, 양수 0) 2. 표현하고자 하는 수의 절댓값을 이진법으로 나타낸다 (142.5625 = 10001110.1001) 3. 소수점을 이동시켜 소수점 왼쪽에 1이 하나만 남도록 한다. (10001110.1001 = 1.00011101001 * 2^7) 4. 소수점을 제거하고 가수부의 비트 수의 맞춰 부족한 만큼을 0으로 채우면 가수부가 된다. (10001110100100000000000) 5. 지수는 7이므로 bias(127)를 더한 134를 더한 134를 이진법으로 표현하면 지수부가 된다. 6. 결론적으로 -142.0625를 32비트 부동소수점으로 표현하면, 1 10000110 10001110100100000000000 이 된다. 5의 bias란 부호부를 가지지 않는 지수부가 음수가 되지 않도록 보정해주는 값을 말한다. * 장점 : 표현할 수 있는 수의 범위가 넓어진다. * 단점 : 오차가 발생할 수 있다. ======================= File: _posts/ChatBot/GDF/2020-11-23-API와의 상호작용.md ======================= <filename>_posts/ChatBot/GDF/2020-11-23-API와의 상호작용.md --- title: "API와의 상호작용" excerpt: "" toc: true toc_sticky: true toc_label: "페이지 주요 목차" header: teaser: categories: - cb tags: - cb-gdf - GDF last_modified_at: 2020-11-23 --- CX에서 API를 사용하는 것은 몇 resource 경로와 함수들이 새로운 타입, 함수, 필드에 맞춰 바뀌었다는 점을 제외하고 ES에서 API를 사용하는 것과 비슷하다. 시스템은 아래의 것을 다뤄야 한다. * Dialogflow CX 는 제한된 integration을 지원하기 때문에 끝단의 사용자와 직접 소통할 수 있는 사용자 인터페이스를 제공해야 한다. * 각 대화 턴마다 유저의 입력을 API에 전송하기 위해 Dialogflow API를 불러야 한다. * Agent가 정적이지 않다면, webhook-enabled fulfillment 를 다루기 위해 webhook 서비스를 호스팅해야 한다. 아래의 다이어그램은 세션에서 한 대화 턴이 이루어졌을 때 발생하는 단계를 나타낸다. ![image](https://user-images.githubusercontent.com/41438361/99923505-5a0c9980-2d79-11eb-9fd2-26bed75061f5.png) 1. 끝단의 유저가 end-user input이라고 알려진 것을 적거나 말한다. 2. 사용자 인터페이스는 입력을 받은 후 detect intent request로 dialogflow api에 전달한다. 3. Dialogflow API는 detect intent request를 받는다. 입력을 intent나 form parameter와 매칭시키고, 요구되는 파라미터들을 설정하고 세션 상태를 업데이트한다. 만약 webhook-enabled fulfillment를 부를 필요가 있다면, 웹훅 request를 웹훅 서비스에 보내고, 아니라면 6단계로 간다. 4. 웹훅 서비스는 웹훅 리퀘스트를 받는다. 서비스는 외부 API를 호출하거나, 데이터베이스를 쿼리하거나 업데이트하는 거과 같이 필요한 행동을 할 수 있다. 5. 웹훅 서비스는 응답을 만들고 Dialogflow에 웹훅 응답을 전송한다. 6. Dialogflow는 detect intent response를 만든다. 만약 webhook이 불러졌다면, 웹훅 응답을 응답으로 제공한다. 만약 웹훅이 불러지지 않았다면, agent에 정의된 정적인 응답을 사용한다. Dialogflow는 유저인터페이스 시스템에 detect intent response를 보낸다. 7. 사용자 인터페이스는 detect intent response를 받고 텍스트나 오디오 응답을 끝단의 사용자에 보낸다. 8. 끝단의 사용자는 응답을 본다. 끝단의 사용자의 입력을 처리하기 위해 CX API에 보내는 것은 ES API와 매우 비슷하다. 아래의 예제는 `Sessions` 자원의 `detectIntent` 함수를 부른다. https://levelup.gitconnected.com/android-dialogflow-chatbot-library-6b7b3822e7bc https://medium.com/@abhi007tyagi/android-chatbot-with-dialogflow-8c0dcc8d8018 https://miningbusinessdata.com/courses/dialogflow-cx-custom-integration-using-flask/ https://miningbusinessdata.com/how-to-move-bot-from-dialogflow-cx-to-dialogflow/ https://miningbusinessdata.com/courses/dialogflow-cx-beginner-tutorial/ ======================= File: _featured_tags/chatbot-convert.md ======================= --- layout: tag-blog title: STT&TTS slug: chatbot-convert category: chatbot menu: false order: 3 --- STT & TTS ======================= File: _posts/CS/2020-08-17-TDD.md ======================= <filename>_posts/CS/2020-08-17-TDD.md --- title: "TDD(테스트 주도 개발)" excerpt: "" toc: true toc_sticky: true toc_label: "페이지 주요 목차" header: teaser: categories: - cs tags: - 공부 - TDD last_modified_at: --- TDD(Test Driven Development)? ## TDD란? TDD = Test Driven Development : 테스트 주도 개발. **테스트가 개발을 이끌어 나간다**는 뜻이다. 반복 테스트를 이용한 소프트웨어 방법론으로, 작은 단위의 테스트 케이스를 작성하고 이를 통과하는 코드를 추가하는 단계를 반복하여 구현한다. 짧은 개발 주기의 반복에 의존하는 개발 프로세스이며 애자일 방법론 중 하나이 eXtream Programming(XP)의 'Test-First' 개념에 기반을 둔 단순한 설계를 중요시한다. *XP? : 미래에 대한 예측을 최대한 하지 않고 지속적으로 프로토타입을 완성하는 애자일 방법론 중 하나이다. 이 방법론은 추가 요구사항이 생기더라도 실시간으로 반영할 수 있다.*.* ## 개발주기 ![image](https://user-images.githubusercontent.com/41438361/90339980-bac85f80-e02f-11ea-8f78-a3d541d287fa.png) 위 그림은 TDD의 개발 주기를 표현한 것이다. * 빨간색 단계에서는 실패하는 테스트 코드를 먼저 작성한다. * 초록색 단계에서는 테스트 코드를 성공시키기 위한 실제 코드를 작성한다. * 노란색 단계에서는 중복 코드를 제거, 일반화 등의 리팩토링을 수행한다. 중요한 것은 실패하는 테스트 코드를 작성할 때까지 실제 코드를 작성하지 않는 것과, 실패하는 테스트를 통과할 정도의 실제 코드를 작성해야 하는 것이다. 이를 통해 실제 코드에 대해 기대되는 바를 보다 명확하게 정의함으로써 불필요한 설계를 피할 수 있고, 정확한 요구 사항에 집중할 수 있다. ## 일반 개발 방식과 TDD 개발 방식 비교 * 일반 개발 방식 일반적으로는 요구사항 분석 -> 설계 -> 개발 -> 테스트 -> 배포 의 개발 주기를 갖는다. 하지만 이는 1. 소비자의 요구사항이 처음부터 명확하지 않을 수 있다. 2. 처음부터 완벽한 설계는 어렵다. 3. 자체 버그 검출 능력 저하 또는 소스코드의 품질이 저하될 수 있다. 4. 자체 테스트 비용이 증가할 수 있다. 라는 문제로 잠재적인 위험들이 존재한다. 결론적으로 이러한 코드들은 **재사용이 어렵고 관리가 어려워져 유지보수를 어렵게 만든다.** 작은 부분을 수정하더라도 모든 부분을 테스트해야 하므로 전체적인 버그를 검출하기 어려워 진다. * TDD 개발 방식 TDD는 테스트 코드를 작성한 뒤에 실제 코드를 작성한다. 반복적인 단계가 진행되면서 자연스럽게 코드의 버그가 줄어들고, 소스코드는 간결해진다. ## TDD 개발 방식의 장점 1. 보다 튼튼한 객체 지향적인 코드 생산 TDD는 코드의 재사용 보장을 명시하므로 TDD를 통한 소프트웨어 개발 시 기능별 철저한 모듈화가 이루어진다. 2. 재설계 시간의 단축 테스트 코드를 먼저 작성하기 때문에 개발자가 지금 무엇을 해야하는지 분명히 정의하고 개발을 시작하게 된다. 3. 디버깅 시간의 단출 예를 들어 사용자의 데이터가 잘못 나온다면 DB 문제인지, 비즈니스 레이어의 문제인지 UI의 문제인지 실제 모든 레이어들을 전부 디버깅 해야 하지만, TDD의 경우 자동화된 유닛테스팅을 전제로 하므로 특정 버그를 쉽게 찾을 수 있다. 4. 테스트 문서의 대체 가능 주로 SI 프로젝트 진행 과정에서 어떤 요소들이 테스트 되었는지 테스트 정의서를 만든다. TDD를 하게 될 경우 테스팅을 자동화 시킴과 동시에 정확학 테스트 근거를 산출할 수 있다. 5. 추가 구현의 용이함 TDD의 경우 자동화된 유닛 테스팅을 전제하기 때문에 테스트 기간을 단축시킬 수 있다. ## TDD 개발 방식의 단점 1. 생산성 저하 개발 속도가 느려질 수 있다. 왜냐하면 처음부터 2개의 코드를 짜야하고, 중간중간 테스트 하면서 고쳐나가야 하기 때문이다. 그래서 SI 프로젝트에서는 소프트웨어의 품질보다 납기일 준수가 중요하기 때문에 TDD 방식을 잘 사용하지 않는다. ## TDD를 하기 어려운 이유? 1. 이제까지 자신이 개발하던 방식을 많이 바꿔야 한다. ## TDD를 잘하는 법 *게임 개발로 좋은 예시를 들어서 가져왔다.* 게임을 개발하면서 stage3를 테스트할 때 항상 stage1, stage2를 클리어한 뒤 테스트를 진행하면 테스트 비용이 증가한다. 이때 바로 stage3로 갈 수 있게 만든다. Back Door 접근법 : 테스트할 때 파라미터를 적용하여 본인이 원하는 시스템의 시작점으로 가게 하는 것. 즉 중복적으로 하는 노력들을 자동화하도록 업그레이드하면 발전할 수 있다. ======================= File: _posts/CS/컴구/2020-10-25-패리티 비트&해밍 코드.md ======================= --- title: "패리티 비트 & 해밍 코드" excerpt: "" toc: true toc_sticky: true toc_label: "페이지 주요 목차" header: teaser: categories: - cs tags: - cs-cs last_modified_at: 2020-10-25 --- ## 패리티 비트 정보 전달 과정에서 오류가 생겼는지 검사하기 위해 추가하는 비트를 말한다. 전송하고자 하는 데이터의 각 문자에 1bit를 더하여 전송한다. * 종류 : 짝수, 홀수 ![image](https://user-images.githubusercontent.com/41438361/97107961-ad091780-170d-11eb-958f-2c6b46dca05e.png) 실제 전송하고자 하는 bit 데이터 외에 추가적으로 패리티 비트를 하나 추가하여 송수신을 하게 된다. ![image](https://user-images.githubusercontent.com/41438361/97107981-d1fd8a80-170d-11eb-8a7b-0062b5928edf.png) 이때 짝수 패리티라고 0을 붙이고 홀수 패리티라고 1을 붙이는 것은 아니다. 짝수 비트에서 1의 개수가 짝수가 되도록 하는 것이고, 홀수 패리티는 전체 비트에서 1의 개수가 홀수가 되도록 비트를 정하는 것이다. 패리티 비트는 가장 앞에 붙인다. ## 해밍 코드 데이터 전송 시 1bit의 에러를 정정할 수 있는 자기 오류 정정 코드를 말한다. 패리티 비트를 보고, 1bit에 대한 오류를 정정할 곳을 찾아 수정할 수 있다. 패리티 비트는 오류를 검출할 수 있지만 수정하지 않기 때문에 해밍 코드를 이용한다. [참고할 블로그](https://eastroot1590.tistory.com/entry/%EC%98%A4%EB%A5%98-%EA%B2%80%EC%B6%9C-%EC%BD%94%EB%93%9C-%ED%95%B4%EB%B0%8D%EC%BD%94%EB%93%9CHamming-Code) ======================= File: _posts/soso/2020-10-12-IapHub.md ======================= <gh_stars>1-10 --- title: "IapHub" excerpt: "" categories: - soso tags: - iaphub last_modified_at: --- ## IapHub은 무엇인가? ios와 android 모두 결제를 하려면 결제 서버가 필요하다. 단말 기기들이 이 서버를 통해서 인증을 하거나 구매를 하는 등의 통신을 한다. 문제는 이 ios와 android의 결제 프로토콜, 서버를 이용하는 방식이 다르다는 것이다. 개발자들은 android와 ios 상에서 모두 동작하는 결제 시스템을 구현하기 위해 android에서 동작하는 결제 시스템 따로, ios에서 동작하는 결제 시스템 따로 이렇게 번거롭게 구현을 해야 했다. 이렇게 번거로운 작업을 줄이기 위해 탄생한 것이 IapHub이다. IapHub은 스타트업에서 만든 api로, 쉽게 얘기하자면 android와 ios의 다른 결제시스템을 하나로 통합하여 개발자들이 IapHub 하나만 가지고 android와 ios의 결제 시스템을 한 번에 다룰 수 있도록 한 것이다. 이 IapHub도 돈을 내고 사용하는 유료 서비스이며, 공식 홈페이지에서 사용할 수 있는 다양한 함수들과 값들에 대한 설명을 docs로 제공하고 있다. ======================= File: _posts/App/iOS/2021-09-24-iOS Memory Deep Dive.md ======================= <reponame>Yoojin99/Yoojin99.github.io<gh_stars>1-10 --- layout: post title: "[iOS] - iOS Memory Deep Dive" subtitle: "" categories: app tags: app-ios memory comments: true header-img: --- > `iOS 메모리에 대해 깊이 알아보자.` --- WWDC 2018에 발표되었던 "iOS Memory Deep Dive"을 보고 정리했다. 이 영상에는 아래의 내용이 포함되어 있다. 1. Memroy Footprint가 무엇인지? (Page Size, Dirty Memory, Swap Memory) 2. Memory Footprint를 profiling하는 도구 3. 메모리 그래프를 분석하기 위해 vmmap과 heap command-line 도구 4. 이미지 렌더링 형식 5. UIGraphicsBeginImageContextWithOptions 대신 사용할 수 있는 UIGraphicsImageRenderer 6. 앱이 백그라운드에 있을 때 최적화하기 우리가 메모리를 줄이는 이유는 무엇인가? 이에 대한 대답은 사용자에게 더 나은 앱 사용 경험을 제공할 수 있기 때문이다. 앱이 빠르게 동작할 수 있고, 시스템이 더 잘 동작한다. 또한 앱이 메모리에 오래 머물러 있을 수 있다. 내 앱 뿐만 아니라 다른 앱도 메모리에 더 오래 있을 수 있다. 여기까지만 봐도 많은 점들이 향상된다. # Memory FootPrint 메모리를 감소하는 것에 대해 말하고 있지만, 더 정확하게는 memory footprint을 줄이는 것이다. 모든 메모리는 동일하게 생성되는 것이 아니다. 이게 무슨 말인지 더 보려면 page에 대해 얘기해야 한다. ## Pages 메모리 페이지는 시스템에 의해 주어진 것이고, heap에 여러 개의 객체를 담을 수 있다. 그리고 몇 객체는 실제로 여러 개의 page에 걸칠 수 있다. ![image](https://user-images.githubusercontent.com/41438361/134643464-faf94dcc-1a44-4d14-85c5-fdc6e45db449.png) * 보통 16KB * 페이지 타입: Clean / Dirty * 앱이 사용한 메모리: Page의 수 X Page size ![image](https://user-images.githubusercontent.com/41438361/134643709-66244841-57a3-453f-adc2-a6ee54f6fe3c.png) 페이지 타입으로 Clean / Dirty가 있는데 옐ㄹ 들어 20,000개의 정수의 배열을 할당하고 싶다고 해보자. 그러면 시스템은 6개의 페이지를 줄 것이다. 이때, 페이지는 내가 할당할 때는 clean하다. ![image](https://user-images.githubusercontent.com/41438361/134644028-df73a535-519c-49fe-b45b-a38abf9133aa.png) 하지만 내가 만약 이 배열의 첫 번째 요소에 값을 쓴다면, 이 page는 dirty해진다. 첫 번째 요소 뿐만 아니라 마지막 페이지에 값을 써도 마찬가지로 dirty해진다. ![image](https://user-images.githubusercontent.com/41438361/134644122-9e5c8346-2965-4d78-b56f-20d610f23338.png) 이때 값을 쓴 첫 번째와 마지막을 제외하고 가운데의 4개의 페이지는 앱이 여기에 값을 쓰지 않았기 때문에 아직 clean하다. ## Memory mapped files 이 파일들은 디스크에 있지만 메모리에 로드된 애들이다. 예를 들어 내가 읽기 전용 파일을 사용한다면, 얘네들은 항상 clean page가 될 것이다. 커널도 디스크에서 RAM으로 오고 나갈때 실제로 이들을 관리한다. 무슨 소리인지 모르겠어서 예시를 들고 왔다. JPEG가 있다고 해보고, 이게 memory mapped in일 때 50KB이고, 메모리에 4 페이지를 차지한다고 해보자. 이때, 4번째 페이지는 완전히 차 있지 않은 상태이기 때문에 다른 것들을 추가로 저장할 수 있다. 하지만 이전의 세 페이지는 항상 시스템에 의해 제거될 수 있는 상태여야 한다. 그리고 우리는 보통 앱의 footprint와 profile이 메모리의 dirty, compressed, clean한 segment를 가지고 있다고 말한다. ![image](https://user-images.githubusercontent.com/41438361/134645518-fa930dd6-3df5-4d9e-86bb-32ed4de33de3.png) ### Clean memory 클린 메모리는 페이지 아웃 될 수 있는 데이터다. 얘네들은 바로 위에서 언급한 memory-mapped 파일이다. 이미지, data Blob, training model, framework가 될 수 있다. ![image](https://user-images.githubusercontent.com/41438361/134645783-1d465e81-d0c2-4094-a757-2d48cbf73cab.png) 위는 클린 메모리인 프레임워크를 보여준 것인데, 모든 프레임워크는 DATA CONST 섹션을 가지고 있다. 얘네들은 보통 clean하지만, 런타임에 메서드 뒤섞기와 같은 이상한 것들을 하면 dirty해질 수 있다. ### Dirty memory Dirty memory는 앱에 의해 쓰여진 메모리이다. 얘네들은 할당된 그 어떤 것이라도 될 수 있다. 객체, 문자열, 배열 등등이 여기 포함된다. ![image](https://user-images.githubusercontent.com/41438361/134646427-41ba4d06-f5e0-406d-8f25-1391a371bc73.png) 얘네들은 디코딩된 이미지 버퍼, 프레임워크가 될 수 있다. 프레임워크는 data 섹션과 data dirty 섹션을 가지고 있다. 여기서, 클린 메모리와 더러운 메모리에 프레임워크가 두 번 언급된 것을 확인할 수 있다. 내가 link한 프레임워크는 memory와 dirty memory를 사용할 수 있다. ======================= File: _posts/App/iOS/2021-05-31-Test.md ======================= --- layout: post title: "[iOS] - Test Code 작성하기" subtitle: "" categories: app tags: app-ios comments: true header-img: img/dev/app/ios/XcodeImg.png --- > `코드를 새로 작성하는 것만큼이나 중요한 테스트 코드를 작성하는 법을 알아보자.` --- XCTest를 이용해서 로직 상의 문제, UI 문제, 그리고 성능을 테스트 할 수 있다. ## 앱을 Xcode에서 test하기 ### 개요 XCTest는 다른 추상화 레벨에서 테스트를 작성할 수 있게 해준다. 좋은 테스트 전략은 테스트 각각의 이점을 극대화하기 위해 여러 타입의 테스트를 섞는 것이다. 아래 그림에서 확인할 수 있듯이 테스트의 "피라미드 형" 분포를 목표로 하는 것이 좋다. 앱의 로직을 커버할 수 있는 빠르고, 고립된 유닛 테스트를 많이 포함시키고, 서로 적절히 연결되어 있는 작은 부분들을 검증하는 것을 테스트하는 통합 테스트는 더 적게, 그리고 일반적인 use case에서 올바른 행위를 확인하는 UI 테스트는 더 적게 포함시킨다. ![image](https://user-images.githubusercontent.com/41438361/120151401-2bd7ad00-c227-11eb-8a9b-83eefbd7ba55.png) UI 테스트는 내가 예상하는 대로 앱이 동작하는 것을 보여주는 궁극적인 지표이지만, 다른 테스트를 실행하는 거보다 더 오래 걸린다. 같은 UI 테스트에서도 실패하게 되는 여러가지 앱의 요소들이 있다. 테스트 피라미드는 사용자가 그들의 작업을 수행할 수 있는 것을 검증하는 high-fidelity 테스트를 앱의 로직이 맞는지와 내가 수정한 사항들의 영향에 대해 빠른 피드백을 줄 수 있는 tightly-focused 테스트와 균형을 맞춘다. 테스트 피라미드에 더불어, 코드의 성능적으로-중요한 부분을 커버하는 성능 테스트 코드를 작성하라. 이에 대한 것은 [여기](https://developer.apple.com/documentation/xcode/improving-your-app-s-performance)에서 확인할 수 있다. ### 유닛 테스트 작성하기 각 유닛 테스트는 프로젝트의 메서드나 함수를 통한 단일한 경로의 예상된 행위를 확인해야 한다. 여러 가지 경로를 커버하고 싶다면 각 시나리오마다 하나의 테스트를 작성해야 한다. 예를 들어 함수가 optional 파라미터를 받는다면, 파라미터가 nil일때와 non-nil일 때의 경우를 모두 테스트해야 한다. 코드에서 논리적으로 갈라지는 부분을 정의하고, 각 케이스마다 커버하는 유닛 테스트를 작성해야 한다. 테스트할 클래스나 함수를 선택하고, 그 함수나 클래스에 대한 테스트를 포함하는 XCTestCase의 하위 클래스를 작성해라. 아무런 인자도 받지 않고 Void를 리턴하며, 이름이 "test"로 시작하는 메서드를 XCTestCase의 하위 클래스에 추가한다. Xcode에서는 새로운 파일을 만들고, 자동으로 적절한 클래스를 생성하는 `Unit Test Case Class` 템플릿ㅇㄹ 선택한다. 테스트 메서드는 꼭 아래의 세 단계를 포함해야 한다. 1. Arrange. 내가 실행하는 코드의 흐름을 따라가는 객체나 데이터 구조를 생성한다. 테스트가 빠르고 결정적으로 실행될 수 있는 것을 보장할 수 있게 복잡한 의존성을 구성하기 쉬운 "stub"으로 대체한다. 프로토콜 기반 프로그래밍을 채택하는 것은 앱에서 객체 사이의 관계가 stub를 실제 구현하는 것으로 대체하는 것을 가능하게 하게끔 충분히 유연하게 만든다. 3. Act. Arrange 단계에서 내가 구성한 파라미터와 프로퍼티를 사용해서 내가 테스트하는 메서드나 함수를 호출한다. 4. Assert. Act 단계에서 내가 실행하는 코드의 동작과 실제 무슨 일이 일어나는지를 비교하기 위해 XCTest 프레임워크의 Test Assertion을 활용한다. Assertion의 조건이 false면 test는 실패하게 된다. 아래의 예제를 보자. ```swift class MyAPITests : XCTestCase { func testMyAPIWorks() { // Arrange: create the necessary dependencies. // Act: call my API, using the dependencies created above. XCTAssertTrue(/* … */, "The result wasn't what I expected") } } ``` ### 통합 테스트 작성하기 통합 테스트는 유닛 테스트와 굉장히 비슷하게 보인다. 같은 API를 사용하고, 같은 Arrange-Act-Asser 패턴을 따른다. 유닛 테스트와 통합 테스트의 차이는 크기다. 유닛 테스트가 앱의 로직의 굉장히 작은 부분을 커버한다면, 통합 테스트는 더 넓은 하위 시스템이나 클래스나 함수의 결합을 테스트한다. Arrange 단계에서는 더 적은 stub 객체를 사용해서 테스트에서 커버하는 실제 프로젝트의 코드의 범위를 넓힌다. 모든 다른 조건을 커버하기 위해 유닛 테스트를 사용하기 보다는, 중요한 상황에서 앱의 목표를 달성하기 위해 같이 컴포넌트들이 같이 동작하는지를 확인하기 위해 통합 테스트를 사용한다. 컨트롤러에서 받아진 값이 model에 잘 넣어졌는지 테스트하는 것과, 네트워크 요청에 의해 발생된 에러가 유저 인터페이스에 잘 전달되어서 나타나지는것과 같은 테스트도 여기에 포함된다. ### UI 테스트 작성하기 UI 테스트는 유닛과 통합 테스트와는 다르게 동작하지만, XCTestCase의 하위 클래스의 메서드로 여전히 분류된다. Xcode에서 새 파일을 만들 때 선택할 수 있는 `UI Test Case Class` 템플릿은 UI 테스트를 작성하는 시작점을 제공한다. 앱의 코드를 직접 실행하기 보다는, 이 테스트는 사용자가 앱을 이용해서 특정 작업을 끝낼 수 있는지를 판단하기 위해 실제 사용자가 하듯이 앱의 UI control을 사용한다. 중요한 사용자 task가 앱에서 완료될 수 있고 버그가 UI control의 행위를 깨지 않는 다는 것을 확인하기 위해 UI test를 생성한다. 실제 사용자의 동작을 똑같이 따라하는 UI 테스트는 앱이 의도된 작업에 사용될 수 있다는 확신을 제공한다. 문서 기반의 앱에 사용되는 UI 테스트는 앱이 새로운 문서를 만들고, 이를 수정하고, 문서를 삭제할 수 있는지를 검증할 것이다. XCTestCase의 하위 클래스에서 UI 테스트를 생성하기 위해, Xcode의 `Record UI Test` 기능을 이용해서 내가 앱과 상호작용하는 것을 기록한다. 실행이 안되었을 때 사용자에게 가장 큰 영향을 줄 것 같은 중요한 실행 흐름을 그대로 따라하고, 문제를 회피할 수 있게 버그를 다시 출력할 수 있게 UI 테스트를 디자인한다. ![image](https://user-images.githubusercontent.com/41438361/120154770-267c6180-c22b-11eb-8816-5418713bb641.png) 내가 테스트하는 기능을 실행하는 워크플로우를 녹화했다면, test assertion 함수들을 이용해서 녹화된 상호작용이 끝나고 UI의 마지막 상태가 내가 예상한 대로인 것을 보장할 수 있게 한다. UI 테스특여러개의 뚜렷한 단계를 구성하는 복잡한 워크 플로우를 따라하는 곳에서, XCTActivity를 이용해서 공유된 단계에 이름을 붙이고 구성한다. 여러 테스트에서 사용되는 행위들을 구현한 것을 공유하기 위해 helper 메서드를 작성한다. ### 성능 테스트 작성하기 특정 코드 구간이 실행될때 걸린 시간, 소요된 메모리, 덮어써진 데이터에 대한 정보를 모으는 성능 테스트를 작성해라. XCTest는 요구된 수치를 측정하면서 코드를 여러번 수행할 것이다. 수치에 대한 기대치를 제시할 수도 있고 만약 측정된 수치가 기대치보다 낮으면, XCTest는 실패하게 된다. 소요된 시간을 테스트하기 위해, `measure(_:)` 메서드를 테스트 함수 안에서 작성하고 코드를 실행시킨다. 사용된 메모리나 디스크에 써진 데이터의 크기를 포함한 수치를 측정하기 위해, `measure(metrics:block:)`을 호출해라. ```swift class PerformanceTests : XCTestCase { func testCodeIsFastEnough() { self.measure() { // performance-sensitive code here } } } ``` ## 프로젝트에 Unit Test 추가하기 테스트 커버리지와 신뢰성을 증가시키기 위해 요소 간의 결합을 지운다. ### 개요 XCTest를 이용해서 작성하는 유닛 테스트는 수정 사항과 추가사항이 앱의 기능에 문제를 일으키지 않는다는 자신을 줌으로써 개발 속도를 증가시킬 수 있다. 테스트 성을 고려하지 않고 내린 디자인 결정은 별도의 클래스나 하위 시스템을 연결지어서 단일하게 테스트 할 수 없도록 만들기 때문에 존재하는 프로젝트에 유닛 테스트를 추가하는 것이 어려울 수 있다. 소프트웨어 디자인에서 커플링은 클래스나 함수가 한 코드가 특정한 방법으로 다른 것과 연결지어질 때만 정상적으로 동작하는 것을 확실하게 한다. 가끔, 이 커플링은 테스트가 테스트를 느리게 만들고 결과가 비결정적이게 만드는 네트워크 연결이나 파일 시스템과의 상호작용을 시도할 수 있다. 커플링을 제거하는 것은 유닛 테스트를 더 생성할 수 있게 하지만 테스트로 커버되지 않는 곳에서 코드를 수정해야 하므로 위험할 수 있다. 테스트하고 싶은 요소를 정의하고 확인하고 싶은 행위를 커버하는 테스트 케이스를 작성해서 프로젝트의 테스트 커버리지를 높인다. 사용자가 겪는 버그가 많이 나타나는 기능의 로직이나 성능이 중요한 영향을 끼치는 곳을 커버하는 것의 우선순위에 risk-focused 접근 법을 사용한다. 테스트하는 코드가 프로젝트의 다른 부분이나 프레임워크 클래스와 연관되어 있다면, 행동을 수정하지 않으면서 컴포넌트를 격리시키는 코드를 최대한 작게 변경한다. 커플링을 없애고, 각 변화와 관련된 위험을 줄이기 위해 변화를 적게 만들어 테스트에서 클래스의 사용성을 향상시킨다. 아래에 나올 내용은 고려사항과 다른 요소가 테스트하는 것을 막는 것 사이에 커플링이 존재할 때 커플링을 제거하는 변화를 소개한다. 각 해결방법은 XCTest 가 행위를 확인하기 위해 어떻게 변경된 코드와 동작하는지를 서술한다. ### 구체적인 타입을 프로토콜로 대체하기 내 코드가 특정 클래스에 의존하고 있어서 테스트를 어렵게 만들때, 내 코드에 의해 사용되는 메서드와 프로퍼티를 나열하는 프로토콜을 생성해라. 이런 문제가 있는 의존성은 외부 상태에 접근하고, 사용자 문서나 데이터 베이스, 혹은 비결정적인 겨ㄹ과를 갖는 것들, 그리고 네트워크 연결이나 임의의 값을 생성하는 것들을 포함한다. 밑의 리스트는 이메일이나 메세지에 첨부되는 파일을 열기 위해 NSWorkspace를 사용하는 코코아 앱의 클래스를 보여준다. `openAttachment(file:in)` 메서드의 결과는 사용자가 요구되는 타입을 다룰 수 있는 앱을 설치했는지와, 파일을 성공적으로 열었는지 여부에 따라 결정된다. 이 모든 요소가 테스트가 실패하게끔 만들며, 개발 속도도 코드와 상관 없는 문제들로 판명난 "에러를" 찾는 것을 느리게 만든다. **Swift** ```swift import Cocoa enum AttachmentOpeningError : Error { case UnableToOpenAttachment } class AttachmentOpener { func openAttachment(file location: URL, with workspace: NSWorkspace) throws { if (!workspace.open(location)) { throw AttachmentOpeningError.UnableToOpenAttachment } } } ``` **Objective-C** ```objective-c // AttachmentOpener.h #import <Cocoa/Cocoa.h> NS_ASSUME_NONNULL_BEGIN @interface AttachmentOpener : NSObject - (BOOL)openAttachmentAtLocation:(NSURL *)file withWorkspace:(NSWorkspace *)workspace error:(NSError * __autoreleasing _Nullable *)error; @end extern NSErrorDomain const AttachmentOpenerErrorDomain; typedef NS_ERROR_ENUM(AttachmentOpenerErrorDomain, AttachmentOpenerErrorCode) { AttachmentOpenerErrorUnableToOpenAttachment, }; NS_ASSUME_NONNULL_END // AttachmentOpener.m #import "AttachmentOpener.h" @implementation AttachmentOpener - (BOOL)openAttachmentAtLocation:(NSURL *)file withWorkspace:(NSWorkspace *)workspace error:(NSError *__autoreleasing _Nullable *)error { BOOL result = [workspace openURL:file]; if (!result && error) { *error = [NSError errorWithDomain:AttachmentOpenerErrorDomain code:AttachmentOpenerErrorUnableToOpenAttachment userInfo:nil]; } return result; } @end const NSErrorDomain AttachmentOpenerErrorDomain = @"AttachmentOpenerErrorDomain"; ``` 이 커플링된 코드를 테스트하기 위해, 코드가 문제가 되는 의존성과 어떻게 상호작용하는지를 나타내는 프로토콜을 설계한다. 코드에서 프로토콜을 사용해서, 클래스가 프로토콜에 있는 메서드의 존재에는 영향을 받지만 구현에는 영향을 받지 않게 설정한다. 상태가 있는 것을 지양하고 비결정적인 작업을 수행하지 않는 프로토콜을 구현하고, 구현된 것을 이용해서 테스트 코드를 작성한다. 아래에서는 프로토콜은 `open(_:)` 메서드를 선언했고, NSWorkSpace의 extension을 이용해 이 프로토콜을 따르게 했다. **Swift** ```swift import Cocoa enum AttachmentOpeningError: Error { case UnableToOpenAttachment } protocol URLOpener { func open(_ file: URL) -> Bool } extension NSWorkspace : URLOpener {} class AttachmentOpener { func openAttachment(file location: URL, with workspace: URLOpener) throws { if (!workspace.open(location)) { throw AttachmentOpeningError.UnableToOpenAttachment } } } ``` **Objective-C** ```objective-c // URLOpener.h #import <Cocoa/Cocoa.h> @protocol URLOpener <NSObject> - (BOOL)openURL:(NSURL *)url; @end @interface NSWorkspace (URLOpener) <URLOpener> @end // AttachmentOpener.h #import <Cocoa/Cocoa.h> #import "URLOpener.h" NS_ASSUME_NONNULL_BEGIN @interface AttachmentOpener : NSObject - (BOOL)openAttachmentAtLocation:(NSURL *)file withWorkspace:(id <URLOpener>)workspace error:(NSError * __autoreleasing _Nullable *)error; @end // The rest of AttachmentOpener.h, and AttachmentOpener.m remains unchanged. ``` 테스트에서는 사용자 컴퓨터에 설치된 앱에 의존하지 않는 `URLOpener` 프로토콜을 다르게 구현한다. **Swift** ```swift class StubWorkspace: URLOpener { var isSuccessful = true func open(_ file: URL) -> Bool { return isSuccessful } } class AttachmentOpenerTests: XCTestCase { var workspace: StubWorkspace! = nil var attachmentOpener: AttachmentOpener! = nil let location = URL(fileURLWithPath: "/tmp/a_file.txt") override func setUp() { workspace = StubWorkspace() attachmentOpener = AttachmentOpener() } override func tearDown() { workspace = nil attachmentOpener = nil } func testWorkspaceCanOpenAttachment() { workspace.isSuccessful = true XCTAssertNoThrow(try attachmentOpener.openAttachment(file: location, with: workspace)) } func testThrowIfWorkspaceCannotOpenAttachment() { workspace.isSuccessful = false XCTAssertThrowsError(try attachmentOpener.openAttachment(file: location, with: workspace)) } } ``` **Objective-C** ```objective-c #import <XCTest/XCTest.h> #import "AttachmentOpener.h" #import "URLOpener.h" @interface StubWorkspace: NSObject <URLOpener> @property (nonatomic, assign, getter=isSuccessful) BOOL successful; @end @implementation StubWorkspace - (BOOL)openURL:(NSURL *)url { return self.isSuccessful; } @end @interface AttachmentOpenerTests : XCTestCase @end @implementation AttachmentOpenerTests { StubWorkspace *workspace; AttachmentOpener *opener; NSURL *location; } - (void)setUp { workspace = [[StubWorkspace alloc] init]; opener = [[AttachmentOpener alloc] init]; location = [NSURL fileURLWithPath:@"/tmp/a_file.txt"]; } - (void)tearDown { workspace = nil; opener = nil; location = nil; } - (void)testWorkspaceCanOpenAttachment { workspace.successful = YES; NSError *error = nil; XCTAssertTrue([opener openAttachmentAtLocation:location withWorkspace:workspace error:&error], @"Opening attachment should have succeeded but failed with %@", error); } - (void)testErrorIfWorkspaceCannotOpenAttachment { workspace.successful = NO; NSError *error = nil; XCTAssertFalse([opener openAttachmentAtLocation:location withWorkspace:workspace error:&error], @"Opening attachment should not have succeeded"); } @end ``` ### Named Type 을 MetaType 값으로 바꾸기 앱에 있는 클래스 하나가 생성되었고 다른 클래스의 인스턴스를 쓰고, 생성된 객체가 테스트하기 어려울 때, 클래스를 생성된 곳에서 테스트하기 어려울 수 있다. 생성된 객체의 타입을 파라미터로 만들고 인스턴스를 생성하기 위해 필요한 이니셜라이저를 사용한다. 사용자의 행위에 응답해서 파일시스템에서 새로운 문저를 만들어야 한다던지, 웹 서비스에서 받은 JSON을 해석하고 받은 데이터를 나타내는 Core Data에 의해 관리되는 새로운 객체를 만드는 메서드와 같은 경우들이 복잡한 테스트 상황의 경우에 포함된다. 각각의 케이스에서 객체는 테스트하고 싶은 코드에 의해 생성되기 때문에 이를 메서드의 파라미터로써 다른 객체로 전달하지 못한다. 객체는 코드에 의해 생성될때까지 존재하지 않고, 이때는 타입이 테스트하지 못하는 상황일 때가 될 것이다. 아래는 사용자가 브라우저에서 문서를 선택할 때 문서 객체를 생성하고 여는 `UIDocumentBrowserViewControllerDelegate`를 보여준다. 이게 생성하는 문서 객체는 파일 시스템에서 데이터를 읽고 쓰기 때문에, 유닛 테스트에서 이를 관리하기 쉽지 않다. **Swift** ```swift class DocumentBrowserDelegate: NSObject, UIDocumentBrowserViewControllerDelegate { func documentBrowser(_ controller: UIDocumentBrowserViewController, didPickDocumentsAt documentURLs: [URL]) { guard let sourceURL = documentURLs.first else { return } let storyBoard = UIStoryboard(name: "Main", bundle: nil) let documentViewController = storyBoard.instantiateViewController(withIdentifier: "DocumentViewController") as! DocumentViewController documentViewController.document = Document(fileURL: sourceURL) documentViewController.modalPresentationStyle =.fullScreen controller.present(documentViewController, animated: true, completion: nil) } } ``` **Objective-C** ```objective-c // DocumentBrowserDelegate.h #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @interface DocumentBrowserDelegate : NSObject <UIDocumentBrowserViewControllerDelegate> @end NS_ASSUME_NONNULL_END // DocumentBrowserDelegate.m #import "DocumentBrowserDelegate.h" #import "DocumentViewController.h" #import "Document.h" @implementation DocumentBrowserDelegate - (void)documentBrowser:(UIDocumentBrowserViewController *)controller didPickDocumentsAtURLs:(NSArray<NSURL *> *)documentURLs { NSURL *sourceURL = [documentURLs firstObject]; UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil]; DocumentViewController *documentViewController = [storyboard instantiateViewControllerWithIdentifier:@"DocumentViewController"]; documentViewController.document = [[Document alloc] initWithFileURL:sourceURL]; documentViewController.modalPresentationStyle = UIModalPresentationFullScreen; [controller presentViewController:documentViewController animated:YES completion:nil]; } @end ``` 내가 테스트하려는 코드와 이게 생성하는 객체 사이의 결합을 없애기 위해, 객체의 타입을 나타내는 변수를 클래스 아래에 생성해라. 변수는 `meatatype value`라고 불린다. 타입의 default 값을 클래스가 이미 사용하는 값으로 설정해라. 인스턴스를 생성하는데 사용되는 이니셜라이저가 `required `로 표기외어있는 것을 보장해야 한다. 이 리스팅은 앞서 나온 변수와 함께 문서 브라우저 view controller delegate를 보여준다. delegate는 메타타입 값으로 정의된 타입으로 문서를 생성한다. **Swift** ```swift class DocumentBrowserDelegate : NSObject, UIDocumentBrowserViewControllerDelegate { var DocumentClass = Document.self func documentBrowser(_ controller: UIDocumentBrowserViewController, didPickDocumentsAt documentURLs: [URL]) { guard let sourceURL = documentURLs.first else { return } let storyBoard = UIStoryboard(name: "Main", bundle: nil) let documentViewController = storyBoard.instantiateViewController(withIdentifier: "DocumentViewController") as! DocumentViewController documentViewController.document = DocumentClass.init(fileURL: sourceURL) documentViewController.modalPresentationStyle =.fullScreen controller.present(documentViewController, animated: true, completion: nil) } } ``` **Objective-C** ```objective-c // DocumentBrowserDelegate.h #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @interface DocumentBrowserDelegate : NSObject <UIDocumentBrowserViewControllerDelegate> @property (nonatomic, assign) Class DocumentClass; @end NS_ASSUME_NONNULL_END // DocumentBrowserDelegate.m #import "DocumentBrowserDelegate.h" #import "DocumentViewController.h" #import "Document.h" @implementation DocumentBrowserDelegate - (instancetype)init { self = [super init]; if (self) { self.DocumentClass = [Document class]; } return self; } - (void)documentBrowser:(UIDocumentBrowserViewController *)controller didPickDocumentsAtURLs:(NSArray<NSURL *> *)documentURLs { NSURL *sourceURL = [documentURLs firstObject]; UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil]; DocumentViewController *documentViewController = [storyboard instantiateViewControllerWithIdentifier:@"DocumentViewController"]; documentViewController.document = [[self.DocumentClass alloc] initWithFileURL:sourceURL]; documentViewController.modalPresentationStyle = UIModalPresentationFullScreen; [controller presentViewController:documentViewController animated:YES completion:nil]; } @end ``` 테스트에서 메타타입을 위한 다른 값을 할당해서, 코드가 같은 테스트할 수 없는 행동을 하지 않는 객체를 코드가 생성하도록 하자. 테스트에서는 문서 클래스의 "테스트 더미" 버전을 생성한다. 이 버전은 같은 인터페이스를 갖는 클래스이지만 테스트하기 어려운 행위를 구현하지 않는다. 이 경우에, 문서 클래스는 파일 시스템과 상호작용하지 말아야 한다. **Swift** ```swift class DummyDocument : Document { static var opensSuccessfully = true static var savesSuccessfully = true static var closesSuccessfully = true override func save(to url: URL, for saveOperation: UIDocument.SaveOperation, completionHandler: ((Bool) -> Void)? = nil) { // don't save anything, just call the completion handler guard let handler = completionHandler else { return } handler(StubDocument.savesSuccessfully) } override func close(completionHandler: ((Bool) -> Void)? = nil) { guard let handler = completionHandler else { return } handler(StubDocument.closesSuccessfully) } override func open(completionHandler: ((Bool) -> Void)? = nil) { guard let handler = completionHandler else { return } handler(StubDocument.opensSuccessfully) } } ``` **Objective-C** ```objective-c @interface DummyDocument : Document @property (nonatomic, assign) BOOL savesSuccessfully; @property (nonatomic, assign) BOOL opensSuccessfully; @property (nonatomic, assign) BOOL closesSuccessfully; @end @implementation DummyDocument - (void)saveToURL:(NSURL *)url forSaveOperation:(UIDocumentSaveOperation)saveOperation completionHandler:(void (^)(BOOL))completionHandler { // don't save anything, just call the completion handler if (completionHandler) { completionHandler(self.savesSuccessfully); } } - (void)openWithCompletionHandler:(void (^)(BOOL))completionHandler { if (completionHandler) { completionHandler(self.opensSuccessfully); } } - (void)closeWithCompletionHandler:(void (^)(BOOL))completionHandler { if (completionHandler) { completionHandler(self.closesSuccessfully); } } @end ``` 테스트케이스의 `setUp()` 메서드에서 문서타입을 터미 타입을 바꿔서 테스트에서 결정적으로 동작하는 더미 문서 타입의 인스턴스를 테스트되는 delegate가 생성할 수 있도록 하자. **Swift** ```swift class DocumentBrowserDelegateTests: XCTestCase { var delegate: DocumentBrowserDelegate! = nil override func setUp() { delegate = DocumentBrowserDelegate() delegate.DocumentClass = StubDocument.self } override func tearDown() {} // Add test methods here. } ``` **Objective-C** ```objective-c @implementation DocumentBrowserDelegateTests { DocumentBrowserDelegate *delegate; } - (void)setUp { delegate = [[DocumentBrowserDelegate alloc] init]; delegate.DocumentClass = [DummyDocument class]; } - (void)tearDown { delegate = nil; } // Add test methods here. @end ``` ### 자식클래스를 만들고 테스트할 수 없는 메서드를 재정의하기 클래스를 테스트하기 어렵게 만드는 상호작용이나 행위를 가지고 있는 로직을 클래스가 가지고 있을 때, 몇개의 클래스의 메서드를 테스트하기 쉽게 만들게 override한 자식 클래스를 만들어라. 테스트에서 관리하기 어려운 행위를 출력하는 프레임워크, 환경과 상호작용하는 행위, 그리고 앱의 로직을 모두 포함하는 클래스를 디자인하는 것은 흔하다. 일반적인 예는 `UIViewController` 의 하위 클래스로, action 메서드에서 앱에 특정화된 코드와 다른 뷰 컨트롤러를 출력하고 뷰를 로드하는 애들이다. 커스텀 앱의 로직을 테스트하는 것은 이 로직들이 예상된 대로 작동하고 성능에 결함이 없는지를 보장하기 위해 필요하다. 클래스와 환경 사이의 상호작용을 관리하거나 작업하는 복잡도는 로직을 테스트하는 것을 더 어렵게 만든다. 예를 들어, 아래의 iOS 뷰 컨트롤러는 프로필 객체에서 찾을 수 있는 사용자의 이름으로 라벨을 생성한다. 파일의 경로를 찾기 위해 `UserDefaults`를 사용하고, 이걸 딕셔너리로 로드하며, UI를 생성하기 위해 딕셔너리에 있는 값들을 사용한다. **Swift** ```swift struct UserProfile { let name: String } class ProfileViewController: UIViewController { @IBOutlet var nameLabel: UILabel! override func viewDidLoad() { self.loadProfile() { [weak self] user in self?.nameLabel.text = user?.name?? "Unknown User" } } func loadProfile(_ completion: (UserProfile?) -> ()) { let path = UserDefaults.standard.string(forKey: "ProfilePath") guard let thePath = path else { completion(nil) return } let profileURL = URL(fileURLWithPath: thePath) let profileDict = NSDictionary(contentsOf: profileURL) guard let profileDictionary = profileDict else { completion(nil) return } guard let userName = profileDictionary["Name"] else { completion(nil) return } let profile = UserProfile(name: userName as! String) completion(profile) } } ``` **Objective-C** ```objective-c // ProfileViewController.h #import <UIKit/UIKit.h> @interface ProfileViewController @property (nonatomic, weak) IBOutlet UILabel *nameLabel; - (void)loadProfileWithCompletion:(void(^)(Profile *))completion; @end // ProfileViewController.m #import "ProfileViewController.h" #import "Profile.h" @implementation ProfileViewController - (void)viewDidLoad { [super viewDidLoad]; [self loadProfileWithCompletion:^(Profile *profile) { if (profile) { self.nameLabel.text = profile.username; } else { self.nameLabel.text = @"Unknown User"; } }]; } - (void)loadProfileWithCompletion:(void (^)(Profile *))completion { NSString *path = [[NSUserDefaults standardUserDefaults] stringForKey:@"ProfilePath"]; if (!path) { completion(nil); return; } NSURL *profileLocation = [NSURL fileURLWithPath:path]; NSDictionary *profileData = [NSDictionary dictionaryWithContentsOfURL:profileLocation]; if (!profileData) { completion(nil); return; } NSString *username = profileData[@"username"]; if (!username) { completion(nil); return; } Profile *profile = [[Profile alloc] initWithUsername:username]; completion(profile); } @end ``` 이 복잡도를 극복하기 위해서, 뷰 컨트롤러의 자식 클래스를 만들고 더 간단한 메서드로 override해서 복잡도와 테스트할 수 없는 상호작용을 생성하는 메서드들을 "stub out"시킨다. 테스트에서 서브클래스를 사용해서 내가 override하지 않은 특정 로직의 행위를 검증한다. 만약 테스트에 있는 코드가 타겟 타입의 인스턴스를 생성한다면 메타 타입 값을 생성해야 할 수 있다. 아래의 리스트는 부모 클래스에 있는 `UserDefaults`와 파일 시스템의 결합도를 가지고 있지 않은 `StubProfileViewController`를 소개한다. 대신, 호출자에 의해 구성되지 않은 `UserProfile` 객체를 사용한다. 이 자식 클래스를 이용해서 테스트하면 테스트하는 로직에서 필요한 객체를 쉽게 제공할 수 있다. **Swift** ```swift class StubProfileViewController: ProfileViewController { var loadedProfile: UserProfile? = nil override func loadProfile(_ completion: (UserProfile?) -> ()) { completion(loadedProfile) } } ``` **Objective-C** ```objective-c @interface StubProfileViewController: ProfileViewController @property (nonatomic, strong) Profile *loadedProfile; @end @implementation StubProfileViewController - (void)loadProfileWithCompletion: (void (^)(Profile *))completion { completion(self.loadedProfile); } @end ``` 두 테스트는 `viewDidLoad()`의 행위를 완전히 커버한다. 한 테스트는 만약 프로파일이 로드될 수 있을 때 이름이 프로파일에서 올바르게 설정되었는지를 확인한다. 다른 테스트는 만약 프로필이 로드되지 않았을때 이름으로 placeholder 값이 잘 사용되었는지를 혹인한다. **Swift** ```swift class ProfileViewControllerTests: XCTestCase { var profileVC: StubProfileViewController! = nil override func setUp() { profileVC = StubProfileViewController() // configure the label, in lieu of loading a storyboard profileVC.nameLabel = UILabel(frame: CGRect.zero) } override func tearDown() {} func testSuccessfulProfileLoadingSetsNameLabel() { profileVC.loadedProfile = UserProfile(name: "<NAME>") profileVC.viewDidLoad() XCTAssertEqual(profileVC.nameLabel.text, "User Name") } func testFailedProfileLoadingUsesPlaceholderLabelValue() { profileVC.loadedProfile = nil profileVC.viewDidLoad() XCTAssertEqual(profileVC.nameLabel.text, "Unknown User") } } ``` **Objective-C** ```objective-C @interface ProfileViewControllerTests: XCTestCase @end @implementation ProfileViewControllerTests { StubProfileViewController *profileVC; } - (void)setUp { profileVC = [[StubProfileViewController alloc] init]; // configure the label, in lieu of loading a storyboard profileVC.nameLabel = [[UILabel alloc] initWithFrame:CGRectZero]; } - (void)tearDown { profileVC = nil; } - (void)testSuccessfulProfileLoadingSetsNameLabel { profileVC.loadedProfile = [[Profile alloc] initWithUsername:"User Name"]; [profileVC viewDidLoad]; XCTAssertEqualObjects(profileVC.nameLabel.text, "User Name"); } - (void)testFailedProfileLoadingUsesPlaceholderLabelValue { profileVC.loadedProfile = nil [profileVC viewDidLoad]; XCTAssertEqualObjects(profileVC.nameLabel.text, "Unknown User"); } @end ``` *패턴은 여러 책임을 갖고 있는 클래스를 테스트하는 것에 도움을 주지만, 테스트 가능한 코드를 디자인하는 것을 따라가기에는 좋지 않다. 다른 문제를 다루는 코드는 다른 클래스에 분리해라. 예를 들어 앱의 로직을 포함한 컨트롤러 클래스와 UIKit과 앱에 종속된 행위를 연결하는 뷰 컨트롤러를 별도로 생성한다. 유닛 테스트에서 제외한 로직을 커버하는 실제 클래스의 행위를 검증하기 위해 UI 테스트를 추가한다. 하위 클래스를 만들고 테스트할 수 없는 메서드를 오버라이딩 하는 것은 존재하는 코드를 다시 디자인하는 것의 첫번째 단계이다. 이를 통해 프레임워크나 다른 외부의 데이터와 앱의 로직이 분리될 것이다. 이런 식으로 코드를 나누는 것은 프로젝트의 어떤 부분이 앱의 기능을 구현했고, 시스템의 나머지와 통합하는지를 이해하기 쉽게 만들고, 새로운 API나 다른 기술을 채택할 때 코드에 대한 변화로 인한 로직에서 생기는 버그를 줄일 수도 있다.* ## Singleton 채택하기 만약 코드가 전역에서 접근가능한 상태나 행위를 하기 위해 싱글턴을 사용한다면, 싱글턴을 테스트에서만 사용가능하게 대체할 수 있는 변수로 바꿔라. 싱글톤을 사용하는 것은 codebase를 통해 퍼질 수 있고, 이것은 내가 테스트하려는 컴포넌트에 의해 사용될 때 싱글톤의 상태를 알기 어렵게 만든다. 다른 순서로 테스트를 실행하면 다른 결과가 나올 수도 있다. `NSApplication`와 default `FileManager`를 포함해서 흔히 사용되는 싱글턴은 외부 상태에 의존하는 행위를 갖고 있고. 이 싱글톤을 사용하는 컴포넌트들은 의존적인 테스트를 하는 것에 직접적으로 복잡도를 추가한다. 이 예제에서, Cocoa 뷰 컨트롤러는 뉴스 앱의 문서 인스펙터의 일부를 출력한다. 뷰 컨트롤러에서 출력되는 객체가 변할 때, 앱의 다른 컴포넌트들이 구독하는 default notification center에 알림을 전송한다. **Swift** ```swift let InspectedArticleDidChangeNotificationName: String = "InspectedArticleDidChange" class ArticleInspectorViewController: NSViewController { var article: Article! = nil override var representedObject: Any? { didSet { article = representedObject as! Article? NotificationCenter.default.post(name: NSNotification.Name(rawValue: InspectedArticleDidChangeNotificationName), object: article, userInfo: ["Article": article!]) } } } ``` **Objective-C** ```objective-c // ArticleInspectorViewController.h #import <Cocoa/Cocoa.h> NS_ASSUME_NONNULL_BEGIN @interface ArticleInspectorViewController : NSViewController @end extern const NSNotificationName InspectedArticleDidChangeNotificationName; NS_ASSUME_NONNULL_END // ArticleInspectorViewController.m #import "ArticleInspectorViewController.h" @implementation ArticleInspectorViewController - (void)setRepresentedObject:(id)representedObject { [super setRepresentedObject:representedObject]; [[NSNotificationCenter defaultCenter] postNotificationName: InspectedArticleDidChangeNotificationName object: self userInfo: @{ @"Article" : representedObject }]; } @end const NSNotificationName InspectedArticleDidChangeNotificationName = @"InspectedArticleDidChange"; ``` 테스트가 이런 알림을 관찰하기 위해 default notification center로 등록할 때, 단일한 싱글톤 알림 센터는 앱의 다른 컴포넌트들이 테스트의 결과에 간섭할 수 있게 만든다. 다른 코드는 알림을 전송하고 관찰자를 제거하거나, 알림에 대한 반응으로 자신만의 코드를 실행할 수 있고, 이와 같이 테스트의 결과에 영향을 받는다. 싱글톤 객체에 대한 직접적인 접근을 테스트에서 컴포넌트 밖에서 제어가 가능한 파라미터나 프로퍼티로 교체한다. 앱에서는, 컴포넌트에 협력하는 것처럼 싱글톤을 계속 사용한다. 테스트에서는, 더 쉽게 제어할 수 있는 대체 객체를 제공한다. 아래의 리스트는 위에서 봤던 문서 인스펙터 뷰 컨트롤러에 이런 변화를 적용한 것을 보여준 것이다. 뷰 컨트롤러는 `notificationCenter` 프로퍼티 안에 default center로 초기화 된 notification center로 전달한다. **Swift** ```swift let InspectedArticleDidChangeNotificationName = "InspectedArticleDidChange" class ArticleInspectorViewController: NSViewController { var article: Article! = nil var notificationCenter: NotificationCenter = NotificationCenter.default override var representedObject: Any? { didSet { article = representedObject as! Article? notificationCenter.post(name: NSNotification.Name(rawValue: InspectedArticleDidChangeNotificationName), object: self, userInfo: ["Article": article!]) } } } ``` **Objective-C** ```objective-c // ArticleInspectorViewController.h @interface ArticleInspectorViewController : NSViewController @property (nonatomic, strong) NSNotificationCenter *notificationCenter; @end // ArticleInspectorViewController.m @implementation ArticleInspectorViewController - (instancetype)initWithNibName:(NSNibName)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { self.notificationCenter = [NSNotificationCenter defaultCenter]; } return self; } - (void)setRepresentedObject:(id)representedObject { [super setRepresentedObject:representedObject]; [self.notificationCenter postNotificationName: InspectedArticleDidChangeNotificationName object: self userInfo: @{ @"Article" : representedObject }]; } @end ``` 테스트 케이스에서는 다른 어디에서도 사용되지 않은 또 다른 notification center로 치원할 수 있다. 이렇게 하면 다른 테스트와 모듈의 행위로부터 고립시킬 수 있다. **Swift** ```swift class ArticleInspectorViewControllerTests: XCTestCase { var viewController: ArticleInspectorViewController! = nil var article: Article! = nil var notificationCenter: NotificationCenter! = nil var articleFromNotification: Article! = nil var observer: NSObjectProtocol? = nil override func setUp() { notificationCenter = NotificationCenter() viewController = ArticleInspectorViewController() viewController.notificationCenter = notificationCenter article = Article() observer = notificationCenter.addObserver(forName: NSNotification.Name(InspectedArticleDidChangeNotificationName), object: viewController, queue: nil) { note in let observedArticle = note.userInfo?["Article"] self.articleFromNotification = observedArticle as? Article } } override func tearDown() { notificationCenter.removeObserver(observer!) } func testNotificationSentOnChangingInspectedArticle() { viewController.representedObject = self.article XCTAssertEqual(self.articleFromNotification, self.article, "Notification should have been posted") } } ``` **Objective-C** ```objective-c @implementation ArticleInspectorViewControllerTests { ArticleInspectorViewController *viewController; NSNotificationCenter *center; Article *article; Article *articleFromNotification; id <NSObject> observer; } - (void)setUp { center = [[NSNotificationCenter alloc] init]; viewController = [[ArticleInspectorViewController alloc] initWithNibName:nil bundle:nil]; viewController.notificationCenter = center; article = [[Article alloc] init]; observer = [center addObserverForName:InspectedArticleDidChangeNotificationName object:viewController queue:nil usingBlock:^(NSNotification * _Nonnull note) { self->articleFromNotification = [note userInfo][@"Article"]; }]; } - (void)tearDown { [center removeObserver:observer]; observer = nil; center = nil; article = nil; articleFromNotification = nil; viewController = nil; } - (void)testNotificationSentOnChangingInspectedArticle { viewController.representedObject = article; XCTAssertEqualObjects(articleFromNotification, article, @"Notification should have been posted"); } @end ``` 출처 * https://developer.apple.com/documentation/xcode/testing-your-apps-in-xcode * https://developer.apple.com/documentation/xcode/adding-unit-tests-to-your-existing-project ======================= File: _posts/App/iOS/2021-08-02-UIViewControllerTransitioningDelegate.md ======================= <filename>_posts/App/iOS/2021-08-02-UIViewControllerTransitioningDelegate.md<gh_stars>1-10 --- layout: post title: "[iOS] - UIViewControllerTransitioningDelegate" subtitle: "" categories: app tags: app-ios comments: true header-img: --- > `Custom UIViewController Transition을 가능하게 하는 UIViewControllerTransitioningDelegate에 대해 알아보자.` --- ## UIViewControllerTransitioningDelegate [이 프로토콜은](https://developer.apple.com/documentation/uikit/uiviewcontrollertransitioningdelegate) 뷰 컨트롤러 간의 고정된 길이나 상호작용 가능한 transition을 관리하는 객체를 제공하는 메서드들을 담고 있다. iOS 7.0부터 사용 가능하다. Custom modal presentation type을 사용해서 뷰 컨트롤러를 출력하고 싶으면, `modalPresentationStyle` 프로퍼티를 `custom`으로 설정하고 `transitioningDelgate` 프로퍼티에 이 프로토콜을 따르를 객체를 할당한다. 뷰 컨트롤러를 출력할 때, UIKit은 뷰 컨트롤러를 제 위치로 애니메이팅할 때 transitioning delegate에 사용할 객체를 요구한다. Transitioning delegate 객체를 구현할 때, 뷰 컨트롤러가 나타나는지, 아니면 해제되는지에 따라 다른 animator 객체를 반환할 수 있다. 모든 전환은 `UIViewControllerAnimatedTransitioning` 프로토콜을 따르는 객체인 **transition animator** 객체를 사용해서 기본적인 애니메이션을 구현한다. 이 transition animator 객체는 유한한 시간동안 애니메이션들을 수행한다. 만약 애니메이션의 타이밍을 조절할 때 터치나 다른 사용자 interaction을 사용하고 싶으면 `UIViewControllerInteractiveTransitioning` 프로토콜을 따르는 객체인 **interactive animator** 객체를 제공해서 애니메이션의 진행도를 업데이트할 수 있다. Custom modal transition 스타일에 대해서는 animator 객체에 추가로 `UIPresentationController` 객체를 제공할 수 있다. 시스템은 이 presentation controller를 뷰 컨트롤러를 출력하기 전에 생성하고 뷰 컨트롤러가 해제될 때까지 이 객체에 대한 참조를 가지고 있는다. 이 presentation controller 객체가 animator 객체의 생명주기를 넘어서서 존재하기 때문에, presentation controller 객체를 사용해서 어려운 presentation이나 dismissal 하는 처리를 하도록 할 수 있다. 예를 들어 custom transition 스타일이 뷰 컨트롤러의 컨텐츠의 배경으로 별도의 그림자 뷰를 출력한다면, presentation controller는 이 그림자 뷰를 만들고 적절한 때에 나타내고 숨길 수 있다. 위에서 총 3가지의 객체에 대해 얘기했다. 1. Transition animator object 2. Interactive animator obejct 3. Custom Presentation controller 프로토콜의 메서드도 이에 맞게 각각의 객체들을 가져오는 메서드들로 이루어져 있다. ![image](https://user-images.githubusercontent.com/41438361/126279764-5523d31c-03a9-45de-9324-3edf0091415a.png) ![image](https://user-images.githubusercontent.com/41438361/126279782-048fdf1c-509e-404c-b063-6a16d41289ce.png) ![image](https://user-images.githubusercontent.com/41438361/126279805-ce9274e1-7ff9-40f2-bc20-2629f3ca9911.png) ### 1. Getting the Transition Animator Objects #### animationController(forPresented:presenting:source:) 뷰 컨트롤러를 띄울 때 delegate에 사용할 **transition animator 객체**를 요청한다. ```swift optional func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? ``` * presented: 화면에 띄워지는 뷰 컨트롤러 객체다. * presenting: 뷰 컨트롤러를 띄우는 뷰 컨트롤러다. Window의 루트 뷰 컨트롤러가 될 수도 있고, 현재 context를 정의하는 부모 뷰 컨트롤러일 수도 있고, 가장 위에 띄워진 뷰 컨트롤러일 수도 있다. source에 있는 것과 같거나 같지 않을 수도 있다. * source: `present(_:animated:completion:)` 메서드가 호출된 뷰 컨트롤러다. **리턴 값** 뷰 컨트롤러를 띄울 때 사용되는 animator 객체를 리턴하거나, custom transition을 이용해서 뷰 컨트롤러를 띄우기 싶지 않을 경우 `nil`을 리턴한다. 여기서 리턴하는 객체는 상호작용이 가능하지 않은 고정된 길이의 애니메이션을 구생하는 객체여야 한다. #### animationController(forDismissed:) 위와는 반대로, 뷰 컨트롤러를 해제할 때 사용할 **transition animator 객체**를 반환한다. ```swift optional func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? ``` * dismissed: 해제될 뷰 컨트롤러 객체다. 나머지는 `animationController(forPresented:presenting:source:)`와 비슷하다. 해제할 때 사용할 애니메이터 객체를 리턴하거나, 애니메이션을 적용하지 않고 해제하려면 `nil`을 리턴한다. ### 2. Getting the Interactive Animator Objects #### interactionControllerForPresentation(using:) 이것도 위에서 봤던 것처럼 animator 객체를 요청하는데, 다른 점은 **interactive** animator 객체를 요청한다는 것이다. ```swift optional func interactionControllerForPresentation(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? ``` 위에서는 리턴 타입으로 `UIViewControllerAnimatedTransitioning?` 타입을 반환했었는데, 여기에서는 리턴타입으로 `UIViewControllerInteractiveTransitioning?`을 리턴하는 것을 보아 확실히 다르다는 것을 알 수 있다. * animator: `animationController(forPresented:presenting:source:)`에 의해 리턴된 transition animator 객체다. 여기서도 마찬가지로, 상호작용이 가능한 interactive transition을 하고 싶지 않으면 `nil`을 리턴하고, 그렇지 않으면 transition의 타이밍을 관리하는 상호작용 animator 객체를 반환한다. 중요한 것은 이 메서드를 구현하면, 파라미터로 넘겨줄 `animator`를 받기 위해 `animationController(forPresented:presenting:source:)` 메서드를 구현해서 custom transition animator 객체를 반환해야 한다는 것이다. #### interactionControllerForDismissal(using:) 뷰 컨트롤러를 해제할 때 사용할 interactive animator 객체를 받는 메서드다. ```swift optional func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? ``` * animator: `animationController(forDismissed:)` 메서드에서 리턴된 애니메이터 객체다. 여기서도 animator에 `animationController(forDismissed:)`에서 반환된 객체를 넣어주므로 이 메서드를 구현하면 꼭 `animationController(forDismissed:)`를 메서드를 구현해야 한다. ### 3. Getting the Custom Presentation Controller #### presentationController(forPresented:presenting:source:) 뷰 컨트롤러를 출력할 때 뷰 계층을 관리할 때 사용하는 custom presentation controller를 delegate에 요청한다. UIKit은 새로운 ViewController를 화면에 그릴 때 UITransitionView를 만들고, 그 위에 ViewController를 그리는데, 이 transitionView를 관리하는 controller라고 생각하면 된다. ```swift optional func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? ``` * presented: 띄워지는 뷰 컨트롤러다 * presenting: 띄워지는 뷰 컨트롤러다. 이 파라미터는 뷰 컨트롤러를 띄우는 뷰 컨트롤러가 나중에 결정될 것이라는 것을 나타내기 위해 `nil`이 될 수 있다. * source: `present(_:animated:completion:)` 메서드를 호출한 뷰 컨트롤러다. **리턴 값** Modal presentation을 관리하기 위한 custom presentation controller를 반환한다. **기타** `UIModealPresentationStyle.custom` presentation 스타일을 사용해서 뷰 컨트롤러를 띄운다면, 시스템은 이 메서드를 호출하고 커스텀 스타일을 관리하는 presentation controller를 요청한다. 이 메서드를 구현하면, presentation process를 관리하기 위한 custom presentation controller 객체를 생성해서 반환하게 한다. dddddssss ddddsss ======================= File: _posts/CS/디자인패턴/2021-04-05-객체지향 모델링, UML, 클래스 다이어그램.md ======================= <filename>_posts/CS/디자인패턴/2021-04-05-객체지향 모델링, UML, 클래스 다이어그램.md --- layout: post title: "객체지향 모델링이란? - UML, Class Diagram" subtitle: "" categories: cs tags: cs-dp uml class-diagram comments: true header-img: --- > `객체지향 모델링이란 무엇인가? UML, Class Diagram은 무엇인가?` --- ## 모델링 모델은 관객들에게 디자이너가 보여주고 싶은 옷의 특징을 잘 보여줄 수 있어야 한다. 자동차 모델 같은 경우에는 모델만 보고도 바퀴가 몇 개이고 좌석이 얼마나 되는지 알 수 있어야 한다. 소프트웨어 개발에서 모델의 역할도 비슷하다. 모델의 역할은 크게 다음과 같다. 1. 서로의 해석을 공유해 합의를 이루거나 해석의 타당성을 검토한다. 2. 현재 시스템 / 앞으로 개발할 시스템의 원하는 모습을 가시화한다. 3. 시스템의 구조와 행위를 명세할 수 있으며 시스템을 구축하는 틀을 제공한다. 모델은 **추상화**를 바탕으로 만들어져야 한다. 추상화는 대상에서 꼭 필요한 부분을 부각시킨다. 예를 들어 수강 시스템에서는 학생의 아침 식단은 전혀 중요하지 않으므로 시스템에서 제외될 수 있지만, 학번 같은 경우에는 매우 중요한 정보이므로 시스템에 포함되어야 한다. ## UML 모델링을 하려면 시스템을 모델로 표현해주는 언어가 필요한데, 대표적으로 UML(Unified Modeling Language)가 있다. **UML은 요구 분석, 시스템 설계, 시스템 구현 등의 개발 과정에서 개발자 사이에 의사소통이 원활하게 이루어질 수 있도록 표준화된 통합 모델링 언어다.** UML 다이어그램의 종류는 아래와 같다. |분류|다이어그램 유형|목적| |--|--|--| |구조 다이어그램(structure diagram)|클래스 다이어그램(class diagram)|시스템을 구성하는 클래스들 사이의 관계를 표현한다.| ||객체 다이어그램(object diagram)|객체 정보를 보여준다.| ||복합체 구조 다이어그램(composite structure diagram)|복합구조의 클래스와 컴포넌트 내부 구조를 표현한다.| ||배치 다이어그램(deployment diagram)|소프트웨어, 하드웨어, 네트워크를 포함한 실행 시스템의 물리 구조를 표현한다.| ||컴포넌트 다이어그램(component diagram)|컴포넌트 구조 사이의 관계를 포함한다.| ||패키지 다이어그램(package diagram)|클래스나 유즈 케이스 등을 포함한 여러 모델 요소들을 그룹화해 패키지를 구성하고 패키지들 사이의 관계를 표현한다.| |행위 다이어그램(behavior diagram)|활동 다이어그램(activity diagram)|업무 처리 과정이나 연산이 수행되는 과정을 표현한다.| ||상태 머신 다이어그램(state machine diagram)|객체의 생명 주기를 표현한다.| ||유즈 케이스 다이어그램(use case diagram)|사용자 관점에서 시스템 행위를 표현한다.| ||순차 다이어그램(sequence diagram)|시간 흐름에 따른 객체 사이의 상호작용을 표현한다.| ||상호작용 개요 다이어그램(interaction overview diagram)|여러 상호작용 다이어그램 사이의 제어 흐름을 표현한다.| ||통신 다이어그램(communication diagram)|객체 사이의 관계를 중심으로 상호작용을 표현한다.| ||타이밍 다이어그램(timing diagram)|객체 상태 변화와 시간 제약을 명시적으로 표현하다.| 위와 같이 다양한 다이어그램이 있는 이유는 다양한 관점에서 시스템을 모델링하기 위해서다. ## 클래스 다이어그램 클래스 다이어그램은 **시간에 따라 변하지 않는 시스템의 정적인 면을 보여주는 대표적인 UML 구조 다이어그램**이다. 클래스 다이어그램은 시스템을 구성하는 클래스와 그것들의 관계를 보여주기 때문에 주요 구성 요소는 클래스와 관계이다. ### 클래스 클래스란 **동일한 속성과 행위를 수행하는 객체의 집합**이다. / **공통의 속성과 책임을 찾는 객체들의 집합이자 실제 객체를 생성하는 설계도다.** 고양이와 사자가 있다고 할 때 두 동물 모두 다 "울" 수 있다. 그리고 둘 다 꼬리를 가지고 있다. 이때 둘다 꼬리라는 것과 운다는 행위를 둘다 가지고 있으므로 고양이와 사자는 각각 하나의 객체가 될 수 있으며 고양이과 를 클래스로 볼 수 있는 것이다. 또 다른 관점은 클래스를 객체를 생성하는 설계도로 간주하는 것이다. ### 관계 클래스 하나만 존재하는 시스템은 없다. 클래스도 여러 개의 클래스가 모인 시스템이 훨씬 효율적이다. 객체지향에서는 클래스가 서로 관계를 맺어 기능을 수행한다. 알 UML에서 클래스는 아래와 같이 표현한다. ![image](https://user-images.githubusercontent.com/41438361/113538458-40783a00-9616-11eb-811e-27d1706ec5ab.png) 가장 윗부분에는 클래스 이름, 중간에는 속성, 마지막에는 연산(메서드)를 기술한다. 경우에 따라 속성 부분이나 연산 부분은 생략할 수 있다. 이 경우에는 생략된 부분을 위해 따로 선을 그리지 않아도 된다. 클래스의 속성과 연산을 기입할 때는 `-`, `+`와 같은 부호를 사용하는데, 이것은 속성과 연산의 **가시화**를 정의한 것이다. 가시화 정보는 외부에 속성과 연산을 어느 정도 공개하느냐에 따라 달라지고 아래는 접근 제어자를 UML에서 어떻게 나타내는지 표를 그린 것이다. |접근 제어자|표시|설명| |--|--|--| |public|+|어떤 클래스의 객체에서든 접근 가능| |private|-|이 클래스에서 생성된 객체들만 접근 가능| |protected|#|이 클래스와 동일 패키지에 있거나 상속 관계에 있는 하위 클래스의 객체들만 접근 가능| |package|~|동일 패키지에 있는 클래스의 객체들만 접근 가능| 하지만 이런 가시화 정보를 항상 표시해야 하는 것은 아니다. 분석 단계에서는 가시화 정보보다 어떤 것을 속성으로 갖는지가, 설계 단계에서는 구체적인 타입과 가시화 정보가 중요할 수 있다. 따라서 속성과 연산 정보를 기입할 때 상황에 따라 생략해서 적을 수 있는 부분들이 있다. `[]`부분은 생략할 수 있는 부분을 의미한다. ||표기방법| |--|--| |속성|[+\|-\|#\|~]이름:타입[다중성 정보][=초기값]| |연산|[+\|-\|#\|~]이름(인자1:타입1,..., 인자n:타입n) : 반환타입| 보통 분석 단계의 클래스 다이어그램에서는 속성과 연산 항목에 타입 정보와 가시화 정보를 기술하지 않고, 설계 단계의 클래스에서는 바로 코드를 생성할 수 있게끔 구체적인 타입 정보와 가시화 정보를 기술한다. 아래는 UML에서 제공하는 클래스들 사이의 관계를 나타낸 표이다. |관계|설명| |--|--| |연관 관계(association)|클래스들이 개념상 서로 연결되었음을 나타낸다. 실선/화살표로 표시하고, 한 클래스가 다른 클래스에서 제공하는 기능을 사용하는 상황일 때 표시한다| |일반화 관계(generalization)|상속 관계. 한 클래스가 다른 클래스를 포함하는 상위 개념일 때 IS-A 관계라고 한다. 속이 빈 화살표로 표시한다.| |집합 관계(composition, aggregation)|클래스 사이의 전체/부분 같은 관계를 나타낸다.| |의존 관계(dependency)|한 클래스가 다른 클래스에서 제공하는 기능을 사용할 때를 나타낸다. 차이점은 두 클래스의 관계가 한 메서드를 실행하는 동안과 같은 아주 짧은 시간만 유지된다. 점섬 화살표로 나타낸다.| |실체화 관계(realization)|책임들의 집합인 인터페이스와 이 책임들을 실제로 실현한 클래스들 사이의 관계를 나타낸다. 상속과 유사한 빈 삼각형을 사용하고 머리에 있는 실선 대신 점선을 사용해 나타낸다.| ### 1. 연관 관계 두 클래스가 연관 관계가 있을 때는 클래스 사이에 선을 그어 표시한다. 클래스 사이의 연관 관계가 명확할 경우에는 연관 관계 이름을 사용하지 않아도 된다. 한 클래스가 다른 클래스와 연관 관계를 가지면 각 클래스의 객체는 해당 연관 관계에서 특정 역할을 수행할 수 있는데 이는 클래스에 이어진 선 가까이에 적을 수 있다. 예를 들어 교수님 클래스와 학생 클래스가 있을 때 '상담한다'라는 연관 관계를 가진다고 해보자. 그러면 이때 교수님은 조언자, 학생은 학생의 역할을 수행하게 되는 것이다. 이런 관계는 **양방향 연관 관계**로 UML에서 두 클래스를 연결한 선에 화살표를 사용하지 않는다. 이는 두 클래스의 객체들이 서로의 존재를 인식한다는 의미이다. 또한 연관 관계를 나타내는 선에 아무런 숫자가 없으면 연관 관계가 1:1임을 나타내는 것이다. 위에서 든 예제에서, 교수님은 여러 명의 학생을 맡을 수 있는데, 이를 나타내기 위해 학생의 수를 선 근처에 표시한다. 이를 **다중성(multiplicity)**이라고 한다. 다중성을 나타내는 방법은 아래와 같다. |다중성 표기|의미| |--|--| |1|딱 1.| |\*|0 이상| |0..\*|0 이상| |1..\*|1 이상| |0..1|0 또는 1| |2..5|2 이상 5 이하| |1,2,6|1 또는 2 또는 6| |1, 3..5|1 또는 3 또는 4 또는 5| 연관 관계는 방향성을 가질 수 있다. 예를 들어 학생이 과목을 수강한다고 했을 때 화살표는 학생에서 나와 과목 쪽으로 들어가야 한다(과목을 화살표가 가리키고 있어야 한다.) 이 경우 학생은 자신이 수강하는 과목을 알지만 과목은 자신을 수강하는 학생들의 존재를 모른다는 것을 의미한다. 이렇게 방향성이 있는 연관 관계를 **단방향 연관 관계**라고 한다. 즉, 양방향 연관 관계는 서로의 존재를 안다는 의미이고, 단방향 연관 관계는 한 쪽은 알지만 다른 쪽은 상대방의 존재를 모른다는 의미이다. ![image](https://user-images.githubusercontent.com/41438361/113540213-9e0e8580-961a-11eb-83cf-b1bff2cfa6f0.png) 일반적으로 다대다 연관 관계는 단방향 연관 관계가 아닌 양방향 연관 관계로 표현되는 것이 적절하다. 하지만 다대다 관계는 자연스럽게 양방향 연관 관계가 되므로 구현하기 복잡한데, 이 관계를 일대다 단방향 연관 관계로 변환해 구현한다. 추가로 학생과 수강 과목 을 연관 관계로 표시한다고 할 때, 성적 정보는 어디에 포함될까? 성적 정보는 '학생'이 '과목'을 수강해야 생기는 것이므로 학생이나 과목 중 오로지 하나에만 포함될 수 없다. 따라서 성적 정보는 클래스의 속성이 아닌 '수강하다'라는 연관 관계의 속성으로 다뤄야 한다. 이때 **연관 클래스**를 사용하는 것이다. 연관 클래스는 연관 관계에 추가할 속성이나 행위가 있을 때 사용하고, 아래 그림과 같이 표시한다. ![image](https://user-images.githubusercontent.com/41438361/113660622-7a614300-96df-11eb-9c95-7c4f3ab8e3ef.png) 이 예에서 1. 학생 2. 과목 3. 성적 클래스를 생성할 수 있다. 성적 객체는 하생과 과목에 대한 정보를 모두 담고 있어야 한다. 학생은 여러 개의 성적을 받을 수 있고, 한 과목에서도 여러 가지 성적이 산출된다. 따라서 학생과 성적의 관계, 과목과 성적의 관계는 일대다 이다. 이것을 기반으로 위의 다이어그램을 수정하면 아래와 같다. ![image](https://user-images.githubusercontent.com/41438361/113660860-f3609a80-96df-11eb-8675-2df29e059689.png) 한 학생이 한 과목을 재수강해서 성적 정보를 여러개 가질 수 있는데, 성적 클래스 이름 아랫부분에 연관관계의 이력(history)를 쓰면 된다. 연관 관계는 **재귀적**일 수 있다. 재귀적 연관 관계란 **동일한 클래스에 속한 객체들 사이의 관계**다. 예를 들어 직원에 관리자와 사원 클래스가 있다 해보자. a가 b를 관리하는 관리자이면 a는 관리자, b는 사원이 된다. 하지만 b도 c를 관리하는 관리자라면 b는 관리자이면서 사원이 되는 것이다. 이렇게 두 클래스에 속하는 모순이 발생하고, 이렇게 두 개의 클래스로 나눠서 관리하면 시스템이 바뀔 때 유연성이 부족할 수 있으므로 역할은 클래스로 웬만해서 만들지 않는 것이 좋다. 그래서 아래와 같이 재귀적인 연관 관계가 등장했다. ![image](https://user-images.githubusercontent.com/41438361/113661321-d37da680-96e0-11eb-964a-c9e548b4f6ed.png) 하지만 a가 b를 관리하고 b가 c를 관리하고 c가 a를 관리하는 상황처럼 **관계의 루프**가 발생하는 경우에 문제가 발생하는데, 이런 상황을 배제하기 위해 연관 관계에 아래와 같이 **제약**을 설정한다. ![image](https://user-images.githubusercontent.com/41438361/113661428-07f16280-96e1-11eb-92d6-8eb11d9bb760.png) 제약은 `{}` 안에 정해진 제약, 문장을 자유롭게 쓸 수 있고, 클래스나 연관 관계를 포함한 UML 모델 요소가 따라야 하는 규칙을 붙여줄 때 사용한다. 위 그림에서 `계층`은 객체 사이에 상하 관계가 존재하고 사이클이 존재하지 않는다는 의미이다. ### 2. 일반화 관계 **한 클래스가 다른 클래스를 포함하는 상위 개념일 때 두 클래스 사이에는 일반화 관계가 존재**한다. 이를 객체지향 개념에서는 '상속 관계'라고 하고, 'is a kind of 관계'랑 같은 말이다. 상위 클래스를 부모 클래스, 하위 클래스를 자식 클래스라고 한다. UML에서 일반화 관계는 화살표의 끝에 빈삼각형 표시를 해 표시한다. 삼각형 표시가 있는 쪽이 부모 클래스, 반대쪽은 자식 클래스다. 자식 클래스들에는 공통 되는 연산들이 있을 수 있는데, 이때 부모 클래스에 구현하지 않은 빈 껍데기만 있는 연산을 선언한다. 이를 **추상 메서드**라고 한다. 빈 껍데기만 만들어 놓는 이유는 이를 자식 클래스에서 상속해서 구현을 모두 다르게 할 수 있기 때문이다. 이처럼 **추상 메서드를 하나 이상 가지는 클래스를 추상 클래스**라고 하고, 다른 일반 클래스와는 다르게 **객체를 생성할 수 없다.** UML에서는 추상클래스와 메서드를 이탤릭체로 써서 구분하거나 스테리오 타입('<<','>>' 안에 이름 넣어 표시)으로 표시한다. ### 3. 집합 관계 집합 관계는 UML 연관 관계의 특별 경우로 **전체와 부분의 관계를 명확하게 명시하고자 할 때 사용**한다. 1. 집약과 2. 합성 두 종류의 집합 관계가 존재한다. 1. 집약 관계 집약 관계는 한 객체가 다른 객체를 포함하는 것을 나타낸다. 이때 전체 객체의 라이프타임과 부분 객체의 라이프타임은 독립적이라 전체 객체가 메모리에서 사라진다 해도 부분 객체는 사라지지 않는다. 전체를 가리키는 클래스 방향에 빈 마름모로 표시한다. 3. 합성 관계 합성 관계는 부분 객체가 전체 객체에 속하는 관계다. 전체를 가리키는 클래스 방향에 채워진 마름모료 표시한다. 전체 객체가 사라지면 부분 객체도 사라진다. 아래의 코드를 비교해보자. ```java // Computer객체가 사라지면 메인보드, CPU 객체가 사라진다. public class Computer { private MainBoard mb; private CPU c; public Computer() { this.mb = new MainBoard(); this.c = new CPU(); } } // Computer 객체가 사라져도 메인보드, CPU 객체는 남아있다. 외부에서 참조만 받아 사용했기 떄문. public class Computer { private MainBoard mb; private CPU c; public Computer(MainBoard mb, CPU c) { this.mb = mb; this.c = c; } } ``` ### 4. 의존 관계 한 클래스가 다른 클래스를 사용하는 경우는 3가지가 있다. 1. 클래스의 속성에서 참조할 때 2. 연산의 인자로 사용도리 때 3. 메서드 내부의 지역객체로 참조될 때 사람-차 의 관계를 봤을 때, 보통 한 사람은 자차를 갖고 있을 때 오랫동안 그 차를 이용할 것이다. 이럴 경우 오랜 기간 관계를 가진다고 할 수 있는데, 자동차-주유기 관계를 보면 다르다. 주유할 때 특정 주유기만 계속 사용할 수 있다는 보장이 없으며, 이용하는 주유기가 매번 달라질 수 있다. 이를 객체지향 프로그램에서는 사용되는 주유기를 인자나 지역 객체로 생성해 구현할 것이다. 연관 관계는 오랜 시간 같이할 객체와의 관계, 의존 관계는 짧은 시간 동안 이용하는 관계다. ### 5. 인터페이스와 실체화 관계 인터페이스란 책임이다. 실제로 책임을 수행하는 객체는 아니며, 이를 실현하는 클래스에서 책임을 수행한다. UML에서는 화살표를 빈 삼각형을 가진 끝과 함께 점선으로 표시한다. ======================= File: _posts/App/iOS/2021-05-15-빅너드 5. Prgrammatic Views.md ======================= <reponame>Yoojin99/Yoojin99.github.io<filename>_posts/App/iOS/2021-05-15-빅너드 5. Prgrammatic Views.md --- layout: post title: "[iOS Programming Big Nerd Ranch] 5. Programmatic Views, 뷰를 코드로 생성하기" subtitle: "" categories: app tags: app-ios comments: true header-img: --- > `view를 코드로 생성해보자.` --- 이미 이전에 컨트롤러 두 개와 각 뷰들을 스토리보드로 만들었다. 그 중 맵 컨트롤러의 View를 선택해서 지운다. ![image](https://user-images.githubusercontent.com/41438361/118354769-b4a7e500-b5a7-11eb-8e31-a592dd00772f.png) ## Creating a View Programmatically 앞에서 뷰 컨트롤러의 뷰를 코드로 만들기 위해 `UIViewController`의 메서드 `loadView()`를 사용한다는 것을 봤다. MapViewController.swift의 코드를 아래와 같이 작성한다. ```swift import UIKit import MapKit class MapViewController: UIViewController { var mapView: MKMapView! override func loadView() { // Create a map view mapView = MKMapView() // Set it as *the* view of this view controller view = mapView } override func viewDidLoad() { super.viewDidLoad() print("MapViewController loaded its view.") } } ``` 뷰 컨트롤러가 생성되었을 때, `view` 프로퍼티는 nil로 설정되어 있다. 뷰 컨트롤러가 `view`를 요청했고 이 `view`가 nil이면, `loadView()` 메서드가 호출된다. 이제 앱을 실행시키면 전과 같은 화면이 나온다. ## Programmatic Constraints 앞에서는 Interface Builder를 이용해서 Auto Layout constraints를 설정했는데, 이제는 코드로 해 볼 것이다. 애플은 간읗나 뷰를 생성하고 제약을 설정하는 것을 Interface Builder에서 하라고 하지만, 뷰가 코드로 생성되었다면 제약 또한 코드로 해야 한다. `~.translatesAutoresizingMaskIntoConstraints = false` 구문은 예전 시스템의 사이즈를 조정하는 인터페이스인 autoresizing masks를 설정한다. Auto Layout이 소개되기 이전에, iOS 애플리케이션은 autoresizing mask를 이용해서 실행시간에 다른 크기의 화면들에 맞게 뷰의 크기를 조정하는 것을 가능하게 해줬다. 모든 뷰는 autoresizing mask를 가지고 있다. 기본적으로, iOS 는 autoresizing mask에 해당하는 제약을 생성해서 뷰에 추가한다. 이 전환된 constraint들은 레이아웃에 명시된 제약들과 충돌을 일으킬 수 있고, 문제가 생길 수 있다. 이 설정을 false로 설정해서 default translation을 꺼놓는 것이다. `loadView()`안에 코드를 작성한다. ```swift let segmentedControl = UISegmentedControl(items: ["Standard", "Hybrid", "Satellite"]) segmentedControl.backgroundColor = UIColor.white.withAlphaComponent(0.5) segmentedControl.selectedSegmentIndex = 0 segmentedControl.translatesAutoresizingMaskIntoConstraints = false view.addSubview(segmentedControl) ``` ## Anchors Auto Layout을 코드로 구현할 때, constraint를 만들기 위해 anchor를 사용한다. Anchor는 anchor를 다른 뷰에 맞춰 설정하고 싶은 속성들에 일치하는 뷰의 속성이다. Anchor들은 두 anchor 사이에 제약을 생성하는 `constraint(equalTo:)`라는 메서드가 있다. `NSLayoutAnchor`에 그 외에 다른 제약을 만드는 메서드가 있다. ```swift let topConstraint = segmentedControl.topAnchor.constraint(equalTo: view.topAnchor) let leadingConstraint = segmentedControl.leadingAnchor.constraint(equalTo: view.leadingAnchor) let trailingConstraint = segmentedControl.trailingAnchor.constraint(equalTo: view.trailingAnchor) ``` ## Activating constraints 이제 세 개의 `NSLayoutConstraint` 인스턴스가 있지만, `isActive` 프로퍼티를 true로 만들어서 명시적으로 활성화하지 않는 이상 아무런 효과를 가지고 있지 않다. ```swift topConstraint.isActive = true leadingConstraint.isActive = true trailingConstraint.isActive = true ``` 제약들은 가장 제약과 연관이 있는 뷰의 가장 최근의 common ancestor에 추가되어야 한다. 아래 그림은 두 뷰의 common ancestor를 함께 보여주는 뷰 계층을 나타낸다. ![image](https://user-images.githubusercontent.com/41438361/118355922-bb395b00-b5ad-11eb-9001-d36e4e974cec.png) 만약 제약이 오직 하나의 뷰에 관련되어 있다면 뷰가 common ancestor가 된다. `active` 프로퍼티를 true로 만들면 제약은 계층에서 제약이 추가되어야 하는 common ancestor를 찾는다. 그리고 적절한 뷰에서 `addConstraint` 메서드를 실행시킨다. 하지만 지금까지 만든 뷰를 보면 위의 세그먼트 컨트롤이 가장 위에 있어서 가장 위의 시간을 표시하는 부분과 겹친다. ![image](https://user-images.githubusercontent.com/41438361/118355998-2125e280-b5ae-11eb-9a9d-f7eaf750870a.png) ### 새로 알게된 점 위에 작성한 코드에서, `loadView()`에서 원래는 ```swift mapView = MKMapView() ``` 로 작성해야 하는 걸 생략해버려서 mapView가 계속 nil인 상태였다. nil인 상태에서 ```swift view.addSubview(segmentedControl) ``` 해버렸으니 nil에 addSubView를 한 것이었다. 위에서도 언급이 되었고 `https://stackoverflow.com/questions/4986098/viewdidload-infinite-loop-issue-ios/7370917`에서도 언급이 되었듯이, `self.view`가 존재하지 않으면 iOS는 `loadView`, `viewDidLoad` 메서드를 계속 불러서 뷰를 생성하려고 한다. 이게 무한 루프에 빠지게 해서 앱이 정상적으로 작동하지 않는 것이었다. ## Layout guides 뷰 컨트롤러는 `topLayoutGuide`와 `bottomLayoutGuide`를 이용해서 레이아웃을 지원한다. `topLayoutGuide`를 사용하면 화면 상단에 있는 status bar나 navigation bar와 컨텐츠가 겹치지 않게 할 수 있다. 반대로 `bottomLayoutGuide`는 화면의 바닥에 있는 탭 바와 겹치지 않게 해준다. ```swift let topConstraint = segmentedControl.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor, constant: 8) ``` 와 같이 topConstraint를 수정한다. ## Margins 이제 leading과 trailing 끝을 superview 안으로 좀 넣어보겠다. 모든 뷰는 컨텐츠를 표시할 때 사용하는 기본 여백을 나타내는 `layoutMargins` 프로퍼티를 가지고 있다. 이 프로퍼티는 `UIEdgeInsets`의 인스턴스이고, 프레임의 한 타입이라고 생각할 수 있다. 제약을 추가할 때, `layoutMargins`의 끝에 묶여진 anchor를 나타내는 `layoutMarginsGuide`를 사용한다. margin을 사용하는 주 장점은 디바이스 타입과 디바이스 사이즈에 따라 margins이 바뀔 수 있다는 것이다. 코드를 아래와 같이 수정한다. ```swift let margins = view.layoutMarginsGuide let leadingConstraint = segmentedControl.leadingAnchor.constraint(equalTo: margins.leadingAnchor) let trailingConstraint = segmentedControl.trailingAnchor.constraint(equalTo: margins.trailingAnchor) ``` ![image](https://user-images.githubusercontent.com/41438361/118356243-2fc0c980-b5af-11eb-9a37-848c95052e7d.png) 예쁘게 바뀐 걸 확인할 수 있다. ## Explicit constraints 메서드가 제약을 어떻게 생성하는지 이해하는 것이 도움이 된다. `NSLayoutConstraint`는 아래의 이니셜라이저를 갖는다. ```swift convenience init(item view1: Any, attribute attr1: NSLayoutAttribute, relatedBy relation: NSLayoutRelation, toItem view2: Any?, attribute attr2: NSLayoutAttribute, multiplier: CGFloat, constant c: CGFloat) ``` 이 이니셜라이저는 두 뷰 객체의 레이아웃 어트리뷰트를 이용해서 단일한 제약을 생성한다. 여기서 multiplier가 비율에 따른 제약을 생성하는 키다. 여기서 상수는 고정된 숫자고, 여백에 관련된 제약에 사용한 것과 비슷하다. 레이아웃 어트리뷰트는 `NSLayoutConstraint` 클래스에서 정의된 상수다. * NSLayoutAttribute.left * NSLayoutAttribute.right * NSLayoutAttribute.leading * NSLayoutAttribute.trailing * NSLayoutAttribute.top * NSLayoutAttribute.bottom * NSLayoutAttribute.width * NSLayoutAttribute.height * NSLayoutAttribute.centerX * NSLayoutAttribute.cetnerY * NSLayoutAttribute.firstBaseline * NSLayoutAttribute.lastBaseline 이 외에도 `NSLayoutAttribute.leadingMargin`과 같이 뷰와 관련된 margins를 다루는 추가의 attribute가 있다. 예를 들어, 이미지의 가로가 세로의 1.5배 길이였으면 좋겠을 때 아래의 코드를 사용한다. ```swift let aspectConstraint = NSLayoutConstraint(item: imageView, attribute:.width, relatedBy:.equal, toItem: imageView, attribute:.height, multiplier: 1.5, constant: 0.0 ) ``` 이 생성자가 어떻게 동작하는지 알기 위해, 아래의 그림을 참고한다. ![image](https://user-images.githubusercontent.com/41438361/118388429-5a6a5b00-b65f-11eb-87b6-f4ce40e1842b.png) 한 뷰의 레이아웃 속성을 다른 뷰의 레이아웃 속성에 multiplier와 단일 constraint를 정의하기 위한 constant를 이용해서 관련짓는다. ## Programmatic Controls `UISegmentedControl`은 `UIControl`의 하위클래스다. Controls는 어떤 이벤트에 대해 target이 반응할 메서드를 호출할 책임이 있다. Control 이벤트는 `UIControlEvents`의 타입이다. * `UIControlEvents.touchDown` : 터치하는 이벤트 * `UIControlEvents.touchUpInside` : 컨트롤의 경계 안에서 누르고 떼는 것 * `UIControlEvents.valueChanged` : 값을 바꾸는 터치 * `UIControlEvents.editingCHanged` : `UITextField`를 바꾸는 터치 아래와 같이 segmentedControl 에 `.valueCHanged` 이벤트와 관련된 타겟 액션을 추가하고 그 함수를 추가한다. ```swift segmentedControl.addTarget(self, action: #selector(MapViewController.mapTypeChanged(_:)), for:.valueChanged) ``` ```swift @objc func mapTypeChanged(_ segControl: UISegmentedControl) { switch segControl.selectedSegmentIndex { case 0: mapView.mapType =.standard case 1: mapView.mapType =.hybrid case 2: mapView.mapType =.satellite default: break } } ``` 이제 앱을 실행시키면 맨 위의 segmentedControl 탭을 터치해서 바꿀 때마다 mapview의 타입이 바뀐다. ![image](https://user-images.githubusercontent.com/41438361/118388640-a79afc80-b660-11eb-9c70-d5dbf67be227.png) ![image](https://user-images.githubusercontent.com/41438361/118388646-ae297400-b660-11eb-89af-d6e210ead05e.png) ![image
1,511
..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'T','t' ]; s: 579), { 415: } ( cc: [ '0'..'9','A'..'F','H'..'Z','_','a'..'f','h'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'G','g' ]; s: 580), { 416: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 417: } ( cc: [ '0'..'9','A'..'T','V'..'Z','_','a'..'t','v'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'U','u' ]; s: 581), { 418: } ( cc: [ '0'..'9','A'..'Q','S'..'Z','_','a'..'q','s'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'R','r' ]; s: 582), { 419: } ( cc: [ '0'..'9','B'..'Z','_','b'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'A','a' ]; s: 583), { 420: } ( cc: [ '0'..'9','A'..'L','N'..'Z','_','a'..'l','n'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'M','m' ]; s: 584), { 421: } ( cc: [ '0'..'9','A'..'M','O'..'Z','_','a'..'m','o'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'N','n' ]; s: 585), { 422: } ( cc: [ '0'..'9','A'..'N','P'..'Z','_','a'..'n','p'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'O','o' ]; s: 586), { 423: } ( cc: [ '0'..'9','A'..'H','J'..'Z','_','a'..'h','j'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'I','i' ]; s: 587), { 424: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 425: } ( cc: [ '0'..'9','A'..'H','J'..'Z','_','a'..'h','j'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'I','i' ]; s: 588), { 426: } ( cc: [ '0'..'9','A'..'K','M'..'Z','_','a'..'k','m'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'L','l' ]; s: 589), { 427: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 428: } ( cc: [ '0'..'9','A'..'D','F'..'Z','_','a'..'d','f'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'E','e' ]; s: 590), { 429: } ( cc: [ '0'..'9','A'..'H','J'..'Z','_','a'..'h','j'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'I','i' ]; s: 591), { 430: } ( cc: [ '0'..'9','A'..'H','J'..'Z','_','a'..'h','j'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'I','i' ]; s: 592), { 431: } ( cc: [ '0'..'9','A'..'S','U'..'Z','_','a'..'s','u'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'T','t' ]; s: 593), { 432: } ( cc: [ '0'..'9','B'..'Z','_','b'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'A','a' ]; s: 594), { 433: } ( cc: [ '0'..'9','A'..'Q','S'..'Z','_','a'..'q','s'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'R','r' ]; s: 595), { 434: } ( cc: [ '0'..'9','A'..'D','F'..'Z','_','a'..'d','f'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'E','e' ]; s: 596), { 435: } ( cc: [ '0'..'9','A'..'V','X'..'Z','_','a'..'v','x'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'W','w' ]; s: 597), { 436: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 437: } ( cc: [ '0'..'9','A'..'H','J'..'Z','_','a'..'h','j'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'I','i' ]; s: 598), { 438: } ( cc: [ '0'..'9','A'..'H','J'..'Z','_','a'..'h','j'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'I','i' ]; s: 599), { 439: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 440: } ( cc: [ '0'..'9','A'..'S','U'..'Z','_','a'..'s','u'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'T','t' ]; s: 600), { 441: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 442: } ( cc: [ '0'..'9','A','C'..'Z','_','a','c'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'B','b' ]; s: 601), { 443: } ( cc: [ '0'..'9','A'..'H','J'..'Z','_','a'..'h','j'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'I','i' ]; s: 602), { 444: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 445: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 446: } ( cc: [ '0'..'9','B'..'Z','_','b'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'A','a' ]; s: 603), { 447: } ( cc: [ '0'..'9','A'..'J','L'..'Z','_','a'..'j','l'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'K','k' ]; s: 604), { 448: } ( cc: [ '0'..'9','A'..'H','J'..'Z','_','a'..'h','j'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'I','i' ]; s: 605), { 449: } ( cc: [ '0'..'9','A'..'Q','S'..'Z','_','a'..'q','s'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'R','r' ]; s: 606), { 450: } ( cc: [ '0'..'9','A'..'Q','S'..'Z','_','a'..'q','s'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'R','r' ]; s: 607), { 451: } ( cc: [ '0'..'9','A'..'Q','S'..'Z','_','a'..'q','s'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'R','r' ]; s: 608), { 452: } ( cc: [ '0'..'9','A'..'S','U'..'Z','_','a'..'s','u'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'T','t' ]; s: 609), { 453: } ( cc: [ '0'..'9','A'..'S','U'..'Z','_','a'..'s','u'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'T','t' ]; s: 610), { 454: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 455: } ( cc: [ '0'..'9','A'..'D','F'..'Z','_','a'..'d','f'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'E','e' ]; s: 611), { 456: } ( cc: [ '0'..'9','A'..'D','F'..'Z','_','a'..'d','f'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'E','e' ]; s: 612), { 457: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 458: } ( cc: [ '0'..'9','A'..'D','F'..'Z','_','a'..'d','f'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'E','e' ]; s: 613), { 459: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 460: } ( cc: [ '0'..'9','B'..'Z','_','b'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'A','a' ]; s: 614), { 461: } ( cc: [ '0'..'9','A'..'W','Y','Z','_','a'..'w','y','z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'X','x' ]; s: 615), { 462: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 463: } ( cc: [ '0'..'9','A'..'F','H'..'Q','S'..'Z','_','a'..'f', 'h'..'q','s'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'G','g' ]; s: 617), ( cc: [ 'R','r' ]; s: 616), { 464: } ( cc: [ '0'..'9','A'..'H','J'..'Z','_','a'..'h','j'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'I','i' ]; s: 618), { 465: } ( cc: [ '0'..'9','A'..'S','U'..'Z','_','a'..'s','u'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'T','t' ]; s: 619), { 466: } ( cc: [ '0'..'9','A'..'M','O'..'Q','S'..'Z','_','a'..'m', 'o'..'q','s'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'N','n' ]; s: 620), ( cc: [ 'R','r' ]; s: 621), { 467: } ( cc: [ '0'..'9','A'..'Q','S'..'Z','_','a'..'q','s'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'R','r' ]; s: 622), { 468: } ( cc: [ '0'..'9','A'..'C','E'..'Z','_','a'..'c','e'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'D','d' ]; s: 623), { 469: } ( cc: [ '0'..'9','B'..'Z','_','b'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'A','a' ]; s: 624), { 470: } ( cc: [ '0'..'9','A'..'L','N'..'Z','_','a'..'l','n'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'M','m' ]; s: 625), { 471: } ( cc: [ '0'..'9','A'..'N','P'..'Z','_','a'..'n','p'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'O','o' ]; s: 626), { 472: } ( cc: [ '0'..'9','A'..'T','V'..'Z','_','a'..'t','v'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'U','u' ]; s: 627), { 473: } ( cc: [ '0'..'9','A'..'M','O'..'Z','_','a'..'m','o'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'N','n' ]; s: 628), { 474: } ( cc: [ '0'..'9','A'..'K','M'..'Z','_','a'..'k','m'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'L','l' ]; s: 629), { 475: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 476: } ( cc: [ '0'..'9','A'..'D','F'..'Z','_','a'..'d','f'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'E','e' ]; s: 630), { 477: } ( cc: [ '0'..'9','A'..'F','H'..'Z','_','a'..'f','h'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'G','g' ]; s: 631), { 478: } ( cc: [ '0'..'9','A'..'S','U'..'Z','_','a'..'s','u'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'T','t' ]; s: 632), { 479: } ( cc: [ '0'..'9','A'..'Q','S'..'Z','_','a'..'q','s'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'R','r' ]; s: 633), { 480: } ( cc: [ '0'..'9','A'..'T','V'..'Z','_','a'..'t','v'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'U','u' ]; s: 634), { 481: } ( cc: [ '0'..'9','A'..'S','U'..'Z','_','a'..'s','u'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'T','t' ]; s: 635), { 482: } ( cc: [ '0'..'9','A'..'O','Q'..'Z','_','a'..'o','q'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'P','p' ]; s: 636), { 483: } ( cc: [ '0'..'9','A'..'O','Q'..'Z','_','a'..'o','q'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'P','p' ]; s: 637), { 484: } ( cc: [ '0'..'9','A'..'H','J'..'Z','_','a'..'h','j'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'I','i' ]; s: 638), { 485: } ( cc: [ '0'..'9','A'..'H','J'..'Z','_','a'..'h','j'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'I','i' ]; s: 639), { 486: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 487: } ( cc: [ '0'..'9','A'..'D','F'..'Z','_','a'..'d','f'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'E','e' ]; s: 640), { 488: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 489: } ( cc: [ '0'..'9','A'..'S','U'..'Z','_','a'..'s','u'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'T','t' ]; s: 641), { 490: } ( cc: [ '0'..'9','A'..'G','I'..'Z','_','a'..'g','i'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'H','h' ]; s: 642), { 491: } ( cc: [ '0'..'9','A'..'S','U'..'Z','_','a'..'s','u'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'T','t' ]; s: 643), { 492: } ( cc: [ '0'..'9','A'..'S','U'..'Z','_','a'..'s','u'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'T','t' ]; s: 644), { 493: } ( cc: [ '0'..'9','A'..'Z','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ '_' ]; s: 645), { 494: } ( cc: [ '0'..'9','A'..'Q','S'..'Z','_','a'..'q','s'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'R','r' ]; s: 646), { 495: } ( cc: [ '0'..'9','A'..'Q','S'..'Z','_','a'..'q','s'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'R','r' ]; s: 647), { 496: } ( cc: [ '0'..'9','A'..'H','J'..'Z','_','a'..'h','j'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'I','i' ]; s: 648), { 497: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 498: } ( cc: [ '0'..'9','A'..'T','V'..'Z','_','a'..'t','v'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'U','u' ]; s: 649), { 499: } ( cc: [ '0'..'9','A'..'D','F'..'Z','_','a'..'d','f'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'E','e' ]; s: 650), { 500: } ( cc: [ '0'..'9','A'..'M','O'..'Z','_','a'..'m','o'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'N','n' ]; s: 651), { 501: } ( cc: [ '0'..'9','A'..'M','O'..'Z','_','a'..'m','o'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'N','n' ]; s: 652), { 502: } ( cc: [ '0'..'9','A'..'Q','S'..'Z','_','a'..'q','s'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'R','r' ]; s: 653), { 503: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 504: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 505: } ( cc: [ '0'..'9','A'..'M','O'..'Z','_','a'..'m','o'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'N','n' ]; s: 654), { 506: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 507: } ( cc: [ '0'..'9','A'..'G','I'..'Z','_','a'..'g','i'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'H','h' ]; s: 655), { 508: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 509: } ( cc: [ '0'..'9','A'..'D','F'..'Z','_','a'..'d','f'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'E','e' ]; s: 656), { 510: } ( cc: [ '0'..'9','A'..'H','J'..'Z','_','a'..'h','j'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'I','i' ]; s: 657), { 511: } ( cc: [ '0'..'9','A'..'G','I'..'Z','_','a'..'g','i'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'H','h' ]; s: 658), { 512: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 513: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 514: } ( cc: [ #9,#10,#12,#13,'']; s: 514), ( cc: [ '''' ]; s: 659), { 515: } ( cc: [ '0'..'9','A'..'D','F'..'Z','_','a'..'d','f'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'E','e' ]; s: 660), { 516: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 517: } ( cc: [ '0'..'9','A'..'S','U'..'Z','_','a'..'s','u'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'T','t' ]; s: 661), { 518: } ( cc: [ '0'..'9','A','B','D'..'Z','_','a','b','d'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'C','c' ]; s: 662), { 519: } ( cc: [ '0'..'9','A'..'Q','S'..'Z','_','a'..'q','s'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'R','r' ]; s: 663), { 520: } ( cc: [ '0'..'9','A'..'S','U'..'Z','_','a'..'s','u'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'T','t' ]; s: 664), { 521: } ( cc: [ '0'..'9','A','B','D'..'Z','_','a','b','d'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'C','c' ]; s: 665), { 522: } ( cc: [ '0'..'9','A'..'M','O'..'Z','_','a'..'m','o'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'N','n' ]; s: 666), { 523: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 524: } ( cc: [ '0'..'9','A'..'R','T'..'Z','_','a'..'r','t'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'S','s' ]; s: 667), { 525: } ( cc: [ '0'..'9','A'..'R','T'..'Z','_','a'..'r','t'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'S','s' ]; s: 668), { 526: } ( cc: [ '0'..'9','A'..'M','O'..'Z','_','a'..'m','o'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'N','n' ]; s: 669), { 527: } ( cc: [ '0'..'9','A'..'Q','S'..'Z','_','a'..'q','s'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'R','r' ]; s: 670), { 528: } ( cc: [ '0'..'9','A'..'N','P'..'Z','_','a'..'n','p'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'O','o' ]; s: 671), { 529: } ( cc: [ '0'..'9','A'..'K','M'..'Z','_','a'..'k','m'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'L','l' ]; s: 672), { 530: } ( cc: [ '0'..'9','A'..'C','E'..'Z','_','a'..'c','e'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'D','d' ]; s: 673), { 531: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 532: } ( cc: [ '0'..'9','A','B','D'..'Z','_','a','b','d'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'C','c' ]; s: 674), { 533: } ( cc: [ '0'..'9','A'..'K','M'..'Z','_','a'..'k','m'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'L','l' ]; s: 675), { 534: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 535: } ( cc: [ '0'..'9','B'..'Z','_','b'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'A','a' ]; s: 676), { 536: } ( cc: [ '0'..'9','A'..'K','M'..'Z','_','a'..'k','m'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'L','l' ]; s: 677), { 537: } ( cc: [ '0'..'9','A'..'K','M'..'Z','_','a'..'k','m'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'L','l' ]; s: 678), { 538: } ( cc: [ '0'..'9','A'..'Q','S'..'Z','_','a'..'q','s'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'R','r' ]; s: 679), { 539: } ( cc: [ '0'..'9','A'..'N','P'..'Z','_','a'..'n','p'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'O','o' ]; s: 680), { 540: } ( cc: [ '0'..'9','A'..'M','O'..'Z','_','a'..'m','o'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'N','n' ]; s: 681), { 541: } ( cc: [ '0'..'9','A'..'S','U'..'Z','_','a'..'s','u'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'T','t' ]; s: 682), { 542: } ( cc: [ '0'..'9','A'..'S','U'..'Z','_','a'..'s','u'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'T','t' ]; s: 683), { 543: } ( cc: [ '0'..'9','A'..'L','N'..'Z','_','a'..'l','n'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'M','m' ]; s: 684), { 544: } ( cc: [ '0'..'9','A'..'Q','S'..'Z','_','a'..'q','s'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'R','r' ]; s: 685), { 545: } ( cc: [ '0'..'9','A'..'Q','S'..'Z','_','a'..'q','s'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'R','r' ]; s: 686), { 546: } ( cc: [ '0'..'9','A'..'H','J'..'Z','_','a'..'h','j'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'I','i' ]; s: 687), { 547: } ( cc: [ '0'..'9','A'..'Q','S'..'Z','_','a'..'q','s'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'R','r' ]; s: 688), { 548: } ( cc: [ '0'..'9','A'..'N','P'..'Z','_','a'..'n','p'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'O','o' ]; s: 689), { 549: } ( cc: [ '0'..'9','B'..'Z','_','b'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'A','a' ]; s: 690), { 550: } ( cc: [ '0'..'9','A'..'H','J'..'Z','_','a'..'h','j'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'I','i' ]; s: 691), { 551: } ( cc: [ '0'..'9','A'..'Q','S'..'Z','_','a'..'q','s'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'R','r' ]; s: 692), { 552: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 553: } ( cc: [ '0'..'9','A'..'H','J'..'Z','_','a'..'h','j'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'I','i' ]; s: 693), { 554: } ( cc: [ '0'..'9','A','B','D'..'Z','_','a','b','d'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'C','c' ]; s: 694), { 555: } ( cc: [ '0'..'9','A'..'M','O'..'Z','_','a'..'m','o'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'N','n' ]; s: 695), { 556: } ( cc: [ '0'..'9','A'..'T','V'..'Z','_','a'..'t','v'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'U','u' ]; s: 696), { 557: } ( cc: [ '0'..'9','A'..'K','M'..'Z','_','a'..'k','m'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'L','l' ]; s: 697), { 558: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 559: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 560: } ( cc: [ '0'..'9','A'..'F','H'..'Z','_','a'..'f','h'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'G','g' ]; s: 698), { 561: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 562: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 563: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 564: } ( cc: [ '0'..'9','A'..'M','O'..'Z','_','a'..'m','o'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'N','n' ]; s: 699), { 565: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 566: } ( cc: [ '0'..'9','A'..'S','U'..'Z','_','a'..'s','u'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'T','t' ]; s: 700), { 567: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 568: } ( cc: [ '0'..'9','A'..'Q','S'..'Z','_','a'..'q','s'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'R','r' ]; s: 701), { 569: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 570: } ( cc: [ '0'..'9','B'..'K','M'..'Z','_','b'..'k','m'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'A','a' ]; s: 702), ( cc: [ 'L','l' ]; s: 703), { 571: } ( cc: [ '0'..'9','A'..'H','J'..'Z','_','a'..'h','j'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'I','i' ]; s: 704), { 572: } ( cc: [ '0'..'9','A'..'S','U'..'Z','_','a'..'s','u'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'T','t' ]; s: 705), { 573: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 574: } ( cc: [ '0'..'9','B'..'Z','_','b'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'A','a' ]; s: 706), { 575: } ( cc: [ '0'..'9','A'..'M','O'..'Z','_','a'..'m','o'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'N','n' ]; s: 707), { 576: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 577: } ( cc: [ '0'..'9','A'..'S','U'..'Z','_','a'..'s','u'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'T','t' ]; s: 708), { 578: } ( cc: [ '0'..'9','A'..'Z','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ '_' ]; s: 709), { 579: } ( cc: [ '0'..'9','A'..'D','F'..'Z','_','a'..'d','f'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'E','e' ]; s: 710), { 580: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 581: } ( cc: [ '0'..'9','A'..'K','M'..'Z','_','a'..'k','m'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'L','l' ]; s: 711), { 582: } ( cc: [ '0'..'9','A'..'Q','S'..'Z','_','a'..'q','s'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'R','r' ]; s: 712), { 583: } ( cc: [ '0'..'9','A'..'Q','S'..'Z','_','a'..'q','s'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'R','r' ]; s: 713), { 584: } ( cc: [ '0'..'9','B'..'Z','_','b'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'A','a' ]; s: 714), { 585: } ( cc: [ '0'..'9','A'..'N','P'..'Z','_','a'..'n','p'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'O','o' ]; s: 715), { 586: } ( cc: [ '0'..'9','A'..'M','O'..'Z','_','a'..'m','o'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'N','n' ]; s: 716), { 587: } ( cc: [ '0'..'9','A'..'M','O'..'Z','_','a'..'m','o'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'N','n' ]; s: 717), { 588: } ( cc: [ '0'..'9','A'..'M','O'..'Z','_','a'..'m','o'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'N','n' ]; s: 718), { 589: } ( cc: [ '0'..'9','A'..'D','F'..'Z','_','a'..'d','f'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'E','e' ]; s: 719), { 590: } ( cc: [ '0'..'9','A'..'Q','S'..'Z','_','a'..'q','s'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'R','r' ]; s: 720), { 591: } ( cc: [ '0'..'9','A'..'R','T'..'Z','_','a'..'r','t'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'S','s' ]; s: 721), { 592: } ( cc: [ '0'..'9','A'..'K','M'..'Z','_','a'..'k','m'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'L','l' ]; s: 722), { 593: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 594: } ( cc: [ '0'..'9','A'..'Q','S'..'Z','_','a'..'q','s'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'R','r' ]; s: 723), { 595: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 596: } ( cc: [ '0'..'9','A'..'C','E'..'Z','_','a'..'c','e'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'D','d' ]; s: 724), { 597: } ( cc: [ '0'..'9','A'..'N','P'..'Z','_','a'..'n','p'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'O','o' ]; s: 725), { 598: } ( cc: [ '0'..'9','B'..'Z','_','b'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'A','a' ]; s: 726), { 599: } ( cc: [ '0'..'9','A','B','D'..'Z','_','a','b','d'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'C','c' ]; s: 727), { 600: } ( cc: [ '0'..'9','A'..'H','J'..'Z','_','a'..'h','j'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'I','i' ]; s: 728), { 601: } ( cc: [ '0'..'9','B'..'Z','_','b'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'A','a' ]; s: 729), { 602: } ( cc: [ '0'..'9','A'..'M','O'..'Z','_','a'..'m','o'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'N','n' ]; s: 730), { 603: } ( cc: [ '0'..'9','A'..'S','U'..'Z','_','a'..'s','u'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'T','t' ]; s: 731), { 604: } ( cc: [ '0'..'9','A'..'D','F'..'Z','_','a'..'d','f'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'E','e' ]; s: 732), { 605: } ( cc: [ '0'..'9','A'..'K','M'..'Z','_','a'..'k','m'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'L','l' ]; s: 733), { 606: } ( cc: [ '0'..'9','A'..'D','F'..'Z','_','a'..'d','f'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'E','e' ]; s: 734), { 607: } ( cc: [ '0'..'9','A'..'H','J'..'Z','_','a'..'h','j'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'I','i' ]; s: 735), { 608: } ( cc: [ '0'..'9','A'..'M','O'..'Z','_','a'..'m','o'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'N','n' ]; s: 736), { 609: } ( cc: [ '0'..'9','A'..'H','J'..'Z','_','a'..'h','j'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'I','i' ]; s: 737), { 610: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 611: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 612: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 613: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 614: } ( cc: [ '0'..'9','A'..'S','U'..'Z','_','a'..'s','u'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'T','t' ]; s: 738), { 615: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 616: } ( cc: [ '0'..'9','A'..'R','T','U','W'..'Z','_','a'..'r', 't','u','w'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'S','s' ]; s: 739), ( cc: [ 'V','v' ]; s: 740), { 617: } ( cc: [ '0'..'9','A'..'D','F'..'Z','_','a'..'d','f'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'E','e' ]; s: 741), { 618: } ( cc: [ '0'..'9','B'..'Z','_','b'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'A','a' ]; s: 742), { 619: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 620: } ( cc: [ '0'..'9','A'..'R','T'..'Z','_','a'..'r','t'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'S','s' ]; s: 743), { 621: } ( cc: [ '0'..'9','A'..'S','U'..'Z','_','a'..'s','u'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'T','t' ]; s: 744), { 622: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 623: } ( cc: [ '0'..'9','A'..'H','J'..'Z','_','a'..'h','j'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'I','i' ]; s: 745), { 624: } ( cc: [ '0'..'9','A'..'S','U'..'Z','_','a'..'s','u'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'T','t' ]; s: 746), { 625: } ( cc: [ '0'..'9','A'..'L','N'..'Z','_','a'..'l','n'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'M','m' ]; s: 747), { 626: } ( cc: [ '0'..'9','A'..'V','X'..'Z','_','a'..'v','x'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'W','w' ]; s: 748), { 627: } ( cc: [ '0'..'9','A'..'D','F'..'Z','_','a'..'d','f'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'E','e' ]; s: 749), { 628: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 629: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 630: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 631: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 632: } ( cc: [ '0'..'9','A'..'D','F'..'Z','_','a'..'d','f'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'E','e' ]; s: 750), { 633: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 634: } ( cc: [ '0'..'9','A'..'S','U'..'Z','_','a'..'s','u'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'T','t' ]; s: 751), { 635: } ( cc: [ '0'..'9','A'..'R','T'..'Z','_','a'..'r','t'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'S','s' ]; s: 752), { 636: } ( cc: [ '0'..'9','A'..'S','U'..'Z','_','a'..'s','u'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'T','t' ]; s: 753), { 637: } ( cc: [ '0'..'9','A'..'D','F'..'Z','_','a'..'d','f'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'E','e' ]; s: 754), { 638: } ( cc: [ '0'..'9','A'..'E','G'..'Z','_','a'..'e','g'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'F','f' ]; s: 755), { 639: } ( cc: [ '0'..'9','A'..'F','H'..'Z','_','a'..'f','h'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'G','g' ]; s: 756), { 640: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 641: } ( cc: [ '0'..'9','A'..'H','J'..'Z','_','a'..'h','j'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'I','i' ]; s: 757), { 642: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 643: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 644: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 645: } ( cc: [ '0'..'9','A'..'R','T'..'Z','_','a'..'r','t'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'S','s' ]; s: 758), { 646: } ( cc: [ '0'..'9','B'..'Z','_','b'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'A','a' ]; s: 759), { 647: } ( cc: [ '0'..'9','A'..'H','J'..'Z','_','a'..'h','j'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'I','i' ]; s: 760), { 648: } ( cc: [ '0'..'9','A'..'E','G'..'Z','_','a'..'e','g'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'F','f' ]; s: 761), { 649: } ( cc: [ '0'..'9','A'..'O','Q'..'Z','_','a'..'o','q'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'P','p' ]; s: 762), { 650: } ( cc: [ '0'..'9','A'..'D','F'..'Z','_','a'..'d','f'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'E','e' ]; s: 763), { 651: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 652: } ( cc: [ '0'..'9','A'..'S','U'..'Z','_','a'..'s','u'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'T','t' ]; s: 764), { 653: } ( cc: [ '0'..'9','A'..'X','Z','_','a'..'x','z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'Y','y' ]; s: 765), { 654: } ( cc: [ '0'..'9','A'..'F','H'..'Z','_','a'..'f','h'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'G','g' ]; s: 766), { 655: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 656: } ( cc: [ '0'..'9','A'..'R','T'..'Z','_','a'..'r','t'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'S','s' ]; s: 767), { 657: } ( cc: [ '0'..'9','A'..'M','O'..'Z','_','a'..'m','o'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'N','n' ]; s: 768), { 658: } ( cc: [ '0'..'9','B'..'Z','_','b'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'A','a' ]; s: 769), { 659: } ( cc: [ #1..#9,#11..'&','('..#255 ]; s: 659), ( cc: [ '''' ]; s: 770), { 660: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 661: } ( cc: [ '0'..'9','A'..'S','U'..'Z','_','a'..'s','u'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'T','t' ]; s: 771), { 662: } ( cc: [ '0'..'9','A'..'S','U'..'Z','_','a'..'s','u'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'T','t' ]; s: 772), { 663: } ( cc: [ '0'..'9','B'..'Z','_','b'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'A','a' ]; s: 773), { 664: } ( cc: [ '0'..'9','A'..'H','J'..'Z','_','a'..'h','j'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'I','i' ]; s: 774), { 665: } ( cc: [ '0'..'9','A'..'S','U'..'Z','_','a'..'s','u'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'T','t' ]; s: 775), { 666: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 667: } ( cc: [ '0'..'9','A'..'O','Q'..'Z','_','a'..'o','q'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'P','p' ]; s: 776), { 668: } ( cc: [ '0'..'9','A','B','D'..'Z','_','a','b','d'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'C','c' ]; s: 777), { 669: } ( cc: [ '0'..'9','A'..'S','U'..'Z','_','a'..'s','u'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'T','t' ]; s: 778), { 670: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 671: } ( cc: [ '0'..'9','A'..'F','H'..'Z','_','a'..'f','h'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'G','g' ]; s: 779), { 672: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 673: } ( cc: [ '0'..'9','A'..'D','F'..'Z','_','a'..'d','f'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'E','e' ]; s: 780), { 674: } ( cc: [ '0'..'9','A'..'S','U'..'Z','_','a'..'s','u'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'T','t' ]; s: 781), { 675: } ( cc: [ '0'..'9','A'..'D','F'..'Z','_','a'..'d','f'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'E','e' ]; s: 782), { 676: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 677: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 678: } ( cc: [ '0'..'9','A'..'H','J'..'Z','_','a'..'h','j'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'I','i' ]; s: 783), { 679: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 680: } ( cc: [ '0'..'9','A'..'M','O'..'Z','_','a'..'m','o'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'N','n' ]; s: 784), { 681: } ( cc: [ '0'..'9','A','B','D'..'Z','_','a','b','d'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'C','c' ]; s: 785), { 682: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 683: } ( cc: [ '0'..'9','A'..'H','J'..'Z','_','a'..'h','j'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'I','i' ]; s: 786), { 684: } ( cc: [ '0'..'9','A'..'Z','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ '_' ]; s: 787), { 685: } ( cc: [ '0'..'9','A'..'X','Z','_','a'..'x','z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'Y','y' ]; s: 788), { 686: } ( cc: [ '0'..'9','A'..'H','J'..'Z','_','a'..'h','j'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'I','i' ]; s: 789), { 687: } ( cc: [ '0'..'9','A'..'M','O'..'Z','_','a'..'m','o'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'N','n' ]; s: 790), { 688: } ( cc: [ '0'..'9','B'..'Z','_','b'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'A','a' ]; s: 791), { 689: } ( cc: [ '0'..'9','A'..'V','X'..'Z','_','a'..'v','x'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'W','w' ]; s: 792), { 690: } ( cc: [ '0'..'9','A'..'S','U'..'Z','_','a'..'s','u'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'T','t' ]; s: 793), { 691: } ( cc: [ '0'..'9','A'..'M','O'..'Z','_','a'..'m','o'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'N','n' ]; s: 794), { 692: } ( cc: [ '0'..'9','A'..'H','J'..'Z','_','a'..'h','j'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'I','i' ]; s: 795), { 693: } ( cc: [ '0'..'9','A'..'S','U'..'Z','_','a'..'s','u'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'T','t' ]; s: 796), { 694: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 695: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 696: } ( cc: [ '0'..'9','A'..'S','U'..'Z','_','a'..'s','u'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'T','t' ]; s: 797), { 697: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 698: } ( cc: [ '0'..'9','A'..'D','F'..'Z','_','a'..'d','f'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'E','e' ]; s: 798), { 699: } ( cc: [ '0'..'9','A'..'F','H'..'Z','_','a'..'f','h'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'G','g' ]; s: 799), { 700: } ( cc: [ '0'..'9','A'..'Z','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ '_' ]; s: 800), { 701: } ( cc: [ '0'..'9','B'..'Z','_','b'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'A','a' ]; s: 801), { 702: } ( cc: [ '0'..'9','A','B','D'..'Z','_','a','b','d'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'C','c' ]; s: 802), { 703: } ( cc: [ '0'..'9','B'..'Z','_','b'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'A','a' ]; s: 803), { 704: } ( cc: [ '0'..'9','A'..'M','O'..'Z','_','a'..'m','o'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'N','n' ]; s: 804), { 705: } ( cc: [ '0'..'9','B'..'Z','_','b'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'A','a' ]; s: 805), { 706: } ( cc: [ '0'..'9','A'..'O','Q'..'Z','_','a'..'o','q'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'P','p' ]; s: 806), { 707: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 708: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 709: } ( cc: [ '0'..'9','A'..'K','M'..'Z','_','a'..'k','m'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'L','l' ]; s: 807), { 710: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 711: } ( cc: [ '0'..'9','A'..'S','U'..'Z','_','a'..'s','u'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'T','t' ]; s: 808), { 712: } ( cc: [ '0'..'9','B'..'D','F'..'Z','_','b'..'d','f'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'A','a' ]; s: 810), ( cc: [ 'E','e' ]; s: 809), { 713: } ( cc: [ '0'..'9','A'..'D','F'..'Z','_','a'..'d','f'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'E','e' ]; s: 811), { 714: } ( cc: [ '0'..'9','A'..'K','M'..'Z','_','a'..'k','m'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'L','l' ]; s: 812), { 715: } ( cc: [ '0'..'9','A'..'R','T'..'Z','_','a'..'r','t'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'S','s' ]; s: 813), { 716: } ( cc: [ '0'..'9','A'..'M','O'..'Z','_','a'..'m','o'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'N','n' ]; s: 814), { 717: } ( cc: [ '0'..'9','A','B','D'..'Z','_','a','b','d'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'C','c' ]; s: 815), { 718: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 719: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 720: } ( cc: [ '0'..'9','A'..'U','W'..'Z','_','a'..'u','w'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'V','v' ]; s: 816), { 721: } ( cc: [ '0'..'9','A'..'H','J'..'Z','_','a'..'h','j'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'I','i' ]; s: 817), { 722: } ( cc: [ '0'..'9','A'..'D','F'..'Z','_','a'..'d','f'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'E','e' ]; s: 818), { 723: } ( cc: [ '0'..'9','A'..'X','Z','_','a'..'x','z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'Y','y' ]; s: 819), { 724: } ( cc: [ '0'..'9','A'..'T','V'..'Z','_','a'..'t','v'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'U','u' ]; s: 820), { 725: } ( cc: [ '0'..'9','A'..'Q','S'..'Z','_','a'..'q','s'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'R','r' ]; s: 821), { 726: } ( cc: [ '0'..'9','A'..'K','M'..'Z','_','a'..'k','m'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'L','l' ]; s: 822), { 727: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 728: } ( cc: [ '0'..'9','A'..'N','P'..'Z','_','a'..'n','p'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'O','o' ]; s: 823), { 729: } ( cc: [ '0'..'9','A','B','D'..'Z','_','a','b','d'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'C','c' ]; s: 824), { 730: } ( cc: [ '0'..'9','A'..'D','F'..'Z','_','a'..'d','f'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'E','e' ]; s: 825), { 731: } ( cc: [ '0'..'9','B'..'Z','_','b'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'A','a' ]; s: 826), { 732: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 733: } ( cc: [ '0'..'9','A'..'C','E'..'Z','_','a'..'c','e'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'D','d' ]; s: 827), { 734: } ( cc: [ '0'..'9','A'..'M','O'..'Z','_','a'..'m','o'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'N','n' ]; s: 828), { 735: } ( cc: [ '0'..'9','A','B','D'..'Z','_','a','b','d'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'C','c' ]; s: 829), { 736: } ( cc: [ '0'..'9','A'..'R','T'..'Z','_','a'..'r','t'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'S','s' ]; s: 830), { 737: } ( cc: [ '0'..'9','A'..'U','W'..'Z','_','a'..'u','w'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'V','v' ]; s: 831), { 738: } ( cc: [ '0'..'9','A'..'H','J'..'Z','_','a'..'h','j'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'I','i' ]; s: 832), { 739: } ( cc: [ '0'..'9','A'..'D','F'..'Z','_','a'..'d','f'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'E','e' ]; s: 833), { 740: } ( cc: [ '0'..'9','B'..'Z','_','b'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'A','a' ]; s: 834), { 741: } ( cc: [ '0'..'9','A'..'Q','S'..'Z','_','a'..'q','s'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'R','r' ]; s: 835), { 742: } ( cc: [ '0'..'9','A'..'K','M'..'Z','_','a'..'k','m'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'L','l' ]; s: 836), { 743: } ( cc: [ '0'..'9','A'..'H','J'..'Z','_','a'..'h','j'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'I','i' ]; s: 837), { 744: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 745: } ( cc: [ '0'..'9','B'..'Z','_','b'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'A','a' ]; s: 838), { 746: } ( cc: [ '0'..'9','A'..'D','F'..'Z','_','a'..'d','f'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'E','e' ]; s: 839), { 747: } ( cc: [ '0'..'9','A'..'H','J'..'Z','_','a'..'h','j'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'I','i' ]; s: 840), { 748: } ( cc: [ '0'..'9','A'..'M','O'..'Z','_','a'..'m','o'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'N','n' ]; s: 841), { 749: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 750: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 751: } ( cc: [ '0'..'9','A'..'D','F'..'Z','_','a'..'d','f'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'E','e' ]; s: 842), { 752: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 753: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 754: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 755: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 756: } ( cc: [ '0'..'9','A'..'M','O'..'Z','_','a'..'m','o'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'N','n' ]; s: 843), { 757: } ( cc: [ '0'..'9','A'..'N','P'..'Z','_','a'..'n','p'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'O','o' ]; s: 844), { 758: } ( cc: [ '0'..'9','A'..'D','F'..'Z','_','a'..'d','f'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'E','e' ]; s: 845), { 759: } ( cc: [ '0'..'9','A'..'K','M'..'Z','_','a'..'k','m'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'L','l' ]; s: 846), { 760: } ( cc: [ '0'..'9','A','B','D'..'Z','_','a','b','d'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'C','c' ]; s: 847), { 761: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 762: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 763: } ( cc: [ '0'..'9','A'..'M','O'..'Z','_','a'..'m','o'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'N','n' ]; s: 848), { 764: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 765: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 766: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 767: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 768: } ( cc: [ '0'..'9','A'..'F','H'..'Z','_','a'..'f','h'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'G','g' ]; s: 849), { 769: } ( cc: [ '0'..'9','A'..'Q','S'..'Z','_','a'..'q','s'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'R','r' ]; s: 850), { 770: } ( cc: [ #9,#10,#12,#13,'']; s: 514), ( cc: [ '''' ]; s: 659), { 771: } ( cc: [ '0'..'9','A'..'D','F'..'Z','_','a'..'d','f'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'E','e' ]; s: 851), { 772: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 773: } ( cc: [ '0'..'9','A'..'H','J'..'Z','_','a'..'h','j'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'I','i' ]; s: 852), { 774: } ( cc: [ '0'..'9','A'..'N','P'..'Z','_','a'..'n','p'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'O','o' ]; s: 853), { 775: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 776: } ( cc: [ '0'..'9','A'..'N','P'..'Z','_','a'..'n','p'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'O','o' ]; s: 854), { 777: } ( cc: [ '0'..'9','A'..'D','F'..'Z','_','a'..'d','f'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'E','e' ]; s: 855), { 778: } ( cc: [ '0'..'9','A'..'Z','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ '_' ]; s: 856), { 779: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 780: } ( cc: [ '0'..'9','A'..'C','E'..'Z','_','a'..'c','e'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'D','d' ]; s: 857), { 781: } ( cc: [ '0'..'9','A'..'D','F'..'Z','_','a'..'d','f'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'E','e' ]; s: 858), { 782: } ( cc: [ '0'..'9','A'..'M','O'..'Z','_','a'..'m','o'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'N','n' ]; s: 859), { 783: } ( cc: [ '0'..'9','A'..'Y','_','a'..'y' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'Z','z' ]; s: 860), { 784: } ( cc: [ '0'..'9','A'..'Z','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ '_' ]; s: 861), { 785: } ( cc: [ '0'..'9','A'..'D','F'..'Z','_','a'..'d','f'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'E','e' ]; s: 862), { 786: } ( cc: [ '0'..'9','A'..'U','W'..'Z','_','a'..'u','w'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'V','v' ]; s: 863), { 787: } ( cc: [ '0'..'9','A'..'T','V'..'Z','_','a'..'t','v'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'U','u' ]; s: 864), { 788: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 789: } ( cc: [ '0'..'9','A'..'M','O'..'Z','_','a'..'m','o'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'N','n' ]; s: 865), { 790: } ( cc: [ '0'..'9','A'..'F','H'..'Z','_','a'..'f','h'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'G','g' ]; s: 866), { 791: } ( cc: [ '0'..'9','A'..'M','O'..'Z','_','a'..'m','o'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'N','n' ]; s: 867), { 792: } ( cc: [ '0'..'9','A'..'M','O'..'Z','_','a'..'m','o'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'N','n' ]; s: 868), { 793: } ( cc: [ '0'..'9','A'..'D','F'..'Z','_','a'..'d','f'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'E','e' ]; s: 869), { 794: } ( cc: [ '0'..'9','A'..'S','U'..'Z','_','a'..'s','u'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'T','t' ]; s: 870), { 795: } ( cc: [ '0'..'9','A'..'Y','_','a'..'y' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'Z','z' ]; s: 871), { 796: } ( cc: [ '0'..'9','A'..'H','J'..'Z','_','a'..'h','j'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'I','i' ]; s: 872), { 797: } ( cc: [ '0'..'9','A'..'D','F'..'Z','_','a'..'d','f'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'E','e' ]; s: 873), { 798: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 799: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 800: } ( cc: [ '0'..'9','A'..'R','T'..'Z','_','a'..'r','t'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'S','s' ]; s: 874), { 801: } ( cc: [ '0'..'9','A'..'Q','S'..'Z','_','a'..'q','s'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'R','r' ]; s: 875), { 802: } ( cc: [ '0'..'9','A'..'S','U'..'Z','_','a'..'s','u'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'T','t' ]; s: 876), { 803: } ( cc: [ '0'..'9','A'..'S','U'..'Z','_','a'..'s','u'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'T','t' ]; s: 877), { 804: } ( cc: [ '0'..'9','A'..'F','H'..'Z','_','a'..'f','h'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'G','g' ]; s: 878), { 805: } ( cc: [ '0'..'9','A'..'L','N'..'Z','_','a'..'l','n'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'M','m' ]; s: 879), { 806: } ( cc: [ '0'..'9','A'..'R','T'..'Z','_','a'..'r','t'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'S','s' ]; s: 880), { 807: } ( cc: [ '0'..'9','A'..'D','F'..'Z','_','a'..'d','f'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'E','e' ]; s: 881), { 808: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 809: } ( cc: [ '0'..'9','A'..'C','E'..'Z','_','a'..'c','e'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'D','d' ]; s: 882), { 810: } ( cc: [ '0'..'9','A','C'..'Z','_','a','c'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'B','b' ]; s: 883), { 811: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 812: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 813: } ( cc: [ '0'..'9','A'..'S','U'..'Z','_','a'..'s','u'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'T','t' ]; s: 884), { 814: } ( cc: [ '0'..'9','A'..'D','F'..'Z','_','a'..'d','f'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'E','e' ]; s: 885), { 815: } ( cc: [ '0'..'9','A'..'S','U'..'Z','_','a'..'s','u'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'T','t' ]; s: 886), { 816: } ( cc: [ '0'..'9','A'..'D','F'..'Z','_','a'..'d','f'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'E','e' ]; s: 887), { 817: } ( cc: [ '0'..'9','A'..'N','P'..'Z','_','a'..'n','p'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'O','o' ]; s: 888), { 818: } ( cc: [ '0'..'9','A'..'F','H'..'Z','_','a'..'f','h'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'G','g' ]; s: 889), { 819: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 820: } ( cc: [ '0'..'9','A'..'Q','S'..'Z','_','a'..'q','s'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'R','r' ]; s: 890), { 821: } ( cc: [ '0'..'9','A'..'C','E'..'Z','_','a'..'c','e'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'D','d' ]; s: 891), { 822: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 823: } ( cc: [ '0'..'9','A'..'M','O'..'Z','_','a'..'m','o'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'N','n' ]; s: 892), { 824: } ( cc: [ '0'..'9','A'..'J','L'..'Z','_','a'..'j','l'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'K','k' ]; s: 893), { 825: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 826: } ( cc: [ '0'..'9','A','C'..'Z','_','a','c'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'B','b' ]; s: 894), { 827: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 828: } ( cc: [ '0'..'9','A','B','D'..'Z','_','a','b','d'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'C','c' ]; s: 895), { 829: } ( cc: [ '0'..'9','A'..'S','U'..'Z','_','a'..'s','u'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'T','t' ]; s: 896), { 830: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 831: } ( cc: [ '0'..'9','A'..'D','F'..'Z','_','a'..'d','f'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'E','e' ]; s: 897), { 832: } ( cc: [ '0'..'9','A'..'N','P'..'Z','_','a'..'n','p'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'O','o' ]; s: 898), { 833: } ( cc: [ '0'..'9','A','B','D'..'Z','_','a','b','d'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'C','c' ]; s: 899), { 834: } ( cc: [ '0'..'9','A'..'K','M'..'Z','_','a'..'k','m'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'L','l' ]; s: 900), { 835: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 836: } ( cc: [ '0'..'9','A'..'K','M'..'Z','_','a'..'k','m'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'L','l' ]; s: 901), { 837: } ( cc: [ '0'..'9','A'..'S','U'..'Z','_','a'..'s','u'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'T','t' ]; s: 902), { 838: } ( cc: [ '0'..'9','A'..'S','U'..'Z','_','a'..'s','u'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'T','t' ]; s: 903), { 839: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 840: } ( cc: [ '0'..'9','A'..'S','U'..'Z','_','a'..'s','u'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'T','t' ]; s: 904), { 841: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 842: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 843: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 844: } ( cc: [ '0'..'9','A'..'M','O'..'Z','_','a'..'m','o'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'N','n' ]; s: 905), { 845: } ( cc: [ '0'..'9','A'..'P','R'..'Z','_','a'..'p','r'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'Q','q' ]; s: 906), { 846: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 847: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 848: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 849: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 850: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 851: } ( cc: [ '0'..'9','A'..'C','E'..'Z','_','a'..'c','e'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'D','d' ]; s: 907), { 852: } ( cc: [ '0'..'9','A'..'M','O'..'Z','_','a'..'m','o'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'N','n' ]; s: 908), { 853: } ( cc: [ '0'..'9','A'..'M','O'..'Z','_','a'..'m','o'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'N','n' ]; s: 909), { 854: } ( cc: [ '0'..'9','A'..'M','O'..'Z','_','a'..'m','o'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'N','n' ]; s: 910), { 855: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 856: } ( cc: [ '0'..'9','B','E'..'R','V'..'Z','_','b','e'..'r', 'v'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'A','a' ]; s: 914), ( cc: [ 'C','c' ]; s: 915), ( cc: [ 'D','d' ]; s: 912), ( cc: [ 'S','s' ]; s: 916), ( cc: [ 'T','t' ]; s: 913), ( cc: [ 'U','u' ]; s: 911), { 857: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 858: } ( cc: [ '0'..'9','A'..'Q','S'..'Z','_','a'..'q','s'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'R','r' ]; s: 917), { 859: } ( cc: [ '0'..'9','A'..'F','H'..'Z','_','a'..'f','h'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'G','g' ]; s: 918), { 860: } ( cc: [ '0'..'9','B'..'Z','_','b'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'A','a' ]; s: 919), { 861: } ( cc: [ '0'..'9','A'..'T','V'..'Z','_','a'..'t','v'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'U','u' ]; s: 920), { 862: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 863: } ( cc: [ '0'..'9','A'..'D','F'..'Z','_','a'..'d','f'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'E','e' ]; s: 921), { 864: } ( cc: [ '0'..'9','A'..'R','T'..'Z','_','a'..'r','t'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'S','s' ]; s: 922), { 865: } ( cc: [ '0'..'9','A'..'F','H'..'Z','_','a'..'f','h'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'G','g' ]; s: 923), { 866: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 867: } ( cc: [ '0'..'9','A'..'R','T'..'Z','_','a'..'r','t'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'S','s' ]; s: 924), { 868: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 869: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 870: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 871: } ( cc: [ '0'..'9','B'..'Z','_','b'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'A','a' ]; s: 925), { 872: } ( cc: [ '0'..'9','A'..'U','W'..'Z','_','a'..'u','w'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'V','v' ]; s: 926), { 873: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 874: } ( cc: [ '0'..'9','A'..'D','F'..'Z','_','a'..'d','f'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'E','e' ]; s: 927), { 875: } ( cc: [ '0'..'9','A'..'X','Z','_','a'..'x','z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'Y','y' ]; s: 928), { 876: } ( cc: [ '0'..'9','A'..'H','J'..'Z','_','a'..'h','j'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'I','i' ]; s: 929), { 877: } ( cc: [ '0'..'9','A'..'H','J'..'Z','_','a'..'h','j'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'I','i' ]; s: 930), { 878: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 879: } ( cc: [ '0'..'9','A'..'O','Q'..'Z','_','a'..'o','q'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'P','p' ]; s: 931), { 880: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 881: } ( cc: [ '0'..'9','A'..'M','O'..'Z','_','a'..'m','o'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'N','n' ]; s: 932), { 882: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 883: } ( cc: [ '0'..'9','A'..'K','M'..'Z','_','a'..'k','m'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'L','l' ]; s: 933), { 884: } ( cc: [ '0'..'9','A'..'H','J'..'Z','_','a'..'h','j'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'I','i' ]; s: 934), { 885: } ( cc: [ '0'..'9','A','B','D'..'Z','_','a','b','d'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'C','c' ]; s: 935), { 886: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 887: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 888: } ( cc: [ '0'..'9','A'..'M','O'..'Z','_','a'..'m','o'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'N','n' ]; s: 936), { 889: } ( cc: [ '0'..'9','A'..'D','F'..'Z','_','a'..'d','f'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'E','e' ]; s: 937), { 890: } ( cc: [ '0'..'9','A'..'D','F'..'Z','_','a'..'d','f'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'E','e' ]; s: 938), { 891: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 892: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 893: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 894: } ( cc: [ '0'..'9','A'..'K','M'..'Z','_','a'..'k','m'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'L','l' ]; s: 939), { 895: } ( cc: [ '0'..'9','A'..'D','F'..'Z','_','a'..'d','f'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'E','e' ]; s: 940), { 896: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 897: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 898: } ( cc: [ '0'..'9','A'..'M','O'..'Z','_','a'..'m','o'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'N','n' ]; s: 941), { 899: } ( cc: [ '0'..'9','A'..'S','U'..'Z','_','a'..'s','u'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'T','t' ]; s: 942), { 900: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 901: } ( cc: [ '0'..'9','A'..'X','Z','_','a'..'x','z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'Y','y' ]; s: 943), { 902: } ( cc: [ '0'..'9','A'..'H','J'..'Z','_','a'..'h','j'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'I','i' ]; s: 944), { 903: } ( cc: [ '0'..'9','A'..'D','F'..'Z','_','a'..'d','f'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'E','e' ]; s: 945), { 904: } ( cc: [ '0'..'9','A'..'S','U'..'Z','_','a'..'s','u'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'T','t' ]; s: 946), { 905: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 906: } ( cc: [ '0'..'9','A'..'T','V'..'Z','_','a'..'t','v'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'U','u' ]; s: 947), { 907: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 908: } ( cc: [ '0'..'9','A'..'S','U'..'Z','_','a'..'s','u'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'T','t' ]; s: 948), { 909: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 910: } ( cc: [ '0'..'9','A'..'C','E'..'Z','_','a'..'c','e'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'D','d' ]; s: 949), { 911: } ( cc: [ '0'..'9','A'..'R','T'..'Z','_','a'..'r','t'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'S','s' ]; s: 950), { 912: } ( cc: [ '0'..'9','B'..'Z','_','b'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'A','a' ]; s: 951), { 913: } ( cc: [ '0'..'9','A'..'H','J'..'Z','_','a'..'h','j'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'I','i' ]; s: 952), { 914: } ( cc: [ '0'..'9','A'..'T','V'..'Z','_','a'..'t','v'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'U','u' ]; s: 953), { 915: } ( cc: [ '0'..'9','B'..'Z','_','b'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'A','a' ]; s: 954), { 916: } ( cc: [ '0'..'9','A','B','D'..'Z','_','a','b','d'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'C','c' ]; s: 955), { 917: } ( cc: [ '0'..'9','A'..'Z','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ '_' ]; s: 956), { 918: } ( cc: [ '0'..'9','A'..'S','U'..'Z','_','a'..'s','u'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'T','t' ]; s: 957), { 919: } ( cc: [ '0'..'9','A','C'..'Z','_','a','c'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'B','b' ]; s: 958), { 920: } ( cc: [ '0'..'9','A'..'R','T'..'Z','_','a'..'r','t'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'S','s' ]; s: 959), { 921: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 922: } ( cc: [ '0'..'9','A'..'D','F'..'Z','_','a'..'d','f'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'E','e' ]; s: 960), { 923: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 924: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 925: } ( cc: [ '0'..'9','A'..'S','U'..'Z','_','a'..'s','u'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'T','t' ]; s: 961), { 926: } ( cc: [ '0'..'9','A'..'D','F'..'Z','_','a'..'d','f'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'E','e' ]; s: 962), { 927: } ( cc: [ '0'..'9','A'..'P','R'..'Z','_','a'..'p','r'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'Q','q' ]; s: 963), { 928: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 929: } ( cc: [ '0'..'9','A'..'N','P'..'Z','_','a'..'n','p'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'O','o' ]; s: 964), { 930: } ( cc: [ '0'..'9','A'..'N','P'..'Z','_','a'..'n','p'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'O','o' ]; s: 965), { 931: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 932: } ( cc: [ '0'..'9','A'..'F','H'..'Z','_','a'..'f','h'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'G','g' ]; s: 966), { 933: } ( cc: [ '0'..'9','A'..'D','F'..'Z','_','a'..'d','f'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'E','e' ]; s: 967), { 934: } ( cc: [ '0'..'9','A','B','D'..'Z','_','a','b','d'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'C','c' ]; s: 968), { 935: } ( cc: [ '0'..'9','A'..'S','U'..'Z','_','a'..'s','u'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'T','t' ]; s: 969), { 936: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 937: } ( cc: [ '0'..'9','A'..'R','T'..'Z','_','a'..'r','t'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'S','s' ]; s: 970), { 938: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 939: } ( cc: [ '0'..'9','A'..'D','F'..'Z','_','a'..'d','f'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'E','e' ]; s: 971), { 940: } ( cc: [ '0'..'9','A'..'R','T'..'Z','_','a'..'r','t'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'S','s' ]; s: 972), { 941: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 942: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 943: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 944: } ( cc: [ '0'..'9','A'..'U','W'..'Z','_','a'..'u','w'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'V','v' ]; s: 973), { 945: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 946: } ( cc: [ '0'..'9','A'..'D','F'..'Z','_','a'..'d','f'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'E','e' ]; s: 974), { 947: } ( cc: [ '0'..'9','A'..'D','F'..'Z','_','a'..'d','f'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'E','e' ]; s: 975), { 948: } ( cc: [ '0'..'9','A'..'R','T'..'Z','_','a'..'r','t'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'S','s' ]; s: 976), { 949: } ( cc: [ '0'..'9','A'..'H','J'..'Z','_','a'..'h','j'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'I','i' ]; s: 977), { 950: } ( cc: [ '0'..'9','A'..'D','F'..'Z','_','a'..'d','f'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'E','e' ]; s: 978), { 951: } ( cc: [ '0'..'9','A'..'S','U'..'Z','_','a'..'s','u'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'T','t' ]; s: 979), { 952: } ( cc: [ '0'..'9','A'..'L','N'..'Z','_','a'..'l','n'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'M','m' ]; s: 980), { 953: } ( cc: [ '0'..'9','A'..'S','U'..'Z','_','a'..'s','u'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'T','t' ]; s: 981), { 954: } ( cc: [ '0'..'9','A'..'S','U'..'Z','_','a'..'s','u'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'T','t' ]; s: 982), { 955: } ( cc: [ '0'..'9','A'..'G','I'..'Z','_','a'..'g','i'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'H','h' ]; s: 983), { 956: } ( cc: [ '0'..'9','A'..'K','M'..'Z','_','a'..'k','m'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'L','l' ]; s: 984), { 957: } ( cc: [ '0'..'9','A'..'G','I'..'Z','_','a'..'g','i'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'H','h' ]; s: 985), { 958: } ( cc: [ '0'..'9','A'..'K','M'..'Z','_','a'..'k','m'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'L','l' ]; s: 986), { 959: } ( cc: [ '0'..'9','A'..'D','F'..'Z','_','a'..'d','f'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'E','e' ]; s: 987), { 960: } ( cc: [ '0'..'9','A'..'Q','S'..'Z','_','a'..'q','s'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'R','r' ]; s: 988), { 961: } ( cc: [ '0'..'9','A'..'H','J'..'Z','_','a'..'h','j'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'I','i' ]; s: 989), { 962: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 963: } ( cc: [ '0'..'9','A'..'T','V'..'Z','_','a'..'t','v'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'U','u' ]; s: 990), { 964: } ( cc: [ '0'..'9','A'..'M','O'..'Z','_','a'..'m','o'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'N','n' ]; s: 991), { 965: } ( cc: [ '0'..'9','A'..'M','O'..'Z','_','a'..'m','o'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'N','n' ]; s: 992), { 966: } ( cc: [ '0'..'9','A'..'S','U'..'Z','_','a'..'s','u'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'T','t' ]; s: 993), { 967: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 968: } ( cc: [ '0'..'9','A'..'R','T'..'Z','_','a'..'r','t'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'S','s' ]; s: 994), { 969: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 970: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 971: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 972: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 973: } ( cc: [ '0'..'9','A'..'D','F'..'Z','_','a'..'d','f'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'E','e' ]; s: 995), { 974: } ( cc: [ '0'..'9','A'..'C','E'..'Z','_','a'..'c','e'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'D','d' ]; s: 996), { 975: } ( cc: [ '0'..'9','A'..'M','O'..'Z','_','a'..'m','o'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'N','n' ]; s: 997), { 976: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 977: } ( cc: [ '0'..'9','A'..'M','O'..'Z','_','a'..'m','o'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'N','n' ]; s: 998), { 978: } ( cc: [ '0'..'9','A'..'Q','S'..'Z','_','a'..'q','s'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'R','r' ]; s: 999), { 979: } ( cc: [ '0'..'9','A'..'D','F'..'Z','_','a'..'d','f'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'E','e' ]; s: 1000), { 980: } ( cc: [ '0'..'9','A'..'D','F'..'Z','_','a'..'d','f'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'E','e' ]; s: 1001), { 981: } ( cc: [ '0'..'9','A'..'G','I'..'Z','_','a'..'g','i'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'H','h' ]; s: 1002), { 982: } ( cc: [ '0'..'9','B'..'Z','_','b'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'A','a' ]; s: 1003), { 983: } ( cc: [ '0'..'9','A'..'D','F'..'Z','_','a'..'d','f'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'E','e' ]; s: 1004), { 984: } ( cc: [ '0'..'9','A'..'D','F'..'Z','_','a'..'d','f'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'E','e' ]; s: 1005), { 985: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 986: } ( cc: [ '0'..'9','A'..'D','F'..'Z','_','a'..'d','f'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'E','e' ]; s: 1006), { 987: } ( cc: [ '0'..'9','A'..'Q','S'..'Z','_','a'..'q','s'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'R','r' ]; s: 1007), { 988: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 989: } ( cc: [ '0'..'9','A'..'N','P'..'Z','_','a'..'n','p'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'O','o' ]; s: 1008), { 990: } ( cc: [ '0'..'9','A'..'D','F'..'Z','_','a'..'d','f'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'E','e' ]; s: 1009), { 991: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 992: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 993: } ( cc: [ '0'..'9','A'..'G','I'..'Z','_','a'..'g','i'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'H','h' ]; s: 1010), { 994: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 995: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 996: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 997: } ( cc: [ '0'..'9','A','B','D'..'Z','_','a','b','d'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'C','c' ]; s: 1011), { 998: } ( cc: [ '0'..'9','A'..'F','H'..'Z','_','a'..'f','h'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'G','g' ]; s: 1012), { 999: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 1000: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 1001: } ( cc: [ '0'..'9','A'..'R','T'..'Z','_','a'..'r','t'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'S','s' ]; s: 1013), { 1002: } ( cc: [ '0'..'9','A'..'H','J'..'Z','_','a'..'h','j'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'I','i' ]; s: 1014), { 1003: } ( cc: [ '0'..'9','A'..'K','M'..'Z','_','a'..'k','m'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'L','l' ]; s: 1015), { 1004: } ( cc: [ '0'..'9','A'..'L','N'..'Z','_','a'..'l','n'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'M','m' ]; s: 1016), { 1005: } ( cc: [ '0'..'9','A'..'M','O'..'Z','_','a'..'m','o'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'N','n' ]; s: 1017), { 1006: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 1007: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 1008: } ( cc: [ '0'..'9','A'..'M','O'..'Z','_','a'..'m','o'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'N','n' ]; s: 1018), { 1009: } ( cc: [ '0'..'9','A'..'M','O'..'Z','_','a'..'m','o'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'N','n' ]; s: 1019), { 1010: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 1011: } ( cc: [ '0'..'9','A'..'D','F'..'Z','_','a'..'d','f'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'E','e' ]; s: 1020), { 1012: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 1013: } ( cc: [ '0'..'9','A'..'S','U'..'Z','_','a'..'s','u'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'T','t' ]; s: 1021), { 1014: } ( cc: [ '0'..'9','A'..'C','E'..'Z','_','a'..'c','e'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'D','d' ]; s: 1022), { 1015: } ( cc: [ '0'..'9','A'..'N','P'..'Z','_','a'..'n','p'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'O','o' ]; s: 1023), { 1016: } ( cc: [ '0'..'9','B'..'Z','_','b'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'A','a' ]; s: 1024), { 1017: } ( cc: [ '0'..'9','A'..'F','H'..'Z','_','a'..'f','h'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'G','g' ]; s: 1025), { 1018: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 1019: } ( cc: [ '0'..'9','A','B','D'..'Z','_','a','b','d'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'C','c' ]; s: 1026), { 1020: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 1021: } ( cc: [ '0'..'9','B'..'Z','_','b'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'A','a' ]; s: 1027), { 1022: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 1023: } ( cc: [ '0'..'9','A'..'F','H'..'Z','_','a'..'f','h'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'G','g' ]; s: 1028), { 1024: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 1025: } ( cc: [ '0'..'9','A'..'S','U'..'Z','_','a'..'s','u'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'T','t' ]; s: 1029), { 1026: } ( cc: [ '0'..'9','A'..'D','F'..'Z','_','a'..'d','f'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'E','e' ]; s: 1030), { 1027: } ( cc: [ '0'..'9','A'..'L','N'..'Z','_','a'..'l','n'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'M','m' ]; s: 1031), { 1028: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 1029: } ( cc: [ '0'..'9','A'..'G','I'..'Z','_','a'..'g','i'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'H','h' ]; s: 1032), { 1030: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 1031: } ( cc: [ '0'..'9','A'..'O','Q'..'Z','_','a'..'o','q'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), ( cc: [ 'P','p' ]; s: 1033), { 1032: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52), { 1033: } ( cc: [ '0'..'9','A'..'Z','_','a'..'z' ]; s: 43), ( cc: [ ':' ]; s: 52) ); yykl : array [0..yynstates-1] of Integer = ( { 0: } 1, { 1: } 1, { 2: } 1, { 3: } 2, { 4: } 3, { 5: } 4, { 6: } 5, { 7: } 6, { 8: } 7, { 9: } 8, { 10: } 9, { 11: } 10, { 12: } 11, { 13: } 12, { 14: } 13, { 15: } 14, { 16: } 15, { 17: } 16, { 18: } 17, { 19: } 18, { 20: } 19, { 21: } 20, { 22: } 21, { 23: } 22, { 24: } 23, { 25: } 24, { 26: } 25, { 27: } 26, { 28: } 27, { 29: } 28, { 30: } 29, { 31: } 30, { 32: } 31, { 33: } 32, { 34: } 33, { 35: } 34, { 36: } 35, { 37: } 36, { 38: } 37, { 39: } 38, { 40: } 40, { 41: } 42, { 42: } 43, { 43: } 44, { 44: } 45, { 45: } 45, { 46: } 46, { 47: } 47, { 48: } 48, { 49: } 49, { 50: } 50, { 51: } 51, { 52: } 52, { 53: } 53, { 54: } 54, { 55: } 55, { 56: } 56, { 57: } 57, { 58: } 58, { 59: } 59, { 60: } 60, { 61: } 61, { 62: } 62, { 63: } 63, { 64: } 64, { 65: } 65, { 66: } 66, { 67: } 68, { 68: } 69, { 69: } 71, { 70: } 72, { 71: } 73, { 72: } 74, { 73: } 75, { 74: } 76, { 75: } 77, { 76: } 78, { 77: } 79, { 78: } 80, { 79: } 81, { 80: } 82, { 81: } 83, { 82: } 84, { 83: } 86, { 84: } 87, { 85: } 88, { 86: } 90, { 87: } 92, { 88: } 93, { 89: } 94, { 90: } 95, { 91: } 97, { 92: } 98, { 93: } 99, { 94: } 100, { 95: } 101, { 96: } 102, { 97: } 104, { 98: } 105, { 99: } 106, { 100: } 107, { 101: } 108, { 102: } 109, { 103: } 110, { 104: } 111, { 105: } 112, { 106: } 113, { 107: } 114, { 108: } 115, { 109: } 116, { 110: } 117, { 111: } 119, { 112: } 121, { 113: } 122, { 114: } 124, { 115: } 125, { 116: } 126, { 117: } 127, { 118: } 128, { 119: } 129, { 120: } 130, { 121: } 131, { 122: } 132, { 123: } 133, { 124: } 134, { 125: } 135, { 126: } 136, { 127: } 137, { 128: } 138, { 129: } 139, { 130: } 140, { 131: } 142, { 132: } 143, { 133: } 144, { 134: } 145, { 135: } 146, { 136: } 147, { 137: } 149, { 138: } 150, { 139: } 151, { 140: } 152, { 141: } 153, { 142: } 154, { 143: } 155, { 144: } 156, { 145: } 157, { 146: } 158, { 147: } 159, { 148: } 160, { 149: } 161, { 150: } 162, { 151: } 163, { 152: } 164, { 153: } 165, { 154: } 166, { 155: } 167, { 156: } 168, { 157: } 169, { 158: } 169, { 159: } 169, { 160: } 170, { 161: } 170, { 162: } 170, { 163: } 170, { 164: } 171, { 165: } 172, { 166: } 173, { 167: } 174, { 168: } 175, { 169: } 176, { 170: } 177, { 171: } 178, { 172: } 179, { 173: } 180, { 174: } 181, { 175: } 182, { 176: } 183, { 177: } 184, { 178: } 185, { 179: } 186, { 180: } 187, { 181: } 188, { 182: } 189, { 183: } 190, { 184: } 191, { 185: } 192, { 186: } 193, { 187: } 195, { 188: } 196, { 189: } 197, { 190: } 199, { 191: } 200, { 192: } 201, { 193: } 202, { 194: } 203, { 195: } 204, { 196: } 205, { 197: } 206, { 198: } 207, { 199: } 208, { 200: } 210, { 201: } 212, { 202: } 214, { 203: } 215, { 204: } 217, { 205: } 218, { 206: } 220, { 207: } 222, { 208: } 223, { 209: } 224, { 210: } 225, { 211: } 226, { 212: } 227, { 213: } 228, { 214: } 229, { 215: } 230, { 216: } 231, { 217: } 232, { 218: } 233, { 219: } 234, { 220: } 235, { 221: } 236, { 222: } 237, { 223: } 238, { 224: } 239, { 225: } 240, { 226: } 241, { 227: } 242, { 228: } 243, { 229: } 244, { 230: } 245, { 231: } 246, { 232: } 247, { 233: } 248, { 234: } 249, { 235: } 250, { 236: } 252, { 237: } 253, { 238: } 254, { 239: } 255, { 240: } 256, { 241: } 257, { 242: } 258, { 243: } 260, { 244: } 261, { 245: } 262, { 246: } 263, { 247: } 264, { 248: } 265, { 249: } 266, { 250: } 267, { 251: } 268, { 252: } 269, { 253: } 270, { 254: } 271, { 255: } 272, { 256: } 273, { 257: } 274, { 258: } 275, { 259: } 276, { 260: } 277, { 261: } 278, { 262: } 279, { 263: } 280, { 264: } 281, { 265: } 282, { 266: } 283, { 267: } 284, { 268: } 285, { 269: } 286, { 270: } 287, { 271: } 288, { 272: } 289, { 273: } 290, { 274: } 291, { 275: } 292, { 276: } 293, { 277: } 294, { 278: } 296, { 279: } 297, { 280: } 298, { 281: } 299, { 282: } 300, { 283: } 301, { 284: } 302, { 285: } 303, { 286: } 304, { 287: } 305, { 288: } 306, { 289: } 307, { 290: } 308, { 291: } 309, { 292: } 310, { 293: } 311, { 294: } 312, { 295: } 313, { 296: } 314, { 297: } 315, { 298: } 316, { 299: } 318, { 300: } 320, { 301: } 321, { 302: } 322, { 303: } 323, { 304: } 324, { 305: } 325, { 306: } 326, { 307: } 327, { 308: } 328, { 309: } 330, { 310: } 331, { 311: } 332, { 312: } 333, { 313: } 334, { 314: } 336, { 315: } 337, { 316: } 338, { 317: } 339, { 318: } 340, { 319: } 342, { 320: } 343, { 321: } 344, { 322: } 345, { 323: } 346, { 324: } 347, { 325: } 349, { 326: } 350, { 327: } 352, { 328: } 353, { 329: } 354, { 330: } 355, { 331: } 356, { 332: } 357, { 333: } 358, { 334: } 358, { 335: } 359, { 336: } 360, { 337: } 361, { 338: } 362, { 339: } 363, { 340: } 364, { 341: } 365, { 342: } 366, { 343: } 367, { 344: } 368, { 345: } 369, { 346: } 370, { 347: } 371, { 348: } 372, { 349: } 373, { 350: } 374, { 351: } 375, { 352: } 376, { 353: } 378, { 354: } 380, { 355: } 382, { 356: } 383, { 357: } 385, { 358: } 386, { 359: } 388, { 360: } 389, { 361: } 390, { 362: } 392, { 363: } 393, { 364: } 394, { 365: } 395, { 366: } 396, { 367: } 397, { 368: } 398, { 369: } 399, { 370: } 400, { 371: } 401, { 372: } 402, { 373: } 403, { 374: } 404, { 375: } 406, { 376: } 407, { 377: } 408, { 378: } 409, { 379: } 410, { 380: } 411, { 381: } 412, { 382: } 413, { 383: } 414, { 384: } 415, { 385: } 416, { 386: } 417, { 387: } 418, { 388: } 419, { 389: } 420, { 390: } 422, { 391: } 423, { 392: } 425, { 393: } 426, { 394: } 427, { 395: } 428, { 396: } 430, { 397: } 431, { 398: } 433, { 399: } 434, { 400: } 435, { 401: } 436, { 402: } 437, { 403: } 439, { 404: } 441, { 405: } 443, { 406: } 445, { 407: } 447, { 408: } 448, { 409: } 449, { 410: } 450, { 411: } 452, { 412: } 453, { 413: } 454, { 414: } 455, { 415: } 456, { 416: } 457, { 417: } 459, { 418: } 460, { 419: } 461, { 420: } 462, { 421: } 463, { 422: } 464, { 423: } 465, { 424: } 466, { 425: } 468, { 426: } 469, { 427: } 470, { 428: } 472, { 429: } 473, { 430: } 474, { 431: } 475, { 432: } 476, { 433: } 477, { 434: } 478, { 435: } 479, { 436: } 480, { 437: } 482, { 438: } 483, { 439: } 484, { 440: } 486, { 441: } 487, { 442: } 489, { 443: } 490, { 444: } 491, { 445: } 493, { 446: } 495, { 447: } 496, { 448: } 497, { 449: } 498, { 450: } 499, { 451: } 500, { 452: } 501, { 453: } 502, { 454: } 503, { 455: } 505, { 456: } 506, { 457: } 507, { 458: } 509, { 459: } 510, { 460: } 512, { 461: } 513, { 462: } 514, { 463: } 516, { 464: } 517, { 465: } 518, { 466: } 519, { 467: } 520, { 468: } 521, { 469: } 522, { 470: } 523, { 471: } 524, { 472: } 525, { 473: } 526, { 474: } 527, { 475: } 528, { 476: } 530, { 477: } 531, { 478: } 532, { 479: } 533, { 480: } 534, { 481: } 535, { 482: } 536, { 483: } 537, { 484: } 538, { 485: } 540, { 486: } 541, { 487: } 543, { 488: } 544, { 489: } 546, { 490: } 547, { 491: } 548, { 492: } 549, { 493: } 550, { 494: } 552, { 495: } 553, { 496: } 554, { 497: } 556, { 498: } 558, { 499: } 559, { 500: } 560, { 501: } 561, { 502: } 562, { 503: } 563, { 504: } 565, { 505: } 567, { 506: } 568, { 507: } 570, { 508: } 571, { 509: } 573, { 510: } 574, { 511: } 575, { 512: } 576, { 513: } 578, { 514: } 580, { 515: } 580, { 516: } 581, { 517: } 583, { 518: } 584, { 519: } 585, { 520: } 586, { 521: } 587, { 522: } 588, { 523: } 589, { 524: } 591, { 525: } 592, { 526: } 593, { 527: } 594, { 528: } 595, { 529: } 596, { 530: } 597, { 531: } 598, { 532: } 600, { 533: } 601, { 534: } 602, { 535: } 604, { 536: } 605, { 537: } 606, { 538: } 607, { 539: } 608, { 540: } 609, { 541: } 610, { 542: } 611, { 543: } 612, { 544: } 613, { 545: } 614, { 546: } 615, { 547: } 616, { 548: } 617, { 549: } 618, { 550: } 619, { 551: } 620, { 552: } 621, { 553: } 623, { 554: } 624, { 555: } 625, { 556: } 626, { 557: } 627, { 558: } 628, { 559: } 630, { 560: } 632, { 561: } 633, { 562: } 635, { 563: } 637, { 564: } 639, { 565: } 640, { 566: } 642, { 567: } 643, { 568: } 645, { 569: } 646, { 570: } 648, { 571: } 649, { 572: } 650, { 573: } 651, { 574: } 653, { 575: } 654, { 576: } 655, { 577: } 657, { 578: } 658, { 579: } 659, { 580: } 660, { 581: } 662, { 582: } 663, { 583: } 664, { 584: } 665, { 585: } 666, { 586: } 667, { 587: } 668, { 588: } 669, { 589: } 670, { 590: } 671, { 591: } 672, { 592: } 673, { 593: } 674, { 594: } 676, { 595: } 677, { 596: } 679, { 597: } 680, { 598: } 681, { 599: } 682, { 600: } 683, { 601: } 684, { 602: } 685, { 603: } 686, { 604: } 687, { 605: } 688, { 606: } 689, { 607: } 690, { 608: } 691, { 609: } 692, { 610: } 693, { 611: } 695, { 612: } 697, { 613: } 699, { 614: } 701, { 615: } 702, { 616: } 704, { 617: } 705, { 618: } 706, { 619: } 707, { 620: } 709, { 621: } 710, { 622: } 711, { 623: } 713, { 624: } 714, { 625: } 715, { 626: } 716, { 627: } 717, { 628: } 718, { 629: } 720, { 630: } 722, { 631: } 724, { 632: } 726, { 633: } 727, { 634: } 729, { 635: } 730, { 636: } 731, { 637: } 732, { 638: } 733, { 639: } 734, { 640: } 735, { 641: } 737, { 642: } 738, { 643: } 740, { 644: } 742, { 645: } 744, { 646: } 745, { 647: } 746, { 648: } 747, { 649: } 748, { 650: } 749, { 651: } 750, { 652: } 752, { 653: } 753, { 654: } 754, { 655: } 755, { 656: } 757, { 657: } 758, { 658: } 759, { 659: } 760, { 660: } 760, { 661: } 762, { 662: } 764, { 663: } 765, { 664: } 766, { 665: } 767, { 666: } 768, { 667: } 770, { 668: } 771, { 669: } 772, { 670: } 773, { 671: } 775, { 672: } 776, { 673: } 778, { 674: } 779, { 675: } 780, { 676: } 781, { 677: } 783, { 678: } 785, { 679: } 786, { 680: } 788, { 681: } 789, { 682: } 790, { 683: } 792, { 684: } 793, { 685: } 794, { 686: } 795, { 687: } 796, { 688: } 797, { 689: } 798, { 690: } 799, { 691: } 800, { 692: } 801, { 693: } 802, { 694: } 803, { 695: } 805, { 696: } 807, { 697: } 808, { 698: } 810, { 699: } 811, { 700: } 812, { 701: } 813, { 702: } 814, { 703: } 815, { 704: } 816, { 705: } 817, { 706: } 818, { 707: } 819, { 708: } 821, { 709: } 823, { 710: } 824, { 711: } 826, { 712: } 827, { 713: } 828, { 714: } 829, { 715: } 830, { 716: } 831, { 717: } 832, { 718: } 833, { 719: } 835, { 720: } 837, { 721: } 838, { 722: } 839, { 723: } 840, { 724: } 841, { 725: } 842, { 726: } 843, { 727: } 844, { 728: } 846, { 729: } 847, { 730: } 848, { 731: } 849, { 732: } 851, { 733: } 853, { 734: } 854, { 735: } 855, { 736: } 856, { 737: } 858, { 738: } 859, { 739: } 860, { 740: } 861, { 741: } 862, { 742: } 863, { 743: } 864, { 744: } 865, { 745: } 867, { 746: } 868, { 747: } 869, { 748: } 870, { 749: } 871, { 750: } 873, { 751: } 875, { 752: } 876, { 753: } 878, { 754: } 880, { 755: } 882, { 756: } 884, { 757: } 885, { 758: } 886, { 759: } 887, { 760: } 888, { 761: } 889, { 762: } 891, { 763: } 893, { 764: } 894, { 765: } 896, { 766: } 898, { 767: } 900, { 768: } 902, { 769: } 903, { 770: } 904, { 771: } 905, { 772: } 906, { 773: } 908, { 774: } 909, { 775: } 910, { 776: } 912, { 777: } 913, { 778: } 914, { 779: } 916, { 780: } 918, { 781: } 920, { 782: } 921, { 783: } 922, { 784: } 923, { 785: } 924, { 786: } 925, { 787: } 926, { 788: } 927, { 789: } 929, { 790: } 930, { 791: } 931, { 792: } 932, { 793: } 933, { 794: } 934, { 795: } 935, { 796: } 936, { 797: } 937, { 798: } 938, { 799: } 940, { 800: } 942, { 801: } 943, { 802: } 944, { 803: } 945, { 804: } 946, { 805: } 947, { 806: } 948, { 807: } 949, { 808: } 950, { 809: } 952, { 810: } 953, { 811: } 954, { 812: } 956, { 813: } 958, { 814: } 959, { 815: } 960, { 816: } 961, { 817: } 962, { 818: } 963, { 819: } 964, { 820: } 966, { 821: } 967, { 822: } 968, { 823: } 970, { 824: } 971, { 825: } 972, { 826: } 974, { 827: } 975, { 828: } 977, { 829: } 978, { 830: } 979, { 831: } 981, { 832: } 982, { 833: } 983, { 834: } 984, { 835: } 985, { 836: } 987, { 837: } 988, { 838: } 989, { 839: } 990, { 840: } 992, { 841: } 993, { 842: } 995, { 843: } 997, { 844: } 999, { 845: } 1000, { 846: } 1001, { 847: } 1003, { 848: } 1005, { 849: } 1007, { 850: } 1009, { 851: } 1011, { 852: } 1012, { 853: } 1013, { 854: } 1014, { 855: } 1015, { 856: } 1017, { 857: } 1018, { 858: } 1020, { 859: } 1021, { 860: } 1022, { 861: } 1023, { 862: } 1024, { 863: } 1026, { 864: } 1027, { 865: } 1028, { 866: } 1029, { 867: } 1031, { 868: } 1032, { 869: } 1034, { 870: } 1036, { 871: } 1038, { 872: } 1039, { 873: } 1040, { 874: } 1042, { 875: } 1043, { 876: } 1044, { 877: } 1045, { 878: } 1046, { 879: } 1048, { 880: } 1049, { 881: } 1051, { 882: } 1052, { 883: } 1054, { 884: } 1055, { 885: } 1056, { 886: } 1057, { 887: } 1059, { 888: } 1061, { 889: } 1062, { 890: } 1063, { 891: } 1064, { 892: } 1066, { 893: } 1068, { 894: } 1070, { 895: } 1071, { 896: } 1072, { 897: } 1074, { 898: } 1076, { 899: } 1077, { 900: } 1078, { 901: } 1080, { 902: } 1081, { 903: } 1082, { 904: } 1083, { 905: } 1084, { 906: } 1086, { 907: } 1087, { 908: } 1089, { 909: } 1090, { 910: } 1092, { 911: } 1093, { 912: } 1094, { 913: } 1095, { 914: } 1096, { 915: } 1097, { 916: } 1098, { 917: } 1099, { 918: } 1101, { 919: } 1102, { 920: } 1103, { 921: } 1104, { 922: } 1106, { 923: } 1107, { 924: } 1109, { 925: } 1111, { 926: } 1112, { 927: } 1113, { 928: } 1114, { 929: } 1116, { 930: } 1117, { 931: } 1118, { 932: } 1120, { 933: } 1121, { 934: } 1122, { 935: } 1123, { 936: } 1124, { 937: } 1126, { 938: } 1127, { 939: } 1129, { 940: } 1130, { 941: } 1131, { 942: } 1133, { 943: } 1135, { 944: } 1137, { 945: } 1138, { 946: } 1140, { 947: } 1141, { 948: } 1142, { 949: } 1144, { 950: } 1145, { 951: } 1146, { 952: } 1147, { 953: } 1148, { 954: } 1149, { 955: } 1150, { 956: } 1151, { 957: } 1152, { 958: } 1153, { 959: } 1154, { 960: } 1155, { 961: } 1156, { 962: } 1157, { 963: } 1159, { 964: } 1160, { 965: } 1161, { 966: } 1162, { 967: } 1163, { 968: } 1165, { 969: } 1166, { 970: } 1168, { 971: } 1170, { 972: } 1172, { 973: } 1174, { 974: } 1175, { 975: } 1176, { 976: } 1177, { 977: } 1179, { 978: } 1180, { 979: } 1181, { 980: } 1182, { 981: } 1183, { 982: } 1184, { 983: } 1185, { 984: } 1186, { 985: } 1187, { 986: } 1189, { 987: } 1190, { 988: } 1191, { 989: } 1193, { 990: } 1194, { 991: } 1195, { 992: } 1197, { 993: } 1199, { 994: } 1200, { 995: } 1202, { 996: } 1204, { 997: } 1206, { 998: } 1207, { 999: } 1208, { 1000: } 1210, { 1001: } 1212, { 1002: } 1214, { 1003: } 1215, { 1004: } 1216, { 1005: } 1217, { 1006: } 1218, { 1007: } 1220, { 1008: } 1222, { 1009: } 1223, { 1010: } 1224, { 1011: } 1226, { 1012: } 1227, { 1013: } 1229, { 1014: } 1230, { 1015: } 1231, { 1016: } 1232, { 1017: } 1233, { 1018: } 1234, { 1019: } 1236, { 1020: } 1237, { 1021: } 1239, { 1022: } 1240, { 1023: } 1242, { 1024: } 1243, { 1025: } 1245, { 1026: } 1246, { 1027: } 1247, { 1028: } 1248, { 1029: } 1250, { 1030: } 1251, { 1031: } 1253, { 1032: } 1254, { 1033: } 1256 ); yykh : array [0..yynstates-1] of Integer = ( { 0: } 0, { 1: } 0, { 2: } 1, { 3: } 2, { 4: } 3, { 5: } 4, { 6: } 5, { 7: } 6, { 8: } 7, { 9: } 8, { 10: } 9, { 11: } 10, { 12: } 11, { 13: } 12, { 14: } 13, { 15: } 14, { 16: } 15, { 17: } 16, { 18: } 17, { 19: } 18, { 20: } 19, { 21: } 20, { 22: } 21, { 23: } 22, { 24: } 23, { 25: } 24, { 26: } 25, { 27: } 26, { 28: } 27, { 29: } 28, { 30: } 29, { 31: } 30, { 32: } 31, { 33: } 32, { 34: } 33, { 35: } 34, { 36: } 35, { 37: } 36, { 38: } 37, { 39: } 39, { 40: } 41, { 41: } 42, { 42: } 43, { 43: } 44, { 44: } 44, { 45: } 45, { 46: } 46, { 47: } 47, { 48: } 48, { 49: } 49, { 50: } 50, { 51: } 51, { 52: } 52, { 53: } 53, { 54: } 54, { 55: } 55, { 56: } 56, { 57: } 57, { 58: } 58, { 59: } 59, { 60: } 60, { 61: } 61, { 62: } 62, { 63: } 63, { 64: } 64, { 65: } 65, { 66: } 67, { 67: } 68, { 68: } 70, { 69: } 71, { 70: } 72, { 71: } 73, { 72: } 74, { 73: } 75, { 74: } 76, { 75: } 77, { 76: } 78, { 77: } 79, { 78: } 80, { 79: } 81, { 80: } 82, { 81: } 83, { 82: } 85, { 83: } 86, { 84: } 87, { 85: } 89, { 86: } 91, { 87: } 92, { 88: } 93, { 89: } 94, { 90: } 96, { 91: } 97, { 92: } 98, { 93: } 99, { 94: } 100, { 95: } 101, { 96: } 103, { 97: } 104, { 98: } 105, { 99: } 106, { 100: } 107, { 101: } 108, { 102: } 109, { 103: } 110, { 104: } 111, { 105: } 112, { 106: } 113, { 107: } 114, { 108: } 115, { 109: } 116, { 110: } 118, { 111: } 120, { 112: } 121, { 113: } 123, { 114: } 124, { 115: } 125, { 116: } 126, { 117: } 127, { 118: } 128, { 119: } 129, { 120: } 130, { 121: } 131, { 122: } 132, { 123: } 133, { 124: } 134, { 125: } 135, { 126: } 136, { 127: } 137, { 128: } 138, { 129: } 139, { 130: } 141, { 131: } 142, { 132: } 143, { 133: } 144, { 134: } 145, { 135: } 146, { 136: } 148, { 137: } 149, { 138: } 150, { 139: } 151, { 140: } 152, { 141: } 153, { 142: } 154, { 143: } 155, { 144: } 156, { 145: } 157, { 146: } 158, { 147: } 159, { 148: } 160, { 149: } 161, { 150: } 162, { 151: } 163, { 152: } 164, { 153: } 165, { 154: } 166, { 155: } 167, { 156: } 168, { 157: } 168, { 158: } 168, { 159: } 169, { 160: } 169, { 161: } 169, { 162: } 169, { 163: } 170, { 164: } 171, { 165: } 172, { 166: } 173, { 167: } 174, { 168: } 175, { 169: } 176, { 170: } 177, { 171: } 178, { 172: } 179, { 173: } 180, { 174: } 181, { 175: } 182, { 176: } 183, { 177: } 184, { 178: } 185, { 179: } 186, { 180: } 187, { 181: } 188, { 182: } 189, { 183: } 190, { 184: } 191, { 185: } 192, { 186: } 194, { 187: } 195, { 188: } 196, { 189: } 198, { 190: } 199, { 191: } 200, { 192: } 201, { 193: } 202, { 194: } 203, { 195: } 204, { 196: } 205, { 197: } 206, { 198: } 207, { 199: } 209, { 200: } 211, { 201: } 213, { 202: } 214, { 203: } 216, { 204: } 217, { 205: } 219, { 206: } 221, { 207: } 222, { 208: } 223, { 209: } 224, { 210: } 225, { 211: } 226, { 212: } 227, { 213: } 228, { 214: } 229, { 215: } 230, { 216: } 231, { 217: } 232, { 218: } 233, { 219: } 234, { 220: } 235, { 221: } 236, { 222: } 237, { 223: } 238, { 224: } 239, { 225: } 240, { 226: } 241, { 227: } 242, { 228: } 243, { 229: } 244, { 230: } 245, { 231: } 246, { 232: } 247, { 233: } 248, { 234: } 249, { 235: } 251, { 236: } 252, { 237: } 253, { 238: } 254, { 239: } 255, { 240: } 256, { 241: } 257, { 242: } 259, { 243: } 260, { 244: } 261, { 245: } 262, { 246: } 263, { 247: } 264, { 248: } 265, { 249: } 266, { 250: } 267, { 251: } 268, { 252: } 269, { 253: } 270, { 254: } 271, { 255: } 272, { 256: } 273, { 257: } 274, { 258: } 275, { 259: } 276, { 260: } 277, { 261: } 278, { 262: } 279, { 263: } 280, { 264: } 281, { 265: } 282, { 266: } 283, { 267: } 284, { 268: } 285, { 269: } 286, { 270: } 287, { 271: } 288, { 272: } 289, { 273: } 290, { 274: } 291, { 275: } 292, { 276: } 293, { 277: } 295, { 278: } 296, { 279: } 297, { 280: } 298, { 281: } 299, { 282: } 300, { 283: } 301, { 284: } 302, { 285: } 303, { 286: } 304, { 287: } 305, { 288: } 306, { 289: } 307, { 290: } 308, { 291: } 309, { 292: } 310, { 293: } 311, { 294: } 312, { 295: } 313, { 296: } 314, { 297: } 315, { 298: } 317, { 299: } 319, { 300: } 320, { 301: } 321, { 302: } 322, { 303: } 323, { 304: } 324, { 305: } 325, { 306: } 326, { 307: } 327, { 308: } 329, { 309: } 330, { 310: } 331, { 311: } 332, { 312: } 333, { 313: } 335, { 314: } 336, { 315: } 337, { 316: } 338, { 317: } 339, { 318: } 341, { 319: } 342, { 320: } 343, { 321: } 344, { 322: } 345, { 323: } 346, { 324: } 348, { 325: } 349, { 326: } 351, { 327: } 352, { 328: } 353, { 329: } 354, { 330: } 355, { 331: } 356, { 332: } 357, { 333: } 357, { 334: } 358, { 335: } 359, { 336: } 360, { 337: } 361, { 338: } 362, { 339: } 363, { 340: } 364, { 341: } 365, { 342: } 366, { 343: } 367, { 344: } 368, { 345: } 369, { 346: } 370, { 347: } 371, { 348: } 372, { 349: } 373, { 350: } 374, { 351: } 375, { 352: } 377, { 353: } 379, { 354: } 381, { 355: } 382, { 356: } 384, { 357: } 385, { 358: } 387, { 359: } 388, { 360: } 389, { 361: } 391, { 362: } 392, { 363: } 393, { 364: } 394, { 365: } 395, { 366: } 396, { 367: } 397, { 368: } 398, { 369: } 399, { 370: } 400, { 371: } 401, { 372: } 402, { 373: } 403, { 374: } 405, { 375: } 406, { 376: } 407, { 377: } 408, { 378: } 409, { 379: } 410, { 380: } 411, { 381: } 412, { 382: } 413, { 383: } 414, { 384: } 415, { 385: } 416, { 386: } 417, { 387: } 418, { 388: } 419, { 389: } 421, { 390: } 422, { 391: } 424, { 392: } 425, { 393: } 426, { 394: } 427, { 395: } 429, { 396: } 430, { 397: } 432, { 398: } 433, { 399: } 434, { 400: } 435, { 401: } 436, { 402: } 438, { 403: } 440, { 404: } 442, { 405: } 444, { 406: } 446, { 407: } 447, { 408: } 448, { 409: } 449, { 410: } 451, { 411: } 452, { 412: } 453, { 413: } 454, { 414: } 455, { 415: } 456, { 416: } 458, { 417: } 459, { 418: } 460, { 419: } 461, { 420: } 462, { 421: } 463, { 422: } 464, { 423: } 465, { 424: } 467, { 425: } 468, { 426: } 469, { 427: } 471, { 428: } 472, { 429: } 473, { 430: } 474, { 431: } 475, { 432: } 476, { 433: } 477, { 434: } 478, { 435: } 479, { 436: } 481, { 437: } 482, { 438: } 483, { 439: } 485, { 440: } 486, { 441: } 488, { 442: } 489, { 443: } 490, { 444: } 492, { 445: } 494, { 446: } 495, { 447: } 496, { 448: } 497, { 449: } 498, { 450: } 499, { 451: } 500, { 452: } 501, { 453: } 502, { 454: } 504, { 455: } 505, { 456: } 506, { 457: } 508, { 458: } 509, { 459: } 511, { 460: } 512, { 461: } 513, { 462: } 515, { 463: } 516, { 464: } 517, { 465: } 518, { 466: } 519, { 467: } 520, { 468: } 521, { 469: } 522, { 470: } 523, { 471: } 524, { 472: } 525, { 473: } 526, { 474: } 527, { 475: } 529, { 476: } 530, { 477: } 531, { 478: } 532, { 479: } 533, { 480: } 534, { 481: } 535, { 482: } 536, { 483: } 537, { 484: } 539, { 485: } 540, { 486: } 542, { 487: } 543, { 488: } 545, { 489: } 546, { 490: } 547, { 491: } 548, { 492: } 549, { 493: } 551, { 494: } 552, { 495: } 553, { 496: } 555, { 497: } 557, { 498: } 558, { 499: } 559, { 500: } 560, { 501: } 561, { 502: } 562, { 503: } 564, { 504: } 566, { 505: } 567, { 506: } 569, { 507: } 570, { 508: } 572, { 509: } 573, { 510: } 574, { 511: } 575, { 512: } 577, { 513: } 579, { 514: } 579, { 515: } 580, { 516: } 582, { 517: } 583, { 518: } 584, { 519: } 585, { 520: } 586, { 521: } 587, { 522: } 588, { 523: } 590, { 524: } 591, { 525: } 592, { 526: } 593, { 527: } 594, { 528: } 595, { 529: } 596, { 530: } 597, { 531: } 599, { 532: } 600, { 533: } 601, { 534: } 603, { 535: } 604, { 536: } 605, { 537: } 606, { 538: } 607, { 539: } 608, { 540: } 609, { 541: } 610, { 542: } 611, { 543: } 612, { 544: } 613, { 545: } 614, { 546: } 615, { 547: } 616, { 548: } 617, { 549: } 618, { 550: } 619, { 551: } 620, { 552: } 622, { 553: } 623, { 554: } 624, { 555: } 625, { 556: } 626, { 557: } 627, { 558: } 629, { 559: } 631, { 560: } 632, { 561: } 634, { 562: } 636, { 563: } 638, { 564: } 639, { 565: } 641, { 566: } 642, { 567: } 644, { 568: } 645, { 569: } 647, { 570: } 648, { 571: } 649, { 572: } 650, { 573: } 652, { 574: } 653, { 575: } 654, { 576: } 656, { 577: } 657, { 578: } 658, { 579: } 659, { 580: } 661, { 581: } 662, { 582: } 663, { 583: } 664, { 584: } 665, { 585: } 666, { 586: } 667, { 587: } 668, { 588: } 669, { 589: } 670, { 590: } 671, { 591: } 672, { 592: } 673, { 593: } 675, { 594: } 676, { 595: } 678, { 596: } 679, { 597: } 680, { 598: } 681, { 599: } 682, { 600: } 683, { 601: } 684, { 602: } 685, { 603: } 686, { 604: } 687, { 605: } 688, { 606: } 689, { 607: } 690, { 608: } 691, { 609: } 692, { 610: } 694, { 611: } 696, { 612: } 698, { 613: } 700, { 614: } 701, { 615: } 703, { 616: } 704, { 617: } 705, { 618: } 706, { 619: } 708, { 620: } 709, { 621: } 710, { 622: } 712, { 623: } 713, { 624: } 714, { 625: } 715, { 626: } 716, { 627: } 717, { 628: } 719, { 629: } 721, { 630: } 723, { 631: } 725, { 632: } 726, { 633: } 728, { 634: } 729, { 635: } 730, { 636: } 731, { 637: } 732, { 638: } 733, { 639: } 734, { 640: } 736, { 641: } 737, { 642: } 739, { 643: } 741, { 644: } 743, { 645: } 744, { 646: } 745, { 647: } 746, { 648: } 747, { 649: } 748, { 650: } 749, { 651: } 751, { 652: } 752, { 653: } 753, { 654: } 754, { 655: } 756, { 656: } 757, { 657: } 758, { 658: } 759, { 659: } 759, { 660: } 761, { 661: } 763, { 662: } 764, { 663: } 765, { 664: } 766, { 665: } 767, { 666: } 769, { 667: } 770, { 668: } 771, { 669: } 772, { 670: } 774, { 671: } 775, { 672: } 777, { 673: } 778, { 674: } 779, { 675: } 780, { 676: } 782, { 677: } 784, { 678: } 785, { 679: } 787, { 680: } 788, { 681: } 789, { 682: } 791, { 683: } 792, { 684: } 793, { 685: } 794, { 686: } 795, { 687: } 796, { 688: } 797, { 689: } 798, { 690: } 799, { 691: } 800, { 692: } 801, { 693: } 802, { 694: } 804, { 695: } 806, { 696: } 807, { 697: } 809, { 698: } 810, { 699: } 811, { 700: } 812, { 701: } 813, { 702: } 814, { 703: } 815, { 704: } 816, { 705: } 817, { 706: } 818, { 707: } 820, { 708: } 822, { 709: } 823, { 710: } 825, { 711: } 826, { 712: } 827, { 713: } 828, { 714: } 829, { 715: } 830, { 716: } 831, { 717: } 832, { 718: } 834, { 719: } 836, { 720: } 837, { 721: } 838, { 722: } 839, { 723: } 840, { 724: } 841, { 725: } 842, { 726: } 843, { 727: } 845, { 728: } 846, { 729: } 847, { 730: } 848, { 731: } 850, { 732: } 852, { 733: } 853, { 734: } 854, { 735: } 855, { 736: } 857, { 737: } 858, { 738: } 859, { 739: } 860, { 740: } 861, { 741: } 862, { 742: } 863, { 743: } 864, { 744: } 866, { 745: } 867, { 746: } 868, { 747: } 869, { 748: } 870, { 749: } 872, { 750: } 874, { 751: } 875, { 752: } 877, { 753: } 879, { 754: } 881, { 755: } 883, { 756: } 884, { 757: } 885, { 758: } 886, { 759: } 887, { 760: } 888, { 761: } 890, { 762: } 892, { 763: } 893, { 764: } 895, { 765: } 897, { 766: } 899, { 767: } 901, { 768: } 902, { 769: } 903, { 770: } 904, { 771: } 905, { 772: } 907, { 773: } 908, { 774: } 909, { 775: } 911, { 776: } 912, { 777: } 913, { 778: } 915, { 779: } 917, { 780: } 919, { 781: } 920, { 782: } 921, { 783: } 922, { 784: } 923, { 785: } 924, { 786: } 925, { 787: } 926, { 788: } 928, { 789: } 929, { 790: } 930, { 791: } 931, { 792: } 932, { 793: } 933, { 794: } 934, { 795: } 935, { 796: } 936, { 797: } 937, { 798: } 939, { 799: } 941, { 800: } 942, { 801: } 943, { 802: } 944, { 803: } 945, { 804: } 946, { 805: } 947, { 806: } 948, { 807: } 949, { 808: } 951, { 809: } 952, { 810: } 953, { 811: } 955, { 812: } 957, { 813: } 958, { 814: } 959, { 815: } 960, { 816: } 961, { 817: } 962, { 818: } 963, { 819: } 965, { 820: } 966, { 821: } 967, { 822: } 969, { 823: } 970, { 824: } 971, { 825: } 973, { 826: } 974, { 827: } 976, { 828: } 977, { 829: } 978, { 830: } 980, { 831: } 981, { 832: } 982, { 833: } 983, { 834: } 984, { 835: } 986, { 836: } 987, { 837: } 988, { 838: } 989, { 839: } 991, { 840: } 992, { 841: } 994, { 842: } 996, { 843: } 998, { 844: } 999, { 845: } 1000, { 846: } 1002, { 847: } 1004, { 848: } 1006, { 849: } 1008, { 850: } 1010, { 851: } 1011, { 852: } 1012, { 853: } 1013, { 854: } 1014, { 855: } 1016, { 856: } 1017, { 857: } 1019, { 858: } 1020, { 859: } 1021, { 860: } 1022, { 861: } 1023, { 862: } 1025, { 863: } 1026, { 864: } 1027, { 865: } 1028, { 866: } 1030, { 867: } 1031, { 868: } 1033, { 869: } 1035, { 870: } 1037, { 871: } 1038, { 872: } 1039, { 873: } 1041, { 874: } 1042, { 875: } 1043, { 876: } 1044, { 877: } 1045, { 878: } 1047, { 879: } 1048, { 880: } 1050, { 881: } 1051, { 882: } 1053, { 883: } 1054, { 884: } 1055, { 885: } 1056, { 886: } 1058, { 887: } 1060, { 888: } 1061, { 889: } 1062, { 890: } 1063, { 891: } 1065, { 892: } 1067, { 893: } 1069, { 894: } 1070, { 895: } 1071, { 896: } 1073, { 897: } 1075, { 898: } 1076, { 899: } 1077, { 900: } 1079, { 901: } 1080, { 902: } 1081, { 903: } 1082, { 904: } 1083, { 905: } 1085, { 906: } 1086, { 907: } 1088, { 908: } 1089, { 909: } 1091, { 910: } 1092, { 911: } 1093, { 912: } 1094, { 913: } 1095, { 914: } 1096, { 915: } 1097, { 916: } 1098, { 917: } 1100, { 918: } 1101, { 919: } 1102, { 920: } 1103, { 921: } 1105, { 922: } 1106, { 923: } 1108, { 924: } 1110, { 925: } 1111, { 926: } 1112, { 927: } 1113, { 928: } 1115, { 929: } 1116, { 930: } 1117, { 931: } 1119, { 932: } 1120, { 933: } 1121, { 934: } 1122, { 935: } 1123, { 936: } 1125, { 937: } 1126, { 938: } 1128, { 939: } 1129, { 940: } 1130, { 941: } 1132, { 942: } 1134, { 943: } 1136, { 944: } 1137, { 945: } 1139, { 946: } 1140, { 947: } 1141, { 948: } 1143, { 949: } 1144, { 950: } 1145, { 951: } 1146, { 952: } 1147, { 953: } 1148, { 954: } 1149, { 955: } 1150, { 956: } 1151, { 957: } 1152, { 958: } 1153, { 959: } 1154, { 960: } 1155, { 961: } 1156, { 962: } 1158, { 963: } 1159, { 964: } 1160, { 965: } 1161, { 966: } 1162, { 967: } 1164, { 968: } 1165, { 969: } 1167, { 970: } 1169, { 971: } 1171, { 972: } 1173, { 973: } 1174, { 974: } 1175, { 975: } 1176, { 976: } 1178, { 977: } 1179, { 978: } 1180, { 979: } 1181, { 980: } 1182, { 981: } 1183, { 982: } 1184, { 983: } 1185, { 984: } 1186, { 985: } 1188, { 986: } 1189, { 987: } 1190, { 988: } 1192, { 989: } 1193, { 990: } 1194, { 991: } 1196, { 992: } 1198, { 993: } 1199, { 994: } 1201, { 995: } 1203, { 996: } 1205, { 997: } 1206, { 998: } 1207, { 999: } 1209, { 1000: } 1211, { 1001: } 1213, { 1002: } 1214, { 1003: } 1215, { 1004: } 1216, { 1005: } 1217, { 1006: } 1219, { 1007: } 1221, { 1008: } 1222, { 1009: } 1223, { 1010: } 1225, { 1011: } 1226, { 1012: } 1228, { 1013: } 1229, { 1014: } 1230, { 1015: } 1231, { 1016: } 1232, { 1017: } 1233, { 1018: } 1235, { 1019: } 1236, { 1020: } 1238, { 1021: } 1239, { 1022: } 1241, { 1023: } 1242, { 1024: } 1244, { 1025: } 1245, { 1026: } 1246, { 1027: } 1247, { 1028: } 1249, { 1029: } 1250, { 1030: } 1252, { 1031: } 1253, { 1032: } 1255, { 1033: } 1257 ); yyml : array [0..yynstates-1] of Integer = ( { 0: } 1, { 1: } 1, { 2: } 1, { 3: } 2, { 4: } 3, { 5: } 4, { 6: } 5, { 7: } 6, { 8: } 7, { 9: } 8, { 10: } 9, { 11: } 10, { 12: } 11, { 13: } 12, { 14: } 13, { 15: } 14, { 16: } 15, { 17: } 16, { 18: } 17, { 19: } 18, { 20: } 19, { 21: } 20, { 22: } 21, { 23: } 22, { 24: } 23, { 25: } 24, { 26: } 25, { 27: } 26, { 28: } 27, { 29: } 28, { 30: } 29, { 31: } 30, { 32: } 31, { 33: } 32, { 34: } 33, { 35: } 34, { 36: } 35, { 37: } 36, { 38: } 37, { 39: } 38, { 40: } 40, { 41: } 42, { 42: } 42, { 43: } 43, { 44: } 44, { 45: } 44, { 46: } 45, { 47: } 46, { 48: } 47, { 49: } 48, { 50: } 49, { 51: } 50, { 52: } 51, { 53: } 52, { 54: } 53, { 55: } 54, { 56: } 55, { 57: } 56, { 58: } 57, { 59: } 58, { 60: } 59, { 61: } 60, { 62: } 61, { 63: } 62, { 64: } 63, { 65: } 64, { 66: } 65, { 67: } 67, { 68: } 68, { 69: } 70, { 70: } 71, { 71: } 72, { 72: } 73, { 73: } 74, { 74: } 75, { 75: } 76, { 76: } 77, { 77: } 78, { 78: } 79, { 79: } 80, { 80: } 81, { 81: } 82, { 82: } 83, { 83: } 85, { 84: } 86, { 85: } 87, { 86: } 89, { 87: } 91, { 88: } 92, { 89: } 93, { 90: } 94, { 91: } 96, { 92: } 97, { 93: } 98, { 94: } 99, { 95: } 100, { 96: } 101, { 97: } 103, { 98: } 104, { 99: } 105, { 100: } 106, { 101: } 107, { 102: } 108, { 103: } 109, { 104: } 110, { 105: } 111, { 106: } 112, { 107: } 113, { 108: } 114, { 109: } 115, { 110: } 116, { 111: } 118, { 112: } 120, { 113: } 121, { 114: } 123, { 115: } 124, { 116: } 125, { 117: } 126, { 118: } 127, { 119: } 128, { 120: } 129, { 121: } 130, { 122: } 131, { 123: } 132, { 124: } 133, { 125: } 134, { 126: } 135, { 127: } 136, { 128: } 137, { 129: } 138, { 130: } 139, { 131: } 141, { 132: } 142, { 133: } 143, { 134: } 144, { 135: } 145, { 136: } 146, { 137: } 148, { 138: } 149, { 139: } 150, { 140: } 151, { 141: } 152, { 142: } 153, { 143: } 154, { 144: } 155, { 145: } 156, { 146: } 157, { 147: } 158, { 148: } 159, { 149: } 160, { 150: } 161, { 151: } 162, { 152: } 163, { 153: } 164, { 154: } 165, { 155: } 166, { 156: } 167, { 157: } 168, { 158: } 168, { 159: } 168, { 160: } 169, { 161: } 170, { 162: } 170, { 163: } 170, { 164: } 171, { 165: } 172, { 166: } 173, { 167: } 174, { 168: } 175, { 169: } 176, { 170: } 177, { 171: } 178, { 172: } 179, { 173: } 180, { 174: } 181, { 175: } 182, { 176: } 183, { 177: } 184, { 178: } 185, { 179: } 186, { 180: } 187, { 181: } 188, { 182: } 189, { 183: } 190, { 184: } 191, { 185: } 192, { 186: } 193, { 187: } 195, { 188: } 196, { 189: } 197, { 190: } 199, { 191: } 200, { 192: } 201, { 193: } 202, { 194: } 203, { 195: } 204, { 196: } 205, { 197: } 206, { 198: } 207, { 199: } 208, { 200: } 210, { 201: } 212, { 202: } 214, { 203: } 215, { 204: } 217, { 205: } 218, { 206: } 220, { 207: } 222, { 208: } 223, { 209: } 224, { 210: } 225, { 211: } 226, { 212: } 227, { 213: } 228, { 214: } 229, { 215: } 230, { 216: } 231, { 217: } 232, { 218: } 233, { 219: } 234, { 220: } 235, { 221: } 236, { 222: } 237, { 223: } 238, { 224: } 239, { 225: } 240, { 226: } 241, { 227: } 242, { 228: } 243, { 229: } 244, { 230: } 245, { 231: } 246, { 232: } 247, { 233: } 248, { 234: } 249, { 235: } 250, { 236: } 252, { 237: } 253, { 238: } 254, { 239: } 255, { 240: } 256, { 241: } 257, { 242: } 258, { 243: } 260, { 244: } 261, { 245: } 262, { 246: } 263, { 247: } 264, { 248: } 265, { 249: } 266, { 250: } 267, { 251: } 268, { 252: } 269, { 253: } 270, { 254: } 271, { 255: } 272, { 256: } 273, { 257: } 274, { 258: } 275, { 259: } 276, { 260: } 277, { 261: } 278, { 262: } 279, { 263: } 280, { 264: } 281, { 265: } 282, { 266: } 283, { 267: } 284, { 268: } 285, { 269: } 286, { 270: } 287, { 271: } 288, { 272: } 289, { 273: } 290, { 274: } 291, { 275: } 292, { 276: } 293, { 277: } 294, { 278: } 296, { 279: } 297, { 280: } 298, { 281: } 299, { 282: } 300, { 283: } 301, { 284: } 302, { 285: } 303, { 286: } 304, { 287: } 305, { 288: } 306, { 289: } 307, { 290: } 308, { 291: } 309, { 292: } 310, { 293: } 311, { 294: } 312, { 295: } 313, { 296: } 314, { 297: } 315, { 298: } 316, { 299: } 318, { 300: } 320, { 301: } 321, { 302: } 322, { 303: } 323, { 304: } 324, { 305: } 325, { 306: } 326, { 307: } 327, { 308: } 328, { 309: } 330, { 310: } 331, { 311: } 332, { 312: } 333, { 313: } 334, { 314: } 336, { 315: } 337, { 316: } 338, { 317: } 339, { 318: } 340, { 319: } 342, { 320: } 343, { 321: } 344, { 322: } 345, { 323: } 346, { 324: } 347, { 325: } 349, { 326: } 350, { 327: } 352, { 328: } 353, { 329: } 354, { 330: } 355, { 331: } 356, { 332: } 357, { 333: } 358, { 334: } 358, { 335: } 359, { 336: } 360, { 337: } 361, { 338: } 362, { 339: } 363, { 340: } 364, { 341: } 365, { 342: } 366, { 343: } 367, { 344: } 368, { 345: } 369, { 346: } 370, { 347: } 371, { 348: } 372, { 349: } 373, { 350: } 374, { 351: } 375, { 352: } 376, { 353: } 378, { 354: } 380, { 355: } 382, { 356: } 383, { 357: } 385, { 358: } 386, { 359: } 388, { 360: } 389, { 361: } 390, { 362: } 392, { 363: } 393, { 364: } 394, { 365: } 395, { 366: } 396, { 367: } 397, { 368: } 398, { 369: } 399, { 370: } 400, { 371: } 401, { 372: } 402, { 373: } 403, { 374: } 404, { 375: } 406, { 376: } 407, { 377: } 408, { 378: } 409, { 379: } 410, { 380: } 411, { 381: } 412, { 382: } 413, { 383: } 414, { 384: } 415, { 385: } 416, { 386: } 417, { 387: } 418, { 388: } 419, { 389: } 420, { 390: } 422, { 391: } 423, { 392: } 425, { 393: } 426, { 394: } 427, { 395: } 428, { 396: } 430, { 397: } 431, { 398: } 433, { 399: } 434, { 400: } 435, { 401: } 436, { 402: } 437, { 403: } 439, { 404: } 441, { 405: } 443, { 406: } 445, { 407: } 447, { 408: } 448, { 409: } 449, { 410: } 450, { 411: } 452, { 412: } 453, { 413: } 454, { 414: } 455, { 415: } 456, { 416: } 457, { 417: } 459, { 418: } 460, { 419: } 461, { 420: } 462, { 421: } 463, { 422: } 464, { 423: } 465, { 424: } 466, { 425: } 468, { 426: } 469, { 427: } 470, { 428: } 472, { 429: } 473, { 430: } 474, { 431: } 475, { 432: } 476, { 433: } 477, { 434: } 478, { 435: } 479, { 436: } 480, { 437: } 482, { 438: } 483, { 439: } 484, { 440: } 486, { 441: } 487, { 442: } 489, { 443: } 490, { 444: } 491, { 445: } 493, { 446: } 495, { 447: } 496, { 448: } 497, { 449: } 498, { 450: } 499, { 451: } 500, { 452: } 501, { 453: } 502, { 454: } 503, { 455: } 505, { 456: } 506, { 457: } 507, { 458: } 509, { 459: } 510, { 460: } 512, { 461: } 513, { 462: } 514, { 463: } 516, { 464: } 517, { 465: } 518, { 466: } 519, { 467: } 520, { 468: } 521, { 469: } 522, { 470: } 523, { 471: } 524, { 472: } 525, { 473: } 526, { 474: } 527, { 475: } 528, { 476: } 530, { 477: } 531, { 478: } 532, { 479: } 533, { 480: } 534, { 481: } 535, { 482: } 536, { 483: } 537, { 484: } 538, { 485: } 540, { 486: } 541, { 487: } 543, { 488: } 544, { 489: } 546, { 490: } 547, { 491: } 548, { 492: } 549, { 493: } 550, { 494: } 552, { 495: } 553, { 496: } 554, { 497: } 556, { 498: } 558, { 499: } 559, { 500: } 560, { 501: } 561, { 502: } 562, { 503: } 563, { 504: } 565, { 505: } 567, { 506: } 568, { 507: } 570, { 508: } 571, { 509: } 573, { 510: } 574, { 511: } 575, { 512: } 576, { 513: } 578, { 514: } 580, { 515: } 580, { 516: } 581, { 517: } 583, { 518: } 584, { 519: } 585, { 520: } 586, { 521: } 587, { 522: } 588, { 523: } 589, { 524: } 591, { 525: } 592, { 526: } 593, { 527: } 594, { 528: } 595, { 529: } 596, { 530: } 597, { 531: } 598, { 532: } 600, { 533: } 601, { 534: } 602, { 535: } 604, { 536: } 605, { 537: } 606, { 538: } 607, { 539: } 608, { 540: } 609, { 541: } 610, { 542: } 611, { 543: } 612, { 544: } 613, { 545: } 614, { 546: } 615, { 547: } 616, { 548: } 617, { 549: } 618, { 550: } 619, { 551: } 620, { 552: } 621, { 553: } 623, { 554: } 624, { 555: } 625, { 556: } 626, { 557: } 627, { 558: } 628, { 559: } 630, { 560: } 632, { 561: } 633, { 562: } 635, { 563: } 637, { 564: } 639, { 565: } 640, { 566: } 642, { 567: } 643, { 568: } 645, { 569: } 646, { 570: } 648, { 571: } 649, { 572: } 650, { 573: } 651, { 574: } 653, { 575: } 654, { 576: } 655, { 577: } 657, { 578: } 658, { 579: } 659, { 580: } 660, { 581: } 662, { 582: } 663, { 583: } 664, { 584: } 665, { 585: } 666, { 586: } 667, { 587: } 668, { 588: } 669, { 589: } 670, { 590: } 671, { 591: } 672, { 592: } 673, { 593: } 674, { 594: } 676, { 595: } 677, { 596: } 679, { 597: } 680, { 598: } 681, { 599: } 682, { 600: } 683, { 601: } 684, { 602: } 685, { 603: } 686, { 604: } 687, { 605: } 688, { 606: } 689, { 607: } 690, { 608: } 691, { 609: } 692, { 610: } 693, { 611: } 695, { 612: } 697, { 613: } 699, { 614: } 701, { 615: } 702, { 616: } 704, { 617: } 705, { 618: } 706, { 619: } 707, { 620: } 709, { 621: } 710, { 622: } 711, { 623: } 713, { 624: } 714, { 625: } 715, { 626: } 716, { 627: } 717, { 628: } 718, { 629: } 720, { 630: } 722, { 631: } 724, { 632: } 726, { 633: } 727, { 634: } 729, { 635: } 730, { 636: } 731, { 637: } 732, { 638: } 733, { 639: } 734, { 640: } 735, { 641: } 737, { 642: } 738, { 643: } 740, { 644: } 742, { 645: } 744, { 646: } 745, { 647: } 746, { 648: } 747, { 649: } 748, { 650: } 749, { 651: } 750, { 652: } 752, { 653: } 753, { 654: } 754, { 655: } 755, { 656: } 757, { 657: } 758, { 658: } 759, { 659: } 760, { 660: } 760, { 661: } 762, { 662: } 764, { 663: } 765, { 664: } 766, { 665: } 767, { 666: } 768, { 667: } 770, { 668: } 771, { 669: } 772, { 670: } 773, { 671: } 775, { 672: } 776, { 673: } 778, { 674: } 779, { 675: } 780, { 676: } 781, { 677: } 783, { 678: } 785, { 679: } 786, { 680: } 788, { 681: } 789, { 682: } 790, { 683: } 792, { 684: } 793, { 685: } 794, { 686: } 795, { 687: } 796, { 688: } 797, { 689: } 798, { 690: } 799, { 691: } 800, { 692: } 801, { 693: } 802, { 694: } 803, { 695: } 805, { 696: } 807, { 697: } 808, { 698: } 810, { 699: } 811, { 700: } 812, { 701: } 813, { 702: } 814, { 703: } 815, { 704: } 816, { 705: } 817, { 706: } 818, { 707: } 819, { 708: } 821, { 709: } 823, { 710: } 824, { 711: } 826, { 712: } 827, { 713: } 828, { 714: } 829, { 715: } 830, { 716: } 831, { 717: } 832, { 718: } 833, { 719: } 835, { 720: } 837, { 721: } 838, { 722: } 839, { 723: } 840, { 724: } 841, { 725: } 842, { 726: } 843, { 727: } 844, { 728: } 846, { 729: } 847, { 730: } 848, { 731: } 849, { 732: } 851, { 733: } 853, { 734: } 854, { 735: } 855, { 736: } 856, { 737: } 858, { 738: } 859, { 739: } 860, { 740: } 861, { 741: } 862, { 742: } 863, { 743: } 864, { 744: } 865, { 745: } 867, { 746: } 868, { 747: } 869, { 748: } 870, { 749: } 871, { 750: } 873, { 751: } 875, { 752: } 876, { 753: } 878, { 754: } 880, { 755: } 882, { 756: } 884, { 757: } 885, { 758: } 886, { 759: } 887, { 760: } 888, { 761: } 889, { 762: } 891, { 763: } 893, { 764: } 894, { 765: } 896, { 766: } 898, { 767: } 900, { 768: } 902, { 769: } 903, { 770: } 904, { 771: } 905, { 772: } 906, { 773: } 908, { 774: } 909, { 775: } 910, { 776: } 912, { 777: } 913, { 778: } 914, { 779: } 916, { 780: } 918, { 781: } 920, { 782: } 921, { 783: } 922, { 784: } 923, { 785: } 924, { 786: } 925, { 787: } 926, { 788: } 927, { 789: } 929, { 790: } 930, { 791: } 931, { 792: } 932, { 793: } 933, { 794: } 934, { 795: } 935, { 796: } 936, { 797: } 937, { 798: } 938, { 799: } 940, { 800: } 942, { 801: } 943, { 802: } 944, { 803: } 945, { 804: } 946, { 805: } 947, { 806: } 948, { 807: } 949, { 808: } 950, { 809: } 952, { 810: } 953, { 811: } 954, { 812: } 956, { 813: } 958, { 814: } 959, { 815: } 960, { 816: } 961, { 817: } 962, { 818: } 963, { 819: } 964, { 820: } 966, { 821: } 967, { 822: } 968, { 823: } 970, { 824: } 971, { 825: } 972, { 826: } 974, { 827: } 975, { 828: } 977, { 829: } 978, { 830: } 979, { 831: } 981, { 832: } 982, { 833: } 983, { 834: } 984, { 835: } 985, { 836: } 987, { 837: } 988, { 838: } 989, { 839: } 990, { 840: } 992, { 841: } 993, { 842: } 995, { 843: } 997, { 844: } 999, { 845: } 1000, { 846: } 1001, { 847: } 1003, { 848: } 1005, { 849: } 1007, { 850: } 1009, { 851: } 1011, { 852: } 1012, { 853: } 1013, { 854: } 1014, { 855: } 1015, { 856: } 1017, { 857: } 1018, { 858: } 1020, { 859: } 1021, { 860: } 1022, { 861: } 1023, { 862: } 1024, { 863: } 1026, { 864: } 1027, { 865: } 1028, { 866: } 1029, { 867: } 1031, { 868: } 1032, { 869: } 1034, { 870: } 1036, { 871: } 1038, { 872: } 1039, { 873: } 1040, { 874: } 1042, { 875: } 1043, { 876: } 1044, { 877: } 1045, { 878: } 1046, { 879: } 1048, { 880: } 1049, { 881: } 1051, { 882: } 1052, { 883: } 1054, { 884: } 1055, { 885: } 1056, { 886: } 1057, { 887: } 1059, { 888: } 1061, { 889: } 1062, { 890: } 1063, { 891: } 1064, { 892: } 1066, { 893: } 1068, { 894: } 1070, { 895: } 1071, { 896: } 1072, { 897: } 1074, { 898: } 1076, { 899: } 1077, { 900: } 1078, { 901: } 1080, { 902: } 1081, { 903: } 1082, { 904: } 1083, { 905: } 1084, { 906: } 1086, { 907: } 1087, { 908: } 1089, { 909: } 1090, { 910: } 1092, { 911: } 1093, { 912: } 1094, { 913: } 1095, { 914: } 1096, { 915: } 1097, { 916: } 1098, { 917: } 1099, { 918: } 1101, { 919: } 1102, { 920: } 1103, { 921: } 1104, { 922: } 1106, { 923: } 1107, { 924: } 1109, { 925: } 1111, { 926: } 1112, { 927: } 1113, { 928: } 1114, { 929: } 1116, { 930: } 1117, { 931: } 1118, { 932: } 1120, { 933: } 1121, { 934: } 1122, { 935: } 1123, { 936: } 1124, { 937: } 1126, { 938: } 1127, { 939: } 1129, { 940: } 1130, { 941: } 1131, { 942: } 1133, { 943: } 1135, { 944: } 1137, { 945: } 1138, { 946: } 1140, { 947: } 1141, { 948: } 1142, { 949: } 1144, { 950: } 1145, { 951: } 1146, { 952: } 1147, { 953: } 1148, { 954: } 1149, { 955: } 1150, { 956: } 1151, { 957: } 1152, { 958: } 1153, { 959: } 1154, { 960: } 1155, { 961: } 1156, { 962: } 1157, { 963: } 1159, { 964: } 1160, { 965: } 1161, { 966: } 1162, { 967: } 1163, { 968: } 1165, { 969: } 1166, { 970: } 1168, { 971: } 1170, { 972: } 1172, { 973: } 1174, { 974: } 1175, { 975: } 1176, { 976: } 1177, { 977: } 1179, { 978: } 1180, { 979: } 1181, { 980: } 1182, { 981: } 1183, { 982: } 1184, { 983: } 1185, { 984: } 1186, { 985: } 1187, { 986: } 1189, { 987: } 1190, { 988: } 1191, { 989: } 1193, { 990: } 1194, { 991: } 1195, { 992: } 1197, { 993: } 1199, { 994: } 1200, { 995: } 1202, { 996: } 1204, { 997: } 1206, { 998: } 1207, { 999: } 1208, { 1000: } 1210, { 1001: } 1212, { 1002: } 1214, { 1003: } 1215, { 1004: } 1216, { 1005: } 1217, { 1006: } 1218, { 1007: } 1220, { 1008: } 1222, { 1009: } 1223, { 1010: } 1224, { 1011: } 1226, { 1012: } 1227, { 1013: } 1229, { 1014: } 1230, { 1015: } 1231, { 1016: } 1232, { 1017: } 1233, { 1018: } 1234, { 1019: } 1236, { 1020: } 1237, { 1021: } 1239, { 1022: } 1240, { 1023: } 1242, { 1024: } 1243, { 1025: } 1245, { 1026: } 1246, { 1027: } 1247, { 1028: } 1248, { 1029: } 1250, { 1030: } 1251, { 1031: } 1253, { 1032: } 1254, { 1033: } 1256 ); yymh : array [0..yynstates-1] of Integer = ( { 0: } 0, { 1: } 0, { 2: } 1, { 3: } 2, { 4: } 3, { 5: } 4, { 6: } 5, { 7: } 6, { 8: } 7, { 9: } 8, { 10: } 9, { 11: } 10, { 12: } 11, { 13: } 12, { 14: } 13, { 15: } 14, { 16: } 15, { 17: } 16, { 18: } 17, { 19: } 18, { 20: } 19, { 21: } 20, { 22: } 21, { 23: } 22, { 24: } 23, { 25: } 24, { 26: } 25, { 27: } 26, { 28: } 27, { 29: } 28,
1,512
customer-managed keys in Azure Key Vault To enable customer-managed keys, you must use an Azure Key Vault to store your keys. You must enable both the **Soft Delete** and **Do Not Purge** properties on the key vault. Only RSA keys of size 2048 are supported with Cognitive Services encryption. For more information about keys, see **Key Vault keys** in [About Azure Key Vault keys, secrets and certificates](https://docs.microsoft.com/azure/key-vault/about-keys-secrets-and-certificates#key-vault-keys). > [!NOTE] > If the entire key vault is deleted, your data will no longer be displayed and all your models will be undeployed. All uploaded data will be deleted from Custom Translator. ### Revoke access to customer-managed keys To revoke access to customer-managed keys, use PowerShell or Azure CLI. For more information, see [Azure Key Vault PowerShell](https://docs.microsoft.com/powershell/module/az.keyvault//) or [Azure Key Vault CLI](https://docs.microsoft.com/cli/azure/keyvault). Revoking access effectively blocks access to all data in the Cognitive Services resource and your models will be undeployed, as the encryption key is inaccessible by Cognitive Services. All uploaded data will also be deleted from Custom Translator. ## Next steps * [Learn more about Azure Key Vault](https://docs.microsoft.com/azure/key-vault/key-vault-overview) ======================= File: articles/data-share/disaster-recovery.md ======================= <reponame>gbuchmsft/azure-docs --- title: Disaster recovery for Azure Data Share description: Disaster recovery for Azure Data Share author: joannapea ms.author: joanpo ms.service: data-share ms.topic: conceptual ms.date: 12/18/2019 --- # Disaster recovery for Azure Data Share In this article, we'll walk through how to configure a disaster recovery environment for Azure Data Share. Azure data center outages are rare, but can last anywhere from a few minutes to hours. Data Center outages can cause disruption to environments that are relying on data being shared by the data provider. By following the steps detailed in this article, data providers can continue to share data with their data consumers in the event of a data center outage for the primary region that is hosting your data share. ## Achieving business continuity for Azure Data Share To be prepared for a data center outage, the data provider can have a data share environment provisioned in a secondary region. There are measures that can be taken which will ensure a smooth failover in the event that a data center outage does occur. Data providers can provision secondary Azure Data Share resources in an additional region. These Data Share resources can be configured to include datasets which exist in the primary data share environment. Data consumers can be added in to the data share when configuring the DR environment, or added in at a later point in time (i.e as part of manual failover steps). If the data consumers have an active share subscription in a secondary environment provisioned for DR purposes, they can enable the snapshot schedule as part of a failover. If the data consumers do not want to subscribe to a secondary region for DR purposes, they can be invited into the secondary data share at a later point in time. Data consumers can either have an active share subscription that's idle for DR purposes, or data providers can add them in at a later point in time as part of manual failover procedures. ## Related information - [Business Continuity and Disaster Recovery](https://docs.microsoft.com/azure/best-practices-availability-paired-regions) - [Build high availability into your BCDR strategy](https://docs.microsoft.com/azure/architecture/solution-ideas/articles/build-high-availability-into-your-bcdr-strategy) ## Next steps To learn how to start sharing data, continue to the [share your data](share-your-data.md) tutorial. ======================= File: articles/active-directory/saas-apps/syncplicity-tutorial.md ======================= --- title: 'Tutorial: Azure Active Directory integration with Syncplicity | Microsoft Docs' description: Learn how to configure single sign-on between Azure Active Directory and Syncplicity. services: active-directory documentationCenter: na author: jeevansd manager: mtillman ms.reviewer: barbkess ms.assetid: 896a3211-f368-46d7-95b8-e4768c23be08 ms.service: active-directory ms.subservice: saas-app-tutorial ms.workload: identity ms.tgt_pltfrm: na ms.devlang: na ms.topic: tutorial ms.date: 06/10/2019 ms.author: jeedes --- # Tutorial: Integrate Syncplicity with Azure Active Directory In this tutorial, you'll learn how to integrate Syncplicity with Azure Active Directory (Azure AD). When you integrate Syncplicity with Azure AD, you can: * Control in Azure AD who has access to Syncplicity. * Enable your users to be automatically signed-in to Syncplicity with their Azure AD accounts. * Manage your accounts in one central location - the Azure portal. To learn more about SaaS app integration with Azure AD, see [What is application access and single sign-on with Azure Active Directory](https://docs.microsoft.com/azure/active-directory/active-directory-appssoaccess-whatis). ## Prerequisites To get started, you need the following items: * An Azure AD subscription. If you don't have a subscription, you can get one-month free trial [here](https://azure.microsoft.com/pricing/free-trial/). * Syncplicity single sign-on (SSO) enabled subscription. ## Scenario description In this tutorial, you configure and test Azure AD SSO in a test environment. Syncplicity supports **SP** initiated SSO. ## Adding Syncplicity from the gallery To configure the integration of Syncplicity into Azure AD, you need to add Syncplicity from the gallery to your list of managed SaaS apps. 1. Sign in to the [Azure portal](https://portal.azure.com) using either a work or school account, or a personal Microsoft account. 1. On the left navigation pane, select the **Azure Active Directory** service. 1. Navigate to **Enterprise Applications** and then select **All Applications**. 1. To add new application, select **New application**. 1. In the **Add from the gallery** section, type **Syncplicity** in the search box. 1. Select **Syncplicity** from results panel and then add the app. Wait a few seconds while the app is added to your tenant. ## Configure and test Azure AD SSO Configure and test Azure AD SSO with Syncplicity using a test user called **B.Simon**. For SSO to work, you need to establish a link relationship between an Azure AD user and the related user in Syncplicity. To configure and test Azure AD SSO with Syncplicity, complete the following building blocks: 1. **[Configure Azure AD SSO](#configure-azure-ad-sso)** - to enable your users to use this feature. 2. **[Configure Syncplicity SSO](#configure-syncplicity-sso)** - to configure the Single Sign-On settings on application side. 3. **[Create an Azure AD test user](#create-an-azure-ad-test-user)** - to test Azure AD single sign-on with B.Simon. 4. **[Assign the Azure AD test user](#assign-the-azure-ad-test-user)** - to enable B.Simon to use Azure AD single sign-on. 5. **[Create Syncplicity test user](#create-syncplicity-test-user)** - to have a counterpart of B.Simon in Syncplicity that is linked to the Azure AD representation of user. 6. **[Test SSO](#test-sso)** - to verify whether the configuration works. ### Configure Azure AD SSO Follow these steps to enable Azure AD SSO in the Azure portal. 1. In the [Azure portal](https://portal.azure.com/), on the **Syncplicity** application integration page, find the **Manage** section and select **Single sign-on**. 1. On the **Select a Single sign-on method** page, select **SAML**. 1. On the **Set up Single Sign-On with SAML** page, click the edit/pen icon for **Basic SAML Configuration** to edit the settings. ![Edit Basic SAML Configuration](common/edit-urls.png) 1. On the **Basic SAML Configuration** page, enter the values for the following fields: a. In the **Sign on URL** text box, type a URL using the following pattern: `https://<companyname>.syncplicity.com` b. In the **Identifier (Entity ID)** text box, type a URL using the following pattern: `https://<companyname>.syncplicity.com/sp` > [!NOTE] > These values are not real. Update these values with the actual Sign on URL and Identifier. Contact [Syncplicity Client support team](https://www.syncplicity.com/contact-us) to get these values. You can also refer to the patterns shown in the **Basic SAML Configuration** section in the Azure portal. 1. On the **Set up Single Sign-On with SAML** page, in the **SAML Signing Certificate** section, find **Certificate (Base64)** and select **Download** to download the certificate and save it on your computer. ![The Certificate download link](common/certificatebase64.png) 1. On the **Set up Syncplicity** section, copy the appropriate URL(s) based on your requirement. ![Copy configuration URLs](common/copy-configuration-urls.png) ### Configure Syncplicity SSO 1. Sign in to your **Syncplicity** tenant. 1. In the menu on the top, click **admin**, select **settings**, and then click **Custom domain and single sign-on**. ![Syncplicity](./media/syncplicity-tutorial/ic769545.png "Syncplicity") 1. On the **Single Sign-On (SSO)** dialog page, perform the following steps: ![Single Sign-On \(SSO\)](./media/syncplicity-tutorial/ic769550.png "Single Sign-On \\\(SSO\\\)") a. In the **Custom Domain** textbox, type the name of your domain. b. Select **Enabled** as **Single Sign-On Status**. c. In the **Entity Id** textbox, Paste the **Identifier (Entity ID)** value, which you have used in the **Basic SAML Configuration** in the Azure portal. d. In the **Sign-in page URL** textbox, Paste the **Login URL** which you have copied from Azure portal. e. In the **Logout page URL** textbox, Paste the **Logout URL** which you have copied from Azure portal. f. In **Identity Provider Certificate**, click **Choose file**, and then upload the certificate which you have downloaded from the Azure portal. g. Click **SAVE CHANGES**. ### Create an Azure AD test user In this section, you'll create a test user in the Azure portal called B.Simon. 1. From the left pane in the Azure portal, select **Azure Active Directory**, select **Users**, and then select **All users**. 1. Select **New user** at the top of the screen. 1. In the **User** properties, follow these steps: 1. In the **Name** field, enter `B.Simon`. 1. In the **User name** field, enter the <EMAIL>@companydomain.extension. For example, `<EMAIL>`. 1. Select the **Show password** check box, and then write down the value that's displayed in the **Password** box. 1. Click **Create**. ### Assign the Azure AD test user In this section, you'll enable B.Simon to use Azure single sign-on by granting access to Syncplicity. 1. In the Azure portal, select **Enterprise Applications**, and then select **All applications**. 1. In the applications list, select **Syncplicity**. 1. In the app's overview page, find the **Manage** section and select **Users and groups**. ![The "Users and groups" link](common/users-groups-blade.png) 1. Select **Add user**, then select **Users and groups** in the **Add Assignment** dialog. ![The Add User link](common/add-assign-user.png) 1. In the **Users and groups** dialog, select **B.Simon** from the Users list, then click the **Select** button at the bottom of the screen. 1. If you're expecting any role value in the SAML assertion, in the **Select Role** dialog, select the appropriate role for the user from the list and then click the **Select** button at the bottom of the screen. 1. In the **Add Assignment** dialog, click the **Assign** button. ### Create Syncplicity test user For Azure AD users to be able to sign in, they must be provisioned to Syncplicity application. This section describes how to create Azure AD user accounts in Syncplicity. **To provision a user account to Syncplicity, perform the following steps:** 1. Sign in to your **Syncplicity** tenant (for example: `https://company.Syncplicity.com`). 1. Click **admin** and select **user accounts** and then click **ADD A USER**. ![Manage Users](./media/syncplicity-tutorial/ic769764.png "Manage Users") 1. Type the **Email addresses** of an Azure AD account you want to provision, select **User** as **Role**, and then click **NEXT**. ![Account Information](./media/syncplicity-tutorial/ic769765.png "Account Information") > [!NOTE] > The Azure AD account holder gets an email including a link to confirm and activate the account. 1. Select a group in your company that your new user should become a member of, and then click **NEXT**. ![Group Membership](./media/syncplicity-tutorial/ic769772.png "Group Membership") > [!NOTE] > If there are no groups listed, click **NEXT**. 1. Select the folders you would like to place under Syncplicity’s control on the user’s computer, and then click **NEXT**. ![Syncplicity Folders](./media/syncplicity-tutorial/ic769773.png "Syncplicity Folders") > [!NOTE] > You can use any other Syncplicity user account creation tools or APIs provided by Syncplicity to provision Azure AD user accounts. ### Test SSO When you select the Syncplicity tile in the Access Panel, you should be automatically signed in to the Syncplicity for which you set up SSO. For more information about the Access Panel, see [Introduction to the Access Panel](https://docs.microsoft.com/azure/active-directory/active-directory-saas-access-panel-introduction). ## Additional Resources - [List of Tutorials on How to Integrate SaaS Apps with Azure Active Directory](https://docs.microsoft.com/azure/active-directory/active-directory-saas-tutorial-list) - [What is application access and single sign-on with Azure Active Directory?](https://docs.microsoft.com/azure/active-directory/active-directory-appssoaccess-whatis) - [What is Conditional Access in Azure Active Directory?](https://docs.microsoft.com/azure/active-directory/conditional-access/overview) ======================= File: articles/cognitive-services/Computer-vision/concept-detecting-adult-content.md ======================= --- title: Adult, racy, gory content - Computer Vision titleSuffix: Azure Cognitive Services description: Concepts related to detecting adult content in images using the Computer Vision APi. services: cognitive-services author: PatrickFarley manager: nitinme ms.service: cognitive-services ms.subservice: computer-vision ms.topic: conceptual ms.date: 10/01/2019 ms.author: pafarley ms.custom: seodec18 --- # Detect adult content Computer Vision can detect adult material in images so that developers can restrict the display of these images in their software. Content flags are applied with a score between zero and one so that developers can interpret the results according to their own preferences. > [!NOTE] > Much of this functionality is offered by the [Azure Content Moderator](https://docs.microsoft.com/azure/cognitive-services/content-moderator/overview) service. See this alternative for solutions to more rigorous content moderation scenarios, such as text moderation and human review workflows. ## Content flag definitions Within the "adult" classification are several different categories: - **Adult** images are defined as those which are explicitly sexual in nature and often depict nudity and sexual acts. - **Racy** images are defined as images that are sexually suggestive in nature and often contain less sexually explicit content than images tagged as **Adult**. - **Gory** images are defined as those which depict gore. ## Use the API You can detect adult content with the [Analyze Image](https://westus.dev.cognitive.microsoft.com/docs/services/5adf991815e1060e6355ad44/operations/56f91f2e778daf14a499e1fa) API. When you add the value of `Adult` to the **visualFeatures** query parameter, the API returns three boolean properties&mdash;`isAdultContent`, `isRacyContent`, and `isGoryContent`&mdash;in its JSON response. The method also returns corresponding properties&mdash;`adultScore`, `racyScore`, and `goreScore`&mdash;which represent confidence scores between zero and one for each respective category. - [Quickstart: Analyze an image (.NET SDK)](./quickstarts-sdk/csharp-analyze-sdk.md) - [Quickstart: Analyze an image (REST API)](./quickstarts/csharp-analyze.md) ======================= File: articles/sentinel/connect-fortinet.md ======================= <filename>articles/sentinel/connect-fortinet.md --- title: Connect Fortinet data to Azure Sentinel| Microsoft Docs description: Learn how to connect Fortinet data to Azure Sentinel. services: sentinel documentationcenter: na author: yelevin manager: rkarlin editor: '' ms.assetid: add92907-0d7c-42b8-a773-f570f2d705ff ms.service: azure-sentinel ms.subservice: azure-sentinel ms.devlang: na ms.topic: conceptual ms.tgt_pltfrm: na ms.workload: na ms.date: 12/30/2019 ms.author: yelevin --- # Connect Fortinet to Azure Sentinel This article explains how to connect your Fortinet appliance to Azure Sentinel. The Fortinet data connector allows you to easily connect your Fortinet logs with Azure Sentinel, to view dashboards, create custom alerts, and improve investigation. Using Fortinet on Azure Sentinel will provide you more insights into your organization’s Internet usage, and will enhance its security operation capabilities.​ ## Forward Fortinet logs to the Syslog agent Configure Fortinet to forward Syslog messages in CEF format to your Azure workspace via the Syslog agent. 1. Open the CLI on your Fortinet appliance and run the following commands: config log syslogd setting set format cef set port 514 set server <ip_address_of_Receiver> set status enable end - Replace the server **ip address** with the IP address of the agent. - Set the **syslog port** to **514** or the port set on the agent. - To enable CEF format in early FortiOS versions, you might need to run the command set **csv disable**. > [!NOTE] > For more information, go to the [Fortinet document library](https://aka.ms/asi-syslog-fortinet-fortinetdocumentlibrary). Select your version, and use the **Handbook** and **Log Message Reference**. 1. To use the relevant schema in Azure Monitor Log Analytics for the Fortinet events, search for `CommonSecurityLog`. 1. Continue to [STEP 3: Validate connectivity](connect-cef-verify.md). ## Next steps In this article, you learned how to connect Fortinet appliances to Azure Sentinel. To learn more about Azure Sentinel, see the following articles: - Learn how to [get visibility into your data, and potential threats](quickstart-get-visibility.md). - Get started [detecting threats with Azure Sentinel](tutorial-detect-threats-built-in.md). - [Use workbooks](tutorial-monitor-your-data.md) to monitor your data. ======================= File: articles/azure-signalr/includes/signalr-quickstart-run-web-application.md ======================= --- title: include file description: include file author: anthonychu ms.service: signalr ms.topic: include ms.date: 03/04/2019 ms.author: antchu ms.custom: include file --- ## Run the web application 1. To simplify your client testing, open your browser to our sample single page web application [https://azure-samples.github.io/signalr-service-quickstart-serverless-chat/demo/chat-v2/](https://azure-samples.github.io/signalr-service-quickstart-serverless-chat/demo/chat-v2/). > [!NOTE] > The source of the HTML file is located at [/docs/demo/chat-v2/index.html](https://github.com/Azure-Samples/signalr-service-quickstart-serverless-chat/blob/master/docs/demo/chat-v2/index.html). And if you'd like to host the HTML yourself, please start a local HTTP server such as [http-server](https://www.npmjs.com/package/http-server) in the */docs/demo/chat-v2* directory. Ensure the origin is added to the `CORS` setting in *local.settings.json* similar to the sample. > > ```javascript > "Host": { > "LocalHttpPort": 7071, > "CORS": "http://localhost:8080,https://azure-samples.github.io", > "CORSCredentials": true > } > > ``` 1. When prompted for the function app base URL, enter `http://localhost:7071`. 1. Enter a username when prompted. 1. The web application calls the *GetSignalRInfo* function in the function app to retrieve the connection information to connect to Azure SignalR Service. When the connection is complete, the chat message input box appears. 1. Type a message and press enter. The application sends the message to the *SendMessage* function in the Azure Function app, which then uses the SignalR output binding to broadcast the message to all connected clients. If everything is working correctly, the message should appear in the application. ![Run the application](../media/signalr-quickstart-azure-functions-csharp/signalr-quickstart-run-application.png) 1. Open another instance of the web application in a different browser window. You will see that any messages sent will appear in all instances of the application. ======================= File: articles/service-fabric/run-to-completion.md ======================= --- title: RunToCompletion semantics in Service Fabric description: Describes RunToCompletion semantics in Service Fabric. author: shsha-msft ms.topic: conceptual ms.date: 03/11/2020 ms.author: shsha --- # RunToCompletion Starting with version 7.1, Service Fabric supports **RunToCompletion** semantics for [containers][containers-introduction-link] and [guest executable][guest-executables-introduction-link] applications. These semantics enable applications and services which complete a task and exit, in contrast to, always running applications and services. Before proceeding with this article, we recommend getting familiar with the [Service Fabric application model][application-model-link] and the [Service Fabric hosting model][hosting-model-link]. > [!NOTE] > RunToCompletion semantics are currently not supported for services written using the [Reliable Services][reliable-services-link] programming model. ## RunToCompletion semantics and specification RunToCompletion semantics can be specified as an **ExecutionPolicy** when [importing the ServiceManifest][application-and-service-manifests-link]. The specified policy is inherited by all the CodePackages comprising the ServiceManifest. The following ApplicationManifest.xml snippet provides an example. ```xml <ServiceManifestImport> <ServiceManifestRef ServiceManifestName="RunToCompletionServicePackage" ServiceManifestVersion="1.0"/> <Policies> <ExecutionPolicy Type="RunToCompletion" Restart="OnFailure"/> </Policies> </ServiceManifestImport> ``` **ExecutionPolicy** allows the following two attributes: * **Type:** **RunToCompletion** is currently the only allowed value for this attribute. * **Restart:** This attribute specifies the restart policy that is applied to CodePackages comprising the ServicePackage, on failure. A CodePackage exiting with a **non-zero exit code** is considered to have failed. Allowed values for this attribute are **OnFailure** and **Never** with **OnFailure** being the default. With restart policy set to **OnFailure**, if any CodePackage fails **(non-zero exit code)**, it is restarted, with back-offs between repeated failures. With restart policy set to **Never**, if any CodePackage fails, the deployment status of the DeployedServicePackage is marked as **Failed** but other CodePackages are allowed to continue execution. If all the CodePackages comprising the ServicePackage run to successful completion **(exit code 0)**, the deployment status of the DeployedServicePackage is marked as **RanToCompletion**. ## Complete example using RunToCompletion semantics Let's look at a complete example using RunToCompletion semantics. > [!IMPORTANT] > The following example assumes familiarity with creating [Windows container applications using Service Fabric and Docker][containers-getting-started-link]. > > This example references mcr.microsoft.com/windows/nanoserver:1809. Windows Server containers are not compatible across all versions of a host OS. To learn more, see [Windows Container Version Compatibility](https://docs.microsoft.com/virtualization/windowscontainers/deploy-containers/version-compatibility). The following ServiceManifest.xml describes a ServicePackage consisting of two CodePackages, which represent containers. *RunToCompletionCodePackage1* just logs a message to **stdout** and exits. *RunToCompletionCodePackage2* pings the loopback address for a while and then exits with an exit code of either **0**, **1** or **2**. ```xml <?xml version="1.0" encoding="UTF-8"?> <ServiceManifest Name="WindowsRunToCompletionServicePackage" Version="1.0" xmlns="http://schemas.microsoft.com/2011/01/fabric" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <Description>Windows RunToCompletion Service</Description> <ServiceTypes> <StatelessServiceType ServiceTypeName="WindowsRunToCompletionServiceType" UseImplicitHost="true"/> </ServiceTypes> <CodePackage Name="RunToCompletionCodePackage1" Version="1.0"> <EntryPoint> <ContainerHost> <ImageName>mcr.microsoft.com/windows/nanoserver:1809</ImageName> <Commands>/c,echo Hi from RunToCompletionCodePackage1 &amp;&amp; exit 0</Commands> <EntryPoint>cmd</EntryPoint> </ContainerHost> </EntryPoint> </CodePackage> <CodePackage Name="RunToCompletionCodePackage2" Version="1.0"> <EntryPoint> <ContainerHost> <ImageName>mcr.microsoft.com/windows/nanoserver:1809</ImageName> <Commands>/v,/c,ping 127.0.0.1 &amp;&amp; set /a exitCode=%random% % 3 &amp;&amp; exit!exitCode!</Commands> <EntryPoint>cmd</EntryPoint> </ContainerHost> </EntryPoint> </CodePackage> </ServiceManifest> ``` The following ApplicationManifest.xml describes an application based on the ServiceManifest.xml discussed above. It specifies **RunToCompletion** **ExecutionPolicy** for *WindowsRunToCompletionServicePackage* with a restart policy of **OnFailure**. Upon activation of *WindowsRunToCompletionServicePackage*, its constituent CodePackages will be started. *RunToCompletionCodePackage1* should exit successfully on the first activation. However, *RunToCompletionCodePackage2* can fail **(non-zero exit code)**, in which case it will be restarted since the restart policy is **OnFailure**. ```xml <?xml version="1.0" encoding="UTF-8"?> <ApplicationManifest ApplicationTypeName="WindowsRunToCompletionApplicationType" ApplicationTypeVersion="1.0" xmlns="http://schemas.microsoft.com/2011/01/fabric" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <Description>Windows RunToCompletion Application</Description> <ServiceManifestImport> <ServiceManifestRef ServiceManifestName="WindowsRunToCompletionServicePackage" ServiceManifestVersion="1.0"/> <Policies> <ExecutionPolicy Type="RunToCompletion" Restart="OnFailure"/> </Policies> </ServiceManifestImport> <DefaultServices> <Service Name="WindowsRunToCompletionService" ServicePackageActivationMode="ExclusiveProcess"> <StatelessService ServiceTypeName="WindowsRunToCompletionServiceType" InstanceCount="1"> <SingletonPartition /> </StatelessService> </Service> </DefaultServices> </ApplicationManifest> ``` ## Querying deployment status of a DeployedServicePackage Deployment status of a DeployedServicePackage can be queried from PowerShell using [Get-ServiceFabricDeployedServicePackage][deployed-service-package-link] or from C# using [FabricClient][fabric-client-link] API [GetDeployedServicePackageListAsync(String, Uri, String)][deployed-service-package-fabricclient-link] ## Considerations when using RunToCompletion semantics The following points should be noted for the current RunToCompletion support. * These semantics are only supported for [containers][containers-introduction-link] and [guest executable][guest-executables-introduction-link] applications. * Upgrade scenarios for applications with RunToCompletion semantics are not allowed. Users should delete and recreate such applications, if necessary. * Failover events can cause CodePackages to re-execute after successful completion, on the same node, or other nodes of the cluster. Examples of failover events are, node restarts and Service Fabric runtime upgrades on a node. ## Next steps See the following articles for related information. * [Service Fabric and containers.][containers-introduction-link] * [Service Fabric and guest executables.][guest-executables-introduction-link] <!-- Links --> [containers-introduction-link]: service-fabric-containers-overview.md [containers-getting-started-link]: service-fabric-get-started-containers.md [guest-executables-introduction-link]: service-fabric-guest-executables-introduction.md [reliable-services-link]: service-fabric-reliable-services-introduction.md [application-model-link]: service-fabric-application-model.md [hosting-model-link]: service-fabric-hosting-model.md [application-and-service-manifests-link]: service-fabric-application-and-service-manifests.md [setup-entry-point-link]: service-fabric-run-script-at-service-startup.md [deployed-service-package-working-with-link]: service-fabric-hosting-model.md#work-with-a-deployed-service-package [deployed-code-package-link]: https://docs.microsoft.com/powershell/module/servicefabric/get-servicefabricdeployedcodepackage [deployed-service-package-link]: https://docs.microsoft.com/powershell/module/servicefabric/get-servicefabricdeployedservicePackage [fabric-client-link]: https://docs.microsoft.com/dotnet/api/system.fabric.fabricclient [deployed-service-package-fabricclient-link]: https://docs.microsoft.com/dotnet/api/system.fabric.fabricclient.queryclient.getdeployedservicepackagelistasync ======================= File: articles/internet-peering/includes/exchange-portal-configuration.md ======================= --- title: include file titleSuffix: Azure description: include file services: internet-peering author: prmitiki ms.service: internet-peering ms.topic: include ms.date: 11/27/2019 ms.author: prmitiki --- 1. On the **Create a Peering** page, on the **Configuration** tab, fill in the boxes as shown. > [!div class="mx-imgBorder"] >![Create a Peering page Exchange peering type](../media/setup-exchange-conf-tab.png) * For **Peering type**, select **Exchange**. * Select **SKU** as **Basic Free**. * Select the **Metro** location where you want to set up peering. > [!NOTE] > If you already have peering connections with Microsoft in the selected **Metro** location and you're using the portal for the first time to set up peering in that location, your existing peering connections will be listed in the **Peering connections** section as shown. Microsoft will automatically convert these peering connections to an Azure resource so that you can manage them all along with the new connections in one place. For more information, see [Convert a legacy Exchange peering to an Azure resource by using the portal](../howto-legacy-exchange-portal.md). > 1. Under **Peering connections**, select **Create new** to add a line for each new connection you want to set up. * To configure or modify connection settings, select the edit button for a line. > [!div class="mx-imgBorder"] >![Edit button](../media/setup-exchange-conf-tab-edit.png) * To delete a line, select **...** > **Delete**. > [!div class="mx-imgBorder"] >![Delete button](../media/setup-exchange-conf-tab-delete.png) * You're required to provide all the settings for a connection, as shown here. > [!div class="mx-imgBorder"] >![Exchange Peering Connection page](../media/setup-exchange-conf-tab-connection.png) 1. Select the **Peering facility** where the connection needs to be set up. 1. In the **IPv4 address** and **IPv6 address** boxes, enter the IPv4 and IPv6 addresses, respectively, that would be configured in Microsoft routers by using the neighbor command. 1. Enter the number of IPv4 and IPv6 prefixes you'll advertise in the **Maximum advertised IPv4 addresses** and **Maximum advertised IPv6 addresses** boxes, respectively. 1. Select **OK** to save your connection settings. 1. Repeat the step to add more connections at any facility where Microsoft is colocated with your network, within the **Metro** selected previously. 1. After you add all the required connections, select **Review + create**. > [!div class="mx-imgBorder"] >![Peering Configuration tab](../media/setup-exchange-conf-tab-final.png) 1. Notice that the portal runs basic validation of the information you entered. A ribbon at the top displays the message *Running final validation...*. > [!div class="mx-imgBorder"] >![Peering Validation tab](../media/setup-direct-review-tab-validation.png) 1. After the message changes to *Validation passed*, verify your information. Submit the request by selecting **Create**. To modify your request, select **Previous** and repeat the steps. > [!div class="mx-imgBorder"] >![Peering submission](../media/setup-exchange-review-tab-submit.png) 1. After you submit the request, wait for the deployment to finish. If deployment fails, contact [Microsoft peering](mailto:<EMAIL>). A successful deployment appears as shown here. > [!div class="mx-imgBorder"] >![Peering success](../media/setup-direct-success.png) ======================= File: articles/blockchain/workbench/includes/preview.md ======================= <reponame>gbuchmsft/azure-docs --- author: PatAltimore ms.service: azure-blockchain ms.topic: include ms.date: 09/09/2019 ms.author: patricka --- > [!IMPORTANT] > Azure Blockchain Workbench is currently in public preview. > For more information, see [Supplemental Terms of Use for Microsoft Azure Previews](https://azure.microsoft.com/support/legal/preview-supplemental-terms/). > Azure Blockchain Workbench is provided without a service level agreement. > Use the [Azure Blockchain forum](https://aka.ms/workbenchforum) for support. ======================= File: includes/iot-hub-include-python-installation-notes.md ======================= --- title: include file description: include file services: iot-hub author: robinsh ms.service: iot-hub ms.topic: include ms.date: 07/24/2019 ms.author: robinsh ms.custom: include file --- * An active Azure account. (If you don't have an account, you can create a [free account](https://azure.microsoft.com/pricing/free-trial/) in just a couple of minutes.) * [Python 2.x or 3.x](https://www.python.org/downloads/). Make sure to use the 32-bit or 64-bit installation as required by your setup. When prompted during the installation, make sure to add Python to your platform-specific environment variable. If you are using Python 2.x, you may need to [install or upgrade *pip*, the Python package management system](https://pip.pypa.io/en/stable/installing/). * If needed, install the [azure-iot-device](https://pypi.org/project/azure-iot-device/) package, using the command `pip install azure-iot-device` * If needed, install the [azure-iothub-service-client](https://pypi.org/project/azure-iothub-service-client/) package, using the command `pip install azure-iothub-service-client` ======================= File: articles/active-directory/user-help/my-account-portal-sign-ins-page.md ======================= <filename>articles/active-directory/user-help/my-account-portal-sign-ins-page.md --- title: View and search your recent sign-in activity from the My Sign-in (preview) page - Azure Active Directory | Microsoft Docs description: Details about how to view and search your recent sign-in activity from the My Sign-ins page of the My Account portal. services: active-directory author: curtand manager: daveba ms.reviewer: rhicock ms.service: active-directory ms.workload: identity ms.subservice: user-help ms.topic: end-user-help ms.date: 10/28/2019 ms.author: curtand --- # View and search your recent sign-in activity from the My Sign-ins (preview) page You can view all of your recent work or school account sign-in activity, from the **My Sign-ins** page of the **My Account** portal. Reviewing your sign-in history helps you to check for unusual activity by helping you to see: - If someone is trying to guess your password. - If an attacker successfully signed in to your account, and from what location. - What apps the attacker tried to access. ## View your recent sign-in activity 1. Sign in to your work or school account and then go to your https://myaccount.microsoft.com/ page. 2. Select **My Sign-ins (preview)** from the left navigation pane or select the **Review recent activity** link from the **My sign-ins (preview)** block. ![My Account page, showing highlighted Recent activity links](media/my-account-portal/my-account-portal-sign-ins.png) 3. Expand and review each of the sign-in items, making sure that you recognize each one. If you find a sign-in item that doesn't look familiar, we highly recommend you change your password to help protect your account if it was compromised. ![Recent activity page with expanded sign-in details](media/my-account-portal/my-account-portal-sign-ins-page.png) ### If you see a Successful sign-in You should recognize your own activity as being normal. However, if you notice a Successful sign-in from strange location, browser, or operating system, it could mean that an attacker has gained access to your account. In this situation, we recommend you immediately change your password, and then go to the [Security info](https://mysignins.microsoft.com/security-info) page to update your security settings. Before you determine something is incorrect, make sure you're not seeing a false positive (where the item looks questionable, but is okay). For example, we determine your approximate location and map based on your IP Address. Mobile networks are especially hard to pinpoint since they sometimes route traffic through distant locations. So, if you signed in using your mobile device in Washington state, the location might show the sign-in coming from California. Because of this, we strongly suggest that you check more details, beyond just the location. You should also make sure the operating system, browser, and app all make sense, too. ### If you see an Unsuccessful sign-in An unsuccessful sign-in, with no session activity, means that your primary verification method (username/password) failed. This could mean that you mistyped your username or password, but it could also mean that an attacker was trying to guess your password. If you think it was attacker trying unsuccessfully to guess your password, you don't have to change your password, but we strongly suggest that you register for Azure Multi-Factor Authentication (MFA). With MFA, even if the hacker eventually guesses your password, it won't be enough to access your account. If you see an unsuccessful sign-in, with a note under Session activity that says, **Additional verification failed, invalid code**, it means that your primary authentication (username/password) succeeded, but MFA failed. If this was an attacker, they correctly guessed your password but were still unable to pass the MFA challenge. In this case, we recommend that you still change your password, since the attacker got that part right, and then go to the [Security info](https://mysignins.microsoft.com/security-info) page to update your security settings. ## Search for specific sign-in activity You can search your recent sign-in activity by any of the available information. For example, you can search for your recent sign-in activity by operating system, location, app, and so on. 1. On the **Review recent activity** page, type the information you want to search for into the **Search** bar. For example, type `My Account` to search for all activity collected by the My Account app. 2. Select the **Search** button to begin searching. ![Recent Activity page, showing highlighted search bar, search button, and results](media/my-account-portal/my-account-portal-sign-ins-page-search.png) ## Next steps After viewing your recent sign-in activity, you can: - View or manage your [security info](user-help-security-info-overview.md). - View or manage your connected [devices](my-account-portal-devices-page.md). - View or manage your [organizations](my-account-portal-organizations-page.md). - View how your organization [uses your privacy-related data](my-account-portal-privacy-page.md). ======================= File: articles/postgresql/howto-create-manage-server-portal.md ======================= --- title: Manage Azure Database for PostgreSQL - Azure portal description: Learn how to manage an Azure Database for PostgreSQL server from the Azure portal. author: rachel-msft ms.author: raagyema ms.service: postgresql ms.topic: conceptual ms.date: 11/20/2019 --- # Manage an Azure Database for PostgreSQL server using the Azure portal This article shows you how to manage your Azure Database for PostgreSQL servers. Management tasks include compute and storage scaling, admin password reset, and viewing server details. ## Sign in Sign in to the [Azure portal](https://portal.azure.com). ## Create a server Visit the [quickstart](quickstart-create-server-database-portal.md) to learn how to create and get started with an Azure Database for PostgreSQL server. ## Scale compute and storage After server creation you can scale between the General Purpose and Memory Optimized tiers as your needs change. You can also scale compute and memory by increasing or decreasing vCores. Storage can be scaled up (however, you cannot scale storage down). ### Scale between General Purpose and Memory Optimized tiers You can scale from General Purpose to Memory Optimized and vice-versa. Changing to and from the Basic tier after server creation is not supported. 1. Select your server in the Azure portal. Select **Pricing tier**, located in the **Settings** section. 2. Select **General Purpose** or **Memory Optimized**, depending on what you are scaling to. ![change-pricing-tier](./media/howto-create-manage-server-portal/change-pricing-tier.png) > [!NOTE] > Changing tiers causes a server restart. 4. Select **OK** to save changes. ### Scale vCores up or down 1. Select your server in the Azure portal. Select **Pricing tier**, located in the **Settings** section. 2. Change the **vCore** setting by moving the slider to your desired value. ![scale-compute](./media/howto-create-manage-server-portal/scaling-compute.png) > [!NOTE] > Scaling vCores causes a server restart. 3. Select **OK** to save changes. ### Scale storage up 1. Select your server in the Azure portal. Select **Pricing tier**, located in the **Settings** section. 2. Change the **Storage** setting by moving the slider up to your desired value. ![scale-storage](./media/howto-create-manage-server-portal/scaling-storage.png) > [!NOTE] > Storage cannot be scaled down. 3. Select **OK** to save changes. ## Update admin password You can change the administrator role's password using the Azure portal. 1. Select your server in the Azure portal. In the **Overview** window select **Reset password**. ![overview](./media/howto-create-manage-server-portal/overview-reset-password.png) 2. Enter a new password and confirm the password. The textbox will prompt you about password complexity requirements. ![reset-password](./media/howto-create-manage-server-portal/reset-password.png) 3. Select **OK** to save the new password. ## Delete a server You can delete your server if you no longer need it. 1. Select your server in the Azure portal. In the **Overview** window select **Delete**. ![delete](./media/howto-create-manage-server-portal/overview-delete.png) 2. Type the name of the server into the input box to confirm that this is the server you want to delete. ![confirm-delete](./media/howto-create-manage-server-portal/confirm-delete.png) > [!NOTE] > Deleting a server is irreversible. 3. Select **Delete**. ## Next steps - Learn about [backups and server restore](howto-restore-server-portal.md) - Learn about [tuning and monitoring options in Azure Database for PostgreSQL](concepts-monitoring.md) ======================= File: articles/firewall/remote-work-support.md ======================= --- title: Azure Firewall remote work support description: This article shows how Azure Firewall can support your remote work force requirements. services: firewall author: vhorne ms.service: firewall ms.topic: conceptual ms.date: 05/04/2020 ms.author: victorh --- # Azure Firewall remote work support Azure Firewall is a managed, cloud-based network security service that protects your Azure virtual network resources. It's a fully stateful firewall as a service with built-in high availability and unrestricted cloud scalability. ## Virtual Desktop Infrastructure (VDI) deployment support Work from home policies requires many IT organizations to address fundamental changes in capacity, network, security, and governance. Employees aren't protected by the layered security policies associated with on-premises services while working from home. Virtual Desktop Infrastructure (VDI) deployments on Azure can help organizations rapidly respond to this changing environment. However, you need a way to protect inbound/outbound Internet access to and from these VDI deployments. You can use Azure Firewall [DNAT rules](rule-processing.md) along with its [threat intelligence](threat-intel.md) based filtering capabilities to protect your VDI deployments. ## Azure Windows Virtual Desktop support Windows Virtual Desktop is a comprehensive desktop and app virtualization service running in Azure. It’s the only virtual desktop infrastructure (VDI) that delivers simplified management, multi-session Windows 10, optimizations for Office 365 ProPlus, and support for Remote Desktop Services (RDS) environments. You can deploy and scale your Windows desktops and apps on Azure in minutes, and get built-in security and compliance features. Windows Virtual Desktop doesn't require you to open any inbound access to your virtual network. However, you must allow a set of outbound network connections for the Windows Virtual Desktop virtual machines that run in your virtual network. For more information, see [Use Azure Firewall to protect Window Virtual Desktop deployments](protect-windows-virtual-desktop.md). ## Next steps Learn more about [Windows Virtual Desktop](https://docs.microsoft.com/azure/virtual-desktop/). ======================= File: articles/azure-maps/tutorial-iot-hub-maps.md ======================= <filename>articles/azure-maps/tutorial-iot-hub-maps.md --- title: 'Tutorial: Implement IoT spatial analytics | Microsoft Azure Maps' description: Integrate IoT Hub with Microsoft Azure Maps service APIs. author: philmea ms.author: philmea ms.date: 11/12/2019 ms.topic: tutorial ms.service: azure-maps services: azure-maps manager: philmea ms.custom: mvc #Customer intent: As a customer, I want to build an IoT system so that I can use Azure Maps APIs for spatial analytics on the device data. --- # Tutorial: Implement IoT spatial analytics using Azure Maps In an IoT scenario, it's common to capture and track relevant events that occur in space and time. Example scenarios include fleet management, asset tracking, mobility, and smart city applications. This tutorial guides you through a solution pattern using the Azure Maps APIs. Relevant events are captured by IoT Hub, using the event subscription model provided by the Event Grid. In this tutorial you will: > [!div class="checklist"] > * Create an IoT Hub. > * Upload geofence area in the Azure Maps, Data service using the Data Upload API. > * Create a function in Azure Functions, implementing business logic based on Azure Maps spatial analytics. > * Subscribe to IoT device telemetry events from the Azure function via Event Grid. > * Filter the telemetry events using IoT Hub message routing. > * Create a storage account to store relevant event data. > * Simulate an in-vehicle IoT device. ## Use case This solution demonstrates a scenario where a car rental company plans to monitor and log events for its rental cars. Car rental companies usually rent cars to a specific geographic region. They need to track the cars whereabouts while they are rented. Instances of a car leaving the chosen geographic region must be logged. Logging data ensures policies, fees, and other business aspects would be handled properly. In our use case, the rental cars are equipped with IoT devices that regularly send telemetry data to Azure IoT Hub. The telemetry includes the current location and indicates whether the car's engine is running. The device location schema adheres to the IoT [Plug and Play schema for geospatial data](https://github.com/Azure/IoTPlugandPlay/blob/master/Schemas/geospatial.md). The rental car's device telemetry schema looks like: ```JSON { "data": { "properties": { "Engine": "ON" }, "systemProperties": { "iothub-content-type": "application/json", "iothub-content-encoding": "utf-8", "iothub-connection-device-id": "ContosoRentalDevice", "iothub-connection-auth-method": "{\"scope\":\"device\",\"type\":\"sas\",\"issuer\":\"iothub\",\"acceptingIpFilterRule\":null}", "iothub-connection-auth-generation-id": "636959817064335548", "iothub-enqueuedtime": "2019-06-18T00:17:20.608Z", "iothub-message-source": "Telemetry" }, "body": { "location": { "type": "Point", "coordinates": [ -77.025988698005662, 38.9015330523316 ] } } } } ``` Let's use in-vehicle device telemetry to accomplish our goal. We want to execute geofencing rules. And, we want to respond whenever we receive an event indicating the car has moved. To do so, we'll subscribe to the device telemetry events from IoT Hub via Event Grid. There are several ways to subscribe to Event Grid, in this tutorial we use Azure Functions. Azure Functions reacts to events published in the Event Grid. It also implements car rental business logic, which is based on Azure Maps spatial analytics. Code inside Azure function checks whether the vehicle has left the geofence. If the vehicle left the geofence, the Azure function gathers additional information such as the address associated to the current location. The function also implements logic to store meaningful event data in a data blob storage that helps provide description of the event circumstances. The event circumstances can be helpful to the car rental company and the rental customer. The following diagram gives you a high-level overview of the system. <center> ![System overview](./media/tutorial-iot-hub-maps/system-diagram.png) </center> The following figure represents the geofence area highlighted in blue. The rental vehicle's route is indicated by a green line. ![Geofence route](./media/tutorial-iot-hub-maps/geofence-route.png) ## Prerequisites ### Create a resource group To complete the steps in this tutorial, you first need to create a resource group in the Azure portal. To create a resource group, do the following steps: 1. Sign in to the [Azure portal](https://portal.azure.com). 2. Select **Resource groups**. ![Resource groups](./media/tutorial-iot-hub-maps/resource-group.png) 3. Under **Resource groups**, select **Add**. ![Add resource group](./media/tutorial-iot-hub-maps/add-resource-group.png) 4. Enter the following property values: * **Subscription:** Select your Azure subscription. * **Resource group:** Enter "ContosoRental" as the resource group name. * **Region:** Select a region for the resource group. ![Resource group details](./media/tutorial-iot-hub-maps/resource-details.png) Select **Review + create**, and then select **Create** on the next page. ### Create an Azure Maps account To implement business logic based on Azure Maps spatial analytics, we need to create an Azure Maps account in the resource group we created. Follow instructions in [Create an account](quick-demo-map-app.md#create-an-account-with-azure-maps) to create an Azure Maps account subscription with S1 pricing tier. Follow the steps in [get primary key](quick-demo-map-app.md#get-the-primary-key-for-your-account) to obtain your primary key for your account. For more information on authentication in Azure Maps, see [manage authentication in Azure Maps](how-to-manage-authentication.md). ### Create a storage account To log event data, we'll create a general-purpose **v2storage** that provides access to all of the Azure Storage services: blobs, files, queues, tables, and disks. We'll need to place this storage account in the "ContosoRental" resource group to store data as blobs. To create a storage account, follow instruction in [create a storage account](https://docs.microsoft.com/azure/storage/common/storage-quickstart-create-account?toc=%2Fazure%2Fstorage%2Fblobs%2Ftoc.json&tabs=azure-portal). Next we'll need to create a container to store blobs. Follow the steps below to do so: 1. In your "storage account - blob, file, table, queue", navigate to Containers. ![blobs](./media/tutorial-iot-hub-maps/blobs.png) 2. Click the container button at the top left and name your container "contoso-rental-logs" and click "OK". ![blob-container](./media/tutorial-iot-hub-maps/blob-container.png) 3. Navigate to the **Access keys** blade in your storage account and copy the "storage account name" and "access key". They're needed in a later step. ![access-keys](./media/tutorial-iot-hub-maps/access-keys.png) Now, we have a storage account and a container to log event data. Next, we'll create an IoT hub. ### Create an IoT Hub The IoT Hub is a managed service in the cloud. The IoT Hub acts as a central message hub for bi-directional communication between an IoT application and the devices managed by it. In order to route device telemetry messages to an Event Grid, create an IoT Hub within the "ContosoRental" resource group. Set up a message route integration where we will filter messages based on the car's engine status. We will also send device telemetry messages to the Event Grid whenever the car is moving. > [!Note] > IoT Hub's functionality to publish device telemetry events on Event Grid is in Public preview. Public preview features are available in all regions except **East US, West US, West Europe, Azure Government, Azure China 21Vianet,** and **Azure Germany**. Create an Iot Hub by following the steps in [create an IoT Hub section](https://docs.microsoft.com/azure/iot-hub/quickstart-send-telemetry-dotnet#create-an-iot-hub). ### Register a device In order to connect to the IoT Hub, a device must be registered. To register a device with IoT hub, follow the steps below: 1. In your IoT Hub, click on the "IoT devices" blade and click "New". ![add-device](./media/tutorial-iot-hub-maps/add-device.png) 2. On the create a device page, name your IoT device, and click "Save". ![register-device](./media/tutorial-iot-hub-maps/register-device.png) 3. Save the **Primary Connection String** of your device to use it in a later step, in which you need to change a placeholder with this connection string. ![add-device](./media/tutorial-iot-hub-maps/connection-string.png) ## Upload geofence We'll use the [Postman application](https://www.getpostman.com) to [upload the geofence](https://docs.microsoft.com/azure/azure-maps/geofence-geojson) to the Azure Maps service using the Azure Maps Data Upload API. Any event when the car is outside this geofence will be logged. Open the Postman app and follow the steps below to upload the geofence using the Azure Maps, Data Upload API. 1. In the Postman app, click new | Create new, and select Request. Enter a Request name for Upload geofence data, select a collection or folder to save it to, and click Save. ![Upload geofences using Postman](./media/tutorial-iot-hub-maps/postman-new.png) 2. Select POST HTTP method on the builder tab and enter the following URL to make a POST request. ```HTTP https://atlas.microsoft.com/mapData/upload?subscription-key={subscription-key}&api-version=1.0&dataFormat=geojson ``` The "geojson" value against the `dataFormat` parameter in the URL path represents the format of the data being uploaded. 3. Click **Params**, and enter the following Key/Value pairs to be used for the POST request URL. Replace subscription-key value with your Azure Maps key. ![Key-Value params Postman](./media/tutorial-iot-hub-maps/postman-key-vals.png) 4. Click **Body** then select **raw** input format and choose **JSON (application/text)** as the input format from the drop-down list. Open the JSON data file [here](https://raw.githubusercontent.com/Azure-Samples/iothub-to-azure-maps-geofencing/master/src/Data/geofence.json?token=<KEY>), and copy the Json in the body section as the data to upload and click **Send**. ![post data](./media/tutorial-iot-hub-maps/post-json-data.png) 5. Review the response headers. Upon a successful request, the **Location** header will contain the status URI to check the current status of the upload request. The status URI will be of the following format. ```HTTP https://atlas.microsoft.com/mapData/{uploadStatusId}/status?api-version=1.0 ``` 6. Copy your status URI and append a `subscription-key` parameter to it. Assign the value of your Azure Maps account subscription key to the `subscription-key` parameter. The status URI format should be like the one below, and `{Subscription-key}` replaced with your subscription key. ```HTTP https://atlas.microsoft.com/mapData/{uploadStatusId}/status?api-version=1.0&subscription-key={Subscription-key} ``` 7. To get the, `udId` open a new tab in the Postman app and select GET HTTP method on the builder tab and make a GET request at the status URI. If your data upload was successful, you'll receive a udId in the response body. Copy the udId for later use. ```JSON { "udid" : "{udId}" } ``` Next we'll create an Azure Function within the "ContosoRental" resource group and then set up a message route in IoT Hub to filter device telemetry messages. ## Create an Azure Function and add an Event Grid subscription Azure Functions is a serverless compute service which enables us to run code on-demand, without the need to explicitly provision or manage compute infrastructure. To learn more about Azure Functions, take a look at the [Azure functions](https://docs.microsoft.com/azure/azure-functions/functions-overview) documentation. The logic we implement in the function is using the location data coming from the in-vehicle device telemetry for assessing the geofence status. In case a given vehicle goes outside the geofence, the function will gather more information like the address of the location via the [Get Search Address Reverse API](https://docs.microsoft.com/rest/api/maps/search/getsearchaddressreverse). This API translates a given location coordinate into a human understandable street address. All relevant event info is then kept in the blob store. Step 5 below points to the executable code implementing such logic. Follow the steps below to create an Azure Function that sends data logs to the blob container in the blob storage account and add an Event Grid subscription to it. 1. In the Azure portal dashboard, select create a resource. Select **Compute** from the list of available resource types and then select **Function App**. ![create-resource](./media/tutorial-iot-hub-maps/create-resource.png) 2. On the **Function App** creation page, name your function app. Under **Resource Group**, select **Use existing**, and select "ContosoRental" from the drop-down list. Select ".NET Core" as the Runtime Stack. Under **Hosting**, for **Storage account**, select the storage account name from a prior step. In our prior step, we named the storage account **v2storage**. Then, select **Review+Create**. ![create-app](./media/tutorial-iot-hub-maps/rental-app.png) 2. Review the function app details, and select "Create". 3. Once the app is created, we need to add a function to it. Go to the function app. Click **New function** to add a function, and choose **In-Portal** as the development environment. Then, select **Continue**. ![create-function](./media/tutorial-iot-hub-maps/function.png) 4. Choose **More templates** and click **Finish and view templates**. 5. Select the template with an **Azure Event Grid Trigger**. Install extensions if prompted, name the function, and select **Create**. ![function-template](./media/tutorial-iot-hub-maps/eventgrid-funct.png) The **Azure Event Hub Trigger** and the **Azure Event Grid Trigger** have similar icons. Make sure you select the **Azure Event Grid Trigger**. 6. Copy the [C# code](https://github.com/Azure-Samples/iothub-to-azure-maps-geofencing/blob/master/src/Azure%20Function/run.csx) into your function. 7. In the C# script, replace the following parameters. Click **Save**. Don't click **Run** yet * Replace the **SUBSCRIPTION_KEY** with your Azure Maps account primary subscription key. * Replace the **UDID** with the udId of the geofence you uploaded, * The **CreateBlobAsync** function in the script creates a blob per event in the data storage account. Replace the **ACCESS_KEY**, **ACCOUNT_NAME**, and **STORAGE_CONTAINER_NAME** with your storage account's access key, account name, and data storage container. 10. Click on **Add Event Grid subscription**. ![add-event-grid](./media/tutorial-iot-hub-maps/add-egs.png) 11. Fill out subscription details, under **EVENT SUBSCRIPTION DETAILS** name your event subscription. For Event Schema choose "Event Grid Schema". Under **TOPIC DETAILS** select "Azure IoT Hub Accounts" as Topic type. Choose the same subscription you used for creating the resource group, select "ContosoRental" as the "Resource Group". Choose the IoT Hub you created as a "Resource". Pick **Device Telemetry** as Event Type. After choosing these options, you'll see the "Topic Type" change to "IoT Hub" automatically. ![event-grid-subscription](./media/tutorial-iot-hub-maps/af-egs.png) ## Filter events using IoT Hub message routing After you add an Event Grid subscription to the Azure Function, you'll see a default message route to Event Grid in IoT Hub's **Message Routing** blade. Message routing enables you to route different data types to various endpoints. For example, you can route device telemetry messages, device life-cycle events, and device twin change events. To learn more about IoT hub message routing, see [Use IoT Hub message routing](https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-messages-d2c). ![hub-EG-route](./media/tutorial-iot-hub-maps/hub-route.png) In our example scenario, we want to filter out all messages where the rental vehicle is moving. In order to publish such device telemetry events to Event Grid, we'll use the routing query to filter the events where the `Engine` property is **"ON"**. There are various ways to query IoT device-to-cloud messages, to learn more about message routing syntax, see [IoT Hub message routing](https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-routing-query-syntax). To create a routing query, click on the **RouteToEventGrid** route and replace the **Routing query** with **"Engine='ON'"** and click **Save**. Now IoT hub will only publish device telemetry where the Engine is ON. ![hub-EG-filter](./media/tutorial-iot-hub-maps/hub-filter.png) ## Send telemetry data to IoT Hub Once our Azure Function is up and running, we can now send telemetry data to the IoT Hub, which will route it to the Event Grid. Let's use a C# application to simulate location data for an in-vehicle device of a rental car. To run the application, you need the.NET Core SDK 2.1.0 or greater on your development machine. Follow the steps below to send simulated telemetry data to IoT Hub. 1. Download the [rentalCarSimulation](https://github.com/Azure-Samples/iothub-to-azure-maps-geofencing/tree/master/src/rentalCarSimulation) C# project. 2. Open the simulatedCar.cs file in a text editor of your choice and replace the value of the `connectionString` with the one you saved when you registered the device and save changes to the file. 3. Make sure you have.NET Core installed on your machine. In your local terminal window, navigate to the root folder of the C# project and run the following command to install the required packages for simulated device application: ```cmd/sh dotnet restore ``` 4. In the same terminal, run the following command to build and run the rental car simulation application: ```cmd/sh dotnet run ``` Your local terminal should look like the one below. ![Terminal output](./media/tutorial-iot-hub-maps/terminal.png) If you open the blob storage container now, you should be able to see four blobs for locations where the vehicle was outside the geofence. ![Enter blob](./media/tutorial-iot-hub-maps/blob.png) The map below shows four points where the vehicle was outside the geofence, logged at regular time intervals. ![violation map](./media/tutorial-iot-hub-maps/violation-map.png) ## Next steps To explore Azure Maps APIs used in this tutorial, see: * [Get Search Address Reverse](https://docs.microsoft.com/rest/api/maps/search/getsearchaddressreverse) * [Get Geofence](https://docs.microsoft.com/rest/api/maps/spatial/getgeofence) For a complete list of Azure Maps REST APIs, see: * [Azure Maps REST APIs](https://docs.microsoft.com/rest/api/maps/spatial/getgeofence) To learn more about IoT Plug and Play, see: * [IoT Plug and Play](https://docs.microsoft.com/azure/iot-pnp) To get a list of devices that are Azure certified for IoT, visit: * [Azure certified devices](https://catalog.azureiotsolutions.com/) To learn more about how to send device to cloud telemetry and the other way around, see: * [Send telemetry from a device](https://docs.microsoft.com/azure/iot-hub/quickstart-send-telemetry-dotnet) ======================= File: articles/active-directory/develop/troubleshoot-publisher-verification.md ======================= --- title: Troubleshoot publisher verification - Microsoft identity platform | Azure description: Describes how to troubleshoot publisher verification (preview) for Microsoft identity platform by calling Microsoft Graph APIs. services: active-directory author: rwike77 manager: CelesteDG ms.service: active-directory ms.subservice: develop ms.topic: conceptual ms.workload: identity ms.date: 05/08/2020 ms.author: ryanwi ms.custom: aaddev ms.reviewer: jesakowi --- # Troubleshoot publisher verification (preview) If you are unable to complete the process or are experiencing unexpected behavior with [publisher verification (preview)](publisher-verification-overview.md), you should start by doing the following if you are receiving errors or seeing unexpected behavior: 1. Review the [requirements](publisher-verification-overview.md#requirements) and ensure they have all been met. 1. Review the instructions to [mark an app as publisher verified](mark-app-as-publisher-verified.md) and ensure all steps have been performed successfully. 1. Review the list of [common issues](#common-issues). 1. Reproduce the request using [Graph Explorer](#making-microsoft-graph-api-calls) to gather additional info and rule out any issues in the UI. ## Common Issues Below are some common issues that may occur during the process. - **I don’t know my Microsoft Partner Network ID (MPN ID) or I don’t who the primary contact for the account is** 1. Navigate to the [MPN enrollment page](https://partner.microsoft.com/dashboard/account/v3/enrollment/joinnow/basicpartnernetwork/new) 1. Sign in with a user account in the org's primary Azure AD tenant 1. If an MPN account already exists, this will be recognized and you will be added to the account 1. Navigate to the [partner profile page](https://partner.microsoft.com/en-us/pcv/accountsettings/connectedpartnerprofile) where the MPN ID and primary account contact will be listed - **I don’t know who my Azure AD Global Admin (also known as Company Admin or Tenant Admin) is, how do I find them? What about the App Administrator, or a different admin role?** 1. Sign in to the [Azure AD Portal](https://aad.portal.azure.com) using a user account in your organization's primary tenant 1. Navigate to [Role Management](https://aad.portal.azure.com/#blade/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/RolesAndAdministrators) 1. Click “Global Administrator”, or the desired admin role 1. The list of users assigned that role will be displayed - **I don't know who the admin(s) for my MPN account are** Go to the [MPN User Management page](https://partner.microsoft.com/en-us/pcv/users) and filter the user list to see what users are in various admin roles. - **I am getting an error saying that my MPN ID is invalid or that I do not have access to it.** 1. Go to your [partner profile](https://partner.microsoft.com/en-us/pcv/accountsettings/connectedpartnerprofile) and verify that: - The MPN ID is correct. - There are no errors or “pending actions” shown, and the verification status under Legal business profile and Partner info both say “authorized” or “success”. 1. Go to the [MPN tenant management page](https://partner.microsoft.com/en-us/dashboard/account/v3/tenantmanagement) and confirm that the tenant the app is registered in and that you are signing with a user account from is on the list of associated tenants. 1. Go to the [MPN User Management page](https://partner.microsoft.com/en-us/pcv/users) and confirm the user you are signing in as is either a Global Admin, MPN Admin, or Accounts Admin. - **When I sign into the Azure AD portal, I do not see any apps registered. Why?** Your app registrations may have been created using a different user account, or in a different tenant. Ensure you are signed in with the correct account in the tenant where your app registrations were created. - **How do I know who the owner of an app registration in Azure AD is?** When signed into a tenant where the app is registered, navigate to the App Registrations blade, click an app, and then click Owners. ## Making Microsoft Graph API calls If you are having an issue but unable to understand why based on what you are seeing in the UI, it may be helpful to perform further troubleshooting by using Microsoft Graph calls to perform the same operations you can perform in the App Registration portal. During the preview phase, these APIs will only be available on the /beta endpoint of Microsoft Graph. The easiest way to make these requests is using [Graph Explorer](https://developer.microsoft.com/graph/graph-explorer). You may also consider other options like using [Postman](https://www.postman.com/), or using PowerShell to [invoke a web request](/powershell/module/microsoft.powershell.utility/invoke-webrequest?view=powershell-7). You can use Microsoft Graph to both set and unset your app’s verified publisher and check the result after performing one of these operations. The result can be seen on both the [application](/graph/api/resources/application?view=graph-rest-beta) object corresponding to your app registration and any [service principals](/graph/api/resources/serviceprincipal?view=graph-rest-beta) that have been instantiated from that app. For more information on the relationship between those objects, see: [Application and service principal objects in Azure Active Directory](app-objects-and-service-principals.md). Here are examples of some useful requests: ### Set Verified Publisher Request ``` POST /applications/0cd04273-0d11-4e62-9eb3-5c3971a7cbec/setVerifiedPublisher { "verifiedPublisherId": "12345678" } ``` Response ``` 204 No Content ``` > [!NOTE] > *verifiedPublisherID* is your MPN ID. ### Unset Verified Publisher Request: ``` POST /applications/0cd04273-0d11-4e62-9eb3-5c3971a7cbec/unsetVerifiedPublisher ``` Response ``` 204 No Content ``` ### Get Verified Publisher info from Application ``` GET https://graph.microsoft.com/beta/applications/0cd04273-0d11-4e62-9eb3-5c3971a7cbec HTTP/1.1 200 OK { "id": "0cd04273-0d11-4e62-9eb3-5c3971a7cbec", ... "verifiedPublisher" : { "displayName": "myexamplePublisher", "verifiedPublisherId": "12345678", "addedDateTime": "2019-12-10T00:00:00" } } ``` ### Get Verified Publisher info from Service Principal ``` GET https://graph.microsoft.com/beta/servicePrincipals/010422a7-4d77-4f40-9335-b81ef5c23dd4 HTTP/1.1 200 OK { "id": "010422a7-4d77-4f40-9335-b81ef5c22dd4", ... "verifiedPublisher" : { "displayName": "myexamplePublisher", "verifiedPublisherId": "12345678", "addedDateTime": "2019-12-10T00:00:00" } } ``` ## Error Reference The following is a list of the potential error codes you may receive, either when troubleshooting with Microsoft Graph or going through the process in the app registration portal. ### MPNAccountNotFoundOrNoAccess The MPN ID you provided (<MPNID>) does not exist, or you do not have access to it. Provide a valid MPN ID and try again. ### MPNGlobalAccountNotFound The MPN ID you provided (<MPNID>) is not valid. Provide a valid MPN ID and try again. ### MPNAccountInvalid The MPN ID you provided (<MPNID>) is not valid. Provide a valid MPN ID and try again. ### MPNAccountNotVetted The MPN ID (<MPNID>) you provided has not completed the vetting process. Complete this process in Partner Center and try again. ### NoPublisherIdOnAssociatedMPNAccount The MPN ID you provided (<MPNID>) is not valid. Provide a valid MPN ID and try again. ### MPNIdDoesNotMatchAssociatedMPNAccount The MPN ID you provided (<MPNID>) is not valid. Provide a valid MPN ID and try again. ### ApplicationNotFound The target application (<AppId>) cannot be found. Provide a valid application ID and try again. ### B2CTenantNotAllowed This capability is not supported in an Azure AD B2C tenant. ### EmailVerifiedTenantNotAllowed This capability is not supported in an email verified tenant. ### NoPublisherDomainOnApplication The target application (<AppId>) does must have a Publisher Domain set. Set a Publisher Domain and try again. ### PublisherDomainIsNotDNSVerified The target application's Publisher Domain (<publisherDomain>) is not a verified domain in this tenant. Verify a tenant domain using DNS verification and try again. ### PublisherDomainMismatch The target application's Publisher Domain (<publisherDomain>) does not match the domain used to perform email verification in Partner Center (<pcDomain>). Ensure these domains match and try again. ### NotAuthorizedToVerifyPublisher You are not authorized to set the verified publisher property on application (<AppId>) ### MPNIdWasNotProvided The MPN ID was not provided in the request body or the request content type was not "application/json". ### MSANotSupported This feature is not supported for Microsoft consumer accounts. Only applications registered in Azure AD by an Azure AD user are supported. ## Next steps If you have reviewed all of the previous information and are still receiving an error from Microsoft Graph, gather as much of the following information as possible related to the failing request and [contact Microsoft support](developer-support-help-options.md#open-a-support-request). - Timestamp - CorrelationId - ObjectID or UserPrincipalName of signed in user - ObjectId of target application - AppId of target application - TenantId where app is registered - MPN ID - REST request being made - Error code and message being returned ======================= File: includes/search-blob-data-sources.md ======================= --- author: mgottein ms.service: cognitive-search ms.topic: include ms.date: 05/02/2019 ms.author: magottei --- * PDF * Microsoft Office formats: DOCX/DOC/DOCM, XLSX/XLS/XLSM, PPTX/PPT/PPTM, MSG (Outlook emails), XML(both 2003 and 2006 WORD XML) * Open Document formats: ODT, ODS, ODP * HTML * XML * ZIP * GZ * EPUB * EML * RTF * Plain text files (see also [Indexing plain text](../articles/search/search-howto-indexing-azure-blob-storage.md#IndexingPlainText)) * JSON (see [Indexing JSON blobs](../articles/search/search-howto-index-json-blobs.md)) * CSV (see [Indexing CSV blobs](../articles/search/search-howto-index-csv-blobs.md)) ======================= File: articles/marketplace/cloud-partner-portal/virtual-machine/cpp-virtual-machine-offer.md ======================= --- title: Virtual machine offer in Azure Marketplace description: Overview of the process for publishing a VM offer on Azure Marketplace. author: dsindona ms.service: marketplace ms.subservice: partnercenter-marketplace-publisher ms.topic: conceptual ms.date: 05/20/2020 ms.author: dsindona --- # Azure Virtual Machine offer [Cloud Partner Portal](https://cloudpartner.azure.com/) no longer supports the creation and management of Azure Virtual Machine offers. This functionality has been moved to Microsoft [Partner Center](https://partner.microsoft.com/pcv/). For more information, see [Create an Azure Virtual Machine offer](../../partner-center-portal/azure-vm-create-offer.md). ======================= File: includes/static-web-apps-cleanup-resource.md ======================= --- author: aaronpowell ms.service: static-web-apps ms.topic: include ms.date: 05/08/2020 ms.author: aapowell --- If you're not going to continue to use this application, you can delete the Azure Static Web App resource through the following steps: 1. Open the [Azure portal](https://portal.azure.com) 1. In the top search bar, search for your application by the name you provided earlier 1. Click on the app 1. Click on the **Delete** button 1. Click **Yes** to confirm the delete action ======================= File: articles/active-directory/hybrid/tshoot-connect-password-hash-synchronization.md ======================= --- title: Troubleshoot password hash synchronization with Azure AD Connect sync | Microsoft Docs description: This article provides information about how to troubleshoot password hash synchronization problems. services: active-directory documentationcenter: '' author: billmath manager: daveba editor: '' ms.assetid: ms.service: active-directory ms.workload: identity ms.tgt_pltfrm: na ms.devlang: na ms.topic: article ms.date: 03/13/2017 ms.subservice: hybrid ms.author: billmath ms.collection: M365-identity-device-management --- # Troubleshoot password hash synchronization with Azure AD Connect sync This topic provides steps for how to troubleshoot issues with password hash synchronization. If passwords are not synchronizing as expected, it can be either for a subset of users or for all users. For Azure Active Directory (Azure AD) Connect deployment with version 1.1.614.0 or after, use the troubleshooting task in the wizard to troubleshoot password hash synchronization issues: * If you have an issue where no passwords are synchronized, refer to the [No passwords are synchronized: troubleshoot by using the troubleshooting task](#no-passwords-are-synchronized-troubleshoot-by-using-the-troubleshooting-task) section. * If you have an issue with individual objects, refer to the [One object is not synchronizing passwords: troubleshoot by using the troubleshooting task](#one-object-is-not-synchronizing-passwords-troubleshoot-by-using-the-troubleshooting-task) section. For deployment with version 1.1.524.0 or later, there is a diagnostic cmdlet that you can use to troubleshoot password hash synchronization issues: * If you have an issue where no passwords are synchronized, refer to the [No passwords are synchronized: troubleshoot by using the diagnostic cmdlet](#no-passwords-are-synchronized-troubleshoot-by-using-the-diagnostic-cmdlet) section. * If you have an issue with individual objects, refer to the [One object is not synchronizing passwords: troubleshoot by using the diagnostic cmdlet](#one-object-is-not-synchronizing-passwords-troubleshoot-by-using-the-diagnostic-cmdlet) section. For older versions of Azure AD Connect deployment: * If you have an issue where no passwords are synchronized, refer to the [No passwords are synchronized: manual troubleshooting steps](#no-passwords-are-synchronized-manual-troubleshooting-steps) section. * If you have an issue with individual objects, refer to the [One object is not synchronizing passwords: manual troubleshooting steps](#one-object-is-not-synchronizing-passwords-manual-troubleshooting-steps) section. ## No passwords are synchronized: troubleshoot by using the troubleshooting task You can use the troubleshooting task to figure out why no passwords are synchronized. > [!NOTE] > The troubleshooting task is available only for Azure AD Connect version 1.1.614.0 or later. ### Run the troubleshooting task To troubleshoot issues where no passwords are synchronized: 1. Open a new Windows PowerShell session on your Azure AD Connect server with the **Run as Administrator** option. 2. Run `Set-ExecutionPolicy RemoteSigned` or `Set-ExecutionPolicy Unrestricted`. 3. Start the Azure AD Connect wizard. 4. Navigate to the **Additional Tasks** page, select **Troubleshoot**, and click **Next**. 5. On the Troubleshooting page, click **Launch** to start the troubleshooting menu in PowerShell. 6. In the main menu, select **Troubleshoot password hash synchronization**. 7. In the sub menu, select **Password hash synchronization does not work at all**. ### Understand the results of the troubleshooting task The troubleshooting task performs the following checks: * Validates that the password hash synchronization feature is enabled for your Azure AD tenant. * Validates that the Azure AD Connect server is not in staging mode. * For each existing on-premises Active Directory connector (which corresponds to an existing Active Directory forest): * Validates that the password hash synchronization feature is enabled. * Searches for password hash synchronization heartbeat events in the Windows Application Event logs. * For each Active Directory domain under the on-premises Active Directory connector: * Validates that the domain is reachable from the Azure AD Connect server. * Validates that the Active Directory Domain Services (AD DS) accounts used by the on-premises Active Directory connector has the correct username, password, and permissions required for password hash synchronization. The following diagram illustrates the results of the cmdlet for a single-domain, on-premises Active Directory topology: ![Diagnostic output for password hash synchronization](./media/tshoot-connect-password-hash-synchronization/phsglobalgeneral.png) The rest of this section describes specific results that are returned by the task and corresponding issues. #### password hash synchronization feature isn't enabled If you haven't enabled password hash synchronization by using the Azure AD Connect wizard, the following error is returned: ![password hash synchronization isn't enabled](./media/tshoot-connect-password-hash-synchronization/phsglobaldisabled.png) #### Azure AD Connect server is in staging mode If the Azure AD Connect server is in staging mode, password hash synchronization is temporarily disabled, and the following error is returned: ![Azure AD Connect server is in staging mode](./media/tshoot-connect-password-hash-synchronization/phsglobalstaging.png) #### No password hash synchronization heartbeat events Each on-premises Active Directory connector has its own password hash synchronization channel. When the password hash synchronization channel is established and there aren't any password changes to be synchronized, a heartbeat event (EventId 654) is generated once every 30 minutes under the Windows Application Event Log. For each on-premises Active Directory connector, the cmdlet searches for corresponding heartbeat events in the past three hours. If no heartbeat event is found, the following error is returned: ![No password hash synchronization heart beat event](./media/tshoot-connect-password-hash-synchronization/phsglobalnoheartbeat.png) #### AD DS account does not have correct permissions If the AD DS account that's used by the on-premises Active Directory connector to synchronize password hashes does not have the appropriate permissions, the following error is returned: ![Incorrect credential](./media/tshoot-connect-password-hash-synchronization/phsglobalaccountincorrectpermission.png) #### Incorrect AD DS account username or password If the AD DS account used by the on-premises Active Directory connector to synchronize password hashes has an incorrect username or password, the following error is returned: ![Incorrect credential](./media/tshoot-connect-password-hash-synchronization/phsglobalaccountincorrectcredential.png) ## One object is not synchronizing passwords: troubleshoot by using the troubleshooting task You can use the troubleshooting task to determine why one object is not synchronizing passwords. > [!NOTE] > The troubleshooting task is available only for Azure AD Connect version 1.1.614.0 or later. ### Run the diagnostics cmdlet To troubleshoot issues for a specific user object: 1. Open a new Windows PowerShell session on your Azure AD Connect server with the **Run as Administrator** option. 2. Run `Set-ExecutionPolicy RemoteSigned` or `Set-ExecutionPolicy Unrestricted`. 3. Start the Azure AD Connect wizard. 4. Navigate to the **Additional Tasks** page, select **Troubleshoot**, and click **Next**. 5. On the Troubleshooting page, click **Launch** to start the troubleshooting menu in PowerShell. 6. In the main menu, select **Troubleshoot password hash synchronization**. 7. In the sub menu, select **Password is not synchronized for a specific user account**. ### Understand the results of the troubleshooting task The troubleshooting task performs the following checks: * Examines the state of the Active Directory object in the Active Directory connector space, Metaverse, and Azure AD connector space. * Validates that there are synchronization rules with password hash synchronization enabled and applied to the Active Directory object. * Attempts to retrieve and display the results of the last attempt to synchronize the password for the object. The following diagram illustrates the results of the cmdlet when troubleshooting password hash synchronization for a single object: ![Diagnostic output for password hash synchronization - single object](./media/tshoot-connect-password-hash-synchronization/phssingleobjectgeneral.png) The rest of this section describes specific results returned by the cmdlet and corresponding issues. #### The Active Directory object isn't exported to Azure AD password hash synchronization for this on-premises Active Directory account fails because there is no corresponding object in the Azure AD tenant. The following error is returned: ![Azure AD object is missing](./media/tshoot-connect-password-hash-synchronization/phssingleobjectnotexported.png) #### User has a temporary password Currently, Azure AD Connect does not support synchronizing temporary passwords with Azure AD. A password is considered to be temporary if the **Change password at next logon** option is set on the on-premises Active Directory user. The following error is returned: ![Temporary password is not exported](./media/tshoot-connect-password-hash-synchronization/phssingleobjecttemporarypassword.png) #### Results of last attempt to synchronize password aren't available By default, Azure AD Connect stores the results of password hash synchronization attempts for seven days. If there are no results available for the selected Active Directory object, the following warning is returned: ![Diagnostic output for single object - no password sync history](./media/tshoot-connect-password-hash-synchronization/phssingleobjectnohistory.png) ## No passwords are synchronized: troubleshoot by using the diagnostic cmdlet You can use the `Invoke-ADSyncDiagnostics` cmdlet to figure out why no passwords are synchronized. > [!NOTE] > The `Invoke-ADSyncDiagnostics` cmdlet is available only for Azure AD Connect version 1.1.524.0 or later. ### Run the diagnostics cmdlet To troubleshoot issues where no passwords are synchronized: 1. Open a new Windows PowerShell session on your Azure AD Connect server with the **Run as Administrator** option. 2. Run `Set-ExecutionPolicy RemoteSigned` or `Set-ExecutionPolicy Unrestricted`. 3. Run `Import-Module ADSyncDiagnostics`. 4. Run `Invoke-ADSyncDiagnostics -PasswordSync`. ## One object is not synchronizing passwords: troubleshoot by using the diagnostic cmdlet You can use the `Invoke-ADSyncDiagnostics` cmdlet to determine why one object is not synchronizing passwords. > [!NOTE] > The `Invoke-ADSyncDiagnostics` cmdlet is available only for Azure AD Connect version 1.1.524.0 or later. ### Run the diagnostics cmdlet To troubleshoot issues where no passwords are synchronized for a user: 1. Open a new Windows PowerShell session on your Azure AD Connect server with the **Run as Administrator** option. 2. Run `Set-ExecutionPolicy RemoteSigned` or `Set-ExecutionPolicy Unrestricted`. 3. Run `Import-Module ADSyncDiagnostics`. 4. Run the following cmdlet: ``` Invoke-ADSyncDiagnostics -PasswordSync -ADConnectorName <Name-of-AD-Connector> -DistinguishedName <DistinguishedName-of-AD-object> ``` For example: ```powershell Invoke-ADSyncDiagnostics -PasswordSync -ADConnectorName "contoso.com" -DistinguishedName "CN=TestUserCN=Users,DC=contoso,DC=com" ``` ## No passwords are synchronized: manual troubleshooting steps Follow these steps to determine why no passwords are synchronized: 1. Is the Connect server in [staging mode](how-to-connect-sync-staging-server.md)? A server in staging mode does not synchronize any passwords. 2. Run the script in the [Get the status of password sync settings](#get-the-status-of-password-sync-settings) section. It gives you an overview of the password sync configuration. ![PowerShell script output from password sync settings](./media/tshoot-connect-password-hash-synchronization/psverifyconfig.png) 3. If the feature is not enabled in Azure AD or if the sync channel status is not enabled, run the Connect installation wizard. Select **Customize synchronization options**, and unselect password sync. This change temporarily disables the feature. Then run the wizard again and re-enable password sync. Run the script again to verify that the configuration is correct. 4. Look in the event log for errors. Look for the following events, which would indicate a problem: * Source: "Directory synchronization" ID: 0, 611, 652, 655 If you see these events, you have a connectivity problem. The event log message contains forest information where you have a problem. For more information, see [Connectivity problem](#connectivity problem). 5. If you see no heartbeat or if nothing else worked, run [Trigger a full sync of all passwords](#trigger-a-full-sync-of-all-passwords). Run the script only once. 6. See the Troubleshoot one object that is not synchronizing passwords section. ### Connectivity problems Do you have connectivity with Azure AD? Does the account have required permissions to read the password hashes in all domains? If you installed Connect by using Express settings, the permissions should already be correct. If you used custom installation, set the permissions manually by doing the following: 1. To find the account used by the Active Directory connector, start **Synchronization Service Manager**. 2. Go to **Connectors**, and then search for the on-premises Active Directory forest you are troubleshooting. 3. Select the connector, and then click **Properties**. 4. Go to **Connect to Active Directory Forest**. ![Account used by Active Directory connector](./media/tshoot-connect-password-hash-synchronization/connectoraccount.png) Note the username and the domain where the account is located. 5. Start **Active Directory Users and Computers**, and then verify that the account you found earlier has the follow permissions set at the root of all domains in your forest: * Replicate Directory Changes * Replicate Directory Changes All 6. Are the domain controllers reachable by Azure AD Connect? If the Connect server cannot connect to all domain controllers, configure **Only use preferred domain controller**. ![Domain controller used by Active Directory connector](./media/tshoot-connect-password-hash-synchronization/preferreddc.png) 7. Go back to **Synchronization Service Manager** and **Configure Directory Partition**. 8. Select your domain in **Select directory partitions**, select the **Only use preferred domain controllers** check box, and then click **Configure**. 9. In the list, enter the domain controllers that Connect should use for password sync. The same list is used for import and export as well. Do these steps for all your domains. 10. If the script shows that there is no heartbeat, run the script in [Trigger a full sync of all passwords](#trigger-a-full-sync-of-all-passwords). ## One object is not synchronizing passwords: manual troubleshooting steps You can easily troubleshoot password hash synchronization issues by reviewing the status of an object. 1. In **Active Directory Users and Computers**, search for the user, and then verify that the **User must change password at next logon** check box is cleared. ![Active Directory productive passwords](./media/tshoot-connect-password-hash-synchronization/adprodpassword.png) If the check box is selected, ask the user to sign in and change the password. Temporary passwords are not synchronized with Azure AD. 2. If the password looks correct in Active Directory, follow the user in the sync engine. By following the user from on-premises Active Directory to Azure AD, you can see whether there is a descriptive error on the object. a. Start the [Synchronization Service Manager](how-to-connect-sync-service-manager-ui.md). b. Click **Connectors**. c. Select the **Active Directory Connector** where the user is located. d. Select **Search Connector Space**. e. In the **Scope** box, select **DN or Anchor**, and then enter the full DN of the user you are troubleshooting. ![Search for user in connector space with DN](./media/tshoot-connect-password-hash-synchronization/searchcs.png) f. Locate the user you are looking for, and then click **Properties** to see all the attributes. If the user is not in the search result, verify your [filtering rules](how-to-connect-sync-configure-filtering.md) and make sure that you run [Apply and verify changes](how-to-connect-sync-configure-filtering.md#apply-and-verify-changes) for the user to appear in Connect. g. To see the password sync details of the object for the past week, click **Log**. ![Object log details](./media/tshoot-connect-password-hash-synchronization/csobjectlog.png) If the object log is empty, Azure AD Connect has been unable to read the password hash from Active Directory. Continue your troubleshooting with Connectivity Errors. If you see any other value than **success**, refer to the table in [Password sync log](#password-sync-log). h. Select the **lineage** tab, and make sure that at least one sync rule in the **PasswordSync** column is **True**. In the default configuration, the name of the sync rule is **In from AD - User AccountEnabled**. ![Lineage information about a user](./media/tshoot-connect-password-hash-synchronization/cspasswordsync.png) i. Click **Metaverse Object Properties** to display a list of user attributes. ![Metaverse information](./media/tshoot-connect-password-hash-synchronization/mvpasswordsync.png) Verify that there is no **cloudFiltered** attribute present. Make sure that the domain attributes (domainFQDN and domainNetBios) have the expected values. j. Click the **Connectors** tab. Make sure that you see connectors to both on-premises Active Directory and Azure AD. ![Metaverse information](./media/tshoot-connect-password-hash-synchronization/mvconnectors.png) k. Select the row that represents Azure AD, click **Properties**, and then click the **Lineage** tab. The connector space object should have an outbound rule in the **PasswordSync** column set to **True**. In the default configuration, the name of the sync rule is **Out to AAD - User Join**. ![Connector Space Object Properties dialog box](./media/tshoot-connect-password-hash-synchronization/cspasswordsync2.png) ### Password sync log The status column can have the following values: | Status | Description | | --- | --- | | Success |Password has been successfully synchronized. | | FilteredByTarget |Password is set to **User must change password at next logon**. Password has not been synchronized. | | NoTargetConnection |No object in the metaverse or in the Azure AD connector space. | | SourceConnectorNotPresent |No object found in the on-premises Active Directory connector space. | | TargetNotExportedToDirectory |The object in the Azure AD connector space has not yet been exported. | | MigratedCheckDetailsForMoreInfo |Log entry was created before build 1.0.9125.0 and is shown in its legacy state. | | Error |Service returned an unknown error. | | Unknown |An error occurred while trying to process a batch of password hashes. | | MissingAttribute |Specific attributes (for example, Kerberos hash) required by Azure AD Domain Services are not available. | | RetryRequestedByTarget |Specific attributes (for example, Kerberos hash) required by Azure AD Domain Services were not available previously. An attempt to resynchronize the user's password hash is made. | ## Scripts to help troubleshooting ### Get the status of password sync settings ```powershell Import-Module ADSync $connectors = Get-ADSyncConnector $aadConnectors = $connectors | Where-Object {$_.SubType -eq "Windows Azure Active Directory (Microsoft)"} $adConnectors = $connectors | Where-Object {$_.ConnectorTypeName -eq "AD"} if ($aadConnectors -ne $null -and $adConnectors -ne $null) { if ($aadConnectors.Count -eq 1) { $features = Get-ADSyncAADCompanyFeature -ConnectorName $aadConnectors[0].Name Write-Host Write-Host "Password sync feature enabled in your Azure AD directory: " $features.PasswordHashSync foreach ($adConnector in $adConnectors) { Write-Host Write-Host "Password sync channel status BEGIN ------------------------------------------------------- " Write-Host Get-ADSyncAADPasswordSyncConfiguration -SourceConnector $adConnector.Name Write-Host $pingEvents = Get-EventLog -LogName "Application" -Source "Directory Synchronization" -InstanceId 654 -After (Get-Date).AddHours(-3) | Where-Object { $_.Message.ToUpperInvariant().Contains($adConnector.Identifier.ToString("D").ToUpperInvariant()) } | Sort-Object { $_.Time } -Descending if ($pingEvents -ne $null) { Write-Host "Latest heart beat event (within last 3 hours). Time " $pingEvents[0].TimeWritten } else { Write-Warning "No ping event found within last 3 hours." } Write-Host Write-Host "Password sync channel status END ------------------------------------------------------- " Write-Host } } else { Write-Warning "More than one Azure AD Connectors found. Please update the script to use the appropriate Connector." } } Write-Host if ($aadConnectors -eq $null) { Write-Warning "No Azure AD Connector was found." } if ($adConnectors -eq $null) { Write-Warning "No AD DS Connector was found." } Write-Host ``` #### Trigger a full sync of all passwords > [!NOTE] > Run this script only once. If you need to run it more than once, something else is the problem. To troubleshoot the problem, contact Microsoft support. You can trigger a full sync of all passwords by using the following script: ```powershell $adConnector = "<CASE SENSITIVE AD CONNECTOR NAME>" $aadConnector = "<CASE SENSITIVE AAD CONNECTOR NAME>" Import-Module adsync $c = Get-ADSyncConnector -Name $adConnector $p = New-Object Microsoft.IdentityManagement.PowerShell.ObjectModel.ConfigurationParameter "Microsoft.Synchronize.ForceFullPasswordSync", String, ConnectorGlobal, $null, $null, $null $p.Value = 1 $c.GlobalParameters.Remove($p.Name) $c.GlobalParameters.Add($p) $c = Add-ADSyncConnector -Connector $c Set-ADSyncAADPasswordSyncConfiguration -SourceConnector $adConnector -TargetConnector $aadConnector -Enable $false Set-ADSyncAADPasswordSyncConfiguration -SourceConnector $adConnector -TargetConnector $aadConnector -Enable $true ``` ## Next steps * [Implementing password hash synchronization with Azure AD Connect sync](how-to-connect-password-hash-synchronization.md) * [Azure AD Connect Sync: Customizing synchronization options](how-to-connect-sync-whatis.md) * [Integrating your on-premises identities with Azure Active Directory](whatis-hybrid-identity.md) ======================= File: articles/azure-functions/functions-bindings-storage-queue.md ======================= --- title: Azure Queue storage trigger and bindings for Azure Functions overview description: Understand how to use the Azure Queue storage trigger and output binding in Azure Functions. author: craigshoemaker ms.topic: reference ms.date: 02/18/2020 ms.author: cshoe ms.custom: cc996988-fb4f-47 --- # Azure Queue storage trigger and bindings for Azure Functions overview Azure Functions can run as new Azure Queue storage messages are created and can write queue messages within a function. | Action | Type | |---------|---------| | Run a function as queue storage data changes | [Trigger](./functions-bindings-storage-queue-trigger.md) | | Write queue storage messages |[Output binding](./functions-bindings-storage-queue-output.md) | ## Add to your Functions app ### Functions 2.x and higher Working with the trigger and bindings requires that you reference the appropriate package. The NuGet package is used for.NET class libraries while the extension bundle is used for all other application types. | Language | Add by... | Remarks |-------------------------------------------------|---------------------------------------------|-------------| | C# | Installing the [NuGet package], version 3.x | | | C# Script, Java, JavaScript, Python, PowerShell | Registering the [extension bundle] | The [Azure Tools extension](https://marketplace.visualstudio.com/items?itemName=ms-vscode.vscode-node-azure-pack) is recommended to use with Visual Studio Code. | | C# Script (online-only in Azure portal) | Adding a binding | To update existing binding extensions without having to republish your function app, see [Update your extensions]. | [core tools]:./functions-run-local.md [extension bundle]:./functions-bindings-register.md#extension-bundles [NuGet package]: https://www.nuget.org/packages/Microsoft.Azure.WebJobs.Extensions.Storage [Update your extensions]:./install-update-binding-extensions-manual.md [Azure Tools extension]: https://marketplace.visualstudio.com/items?itemName=ms-vscode.vscode-node-azure-pack ### Functions 1.x Functions 1.x apps automatically have a reference the [Microsoft.Azure.WebJobs](https://www.nuget.org/packages/Microsoft.Azure.WebJobs) NuGet package, version 2.x. [!INCLUDE [functions-storage-sdk-version](../../includes/functions-storage-sdk-version.md)] ## Next steps - [Run a function as queue storage data changes (Trigger)](./functions-bindings-storage-queue-trigger.md) - [Write queue storage messages (Output binding)](./functions-bindings-storage-queue-output.md) ======================= File: articles/azure-monitor/insights/resource-group-insights.md ======================= --- title: Azure Monitor Resource Group Insights | Microsoft Docs description: Understand the health and performance of your distributed applications and services at the Resource Group level with Azure Monitor ms.subservice: ms.topic: conceptual author: NumberByColors ms.author: daviste ms.date: 09/19/2018 ms.reviewer: mbullwin --- # Monitor resource groups with Azure Monitor (preview) Modern applications are often complex and highly distributed with many discrete parts working together to deliver a service. Recognizing this complexity, Azure Monitor provides monitoring insights for resource groups. This makes it easy to triage and diagnose any problems your individual resources encounter, while offering context as to the health and performance of the resource group&mdash;and your application&mdash;as a whole. ## Access insights for resource groups 1. Select **Resource groups** from the left-side navigation bar. 2. Pick one of your resource groups that you want to explore. (If you have a large number of resource groups filtering by subscription can sometimes be helpful.) 3. To access insights for a resource group, click **Insights** in the left-side menu of any resource group. ![Screenshot of resource group insights overview page](./media/resource-group-insights/0001-overview.png) ## Resources with active alerts and health issues The overview page shows how many alerts have been fired and are still active, along with the current Azure Resource Health of each resource. Together, this information can help you quickly spot any resources that are experiencing issues. Alerts help you detect issues in your code and how you've configured your infrastructure. Azure Resource Health surfaces issue with the Azure platform itself, that aren't specific to your individual applications. ![Screenshot of Azure Resource Health pane](./media/resource-group-insights/0002-overview.png) ### Azure Resource Health To display Azure Resource Health, check the **Show Azure Resource Health** box above the table. This column is hidden by default to help the page load quickly. ![Screenshot with resource health graph added](./media/resource-group-insights/0003-overview.png) By default, the resources are grouped by app layer and resource type. **App layer** is a simple categorization of resource types, that only exists within the context of the resource group insights overview page. There are resource types related to application code, compute infrastructure, networking, storage + databases. Management tools get their own app layers, and every other resource is categorized as belonging to the **Other** app layer. This grouping can help you see at-a-glance what subsystems of your application are healthy and unhealthy. ## Diagnose issues in your resource group The resource group insights page provides several other tools scoped to help you diagnose issues | | | | ---------------- |:-----| | [**Alerts**](https://docs.microsoft.com/azure/monitoring-and-diagnostics/monitoring-overview-unified-alerts) | View, create, and manage your alerts. | | [**Metrics**](https://docs.microsoft.com/azure/monitoring-and-diagnostics/monitoring-overview-metrics) | Visualize and explore your metric based data. | | [**Activity logs**](https://docs.microsoft.com/azure/monitoring-and-diagnostics/monitoring-overview-activity-logs) | Subscription level events that have occurred in Azure. | | [**Application map**](https://docs.microsoft.com/azure/application-insights/app-insights-app-map) | Navigate your distributed application's topology to identify performance bottlenecks or failure hotspots. | ## Failures and performance What if you've noticed your application is running slowly, or users have reported errors? It's time consuming to search through all of your resources to isolate problems. The **Performance** and **Failures** tabs simplify this process by bringing together performance and failure diagnostic views for many common resource types. Most resource types will open a gallery of Azure Monitor Workbook templates. Each workbook you create can be customized, saved, shared with your team, and reused in the future to diagnose similar issues. ### Investigate failures To test out the Failures tab select **Failures** under **Investigate** in the left-hand menu. The left-side menu bar changes after your selection is made, offering you new options. ![Screenshot of Failure overview pane](./media/resource-group-insights/00004-failures.png) When App Service is chosen, you are presented with a gallery of Azure Monitor Workbook templates. ![Screenshot of application workbook gallery](./media/resource-group-insights/0005-failure-insights-workbook.png) Choosing the template for Failure Insights will open the workbook. ![Screenshot of failure report](./media/resource-group-insights/0006-failure-visual.png) You can select any of the rows. The selection is then displayed in a graphical details view. ![Screenshot of failure details](./media/resource-group-insights/0007-failure-details.png) Workbooks abstract away the difficult work of creating custom reports and visualizations into an easily consumable format. While some users may only want to adjust the prebuilt parameters, workbooks are completely customizable. To get a sense of how this workbook functions internally, select **Edit** in the top bar. ![Screenshot of additional edit option](./media/resource-group-insights/0008-failure-edit.png) A number of **Edit** boxes appear near the various elements of the workbook. Select the **Edit** box below the table of operations. ![Screenshot of edit boxes](./media/resource-group-insights/0009-failure-edit-graph.png) This reveals the underlying log query that is driving the table visualization. ![Screenshot of log query window](./media/resource-group-insights/0010-failure-edit-query.png) You can modify the query directly. Or you can use it as a reference and borrow from it when designing your own custom parameterized workbook. ### Investigate performance Performance offers its own gallery of workbooks. For App Service the prebuilt Application Performance workbook offers the following view: ![Screenshot of performance view](./media/resource-group-insights/0011-performance.png) In this case, if you select edit you will see that this set of visualizations is powered by Azure Monitor Metrics. ![Screenshot of performance view with Azure Metrics](./media/resource-group-insights/0012-performance-metrics.png) ## Troubleshooting ### Enabling access to alerts To see alerts in Azure Monitor for Resource Groups, someone with an Owner or Contributor role for this subscription needs to open Azure Monitor for Resource Groups for any resource group in the subscription. This will enable anyone with read access to see alerts in Azure Monitor for Resource Groups for all of the resource groups in the subscription. If you have an Owner or Contributor role, refresh this page in a few minutes. Azure Monitor for Resource Groups relies on the Azure Monitor Alerts Management system to retrieve alert status. Alerts Management isn't configured for every resource group and subscription by default, and it can only be enabled by someone with an Owner or Contributor role. It can be enabled either by: * Opening Azure Monitor for Resource Groups for any resource group in the subscription. * Or by going to the subscription, clicking **Resource Providers**, then clicking **Register for Alerts.Management**. ## Next steps - [Azure Monitor Workbooks](https://docs.microsoft.com/azure/azure-monitor/platform/workbooks-overview) - [Azure Resource Health](https://docs.microsoft.com/azure/service-health/resource-health-overview) - [Azure Monitor Alerts](https://docs.microsoft.com/azure/monitoring-and-diagnostics/monitoring-overview-unified-alerts) ======================= File: articles/service-fabric/configure-new-azure-service-fabric-enable-managed-identity.md ======================= --- title: Configure managed identity support for a new Service Fabric cluster description: Here's how to enable managed identities support in a new Azure Service Fabric cluster ms.topic: article ms.date: 12/09/2019 ms.custom: sfrev --- # Configure managed identity support for a new Service Fabric cluster To use [Managed identities for Azure resources](../active-directory/managed-identities-azure-resources/overview.md) in your Service Fabric applications, first enable the *Managed Identity Token Service* on the cluster. This service is responsible for the authentication of Service Fabric applications using their managed identities, and for obtaining access tokens on their behalf. Once the service is enabled, you can see it in Service Fabric Explorer under the **System** section in the left pane, running under the name **fabric:/System/ManagedIdentityTokenService** next to other system services. > [!NOTE] > Service Fabric runtime version 6.5.658.9590 or higher is required to enable the **Managed Identity Token Service**. ## Enable the Managed Identity Token Service To enable the Managed Identity Token Service at cluster creation time, add the following snippet to your cluster Azure Resource Manager template: ```json "fabricSettings": [ { "name": "ManagedIdentityTokenService", "parameters": [ { "name": "IsEnabled", "value": "true" } ] } ] ``` ## Errors If the deployment fails with this message, it means the cluster is not on the required Service Fabric version (the minimum supported runtime is 6.5 CU2): ```json { "code": "ParameterNotAllowed", "message": "Section 'ManagedIdentityTokenService' and Parameter 'IsEnabled' is not allowed." } ``` ## Related Articles * Review [managed identity support](./concepts-managed-identity.md) in Azure Service Fabric * [Enable managed identity support in an existing Azure Service Fabric cluster](./configure-existing-cluster-enable-managed-identity-token-service.md) ## Next steps * [Deploy an Azure Service Fabric application with a system-assigned managed identity](./how-to-deploy-service-fabric-application-system-assigned-managed-identity.md) * [Deploy an Azure Service Fabric application with a user-assigned managed identity](./how-to-deploy-service-fabric-application-user-assigned-managed-identity.md) * [Leverage the managed identity of a Service Fabric application from service code](./how-to-managed-identity-service-fabric-app-code.md) * [Grant an Azure Service Fabric application access to other Azure resources](./how-to-grant-access-other-resources.md) ======================= File: articles/iot-dps/how-to-manage-enrollments-sdks.md ======================= --- title: Manage device enrollments using Azure DPS SDKs description: How to manage device enrollments in the IoT Hub Device Provisioning Service (DPS) using the Service SDKs author: robinsh ms.author: robinsh ms.date: 04/04/2018 ms.topic: conceptual ms.service: iot-dps services: iot-dps --- # How to manage device enrollments with Azure Device Provisioning Service SDKs A *device enrollment* creates a record of a single device or a group of devices that may at some point register with the Device Provisioning Service. The enrollment record contains the initial desired configuration for the device(s) as part of that enrollment, including the desired IoT hub. This article shows you how to manage device enrollments for your provisioning service programmatically using the Azure IoT Provisioning Service SDKs. The SDKs are available on GitHub in the same repository as Azure IoT SDKs. ## Prerequisites * Obtain the connection string from your Device Provisioning Service instance. * Obtain the device security artifacts for the [attestation mechanism](concepts-security.md#attestation-mechanism) used: * [**Trusted Platform Module (TPM)**](/azure/iot-dps/concepts-security#trusted-platform-module): * Individual enrollment: Registration ID and TPM Endorsement Key from a physical device or from TPM Simulator. * Enrollment group does not apply to TPM attestation. * [**X.509**](/azure/iot-dps/concepts-security): * Individual enrollment: The [Leaf certificate](/azure/iot-dps/concepts-security) from physical device or from the SDK [DICE](https://azure.microsoft.com/blog/azure-iot-supports-new-security-hardware-to-strengthen-iot-security/) Emulator. * Enrollment group: The [CA/root certificate](/azure/iot-dps/concepts-security#root-certificate) or the [intermediate certificate](/azure/iot-dps/concepts-security#intermediate-certificate), used to produce device certificate on a physical device. It can also be generated from the SDK DICE emulator. * Exact API calls may be different due to language differences. Please review the samples provided on GitHub for details: * [Java Provisioning Service Client samples](https://github.com/Azure/azure-iot-sdk-java/tree/master/provisioning/provisioning-samples) * [Node.js Provisioning Service Client samples](https://github.com/Azure/azure-iot-sdk-node/tree/master/provisioning/service/samples) * [.NET Provisioning Service Client samples](https://github.com/Azure/azure-iot-sdk-csharp/tree/master/provisioning/service/samples) ## Create a device enrollment There are two ways you can enroll your devices with the provisioning service: * An **Enrollment group** is an entry for a group of devices that share a common attestation mechanism of X.509 certificates, signed by the [root certificate](https://docs.microsoft.com/azure/iot-dps/concepts-security#root-certificate) or the [intermediate certificate](https://docs.microsoft.com/azure/iot-dps/concepts-security#intermediate-certificate). We recommend using an enrollment group for a large number of devices that share a desired initial configuration, or for devices all going to the same tenant. Note that you can only enroll devices that use the X.509 attestation mechanism as *enrollment groups*. You can create an enrollment group with the SDKs following this workflow: 1. For enrollment group, the attestation mechanism uses X.509 root certificate. Call Service SDK API ```X509Attestation.createFromRootCertificate``` with root certificate to create attestation for enrollment. X.509 root certificate is provided in either a PEM file or as a string. 1. Create a new ```EnrollmentGroup``` variable using the ```attestation``` created and a unique ```enrollmentGroupId```. Optionally, you can set parameters like ```Device ID```, ```IoTHubHostName```, ```ProvisioningStatus```. 2. Call Service SDK API ```createOrUpdateEnrollmentGroup``` in your backend application with ```EnrollmentGroup``` to create an enrollment group. * An **Individual enrollment** is an entry for a single device that may register. Individual enrollments may use either X.509 certificates or SAS tokens (from a physical or virtual TPM) as attestation mechanisms. We recommend using individual enrollments for devices that require unique initial configurations, or for devices which can only use SAS tokens via TPM or virtual TPM as the attestation mechanism. Individual enrollments may have the desired IoT hub device ID specified. You can create an individual enrollment with the SDKs following this workflow: 1. Choose your ```attestation``` mechanism, which can be TPM or X.509. 1. **TPM**: Using the Endorsement Key from a physical device or from TPM Simulator as the input, you can call Service SDK API ```TpmAttestation``` to create attestation for enrollment. 2. **X.509**: Using the client certificate as the input, you can call Service SDK API ```X509Attestation.createFromClientCertificate``` to create attestation for enrollment. 2. Create a new ```IndividualEnrollment``` variable with using the ```attestation``` created and a unique ```registrationId``` as input, which is on your device or generated from the TPM Simulator. Optionally, you can set parameters like ```Device ID```, ```IoTHubHostName```, ```ProvisioningStatus```. 3. Call Service SDK API ```createOrUpdateIndividualEnrollment``` in your backend application with ```IndividualEnrollment``` to create an individual enrollment. After you have successfully created an enrollment, the Device Provisioning Service returns an enrollment result. This workflow is demonstrated in the samples [mentioned previously](#prerequisites). ## Update an enrollment entry After you have created an enrollment entry, you may want to update the enrollment. Potential scenarios include updating the desired property, updating the attestation method, or revoking device access. There are different APIs for individual enrollment and group enrollment, but no distinction for attestation mechanism. You can update an enrollment entry following this workflow: * **Individual enrollment**: 1. Get the latest enrollment from the provisioning service first with Service SDK API ```getIndividualEnrollment```. 2. Modify the parameter of the latest enrollment as necessary. 3. Using the latest enrollment, call Service SDK API ```createOrUpdateIndividualEnrollment``` to update your enrollment entry. * **Group enrollment**: 1. Get the latest enrollment from the provisioning service first with Service SDK API ```getEnrollmentGroup```. 2. Modify the parameter of the latest enrollment as necessary. 3. Using the latest enrollment, call Service SDK API ```createOrUpdateEnrollmentGroup``` to update your enrollment entry. This workflow is demonstrated in the samples [mentioned previously](#prerequisites). ## Remove an enrollment entry * **Individual enrollment** can be deleted by calling Service SDK API ```deleteIndividualEnrollment``` using ```registrationId```. * **Group enrollment** can be deleted by calling Service SDK API ```deleteEnrollmentGroup``` using ```enrollmentGroupId```. This workflow is demonstrated in the samples [mentioned previously](#prerequisites). ## Bulk operation on individual enrollments You can perform bulk operation to create, update, or remove multiple individual enrollments following this workflow: 1. Create a variable that contains multiple ```IndividualEnrollment```. Implementation of this variable is different for every language. Review the bulk operation sample on GitHub for details. 2. Call Service SDK API ```runBulkOperation``` with a ```BulkOperationMode``` for desired operation and your variable for individual enrollments. Four modes are supported: create, update, updateIfMatchEtag, and delete. After you have successfully performed an operation, the Device Provisioning Service would return a bulk operation result. This workflow is demonstrated in the samples [mentioned previously](#prerequisites). ======================= File: articles/vmware-cloudsimple/high-availability-vpn-connection.md ======================= --- title: Azure VMware Solution by CloudSimple - Configure high availability from on-premises to CloudSimple VPN gateway description: Describes how to configure a high availability connection from your on-premises environment to a CloudSimple VPN gateway enabled for high availability author: sharaths-cs ms.author: b-shsury ms.date: 08/14/2019 ms.topic: article ms.service: azure-vmware-cloudsimple ms.reviewer: cynthn manager: dikamath --- # Configure a high availability connection from on-premises to CloudSimple VPN gateway Network administrators can configure a high availability IPsec Site-to-Site VPN connection from their on-premises environment to a CloudSimple VPN gateway. This guide presents steps to configure an on-premises firewall for an IPsec Site-to-Site VPN high availability connection. The detailed steps are specific to the type of on-premises firewall. As examples, this guide presents steps for two types of firewalls: Cisco ASA and Palo Alto Networks. ## Before you begin Complete the following tasks before you configure the on-premises firewall. 1. Verify that your organization has [provisioned](create-nodes.md) the required nodes and created at least one CloudSimple Private Cloud. 2. [Configure a Site-to-Site VPN gateway](vpn-gateway.md#set-up-a-site-to-site-vpn-gateway) between your on-premises network and your CloudSimple Private Cloud. See [VPN gateways overview](cloudsimple-vpn-gateways.md) for supported phase 1 and phase 2 proposals. ## Configure on-premises Cisco ASA firewall The instructions in this section apply to Cisco ASA version 8.4 and later. In the configuration example, Cisco Adaptive Security Appliance Software Version 9.10 is deployed and configured in IKEv1 mode. For the Site-to-Site VPN to work, you must allow UDP 500/4500 and ESP (IP protocol 50) from the CloudSimple primary and secondary public IP (peer IP) on the outside interface of the on-premises Cisco ASA VPN gateway. ### 1. Configure phase 1 (IKEv1) To enable phase 1 (IKEv1) on the outside interface, enter the following CLI command in the Cisco ASA firewall. ```crypto ikev1 enable outside``` ### 2. Create an IKEv1 policy Create an IKEv1 policy that defines the algorithms and methods to be used for hashing, authentication, Diffie-Hellman group, lifetime, and encryption. ``` crypto ikev1 policy 1 authentication pre-share encryption aes-256 hash sha group 2 lifetime 28800 ``` ### 3. Create a tunnel group Create a tunnel group under the IPsec attributes. Configure the peer IP address and the tunnel pre-shared key, which you set when [configuring your Site-to-Site VPN gateway](vpn-gateway.md#set-up-a-site-to-site-vpn-gateway). ``` tunnel-group <primary peer ip> type ipsec-l2l tunnel-group <primary peer ip> ipsec-attributes ikev1 pre-shared-key ***** tunnel-group <secondary peer ip> type ipsec-l2l tunnel-group <secondary peer ip> ipsec-attributes ikev1 pre-shared-key ***** ``` ### 4. Configure phase 2 (IPsec) To configure phase 2 (IPsec), create an access control list (ACL) that defines the traffic to be encrypted and tunneled. In the following example, the traffic of interest is from the tunnel that is sourced from the on-premises local subnet (10.16.1.0/24) to the Private Cloud remote subnet (192.168.0.0/24). The ACL can contain multiple entries if there are multiple subnets between the sites. In Cisco ASA versions 8.4 and later, objects or object groups can be created that serve as containers for the networks, subnets, host IP addresses, or multiple objects. Create an object for the local and an object for the remote subnets and use them for the crypto ACL and the NAT statements. #### Define an on-premises local subnet as an object ``` object network AZ_inside subnet 10.16.1.0 255.255.255.0 ``` #### Define the CloudSimple remote subnet as an object ``` object network CS_inside subnet 192.168.0.0 255.255.255.0 ``` #### Configure an access list for the traffic of interest ``` access-list ipsec-acl extended permit ip object AZ_inside object CS_inside ``` ### 5. Configure the transform set Configure the transform set (TS), which must involve the keyword ```ikev1```. The encryption and hash attributes specified in the TS must match with the parameters listed in [Default configuration for CloudSimple VPN gateways](cloudsimple-vpn-gateways.md). ``` crypto ipsec ikev1 transform-set devtest39 esp-aes-256 esp-sha-hmac ``` ### 6. Configure the crypto map Configure the crypto map, which contains these components: * Peer IP address * Defined ACL that contains the traffic of interest * Transform Set ``` crypto map mymap 1 set peer <primary peer ip> <secondary peer ip> crypto map mymap 1 match address ipsec-acl crypto map mymap 1 set ikev1 transform-set devtest39 ``` ### 7. Apply the crypto map Apply the crypto map on the outside interface: ```crypto map mymap interface outside``` ### 8. Confirm applicable NAT rules The following is the NAT rule that is used. Ensure that the VPN traffic is not subjected to any other NAT rule. ```nat (inside,outside) source static AZ_inside AZ_inside destination static CS_inside CS_inside``` ### Sample IPsec Site-to-Site VPN established output from Cisco ASA Phase 1 output: ![Phase 1 output for Cisco ASA firewall](media/ha-vpn-connection-cisco-phase1.png) Phase 2 output: ![Phase 2 output for Cisco ASA firewall](media/ha-vpn-connection-cisco-phase2.png) ## Configure on-premises Palo Alto Networks firewall The instructions in this section apply to Palo Alto Networks version 7.1 and later. In this configuration example, Palo Alto Networks VM-Series Software Version 8.1.0 is deployed and configured in IKEv1 mode. For the Site-to-Site VPN to work, you must allow UDP 500/4500 and ESP (IP protocol 50) from the CloudSimple primary and secondary public IP (peer IP) on the outside interface of the on-premises Palo Alto Networks gateway. ### 1. Create primary and secondary tunnel interfaces Sign in to the Palo Alto firewall, select **Network** > **Interfaces** > **Tunnel** > **Add**, configure the following fields, and click **OK**. * Interface Name. The first field is autopopulated with keyword 'tunnel'. In the adjacent field, enter any number between from 1 to 9999. This interface will be used as a primary tunnel interface to carry Site-to-Site traffic between the on-premises datacenter and the Private Cloud. * Comment. Enter comments for easy identification of the purpose of the tunnel * Netflow Profile. Leave default. * Config. Assign Interface To: Virtual Router: Select **default**. Security Zone: Select the zone for trusted LAN traffic. In this example, the name of the zone for LAN traffic is 'Trust'. * IPv4. Click **Add** and add any non-overlapping unused /32 ip address in your environment, which will be assigned to the primary tunnel interface and will be used for monitoring the tunnels (explained later). Because this configuration is for a high availability VPN, two tunnel interfaces are required: One primary and one secondary. Repeat the previous steps to create the secondary tunnel interface. Select a different tunnel ID and a different unused /32 ip address. ### 2. Set up static routes for Private Cloud subnets to be reached over the Site-to-Site VPN Routes are necessary for the on-premises subnets to reach CloudSimple private cloud subnets. Select **Network** > **Virtual Routers** > *default* > **Static Routes** > **Add**, configure the following fields, and click **OK**. * Name. Enter any name for easy identification of the purpose of the route. * Destination. Specify the CloudSimple private cloud subnets to be reached over S2S tunnel interfaces from on-premises * Interface. Select the primary tunnel interface created in step-1(Section-2) from the dropdown. In this example, it is tunnel.20. * Next Hop. Select **None**. * Admin Distance. Leave default. * Metric. Enter any value from 1 to 65535. The key is to enter lower metric for the route corresponding to primary tunnel interface compared to the route corresponding secondary tunnel interface making the former route preferred. If tunnel.20 has metric value of 20 as opposed to a metric value of 30 for tunnel.30, tunnel.20 is preferred. * Route Table. Leave default. * BFD Profile. Leave default. * Path monitoring. Leave unchecked. Repeat the previous steps to create another route for Private Cloud subnets to use as a secondary/backup route via secondary tunnel interface. This time, select different tunnel ID and a higher metric than for the primary route. ### 3. Define the cryptographic profile Define a cryptographic profile that specifies the protocols and algorithms for identification, authentication, and encryption to be used for setting up VPN tunnels in IKEv1 Phase 1. Select **Network** > **Expand Network Profiles** > **IKE Crypto** > **Add**, configure the following fields, and click **OK**. * Name. Enter any name of the IKE crypto profile. * DH Group. Click **Add** and select the appropriate DH group. * Encryption. Click **Add** and select the appropriate encryption method. * Authentication. Click **Add** and select the appropriate authentication method. * Key lifetime. Leave default. * IKEv2 Authentication Multiple. Leave default. ### 4. Define IKE gateways Define IKE gateways to establish communication between the peers across each end of the VPN tunnel. Select **Network** > **Expand Network Profiles** > **IKE Gateways** > **Add**, configure the following fields, and click **OK**. General tab: * Name. Enter the name for the IKE gateway to be peered with the primary CloudSimple VPN peer. * Version. Select **IKEv1 only mode**. * Address Type. Select **IPv4**. * Interface. Select the public facing or outside interface. * Local IP Address. Leave default. * Peer IP Address Type. Select **IP**. * Peer Address. Enter the primary CloudSimple VPN peer IP address. * Authentication. Select **Pre-Shared Key**. * Pre-shared Key / Confirm Pre-shared Key. Enter the pre-shared key to match the CloudSimple VPN gateway key. * Local Identification. Enter the public IP address of the on-premises Palo Alto firewall. * Peer Identification. Enter the primary CloudSimple VPN peer IP address. Advanced Options tab: * Enable Passive Mode. Leave unchecked. * Enable NAT Traversal. Leave unchecked if the on-premises Palo Alto firewall is not behind any NAT device. Otherwise, select the checkbox. IKEv1: * Exchange Mode. Select **main**. * IKE Crypto Profile. Select the IKE Crypto profile that you created earlier. Leave the Enable Fragmentation box unchecked. * Dead Peer Detection. Leave the box unchecked. Repeat the previous steps to create the secondary IKE gateway. ### 5. Define IPSEC Crypto profiles Select **Network** > **Expand Network Profiles** > **IPSEC Crypto** > **Add**, configure the following fields, and click **OK**. * Name. Enter a name for the IPsec crypto profile. * IPsec Protocol. Select **ESP**. * Encryption. Click **Add** and select the appropriate encryption method. * Authentication. Click **Add** and select the appropriate authentication method. * DH Group. Select **no-pfs**. * Lifetime. Set as 30 minutes. * Enable. Leave the box unchecked. Repeat the previous steps to create another IPsec crypto profile, which will be used for as the secondary CloudSimple VPN peer. The same IPSEC Crypto profile can also be used for both the primary and secondary IPsec tunnels (see the following procedure). ### 6. Define monitor profiles for tunnel monitoring Select **Network** > **Expand Network Profiles** > **Monitor** > **Add**, configure the following fields, and click **OK**. * Name. Enter any name of the Monitor profile to be used for tunnel monitoring for proactive reaction to the failure. * Action. Select **Fail Over**. * Interval. Enter the value **3**. * Threshold. Enter the value **7**. ### 7. Set up primary and secondary IPsec tunnels. Select **Network** > **IPsec Tunnels** > **Add**, configure the following fields, and click **OK**. General tab: * Name. Enter any name for the primary IPSEC tunnel to be peered with primary CloudSimple VPN peer. * Tunnel Interface. Select the primary tunnel interface. * Type. Leave default. * Address Type. Select **IPv4**. * IKE Gateway. Select the primary IKE gateway. * IPsec Crypto Profile. Select the primary IPsec profile. Select **Show Advanced options**. * Enable Replay Protection. Leave default. * Copy TOS Header. Leave the box unchecked. * Tunnel Monitor. Check the box. * Destination IP. Enter any IP address belonging to the CloudSimple Private Cloud subnet that is allowed over the Site-to-Site connection. Make sure that the tunnel interfaces (such as tunnel.20 - 10.64.5.2/32 and tunnel.30 - 10.64.6.2/32) on Palo Alto are allowed to reach the CloudSimple Private Cloud IP address over the Site-to-Site VPN. See the following configuration for proxy IDs. * Profile. Select the monitor profile. Proxy IDs tab: Click **IPv4** > **Add** and configure the following: * Proxy ID. Enter any name for the interesting traffic. There could be multiple Proxy IDs carried inside one IPsec tunnel. * Local. Specify the on-premises local subnets that are allowed to communicate with Private Cloud subnets over the Site-to-Site VPN. * Remote. Specify the Private Cloud remote subnets that are allowed to communicate with the local subnets. * Protocol. Select **any**. Repeat the previous steps to create another IPsec tunnel to use for the secondary CloudSimple VPN peer. ## References Configuring NAT on Cisco ASA: <a href="https://www.cisco.com/c/en/us/td/docs/security/asa/asa84/configuration/guide/asa_84_cli_config/nat_objects.html" target="_blank">Cisco ASA 5500 Series Configuration Guide</a> Supported IKEv1 and IKEv2 attributes on Cisco ASA: <a href="https://www.cisco.com/c/en/us/td/docs/security/asa/asa90/configuration/guide/asa_90_cli_config/vpn_ike.html#21661" target="_blank">Cisco ASA Series CLI Configuration Guide</a> Configuring IPsec Site-to-Site VPN on Cisco ASA with version 8.4 and later: <a href="https://www.cisco.com/c/en/us/support/docs/security/asa-5500-x-series-next-generation-firewalls/119141-configure-asa-00.html#anc8" target="_blank">Configure IKEv1 IPsec Site-to-Site Tunnels with the ASDM or CLI on the ASA</a> Configuring Cisco Adaptive Security Appliance virtual (ASAv) on Azure: <a href="https://www.cisco.com/c/en/us/td/docs/security/asa/asa96/asav/quick-start-book/asav-96-qsg/asav-azure.html" target="_blank">Cisco Adaptive Security Virtual Appliance (ASAv) quickstart Guide</a> Configuring Site-to-Site VPN with Proxy IDs on Palo Alto: [Set Up Site-to-Site VPN](https://docs.paloaltonetworks.com/pan-os/9-0/pan-os-admin/vpns/set-up-site-to-site-vpn#) Setting up tunnel monitor: [Set Up Tunnel Monitoring](https://docs.paloaltonetworks.com/pan-os/7-1/pan-os-admin/vpns/set-up-tunnel-monitoring.html) IKE gateway or IPsec tunnel operations: <a href="https://docs.paloaltonetworks.com/pan-os/9-0/pan-os-admin/vpns/set-up-site-to-site-vpn/enabledisable-refresh-or-restart-an-ike-gateway-or-ipsec-tunnel#" target="_blank">Enable/Disable, Refresh, or Restart an IKE Gateway or IPsec Tunnel</a> ======================= File: articles/lab-services/scripts/create-custom-image-from-vhd.md ======================= <filename>articles/lab-services/scripts/create-custom-image-from-vhd.md --- title: PowerShell - Create custom image from VHD file in Azure Lab Services description: This PowerShell script creates a custom image from a VHD file in Azure Lab Services. services: lab-services author: spelluru manager: editor: '' ms.service: lab-services ms.workload: na ms.tgt_pltfrm: na ms.devlang: na ms.topic: article ms.date: 01/16/2020 ms.author: spelluru --- # Use PowerShell to create a custom image from a VHD file in Azure Lab Services This sample PowerShell script creates a custom image from a VHD file in Azure Lab Services [!INCLUDE [updated-for-az](../../../includes/updated-for-az.md)] [!INCLUDE [sample-powershell-install](../../../includes/sample-powershell-install-no-ssh-az.md)] ## Prerequisites * **A lab**. The script requires you to have an existing lab. ## Sample script [!code-powershell[main](../../../powershell_scripts/devtest-lab/create-custom-image-from-vhd/create-custom-image-from-vhd.ps1 "Add external user to a lab")] ## Script explanation This script uses the following commands: | Command | Notes | |---|---| | [Get-AzResource](/powershell/module/az.resources/get-azresource) | Gets resources. | | [Get-AzStorageAccountKey](/powershell/module/az.storage/get-azstorageaccountkey) | Gets the access keys for an Azure Storage account. | | [New-AzResourceGroupDeployment](/powershell/module/az.resources/new-azresourcegroupdeployment) | Adds an Azure deployment to a resource group. | ## Next steps For more information on the Azure PowerShell, see [Azure PowerShell documentation](https://docs.microsoft.com/powershell/). Additional Azure Lab Services PowerShell script samples can be found in the [Azure Lab Services PowerShell samples](../samples-powershell.md). ======================= File: portal-articles/Microsoft_Azure_Compute/Linux/Overview.md ======================= <gh_stars>1-10 --- title: Linux Virtual machines overview | Microsoft Docs description: Help content for Linux Virtual machines overview within Azure portal services: virtual-machines-linux author: sewatson manager: lwelicki ms.service: virtual-machines-linux ms.topic: article ms.date: 04/27/2017 ms.author: sewatson --- # Linux Virtual Machines Documentation Azure Linux Virtual Machines provides on-demand, high-scale, secure, virtualized infrastructure using Red Hat, Ubuntu, or the Linux distribution of your choice. Learn how to create, configure, manage, and scale Linux VMs with our quickstarts, tutorials, and samples. ## 5-Minute Quickstarts Learn how to deploy an NGINX web-server within a Virtual Machine running Ubuntu: - [Azure Portal](/azure/virtual-machines/virtual-machines-linux-quick-create-portal?toc=%2fazure%2fvirtual-machines%2flinux%2ftoc.json) - [Azure PowerShell](/azure/virtual-machines/virtual-machines-linux-quick-create-powershell?toc=%2fazure%2fvirtual-machines%2flinux%2ftoc.json) - [Azure CLI](/azure/virtual-machines/virtual-machines-linux-quick-create-cli?toc=%2fazure%2fvirtual-machines%2flinux%2ftoc.json) ## Step-by-Step Tutorials Learn how to deploy, manage, and scale Linux VMs on Azure. - [Create and manage Linux VMs](/azure/virtual-machines/linux/tutorial-manage-vm) - [Create and manage VM disks](/azure/virtual-machines/linux/tutorial-manage-disks) - [Automate VM configuration](/azure/virtual-machines/linux/tutorial-automate-vm-deployment) - [Create custom VM images](/azure/virtual-machines/linux/tutorial-custom-images) - [Create highly available VMs](/azure/virtual-machines/linux/tutorial-availability-sets) - [Create a VM scale set](/azure/virtual-machines/linux/tutorial-create-vmss) - [Load balance VMs](/azure/virtual-machines/linux/tutorial-load-balancer) - [Manage VMs and virtual networks](/azure/virtual-machines/linux/tutorial-virtual-network) - [Backup VMs](/azure/virtual-machines/linux/tutorial-backup-vms) - [Monitor VMs](/azure/virtual-machines/linux/tutorial-monitoring) - [Manage security on VMs](/azure/virtual-machines/linux/tutorial-azure-security) - [Create a CI/CD infrastructure with Jenkins, Docker, and GitHub](/azure/jenkins/tutorial-jenkins-github-docker-cicd) ## Free Pluralsight Video Training - [Azure Administrator](https://go.microsoft.com/fwlink/?linkid=2012827) ## Samples Deploy your first application to Azure. - [Azure CLI](/azure/virtual-machines/virtual-machines-linux-cli-samples) - [Azure PowerShell](/azure/virtual-machines/virtual-machines-linux-powershell-samples) ## More - [Visit documentation to learn more](/azure/virtual-machines/linux/index) - [Learn about all Azure Services](https://aka.ms/j3wr7y) ======================= File: articles/firewall-manager/vhubs-and-vnets.md ======================= --- title: What are the Azure Firewall Manager architecture options? description: Compare and contrast using hub virtual network or secured virtual hub architectures with Azure Firewall Manager. author: vhorne ms.service: firewall-manager services: firewall-manager ms.topic: article ms.date: 02/18/2020 ms.author: victorh --- # What are the Azure Firewall Manager architecture options? Azure Firewall Manager can provide security management for two network architecture types: - **secured virtual hub** An [Azure Virtual WAN Hub](../virtual-wan/virtual-wan-about.md#resources) is a Microsoft-managed resource that lets you easily create hub and spoke architectures. When security and routing policies are associated with such a hub, it's referred to as a *[secured virtual hub](secured-virtual-hub.md)*. - **hub virtual network** This is a standard Azure virtual network that you create and manage yourself. When security policies are associated with such a hub, it is referred to as a *hub virtual network*. At this time, only Azure Firewall Policy is supported. You can peer spoke virtual networks that contain your workload servers and services. You can also manage firewalls in standalone virtual networks that are not peered to any spoke. ## Comparison The following table compares these two architecture options and can help you decide which one is right for your organization's security requirements: | |**Hub virtual network**|**Secured virtual hub** | |---------|---------|---------| |**Underlying resource** |Virtual network|Virtual WAN Hub| |**Hub & Spoke** |Uses Virtual network peering|Automated using hub virtual network connection| |**On-prem connectivity** |VPN Gateway up to 10 Gbps and 30 S2S connections; ExpressRoute|More scalable VPN Gateway up 20 Gbps and 1000 S2S connections; Express Route| |**Automated branch connectivity using SDWAN** |Not supported|Supported| |**Hubs per region** |Multiple Virtual Networks per region|Single Virtual Hub per region. Multiple hubs possible with multiple Virtual WANs| |**Azure Firewall – multiple public IP addresses** |Customer provided|Auto generated. To be available by GA.| |**Azure Firewall Availability Zones** |Supported|Not available in preview. To be available by GA| |**Advanced Internet security with third-party Security as a Service partners** |Customer established and managed VPN connectivity to partner service of choice|Automated via Trusted Security Partner flow and partner management experience| |**Centralized route management to route traffic to the hub** |Customer-managed User Defined Route|Supported using BGP| |**Web Application Firewall on Application Gateway** |Supported in Virtual Network|Currently supported in spoke network| |**Network Virtual Appliance**|Supported in Virtual Network|Currently supported in spoke network| ## Next steps - Review [Azure Firewall Manager Preview deployment overview](deployment-overview.md) - Learn about [secured Virtual Hubs](secured-virtual-hub.md). ======================= File: articles/cognitive-services/LUIS/sdk-query-prediction-endpoint.md ======================= <reponame>gbuchmsft/azure-docs --- title: "Quickstart: SDK query prediction endpoint - LUIS" description: This quickstart will show you how to use the SDK to send a user utterance to the Azure Cognitive Services LUIS application and receive a prediction. ms.topic: quickstart ms.date: 05/28/2020 ms.custom: tracking-python zone_pivot_groups: programming-languages-set-diberry-3core --- # Quickstart: Query V3 prediction endpoint with SDK Use the SDK, to send a user utterance to Language Understanding (LUIS) and receive a prediction of the user's intention. ::: zone pivot="programming-language-csharp" [!INCLUDE [Get prediction with C# SDK](./includes/sdk-csharp-prediction.md)] ::: zone-end ::: zone pivot="programming-language-javascript" [!INCLUDE [Get prediction with Node.js SDK](./includes/sdk-nodejs-prediction.md)] ::: zone-end ::: zone pivot="programming-language-python" [!INCLUDE [Get prediction with Python SDK](./includes/sdk-python-prediction.md)] ::: zone-end ## Next steps > [!div class="nextstepaction"] > [Tutorial: Build LUIS app to determine user intentions](luis-quickstart-intents-only.md) ======================= File: articles/media-services/live-video-analytics-edge/detect-motion-record-video-clips-edge-devices-quickstart.md ======================= --- title: Detect motion, record video on edge devices - Azure description: This quickstart shows you how to use Live Video Analytics on IoT Edge to analyze the live video feed from a (simulated) IP camera, detect if any motion is present, and if so, record an MP4 video clip to the local file system on the edge device. ms.topic: quickstart ms.date: 04/27/2020 --- # Quickstart: Detect motion, record video on edge devices This quickstart shows you how to use Live Video Analytics on IoT Edge to analyze the live video feed from a (simulated) IP camera, detect if any motion is present, and if so, record an MP4 video clip to the local file system on the edge device. It uses an Azure VM as an IoT Edge device and a simulated live video stream. This article is based on sample code written in C#. This article builds on top of [this](detect-motion-emit-events-quickstart.md) quickstart. ## Prerequisites * An Azure account with an active subscription. [Create an account for free](https://azure.microsoft.com/free/?WT.mc_id=A261C142F). * [Visual Studio Code](https://code.visualstudio.com/) on your machine with the following extensions: * [Azure IoT Tools](https://marketplace.visualstudio.com/items?itemName=vsciot-vscode.azure-iot-tools) * [C#](https://marketplace.visualstudio.com/items?itemName=ms-dotnettools.csharp) * [.NET Core 3.1 SDK](https://dotnet.microsoft.com/download/dotnet-core/3.1) installed on your system * If you have not previously completed [this](detect-motion-emit-events-quickstart.md) quickstart, then finish the following steps: * [Set up Azure resources](detect-motion-emit-events-quickstart.md#set-up-azure-resources) * [Set up your development environment](detect-motion-emit-events-quickstart.md#set-up-your-development-environment) * [Generate and deploy the IoT Edge deployment manifest](detect-motion-emit-events-quickstart.md#generate-and-deploy-the-iot-edge-deployment-manifest) * [Prepare for monitoring events](detect-motion-emit-events-quickstart.md#prepare-for-monitoring-events) > [!TIP] > When installing the Azure IoT Tools, you might be prompted to install docker. Feel free to ignore it. ## Review the sample video As part of the steps above to set up the Azure resources, a (short) video of a parking lot will be copied to the Linux VM in Azure being used as the IoT Edge device. This video file will be used to simulate a live stream for this tutorial. You can use an application like [VLC Player](https://www.videolan.org/vlc/), launch it, hit Control+N, and paste [this](https://lvamedia.blob.core.windows.net/public/lots_015.mkv) link to the parking lot video to start playback. At about the 5-second mark, a white car moves through the parking lot. When you complete the steps below, you will have used Live Video Analytics on IoT Edge to detect that motion of the car, and record a video clip starting at around that 5-second mark. ## Overview ![overview](./media/quickstarts/overview-qs4.png) The diagram above shows how the signals flow in this quickstart. An edge module (detailed [here](https://github.com/Azure/live-video-analytics/tree/master/utilities/rtspsim-live555)) simulates an IP camera hosting an RTSP server. An [RTSP source](media-graph-concept.md#rtsp-source) node pulls the video feed from this server, and sends video frames to the [motion detection processor](media-graph-concept.md#motion-detection-processor) node. The RTSP source sends the same video frames to a [signal gate processor](media-graph-concept.md#signal-gate-processor) node, which remains closed until it is triggered by an event. When the motion detection processor determines that motion is present in the video, it sends an event to the signal gate processor node, triggering it. The gate opens for the configured duration of time, sending video frames to the [file sink](media-graph-concept.md#file-sink) node. This sink node records the video as an MP4 file to the local file system of your edge device, at the configured location. In this quickstart, you will: 1. Create and deploy the media graph 1. Interpret the results 1. Clean up resources ## Examine and edit the sample files As part of the pre-requisites, you would have downloaded the sample code to a folder. Launch Visual Studio Code, and open the folder. 1. In Visual Studio Code, browse to "src/edge". You will see the.env file that you created along with a few deployment template files * The deployment template refers to the deployment manifest for the edge device with some placeholder values. The.env file has the values for those variables. 1. Next, browse to "src/cloud-to-device-console-app" folder. Here you will see the appsettings.json file that you created along with a few other files: * c2d-console-app.csproj - This is the project file for Visual Studio Code * operations.json - This file will list the different operations that you would like the program to run * Program.cs - This is the sample program code, which does the following: * Loads the app settings * Invokes direct methods exposed by the Live Video Analytics on IoT Edge module. You can use the module to analyze live video streams by invoking its [direct methods](direct-methods.md) * Pauses for you to examine the output from the program in the TERMINAL window and the events generated by the module in the OUTPUT window * Invokes direct methods to clean up resources 1. Make the following edits to the operations.json file * Change the link to the graph topology: `"topologyUrl" : "https://raw.githubusercontent.com/Azure/live-video-analytics/master/MediaGraph/topologies/evr-motion-files/topology.json"` * Under GraphInstanceSet, edit the name of the graph topology to match the value in the link above `"topologyName" : "EVRToFilesOnMotionDetection"` * Also edit the RTSP URL to point to the desired video file `"value": "rtsp://rtspsim:554/media/lots_015.mkv"` * Under GraphTopologyDelete, edit the name `"name": "EVRToFilesOnMotionDetection"` ## Review - check status of the modules At the [Generate and deploy the IoT Edge deployment manifest](detect-motion-emit-events-quickstart.md#generate-and-deploy-the-iot-edge-deployment-manifest) step, in Visual Studio Code, if you expand the "lva-sample-device" node under AZURE IOT HUB (at the bottom-left section) you should see the following modules deployed 1. The Live Video Analytics module, named as “lvaEdge” 1. A module named “rtspsim” which simulates an RTSP Server, acting as the source of a live video feed ![Modules](./media/quickstarts/lva-sample-device-node.png) ## Review - prepare for monitoring events Check that you have completed the steps to [Prepare for monitoring events](detect-motion-emit-events-quickstart.md#prepare-for-monitoring-events) ![Start Monitoring Built-in Event Endpoint](./media/quickstarts/start-monitoring-iothub-events.png) ## Run the sample program 1. Start a debugging session (hit F5). You will start seeing some messages printed in the TERMINAL window. 1. The operations.json starts off with calls to the direct methods GraphTopologyList and GraphInstanceList. If you have cleaned up resources after previous quickstarts, this will return empty lists, and then pause for you to hit Enter ``` -------------------------------------------------------------------------- Executing operation GraphTopologyList ----------------------- Request: GraphTopologyList -------------------------------------------------- { "@apiVersion": "1.0" } --------------- Response: GraphTopologyList - Status: 200 --------------- { "value": [] } -------------------------------------------------------------------------- Executing operation WaitForInput Press Enter to continue ``` 1. When you press the "Enter" key in the TERMINAL window, the next set of direct method calls are made * A call to GraphTopologySet using the topologyUrl above * A call to GraphInstanceSet using the following body ``` { "@apiVersion": "1.0", "name": "Sample-Graph", "properties": { "topologyName": "EVRToFilesOnMotionDetection", "description": "Sample graph description", "parameters": [ { "name": "rtspUrl", "value": "rtsp://rtspsim:554/media/lots_015.mkv" }, { "name": "rtspUserName", "value": "testuser" }, { "name": "rtspPassword", "value": "<PASSWORD>" } ] } } ``` * A call to GraphInstanceActivate to start the graph instance, and start the flow of video * A second call to GraphInstanceList to show that the graph instance is indeed in the running state 1. The output in the TERMINAL window will pause now at a 'Press Enter to continue' prompt. Do not hit "Enter" at this time. You can scroll up to see the JSON response payloads for the direct methods you invoked 1. If you now switch over to the OUTPUT window in Visual Studio Code, you will see messages that are being sent to the IoT Hub, by the Live Video Analytics on IoT Edge module. * These messages are discussed in the section below 1. The media graph will continue to run, and print results – the RTSP simulator will keep looping the source video. In order to stop the media graph, you go back to the TERMINAL window and hit "Enter". The next series of calls are made to clean up resources: * A call to GraphInstanceDeactivate to deactivate the graph instance * A call to GraphInstanceDelete to delete the instance * A call to GraphTopologyDelete to delete the topology * A final call to GraphTopologyList to show that the list is now empty ## Interpret results When you run the media graph, the results from the motion detector processor node are sent via the IoT Hub sink node to the IoT Hub. The messages you see in the OUTPUT window of Visual Studio Code contain a "body" section and an "applicationProperties" section. To understand what these sections represent, read [this](https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-messages-construct) article. In the messages below, the application properties and the content of the body are defined by the Live Video Analytics module. ## MediaSession Established event When a media graph is instantiated, the RTSP source node attempts to connect to the RTSP server running on the rtspsim-live555 container. If successful, it will print this event: ``` [IoTHubMonitor] [05:37:21 AM] Message received from [lva-sample-device/lvaEdge]: { "body": { "sdp": "SDP:\nv=0\r\no=- 1586450538111534 1 IN IP4 xxx.xxx.xxx.xxx\r\ns=Matroska video+audio+(optional)subtitles, streamed by the LIVE555 Media Server\r\ni=media/camera-300s.mkv\r\nt=0 0\r\na=tool:LIVE555 Streaming Media v2020.03.06\r\na=type:broadcast\r\na=control:*\r\na=range:npt=0-300.000\r\na=x-qt-text-nam:Matroska video+audio+(optional)subtitles, streamed by the LIVE555 Media Server\r\na=x-qt-text-inf:media/camera-300s.mkv\r\nm=video 0 RTP/AVP 96\r\nc=IN IP4 0.0.0.0\r\nb=AS:500\r\na=rtpmap:96 H264/90000\r\na=fmtp:96 packetization-mode=1;profile-level-id=4D0029;sprop-parameter-sets={SPS}\r\na=control:track1\r\n" }, "applicationProperties": { "dataVersion": "1.0", "topic": "/subscriptions/{subscriptionID}/resourceGroups/{name}/providers/microsoft.media/mediaservices/hubname", "subject": "/graphInstances/Sample-Graph-1/sources/rtspSource", "eventType": "Microsoft.Media.MediaGraph.Diagnostics.MediaSessionEstablished", "eventTime": "2020-05-21T05:37:21.398Z", } } ``` * The message is a Diagnostics event, MediaSessionEstablished, indicates that the RTSP source node (the subject) was able to establish connection with the RTSP simulator, and begin to receive a (simulated) live feed. * The "subject" in applicationProperties references the node in the graph topology from which the message was generated. In this case, the message is originating from the RTSP source node. * "eventType" in applicationProperties indicates that this is a Diagnostics event. * "eventTime" indicates the time when the event occurred. * "body" contains data about the diagnostic event, which, in this case, is the [SDP](https://en.wikipedia.org/wiki/Session_Description_Protocol) details. ## Recording Started event As explained [here](#overview), when motion is detected, the signal gate processor node is activated and the file sink node in the media graph starts to the write an MP4 file. The file sink node sends an Operational event. The type is set to “motion” to indicate it’s a result from the Motion Detection Processor, and the eventTime tells you at what time (UTC) motion occurred. Below is an example: ``` [IoTHubMonitor] [05:37:27 AM] Message received from [lva-sample-device/lvaEdge]: { "body": { "outputType": "filePath", "outputLocation": "/var/media/sampleFilesFromEVR-filesinkOutput-20200521T053726Z.mp4" }, "applicationProperties": { "topic": "/subscriptions/{subscriptionID}/resourceGroups/{name}/providers/microsoft.media/mediaservices/hubname", "subject": "/graphInstances/Sample-Graph-1/sinks/fileSink", "eventType": "Microsoft.Media.Graph.Operational.RecordingStarted", "eventTime": "2020-05-21T05:37:27.713Z", "dataVersion": "1.0" } } ``` * "subject" in applicationProperties references the node in the media graph from which the message was generated. In this case, the message is originating from the file sink node. * "eventType" in applicationProperties indicates that this is an Operational event. * "eventTime" indicates the time when the event occurred. Note that this 5-6 seconds after the MediaSessionEstablished and video starts to flow. This corresponds to the 5-6 second mark when the [car started to move](#review-the-sample-video) into the parking lot * "body" contains data about the operational event, which in this case is "outputType" and "outputLocation" data. * "outputType" indicates that this information is about the file path * "outputLocation" provides the location of the MP4 file, from within the edge module ## Recording Stopped and Available events If you examine the properties of the signal gate processor node in the [graph topology](https://github.com/Azure/live-video-analytics/blob/master/MediaGraph/topologies/evr-motion-files/topology.json), you will see that the activation times have been set to 5 seconds. So about 5 seconds after the RecordingStarted event is received, you will get a * RecordingStopped event, indicating that the recording has stopped * RecordingAvailable event, indicating that the MP4 file can now be used for viewing The two events are typically emitted with seconds of each other. ### Playing back the MP4 clip 1. The MP4 files are written to a directory on the edge device that you configured in the.env file via this key - OUTPUT_VIDEO_FOLDER_ON_DEVICE. If you left it to the default value then the results should be in /home/lvaadmin/samples/output/ 1. Go to your resource group, find the VM and connect using Bastion ![Resource group](./media/quickstarts/resource-group.png) ![VM](./media/quickstarts/virtual-machine.png) 1. Once signed in (using credentials that were generated during [this](detect-motion-emit-events-quickstart.md#set-up-azure-resources) step), on the command prompt, go to the relevant directory (default: /home/lvaadmin/samples/output) and you should see the MP4 files there. You can [scp the files](https://docs.microsoft.com/azure/virtual-machines/linux/copy-files-to-linux-vm-using-scp) over to your local machine and play them back via [VLC player](https://www.videolan.org/vlc/) or any other MP4 player. ![Output](./media/quickstarts/samples-output.png) ## Clean up resources If you intend to try the other quickstarts, you should hold on to the resources created. Otherwise, go to the Azure portal, browse to your resource groups, select the resource group under which you ran this quickstart, and delete all the resources. ## Next steps * Run the [Run Live Video Analytics with your own model](use-your-model-quickstart.md) quickstart, which shows how to apply AI to live video feeds. * Review additional challenges for advanced users: * Use an [IP camera](https://en.wikipedia.org/wiki/IP_camera) with support for RTSP instead of using the RTSP simulator. You can search for IP cameras with RTSP support on the [ONVIF conformant products](https://en.wikipedia.org/wiki/IP_camera) page by looking for devices that conform with profiles G, S, or T. * Use an AMD64 or X64 Linux device (vs. using an Azure Linux VM). This device must be in the same network as the IP camera. You can follow instructions in [Install Azure IoT Edge runtime on Linux](https://docs.microsoft.com/azure/iot-edge/how-to-install-iot-edge-linux) and then follow instructions in the [Deploy your first IoT Edge module to a virtual Linux device](https://docs.microsoft.com/azure/iot-edge/quickstart-linux) quickstart to register the device with Azure IoT Hub. ======================= File: includes/functions-add-storage-binding-csharp-library-code.md ======================= --- author: ggailey777 ms.service: azure-functions ms.topic: include ms.date: 07/05/2019 ms.author: glenga --- Add code that uses the `msg` output binding object to create a queue message. Add this code before the method returns. :::code language="csharp" range="28-32" source="~/functions-docs-csharp/functions-add-output-binding-storage-queue-cli/HttpExample.cs" ::: At this point, your function should look as follows: :::code language="csharp" source="~/functions-docs-csharp/functions-add-output-binding-storage-queue-cli/HttpExample.cs" range="14-36"::: ======================= File: articles/active-directory-b2c/identity-provider-amazon-custom.md ======================= --- title: Set up sign-in with an Amazon account using custom policies titleSuffix: Azure AD B2C description: Set up sign-in with an Amazon account in Azure Active Directory B2C using custom policies. services: active-directory-b2c author: msmimart manager: celestedg ms.service: active-directory ms.workload: identity ms.topic: conceptual ms.date: 05/04/2020 ms.author: mimart ms.subservice: B2C --- # Set up sign-in with an Amazon account using custom policies in Azure Active Directory B2C [!INCLUDE [active-directory-b2c-advanced-audience-warning](../../includes/active-directory-b2c-advanced-audience-warning.md)] This article shows you how to enable sign-in for users from an Amazon account by using [custom policies](custom-policy-overview.md) in Azure Active Directory B2C (Azure AD B2C). ## Prerequisites - Complete the steps in [Get started with custom policies](custom-policy-get-started.md). - If you don't already have an Amazon account, create one at [https://www.amazon.com/](https://www.amazon.com/). ## Create an app in the Amazon developer console To use an Amazon account as a federated identity provider in Azure Active Directory B2C (Azure AD B2C), you need to create an application in your [Amazon Developer Services and Technologies](https://developer.amazon.com). If you don't already have an Amazon account, you can sign up at [https://www.amazon.com/](https://www.amazon.com/). > [!NOTE] > Use the following URLs in **step 8** below, replacing `your-tenant-name` with the name of your tenant. When entering your tenant name, use all lowercase letters, even if the tenant is defined with uppercase letters in Azure AD B2C. > - For **Allowed Origins**, enter `https://your-tenant-name.b2clogin.com` > - For **Allowed Return URLs**, enter `https://your-tenant-name.b2clogin.com/your-tenant-name.onmicrosoft.com/oauth2/authresp` [!INCLUDE [identity-provider-amazon-idp-register.md](../../includes/identity-provider-amazon-idp-register.md)] ## Create a policy key You need to store the client secret that you previously recorded in your Azure AD B2C tenant. 1. Sign in to the [Azure portal](https://portal.azure.com/). 2. Make sure you're using the directory that contains your Azure AD B2C tenant by selecting the **Directory + subscription** filter in the top menu and choosing the directory that contains your tenant. 3. Choose **All services** in the top-left corner of the Azure portal, and then search for and select **Azure AD B2C**. 4. On the Overview page, select **Identity Experience Framework**. 5. Select **Policy Keys** and then select **Add**. 6. For **Options**, choose `Manual`. 7. Enter a **Name** for the policy key. For example, `AmazonSecret`. The prefix `B2C_1A_` is added automatically to the name of your key. 8. In **Secret**, enter your client secret that you previously recorded. 9. For **Key usage**, select `Signature`. 10. Click **Create**. ## Add a claims provider If you want users to sign in by using an Amazon account, you need to define the account as a claims provider that Azure AD B2C can communicate with through an endpoint. The endpoint provides a set of claims that are used by Azure AD B2C to verify that a specific user has authenticated. You can define an Amazon account as a claims provider by adding it to the **ClaimsProviders** element in the extension file of your policy. 1. Open the *TrustFrameworkExtensions.xml*. 2. Find the **ClaimsProviders** element. If it does not exist, add it under the root element. 3. Add a new **ClaimsProvider** as follows: ```xml <ClaimsProvider> <Domain>amazon.com</Domain> <DisplayName>Amazon</DisplayName> <TechnicalProfiles> <TechnicalProfile Id="Amazon-OAUTH"> <DisplayName>Amazon</DisplayName> <Protocol Name="OAuth2" /> <Metadata> <Item Key="ProviderName">amazon</Item> <Item Key="authorization_endpoint">https://www.amazon.com/ap/oa</Item> <Item Key="AccessTokenEndpoint">https://api.amazon.com/auth/o2/token</Item> <Item Key="ClaimsEndpoint">https://api.amazon.com/user/profile</Item> <Item Key="scope">profile</Item> <Item Key="HttpBinding">POST</Item> <Item Key="UsePolicyInRedirectUri">0</Item> <Item Key="client_id">Your Amazon application client ID</Item> </Metadata> <CryptographicKeys> <Key Id="client_secret" StorageReferenceId="B2C_1A_AmazonSecret" /> </CryptographicKeys> <OutputClaims> <OutputClaim ClaimTypeReferenceId="issuerUserId" PartnerClaimType="user_id" /> <OutputClaim ClaimTypeReferenceId="email" PartnerClaimType="email" /> <OutputClaim ClaimTypeReferenceId="displayName" PartnerClaimType="name" /> <OutputClaim ClaimTypeReferenceId="identityProvider" DefaultValue="amazon.com" /> <OutputClaim ClaimTypeReferenceId="authenticationSource" DefaultValue="socialIdpAuthentication" /> </OutputClaims> <OutputClaimsTransformations> <OutputClaimsTransformation ReferenceId="CreateRandomUPNUserName" /> <OutputClaimsTransformation ReferenceId="CreateUserPrincipalName" /> <OutputClaimsTransformation ReferenceId="CreateAlternativeSecurityId" /> </OutputClaimsTransformations> <UseTechnicalProfileForSessionManagement ReferenceId="SM-SocialLogin" /> </TechnicalProfile> </TechnicalProfiles> </ClaimsProvider> ``` 4. Set **client_id** to the application ID from the application registration. 5. Save the file. ### Upload the extension file for verification By now, you have configured your policy so that Azure AD B2C knows how to communicate with your Azure AD directory. Try uploading the extension file of your policy just to confirm that it doesn't have any issues so far. 1. On the **Custom Policies** page in your Azure AD B2C tenant, select **Upload Policy**. 2. Enable **Overwrite the policy if it exists**, and then browse to and select the *TrustFrameworkExtensions.xml* file. 3. Click **Upload**. ## Register the claims provider At this point, the identity provider has been set up, but it’s not available in any of the sign-up/sign-in screens. To make it available, you create a duplicate of an existing template user journey, and then modify it so that it also has the Amazon identity provider. 1. Open the *TrustFrameworkBase.xml* file from the starter pack. 2. Find and copy the entire contents of the **UserJourney** element that includes `Id="SignUpOrSignIn"`. 3. Open the *TrustFrameworkExtensions.xml* and find the **UserJourneys** element. If the element doesn't exist, add one. 4. Paste the entire content of the **UserJourney** element that you copied as a child of the **UserJourneys** element. 5. Rename the ID of the user journey. For example, `SignUpSignInAmazon`. ### Display the button The **ClaimsProviderSelection** element is analogous to an identity provider button on a sign-up/sign-in screen. If you add a **ClaimsProviderSelection** element for an Amazon account, a new button shows up when a user lands on the page. 1. Find the **OrchestrationStep** element that includes `Order="1"` in the user journey that you created. 2. Under **ClaimsProviderSelects**, add the following element. Set the value of **TargetClaimsExchangeId** to an appropriate value, for example `AmazonExchange`: ```XML <ClaimsProviderSelection TargetClaimsExchangeId="AmazonExchange" /> ``` ### Link the button to an action Now that you have a button in place, you need to link it to an action. The action, in this case, is for Azure AD B2C to communicate with an Amazon account to receive a token. 1. Find the **OrchestrationStep** that includes `Order="2"` in the user journey. 2. Add the following **ClaimsExchange** element making sure that you use the same value for the ID that you used for **TargetClaimsExchangeId**: ```XML <ClaimsExchange Id="AmazonExchange" TechnicalProfileReferenceId="Amazon-OAuth" /> ``` Update the value of **TechnicalProfileReferenceId** to the ID of the technical profile you created earlier. For example, `Amazon-OAuth`. 3. Save the *TrustFrameworkExtensions.xml* file and upload it again for verification. ## Create an Azure AD B2C application Communication with Azure AD B2C occurs through an application that you register in your B2C tenant. This section lists optional steps you can complete to create a test application if you haven't already done so. [!INCLUDE [active-directory-b2c-appreg-idp](../../includes/active-directory-b2c-appreg-idp.md)] ## Update and test the relying party file Update the relying party (RP) file that initiates the user journey that you created. 1. Make a copy of *SignUpOrSignIn.xml* in your working directory, and rename it. For example, rename it to *SignUpSignInAmazon.xml*. 2. Open the new file and update the value of the **PolicyId** attribute for **TrustFrameworkPolicy** with a unique value. For example, `SignUpSignInAmazon`. 3. Update the value of **PublicPolicyUri** with the URI for the policy. For example,`http://contoso.com/B2C_1A_signup_signin_amazon` 4. Update the value of the **ReferenceId** attribute in **DefaultUserJourney** to match the ID of the new user journey that you created (SignUpSignAmazon). 5. Save your changes, upload the file, and then select the new policy in the list. 6. Make sure that Azure AD B2C application that you created is selected in the **Select application** field, and then test it by clicking **Run now**. ======================= File: articles/cognitive-services/LUIS/luis-glossary.md ======================= --- title: Glossary - LUIS description: The glossary explains terms that you might encounter as you work with the LUIS API Service. ms.topic: reference ms.date: 05/08/2020 --- # Language understanding glossary of common vocabulary and concepts The Language Understanding (LUIS) glossary explains terms that you might encounter as you work with the LUIS service. ## Active version The active version is the [version](luis-how-to-manage-versions.md) of your app that is updated when you make changes to the model using the LUIS portal. In the LUIS portal, if you want to make changes to a version that is not the active version, you need to first set that version as active. ## Active learning Active learning is a technique of machine learning in which the machine learned model is used to identify informative new examples to label. In LUIS, active learning refers to adding utterances from the endpoint traffic whose current predictions are unclear to improve your model. Click on "review endpoint utterances", to view utterances to label. See also: * [Conceptual information](luis-concept-review-endpoint-utterances.md) * [Tutorial reviewing endpoint utterances](luis-tutorial-review-endpoint-utterances.md) * How to improve the LUIS app by [reviewing endpoint utterances](luis-how-to-review-endpoint-utterances.md) ## Application (App) In LUIS, your application, or app, is a collection of machine learned models, built on the same data set, that works together to predict intents and entities for a particular scenario. Each application has a separate prediction endpoint. If you are building an HR bot, you might have a set of intents, such as "Schedule leave time", "inquire about benefits" and "update personal information" and entities for each one of those intents that you group into a single application. ## Authoring Authoring is the ability to create, manage and deploy a LUIS app, either using the LUIS portal or the authoring APIs. ### Authoring Key The [authoring key](luis-concept-keys.md) is used to author the app. Not used for production-level endpoint queries. For more information, see [Key limits](luis-limits.md#key-limits). ### Authoring Resource Your LUIS [authoring resource](luis-concept-keys.md#azure-resources-for-luis) is a manageable item that is available through Azure. The resource is your access to the associated authoring, training, and publishing abilities of the Azure service. The resource includes authentication, authorization, and security information you need to access the associated Azure service. The authoring resource has an Azure "kind" of `LUIS-Authoring`. ## Batch test Batch testing is the ability to validate a current LUIS app's models with a consistent and known test set of user utterances. The batch test is defined in a [JSON formatted file](luis-concept-batch-test.md#batch-file-format). See also: * [Concepts](luis-concept-batch-test.md) * [How-to](luis-how-to-batch-test.md) run a batch test * [Tutorial](luis-tutorial-batch-testing.md) - create and run a batch test ### F-measure In batch testing, a measure of the test's accuracy. ### False negative (FN) In batch testing, the data points represent utterances in which your app incorrectly predicted the absence of the target intent/entity. ### False positive (FP) In batch testing, the data points represent utterances in which your app incorrectly predicted the existence of the target intent/entity. ### Precision In batch testing, precision (also called positive predictive value) is the fraction of relevant utterances among the retrieved utterances. An example for an animal batch test is the number of sheep that were predicted divided by the total number of animals (sheep and non-sheep alike). ### Recall In batch testing, recall (also known as sensitivity), is the ability for LUIS to generalize. An example for an animal batch test is the number of sheep that were predicted divided by the total number of sheep available. ### True negative (TN) A true negative is when your app correctly predicts no match. In batch testing, a true negative occurs when your app does predict an intent or entity for an example that has not been labeled with that intent or entity. ### True positive (TP) True positive (TP) A true positive is when your app correctly predicts a match. In batch testing, a true positive occurs when your app predicts an intent or entity for an example that has been labeled with that intent or entity. ## Classifier A classifier is a machine learned model that predicts what category or class an input fits into. An [intent](#intent) is an example of a classifier. ## Collaborator A collaborator is conceptually the same thing as a [contributor](#contributor). A collaborator is granted access when an owner adds the collaborator's email address to an app that isn't controlled with role-based access (RBAC). If you are still using collaborators, you should migrate your LUIS account, and use LUIS authoring resources to manage contributors with RBAC. ## Contributor A contributor is not the [owner](#owner) of the app, but has the same permissions to add, edit, and delete the intents, entities, utterances. A contributor provides role-based access (RBAC) to a LUIS app. See also: * [How-to](luis-how-to-collaborate.md#add-contributor-to-azure-authoring-resource) add contributors ## Descriptor A descriptor is the term formerly used for a machine learning [feature](#features). ## Domain In the LUIS context, a domain is an area of knowledge. Your domain is specific to your scenario. Different domains use specific language and terminology that have meaning in the context of the domain. For example, if you are building an application to play music, your application would have terms and language specific to music – words like "song, track, album, lyrics, b-side, artist". For examples of domains, see [prebuilt domains](#prebuilt-domain). ## Endpoint ### Authoring endpoint The LUIS authoring endpoint URL is where you author, train, and publish your app. The endpoint URL contains the region or custom subdomain of the published app as well as the app ID. Learn more about authoring your app programmatically from the [Developer reference](developer-reference-resource.md#rest-endpoints) ### Prediction endpoint The LUIS prediction endpoint URL is where you submit LUIS queries after the [LUIS app](#application-app) is authored and published. The endpoint URL contains the region or custom subdomain of the published app as well as the app ID. You can find the endpoint on the **[Azure resources](luis-how-to-azure-subscription.md)** page of your app, or you can get the endpoint URL from the [Get App Info](https://westus.dev.cognitive.microsoft.com/docs/services/5890b47c39e2bb17b84a55ff/operations/5890b47c39e2bb052c5b9c37) API. Your access to the prediction endpoint is authorized with the LUIS prediction key. ## Entity [Entities](luis-concept-entity-types.md) are words in utterances that describe information used to fulfill or identify an intent. If your entity is complex and you would like your model to identify specific parts, you can break your model into subentities. For example, you might want you model to predict an address, but also the subentities of street, city, state, and zipcode. Entities can also be used as features to models. Your response from the LUIS app will include both the predicted intents and all the entities. ### Entity extractor An entity extractor sometimes known only as an extractor is the type of machine learned model that LUIS uses to predict entities. ### Entity schema The entity schema is the structure you define for machine learned entities with subentities. The prediction endpoint returns all of the extracted entities and subentities defined in the schema. ### Entity's subentity A subentity is a child entity of a machine-learning entity. ### Non-machine-learning entity An entity that uses text matching to extract data: * List entity * Regular expression entity ### List entity A [list entity](reference-entity-list.md) represents a fixed, closed set of related words along with their synonyms. List entities are exact matches, unlike machined learned entities. The entity will be predicted if a word in the list entity is included in the list. For example, if you have a list entity called "size" and you have the words "small, medium, large" in the list, then the size entity will be predicted for all utterances where the words "small", "medium", or "large" are used regardless of the context. ### Regular expression A [regular expression entity](reference-entity-regular-expression.md) represents a regular expression. Regular expression entities are exact matches, unlike machined learned entities. ### Prebuilt entity See Prebuilt model's entry for [prebuilt entity](#prebuilt-entity) ## Features In machine learning, a feature is a characteristic that helps the model recognize a particular concept. It is a hint that LUIS can use, but not a hard rule. This term is also referred to as a **[machine-learning feature](luis-concept-feature.md)**. These hints are used in conjunction with the labels to learn how to predict new data. LUIS supports both phrase lists and using other models as features. ### Required feature A required feature is a way to constrain the output of a LUIS model. When a feature for an entity is marked as required, the feature must be present in the example for the entity to be predicted, regardless of what the machine learned model predicts. Consider an example where you have a prebuilt-number feature that you have marked as required on the quantity entity for a menu ordering bot. When your bot sees `I want a bajillion large pizzas?`, bajillion will not be predicted as a quantity regardless of the context in which it appears. Bajillion is not a valid number and won’t be predicted by the number pre-built entity. ## Intent An [intent](luis-concept-intent.md) represents a task or action the user wants to perform. It is a purpose or goal expressed in a user's input, such as booking a flight, or paying a bill. In LUIS, an utterance as a whole is classified as an intent, but parts of the utterance are extracted as entities ## Labeling examples Labeling, or marking, is the process of associating a positive or negative example with a model. ### Labeling for intents In LUIS, intents within an app are mutually exclusive. This means when you add an utterance to an intent, it is considered a _positive_ example for that intent and a _negative_ example for all other intents. Negative examples should not be confused with the "None" intent, which represents utterances that are outside the scope of the app. ### Labeling for entities In LUIS, you [label](label-entity-example-utterance.md) a word or phrase in an intent's example utterance with an entity as a _positive_ example. Labeling shows the intent what it should predict for that utterance. The labeled utterances are used to train the intent. ## LUIS app See the definition for [application (app)](#application-app). ## Model A (machine learned) model is a function that makes a prediction on input data. In LUIS, we refer to intent classifiers and entity extractors generically as "models", and we refer to a collection of models that are trained, published, and queried together as an "app". ## Normalized value You add values to your [list](#list-entity) entities. Each of those values can have a list of one or more synonyms. Only the normalized value is returned in the response. ## Overfitting Overfitting happens when the model is fixated on the specific examples and is not able to generalize well. ## Owner Each app has one owner who is the person that created the app. The owner manages permissions to the application in the Azure portal. ## Phrase list A [phrase list](luis-concept-feature.md) is a specific type of machine learning feature that includes a group of values (words or phrases) that belong to the same class and must be treated similarly (for example, names of cities or products). ## Prebuilt model A [prebuilt model](luis-concept-prebuilt-model.md) is an intent, entity, or collection of both, along with labeled examples. These common prebuilt models can be added to your app to reduce the model development work required for your app. ### Prebuilt domain A prebuilt domain is a LUIS app configured for a specific domain such as home automation (HomeAutomation) or restaurant reservations (RestaurantReservation). The intents, utterances, and entities are configured for this domain. ### Prebuilt entity A prebuilt entity is an entity LUIS provides for common types of information such as number, URL, and email. These are created based on public data. You can choose to add a prebuilt entity as a stand-alone entity, or as a feature to an entity ### Prebuilt intent A prebuilt intent is an intent LUIS provides for common types of information and come with their own labeled example utterances. ## Prediction A prediction is a REST request to the Azure LUIS prediction service that takes in new data (user utterance), and applies the trained and published application to that data to determine what intents and entities are found. ### Prediction key The [prediction key](luis-concept-keys.md) (previously known as the subscription key) is the key associated with the LUIS service you created in Azure that authorizes your usage of the prediction endpoint. This key is not the authoring key. If you have a prediction endpoint key, it should be used for any endpoint requests instead of the authoring key. You can see your current prediction key inside the endpoint URL at the bottom of Azure resources page in LUIS website. It is the value of the subscription-key name/value pair. ### Prediction resource Your LUIS prediction resource is a manageable item that is available through Azure. The resource is your access to the associated prediction of the Azure service. The resource includes predictions. The prediction resource has an Azure "kind" of `LUIS`. ### Prediction score The [score](luis-concept-prediction-score.md) is a number from 0 and 1 that is a measure of how confident the system is that a particular input utterance matches a particular intent. A score closer to 1 means the system is very confident about its output and a score closer to 0 means the system is confident that the input does not match a particular output. Scores in the middle mean the system is very unsure of how to make the decision. For example, take a model that is used to identify if some customer text includes a food order. It might give a score of 1 for "I'd like to order one coffee" (the system is very confident that this is an order) and a score of 0 for "my team won the game last night" (the system is very confident that this is NOT an order). And it might have a score of 0.5 for "let's have some tea" (isn't sure if this is an order or not). ## Programmatic key Renamed to [authoring key](#authoring-key). ## Publish [Publishing](luis-how-to-publish-app.md) means making a LUIS active version available on either the staging or production [endpoint](#endpoint). ## Quota LUIS quota is the limitation of the Azure subscription tier. The LUIS quota can be limited by both requests per second (HTTP Status 429) and total requests in a month (HTTP Status 403). ## Schema Your schema includes your intents and entities along with the subentities. The schema is initially planned for then iterated over time. The schema doesn't include app settings, features, or example utterances. ## Sentiment Analysis Sentiment analysis provides positive or negative values of the utterances provided by [Text Analytics](../text-analytics/overview.md). ## Speech priming Speech priming improves the recognition of spoken words and phrases that are commonly used in your scenario with [Speech Services](../speech-service/overview.md). For speech priming enabled applications, all LUIS labeled examples are used to improve speech recognition accuracy by creating a customized speech model for this specific application. For example, in a chess game you want to make sure that when the user says "Move knight", it isn’t interpreted as "Move night". The LUIS app should include examples in which "knight" is labeled as an entity. ## Starter key A free key to use when first starting out using LUIS. ## Synonyms In LUIS [list entities](reference-entity-list.md), you can create a normalized value, which can each have a list of synonyms. For example, if you create a size entity that has normalized values of small, medium, large, and extra-large. You could create synonyms for each value like this: |Nomalized value| Synonyms| |--|--| |Small| the little one, 8 ounce| |Medium| regular, 12 ounce| |Large| big, 16 ounce| |Xtra large| the biggest one, 24 ounce| The model will return the normalized value for the entity when any of synonyms are seen in the input. ## Test [Testing](luis-concept-test.md) a LUIS app means viewing model predictions. ## Timezone offset The endpoint includes [timezoneOffset](luis-concept-data-alteration.md#change-time-zone-of-prebuilt-datetimev2-entity). This is the number in minutes you want to add or remove from the datetimeV2 prebuilt entity. For example, if the utterance is "what time is it now?", the datetimeV2 returned is the current time for the client request. If your client request is coming from a bot or other application that is not the same as your bot's user, you should pass in the offset between the bot and the user. See [Change time zone of prebuilt datetimeV2 entity](luis-concept-data-alteration.md?#change-time-zone-of-prebuilt-datetimev2-entity). ## Token A [token](luis-language-support.md#tokenization) is the smallest unit of text that LUIS can recognize. This differs slightly across languages. For **English**, a token is a continuous span (no spaces or punctuation) of letters and numbers. A space is NOT a token. |Phrase|Token count|Explanation| |--|--|--| |`Dog`|1|A single word with no punctuation or spaces.| |`RMT33W`|1|A record locator number. It may have numbers and letters, but does not have any punctuation.| |`425-555-5555`|5|A phone number. Each punctuation mark is a single token so `425-555-<PASSWORD>` would be 5 tokens:<br>`425`<br>`-`<br>`555`<br>`-`<br>`5555` | |`https://luis.ai`|7|`https`<br>`:`<br>`/`<br>`/`<br>`luis`<br>`.`<br>`ai`<br>| ## Train [Training](luis-how-to-train.md) is the process of teaching LUIS about any changes to the active version since the last training. ### Training data Training data is the set of information that is needed to train a model. This includes the schema, labeled utterances, features, and application settings. ### Training errors Training errors are predictions on your training data that do not match their labels. ## Utterance An [utterance](luis-concept-utterance.md) is user input that is short text representative of a sentence in a conversation. It is a natural language phrase such as "book 2 tickets to Seattle next Tuesday". Example utterances are added to train the model and the model predicts on new utterance at runtime ## Version A LUIS [version](luis-how-to-manage-versions.md) is a specific instance of a LUIS application associated with a LUIS app ID and the published endpoint. Every LUIS app has at least one version. ======================= File: articles/internet-peering/howto-legacy-exchange-powershell.md ======================= <gh_stars>1-10 --- title: Convert a legacy Exchange peering to an Azure resource by using PowerShell titleSuffix: Azure description: Convert a legacy Exchange peering to an Azure resource by using PowerShell services: internet-peering author: prmitiki ms.service: internet-peering ms.topic: how-to ms.date: 11/27/2019 ms.author: prmitiki --- # Convert a legacy Exchange peering to an Azure resource by using PowerShell This article describes how to convert an existing legacy Exchange peering to an Azure resource by using PowerShell cmdlets. If you prefer, you can complete this guide by using the Azure [portal](howto-legacy-exchange-portal.md). ## Before you begin * Review the [prerequisites](prerequisites.md) and the [Exchange peering walkthrough](walkthrough-exchange-all.md) before you begin configuration. ### Work with Azure PowerShell [!INCLUDE [CloudShell](./includes/cloudshell-powershell-about.md)] ## Convert a legacy Exchange peering to an Azure resource ### Sign in to your Azure account and select your subscription [!INCLUDE [Account](./includes/account-powershell.md)] ### <a name= get></a>Get legacy Exchange peering for conversion This example shows how to get legacy Exchange peering at the Seattle peering location: ```powershell $legacyPeering = Get-AzLegacyPeering -Kind Exchange -PeeringLocation "Seattle" $legacyPeering ``` The response looks similar to the following example: ```powershell Kind : Exchange PeeringLocation : Seattle PeerAsn : 65000 Connection : ------------------------ PeerSessionIPv4Address : 10.21.31.100 MicrosoftIPv4Address : 10.21.31.50 SessionStateV4 : Established MaxPrefixesAdvertisedV4 : 20000 PeerSessionIPv6Address : fc00:db20:35b:7399::5:100 MicrosoftIPv6Address : fc00:db20:35b:7399::5:50 SessionStateV6 : Established MaxPrefixesAdvertisedV6 : 2000 ConnectionState : Active ``` ### Convert legacy peering This command can be used to convert legacy Exchange peering to an Azure resource: ```powershell $legacyPeering[0] | New-AzPeering ` -Name "SeattleExchangePeering" ` -ResourceGroupName "PeeringResourceGroup" ``` &nbsp; > [!IMPORTANT] > When you convert legacy peering to an Azure resource, modifications aren't supported. &nbsp; This example response shows when the end-to-end provisioning was successfully completed: ```powershell Name : SeattleExchangePeering Kind : Exchange Sku : Basic_Exchange_Free PeeringLocation : Seattle PeerAsn : 65000 Connection : ------------------------ PeerSessionIPv4Address : 10.21.31.100 MicrosoftIPv4Address : 10.21.31.50 SessionStateV4 : Established MaxPrefixesAdvertisedV4 : 20000 PeerSessionIPv6Address : fc00:db20:35b:7399::5:100 MicrosoftIPv6Address : fc00:db20:35b:7399::5:50 SessionStateV6 : Established MaxPrefixesAdvertisedV6 : 2000 ConnectionState : Active ``` ## Additional resources You can get detailed descriptions of all the parameters by running the following command: ```powershell Get-Help Get-AzPeering -detailed ``` For more information, see [Internet peering FAQs](faqs.md). ## Next steps * [Create or modify an Exchange peering by using PowerShell](howto-exchange-powershell.md) ======================= File: articles/azure-portal/azure-portal-quickstart-center.md ======================= --- title: Get started with the Azure Quickstart Center description: Use the Azure Quickstart Center guided experience to get started with Azure. Learn to set up, migrate, and innovate. services: azure-portal keywords: author: mgblythe ms.author: mblythe ms.date: 01/29/2020 ms.topic: conceptual ms.service: azure-portal manager: mtillman --- # Get started with the Azure Quickstart Center Azure Quickstart Center is a guided experience in the Azure portal available to anyone who wants to improve their knowledge of Azure. For organizations new to Azure, it's the fastest way to onboard and set up your cloud environment. ## Overview Azure Quickstart Center has three options for getting started: * **Setup guides**: Designed for the IT admin and cloud architect, our guides introduce key concepts for Azure adoption. Structured steps help you take action as you learn, applying Microsoft's recommended best practices. The migration guide helps you assess readiness and plan as you prepare to shift to Azure. * **Start a project**: If you're ready to create a resource, this section lets you learn more about your choices before you commit to a service option. You'll discover more about the service and why you should use it, explore costs, and identify prerequisites. After making your choice, you can go directly to create. * **Online learning**: This section of the Azure Quickstart Center highlights free introductory course modules from Microsoft Learn. Select a tile to launch a course and learn more about cloud concepts and managing resources in Azure. ## How to use Azure Quickstart Center 1. Sign in to the [Azure portal](https://portal.azure.com). 1. Select **All services** from the Azure portal menu. 1. Select **General** > **Quickstart Center**. For an in-depth look at what Azure Quickstart Center can do for you, check out this video: > [!VIDEO https://www.youtube.com/embed/0bSA7RXrbAg] [Introduction to Azure Quickstart Center](https://www.youtube.com/watch?v=0bSA7RXrbAg) ## Next steps * Learn more about Azure setup and migration in the [Microsoft Cloud Adoption Framework for Azure](/azure/architecture/cloud-adoption/). * Unlock your cloud skills with more courses from [Microsoft Learn](/learn/azure/). ======================= File: articles/cost-management-billing/reservations/understand-rhel-reservation-charges.md ======================= <gh_stars>1-10 --- title: Red Hat reservation plan discounts - Azure description: Learn how Red Hat plan discounts are applied to Red Hat software on virtual machines. author: yashesvi ms.service: cost-management-billing ms.topic: conceptual ms.date: 06/11/2020 ms.author: banders --- # Understand how the Red Hat Linux Enterprise software reservation plan discount is applied for Azure After you buy a Red Hat Linux plan, the discount is automatically applied to deployed Red Hat virtual machines (VMs) that match the reservation. A Red Hat Linux plan covers the cost of running the Red Hat software on an Azure VM. To buy the right Red Hat Linux plan, you need to understand what Red Hat VMs you run and the number of vCPUs on those VMs. Use the following sections to help identify from your usage CSV file what plan to buy. ## Discount applies to different VM sizes Like Reserved VM Instances, Red Hat plan purchases offer instance size flexibility. This means that your discount applies even when you deploy a VM with a different vCPU count. The discount applies to different VM sizes within the software plan. The discount amount depends on the ratio listed in the following tables. The ratio compares the relative footprint for each VM size in that group. The ratio depends on the VM vCPUs. Use the ratio value to calculate how many VM instances get the Red Hat Linux plan discount. For example, if you buy a plan for Red Hat Linux Enterprise Server for a VM with 1 to 4 vCPUs, the ratio for that reservation is 1. The discount covers the Red Hat software cost for: - 1 deployed VMs with 1 to 4 vCPUs, - or 0.46 or about 46% of Red Hat Enterprise Linux costs for a VM with 5 or more vCPUs. ### Red Hat Enterprise Linux Azure portal marketplace names: - Red Hat Enterprise Linux 6.7 - Red Hat Enterprise Linux 6.8 - Red Hat Enterprise Linux 6.9 - Red Hat Enterprise Linux 6.10 - Red Hat Enterprise Linux 7 - Red Hat Enterprise Linux 7.2 - Red Hat Enterprise Linux 7.3 - Red Hat Enterprise Linux 7.4 - Red Hat Enterprise Linux 7.5 - Red Hat Enterprise Linux 7.6 - Red Hat Enterprise Linux 8.2 [Check Red Hat Enterprise Linux meters that the plan applies to](https://isfratio.blob.core.windows.net/isfratio/RHELRatios.csv) ## Next steps To learn more about reservations, see the following articles: - [What are reservations for Azure](save-compute-costs-reservations.md) - [Prepay for Red Hat software plans with Azure reservations](../../virtual-machines/linux/prepay-rhel-software-charges.md) - [Prepay for Virtual Machines with Azure Reserved VM Instances](../../virtual-machines/windows/prepay-reserved-vm-instances.md) - [Manage reservations for Azure](manage-reserved-vm-instance.md) - [Understand reservation usage for your Pay-As-You-Go subscription](understand-reserved-instance-usage.md) - [Understand reservation usage for your Enterprise enrollment](understand-reserved-instance-usage-ea.md) ## Need help? Contact us If you have questions or need help, [create a support request](https://portal.azure.com/#blade/Microsoft_Azure_Support/HelpAndSupportBlade/newsupportrequest). ======================= File: articles/azure-resource-manager/managed-applications/microsoft-common-textbox.md ======================= --- title: TextBox UI element description: Describes the Microsoft.Common.TextBox UI element for Azure portal. Use for adding unformatted text. author: tfitzmac ms.topic: conceptual ms.date: 06/27/2018 ms.author: tomfitz --- # Microsoft.Common.TextBox UI element A control that can be used to edit unformatted text. ## UI sample ![Microsoft.Common.TextBox](./media/managed-application-elements/microsoft.common.textbox.png) ## Schema ```json { "name": "element1", "type": "Microsoft.Common.TextBox", "label": "Example text box 1", "defaultValue": "my text value", "toolTip": "Use only allowed characters", "constraints": { "required": true, "regex": "^[a-z0-9A-Z]{1,30}$", "validationMessage": "Only alphanumeric characters are allowed, and the value must be 1-30 characters long." }, "visible": true } ``` ## Sample output ```json "my text value" ``` ## Remarks - If `constraints.required` is set to **true**, then the text box must have a value to validate successfully. The default value is **false**. - `constraints.regex` is a JavaScript regular expression pattern. If specified, then the text box's value must match the pattern to validate successfully. The default value is **null**. - `constraints.validationMessage` is a string to display when the text box's value fails validation. If not specified, then the text box's built-in validation messages are used. The default value is **null**. - It's possible to specify a value for `constraints.regex` when `constraints.required` is set to **false**. In this scenario, a value isn't required for the text box to validate successfully. If one is specified, it must match the regular expression pattern. ## Next steps * For an introduction to creating UI definitions, see [Getting started with CreateUiDefinition](create-uidefinition-overview.md). * For a description of common properties in UI elements, see [CreateUiDefinition elements](create-uidefinition-elements.md). ======================= File: articles/azure-cache-for-redis/cache-redis-samples.md ======================= --- title: Azure Cache for Redis samples description: 'Learn how to use Azure Cache for Redis with these code samples: connecting to a cache, reading and writing data in a cache, ASP.NET Azure Cache for Redis providers.' author: yegu-ms ms.author: yegu ms.service: cache ms.topic: sample ms.date: 01/23/2017 --- # Azure Cache for Redis samples This topic provides a list of Azure Cache for Redis samples, covering scenarios such as connecting to a cache, reading and writing data to and from a cache, and using the ASP.NET Azure Cache for Redis providers. Some of the samples are downloadable projects, and some provide step-by-step guidance and include code snippets but do not link to a downloadable project. ## Hello world samples The samples in this section show the basics of connecting to an Azure Cache for Redis instance and reading and writing data to the cache using a variety of languages and Redis clients. The [Hello world](https://github.com/rustd/RedisSamples/tree/master/HelloWorld) sample shows how to perform various cache operations using the [StackExchange.Redis](https://github.com/StackExchange/StackExchange.Redis).NET client. This sample shows how to: * Use various connection options * Read and write objects to and from the cache using synchronous and asynchronous operations * Use Redis MGET/MSET commands to return values of specified keys * Perform Redis transactional operations * Work with Redis lists and sorted sets * Store.NET objects using JsonConvert serializers * Use Redis sets to implement tagging * Work with Redis Cluster For more information, see the [StackExchange.Redis](https://github.com/StackExchange/StackExchange.Redis) documentation on GitHub, and for more usage scenarios see the [StackExchange.Redis.Tests](https://github.com/StackExchange/StackExchange.Redis/tree/master/tests) unit tests. [How to use Azure Cache for Redis with Python](cache-python-get-started.md) shows how to get started with Azure Cache for Redis using Python and the [redis-py](https://github.com/andymccurdy/redis-py) client. [Work with.NET objects in the cache](cache-dotnet-how-to-use-azure-redis-cache.md#work-with-net-objects-in-the-cache) shows you one way to serialize.NET objects so you can write them to and read them from an Azure Cache for Redis instance. ## Use Azure Cache for Redis as a Scale out Backplane for ASP.NET SignalR The [Use Azure Cache for Redis as a Scale out Backplane for ASP.NET SignalR](https://github.com/rustd/RedisSamples/tree/master/RedisAsSignalRBackplane) sample demonstrates how you can use Azure Cache for Redis as a SignalR backplane. For more information about backplane, see [SignalR Scaleout with Redis](https://www.asp.net/signalr/overview/performance/scaleout-with-redis). ## Azure Cache for Redis customer query sample This sample demonstrates compares performance between accessing data from a cache and accessing data from persistence storage. This sample has two projects. * [Demo how Azure Cache for Redis can improve performance by Caching data](https://github.com/rustd/RedisSamples/tree/master/RedisCacheCustomerQuerySample) * [Seed the Database and Cache for the demo](https://github.com/rustd/RedisSamples/tree/master/SeedCacheForCustomerQuerySample) ## ASP.NET Session State and Output Caching The [Use Azure Cache for Redis to store ASP.NET SessionState and OutputCache](https://github.com/rustd/RedisSamples/tree/master/SessionState_OutputCaching) sample demonstrates how you to use Azure Cache for Redis to store ASP.NET Session and Output Cache using the SessionState and OutputCache providers for Redis. ## Manage Azure Cache for Redis with MAML The [Manage Azure Cache for Redis using Azure Management Libraries](https://github.com/rustd/RedisSamples/tree/master/ManageCacheUsingMAML) sample demonstrates how can you use Azure Management Libraries to manage - (Create/ Update/ delete) your Cache. ## Custom monitoring sample The [Access Azure Cache for Redis Monitoring data](https://github.com/rustd/RedisSamples/tree/master/CustomMonitoring) sample demonstrates how you can access monitoring data for your Azure Cache for Redis outside of the Azure Portal. ## A Twitter-style clone written using PHP and Redis The [Retwis](https://github.com/SyntaxC4-MSFT/retwis) sample is the Redis Hello World. It is a minimal Twitter-style social network clone written using Redis and PHP using the [Predis](https://github.com/nrk/predis) client. The source code is designed to be very simple and at the same time to show different Redis data structures. ## Bandwidth monitor The [Bandwidth monitor](https://github.com/JonCole/SampleCode/tree/master/BandWidthMonitor) sample allows you to monitor the bandwidth used on the client. To measure the bandwidth, run the sample on the cache client machine, make calls to the cache, and observe the bandwidth reported by the bandwidth monitor sample. ======================= File: articles/event-hubs/use-blob-storage-checkpoint-store-azure-stack-hub.md ======================= --- title: Use Blob Storage as checkpoint store on Azure Stack Hub (preview) description: This article describes how to use Blob Storage as a checkpoint store in Event Hubs on Azure Stack Hub (preview). services: event-hubs documentationcenter: na author: spelluru ms.service: event-hubs ms.topic: how-to ms.date: 03/18/2020 ms.author: spelluru --- # Use Blob Storage as checkpoint store - Event Hubs on Azure Stack Hub (preview) If you're using Azure Blob Storage as the checkpoint store in an environment that supports a different version of Storage Blob SDK than the ones that are typically available on Azure, you'll need to use code to change the Storage service API version to the specific version supported by that environment. For example, if you're running [Event Hubs on an Azure Stack Hub version 2002](https://docs.microsoft.com/azure-stack/user/event-hubs-overview), the highest available version for the Storage service is version 2017-11-09. In this case, you need to use code to target the Storage service API version to 2017-11-09. For an example on how to target a specific Storage API version, see these samples on GitHub: - [.NET](https://github.com/Azure/azure-sdk-for-net/tree/master/sdk/eventhub/Azure.Messaging.EventHubs.Processor/samples/Sample10_RunningWithDifferentStorageVersion.cs) - [Java](https://github.com/Azure/azure-sdk-for-java/blob/master/sdk/eventhubs/azure-messaging-eventhubs-checkpointstore-blob/src/samples/java/com/azure/messaging/eventhubs/checkpointstore/blob/EventProcessorWithCustomStorageVersion.java). - [JavaScript](https://github.com/Azure/azure-sdk-for-js/blob/master/sdk/eventhub/eventhubs-checkpointstore-blob/samples/javascript/receiveEventsWithApiSpecificStorage.js) or [TypeScript](https://github.com/Azure/azure-sdk-for-js/blob/master/sdk/eventhub/eventhubs-checkpointstore-blob/samples/typescript/src/receiveEventsWithApiSpecificStorage.ts) - Python - [Synchronous](https://github.com/Azure/azure-sdk-for-python/blob/master/sdk/eventhub/azure-eventhub-checkpointstoreblob/samples/receive_events_using_checkpoint_store_storage_api_version.py), [Asynchronous](https://github.com/Azure/azure-sdk-for-python/blob/master/sdk/eventhub/azure-eventhub-checkpointstoreblob-aio/samples/receive_events_using_checkpoint_store_storage_api_version_async.py) > [!IMPORTANT] > Event Hubs on Azure Stack Hub is currently in [preview](https://azure.microsoft.com/support/legal/preview-supplemental-terms/) and is free. If you run Event Hubs receiver that uses Blob Storage as the checkpoint store without targeting the version that Azure Stack Hub supports, you'll receive the following error message: ``` The value for one of the HTTP headers is not in the correct format ``` ## Sample error message in Python For Python, an error of `azure.core.exceptions.HttpResponseError` is passed to the error handler `on_error(partition_context, error)` of `EventHubConsumerClient.receive()`. But, the method `receive()` doesn't raise an exception. `print(error)` will print the following exception information: ```bash The value for one of the HTTP headers is not in the correct format. RequestId:f048aee8-a90c-08ba-4ce1-e69dba759297 Time:2020-03-17T22:04:13.3559296Z ErrorCode:InvalidHeaderValue Error:None HeaderName:x-ms-version HeaderValue:2019-07-07 ``` The logger will log two warnings like the following ones: ```bash WARNING:azure.eventhub.extensions.checkpointstoreblobaio._blobstoragecsaio: An exception occurred during list_ownership for namespace '<namespace-name>.eventhub.<region>.azurestack.corp.microsoft.com' eventhub 'python-eh-test' consumer group '$Default'. Exception is HttpResponseError('The value for one of the HTTP headers is not in the correct format.\nRequestId:f048aee8-a90c-08ba-4ce1-e69dba759297\nTime:2020-03-17T22:04:13.3559296Z\nErrorCode:InvalidHeaderValue\nError:None\nHeaderName:x-ms-version\nHeaderValue:2019-07-07') WARNING:azure.eventhub.aio._eventprocessor.event_processor:EventProcessor instance '26d84102-45b2-48a9-b7f4-da8916f68214' of eventhub 'python-eh-test' consumer group '$Default'. An error occurred while load-balancing and claiming ownership. The exception is HttpResponseError('The value for one of the HTTP headers is not in the correct format.\nRequestId:f048aee8-a90c-08ba-4ce1-e69dba759297\nTime:2020-03-17T22:04:13.3559296Z\nErrorCode:InvalidHeaderValue\nError:None\nHeaderName:x-ms-version\nHeaderValue:2019-07-07'). Retrying after 71.45254944090853 seconds ``` ## Next steps See the following article learn about partitioning and checkpointing: [Balance partition load across multiple instances of your application](event-processor-balance-partition-load.md) ======================= File: articles/confidential-computing/quick-create-marketplace.md ======================= --- title: Quickstart - Create an Azure confidential computing virtual machine with Marketplace description: Get started with your deployments by learning how to quickly create a confidential computing virtual machine with Marketplace. author: JBCook ms.service: virtual-machines ms.subservice: workloads ms.workload: infrastructure ms.topic: quickstart ms.date: 04/06/2020 ms.author: JenCook --- # Quickstart: Deploy an Azure Confidential Computing VM in the Marketplace Get started with Azure confidential computing by using the Azure Marketplace to create a virtual machine (VM) backed by Intel SGX. You'll then install the Open Enclave Software Development Kit (SDK) to set up your development environment. This tutorial is recommended if you want to quickly start deploying a confidential computing virtual machine. The VMs are run on specialty hardware and require specific configuration inputs to run as intended. The marketplace offering described in this quickstart makes it easier to deploy, by restricting user input. If you're interested in deploying a confidential compute virtual machine with more custom configuration, follow the [Azure portal Confidential Compute virtual machine deployment steps](quick-create-portal.md). ## Prerequisites If you don't have an Azure subscription, [create an account](https://azure.microsoft.com/pricing/purchase-options/pay-as-you-go/) before you begin. > [!NOTE] > Free trial accounts do not have access to the virtual machines used in this tutorial. Please upgrade to a Pay-As-You-Go subscription. ## Sign in to Azure 1. Sign in to the [Azure portal](https://portal.azure.com/). 1. At the top, type **Azure confidential computing** into the search bar. 1. Select **Azure confidential computing (Virtual Machine)** in the **Marketplace** section. ![Select Marketplace](media/quick-create-marketplace/portal-search-marketplace.png) 1. On the Azure confidential compute deployment landing page, select **Create**. ## Configure your virtual machine 1. In the **Basics** tab, select your **Subscription** and **Resource Group**. Your resource group must be empty to deploy a virtual machine from this template into it. 1. Type or select the following values: * **Region**: Select the Azure region that's right for you. > [!NOTE] > Confidential compute virtual machines only run on specialized hardware available in specific regions. For the latest available regions for DCsv2-Series VMs, see [available regions](https://azure.microsoft.com/global-infrastructure/services/?products=virtual-machines). * **Choose Image**: Select any image. If you would like to complete this specific tutorial, select Ubuntu 18.04 (Gen 2). Otherwise, you'll be redirected at the appropriate steps below. * **Virtual machine name**, enter a name for your new VM. * **Authentication type**: Select **SSH public key** if you're creating a Linux VM. > [!NOTE] > You have the choice of using an SSH public key or a Password for authentication. SSH is more secure. For instructions on how to generate an SSH key, see [Create SSH keys on Linux and Mac for Linux VMs in Azure](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-linux-mac-create-ssh-keys). * **Username**: Enter the Administrator name for the VM. * **SSH public key**: If applicable, enter your RSA public key. * **Password**: If applicable, enter your password for authentication. 1. Select the **Next: Virtual machine settings** button at the bottom of your screen. > [!IMPORTANT] > Wait for the page to update. You *should not* see a message that says "Confidential Computing DCsv2-series VMs are available in a limited number of regions." If this message persists, return to the previous page and select an available DCsv2-Series region. 1. For **change size**, choose a VM with confidential compute capabilities in the size selector. > [!TIP] > You should see sizes **DC1s_v2**, **DC2s_v2**, **DC4s_V2**, and **DC8_v2**. These are the only virtual machine sizes that currently support confidential computing. [Learn more](virtual-machine-solutions.md). 1. For **OS Disk Type**, select a disk type. 1. For **Virtual Network**, create a new one or choose from an existing resource. 1. For **Subnet**, create a new one or choose from an existing resource. 1. For **Select public inbound ports**, choose **SSH(Linux)/RDP(Windows)**. In this quickstart, this step is necessary to connect to the VM and complete the Open Enclave SDK configuration. 1. For **Boot Diagnostics**, leave it disabled for this quickstart. 1. Select **Review + create**. 1. In the **Review + create** pane, select **Create**. > [!NOTE] > Proceed to the next section and continue with this tutorial if you deployed a Linux VM. If you deployed a Windows VM, [follow these steps to connect to your Windows VM](../virtual-machines/windows/connect-logon.md) and then [install the OE SDK on Windows](https://github.com/openenclave/openenclave/blob/master/docs/GettingStartedDocs/install_oe_sdk-Windows.md). ## Connect to the Linux VM If you already use a BASH shell, connect to the Azure VM using the **ssh** command. In the following command, replace the VM user name and IP address to connect to your Linux VM. ```bash ssh [email protected] ``` You can find the Public IP address of your VM in the Azure portal, under the Overview section of your virtual machine. ![IP address in Azure portal](media/quick-create-portal/public-ip-virtual-machine.png) If you're running on Windows and don't have a BASH shell, install an SSH client, such as PuTTY. 1. [Download and install PuTTY](https://www.chiark.greenend.org.uk/~sgtatham/putty/download.html). 1. Run PuTTY. 1. On the PuTTY configuration screen, enter your VM's public IP address. 1. Select **Open** and enter your username and password at the prompts. For more information about connecting to Linux VMs, see [Create a Linux VM on Azure using the Portal](../virtual-machines/linux/quick-create-portal.md). > [!NOTE] > If you see a PuTTY security alert about the server's host key not being cached in the registry, choose from the following options. If you trust this host, select **Yes** to add the key to PuTTy's cache and continue connecting. If you want to carry on connecting just once, without adding the key to the cache, select **No**. If you don't trust this host, select **Cancel** to abandon the connection. ## Install the Open Enclave SDK (OE SDK) <a id="Install"></a> Follow the step-by-step instructions to install the [OE SDK](https://github.com/openenclave/openenclave) on your DCsv2-Series virtual machine running an Ubuntu 18.04 LTS Gen 2 image. If your virtual machine runs on Ubuntu 16.04 LTS Gen 2, you'll need to follow [installation instructions for Ubuntu 16.04](https://github.com/openenclave/openenclave/blob/master/docs/GettingStartedDocs/install_oe_sdk-Ubuntu_16.04.md). #### 1. Configure the Intel and Microsoft APT Repositories ```bash echo 'deb [arch=amd64] https://download.01.org/intel-sgx/sgx_repo/ubuntu bionic main' | sudo tee /etc/apt/sources.list.d/intel-sgx.list wget -qO - https://download.01.org/intel-sgx/sgx_repo/ubuntu/intel-sgx-deb.key | sudo apt-key add - echo "deb http://apt.llvm.org/bionic/ llvm-toolchain-bionic-7 main" | sudo tee /etc/apt/sources.list.d/llvm-toolchain-bionic-7.list wget -qO - https://apt.llvm.org/llvm-snapshot.gpg.key | sudo apt-key add - echo "deb [arch=amd64] https://packages.microsoft.com/ubuntu/18.04/prod bionic main" | sudo tee /etc/apt/sources.list.d/msprod.list wget -qO - https://packages.microsoft.com/keys/microsoft.asc | sudo apt-key add - ``` #### 2. Install the Intel SGX DCAP Driver ```bash sudo apt update sudo apt -y install dkms wget https://download.01.org/intel-sgx/sgx-dcap/1.4/linux/distro/ubuntuServer18.04/sgx_linux_x64_driver_1.21.bin -O sgx_linux_x64_driver.bin chmod +x sgx_linux_x64_driver.bin sudo./sgx_linux_x64_driver.bin ``` > [!WARNING] > Please use the latest Intel SGX DCAP driver from [Intel's SGX site](https://01.org/intel-software-guard-extensions/downloads). #### 3. Install the Intel and Open Enclave packages and dependencies ```bash sudo apt -y install clang-7 libssl-dev gdb libsgx-enclave-common libsgx-enclave-common-dev libprotobuf10 libsgx-dcap-ql libsgx-dcap-ql-dev az-dcap-client open-enclave ``` > [!NOTE] > This step also installs the [az-dcap-client](https://github.com/microsoft/azure-dcap-client) package which is necessary for performing remote attestation in Azure. #### 4. **Verify the Open Enclave SDK install** See [Using the Open Enclave SDK](https://github.com/openenclave/openenclave/blob/master/docs/GettingStartedDocs/Linux_using_oe_sdk.md) on GitHub for verifying and using the installed SDK. ## Clean up resources When no longer needed, you can delete the resource group, virtual machine, and all related resources. Select the resource group for the virtual machine, then select **Delete**. Confirm the name of the resource group to finish deleting the resources. ## Next steps In this quickstart, you deployed a confidential computing virtual machine, and installed the Open Enclave SDK. For more information about confidential computing virtual machines on Azure, see [Solutions on Virtual Machines](virtual-machine-solutions.md). If you deployed a Windows VM, learn how to build applications with the [OE SDK Samples for Windows](https://github.com/openenclave/openenclave/blob/master/samples/README_Windows.md) on GitHub. Discover how you can build confidential computing applications on Linux, by continuing to the Open Enclave SDK Linux samples on GitHub. > [!div class="nextstepaction"] > [Building Open Enclave SDK Samples on Linux](https://github.com/openenclave/openenclave/blob/master/samples/README_Linux.md) ======================= File: articles/active-directory/saas-apps/ciscocloudlock-tutorial.md ======================= --- title: 'Tutorial: Azure Active Directory integration with The Cloud Security Fabric | Microsoft Docs' description: Learn how to configure single sign-on between Azure Active Directory and The Cloud Security Fabric. services: active-directory documentationCenter: na author: jeevansd manager: mtillman ms.reviewer: barbkess ms.assetid: 549e8810-1b3b-4351-bf4b-f07de98980d1 ms.service: active-directory ms.subservice: saas-app-tutorial ms.workload: identity ms.tgt_pltfrm: na ms.devlang: na ms.topic: tutorial ms.date: 07/18/2019 ms.author: jeedes ms.collection: M365-identity-device-management --- # Tutorial: Integrate The Cloud Security Fabric with Azure Active Directory In this tutorial, you'll learn how to integrate The Cloud Security Fabric with Azure Active Directory (Azure AD). When you integrate The Cloud Security Fabric with Azure AD, you can: * Control in Azure AD who has access to The Cloud Security Fabric. * Enable your users to be automatically signed-in to The Cloud Security Fabric with their Azure AD accounts. * Manage your accounts in one central location - the Azure portal. To learn more about SaaS app integration with Azure AD, see [What is application access and single sign-on with Azure Active Directory](https://docs.microsoft.com/azure/active-directory/active-directory-appssoaccess-whatis). ## Prerequisites To get started, you need the following items: * An Azure AD subscription. If you don't have a subscription, you can get a [free account](https://azure.microsoft.com/free/). * The Cloud Security Fabric single sign-on (SSO) enabled subscription. ## Scenario description In this tutorial, you configure and test Azure AD SSO in a test environment. * The Cloud Security Fabric supports **SP** initiated SSO ## Adding The Cloud Security Fabric from the gallery To configure the integration of The Cloud Security Fabric into Azure AD, you need to add The Cloud Security Fabric from the gallery to your list of managed SaaS apps. 1. Sign in to the [Azure portal](https://portal.azure.com) using either a work or school account, or a personal Microsoft account. 1. On the left navigation pane, select the **Azure Active Directory** service. 1. Navigate to **Enterprise Applications** and then select **All Applications**. 1. To add new application, select **New application**. 1. In the **Add from the gallery** section, type **The Cloud Security Fabric** in the search box. 1. Select **The Cloud Security Fabric** from results panel and then add the app. Wait a few seconds while the app is added to your tenant. ## Configure and test Azure AD single sign-on Configure and test Azure AD SSO with The Cloud Security Fabric using a test user called **B.Simon**. For SSO to work, you need to establish a link relationship between an Azure AD user and the related user in The Cloud Security Fabric. To configure and test Azure AD SSO with The Cloud Security Fabric, complete the following building blocks: 1. **[Configure Azure AD SSO](#configure-azure-ad-sso)** - to enable your users to use this feature. 2. **[Configure The Cloud Security Fabric SSO](#configure-the-cloud-security-fabric-sso)** - to configure the Single Sign-On settings on application side. 3. **[Create an Azure AD test user](#create-an-azure-ad-test-user)** - to test Azure AD single sign-on with B.Simon. 4. **[Assign the Azure AD test user](#assign-the-azure-ad-test-user)** - to enable B.Simon to use Azure AD single sign-on. 5. **[Create The Cloud Security Fabric test user](#create-the-cloud-security-fabric-test-user)** - to have a counterpart of B.Simon in The Cloud Security Fabric that is linked to the Azure AD representation of user. 6. **[Test SSO](#test-sso)** - to verify whether the configuration works. ### Configure Azure AD SSO Follow these steps to enable Azure AD SSO in the Azure portal. 1. In the [Azure portal](https://portal.azure.com/), on the **The Cloud Security Fabric** application integration page, find the **Manage** section and select **Single sign-on**. 1. On the **Select a Single sign-on method** page, select **SAML**. 1. On the **Set up Single Sign-On with SAML** page, click the edit/pen icon for **Basic SAML Configuration** to edit the settings. ![Edit Basic SAML Configuration](common/edit-urls.png) 4. On the **Basic SAML Configuration** section, perform the following steps: a. In the **Sign on URL** text box, type a URL: | | |--| | `https://platform.cloudlock.com` | | `https://app.cloudlock.com` | b. In the **Identifier (Entity ID)** text box, type a URL using the following pattern: | | |--| | `https://platform.cloudlock.com/gate/saml/sso/<subdomain>` | | `https://app.cloudlock.com/gate/saml/sso/<subdomain>` | > [!NOTE] > The Identifier value is not real. Update the value with the actual Identifier. Contact [The Cloud Security Fabric Client support team](mailto:<EMAIL>) to get the value. You can also refer to the patterns shown in the **Basic SAML Configuration** section in the Azure portal. 4. On the **Set up Single Sign-On with SAML** page, in the **SAML Signing Certificate** section, find **Federation Metadata XML** and select **Download** to download the certificate and save it on your computer. ![The Certificate download link](common/metadataxml.png) 5. To Modify the **Signing** options as per your requirement, click **Edit** button to open **SAML Signing Certificate** dialog. ![Saml Response](./media/ciscocloudlock-tutorial/saml.png) a. Select the **Sign SAML response and assertion** option for **Signing Option**. b. Select the **SHA-256** option for **Signing Algorithm**. c. Click **Save**. 6. On the **Set up The Cloud Security Fabric** section, copy the appropriate URL(s) based on your requirement. ![Copy configuration URLs](common/copy-configuration-urls.png) ### Configure The Cloud Security Fabric SSO To configure single sign-on on **The Cloud Security Fabric** side, you need to send the downloaded **Federation Metadata XML** and appropriate copied URLs from Azure portal to [The Cloud Security Fabric support team](mailto:<EMAIL>). They set this setting to have the SAML SSO connection set properly on both sides. ### Create an Azure AD test user In this section, you'll create a test user in the Azure portal called B.Simon. 1. From the left pane in the Azure portal, select **Azure Active Directory**, select **Users**, and then select **All users**. 1. Select **New user** at the top of the screen. 1. In the **User** properties, follow these steps: 1. In the **Name** field, enter `B.Simon`. 1. In the **User name** field, enter the <EMAIL>. For example, `<EMAIL>`. 1. Select the **Show password** check box, and then write down the value that's displayed in the **Password** box. 1. Click **Create**. ### Assign the Azure AD test user In this section, you'll enable B.Simon to use Azure single sign-on by granting access to The Cloud Security Fabric. 1. In the Azure portal, select **Enterprise Applications**, and then select **All applications**. 1. In the applications list, select **The Cloud Security Fabric**. 1. In the app's overview page, find the **Manage** section and select **Users and groups**. ![The "Users and groups" link](common/users-groups-blade.png) 1. Select **Add user**, then select **Users and groups** in the **Add Assignment** dialog. ![The Add User link](common/add-assign-user.png) 1. In the **Users and groups** dialog, select **B.Simon** from the Users list, then click the **Select** button at the bottom of the screen. 1. If you're expecting any role value in the SAML assertion, in the **Select Role** dialog, select the appropriate role for the user from the list and then click the **Select** button at the bottom of the screen. 1. In the **Add Assignment** dialog, click the **Assign** button. ### Create The Cloud Security Fabric test user In this section, you create a user called B.Simon in The Cloud Security Fabric. Work with [The Cloud Security Fabric support team](mailto:<EMAIL>) to add the users in the The Cloud Security Fabric platform. Users must be created and activated before you use single sign-on. ### Test SSO In this section, you test your Azure AD single sign-on configuration using the Access Panel. When you click the The Cloud Security Fabric tile in the Access Panel, you should be automatically signed in to the The Cloud Security Fabric for which you set up SSO. For more information about the Access Panel, see [Introduction to the Access Panel](https://docs.microsoft.com/azure/active-directory/active-directory-saas-access-panel-introduction). ## Additional Resources - [List of Tutorials on How to Integrate SaaS Apps with Azure Active Directory](https://docs.microsoft.com/azure/active-directory/active-directory-saas-tutorial-list) - [What is application access and single sign-on with Azure Active Directory?](https://docs.microsoft.com/azure/active-directory/active-directory-appssoaccess-whatis) - [What is conditional access in Azure Active Directory?](https://docs.microsoft.com/azure/active-directory/conditional-access/overview) ======================= File: articles/virtual-machines/linux/disk-encryption-sample-scripts.md ======================= <gh_stars>1-10 --- title: Azure Disk Encryption sample scripts description: This article is the appendix for Microsoft Azure Disk Encryption for Linux VMs. author: msmbaldwin ms.service: virtual-machines-linux ms.subservice: security ms.topic: article ms.author: mbaldwin ms.date: 08/06/2019 ms.custom: seodec18 --- # Azure Disk Encryption sample scripts This article provides sample scripts for preparing pre-encrypted VHDs and other tasks. ## Sample PowerShell scripts for Azure Disk Encryption - **List all encrypted VMs in your subscription** ```azurepowershell-interactive $osVolEncrypted = {(Get-AzVMDiskEncryptionStatus -ResourceGroupName $_.ResourceGroupName -VMName $_.Name).OsVolumeEncrypted} $dataVolEncrypted= {(Get-AzVMDiskEncryptionStatus -ResourceGroupName $_.ResourceGroupName -VMName $_.Name).DataVolumesEncrypted} Get-AzVm | Format-Table @{Label="MachineName"; Expression={$_.Name}}, @{Label="OsVolumeEncrypted"; Expression=$osVolEncrypted}, @{Label="DataVolumesEncrypted"; Expression=$dataVolEncrypted} ``` - **List all disk encryption secrets used for encrypting VMs in a key vault** ```azurepowershell-interactive Get-AzKeyVaultSecret -VaultName $KeyVaultName | where {$_.Tags.ContainsKey('DiskEncryptionKeyFileName')} | format-table @{Label="MachineName"; Expression={$_.Tags['MachineName']}}, @{Label="VolumeLetter"; Expression={$_.Tags['VolumeLetter']}}, @{Label="EncryptionKeyURL"; Expression={$_.Id}} ``` ### Using the Azure Disk Encryption prerequisites PowerShell script If you're already familiar with the prerequisites for Azure Disk Encryption, you can use the [Azure Disk Encryption prerequisites PowerShell script](https://raw.githubusercontent.com/Azure/azure-powershell/master/src/Compute/Compute/Extension/AzureDiskEncryption/Scripts/AzureDiskEncryptionPreRequisiteSetup.ps1 ). For an example of using this PowerShell script, see the [Encrypt a VM Quickstart](disk-encryption-powershell-quickstart.md). You can remove the comments from a section of the script, starting at line 211, to encrypt all disks for existing VMs in an existing resource group. The following table shows which parameters can be used in the PowerShell script: |Parameter|Description|Mandatory?| |------|------|------| |$resourceGroupName| Name of the resource group to which the KeyVault belongs to. A new resource group with this name will be created if one doesn't exist.| True| |$keyVaultName|Name of the KeyVault in which encryption keys are to be placed. A new vault with this name will be created if one doesn't exist.| True| |$location|Location of the KeyVault. Make sure the KeyVault and VMs to be encrypted are in the same location. Get a location list with `Get-AzLocation`.|True| |$subscriptionId|Identifier of the Azure subscription to be used. You can get your Subscription ID with `Get-AzSubscription`.|True| |$aadAppName|Name of the Azure AD application that will be used to write secrets to KeyVault. A new application with this name will be created if one doesn't exist. If this app already exists, pass aadClientSecret parameter to the script.|False| |$aadClientSecret|Client secret of the Azure AD application that was created earlier.|False| |$keyEncryptionKeyName|Name of optional key encryption key in KeyVault. A new key with this name will be created if one doesn't exist.|False| ### Encrypt or decrypt VMs without an Azure AD app - [Enable disk encryption on an existing or running Linux VM](https://github.com/Azure/azure-quickstart-templates/tree/master/201-encrypt-running-linux-vm-without-aad) - [Disable encryption on a running Linux VM](https://github.com/Azure/azure-quickstart-templates/tree/master/201-decrypt-running-linux-vm-without-aad) - Disabling encryption is only allowed on Data volumes for Linux VMs. ### Encrypt or decrypt VMs with an Azure AD app (previous release) - [Enable disk encryption on an existing or running Linux VM](https://github.com/Azure/azure-quickstart-templates/tree/master/201-encrypt-running-linux-vm) - [Disable encryption on a running Linux VM](https://github.com/Azure/azure-quickstart-templates/tree/master/201-decrypt-running-linux-vm) - Disabling encryption is only allowed on Data volumes for Linux VMs. - [Create a new encrypted managed disk from a pre-encrypted VHD/storage blob](https://github.com/Azure/azure-quickstart-templates/tree/master/201-create-encrypted-managed-disk) - Creates a new encrypted managed disk provided a pre-encrypted VHD and its corresponding encryption settings ## Encrypting an OS drive on a running Linux VM ### Prerequisites for OS disk encryption * The VM must be using a distribution compatible with OS disk encryption as listed in the [Azure Disk Encryption supported operating systems](disk-encryption-overview.md#supported-vms) * The VM must be created from the Marketplace image in Azure Resource Manager. * Azure VM with at least 4 GB of RAM (recommended size is 7 GB). * (For RHEL and CentOS) Disable SELinux. To disable SELinux, see "4.4.2. Disabling SELinux" in the [SELinux User's and Administrator's Guide](https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/SELinux_Users_and_Administrators_Guide/sect-Security-Enhanced_Linux-Working_with_SELinux-Changing_SELinux_Modes.html#sect-Security-Enhanced_Linux-Enabling_and_Disabling_SELinux-Disabling_SELinux) on the VM. * After you disable SELinux, reboot the VM at least once. ### Steps 1. Create a VM by using one of the distributions specified previously. For CentOS 7.2, OS disk encryption is supported via a special image. To use this image, specify "7.2n" as the SKU when you create the VM: ```powershell Set-AzVMSourceImage -VM $VirtualMachine -PublisherName "OpenLogic" -Offer "CentOS" -Skus "7.2n" -Version "latest" ``` 2. Configure the VM according to your needs. If you're going to encrypt all the (OS + data) drives, the data drives need to be specified and mountable from /etc/fstab. > [!NOTE] > Use UUID=... to specify data drives in /etc/fstab instead of specifying the block device name (for example, /dev/sdb1). During encryption, the order of drives changes on the VM. If your VM relies on a specific order of block devices, it will fail to mount them after encryption. 3. Sign out of the SSH sessions. 4. To encrypt the OS, specify volumeType as **All** or **OS** when you enable encryption. > [!NOTE] > All user-space processes that are not running as `systemd` services should be killed with a `SIGKILL`. Reboot the VM. When you enable OS disk encryption on a running VM, plan on VM downtime. 5. Periodically monitor the progress of encryption by using the instructions in the [next section](#monitoring-os-encryption-progress). 6. After Get-AzVmDiskEncryptionStatus shows "VMRestartPending", restart your VM either by signing in to it or by using the portal, PowerShell, or CLI. ```powershell C:\> Get-AzVmDiskEncryptionStatus -ResourceGroupName $ResourceGroupName -VMName $VMName -ExtensionName $ExtensionName OsVolumeEncrypted : VMRestartPending DataVolumesEncrypted : NotMounted OsVolumeEncryptionSettings : Microsoft.Azure.Management.Compute.Models.DiskEncryptionSettings ProgressMessage : OS disk successfully encrypted, reboot the VM ``` Before you reboot, we recommend that you save [boot diagnostics](https://azure.microsoft.com/blog/boot-diagnostics-for-virtual-machines-v2/) of the VM. ## Monitoring OS encryption progress You can monitor OS encryption progress in three ways: * Use the `Get-AzVmDiskEncryptionStatus` cmdlet and inspect the ProgressMessage field: ```powershell OsVolumeEncrypted : EncryptionInProgress DataVolumesEncrypted : NotMounted OsVolumeEncryptionSettings : Microsoft.Azure.Management.Compute.Models.DiskEncryptionSettings ProgressMessage : OS disk encryption started ``` After the VM reaches "OS disk encryption started", it takes about 40 to 50 minutes on a Premium-storage backed VM. Because of [issue #388](https://github.com/Azure/WALinuxAgent/issues/388) in WALinuxAgent, `OsVolumeEncrypted` and `DataVolumesEncrypted` show up as `Unknown` in some distributions. With WALinuxAgent version 2.1.5 and later, this issue is fixed automatically. If you see `Unknown` in the output, you can verify disk-encryption status by using the Azure Resource Explorer. Go to [Azure Resource Explorer](https://resources.azure.com/), and then expand this hierarchy in the selection panel on left: ~~~~ |-- subscriptions |-- [Your subscription] |-- resourceGroups |-- [Your resource group] |-- providers |-- Microsoft.Compute |-- virtualMachines |-- [Your virtual machine] |-- InstanceView ~~~~ In the InstanceView, scroll down to see the encryption status of your drives. ![VM Instance View](./media/disk-encryption/vm-instanceview.png) * Look at [boot diagnostics](https://azure.microsoft.com/blog/boot-diagnostics-for-virtual-machines-v2/). Messages from the ADE extension should be prefixed with `[AzureDiskEncryption]`. * Sign in to the VM via SSH, and get the extension log from: /var/log/azure/Microsoft.Azure.Security.AzureDiskEncryptionForLinux We recommend that you don't sign-in to the VM while OS encryption is in progress. Copy the logs only when the other two methods have failed. ## Prepare a pre-encrypted Linux VHD The preparation for pre-encrypted VHDs can vary depending on the distribution. Examples on preparing Ubuntu 16, openSUSE 13.2, and CentOS 7 are available. ### Ubuntu 16 Configure encryption during the distribution installation by doing the following steps: 1. Select **Configure encrypted volumes** when you partition the disks. ![Ubuntu 16.04 Setup - Configure encrypted volumes](./media/disk-encryption/ubuntu-1604-preencrypted-fig1.png) 2. Create a separate boot drive, which must not be encrypted. Encrypt your root drive. ![Ubuntu 16.04 Setup - Select devices to encrypt](./media/disk-encryption/ubuntu-1604-preencrypted-fig2.png) 3. Provide a passphrase. This is the passphrase that you uploaded to the key vault. ![Ubuntu 16.04 Setup - Provide passphrase](./media/disk-encryption/ubuntu-1604-preencrypted-fig3.png) 4. Finish partitioning. ![Ubuntu 16.04 Setup - Finish partitioning](./media/disk-encryption/ubuntu-1604-preencrypted-fig4.png) 5. When you boot the VM and are asked for a passphrase, use the passphrase you provided in step 3. ![Ubuntu 16.04 Setup - Provide passphrase on boot](./media/disk-encryption/ubuntu-1604-preencrypted-fig5.png) 6. Prepare the VM for uploading into Azure using [these instructions](https://azure.microsoft.com/documentation/articles/virtual-machines-linux-create-upload-ubuntu/). Don't run the last step (deprovisioning the VM) yet. Configure encryption to work with Azure by doing the following steps: 1. Create a file under /usr/local/sbin/azure_crypt_key.sh, with the content in the following script. Pay attention to the KeyFileName, because it's the passphrase file name used by Azure. ```bash #!/bin/sh MountPoint=/tmp-keydisk-mount KeyFileName=LinuxPassPhraseFileName echo "Trying to get the key from disks..." >&2 mkdir -p $MountPoint modprobe vfat >/dev/null 2>&1 modprobe ntfs >/dev/null 2>&1 sleep 2 OPENED=0 cd /sys/block for DEV in sd*; do echo "> Trying device: $DEV..." >&2 mount -t vfat -r /dev/${DEV}1 $MountPoint >/dev/null|| mount -t ntfs -r /dev/${DEV}1 $MountPoint >/dev/null if [ -f $MountPoint/$KeyFileName ]; then cat $MountPoint/$KeyFileName umount $MountPoint 2>/dev/null OPENED=1 break fi umount $MountPoint 2>/dev/null done if [ $OPENED -eq 0 ]; then echo "FAILED to find suitable passphrase file..." >&2 echo -n "Try to enter your password: " >&2 read -s -r A </dev/console echo -n "$A" else echo "Success loading keyfile!" >&2 fi ``` 2. Change the crypt config in */etc/crypttab*. It should look like this: ``` xxx_crypt uuid=xxxxxxxxxxxxxxxxxxxxx none luks,discard,keyscript=/usr/local/sbin/azure_crypt_key.sh ``` 4. Add executable permissions to the script: ``` chmod +x /usr/local/sbin/azure_crypt_key.sh ``` 5. Edit */etc/initramfs-tools/modules* by appending lines: ``` vfat ntfs nls_cp437 nls_utf8 nls_iso8859-1 ``` 6. Run `update-initramfs -u -k all` to update the initramfs to make the `keyscript` take effect. 7. Now you can deprovision the VM. ![Ubuntu 16.04 Setup - update-initramfs](./media/disk-encryption/ubuntu-1604-preencrypted-fig6.png) 8. Continue to the next step and upload your VHD into Azure. ### openSUSE 13.2 To configure encryption during the distribution installation, do the following steps: 1. When you partition the disks, select **Encrypt Volume Group**, and then enter a password. This is the password that you'll upload to your key vault. ![openSUSE 13.2 Setup - Encrypt Volume Group](./media/disk-encryption/opensuse-encrypt-fig1.png) 2. Boot the VM using your password. ![openSUSE 13.2 Setup - Provide passphrase on boot](./media/disk-encryption/opensuse-encrypt-fig2.png) 3. Prepare the VM for uploading to Azure by following the instructions in [Prepare a SLES or openSUSE virtual machine for Azure](https://azure.microsoft.com/documentation/articles/virtual-machines-linux-suse-create-upload-vhd/#prepare-opensuse-131). Don't run the last step (deprovisioning the VM) yet. To configure encryption to work with Azure, do the following steps: 1. Edit the /etc/dracut.conf, and add the following line: ``` add_drivers+=" vfat ntfs nls_cp437 nls_iso8859-1" ``` 2. Comment out these lines by the end of the file /usr/lib/dracut/modules.d/90crypt/module-setup.sh: ```bash # inst_multiple -o \ # $systemdutildir/system-generators/systemd-cryptsetup-generator \ # $systemdutildir/systemd-cryptsetup \ # $systemdsystemunitdir/systemd-ask-password-console.path \ # $systemdsystemunitdir/systemd-ask-password-console.service \ # $systemdsystemunitdir/cryptsetup.target \ # $systemdsystemunitdir/sysinit.target.wants/cryptsetup.target \ # systemd-ask-password systemd-tty-ask-password-agent # inst_script "$moddir"/crypt-run-generator.sh /sbin/crypt-run-generator ``` 3. Append the following line at the beginning of the file /usr/lib/dracut/modules.d/90crypt/parse-crypt.sh: ```bash DRACUT_SYSTEMD=0 ``` And change all occurrences of: ```bash if [ -z "$DRACUT_SYSTEMD" ]; then ``` to: ```bash if [ 1 ]; then ``` 4. Edit /usr/lib/dracut/modules.d/90crypt/cryptroot-ask.sh and append it to "# Open LUKS device": ```bash MountPoint=/tmp-keydisk-mount KeyFileName=LinuxPassPhraseFileName echo "Trying to get the key from disks..." >&2 mkdir -p $MountPoint >&2 modprobe vfat >/dev/null >&2 modprobe ntfs >/dev/null >&2 for SFS in /dev/sd*; do echo "> Trying device:$SFS..." >&2 mount ${SFS}1 $MountPoint -t vfat -r >&2 || mount ${SFS}1 $MountPoint -t ntfs -r >&2 if [ -f $MountPoint/$KeyFileName ]; then echo "> keyfile got..." >&2 cp $MountPoint/$KeyFileName /tmp-keyfile >&2 luksfile=/tmp-keyfile umount $MountPoint >&2 break fi done ``` 5. Run `/usr/sbin/dracut -f -v` to update the initrd. 6. Now you can deprovision the VM and upload your VHD into Azure. ### CentOS 7 and RHEL 8.1 To configure encryption during the distribution installation, do the following steps: 1. Select **Encrypt my data** when you partition disks. ![CentOS 7 Setup -Installation destination](./media/disk-encryption/centos-encrypt-fig1.png) 2. Make sure **Encrypt** is selected for root partition. ![CentOS 7 Setup -Select encrypt for root partition](./media/disk-encryption/centos-encrypt-fig2.png) 3. Provide a passphrase. This is the passphrase that you'll upload to your key vault. ![CentOS 7 Setup - provide passphrase](./media/disk-encryption/centos-encrypt-fig3.png) 4. When you boot the VM and are asked for a passphrase, use the passphrase you provided in step 3. ![CentOS 7 Setup - Enter passphrase on bootup](./media/disk-encryption/centos-encrypt-fig4.png) 5. Prepare the VM for uploading into Azure by using the "CentOS 7.0+" instructions in [Prepare a CentOS-based virtual machine for Azure](https://azure.microsoft.com/documentation/articles/virtual-machines-linux-create-upload-centos/#centos-70). Don't run the last step (deprovisioning the VM) yet. 6. Now you can deprovision the VM and upload your VHD into Azure. To configure encryption to work with Azure, do the following steps: 1. Edit the /etc/dracut.conf, and add the following line: ``` add_drivers+=" vfat ntfs nls_cp437 nls_iso8859-1" ``` 2. Comment out these lines by the end of the file /usr/lib/dracut/modules.d/90crypt/module-setup.sh: ```bash # inst_multiple -o \ # $systemdutildir/system-generators/systemd-cryptsetup-generator \ # $systemdutildir/systemd-cryptsetup \ # $systemdsystemunitdir/systemd-ask-password-console.path \ # $systemdsystemunitdir/systemd-ask-password-console.service \ # $systemdsystemunitdir/cryptsetup.target \ # $systemdsystemunitdir/sysinit.target.wants/cryptsetup.target \ # systemd-ask-password systemd-tty-ask-password-agent # inst_script "$moddir"/crypt-run-generator.sh /sbin/crypt-run-generator ``` 3. Append the following line at the beginning of the file /usr/lib/dracut/modules.d/90crypt/parse-crypt.sh: ```bash DRACUT_SYSTEMD=0 ``` And change all occurrences of: ```bash if [ -z "$DRACUT_SYSTEMD" ]; then ``` to ```bash if [ 1 ]; then ``` 4. Edit /usr/lib/dracut/modules.d/90crypt/cryptroot-ask.sh and append the following after the "# Open LUKS device": ```bash MountPoint=/tmp-keydisk-mount KeyFileName=LinuxPassPhraseFileName echo "Trying to get the key from disks..." >&2 mkdir -p $MountPoint >&2 modprobe vfat >/dev/null >&2 modprobe ntfs >/dev/null >&2 for SFS in /dev/sd*; do echo "> Trying device:$SFS..." >&2 mount ${SFS}1 $MountPoint -t vfat -r >&2 || mount ${SFS}1 $MountPoint -t ntfs -r >&2 if [ -f $MountPoint/$KeyFileName ]; then echo "> keyfile got..." >&2 cp $MountPoint/$KeyFileName /tmp-keyfile >&2 luksfile=/tmp-keyfile umount $MountPoint >&2 break fi done ``` 5. Run the "/usr/sbin/dracut -f -v" to update the initrd. ![CentOS 7 Setup - run /usr/sbin/dracut -f -v](./media/disk-encryption/centos-encrypt-fig5.png) ## Upload encrypted VHD to an Azure storage account After DM-Crypt encryption is enabled, the local encrypted VHD needs to be uploaded to your storage account. ```powershell Add-AzVhd [-Destination] <Uri> [-LocalFilePath] <FileInfo> [[-NumberOfUploaderThreads] <Int32> ] [[-BaseImageUriToPatch] <Uri> ] [[-OverWrite]] [ <CommonParameters>] ``` ## Upload the secret for the pre-encrypted VM to your key vault When encrypting using an Azure AD app (previous release), the disk-encryption secret that you obtained previously must be uploaded as a secret in your key vault. The key vault needs to have disk encryption and permissions enabled for your Azure AD client. ```powershell $AadClientId = "My-AAD-Client-Id" $AadClientSecret = "My-AAD-Client-Secret" $key vault = New-AzKeyVault -VaultName $KeyVaultName -ResourceGroupName $ResourceGroupName -Location $Location Set-AzKeyVaultAccessPolicy -VaultName $KeyVaultName -ResourceGroupName $ResourceGroupName -ServicePrincipalName $AadClientId -PermissionsToKeys all -PermissionsToSecrets all Set-AzKeyVaultAccessPolicy -VaultName $KeyVaultName -ResourceGroupName $ResourceGroupName -EnabledForDiskEncryption ``` ### Disk encryption secret not encrypted with a KEK To set up the secret in your key vault, use [Set-AzKeyVaultSecret](/powershell/module/az.keyvault/set-azkeyvaultsecret). The passphrase is encoded as a base64 string and then uploaded to the key vault. In addition, make sure that the following tags are set when you create the secret in the key vault. ```powershell # This is the passphrase that was provided for encryption during the distribution installation $passphrase = "<PASSWORD>" $tags = @{"DiskEncryptionKeyEncryptionAlgorithm" = "RSA-OAEP"; "DiskEncryptionKeyFileName" = "LinuxPassPhraseFileName"} $secretName = [guid]::NewGuid().ToString() $secretValue = [Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($passphrase)) $secureSecretValue = ConvertTo-SecureString $secretValue -AsPlainText -Force $secret = Set-AzKeyVaultSecret -VaultName $KeyVaultName -Name $secretName -SecretValue $secureSecretValue -tags $tags $secretUrl = $secret.Id ``` Use the `$secretUrl` in the next step for [attaching the OS disk without using KEK](#without-using-a-kek). ### Disk encryption secret encrypted with a KEK Before you upload the secret to the key vault, you can optionally encrypt it by using a key encryption key. Use the wrap [API](https://msdn.microsoft.com/library/azure/dn878066.aspx) to first encrypt the secret using the key encryption key. The output of this wrap operation is a base64 URL encoded string, which you can then upload as a secret by using the [`Set-AzKeyVaultSecret`](/powershell/module/az.keyvault/set-azkeyvaultsecret) cmdlet. ```powershell # This is the passphrase that was provided for encryption during the distribution installation $passphrase = "<PASSWORD>" Add-AzKeyVaultKey -VaultName $KeyVaultName -Name "keyencryptionkey" -Destination Software $KeyEncryptionKey = Get-AzKeyVaultKey -VaultName $KeyVault.OriginalVault.Name -Name "keyencryptionkey" $apiversion = "2015-06-01" ############################## # Get Auth URI ############################## $uri = $KeyVault.VaultUri + "/keys" $headers = @{} $response = try { Invoke-RestMethod -Method GET -Uri $uri -Headers $headers } catch { $_.Exception.Response } $authHeader = $response.Headers["www-authenticate"] $authUri = [regex]::match($authHeader, 'authorization="(.*?)"').Groups[1].Value Write-Host "Got Auth URI successfully" ############################## # Get Auth Token ############################## $uri = $authUri + "/oauth2/token" $body = "grant_type=client_credentials" $body += "&client_id=" + $AadClientId $body += "&client_secret=" + [Uri]::EscapeDataString($AadClientSecret) $body += "&resource=" + [Uri]::EscapeDataString("https://vault.azure.net") $headers = @{} $response = Invoke-RestMethod -Method POST -Uri $uri -Headers $headers -Body $body $access_token = $response.access_token Write-Host "Got Auth Token successfully" ############################## # Get KEK info ############################## $uri = $KeyEncryptionKey.Id + "?api-version=" + $apiversion $headers = @{"Authorization" = "Bearer " + $access_token} $response = Invoke-RestMethod -Method GET -Uri $uri -Headers $headers $keyid = $response.key.kid Write-Host "Got KEK info successfully" ############################## # Encrypt passphrase using KEK ############################## $passphraseB64 = [Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($Passphrase)) $uri = $keyid + "/encrypt?api-version=" + $apiversion $headers = @{"Authorization" = "Bearer " + $access_token; "Content-Type" = "application/json"} $bodyObj = @{"alg" = "RSA-OAEP"; "value" = $passphraseB64} $body = $bodyObj | ConvertTo-Json $response = Invoke-RestMethod -Method POST -Uri $uri -Headers $headers -Body $body $wrappedSecret = $response.value Write-Host "Encrypted passphrase successfully" ############################## # Store secret ############################## $secretName = [guid]::NewGuid().ToString() $uri = $KeyVault.VaultUri + "/secrets/" + $secretName + "?api-version=" + $apiversion $secretAttributes = @{"enabled" = $true} $secretTags = @{"DiskEncryptionKeyEncryptionAlgorithm" = "RSA-OAEP"; "DiskEncryptionKeyFileName" = "LinuxPassPhraseFileName"} $headers = @{"Authorization" = "Bearer " + $access_token; "Content-Type" = "application/json"} $bodyObj = @{"value" = $wrappedSecret; "attributes" = $secretAttributes; "tags" = $secretTags} $body = $bodyObj | ConvertTo-Json $response = Invoke-RestMethod -Method PUT -Uri $uri -Headers $headers -Body $body Write-Host "Stored secret successfully" $secretUrl = $response.id ``` Use `$KeyEncryptionKey` and `$secretUrl` in the next step for [attaching the OS disk using KEK](#using-a-kek). ## Specify a secret URL when you attach an OS disk ### Without using a KEK While you're attaching the OS disk, you need to pass `$secretUrl`. The URL was generated in the "Disk-encryption secret not encrypted with a KEK" section. ```powershell Set-AzVMOSDisk ` -VM $VirtualMachine ` -Name $OSDiskName ` -SourceImageUri $VhdUri ` -VhdUri $OSDiskUri ` -Linux ` -CreateOption FromImage ` -DiskEncryptionKeyVaultId $KeyVault.ResourceId ` -DiskEncryptionKeyUrl $SecretUrl ``` ### Using a KEK When you attach the OS disk, pass `$KeyEncryptionKey` and `$secretUrl`. The URL was generated in the "Disk encryption secret encrypted with a KEK" section. ```powershell Set-AzVMOSDisk ` -VM $VirtualMachine ` -Name $OSDiskName ` -SourceImageUri $CopiedTemplateBlobUri ` -VhdUri $OSDiskUri ` -Linux ` -CreateOption FromImage ` -DiskEncryptionKeyVaultId $KeyVault.ResourceId ` -DiskEncryptionKeyUrl $SecretUrl ` -KeyEncryptionKeyVaultId $KeyVault.ResourceId ` -KeyEncryptionKeyURL $KeyEncryptionKey.Id ``` ======================= File: articles/container-instances/container-instances-update.md ======================= --- title: Update container group description: Learn how to update running containers in your Azure Container Instances container groups. ms.topic: article ms.date: 04/17/2020 --- # Update containers in Azure Container Instances During normal operation of your container instances, you may find it necessary to update the running containers in a [container group](./container-instances-container-groups.md). For example, you might wish to update a property such as an image version, a DNS name, or an environment variable, or refresh a property in a container whose application has crashed. Update the containers in a running container group by redeploying an existing group with at least one modified property. When you update a container group, all running containers in the group are restarted in-place, usually on the same underlying container host. > [!NOTE] > Terminated or deleted container groups can't be updated. Once a container group has terminated (is in either a Succeeded or Failed state) or has been deleted, the group must be deployed as new. See other [limitations](#limitations). ## Update a container group To update an existing container group: * Issue the create command (or use the Azure portal) and specify the name of an existing group * Modify or add at least one property of the group that supports update when you redeploy. Certain properties [don't support updates](#properties-that-require-container-delete). * Set other properties with the values you provided previously. If you don't set a value for a property, it reverts to its default value. > [!TIP] > A [YAML file](./container-instances-container-groups.md#deployment) helps maintain a container group's deployment configuration, and provides a starting point to deploy an updated group. If you used a different method to create the group, you can export the configuration to YAML by using [az container export][az-container-export], ### Example The following Azure CLI example updates a container group with a new DNS name label. Because the DNS name label property of the group is one that can be updated, the container group is redeployed, and its containers restarted. Initial deployment with DNS name label *myapplication-staging*: ```azurecli-interactive # Create container group az container create --resource-group myResourceGroup --name mycontainer \ --image nginx:alpine --dns-name-label myapplication-staging ``` Update the container group with a new DNS name label, *myapplication*, and set the remaining properties with the values used previously: ```azurecli-interactive # Update DNS name label (restarts container), leave other properties unchanged az container create --resource-group myResourceGroup --name mycontainer \ --image nginx:alpine --dns-name-label myapplication ``` ## Update benefits The primary benefit of updating an existing container group is faster deployment. When you redeploy an existing container group, its container image layers are pulled from those cached by the previous deployment. Instead of pulling all image layers fresh from the registry as is done with new deployments, only modified layers (if any) are pulled. Applications based on larger container images like Windows Server Core can see significant improvement in deployment speed when you update instead of delete and deploy new. ## Limitations * Not all properties of a container group support updates. To change some properties of a container group, you must first delete, then redeploy the group. See [Properties that require container delete](#properties-that-require-container-delete). * All containers in a container group are restarted when you update the container group. You can't perform an update or in-place restart of a specific container in a multi-container group. * The IP address of a container group is typically retained between updates, but isn't guaranteed to remain the same. As long as the container group is deployed to the same underlying host, the container group retains its IP address. Although rare, there are some Azure-internal events that can cause redeployment to a different host. To mitigate this issue, we recommend using a DNS name label for your container instances. * Terminated or deleted container groups can't be updated. Once a container group is stopped (is in the *Terminated* state) or deleted, the group is deployed as new. ## Properties that require container delete Not all container group properties can be updated. For example, to change the restart policy of a container, you must first delete the container group, then create it again. Changes to these properties require container group deletion prior to redeployment: * OS type * CPU, memory, or GPU resources * Restart policy * Network profile When you delete a container group and recreate it, it's not "redeployed," but created new. All image layers are pulled fresh from the registry, not from those cached by a previous deployment. The IP address of the container might also change due to being deployed to a different underlying host. ## Next steps Mentioned several times in this article is the **container group**. Every container in Azure Container Instances is deployed in a container group, and container groups can contain more than one container. [Container groups in Azure Container Instances](./container-instances-container-groups.md) [Deploy a multi-container group](container-instances-multi-container-group.md) [Manually stop or start containers in Azure Container Instances](container-instances-stop-start.md) <!-- LINKS - External --> <!-- LINKS - Internal --> [az-container-create]: /cli/azure/container?view=azure-cli-latest#az-container-create [azure-cli-install]: /cli/azure/install-azure-cli [az-container-export]: /cli/azure/container#az-container-export ======================= File: articles/active-directory/authentication/howto-mfa-app-passwords.md ======================= --- title: Configure app passwords for Azure Multi-Factor Authentication - Azure Active Directory description: Learn how to configure and use app passwords for legacy applications in Azure Multi-Factor Authentication services: multi-factor-authentication ms.service: active-directory ms.subservice: authentication ms.topic: how-to ms.date: 06/05/2020 ms.author: iainfou author: iainfoulds manager: daveba ms.reviewer: michmcla ms.collection: M365-identity-device-management --- # Enable and use Azure Multi-Factor Authentication with legacy applications using app passwords Some applications, like Office 2010 or earlier and Apple Mail before iOS 11, don't support multi-factor authentication. The apps aren't configured to accept a secondary form of authentication or prompt. To use these applications in a secure way with Azure Multi-Factor Authentication enabled for user accounts, you can use app passwords. These app passwords replaced your traditional password to allow an app to bypass multi-factor authentication and work correctly. Modern authentication is supported for the Microsoft Office 2013 clients and later. Office 2013 clients, including Outlook, support modern authentication protocols and can be enabled to work with two-step verification. After the client is enabled, app passwords aren't required for the client. This article shows you how to enable and use app passwords for legacy applications that don't support multi-factor authentication prompts. >[!NOTE] > App passwords don't work with Conditional Access based multi-factor authentication policies and modern authentication. ## Overview and considerations When a user account is enabled for Azure Multi-Factor Authentication, the regular sign-in prompt is interrupted by a request for additional verification. Some older applications don't understand this break in the sign-in process, so authentication fails. To maintain user account security and leave Azure Multi-Factor Authentication enabled, app passwords can be used instead of the user's regular username and password. When an app password used during sign-in, there's no additional verification prompt, so authentication is successful. App passwords are automatically generated, not specified by the user. This automatically generated password makes it harder for an attacker to guess, so is more secure. Users don't have to keep track of the passwords or enter them every time as app passwords are only entered once per application. When you use app passwords, the following considerations apply: * There's a limit of 40 app passwords per user. * Applications that cache passwords and use them in on-premises scenarios can fail because the app password isn't known outside the work or school account. An example of this scenario is Exchange emails that are on-premises, but the archived mail is in the cloud. In this scenario, the same password doesn't work. * After Azure Multi-Factor Authentication is enabled on a user's account, app passwords can be used with most non-browser clients like Outlook and Microsoft Skype for Business. However, administrative actions can't be performed by using app passwords through non-browser applications, such as Windows PowerShell. The actions can't be performed even when the user has an administrative account. * To run PowerShell scripts, create a service account with a strong password and don't enable the account for two-step verification. >[!WARNING] > App passwords don't work in hybrid environments where clients communicate with both on-premises and cloud auto-discover endpoints. Domain passwords are required to authenticate on-premises. App passwords are required to authenticate with the cloud. ### App password names App password names should reflect the device on which they're used. If you have a laptop that has non-browser applications like Outlook, Word, and Excel, create one app password named **Laptop** for these apps. Create another app password named **Desktop** for the same applications that run on your desktop computer. It's recommended to create one app password per device, rather than one app password per application. ## Federated or single sign-on app passwords Azure AD supports federation, or single sign-on (SSO), with on-premises Active Directory Domain Services (AD DS). If your organization is federated with Azure AD and you're using Azure Multi-Factor Authentication, the following app password considerations apply: >[!NOTE] > The following points apply only to federated (SSO) customers. * App passwords are verified by Azure AD, and therefore, bypass federation. Federation is actively used only when setting up app passwords. * The Identity Provider (IdP) is not contacted for federated (SSO) users, unlike the passive flow. The app passwords are stored in the work or school account. If a user leaves the company, the user's information flows to the work or school account by using **DirSync** in real time. The disable / deletion of the account can take up to three hours to synchronize, which can delay the disable / deletion of the app password in Azure AD. * On-premises client Access Control settings aren't honored by the app passwords feature. * No on-premises authentication logging or auditing capability is available with the app passwords feature. Some advanced architectures require a combination of credentials for multi-factor authentication with clients. These credentials can include a work or school account username and passwords, and app passwords. The requirements depend on how the authentication is performed. For clients that authenticate against an on-premises infrastructure, a work or school account username and password a required. For clients that authenticate against Azure AD, an app password is required. For example, suppose you have the following architecture: * Your on-premises instance of Active Directory is federated with Azure AD. * You use Exchange online. * You use Skype for Business on-premises. * You use Azure Multi-Factor Authentication. In this scenario, you use the following credentials: * To sign in to Skype for Business, use your work or school account username and password. * To access the address book from an Outlook client that connects to Exchange online, use an app password. ## Allow users to create app passwords By default, users can't create app passwords. The app passwords feature must be enabled before users can use them. To give users the ability to create app passwords, complete the following steps: 1. Sign in to the [Azure portal](https://portal.azure.com). 2. Search for and select **Azure Active Directory**, then choose **Users**. 3. Select **Multi-Factor Authentication** from the navigation bar across the top of the *Users* window. 4. Under Multi-Factor Authentication, select **service settings**. 5. On the **Service Settings** page, select the **Allow users to create app passwords to sign in to non-browser apps** option. ![Screenshot of the Azure portal that shows the service settings for multi-factor authentication to allow the user of app passwords](media/concept-authentication-methods/app-password-authentication-method.png) ## Create an app password When users complete their initial registration for Azure Multi-Factor Authentication, there's an option to create app passwords at the end of the registration process. Users can also create app passwords after registration. For more information and detailed steps for your users, see [What are app passwords in Azure Multi-Factor Authentication?](../user-help/multi-factor-authentication-end-user-app-passwords.md) ## Next steps For more information on how to allow users to quickly register for Azure Multi-Factor Authentication, see [Combined security information registration overview](concept-registration-mfa-sspr-combined.md). ======================= File: articles/postgresql/concepts-supported-versions.md ======================= --- title: Supported versions - Azure Database for PostgreSQL - Single Server description: Describes the supported Postgres major and minor versions in Azure Database for PostgreSQL - Single Server. author: rachel-msft ms.author: raagyema ms.service: postgresql ms.topic: conceptual ms.date: 12/03/2019 ms.custom: fasttrack-edit --- # Supported PostgreSQL major versions Microsoft aims to support n-2 versions of the PostgreSQL engine in Azure Database for PostgreSQL - Single Server. The versions would be the current major version on Azure (n) and the two prior major versions (-2). Azure Database for PostgreSQL currently supports the following major versions: ## PostgreSQL version 11 The current minor release is 11.5. Refer to the [PostgreSQL documentation](https://www.postgresql.org/docs/11/static/release-11-5.html) to learn more about improvements and fixes in this minor release. ## PostgreSQL version 10 The current minor release is 10.10. Refer to the [PostgreSQL documentation](https://www.postgresql.org/docs/10/static/release-10-10.html) to learn more about improvements and fixes in this minor release. ## PostgreSQL version 9.6 The current minor release is 9.6.15. Refer to the [PostgreSQL documentation](https://www.postgresql.org/docs/9.6/static/release-9-6-15.html) to learn more about improvements and fixes in this minor release. ## PostgreSQL version 9.5 The current minor release is 9.5.19. Refer to the [PostgreSQL documentation](https://www.postgresql.org/docs/9.5/static/release-9-5-19.html) to learn about improvements and fixes in this minor release. ## Managing upgrades The PostgreSQL project regularly issues minor releases to fix reported bugs. Azure Database for PostgreSQL automatically patches servers with minor releases during the service's monthly deployments. Automatic major version upgrade is not supported. For example, there is not an automatic upgrade from PostgreSQL 9.5 to PostgreSQL 9.6. To upgrade to the next major version, create a [database dump and restore](./howto-migrate-using-dump-and-restore.md) to a server that was created with the new engine version. ### Version syntax Before PostgreSQL version 10, the [PostgreSQL versioning policy](https://www.postgresql.org/support/versioning/) considered a _major version_ upgrade to be an increase in the first _or_ second number. For example, 9.5 to 9.6 was considered a _major_ version upgrade. As of version 10, only a change in the first number is considered a major version upgrade. For example, 10.0 to 10.1 is a _minor_ release upgrade. Version 10 to 11 is a _major_ version upgrade. ## Next steps For information on supported PostgreSQL extensions, see [the extensions document](concepts-extensions.md). ======================= File: articles/iot-central/energy/concept-iot-central-smart-meter-app.md ======================= --- title: Architectural concepts in Azure IoT Central - Energy | Microsoft Docs description: This article introduces key concepts relating the architecture of Azure IoT Central energy app template author: op-ravi ms.author: omravi ms.date: 10/22/2019 ms.topic: overview ms.service: iot-central services: iot-central manager: abjork --- # Azure IoT Central - smart meter app architecture This article provides an overview of the smart meter monitoring app template architecture. The diagram below shows a commonly used architecture for smart meter app on Azure using IoT Central platform. > [!div class="mx-imgBorder"] >![smart meter architecture](media/concept-iot-central-smart-meter/smart-meter-app-architecture.png) This architecture consists of the following components. Some solutions may not require every component listed here. ## Smart meters and connectivity A smart meter is one of the most important devices among all the energy assets. It records and communicates energy consumption data to utilities for monitoring and other use cases, such as billing and demand response. Based on the meter type, it can connect to IoT Central either using gateways or other intermediate devices or systems, such edge devices and head-end systems. Build IoT Central device bridge to connect devices, which can't be connected directly. The IoT Central device bridge is an open-source solution and you can find the complete details [here](https://docs.microsoft.com/azure/iot-central/core/howto-build-iotc-device-bridge). ## IoT Central platform Azure IoT Central is a platform that simplifies building your IoT solution and helps reduce the burden and costs of IoT management, operations, and development. With IoT Central, you can easily connect, monitor, and manage your Internet of Things (IoT) assets at scale. After you connect your smart meters to IoT Central, the app template uses built-in features such as device models, commands, and dashboards. The app template also uses the IoT Central storage for warm path scenarios such as near real-time meter data monitoring, analytics, rules, and visualization. ## Extensibility options to build with IoT Central The IoT Central platform provides two extensibility options: Continuous Data Export (CDE) and APIs. The customers and partners can choose between these options based to customize their solutions for specific needs. For example, one of our partners configured CDE with Azure Data Lake Storage (ADLS). They're using ADLS for long-term data retention and other cold path storage scenarios, such batch processing, auditing and reporting purposes. ## Next steps * Now that you've learned about the architecture, [create smart meter app for free](https://apps.azureiotcentral.com/build/new/smart-meter-monitoring) * To learn more about IoT Central, see [IoT Central overview](https://docs.microsoft.com/azure/iot-central/) ======================= File: articles/sql-database/scripts/sql-database-auditing-and-threat-detection-cli.md ======================= <filename>articles/sql-database/scripts/sql-database-auditing-and-threat-detection-cli.md --- title: CLI example of auditing and Advanced Threat Protection - Azure SQL Database description: Azure CLI example script to configure auditing and Advanced Threat Protection in an Azure SQL Database services: sql-database ms.service: sql-database ms.subservice: security ms.custom: security ms.devlang: azurecli ms.topic: sample author: ronitr ms.author: ronitr ms.reviewer: carlrab, vanto ms.date: 08/05/2019 --- # Use CLI to configure SQL Database auditing and Advanced Threat Protection This Azure CLI script example configures SQL Database auditing and Advanced Threat Protection. If you choose to install and use the CLI locally, this topic requires that you are running the Azure CLI version 2.0 or later. Run `az --version` to find the version. If you need to install or upgrade, see [Install the Azure CLI](/cli/azure/install-azure-cli). ## Sample script ### Sign in to Azure [!INCLUDE [quickstarts-free-trial-note](../../../includes/quickstarts-free-trial-note.md)] ```azurecli-interactive $subscription = "<subscriptionId>" # add subscription here az account set -s $subscription #...or use 'az login' ``` ### Run the script [!code-azurecli-interactive[main](../../../cli_scripts/sql-database/database-auditing-and-threat-detection/database-auditing-and-threat-detection.sh "Configure auditing and threat detection")] ### Clean up deployment Use the following command to remove the resource group and all resources associated with it. ```azurecli-interactive az group delete --name $resource ``` ## Sample reference This script uses the following commands. Each command in the table links to command specific documentation. | | | |---|---| | [az sql db audit-policy](/cli/azure/sql/db/audit-policy) | Sets the auditing policy for a database. | | [az sql db threat-policy](/cli/azure/sql/db/threat-policy) | Sets an Advanced Threat Protection policy on a database. | ## Next steps For more information on the Azure CLI, see [Azure CLI documentation](/cli/azure). Additional SQL Database CLI script samples can be found in the [Azure SQL Database documentation](../../azure-sql/database/az-cli-script-samples-content-guide.md). ======================= File: articles/active-directory-domain-services/concepts-forest-trust.md ======================= --- title: How trusts work for Azure AD Domain Services | Microsoft Docs description: Learn more about how forest trust work with Azure AD Domain Services services: active-directory-ds author: iainfoulds manager: daveba ms.service: active-directory ms.subservice: domain-services ms.workload: identity ms.topic: conceptual ms.date: 03/30/2020 ms.author: iainfou --- # How trust relationships work for resource forests in Azure Active Directory Domain Services Active Directory Domain Services (AD DS) provides security across multiple domains or forests through domain and forest trust relationships. Before authentication can occur across trusts, Windows must first check if the domain being requested by a user, computer, or service has a trust relationship with the domain of the requesting account. To check for this trust relationship, the Windows security system computes a trust path between the domain controller (DC) for the server that receives the request and a DC in the domain of the requesting account. The access control mechanisms provided by AD DS and the Windows distributed security model provide an environment for the operation of domain and forest trusts. For these trusts to work properly, every resource or computer must have a direct trust path to a DC in the domain in which it is located. The trust path is implemented by the Net Logon service using an authenticated remote procedure call (RPC) connection to the trusted domain authority. A secured channel also extends to other AD DS domains through interdomain trust relationships. This secured channel is used to obtain and verify security information, including security identifiers (SIDs) for users and groups. ## Trust relationship flows The flow of secured communications over trusts determines the elasticity of a trust. How you create or configure a trust determines how far the communication extends within or across forests. The flow of communication over trusts is determined by the direction of the trust. Trusts can be one-way or two-way, and can be transitive or non-transitive. The following diagram shows that all domains in *Tree 1* and *Tree 2* have transitive trust relationships by default. As a result, users in *Tree 1* can access resources in domains in *Tree 2* and users in *Tree 1* can access resources in *Tree 2*, when the proper permissions are assigned at the resource. ![Diagram of trust relationships between two forests](./media/concepts-forest-trust/trust-relationships.png) ### One-way and two-way trusts Trust relationships enable access to resources can be either one-way or two-way. A one-way trust is a unidirectional authentication path created between two domains. In a one-way trust between *Domain A* and *Domain B*, users in *Domain A* can access resources in *Domain B*. However, users in *Domain B* can't access resources in *Domain A*. Some one-way trusts can be either non-transitive or transitive depending on the type of trust being created. In a two-way trust, *Domain A* trusts *Domain B* and *Domain B* trusts *Domain A*. This configuration means that authentication requests can be passed between the two domains in both directions. Some two-way relationships can be non-transitive or transitive depending on the type of trust being created. All domain trusts in an AD DS forest are two-way, transitive trusts. When a new child domain is created, a two-way, transitive trust is automatically created between the new child domain and the parent domain. ### Transitive and non-transitive trusts Transitivity determines whether a trust can be extended outside of the two domains with which it was formed. * A transitive trust can be used to extend trust relationships with other domains. * A non-transitive trust can be used to deny trust relationships with other domains. Each time you create a new domain in a forest, a two-way, transitive trust relationship is automatically created between the new domain and its parent domain. If child domains are added to the new domain, the trust path flows upward through the domain hierarchy extending the initial trust path created between the new domain and its parent domain. Transitive trust relationships flow upward through a domain tree as it is formed, creating transitive trusts between all domains in the domain tree. Authentication requests follow these trust paths, so accounts from any domain in the forest can be authenticated by any other domain in the forest. With a single logon process, accounts with the proper permissions can access resources in any domain in the forest. ## Forest trusts Forest trusts help you to manage a segmented AD DS infrastructures and support access to resources and other objects across multiple forests. Forest trusts are useful for service providers, companies undergoing mergers or acquisitions, collaborative business extranets, and companies seeking a solution for administrative autonomy. Using forest trusts, you can link two different forests to form a one-way or two-way transitive trust relationship. A forest trust allows administrators to connect two AD DS forests with a single trust relationship to provide a seamless authentication and authorization experience across the forests. A forest trust can only be created between a forest root domain in one forest and a forest root domain in another forest. Forest trusts can only be created between two forests and can't be implicitly extended to a third forest. This behavior means that if a forest trust is created between *Forest 1* and *Forest 2*, and another forest trust is created between *Forest 2* and *Forest 3*, *Forest 1* doesn't have an implicit trust with *Forest 3*. The following diagram shows two separate forest trust relationships between three AD DS forests in a single organization. ![Diagram of forest trusts relationships within a single organization](./media/con
1,513
Repo: usbong/UsbongPOSApp ======================= File: src/usbong/android/db/UsbongDbHelper.java ======================= <reponame>usbong/UsbongPOSApp /* * Copyright 2017 Usbong Social Systems, Inc. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ //Reference: //1) https://developer.android.com/training/basics/data-storage/databases.html#WriteDbRow //last accessed: 20170518 //2) http://stackoverflow.com/questions/513084/ship-an-application-with-a-database //last accessed: 20170518 //answer by: <NAME> - OMS; edited by: <NAME> package usbong.android.db; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.text.Normalizer; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import org.json.JSONArray; import org.json.JSONObject; import usbong.android.pos_app.R; import usbong.android.pos_app.RequestActivity; import usbong.android.pos_app.UsbongMainActivity; import usbong.android.utils.UsbongConstants; import usbong.android.utils.UsbongDownloadImageTask; import usbong.android.utils.UsbongUtils; import android.app.AlertDialog; import android.content.ContentValues; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.res.Resources; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.net.Uri; import android.provider.BaseColumns; import android.util.Log; import android.widget.TextView; import android.widget.Toast; public class UsbongDbHelper extends SQLiteOpenHelper { // If you change the database schema, you must increment the database version. public static final int DATABASE_VERSION = 35; // public static final String DB_NAME = "usbong_store.db"; // private static String DB_DIR = "/data/data/usbong.android.store_app/databases/"; private static String DB_NAME = "usbong_store.sql";//"database.sqlite"; private static String DB_PATH;// = DB_DIR + DB_NAME; // private static String OLD_DB_PATH = DB_DIR + "old_" + DB_NAME; private final Context myContext; private static SQLiteDatabase db; //added by Mike, 20180525 private static UsbongDbHelper instance; //added by Mike, 20180528 private boolean createDatabase = false; private boolean upgradeDatabase = false; private List<String> attachmentFilePaths; //added by Mike, 20180814 /* Inner class that defines the table contents */ public static class UsbongStoreEntry implements BaseColumns { public static final String TABLE_NAME = "entry"; public static final String COLUMN_NAME_TITLE = "title"; public static final String COLUMN_NAME_SUBTITLE = "subtitle"; } /* private static final String SQL_CREATE_ENTRIES = "CREATE TABLE " + UsbongStoreEntry.TABLE_NAME + " (" + UsbongStoreEntry._ID + " INTEGER PRIMARY KEY," + UsbongStoreEntry.COLUMN_NAME_TITLE + " TEXT," + UsbongStoreEntry.COLUMN_NAME_SUBTITLE + " TEXT)"; private static final String SQL_DELETE_ENTRIES = "DROP TABLE IF EXISTS " + UsbongStoreEntry.TABLE_NAME; */ public UsbongDbHelper(Context context) { super(context, DB_NAME, null, DATABASE_VERSION); myContext = context; // Get the path of the database that is based on the context. DB_PATH = myContext.getDatabasePath(DB_NAME).getAbsolutePath(); instance = this; //added by Mike, 20180528 // getWritableDatabase(); // In the constructor try { SQLiteDatabase.deleteDatabase(new File(DB_PATH)); } //added by Mike, 20180501 catch(NoSuchMethodError e) { myContext.deleteDatabase(DB_NAME); } catch (NullPointerException e) { //no DB to delete } } /** * Upgrade the database in internal storage if it exists but is not current. * Create a new empty database in internal storage if it does not exist. */ public void initializeDataBase() { /* * Creates or updates the database in internal storage if it is needed * before opening the database. In all cases opening the database copies * the database in internal storage to the cache. */ getWritableDatabase(); if (createDatabase) { /* * If the database is created by the copy method, then the creation * code needs to go here. This method consists of copying the new * database from assets into internal storage and then caching it. */ try { /* * Write over the empty data that was created in internal * storage with the one in assets and then cache it. */ copyDataBase(); } catch (IOException e) { throw new Error("Error copying database"); } } else if (upgradeDatabase) { /* * If the database is upgraded by the copy and reload method, then * the upgrade code needs to go here. This method consists of * renaming the old database in internal storage, create an empty * new database in internal storage, copying the database from * assets to the new database in internal storage, caching the new * database from internal storage, loading the data from the old * database into the new database in the cache and then deleting the * old database from internal storage. */ try { /* FileHelper.copyFile(DB_PATH, OLD_DB_PATH); */ copyDataBase(); /* SQLiteDatabase old_db = SQLiteDatabase.openDatabase(OLD_DB_PATH, null, SQLiteDatabase.OPEN_READWRITE); SQLiteDatabase new_db = SQLiteDatabase.openDatabase(DB_PATH, null, SQLiteDatabase.OPEN_READWRITE); */ /* * Add code to load data into the new database from the old * database and then delete the old database from internal * storage after all data has been transferred. */ } catch (IOException e) { throw new Error("Error copying database"); } } } /** * Copies your database from your local assets-folder to the just created * empty database in the system folder, from where it can be accessed and * handled. This is done by transfering bytestream. * */ private void copyDataBase() throws IOException { /* * Close SQLiteOpenHelper so it will commit the created empty database * to internal storage. */ close(); /* * Open the database in the assets folder as the input stream. */ InputStream myInput = myContext.getAssets().open(DB_NAME); /* * Open the empty db in interal storage as the output stream. */ OutputStream myOutput = new FileOutputStream(DB_PATH); /* * Copy over the empty db in internal storage with the database in the * assets folder. */ FileHelper.copyFile(myInput, myOutput); /* * Access the copied database so SQLiteHelper will cache it and mark it * as created. */ getWritableDatabase().close(); } /* * This is where the creation of tables and the initial population of the * tables should happen, if a database is being created from scratch instead * of being copied from the application package assets. Copying a database * from the application package assets to internal storage inside this * method will result in a corrupted database. * <P> * NOTE: This method is normally only called when a database has not already * been created. When the database has been copied, then this method is * called the first time a reference to the database is retrieved after the * database is copied since the database last cached by SQLiteOpenHelper is * different than the database in internal storage. */ @Override public void onCreate(SQLiteDatabase db) { if (!upgradeDatabase) { /* //added by Mike, 20180529 UsbongDbHelper.db = db; */ /* * Signal that a new database needs to be copied. The copy process must * be performed after the database in the cache has been closed causing * it to be committed to internal storage. Otherwise the database in * internal storage will not have the same creation timestamp as the one * in the cache causing the database in internal storage to be marked as * corrupted. */ createDatabase = true; /* * This will create by reading a sql file and executing the commands in * it. */ try { InputStream is = myContext.getResources().getAssets().open( "usbong_store.sql"); String[] statements = FileHelper.parseSqlFile(is); for (String statement : statements) { db.execSQL(statement); } }catch (Exception ex) { ex.printStackTrace(); } // try { // InputStream is = myContext.getResources().getAssets().open( // "create_database.sql"); // // String[] statements = FileHelper.parseSqlFile(is); // // for (String statement : statements) { // db.execSQL(statement); // } // } catch (Exception ex) { // ex.printStackTrace(); // } } } /** * Called only if version number was changed and the database has already * been created. Copying a database from the application package assets to * the internal data system inside this method will result in a corrupted * database in the internal data system. */ @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { /* //added by Mike, 20180529 UsbongDbHelper.db = db; */ /* * Signal that the database needs to be upgraded for the copy method of * creation. The copy process must be performed after the database has * been opened or the database will be corrupted. */ upgradeDatabase = true; /* * Code to update the database via execution of sql statements goes * here. */ /* * This will upgrade by reading a sql file and executing the commands in * it. */ try { // myContext.deleteDatabase(DB_PATH); // String p = myContext.getDatabasePath(DB_NAME).getAbsolutePath(); // myContext.deleteDatabase(p); // if (SQLiteDatabase.deleteDatabase(new File(p))) { InputStream is = myContext.getResources().getAssets().open( "usbong_store.sql"); String[] statements = FileHelper.parseSqlFile(is); for (String statement : statements) { db.execSQL(statement); } // } } catch (Exception ex) { ex.printStackTrace(); } } /** * Called everytime the database is opened by getReadableDatabase or * getWritableDatabase. This is called after onCreate or onUpgrade is * called. */ @Override public void onOpen(SQLiteDatabase db) { super.onOpen(db); } /* * Add your public helper methods to access and get content from the * database. You could return cursors by doing * "return myDataBase.query(....)" so it'd be easy to you to create adapters * for your views. */ /* public void onCreate(SQLiteDatabase db) { db.execSQL(SQL_CREATE_ENTRIES); } public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // This database is only a cache for online data, so its upgrade policy is // to simply to discard the data and start over db.execSQL(SQL_DELETE_ENTRIES); onCreate(db); } public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) { onUpgrade(db, oldVersion, newVersion); } */ //TODO: update this; use UsbongDbHelper.db //added by Mike, 20180213 public void syncInternalDBwithServerDB(/*SQLiteDatabase db,*/ JSONArray serverProductsTable) { try { //check first if the internal DB is already synced int serverProductsTableLength = serverProductsTable.length(); int internalDBProductsTableLength=0; Cursor c = db.rawQuery("SELECT MAX(`product_id`) FROM `product`", null); if (c.moveToFirst()){ internalDBProductsTableLength = c.getInt(0); } c.close(); if (internalDBProductsTableLength==serverProductsTableLength) { return; } //get all the product types from SQLite DB Cursor cProductType = db.rawQuery("SELECT `product_type_name` FROM `product_type`", null); ArrayList<String> listOfProductTypes = new ArrayList<String>(); if (cProductType!= null) { if (cProductType.moveToFirst()) { // if Cursor is not empty while (!cProductType.isAfterLast()) { listOfProductTypes.add(cProductType.getString(cProductType.getColumnIndex("product_type_name"))); cProductType.moveToNext(); } } else { // Cursor is empty Log.d(">>>>>", "cursor is empty"); } } else { // Cursor is null Log.d(">>>>>", "cursor is null"); } cProductType.close(); Resources myRes = ((UsbongMainActivity)myContext).getResources(); // String[][] listOfProductsPerProductType = new String[listOfProductTypes.size()][]; HashMap<String, String[]> listOfProductsPerProductTypeHashMap = new HashMap<String, String[]>(); //TODO: add: also the products in the sd card if available for(int i=0; i<listOfProductTypes.size(); i++) { String productType = listOfProductTypes.get(i).toLowerCase().replace("'","").replace(" & ", "_and_"); listOfProductsPerProductTypeHashMap.put(productType, myRes.getAssets().list(productType)); } //delete the entire DB to make sure that the primary keys are the same with the online DB // db.execSQL("delete from " + "product"); ContentValues insertValues = new ContentValues(); // JSONArray json = new JSONArray(serverProductsTable); /* for(int i=0;i<serverProductsTable.length();i++) { */ JSONArray nestedJsonArray = serverProductsTable; //.optJSONArray(i); /* JSONArray innerArray = serverProductsTable.getJSONArray(i); double[] innerResult = new double[innerArray.length()]; */ if (nestedJsonArray!= null) { for(int j=0;j<nestedJsonArray.length();j++) { JSONObject jo_inside = nestedJsonArray.getJSONObject(j); insertValues.put("product_id", jo_inside.getString("product_id")); insertValues.put("merchant_id", jo_inside.getString("merchant_id")); insertValues.put("product_type_id", jo_inside.getString("product_type_id")); // insertValues.put("product_type_name", jo_inside.getString("product_type_name")); insertValues.put("name", jo_inside.getString("name")); insertValues.put("price", jo_inside.getString("price")); insertValues.put("previous_price", jo_inside.getString("previous_price")); insertValues.put("language", jo_inside.getString("language")); insertValues.put("author", jo_inside.getString("author")); insertValues.put("supplier", jo_inside.getString("supplier")); insertValues.put("description", jo_inside.getString("description")); insertValues.put("image_location", jo_inside.getString("image_location")); insertValues.put("format", jo_inside.getString("format")); insertValues.put("quantity_in_stock", jo_inside.getString("quantity_in_stock")); insertValues.put("translator", jo_inside.getString("translator")); insertValues.put("pages", jo_inside.getString("pages")); // db.insert("product", null, insertValues); //added by Mike, 20180222 //verify whether the product item image is already stored in the assets' folder of the.apk String product_item_image_name = jo_inside.getString("name").replace("'", "").replace(":", "") + ".jpg"; //added by Mike, 20180308 product_item_image_name = Normalizer.normalize(product_item_image_name, Normalizer.Form.NFD); product_item_image_name = product_item_image_name.replaceAll("[^\\p{ASCII}]", ""); String url_friendly_product_type_name = jo_inside.getString("product_type_name").toLowerCase().replace("'", "").replace(" & ", "_and_"); try { /*Drawable myDrawableImage = */ //this will throw a FileNotFoundException if the file does not exist // Drawable.createFromStream(myRes.getAssets().open(jo_inside.getString("product_type_name").toLowerCase() + "/" + product_item_image_name), null); // String[] myList = myRes.getAssets().list(url_friendly_product_type_name);// + "/"); // String path = url_friendly_product_type_name + "/" + product_item_image_name; /* boolean isInList=false; */ if (listOfProductsPerProductTypeHashMap.get(url_friendly_product_type_name)!=null) { List<String> myList = Arrays.asList(listOfProductsPerProductTypeHashMap.get(url_friendly_product_type_name)); if (!myList.contains(product_item_image_name)) { //added by Mike, 20180310 db.insert("product", null, insertValues); new UsbongDownloadImageTask().execute("https://store.usbong.ph/assets/images/" + url_friendly_product_type_name + "/" + product_item_image_name.replace(" ", "%20")); } } /* for(int i=0; i<myList.length; i++) { // Log.d(">>>>", myList[i]); if (myList[i].equals(product_item_image_name)) { isInList=true; break; } } if (!isInList) { //Drawable.createFromStream(myRes.getAssets().open(path), null); new UsbongDownloadImageTask().execute("https://store.usbong.ph/assets/images/" + url_friendly_product_type_name + "/" + product_item_image_name.replace(" ", "%20")); } */ /* if (myDrawableImage == null) { new UsbongDownloadImageTask().execute("https://store.usbong.ph/assets/images/" + jo_inside.getString("product_type_name").toLowerCase() + "/" + product_item_image_name.replace(" ", "%20")); } */ } /* catch (FileNotFoundException e) { new UsbongDownloadImageTask().execute("https://store.usbong.ph/assets/images/" + jo_inside.getString("product_type_name").toLowerCase() + "/" + product_item_image_name.replace(" ", "%20")); } */ catch (Exception e) { e.printStackTrace(); } //add the image in the sd card // new UsbongDownloadImageTask().execute("https://store.usbong.ph/assets/images/childrens/Harry%20Potter%20and%20the%20Sorcerers%20Stone.jpg"); // new UsbongDownloadImageTask().execute("https://store.usbong.ph/assets/images/" + jo_inside.getString("product_type_name").toLowerCase() + "/" + product_item_image_name); } } /* } */ }catch (Exception ex) { ex.printStackTrace(); } } //added by Mike, 20180517 public String generateReportForTheDay(){//SQLiteDatabase db) { //edited by Mike, 20180530 // UsbongDbHelper.db = UsbongDbHelper.instance.getReadableDatabase(); if (UsbongDbHelper.db==null) { return null; } String getCart = "select * from 'cart'"; Cursor c = UsbongDbHelper.db.rawQuery(getCart, null); StringBuffer outputStringBuffer = new StringBuffer(); outputStringBuffer.append( "cart_id"+","+ "product_id"+","+ "quantity"+","+ "price"+","+ "purchased_datetime_stamp"+"\n"); if (c!= null) { if (c.moveToFirst()) { while (!c.isAfterLast()) { outputStringBuffer.append( c.getString(c.getColumnIndex("cart_id"))+","+ c.getString(c.getColumnIndex("product_id"))+","+ c.getString(c.getColumnIndex("quantity"))+","+ c.getString(c.getColumnIndex("price"))+","+ c.getString(c.getColumnIndex("purchased_datetime_stamp"))+"\n"); c.moveToNext(); } } } String myOutputDirectory=UsbongUtils.getDateTimeStamp()+"/"; String offset = "output/reportForTheDay/"; try { UsbongUtils.createNewOutputFolderStructure(offset); } catch(Exception e) { e.printStackTrace(); } String output_path = UsbongUtils.BASE_FILE_PATH + offset + myOutputDirectory + UsbongUtils.getDateTimeStamp() + ".csv"; UsbongUtils.storeOutputInSDCard(output_path, outputStringBuffer.toString()); return output_path; } //added by Mike, 20180517 public String generatePresentInventory(){//SQLiteDatabase db) { //edited by Mike, 20180530 // UsbongDbHelper.db = UsbongDbHelper.instance.getReadableDatabase(); if (UsbongDbHelper.db==null) { UsbongDbHelper.db = UsbongDbHelper.instance.getReadableDatabase(); /* return null; */ } String getProduct = "select * from 'product'"; Cursor c = UsbongDbHelper.db.rawQuery(getProduct, null); StringBuffer outputStringBuffer = new StringBuffer(); outputStringBuffer.append( "product_id"+","+ "quantity_in_stock"+","+ "price"+","+ "quantity_sold"+"\n"); if (c!= null) { if (c.moveToFirst()) { while (!c.isAfterLast()) { outputStringBuffer.append( c.getString(c.getColumnIndex("product_id"))+","+ c.getString(c.getColumnIndex("quantity_in_stock"))+","+ c.getString(c.getColumnIndex("price"))+","+ c.getString(c.getColumnIndex("quantity_sold"))+"\n"); c.moveToNext(); } } } String myOutputDirectory=UsbongUtils.getDateTimeStamp()+"/"; String offset = "output/presentInventory/"; try { UsbongUtils.createNewOutputFolderStructure(offset); } catch(Exception e) { e.printStackTrace(); } String output_path = UsbongUtils.BASE_FILE_PATH + offset + myOutputDirectory + UsbongUtils.getDateTimeStamp() + ".csv"; UsbongUtils.storeOutputInSDCard(output_path, outputStringBuffer.toString()); return output_path; } //edited by Mike, 20180814 //the return String is the output_path to be used to attach the.csv file to the email public void submitReportForTheDay(){//SQLiteDatabase db) { // return generateReportForTheDay();//db); String output_path = generateReportForTheDay(); if (output_path!=null) { //added by Mike, 20180812 attachmentFilePaths = new ArrayList<String>(); //only add path if it's not already in attachmentFilePaths if (!attachmentFilePaths.contains(output_path)) { attachmentFilePaths.add(output_path); } emailReport(UsbongConstants.REPORT_TYPE_REPORT_FOR_THE_DAY); } } //edited by Mike, 20180812 //the return String is the output_path to be used to attach the.csv file to the email public void submitPresentInventory(){//SQLiteDatabase db) { // return generatePresentInventory();//db); // return generateReportForTheDay();//db); String output_path = generatePresentInventory(); if (output_path!=null) { //added by Mike, 20180812 attachmentFilePaths = new ArrayList<String>(); //only add path if it's not already in attachmentFilePaths if (!attachmentFilePaths.contains(output_path)) { attachmentFilePaths.add(output_path); } emailReport(UsbongConstants.REPORT_TYPE_INVENTORY); } } //edited by Mike, 20180530 public void updateCartTable(/*SQLiteDatabase db, */ArrayList<String> listOfItemsArrayList) { /* if ((UsbongDbHelper.db!=null) && (!UsbongDbHelper.db.isOpen())) { UsbongDbHelper.db = UsbongDbHelper.instance.getReadableDatabase(); } else { UsbongDbHelper.db = db; } */ /* UsbongDbHelper.db = UsbongDbHelper.instance.getWritableDatabase(); */ //added by Mike, 20180602 if (UsbongDbHelper.db==null) { UsbongDbHelper.db = UsbongDbHelper.instance.getWritableDatabase(); } ContentValues insertValues = new ContentValues(); //TODO: put this portion of code in UsbongUtils, since I use this more than once; the other is in CartActivity //This creates two lists: 1) unique product items, 2) the quantity of each unique product item; //The index used for the product list, i.e. productsList, matches with the index for the quantity list //This is to properly identify the product item in both lists. //------------------------------------------------------------ String prev=""; int quantity=0; ArrayList<String> productsList = new ArrayList<String>(); ArrayList<String> quantityList = new ArrayList<String>(); int listOfItemsArrayListSize = listOfItemsArrayList.size(); if (listOfItemsArrayListSize!= 0) { for (int i=0; i<listOfItemsArrayListSize; i++) { if (prev.equals("")) { quantity++; prev = listOfItemsArrayList.get(i); } else if (listOfItemsArrayList.get(i).equals(prev)) { quantity++; } else { /* Log.d(">>>>>>listOfItemsArrayList.get(i-1)", ""+listOfItemsArrayList.get(i-1).toString()); Log.d(">>>>>>quantity", ""+quantity); */ productsList.add(listOfItemsArrayList.get(i-1).toString()); quantityList.add(""+quantity); //"<b>Quantity:</b> "+quantity prev = listOfItemsArrayList.get(i); quantity=1; } } productsList.add(listOfItemsArrayList.get(listOfItemsArrayListSize-1)); quantityList.add(""+quantity); } //------------------------------------------------------------ for (int i=0; i<productsList.size(); i++) { String s = productsList.get(i); int currProductId = Integer.parseInt(s.substring(s.indexOf("ProductId: ")+"ProductId: ".length()).toString()); String priceStartString = s.substring(s.indexOf("₱")+"₱".length()); String priceString = priceStartString.substring(0, priceStartString.indexOf("</b>")); Double price = Double.parseDouble(priceString); String dateTimeStamp = UsbongUtils.getDateTimeStamp(); insertValues.put("product_id", currProductId); insertValues.put("quantity", quantityList.get(i)); insertValues.put("price", price); insertValues.put("purchased_datetime_stamp", dateTimeStamp); UsbongDbHelper.db.insert("cart", null, insertValues); } /* UsbongDbHelper.instance.close(); */ /* String getCart = "select * from 'cart'"; Cursor c = db.rawQuery(getCart, null); if (c!= null) { if (c.moveToFirst()) { while (!c.isAfterLast()) { Log.d(">>> getCartId", c.getString(c.getColumnIndex("cart_id"))); Log.d(">>> getProductId", c.getString(c.getColumnIndex("product_id"))); Log.d(">>> quantity", c.getString(c.getColumnIndex("quantity"))); Log.d(">>> price", c.getString(c.getColumnIndex("price"))); Log.d(">>> purchased_datetime_stamp", c.getString(c.getColumnIndex("purchased_datetime_stamp"))); c.moveToNext(); } } } */ } //added by Mike, 20180814 public void emailReport(int reportType) { StringBuffer emailSummary = new StringBuffer(); switch (reportType) { case UsbongConstants.REPORT_TYPE_REPORT_FOR_THE_DAY: emailSummary.append("-Report for the Day-\n"); break; case UsbongConstants.REPORT_TYPE_INVENTORY: emailSummary.append("-Present Inventory-\n"); break; } //TODO: update this emailSummary.append("Location: Marikina Orthopedic Specialty Clinic (MOSC)\n\n"); emailSummary.append("Thank you.\n\n"); emailSummary.append("-End of Report-"); //http://stackoverflow.com/questions/2197741/how-can-i-send-emails-from-my-android-application; //answer by: <NAME>, 20100204 //added by Mike, 20170220 Intent i = new Intent(Intent.ACTION_SEND_MULTIPLE); //changed from ACTION_SEND to ACTION_SEND_MULTIPLE by Mike, 20170313 i.setType("message/rfc822"); //remove all non-email apps that support send intent from chooser i.putExtra(Intent.EXTRA_EMAIL , new String[]{UsbongConstants.ADMIN_EMAIL_ADDRESS}); switch (reportType) { case UsbongConstants.REPORT_TYPE_REPORT_FOR_THE_DAY: i.putExtra(Intent.EXTRA_SUBJECT, "Usbong MOSC: Report for the Day"); break; case UsbongConstants.REPORT_TYPE_INVENTORY: i.putExtra(Intent.EXTRA_SUBJECT, "Usbong MOSC: Present Inventory"); break; } i.putExtra(Intent.EXTRA_TEXT , emailSummary.toString()); //added by Mike, 20170310 //Reference: http://stackoverflow.com/questions/2264622/android-multiple-email-attachments-using-intent //last accessed: 14 March 2012 //has to be an ArrayList ArrayList<Uri> uris = new ArrayList<Uri>(); //convert from paths to Android friendly Parcelable Uri's for (String file : attachmentFilePaths) { File fileIn = new File(file); if (fileIn.exists()) { //added by Mike, May 13, 2012 Uri u = Uri.fromFile(fileIn); uris.add(u); // System.out.println(">>>>>>>>>>>>>>>>>> u: "+u); } } i.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris); try { // isSendingData=true; //added by Mike, 20170225 UsbongMainActivity.getInstance().startActivityForResult(Intent.createChooser(i, "Sending email..."), 1); } catch (android.content.ActivityNotFoundException ex) { Toast.makeText(UsbongMainActivity.getInstance(), "There are no email clients installed.", Toast.LENGTH_SHORT).show(); } } } ======================= File: src/usbong/android/pos_app/CartActivity.java ======================= <filename>src/usbong/android/pos_app/CartActivity.java /* * Copyright 2016 <NAME> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package usbong.android.pos_app; import java.io.File; import java.io.InputStream; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import usbong.android.db.UsbongDbHelper; import usbong.android.utils.UsbongConstants; import usbong.android.utils.UsbongUtils; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Resources; import android.database.sqlite.SQLiteDatabase; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.AppCompatRadioButton; import android.text.Html; import android.text.InputType; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; //commented out by Mike, 20180427 //import usbong.android.pos_app.UsbongDecisionTreeEngineActivity; /* * This is Usbong's Main Menu activity. */ public class CartActivity extends AppCompatActivity/*Activity*/ { private final static int SHOPPING_CART_SCREEN=0; private final static int ACCOUNT_SCREEN=1; private static int currScreen; //added by Mike, 20170427 public ListView treesListView; private CustomDataAdapter mCustomAdapter; private ArrayList<String> listOfItemsArrayList; private static CartActivity instance; private boolean isSendingData; //edited by Mike, 20170225 private static int currPreference=UsbongConstants.defaultPreference; private static int currModeOfPayment=UsbongConstants.defaultModeOfPayment; private String productDetails; //added by Mike, 20170221 private Button confirmButton; private Button buyButton; //added by Mike, 20170220 private Button backButton; /* private Button sellButton; private Button requestButton; */ // private static BuyActivity instance; public static String timeStamp; // private static Date startTime; //commented out by Mike, 20180427 // protected UsbongDecisionTreeEngineActivity myUsbongDecisionTreeEngineActivity; protected SettingsActivity mySettingsActivity; private static Activity myActivityInstance; private ProgressDialog myProgressDialog; private AlertDialog inAppSettingsDialog; //added by Mike, 20160417 private ArrayList<String> quantityList; //added by Mike, 20170505 private ArrayList<String> tempList; //added by Mike, 20170511 private Double orderSubtotalCost; //edited by Mike, 20180508 private String orderSubtotalCostString; //edited by Mike, 20180509 /* private int less70pesosPromoTotal; //added by Mike, 20170902 */ @Override public void onCreate(Bundle savedInstanceState) { getWindow().requestFeature(Window.FEATURE_ACTION_BAR); super.onCreate(savedInstanceState); instance=this; //added by Mike, 27 Sept. 2015 getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); myActivityInstance = this; currScreen=SHOPPING_CART_SCREEN;//default; added by Mike, 20170220 //added by Mike, 25 Sept. 2015 getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setTitle(getResources().getString(R.string.usbong)); //app_name // getSupportActionBar().setDisplayUseLogoEnabled(true); setContentView(R.layout.cart_tree_list_interface); // setContentView(R.layout.buy); /*//commented out by Mike, 20170216 //added by Mike, 20161117 Bundle extras = getIntent().getExtras(); if (extras!=null) { String message = extras.getString("completed_tree"); if (message.equals("true")) { AppRater.showRateDialog(this); } } */ reset(); initCart(); } public Activity getInstance() { // return instance; return myActivityInstance; } /* * Initialize this activity */ public void initCart() { //edited by Mike, 20170429 // String currCategory = UsbongConstants.ITEMS_LIST_BOOKS; // listOfItemsArrayList = UsbongUtils.getItemArrayList(UsbongUtils.USBONG_TREES_FILE_PATH + currCategory+".txt"); if (UsbongUtils.itemsInCart!=null) { Collections.sort(UsbongUtils.itemsInCart); //added by Mike, 20170509 listOfItemsArrayList = UsbongUtils.itemsInCart; } else { listOfItemsArrayList = new ArrayList<String>(); } /* int listOfItemsArrayListSize = listOfItemsArrayList.size(); if (listOfItemsArrayListSize==0) { return; } */ String prev=""; int quantity=0; tempList = new ArrayList<String>(); quantityList = new ArrayList<String>(); /* listOfItemsArrayList = noQuantityList; */ int listOfItemsArrayListSize = listOfItemsArrayList.size(); if (listOfItemsArrayListSize!= 0) { // Collections.sort(listOfItemsArrayList); for (int i=0; i<listOfItemsArrayListSize; i++) { if (prev.equals("")) { quantity++; prev = listOfItemsArrayList.get(i); } else if (listOfItemsArrayList.get(i).equals(prev)) { quantity++; } else { Log.d(">>>>>>listOfItemsArrayList.get(i)", i+": "+listOfItemsArrayList.get(i)); Log.d(">>>>>>prev", prev); tempList.add(listOfItemsArrayList.get(i-1).toString()); quantityList.add(""+quantity); //"<b>Quantity:</b> "+quantity prev = listOfItemsArrayList.get(i); quantity=1; } } tempList.add(listOfItemsArrayList.get(listOfItemsArrayListSize-1)); quantityList.add(""+quantity); //"<b>Quantity:</b> "+quantity //listOfItemsArrayList = tempList; } mCustomAdapter = new CustomDataAdapter(this, R.layout.tree_loader_cart, tempList); //listOfItemsArrayList // mCustomAdapter.sort(); //edited by Mike, 20170203 /* //Reference: http://stackoverflow.com/questions/8908549/sorting-of-listview-by-name-of-the-product-using-custom-adaptor; //last accessed: 2 Jan. 2014; answer by <NAME> mCustomAdapter.sort(new Comparator<String>() { public int compare(String arg0, String arg1) { return arg0.compareTo(arg1); } }); */ treesListView = (ListView)findViewById(R.id.tree_list_view); treesListView.setLongClickable(true); treesListView.setAdapter(mCustomAdapter); processPromoAndOrderTotal(); //added by Mike, 20170511 //added by Mike, 20160126 confirmButton = (Button)findViewById(R.id.confirm_button); confirmButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (currScreen==SHOPPING_CART_SCREEN) { //this should be true //added by Mike, 20170427 // UsbongUtils.cartIcon.setIcon(R.drawable.cart_icon_not_empty); UsbongUtils.cartIconDrawableResourceId = R.drawable.cart_icon_not_empty; myActivityInstance.invalidateOptionsMenu(); /* //commented out by Mike, 20180509 currScreen=ACCOUNT_SCREEN; setContentView(R.layout.account); init(); */ new AlertDialog.Builder(CartActivity.this).setTitle("CHECKOUT") // .setMessage(UsbongUtils.getHumanReadableDateTimeStamp() +"\nCustomer's Order Total: " + orderSubtotalCostString) .setMessage("Customer's Order Total: " + orderSubtotalCostString) .setPositiveButton("CONFIRM", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { UsbongUtils.cartIconDrawableResourceId = R.drawable.cart_icon; UsbongMainActivity.getInstance().invalidateOptionsMenu(); //TODO: //do this only once /* UsbongDbHelper myDbHelper = new UsbongDbHelper(UsbongMainActivity.getInstance()); //edited by Mike, 20180524 myDbHelper.initializeDataBase(); SQLiteDatabase mySQLiteDatabase = myDbHelper.getReadableDatabase(); */ /* int listOfItemsArrayListSize = listOfItemsArrayList.size(); if (listOfItemsArrayListSize!= 0) { for (int i=0; i<listOfItemsArrayListSize; i++) { Log.d(">>>", listOfItemsArrayList.get(i)); } } */ //edited by Mike, 20180529 UsbongMainActivity.getInstance().updateDbHelperCartTable(/*mySQLiteDatabase,*/listOfItemsArrayList); //edited by Mike, 20180517 UsbongUtils.itemsInCart.clear(); returnToProductSelection(); } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { //ACTION } }) .show(); } } }); } //edited by Mike, 20170928 public void processPromoAndOrderTotal() { orderSubtotalCost = 0.00; /* less70pesosPromoTotal = 0; */ for (int i=0; i<tempList.size(); i++) { String s = tempList.get(i); String sPart1 = s.substring(s.indexOf("₱")); String item_price = sPart1.substring(0,sPart1.indexOf("<"));//("("));//(used), (new) /* less70pesosPromoTotal+=Integer.parseInt(quantityList.get(i))*70; */ // orderSubtotalCost+=Integer.parseInt(item_price.replace("₱", "").trim())*Integer.parseInt(quantityList.get(i)); //edited by Mike, 20180508 orderSubtotalCost+=Double.parseDouble(item_price.replace("₱", "").trim())*Integer.parseInt(quantityList.get(i)); } /* //edited by Mike, 20170930 if (tempList.size()>0) { less70pesosPromoTotal-=70; } TextView less70pesosTextView = (TextView)findViewById(R.id.less_70pesos); less70pesosTextView.setText("Less ₱70 promo: -₱"+less70pesosPromoTotal); orderSubtotalCost-=less70pesosPromoTotal; */ TextView orderSubtotalCostTextView = (TextView)findViewById(R.id.order_subtotal); //edited by Mike, 20180519 NumberFormat formatter = NumberFormat.getNumberInstance(); formatter.setMinimumFractionDigits(2); formatter.setMaximumFractionDigits(2); String output = formatter.format(orderSubtotalCost); //edited by Mike, 20180509 // int subtotalNumber = quantity*Integer.parseInt(item_price.replace("₱", "").trim()); orderSubtotalCostString = "₱" + output;//orderSubtotalCost; /* if (orderSubtotalCostString.contains(".")) { if (orderSubtotalCostString.substring(orderSubtotalCostString.indexOf(".")).length()-1 < 2) { orderSubtotalCostString = orderSubtotalCostString.concat("0"); } } */ orderSubtotalCostTextView.setText("Order Total: "+orderSubtotalCostString); } public void init() { //added by Mike, 20170310 UsbongUtils.deleteRecursive(new File(UsbongUtils.BASE_FILE_PATH_TEMP)); //Reference: http://stackoverflow.com/questions/23024831/android-shared-preferences-example //; last accessed: 20150609 //answer by Elenasys //added by Mike, 20150207 SharedPreferences prefs = getSharedPreferences(UsbongConstants.MY_ACCOUNT_DETAILS, MODE_PRIVATE); if (prefs!=null) { ((TextView)findViewById(R.id.first_name)).setText(prefs.getString("firstName", ""));//"" is the default value. ((TextView)findViewById(R.id.surname)).setText(prefs.getString("surname", "")); //"" is the default value. ((TextView)findViewById(R.id.contact_number)).setText(prefs.getString("contactNumber", "")); //"" is the default value /* //added by Mike, 20170223 RadioGroup preferenceRadioButtonGroup = ((RadioGroup)findViewById(R.id.preference_radiogroup)); ((RadioButton)preferenceRadioButtonGroup.getChildAt(prefs.getInt("preference", UsbongConstants.defaultPreference))).setChecked(true); */ ((TextView)findViewById(R.id.address)).setText(prefs.getString("shippingAddress", "")); //"" is the default value //added by Mike, 20170223 RadioGroup modeOfPaymentRadioButtonGroup = ((RadioGroup)findViewById(R.id.mode_of_payment_radiogroup)); ((RadioButton)modeOfPaymentRadioButtonGroup.getChildAt(prefs.getInt("modeOfPayment", UsbongConstants.defaultModeOfPayment))).setChecked(true); /* //added by Mike, 20180406 RadioButton modeOfPaymentBankDepositRadioButton = ((RadioButton)findViewById(R.id.bank_deposit_radiobutton)); modeOfPaymentBankDepositRadioButton.setText( Html.fromHtml("Bank Deposit (<a href='https://www.bdo.com.ph/send-money' target='_blank'> " + "BDO</a>" + "/" + "<a href='https://www.bpiexpressonline.com/p/0/6/online-banking' target='_blank'> " + "BPI</a>)")); */ } //added by Mike, 20160126 confirmButton = (Button)findViewById(R.id.confirm_button); confirmButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { /*if (currScreen==SHOPPING_CART_SCREEN) { //added by Mike, 20170427 // UsbongUtils.cartIcon.setIcon(R.drawable.cart_icon_not_empty); UsbongUtils.cartIconDrawableResourceId = R.drawable.cart_icon_not_empty; myActivityInstance.invalidateOptionsMenu(); currScreen=ACCOUNT_SCREEN; setContentView(R.layout.account); init(); } else {*/ if (verifyFields()) { //save data //Reference: http://stackoverflow.com/questions/23024831/android-shared-preferences-example //; last accessed: 20150609 //answer by Elenasys //added by Mike, 20170207 SharedPreferences.Editor editor = getSharedPreferences(UsbongConstants.MY_ACCOUNT_DETAILS, MODE_PRIVATE).edit(); editor.putString("firstName", ((TextView)findViewById(R.id.first_name)).getText().toString()); editor.putString("surname", ((TextView)findViewById(R.id.surname)).getText().toString()); editor.putString("contactNumber", ((TextView)findViewById(R.id.contact_number)).getText().toString()); /* RadioGroup radioButtonGroup = (RadioGroup)findViewById(R.id.preference_radiogroup); for (int i=0; i< radioButtonGroup.getChildCount(); i++) { if (((RadioButton)radioButtonGroup.getChildAt(i)).isChecked()) { currPreference=i; } } editor.putInt("preference", currPreference); //added by Mike, 20170223 */ editor.putString("shippingAddress", ((TextView)findViewById(R.id.address)).getText().toString()); RadioGroup paymentMethodRadioButtonGroup = (RadioGroup)findViewById(R.id.mode_of_payment_radiogroup); for (int i=0; i< paymentMethodRadioButtonGroup.getChildCount(); i++) { if (((RadioButton)paymentMethodRadioButtonGroup.getChildAt(i)).isChecked()) { currModeOfPayment=i; } } editor.putInt("modeOfPayment", currModeOfPayment); //added by Mike, 20170223 editor.commit(); StringBuffer buySummary = new StringBuffer(); buySummary.append("-Purchase Order Summary-\n"); int tempListSize = tempList.size(); for (int i=0; i<tempListSize; i++) { //edited by Mike, 20170725 String o = tempList.get(i).toString(); buySummary.append(Html.fromHtml(o.substring(0, o.indexOf("ImageFileName: ")) .replace("MerchantName: ", "<br>")) +"\n"); buySummary.append("Quantity: "+quantityList.get(i)+"\n"); if (i<tempListSize-1) { buySummary.append("-\n"); } } buySummary.append("--\n"); /* buySummary.append("Less ₱70 promo: -₱"+less70pesosPromoTotal+"\n"); */ int paymentMethodRadioButtonID = paymentMethodRadioButtonGroup.getCheckedRadioButtonId(); RadioButton paymentMethodRadioButton = (RadioButton) paymentMethodRadioButtonGroup.findViewById(paymentMethodRadioButtonID); String paymentMethodSelectedText = paymentMethodRadioButton.getText().toString(); if (paymentMethodSelectedText.contains("Meetup at MOSC (Less ₱70)")) { buySummary.append("Meetup at MOSC promo: -₱70\n"); orderSubtotalCost-=70; } buySummary.append("Order Total: ₱"+orderSubtotalCost+"\n"); buySummary.append("--\n"); /* buySummary.append(productDetails+"\n"); String quantity = ((TextView)findViewById(R.id.quantity)).getText().toString(); if (quantity.trim().equals("")) { buySummary.append("Quantity: "+ "1" +"\n--\n"); } else { buySummary.append("Quantity: "+ quantity +"\n--\n"); } */ buySummary.append("Customer Name: "+ ((TextView)findViewById(R.id.surname)).getText().toString()+", "+ ((TextView)findViewById(R.id.first_name)).getText().toString()+"\n"); buySummary.append("Contact Number: "+ ((TextView)findViewById(R.id.contact_number)).getText().toString()+"\n"); /* // RadioGroup radioButtonGroup = (RadioGroup)findViewById(R.id.preference_radiogroup); int radioButtonID = radioButtonGroup.getCheckedRadioButtonId(); // RadioButton r = (RadioButton) radioButtonGroup.getChildAt(radioButtonID); RadioButton radioButton = (RadioButton) radioButtonGroup.findViewById(radioButtonID); String selectedText = radioButton.getText().toString(); buySummary.append("Preference: "+selectedText+"\n"); */ /* buySummary.append("Address: "+ ((TextView)findViewById(R.id.address)).getText().toString()+"\n"); */ if (paymentMethodSelectedText.contains("Meetup at MOSC (Less ₱70)")) { buySummary.append("Address: Marikina Orthopedic Specialty Clinic\n"); } else { buySummary.append("Address: "+ ((TextView)findViewById(R.id.address)).getText().toString()+"\n"); } /* // RadioGroup paymentMethodRadioButtonGroup = (RadioGroup)findViewById(R.id.mode_of_payment_radiogroup); int paymentMethodRadioButtonID = paymentMethodRadioButtonGroup.getCheckedRadioButtonId(); RadioButton paymentMethodRadioButton = (RadioButton) paymentMethodRadioButtonGroup.findViewById(paymentMethodRadioButtonID); String paymentMethodSelectedText = paymentMethodRadioButton.getText().toString(); */ buySummary.append("Payment Method: "+paymentMethodSelectedText+"\n"); String additionalInstructionsString = ((TextView)findViewById(R.id.additional_instructions)).getText().toString(); if (additionalInstructionsString.trim().equals("")) { buySummary.append("Additional Instructions: "+ "N/A\n"); } else { buySummary.append("Additional Instructions: "+ additionalInstructionsString+"\n"); } String additionalInquiriesString = ((TextView)findViewById(R.id.additional_inquiries)).getText().toString(); if (additionalInquiriesString.trim().equals("")) { buySummary.append("Additional Inquiries: "+ "N/A\n"); } else { buySummary.append("Additional Inquiries: "+ additionalInquiriesString+"\n"); } /* //added by Mike, 20170221 UsbongUtils.generateDateTimeStamp(); buySummary.append("\nPurchase Order ID:\n"+UsbongUtils.getDateTimeStamp()+"\n"); */ buySummary.append("-End of Summary-"); //added by Mike, 20170511 String s = ""; if (tempList.size()>1) { s="..."; } //http://stackoverflow.com/questions/2197741/how-can-i-send-emails-from-my-android-application; //answer by: <NAME>, 20100204 //added by Mike, 20170220 Intent i = new Intent(Intent.ACTION_SEND); i.setType("message/rfc822"); //remove all non-email apps that support send intent from chooser i.putExtra(Intent.EXTRA_EMAIL , new String[]{UsbongConstants.ORDER_EMAIL_ADDRESS}); // i.putExtra(Intent.EXTRA_SUBJECT, "Purchase Order: "+productDetails.substring(0,productDetails.indexOf("\n")).replace("Title: ","")); i.putExtra(Intent.EXTRA_SUBJECT, "Purchase Order: "+tempList.get(0).substring("<b>".length(),tempList.get(0).indexOf("</b>"))+s); i.putExtra(Intent.EXTRA_TEXT , buySummary.toString()); try { isSendingData=true; //added by Mike, 20170225 startActivityForResult(Intent.createChooser(i, "Sending email..."), 1); } catch (android.content.ActivityNotFoundException ex) { Toast.makeText(CartActivity.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show(); } /* isSendingData=true; //added by Mike, 20170225 Intent intent = new Intent(Intent.ACTION_SENDTO); // it's not ACTION_SEND intent.setType("message/rfc822"); intent.putExtra(Intent.EXTRA_SUBJECT, "Purchase Order: "+tempList.get(0).substring("<b>".length(),tempList.get(0).indexOf("</b>"))+s); intent.putExtra(Intent.EXTRA_TEXT, buySummary.toString()); intent.setData(Uri.parse("mailto:"+UsbongConstants.ORDER_EMAIL_ADDRESS)); // or just "mailto:" for blank intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // this will make such that when user returns to your app, your app is displayed, instead of the email app. startActivity(intent); */ } } /* } */ }); /* //added by Mike, 20160126 backButton = (Button)findViewById(R.id.back_button); backButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //TODO: store product details later setContentView(R.layout.ecommerce_text_image_display_screen); } }); */ } public boolean verifyFields() { boolean allFieldsAreFilledUp=true; TextView surnameTextView = ((TextView)findViewById(R.id.surname)); String surname = surnameTextView.getText().toString(); if (surname.trim().equals("")) { surnameTextView.setBackgroundColor(Color.parseColor("#fff9b6")); allFieldsAreFilledUp=false; } else { surnameTextView.setBackgroundColor(Color.parseColor("#EEEEEE")); } TextView firstnameTextView = ((TextView)findViewById(R.id.first_name)); String firstname = firstnameTextView.getText().toString(); if (firstname.trim().equals("")) { firstnameTextView.setBackgroundColor(Color.parseColor("#fff9b6")); allFieldsAreFilledUp=false; } else { firstnameTextView.setBackgroundColor(Color.parseColor("#EEEEEE")); } TextView contactNumberTextView = ((TextView)findViewById(R.id.contact_number)); String contactNumber = contactNumberTextView.getText().toString(); if (contactNumber.trim().equals("")) { contactNumberTextView.setBackgroundColor(Color.parseColor("#fff9b6")); allFieldsAreFilledUp=false; } else { contactNumberTextView.setBackgroundColor(Color.parseColor("#EEEEEE")); } TextView addressTextView = ((TextView)findViewById(R.id.address)); String address = addressTextView.getText().toString(); if (address.trim().equals("")) { addressTextView.setBackgroundColor(Color.parseColor("#fff9b6")); allFieldsAreFilledUp=false; } else { addressTextView.setBackgroundColor(Color.parseColor("#EEEEEE")); } if (!allFieldsAreFilledUp) { Toast.makeText(CartActivity.this, "Please fill up all required fields.", Toast.LENGTH_LONG).show(); return false; } return true; } public void reset() { UsbongUtils.generateDateTimeStamp(); //create a new timestamp for this "New Entry" } //added by Mike, 29 July 2015 //Reference: http://stackoverflow.com/questions/10407159/how-to-manage-startactivityforresult-on-android; //last accessed: 29 Sept. 2015; answer by Nishant, 2 May 2012; edited by <NAME>, 9 July 2015 @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == 1) { if(resultCode == RESULT_OK){ if (myProgressDialog!=null) { myProgressDialog.dismiss(); } // String result=data.getStringExtra("result"); } if (resultCode == RESULT_CANCELED) { //Write your code if there's no result } //added by Mike, 20170225 if (isSendingData) { isSendingData=false; // returnToProductSelection(); //added by Mike, 20170730 AlertDialog.Builder allowUsToEmptyCartAlertDialog = new AlertDialog.Builder(CartActivity.this).setTitle("Hey!"); TextView tv = new TextView(getInstance()); tv.setText("\nAllow us to empty your cart?"); tv.setGravity(Gravity.CENTER_HORIZONTAL); tv.setTextSize(16); allowUsToEmptyCartAlertDialog.setView(tv); allowUsToEmptyCartAlertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //added by Mike, 20170730 UsbongUtils.cartIconDrawableResourceId = R.drawable.cart_icon; UsbongMainActivity.getInstance().invalidateOptionsMenu(); UsbongUtils.itemsInCart.clear(); returnToProductSelection(); } }) .setNegativeButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }).show(); /* //added by Mike, 20170729 UsbongUtils.cartIconDrawableResourceId = R.drawable.cart_icon; myActivityInstance.invalidateOptionsMenu(); UsbongUtils.itemsInCart.clear(); */ /* //edited by Mike, 20170525 finish(); Intent toCallingActivityIntent = new Intent(getInstance(), UsbongMainActivity.class); toCallingActivityIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(toCallingActivityIntent); */ /* //added by Mike, 20170225 finish(); Intent toUsbongDecisionTreeEngineActivityIntent = new Intent(CartActivity.this, UsbongDecisionTreeEngineActivity.class); toUsbongDecisionTreeEngineActivityIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(toUsbongDecisionTreeEngineActivityIntent); */ } } }//onActivityResult //added by Mike, 20170801 public void returnToProductSelection() { final Activity a; a = UsbongMainActivity.getInstance(); //edited by Mike, 20180427 /*//commented out by Mike, 20180427 if ((getIntent().getExtras().getInt("activity caller")==0) || (getIntent().getExtras().getInt("activity caller")==UsbongConstants.USBONG_MAIN_ACTIVITY)) { a = UsbongMainActivity.getInstance(); } else { a = UsbongDecisionTreeEngineActivity.getInstance(); } */ //edited by Mike, 20170525 finish(); Intent toCallingActivityIntent = new Intent(getInstance(), a.getClass()); toCallingActivityIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(toCallingActivityIntent); } //added by Mike, July 2, 2015 @Override public void onBackPressed() { /* //edited by Mike, 20160417 if ((mTts!=null) && (mTts.isSpeaking())) { mTts.stop(); } //edited by Mike, 20160417 if ((myMediaPlayer!=null) && (myMediaPlayer.isPlaying())) { myMediaPlayer.stop(); } */ //edited by Mike, 20170801 returnToProductSelection(); /* //Reference: http://stackoverflow.com/questions/11495188/how-to-put-application-to-background //; last accessed: 14 April 2015, answer by: JavaCoderEx Intent i = new Intent(Intent.ACTION_MAIN); i.addCategory(Intent.CATEGORY_HOME); startActivity(i); */ } //added by Mike, 25 Sept. 2015 @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.standard_menu, menu); //added by Mike, 20170427 UsbongUtils.cartIcon = menu.findItem(R.id.cart).setIcon(UsbongUtils.cartIconDrawableResourceId); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { /* case(R.id.settings): //Reference: http://stackoverflow.com/questions/16954196/alertdialog-with-checkbox-in-android; //last accessed: 20160408; answer by: kamal; edited by: Empty2K12 final CharSequence[] items = {UsbongConstants.AUTO_NARRATE_STRING, UsbongConstants.AUTO_PLAY_STRING, UsbongConstants.AUTO_LOOP_STRING}; // arraylist to keep the selected items UsbongDecisionTreeEngineActivity.selectedSettingsItems=new ArrayList<Integer>(); //check saved settings if (UsbongUtils.IS_IN_AUTO_NARRATE_MODE) { UsbongDecisionTreeEngineActivity.selectedSettingsItems.add(UsbongConstants.AUTO_NARRATE); } if (UsbongUtils.IS_IN_AUTO_PLAY_MODE) { UsbongDecisionTreeEngineActivity.selectedSettingsItems.add(UsbongConstants.AUTO_PLAY); UsbongDecisionTreeEngineActivity.selectedSettingsItems.add(UsbongConstants.AUTO_NARRATE); //if AUTO_PLAY is checked, AUTO_NARRATE should also be checked } if (UsbongUtils.IS_IN_AUTO_LOOP_MODE) { UsbongDecisionTreeEngineActivity.selectedSettingsItems.add(UsbongConstants.AUTO_LOOP); } UsbongDecisionTreeEngineActivity.selectedSettingsItemsInBoolean = new boolean[items.length]; for(int k=0; k<items.length; k++) { UsbongDecisionTreeEngineActivity.selectedSettingsItemsInBoolean[k] = false; } for(int i=0; i<UsbongDecisionTreeEngineActivity.selectedSettingsItems.size(); i++) { UsbongDecisionTreeEngineActivity.selectedSettingsItemsInBoolean[UsbongDecisionTreeEngineActivity.selectedSettingsItems.get(i)] = true; } inAppSettingsDialog = new AlertDialog.Builder(this) .setTitle("Settings") .setMultiChoiceItems(items, UsbongDecisionTreeEngineActivity.selectedSettingsItemsInBoolean, new DialogInterface.OnMultiChoiceClickListener() { @Override public void onClick(DialogInterface dialog, int indexSelected, boolean isChecked) { Log.d(">>>","onClick"); if (isChecked) { // If the user checked the item, add it to the selected items UsbongDecisionTreeEngineActivity.selectedSettingsItems.add(indexSelected); if ((indexSelected==UsbongConstants.AUTO_PLAY) &&!UsbongDecisionTreeEngineActivity.selectedSettingsItems.contains(UsbongConstants.AUTO_NARRATE)) { final ListView list = inAppSettingsDialog.getListView(); list.setItemChecked(UsbongConstants.AUTO_NARRATE, true); } } else if (UsbongDecisionTreeEngineActivity.selectedSettingsItems.contains(indexSelected)) { if ((indexSelected==UsbongConstants.AUTO_NARRATE) && UsbongDecisionTreeEngineActivity.selectedSettingsItems.contains(UsbongConstants.AUTO_PLAY)) { final ListView list = inAppSettingsDialog.getListView(); list.setItemChecked(indexSelected, false); } else { // Else, if the item is already in the array, remove it UsbongDecisionTreeEngineActivity.selectedSettingsItems.remove(Integer.valueOf(indexSelected)); } } //updated selectedSettingsItemsInBoolean for(int k=0; k<items.length; k++) { UsbongDecisionTreeEngineActivity.selectedSettingsItemsInBoolean[k] = false; } for(int i=0; i<UsbongDecisionTreeEngineActivity.selectedSettingsItems.size(); i++) { UsbongDecisionTreeEngineActivity.selectedSettingsItemsInBoolean[UsbongDecisionTreeEngineActivity.selectedSettingsItems.get(i)] = true; } } }).setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { try { InputStreamReader reader = UsbongUtils.getFileFromSDCardAsReader(UsbongUtils.BASE_FILE_PATH + "usbong.config"); BufferedReader br = new BufferedReader(reader); String currLineString; //write first to a temporary file PrintWriter out = UsbongUtils.getFileFromSDCardAsWriter(UsbongUtils.BASE_FILE_PATH + "usbong.config" +"TEMP"); while((currLineString=br.readLine())!=null) { Log.d(">>>", "currLineString: "+currLineString); if ((currLineString.contains("IS_IN_AUTO_NARRATE_MODE=")) || (currLineString.contains("IS_IN_AUTO_PLAY_MODE=")) || (currLineString.contains("IS_IN_AUTO_LOOP_MODE="))) { continue; } else { out.println(currLineString); } } for (int i=0; i<items.length; i++) { Log.d(">>>>", i+""); if (UsbongDecisionTreeEngineActivity.selectedSettingsItemsInBoolean[i]==true) { if (i==UsbongConstants.AUTO_NARRATE) { out.println("IS_IN_AUTO_NARRATE_MODE=ON"); UsbongUtils.IS_IN_AUTO_NARRATE_MODE=true; } else if (i==UsbongConstants.AUTO_PLAY) { out.println("IS_IN_AUTO_PLAY_MODE=ON"); UsbongUtils.IS_IN_AUTO_PLAY_MODE=true; } else if (i==UsbongConstants.AUTO_LOOP) { out.println("IS_IN_AUTO_LOOP_MODE=ON"); UsbongUtils.IS_IN_AUTO_LOOP_MODE=true; } } else { if (i==UsbongConstants.AUTO_NARRATE) { out.println("IS_IN_AUTO_NARRATE_MODE=OFF"); UsbongUtils.IS_IN_AUTO_NARRATE_MODE=false; } else if (i==UsbongConstants.AUTO_PLAY) { out.println("IS_IN_AUTO_PLAY_MODE=OFF"); UsbongUtils.IS_IN_AUTO_PLAY_MODE=false; } else if (i==UsbongConstants.AUTO_LOOP) { out.println("IS_IN_AUTO_LOOP_MODE=OFF"); UsbongUtils.IS_IN_AUTO_LOOP_MODE=false; } } } out.close(); //remember to close //copy temp file to actual usbong.config file InputStreamReader reader2 = UsbongUtils.getFileFromSDCardAsReader(UsbongUtils.BASE_FILE_PATH + "usbong.config"+"TEMP"); BufferedReader br2 = new BufferedReader(reader2); String currLineString2; //write to actual usbong.config file PrintWriter out2 = UsbongUtils.getFileFromSDCardAsWriter(UsbongUtils.BASE_FILE_PATH + "usbong.config"); while((currLineString2=br2.readLine())!=null) { out2.println(currLineString2); } out2.close(); UsbongUtils.deleteRecursive(new File(UsbongUtils.BASE_FILE_PATH + "usbong.config"+"TEMP")); } catch(Exception e) { e.printStackTrace(); } } }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { // Your code when user clicked on Cancel } }).create(); inAppSettingsDialog.show(); return true; */ case(R.id.cart): //added by Mike, 20170427 if ((UsbongUtils.itemsInCart==null) || (UsbongUtils.itemsInCart.isEmpty())) { AlertDialog.Builder emptyCartAlertDialog = new AlertDialog.Builder(CartActivity.this).setTitle("Your Shopping Cart"); TextView tv = new TextView(this); tv.setText("\nIt is currently empty."); tv.setGravity(Gravity.CENTER_HORIZONTAL); tv.setTextSize(16); emptyCartAlertDialog.setView(tv); emptyCartAlertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }).show(); } else { finish(); //added by Mike, 20170216 Intent toCartActivityIntent = new Intent().setClass(getInstance(), CartActivity.class); // toCartActivityIntent.putExtra("newSellActivity", true); //added by Mike, 20170328 toCartActivityIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(toCartActivityIntent); } return true; /* case(R.id.sell): //added by Mike, 20170308 finish(); //added by Mike, 20170216 Intent toSellActivityIntent = new Intent().setClass(getInstance(), SellActivity.class); toSellActivityIntent.putExtra("newSellActivity", true); //added by Mike, 20170328 toSellActivityIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(toSellActivityIntent); return true; */ //added by Mike, 20180815 case(R.id.submit_report): //edited by Mike, 20180816 if (UsbongUtils.itemsInCart==null) { /* String s = "<br><big>Please add items to the <font color='#74bc1e'><b>SHOPPING CART</b></font> first, before you submit your report online.</big><br>"; TextView alertDialogTextView = new TextView(UsbongMainActivity.instance); alertDialogTextView.setText(Html.fromHtml(s)); */ // alertDialogTextView.setGravity(Gravity.CENTER_HORIZONTAL); String s = "<br>Please add items to the <font color='#74bc1e'><b>SHOPPING CART</b></font> first, before you submit your report online.<br>"; new AlertDialog.Builder(CartActivity.instance).setTitle("Hey there!") // .setMessage("\nPlease confirm CHECKOUT of your SHOPPING CART first, before you submit your report.\n") .setMessage(Html.fromHtml(s)) /* .setView(alertDialogTextView) */ .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }).show(); } else if (!UsbongUtils.itemsInCart.isEmpty()) { String s = "<br>Please confirm <font color='#74bc1e'><b>CHECKOUT</b></font> of the <font color='#74bc1e'><b>SHOPPING CART</b></font> first, before you submit your report online.<br>"; new AlertDialog.Builder(CartActivity.myActivityInstance).setTitle("Hey there!") // .setMessage("\nPlease confirm CHECKOUT of your SHOPPING CART first, before you submit your report.\n") .setMessage(Html.fromHtml(s)) .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }).show(); } else { new AlertDialog.Builder(CartActivity.myActivityInstance).setTitle("Report for the Day") .setMessage("Are you sure you want to submit your report online now?") .setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { UsbongMainActivity.getInstance().getMyDbHelper().submitReportForTheDay(); } }) .setNegativeButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }).show(); } return true; case(R.id.submit_inventory): new AlertDialog.Builder(CartActivity.myActivityInstance).setTitle("Submit Present Inventory") .setMessage("Are you sure you want to submit the inventory online now?") .setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { UsbongMainActivity.getInstance().getMyDbHelper().submitPresentInventory(); } }) .setNegativeButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }).show(); return true; case(R.id.request): finish(); //added by Mike, 20170216 Intent toRequestActivityIntent = new Intent().setClass(getInstance(), RequestActivity.class); toRequestActivityIntent.putExtra("newRequestActivity", true); //added by Mike, 20170330 toRequestActivityIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(toRequestActivityIntent); return true; case(R.id.contact): finish(); //added by Mike, 20170216 Intent toContactActivityIntent = new Intent().setClass(getInstance(), ContactActivity.class); toContactActivityIntent.putExtra("newContactActivity", true); //added by Mike, 20180204 toContactActivityIntent.putExtra("activityCaller", UsbongConstants.USBONG_MAIN_ACTIVITY); //added by Mike, 20180204 toContactActivityIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(toContactActivityIntent); return true; //added by Mike, 20180717 case(R.id.sort_remaining_in_stock): final Activity aSort; aSort = UsbongMainActivity.getInstance(); //edited by Mike, 20180427 TextView tv = new TextView(this); tv.setText("\nWhich list do you want to sort?"); tv.setGravity(Gravity.CENTER_HORIZONTAL); tv.setTextSize(16); new AlertDialog.Builder(CartActivity.myActivityInstance).setTitle("Sort Remaining In-stock") .setView(tv) .setPositiveButton("NON-MED list", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //edited by Mike, 20170525 finish(); Intent toCallingActivityIntent = new Intent(getInstance(), aSort.getClass()); toCallingActivityIntent.putExtra(UsbongConstants.SORT_QUANTITY_IN_STOCK_ASCENDING_NON_MED, true); //added by Mike, 20180716 toCallingActivityIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(toCallingActivityIntent); } }) .setNeutralButton("MED list", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //edited by Mike, 20170525 finish(); Intent toCallingActivityIntent = new Intent(getInstance(), aSort.getClass()); toCallingActivityIntent.putExtra(UsbongConstants.SORT_QUANTITY_IN_STOCK_ASCENDING_MED, true); //added by Mike, 20180716 toCallingActivityIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(toCallingActivityIntent); } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }).show(); return true; case(R.id.about): new AlertDialog.Builder(CartActivity.this).setTitle("About") .setMessage(UsbongUtils.readTextFileInAssetsFolder(CartActivity.this,"credits.txt")) //don't add a '/', otherwise the file would not be found .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }).show(); return true; case(R.id.account): final EditText firstName = new EditText(this); firstName.setHint("First Name"); final EditText surName = new EditText(this); surName.setHint("Surname"); final EditText contactNumber = new EditText(this); contactNumber.setHint("Contact Number"); contactNumber.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL); /* //added by Mike, 20170223 final RadioGroup preference = new RadioGroup(this); preference.setOrientation(RadioGroup.HORIZONTAL); RadioButton meetup = new AppCompatRadioButton(this); meetup.setText("Meet-up"); preference.addView(meetup); RadioButton shipping = new AppCompatRadioButton(this); shipping.setText("Shipping"); preference.addView(shipping); */ final EditText shippingAddress = new EditText(this); shippingAddress.setHint("Shipping Address"); shippingAddress.setMinLines(5); //added by Mike, 20170223 final RadioGroup modeOfPayment = new RadioGroup(this); modeOfPayment.setOrientation(RadioGroup.VERTICAL); /* RadioButton cashUponMeetup = new AppCompatRadioButton(this); cashUponMeetup.setText("Cash upon meet-up"); modeOfPayment.addView(cashUponMeetup); */ RadioButton bankDeposit = new AppCompatRadioButton(this); bankDeposit.setText("Bank Deposit" + " (BDO/BPI)"); modeOfPayment.addView(bankDeposit); /* RadioButton peraPadala = new AppCompatRadioButton(this); peraPadala.setText("Pera Padala"); modeOfPayment.addView(peraPadala); */ RadioButton paypal = new AppCompatRadioButton(this); paypal.setText("PayPal"); modeOfPayment.addView(paypal); RadioButton meetupAtMOSC = new AppCompatRadioButton(this); meetupAtMOSC.setText("Meetup at MOSC"); modeOfPayment.addView(meetupAtMOSC); //Reference: http://stackoverflow.com/questions/23024831/android-shared-preferences-example //; last accessed: 20150609 //answer by Elenasys //added by Mike, 20150207 SharedPreferences prefs = getSharedPreferences(UsbongConstants.MY_ACCOUNT_DETAILS, MODE_PRIVATE); if (prefs!=null) { firstName.setText(prefs.getString("firstName", ""));//"" is the default value. surName.setText(prefs.getString("surname", "")); //"" is the default value. contactNumber.setText(prefs.getString("contactNumber", "")); //"" is the default value. /* //added by Mike, 20170223 ((RadioButton)preference.getChildAt(prefs.getInt("preference", UsbongConstants.defaultPreference))).setChecked(true); */ shippingAddress.setText(prefs.getString("shippingAddress", "")); //"" is the default value. //added by Mike, 20170223 ((RadioButton)modeOfPayment.getChildAt(prefs.getInt("modeOfPayment", UsbongConstants.defaultModeOfPayment))).setChecked(true); } LinearLayout ll=new LinearLayout(this); ll.setOrientation(LinearLayout.VERTICAL); ll.addView(firstName); ll.addView(surName); ll.addView(contactNumber); /* ll.addView(preference);*/ ll.addView(shippingAddress); ll.addView(modeOfPayment); new AlertDialog.Builder(this).setTitle("My Account") .setView(ll) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { //ACTION } }) .setPositiveButton("Save & Exit", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { //ACTION //Reference: http://stackoverflow.com/questions/23024831/android-shared-preferences-example //; last accessed: 20150609 //answer by Elenasys //added by Mike, 20170207 SharedPreferences.Editor editor = getSharedPreferences(UsbongConstants.MY_ACCOUNT_DETAILS, MODE_PRIVATE).edit(); editor.putString("firstName", firstName.getText().toString()); editor.putString("surname", surName.getText().toString()); editor.putString("contactNumber", contactNumber.getText().toString()); /* for (int i=0; i< preference.getChildCount(); i++) { if (((RadioButton)preference.getChildAt(i)).isChecked()) { currPreference=i; } } editor.putInt("preference", currPreference); //added by Mike, 20170223 */ editor.putString("shippingAddress", shippingAddress.getText().toString()); for (int i=0; i< modeOfPayment.getChildCount(); i++) { if (((RadioButton)modeOfPayment.getChildAt(i)).isChecked()) { currModeOfPayment=i; } } editor.putInt("modeOfPayment", currModeOfPayment); //added by Mike, 20170223 editor.commit(); if (currScreen!=SHOPPING_CART_SCREEN) { //added by Mike, 20170222 setContentView(R.layout.account); init(); } } }).show(); return true; case android.R.id.home: //added by Mike, 22 Sept. 2015 /*//commented out by Mike, 201702014; UsbongDecisionTreeEngineActivity is already the main menu processReturnToMainMenuActivity(); */ //added by Mike, 20170216 //return to UsbongDecisionTreeEngineActivity //added by Mike, 20170525 final Activity a; a = UsbongMainActivity.getInstance(); //edited by Mike, 20180427 /*//commented out by Mike, 20180427 if ((getIntent().getExtras().getInt("activity caller")==0) || (getIntent().getExtras().getInt("activity caller")==UsbongConstants.USBONG_MAIN_ACTIVITY)) { a = UsbongMainActivity.getInstance(); } else { a = UsbongDecisionTreeEngineActivity.getInstance(); } */ //edited by Mike, 20170525 finish(); Intent toCallingActivityIntent = new Intent(getInstance(), a.getClass()); toCallingActivityIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(toCallingActivityIntent); return true; default: return super.onOptionsItemSelected(item); } } private class CustomDataAdapter extends ArrayAdapter<String> { private ArrayList<String> items; public CustomDataAdapter(Context context, int textViewResourceId, ArrayList<String> items) { super(context, textViewResourceId, items); this.items = items; } //added by Mike, 20170203 public void sort() { // Collections.sort(items); //Reference: http://stackoverflow.com/questions/8908549/sorting-of-listview-by-name-of-the-product-using-custom-adaptor; //last accessed: 2 Jan. 2014; answer by <NAME> Collections.sort(items, new Comparator<String>() { public int compare(String arg0, String arg1) { return arg0.compareTo(arg1); } }); } @Override public View getView(final int position, View convertView, ViewGroup parent) { //edited by Mike, 20170505 final String o = items.get(position); final View v;// = convertView; //edited by Mike, 20170511 // if (v == null) { //Reference: https://stackoverflow.com/questions/14156996/out-of-memory-on-android-app-on-scrolling-list-with-images; //last accessed: 20170607 //answer by: dev_android if (convertView == null) { LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE); /* if (o.contains("PROMO")||o.contains("RetroCC")||o.toLowerCase().contains("manga")) { //TODO: make this more generic // if (o.toString().substring(0,items.get(position).indexOf("T")).equals(""+UsbongConstants.PRODUCT_TYPE_COMBOS)) { //COMBO v = vi.inflate(R.layout.tree_loader_alternative_cart, null); } else { */ v = vi.inflate(R.layout.tree_loader_cart, null); /* } */ } else { v = convertView; } if (o!= null) { try { TextView dataCurrentTextView = (TextView)v.findViewById(R.id.tree_item); // final String tempS = o.toString(); // String tempS; final String s; final String imageFileName; //Reference: http://www.anddev.org/tinytut_-_get_resources_by_name__getidentifier_-t460.html; last accessed 14 Sept 2011 Resources myRes = instance.getResources(); String tempS = o.toString().replace("\n", "<br>"); s = tempS.subSequence(0, tempS.indexOf("MerchantName: ")).toString(); imageFileName = o.toString().substring(o.indexOf("ImageFileName: ")+"ImageFileName: ".length(), o.indexOf("ProductOverview: ")); /* imageFileName = o.toString().substring(0, o.toString().indexOf("</b>")) .replace("<b>","") .replace("’","") .replace("'","") .replace(":","")+".jpg"; //edited by Mike, 20170202 */ //added by Mike, 20180429 int index = o.indexOf("MerchantName: ")+"MerchantName: ".length(); int endIndex = o.indexOf("ImageFileName: "); //added by Mike, 20170529 final String merchantName = o.substring(index, endIndex); //added by Mike, 20180517 String tempS2 = o.toString(); final int currProductId = Integer.parseInt(tempS2.substring(tempS2.indexOf("ProductId: ")+"ProductId: ".length())); //added by Mike, 20180429 String tempS3 = o.toString(); final String currProductOverview = tempS3.substring(tempS3.indexOf("ProductOverview: ")+"ProductOverview: ".length(), tempS3.indexOf("ProductId: ")).toString(); /* String imageString = o.toString() .replace("\n", "<br>")+"<br><br>"; tempS = "<b>"+imageString.substring(0, imageString.indexOf("<br>"))+"</b>" + //name imageString.substring("<br>", imageString.indexOf("<br>")+ "<font color='#644d17'><b>"+imageString.substring(imageString.indexOf("₱"), ); imageFileName = imageString.substring(0, imageString.indexOf("<br>")) .replace("<b>","") .replace("’","") .replace("'","") .replace(":","")+".jpg"; //edited by Mike, 20170202 */ InputStream myInputStream; String folderName = imageFileName.substring(0, imageFileName.indexOf("/")); List<String> myList = Arrays.asList(myRes.getAssets().list(folderName)); if (myList.contains(imageFileName.replace(folderName +"/",""))) { /* if (Arrays.asList(getResources().getAssets().list("folderName")).contains(imageFileName.replace("/"+folderName,""))) { */ myInputStream = myRes.getAssets().open(imageFileName); } else { myInputStream = UsbongUtils.getFileFromSDCardAsInputStream(UsbongUtils.BASE_IMAGE_FILE_PATH + imageFileName); } //edited by Mike, 20180429 // InputStream is = myRes.getAssets().open(imageFileName); if (myInputStream!=null) { final Drawable myDrawableImage = Drawable.createFromStream(myInputStream, null); //edited by Mike, 20170202 final ImageView image = (ImageView) v.findViewById(R.id.tree_item_image_view); if (myDrawableImage!=null) { image.setImageDrawable(myDrawableImage); image.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { /* //added by Mike, 20170203 setVariableOntoMyUsbongVariableMemory(UsbongConstants.ITEM_VARIABLE_NAME, s); setVariableOntoMyUsbongVariableMemory(UsbongConstants.ITEM_IMAGE_NAME, imageFileName); //added by Mike, 20160203 image.setImageDrawable(myDrawableImage); initParser(UsbongConstants.TREE_TYPE_BUY); //added by Mike, 20160202 */ //added by Mike, 20170216 Intent toBuyActivityIntent = new Intent().setClass(getInstance(), BuyActivity.class); toBuyActivityIntent.putExtra(UsbongConstants.ITEM_VARIABLE_NAME, s); toBuyActivityIntent.putExtra(UsbongConstants.ITEM_IMAGE_NAME, imageFileName); toBuyActivityIntent.putExtra(UsbongConstants.MERCHANT_NAME, merchantName); //added by Mike, 20170529 toBuyActivityIntent.putExtra(UsbongConstants.ITEM_PRODUCT_OVERVIEW, currProductOverview); //added by Mike, 20180429 toBuyActivityIntent.putExtra(UsbongConstants.ITEM_PRODUCT_ID, currProductId); //added by Mike, 20180517 startActivityForResult(toBuyActivityIntent,1); } }); } } dataCurrentTextView.setText(Html.fromHtml(s)); // dataCurrentTextView.setText(o.toString()); dataCurrentTextView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { /* //added by Mike, 20170203 setVariableOntoMyUsbongVariableMemory(UsbongConstants.ITEM_VARIABLE_NAME, s); setVariableOntoMyUsbongVariableMemory(UsbongConstants.ITEM_IMAGE_NAME, imageFileName); //added by Mike, 20160203 image.setImageDrawable(myDrawableImage); initParser(UsbongConstants.TREE_TYPE_BUY); */ /* //commented out by Mike, 20180429 //added by Mike, 20170216 Intent toBuyActivityIntent = new Intent().setClass(getInstance(), BuyActivity.class); toBuyActivityIntent.putExtra(UsbongConstants.ITEM_VARIABLE_NAME, s); toBuyActivityIntent.putExtra(UsbongConstants.ITEM_IMAGE_NAME, imageFileName); toBuyActivityIntent.putExtra(UsbongConstants.MERCHANT_NAME, merchantName); //added by Mike, 20170529 startActivityForResult(toBuyActivityIntent,1); */ //added by Mike, 20170216 Intent toBuyActivityIntent = new Intent().setClass(getInstance(), BuyActivity.class); toBuyActivityIntent.putExtra(UsbongConstants.ITEM_VARIABLE_NAME, s); toBuyActivityIntent.putExtra(UsbongConstants.ITEM_IMAGE_NAME, imageFileName); toBuyActivityIntent.putExtra(UsbongConstants.MERCHANT_NAME, merchantName); //added by Mike, 20170528 toBuyActivityIntent.putExtra(UsbongConstants.ITEM_PRODUCT_OVERVIEW, currProductOverview); //added by Mike, 20180419 toBuyActivityIntent.putExtra(UsbongConstants.ITEM_PRODUCT_ID, currProductId); //added by Mike, 20180730 startActivityForResult(toBuyActivityIntent,1); } }); /* //added by Mike, 20170505 TextView quantity = (TextView) v.findViewById(R.id.quantity); quantity.setText(Html.fromHtml(quantityList.get(position))); */ final Spinner quantitySpinner = (Spinner) v.findViewById(R.id.quantity); //edited by Mike, 20170508 final int quantity = Integer.parseInt(quantityList.get(position)); ArrayList<String> quantityItems = new ArrayList<String>(); for (int i=quantity; i>0; i--) { quantityItems.add(" "+i+" "); } /* quantityItems.add("Remove"); */ //This will put "Remove" in the second position of the list. quantityItems.add(1,"Remove"); //edited by Mike, 20180802 final ArrayAdapter<String> adapter = new ArrayAdapter<String>(instance, android.R.layout.simple_dropdown_item_1line, quantityItems); quantitySpinner.setAdapter(adapter); //added by Mike, 20170509 quantitySpinner.setOnItemSelectedListener(new OnItemSelectedListener() { private int prevQuantityIndex; @Override public void onItemSelected(AdapterView<?> arg0, View arg1, final int arg2, long arg3) { if (quantitySpinner.getItemAtPosition(arg2).toString().equals("Remove")){ new AlertDialog.Builder(CartActivity.this).setTitle("Hey!") .setMessage("Are you sure you want to remove this item from your cart?") .setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { items.remove(position); quantityList.remove(position); updateItemsInCart(items); //added by Mike, 20170509 if (UsbongUtils.itemsInCart.isEmpty()) { UsbongUtils.cartIconDrawableResourceId = R.drawable.cart_icon; myActivityInstance.invalidateOptionsMenu(); } prevQuantityIndex=0; instance.initCart(); } }) .setNegativeButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { quantitySpinner.setSelection(prevQuantityIndex); } }).show(); } else { // if (prevQuantityIndex!=arg2) { prevQuantityIndex=arg2; quantityList.remove(position); String q = quantitySpinner.getSelectedItem().toString().trim(); quantityList.add(position, q); //added by Mike, 20170511 updateItemsInCart(items); processSubtotal(v, Integer.parseInt(q), s); //processOrderTotal(); processPromoAndOrderTotal(); // } } } @Override public void onNothingSelected(AdapterView<?> arg0) { // TODO Auto-generated method stub } }); //added by Mike, 20170511 processSubtotal(v, quantity, s); } catch(Exception e) { e.printStackTrace(); } } return v; } } //added by Mike, 20170511 public void processSubtotal(View v, int quantity, String s) { //added by Mike, 20170508 TextView price = (TextView) v.findViewById(R.id.price); //get item price String sPart1 = s.substring(s.indexOf("₱")); String item_price = sPart1.substring(0,sPart1.indexOf("<"));//("("));//(used), (new) //500<br> price.setText(item_price+"\neach"); //added by Mike, 20170508 TextView subtotal = (TextView) v.findViewById(R.id.subtotal); //edited by Mike, 20180508 // int subtotalNumber = quantity*Integer.parseInt(item_price.replace("₱", "").trim()); Double subtotalNumber = quantity*Double.parseDouble(item_price.replace("₱", "").trim()); //edited by Mike, 20180519 NumberFormat formatter = NumberFormat.getNumberInstance(); formatter.setMinimumFractionDigits(2); formatter.setMaximumFractionDigits(2); String output = formatter.format(subtotalNumber); String subTotalString = "₱" + output;//subtotalNumber; /* if (subTotalString.contains(".")) { if (subTotalString.substring(subTotalString.indexOf(".")).length()-1 < 2) { subTotalString = subTotalString.concat("0"); } } */ subtotal.setText(subTotalString+"\nSubtotal"); } public void updateItemsInCart(ArrayList<String> items) { UsbongUtils.itemsInCart.clear(); for (int i=0; i<items.size(); i++) { int quantitySize = Integer.parseInt(quantityList.get(i)); for (int k=0; k<quantitySize; k++) { UsbongUtils.itemsInCart.add(items.get(i)); } } } } ======================= File: src/com/example/android/apis/graphics/CameraPreview.java ======================= /* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ //@edited: <NAME> //@date created: July 21, 2011 //@last updated: Sept. 21, 2013 //@desc: made public the methods/class //@ref: Android\android-sdk\samples\android-8\ApiDemos\src\com\example\android\apis\graphics\CameraPreview.java package com.example.android.apis.graphics; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import usbong.android.features.node.QRCodeReaderActivity; import usbong.android.pos_app.SellActivity; import usbong.android.utils.UsbongUtils; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Bitmap.CompressFormat; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.hardware.Camera; import android.hardware.Camera.PictureCallback; import android.hardware.Camera.ShutterCallback; import android.util.Log; import android.view.Display; import android.view.MotionEvent; import android.view.Surface; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.view.View.OnTouchListener; import android.view.WindowManager; //import android.hardware.Camera.CameraInfo; //android api 9 public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback, OnTouchListener { private static final String TAG = "UsbongCameraPreview"; private SurfaceHolder mHolder; private Camera mCamera; private CameraPreview mContext = this; public String myPictureName; // public String timeStamp; private static Context myContext; private Display myDisplay; private boolean isPreviewRunning=false; public CameraPreview(Context context, String myPictureName) { super(context); myContext = context; this.myPictureName = myPictureName; // Install a SurfaceHolder.Callback so we get notified when the // underlying surface is created and destroyed. mHolder = getHolder(); mHolder.addCallback(this); mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); /* new AlertDialog.Builder(CameraPreview.this.getContext()).setTitle("Usbong Tip") .setMessage("Tap the screen to take a picture!") .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }).show(); */ this.setOnTouchListener(this); } @Override public void surfaceCreated(SurfaceHolder holder) { // The Surface has been created, acquire the camera and tell it where // to draw. mCamera = Camera.open(); try { mCamera.setPreviewDisplay(holder); } catch (IOException exception) { mCamera.release(); mCamera = null; // TODO: add more exception handling logic here } } @Override public void surfaceDestroyed(SurfaceHolder holder) { // Surface will be destroyed when we return, so stop the preview. // Because the CameraDevice object is not a shared resource, it's very // important to release it when the activity is paused. mCamera.stopPreview(); mCamera.release(); mCamera = null; } /* private Size getOptimalPreviewSize(List<Size> sizes, int w, int h) { final double ASPECT_TOLERANCE = 0.05; double targetRatio = (double) w / h; if (sizes == null) return null; Size optimalSize = null; double minDiff = Double.MAX_VALUE; int targetHeight = h; // Try to find an size match aspect ratio and size for (Size size : sizes) { double ratio = (double) size.width / size.height; if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue; if (Math.abs(size.height - targetHeight) < minDiff) { optimalSize = size; minDiff = Math.abs(size.height - targetHeight); } } // Cannot find the one match the aspect ratio, ignore the requirement if (optimalSize == null) { minDiff = Double.MAX_VALUE; for (Size size : sizes) { if (Math.abs(size.height - targetHeight) < minDiff) { optimalSize = size; minDiff = Math.abs(size.height - targetHeight); } } } return optimalSize; } */ //Android SDK; last accessed: 3 Oct 2011 public static void setCameraDisplayOrientation(Activity activity, int cameraId, android.hardware.Camera camera) { /*//found in Android SDK 9 android.hardware.Camera.CameraInfo info = new android.hardware.Camera.CameraInfo(); android.hardware.Camera.getCameraInfo(cameraId, info); */ int rotation = activity.getWindowManager().getDefaultDisplay() .getRotation(); int degrees = 0; switch (rotation) { case Surface.ROTATION_0: degrees = 0; break; case Surface.ROTATION_90: degrees = 90; break; case Surface.ROTATION_180: degrees = 180; break; case Surface.ROTATION_270: degrees = 270; break; } int result; result = (0 + degrees) % 360; // result = (360 - result) % 360; // compensate the mirror /* if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) { result = (info.orientation + degrees) % 360; result = (360 - result) % 360; // compensate the mirror } else { // back-facing result = (info.orientation - degrees + 360) % 360; } */ camera.setDisplayOrientation(result); } @Override public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { if (isPreviewRunning) { mCamera.stopPreview(); } // Now that the size is known, set up the camera parameters and begin // the preview. Camera.Parameters parameters = mCamera.getParameters(); /* List<Size> sizes = parameters.getSupportedPreviewSizes(); Size optimalSize = getOptimalPreviewSize(sizes, w, h); */ // parameters.setPreviewSize(optimalSize.width, optimalSize.height); //added by Mike, Aug. 20, 2011 //http://stackoverflow.com/questions/3841122/android-camera-preview-is-sideways/5110406#5110406; last accessed: Aug. 20, 2011 myDisplay = ((WindowManager)myContext.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); System.out.println(">>>>>>myDisplay.getRotation(): "+myDisplay.getRotation()); /* if(myDisplay.getRotation() == Surface.ROTATION_0) //0 { parameters.setPreviewSize(optimalSize.height, optimalSize.width); mCamera.setDisplayOrientation(90); } if(myDisplay.getRotation() == Surface.ROTATION_90) //1 { parameters.setPreviewSize(optimalSize.width, optimalSize.height); mCamera.setDisplayOrientation(-90); } if(myDisplay.getRotation() == Surface.ROTATION_180) //2 { parameters.setPreviewSize(optimalSize.height, optimalSize.width); } if(myDisplay.getRotation() == Surface.ROTATION_270) //3 { parameters.setPreviewSize(optimalSize.width, optimalSize.height); mCamera.setDisplayOrientation(180); } */ mCamera.setParameters(parameters); try { mCamera.setPreviewDisplay(holder); mCamera.startPreview(); isPreviewRunning=true; } catch(Exception e) { Log.d(TAG, "Cannot start preview", e); } mCamera.startPreview(); } //added by Mike, July 22, 2011 @Override public boolean onTouch(View arg0, MotionEvent me) { switch(me.getAction()) { case MotionEvent.ACTION_DOWN: mCamera.takePicture(shutterCallback, rawCallback, jpegCallback); return true; } return false; } //Reference: http://p2p.wrox.com/book-professional-android-application-development-isbn-978-0-470-34471-2/72528-article-using-android-camera.html //Last accessed on: July 12, 2010 ShutterCallback shutterCallback = new ShutterCallback() { @Override public void onShutter() { // TODO Do something when the shutter closes. } }; PictureCallback rawCallback = new PictureCallback() { @Override public void onPictureTaken(byte[] _data, Camera _camera) { if (_data!= null) { //Intent mIntent = new Intent(); StoreByteImage(mContext, _data, 50, "ImageName"); mCamera.startPreview(); //setResult(FOTO_MODE, mIntent); //finish(); } } }; PictureCallback jpegCallback = new PictureCallback() { @Override public void onPictureTaken(final byte[] _data, Camera _camera) { if (_data!= null) { //Intent mIntent = new Intent(); AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); builder.setCancelable(true); builder.setMessage("Do you want to save this image?"); //builder.setIcon(R.drawable.dialog_question); builder.setTitle("Image Saving"); builder.setInverseBackgroundForced(true); builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); StoreByteImage(mContext, _data, 50, "ImageName"); //removed by Mike, Sept. 21, 2013 // UsbongDecisionTreeEngineActivity.setCurrScreen(UsbongDecisionTreeEngineActivity.PHOTO_CAPTURE_SCREEN); ((Activity) getContext()).finish(); } }); builder.setNegativeButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); mCamera.startPreview(); } }); AlertDialog alert = builder.create(); alert.show(); //setResult(FOTO_MODE, mIntent); //finish(); } System.out.println("DITO SA onPictureTaken(...)!"); } }; public boolean StoreByteImage(CameraPreview mContext2, byte[] imageData, int quality, String expName) { // File sdImageMainDirectory = new File("/sdcard/usbong" + "/" +UsbongUtils.getDateTimeStamp() +"/"); /* File sdImageMainDirectory = new File(UsbongUtils.BASE_FILE_PATH + "/" +UsbongUtils.getDateTimeStamp() +"/"); */ File sdImageMainDirectory = new File(UsbongUtils.BASE_FILE_PATH_TEMP); // stackoverflow.com/questions/2130932/how-to-create-directory-automatically-on-sd-card if (!sdImageMainDirectory.exists() &&!sdImageMainDirectory.mkdirs()) { System.out.println("Path to file could not be created."); } FileOutputStream fileOutputStream = null; // String nameFile; try { BitmapFactory.Options options=new BitmapFactory.Options(); options.inSampleSize = 5; Bitmap myImage = BitmapFactory.decodeByteArray(imageData, 0, imageData.length,options); File outputFile= new File(sdImageMainDirectory, myPictureName +".jpg" ); fileOutputStream = new FileOutputStream(outputFile); BufferedOutputStream bos = new BufferedOutputStream( fileOutputStream); //added by Mike, 20160119 Matrix matrix = new Matrix(); matrix.postRotate(90); Bitmap myBitmapRotated = Bitmap.createBitmap(myImage, 0, 0, myImage.getWidth(), myImage.getHeight(), matrix, true); myBitmapRotated.compress(CompressFormat.JPEG, quality, bos); /* //commented out by Mike, 20160119 myImage.compress(CompressFormat.JPEG, quality, bos); */ bos.flush(); bos.close(); // File imageFile = new File("/sdcard/usbong/" +UsbongUtils.getDateTimeStamp() +"/" + myPictureName+".jpg"); /* File imageFile = new File(UsbongUtils.BASE_FILE_PATH +UsbongUtils.getDateTimeStamp() +"/" + myPictureName+".jpg"); */ File imageFile = new File(UsbongUtils.BASE_FILE_PATH_TEMP + myPictureName+".jpg"); if(imageFile.exists()) { System.out.println("FILE EXISTS!"); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return true; } } ======================= File: README.md ======================= <filename>README.md # Usbong POS App The "Usbong POS (Point-of-Sale) App" is built based on the Usbong app, the Usbong Specialty Bookstore app, and the Usbong Store app.<br><br> # Usbong POS App (Demo version) http://pos.usbong.ph # Official Usbong Store App http://app.usbong.ph # Official Company Website http://www.usbong.ph # Open Source Software License Copyright 2018 Usbong Social Systems, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ======================= File: assets/usbong_store.sql ======================= BEGIN; CREATE TABLE merchant ( merchant_id INTEGER PRIMARY KEY, merchant_name TEXT, merchant_motto TEXT, merchant_motto_font_color TEXT ); INSERT INTO merchant (merchant_id, merchant_name, merchant_motto, merchant_motto_font_color) VALUES (1, 'Usbong Specialty Bookstore', 'Uplifting Human Lives', '#6f5630'), (2, 'RetroCC', 'Keep Reading.<br>Keep Collecting.', '#FFFFFF'), (3, 'Adarna House, Inc', 'Una sa Filipino', '#4f4c41'), (4, 'Usbong Mart', 'Uplifting Human Lives', '#6f5630'), (5, 'Marikina Orthopedic Specialty Clinic', 'Marikina Orthopedic Specialty Clinic', '#4f4c41'), (6, 'Pinoydrones', 'We don''t just sell drones, We sell an experience.', '#FFFFFF'); CREATE TABLE product ( product_id INTEGER PRIMARY KEY, merchant_id INTEGER, product_type_id INTEGER, name TEXT, price REAL, previous_price REAL, language TEXT, author TEXT, supplier TEXT, description TEXT, image_location TEXT, format TEXT, quantity_in_stock INTEGER, translator TEXT, product_overview TEXT, pages INTEGER, product_view_num INTEGER, quantity_sold INTEGER, external_url TEXT, show INTEGER, publisher TEXT, released_date TEXT, is_essential_reading INTEGER, expiration TEXT ); INSERT INTO product (product_id, merchant_id, product_type_id, name, price, previous_price, language, author, supplier, description, image_location, format, quantity_in_stock, translator, product_overview, pages, product_view_num, quantity_sold, external_url, show, publisher, released_date, is_essential_reading, expiration) VALUES (487, 5, 13, 'Back Support (Small)', 1700.00, NULL, NULL, NULL, NULL, 'New', NULL, NULL, 1, NULL, 'Back Support (Small)<br><br><strong>Also available:</strong><br><a href=''''https://store.usbong.ph/w/Back-Support-Medium-/488''''>Back Support (Medium)</a><br><a href=''''https://store.usbong.ph/w/Back-Support-Large-/489''''>Back Support (Large)</a><br><a href=''''https://store.usbong.ph/w/Back-Support-Xtra-Large-/490''''>Back Support (Xtra-Large)</a><br>', NULL, 21, 0, NULL, 1, '', '', 0, NULL), (488, 5, 13, 'Back Support (Medium)', 1700.00, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 1, NULL, 'Back Support (Medium)<br><br><strong>Also available:</strong><br><a href=''''https://store.usbong.ph/w/Back-Support-Small-/487''''>Back Support (Small)</a><br><a href=''''https://store.usbong.ph/w/Back-Support-Large-/489''''>Back Support (Large)</a><br><a href=''''https://store.usbong.ph/w/Back-Support-Xtra-Large-/490''''>Back Support (Xtra-Large)</a><br>', NULL, 15, 0, NULL, 1, '', '', 0, NULL), (489, 5, 13, 'Back Support (Large)', 1700.00, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 1, NULL, 'Back Support (Large)<br><br><strong>Also available:</strong><br><a href=''''https://store.usbong.ph/w/Back-Support-Small-/487''''>Back Support (Small)</a><br><a href=''''https://store.usbong.ph/w/Back-Support-Medium-/488''''>Back Support (Medium)</a><br><a href=''''https://store.usbong.ph/w/Back-Support-Xtra-Large-/490''''>Back Support (Xtra-Large)</a><br>', NULL, 11, 0, NULL, 1, '', '', 0, NULL), (490, 5, 13, 'Back Support (Xtra-Large)', 1700.00, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 1, NULL, 'Back Support (Xtra-Large)<br><br><strong>Also available:</strong><br><a href=''''https://store.usbong.ph/w/Back-Support-Small-/487''''>Back Support (Small)</a><br><a href=''''https://store.usbong.ph/w/Back-Support-Medium-/488''''>Back Support (Medium)</a><br><a href=''''https://store.usbong.ph/w/Back-Support-Large-/489''''>Back Support (Large)</a><br>', NULL, 11, 0, NULL, 1, '', '', 0, NULL), (491, 5, 14, 'Lagaflex (carisoprodol/paracetamol 300/250)', 23.00, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 1, NULL, 'ANALGESIC/MUSCLE RELAXANT', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2020-09-00T00:00:00+08:00'), (492, 5, 14, 'Paradrinforte (Para + orphanadrinecitrate)', 19.00, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 1, NULL, 'ANALGESIC/MUSCLE RELAXANT', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2019-10-00T00:00:00+08:00'), (493, 5, 14, 'Proparforte 650/35 (Para + orphanadrinecitrate)', 19.00, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 800, NULL, 'ANTI-ALLERGIES', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2019-10-00T00:00:00+08:00'), (494, 5, 14, 'Loraox (Loratadine 10m)', 7.00, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 144, NULL, 'ANTI-ALLERGIES', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2019-05-00T00:00:00+08:00'), (495, 5, 14, 'Gabaron 300mg (Gabapentin)', 25.00, NULL, 'English', NULL, NULL, '', NULL, NULL, 600, NULL, 'ANTI-CONVULSANT', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2019-11-00T00:00:00+08:00'), (496, 5, 14, 'Gabix 100mg (Gabapentin)', 23.90, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 76, NULL, 'ANTI-CONVULSANT', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2020-07-00T00:00:00+08:00'), (497, 5, 14, 'Gabix 300mg (Gabapentin)', 30.00, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 57, NULL, 'ANTI-CONVULSANT', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2019-11-00T00:00:00+08:00'), (498, 5, 14, 'Adiac 500mg (Metformin 500mg)', 1.70, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 168, NULL, 'ANTI-DIABETIC', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2019-06-00T00:00:00+08:00'), (499, 5, 14, 'Zebet 80 (Gliclazide 80mg)', 5.80, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 164, NULL, 'ANTI-DIABETIC', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2019-04-00T00:00:00+08:00'), (500, 5, 14, 'Allopurinol 100mg', 1.60, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 560, NULL, 'ANTI-GOUT', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2019-07-00T00:00:00+08:00'), (501, 5, 14, 'Colchicine 500mg', 3.00, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 700, NULL, 'ANTI-GOUT', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2019-10-00T00:00:00+08:00'), (502, 5, 14, 'Rhea (colchicine) 500mg', 5.00, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 100, NULL, 'ANTI-GOUT', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2020-03-00T00:00:00+08:00'), (503, 5, 14, 'Lodipex 5mg (Amlodipine)', 2.75, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 238, NULL, 'ANTI-HYPERTENSIVE', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2019-03-00T00:00:00+08:00'), (504, 5, 14, 'Diadipine 10mg (Amlodipine)', 3.25, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 130, NULL, 'ANTI-HYPERTENSIVE', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2019-06-00T00:00:00+08:00'); INSERT INTO product (product_id, merchant_id, product_type_id, name, price, previous_price, language, author, supplier, description, image_location, format, quantity_in_stock, translator, product_overview, pages, product_view_num, quantity_sold, external_url, show, publisher, released_date, is_essential_reading, expiration) VALUES (505, 5, 14, 'Zenobloc 50mg (Atenolol)', 4.50, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 113, NULL, 'ANTI-HYPERTENSIVE', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2018-11-00T00:00:00+08:00'), (506, 5, 14, 'Zenobloc 100mg (Atenolol)', 6.00, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 190, NULL, 'ANTI-HYPERTENSIVE', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2018-06-00T00:00:00+08:00'), (507, 5, 14, 'Amgel 50mg (Losartan)', 11.20, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 132, NULL, 'ANTI-HYPERTENSIVE', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2019-04-00T00:00:00+08:00'), (508, 5, 14, 'Losac 100mg (Losartan)', 19.25, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 93, NULL, 'ANTI-HYPERTENSIVE', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2019-08-00T00:00:00+08:00'), (509, 5, 14, 'Prolol 50mg (Metoprolol)', 2.60, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 269, NULL, 'ANTI-HYPERTENSIVE', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2018-06-00T00:00:00+08:00'), (510, 5, 14, 'Prolol 100mg (Metoprolol)', 4.20, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 200, NULL, 'ANTI-HYPERTENSIVE', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2019-01-00T00:00:00+08:00'), (511, 5, 14, 'Arcoxia 120mg (Etoricoxib)', 80.00, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 80, NULL, 'ANTI-INFLAMMATORY/ANALGESIC', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2020-01-00T00:00:00+08:00'), (512, 5, 14, 'Xibra 60mg (Etoricoxib)', 35.00, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 57, NULL, 'ANTI-INFLAMMATORY/ANALGESIC', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2020-06-00T00:00:00+08:00'), (513, 5, 14, 'Dologesic 325/37.5 (Para + Tramadol HCI)', 1.50, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 330, NULL, 'ANTI-INFLAMMATORY/ANALGESIC', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2019-01-00T00:00:00+08:00'), (514, 5, 14, 'Cetradol 325/37.5 (Para + Tramadol HCI)', 10.00, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 600, NULL, 'ANTI-INFLAMMATORY/ANALGESIC', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2019-05-00T00:00:00+08:00'), (515, 5, 14, 'Trap 325/37.5 (Para + Tramadol HCI)', 16.00, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 83, NULL, 'ANTI-INFLAMMATORY/ANALGESIC', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2018-09-00T00:00:00+08:00'), (516, 5, 14, 'Tramadol 50mg', 5.00, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 316, NULL, 'ANTI-INFLAMMATORY/ANALGESIC', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2020-09-00T00:00:00+08:00'), (517, 5, 14, 'Clanza 100mg (Aceclofenac)', 15.20, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 709, NULL, 'ANTI-INFLAMMATORY/ANALGESIC', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2020-11-00T00:00:00+08:00'), (518, 5, 14, 'Diclotol 100mg (Aceclofenac)', 11.00, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 48, NULL, 'ANTI-INFLAMMATORY/ANALGESIC', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2019-12-00T00:00:00+08:00'), (519, 5, 14, 'Dolowin SR 200mg (Aceclofenac)', 20.00, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 407, NULL, 'ANTI-INFLAMMATORY/ANALGESIC', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2019-04-00T00:00:00+08:00'), (520, 5, 14, 'Dolowin Plus 100mg (Aceclofenac + Para)', 16.00, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 781, NULL, 'ANTI-INFLAMMATORY/ANALGESIC', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2020-04-00T00:00:00+08:00'), (521, 5, 14, 'Ibuprofen 200mg', 1.20, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 180, NULL, 'ANTI-INFLAMMATORY/ANALGESIC', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2020-03-00T00:00:00+08:00'), (522, 5, 14, 'Ibuprofen 400mg', 1.60, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 200, NULL, 'ANTI-INFLAMMATORY/ANALGESIC', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2019-02-00T00:00:00+08:00'), (523, 5, 14, 'Ketesse 25mg (Dexcetoprofen)', 28.00, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 160, NULL, 'ANTI-INFLAMMATORY/ANALGESIC', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2019-06-00T00:00:00+08:00'), (524, 5, 14, 'Mefenamic 250mg', 1.50, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 137, NULL, 'ANTI-INFLAMMATORY/ANALGESIC', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2020-08-00T00:00:00+08:00'), (525, 5, 14, 'Mefenamic 500mg', 2.00, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 437, NULL, 'ANTI-INFLAMMATORY/ANALGESIC', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2020-09-00T00:00:00+08:00'), (526, 5, 14, 'Meloxican 15mg', 12.00, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 1040, NULL, 'ANTI-INFLAMMATORY/ANALGESIC', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2019-11-00T00:00:00+08:00'), (527, 5, 14, 'Naproxen 500mg', 7.00, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 150, NULL, 'ANTI-INFLAMMATORY/ANALGESIC', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2020-01-00T00:00:00+08:00'), (528, 5, 14, 'Subsyde CR 100mg (Diclofenac Na)', 10.00, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 2939, NULL, 'ANTI-INFLAMMATORY/ANALGESIC', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2019-01-00T00:00:00+08:00'), (529, 5, 14, 'Zornica - 4 (Lornoxican)', 16.50, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 155, NULL, 'ANTI-INFLAMMATORY/ANALGESIC', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2018-12-00T00:00:00+08:00'), (530, 5, 14, 'Amoxicillin 500mg', 4.00, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 166, NULL, 'ANTI-INFECTIVES/BACTERIA', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2020-10-00T00:00:00+08:00'), (531, 5, 14, 'Cefalaxin 500mg', 7.00, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 181, NULL, 'ANTI-INFECTIVES/BACTERIA', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2020-08-00T00:00:00+08:00'), (532, 5, 14, 'Cefixin 200mg', 25.00, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 100, NULL, 'ANTI-INFECTIVES/BACTERIA', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2020-03-00T00:00:00+08:00'), (533, 5, 14, 'Cefuroxine 500mg', 46.00, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 48, NULL, 'ANTI-INFECTIVES/BACTERIA', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2019-04-00T00:00:00+08:00'), (534, 5, 14, 'Ciprofloxacin 500mg', 7.00, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 150, NULL, 'ANTI-INFECTIVES/BACTERIA', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2020-03-00T00:00:00+08:00'), (535, 5, 14, 'Clindamycin 300mg', 8.00, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 155, NULL, 'ANTI-INFECTIVES/BACTERIA', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2019-12-00T00:00:00+08:00'), (536, 5, 14, 'Cloxacillin 500mg', 5.00, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 137, NULL, 'ANTI-INFECTIVES/BACTERIA', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2018-07-00T00:00:00+08:00'), (537, 5, 14, 'Co Amoxiclav 625mg', 25.00, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 164, NULL, 'ANTI-INFECTIVES/BACTERIA', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2019-10-00T00:00:00+08:00'), (538, 5, 14, 'Doxycycline Hyclate 100mg', 2.00, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 23, NULL, 'ANTI-INFECTIVES/BACTERIA', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2018-07-00T00:00:00+08:00'), (539, 5, 14, 'Ofloxacin 200mg', 10.00, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 120, NULL, 'ANTI-INFECTIVES/BACTERIA', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2019-10-00T00:00:00+08:00'), (540, 5, 14, 'Ofloxacin 400mg', 13.00, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 73, NULL, 'ANTI-INFECTIVES/BACTERIA', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2019-01-00T00:00:00+08:00'), (541, 5, 14, 'Aldren 70mg (Alendronete Sodium)', 145.00, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 92, NULL, 'ANTI-OSTEOPOROSIS', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2019-04-00T00:00:00+08:00'), (542, 5, 14, 'Alendra 70mg (Alendronete Sodium)', 280.00, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 78, NULL, 'ANTI-OSTEOPOROSIS', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2019-05-00T00:00:00+08:00'), (543, 5, 14, 'Reventa 70mg (Alendronete Sodium)', 158.00, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 44, NULL, 'ANTI-OSTEOPOROSIS', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2019-04-00T00:00:00+08:00'), (544, 5, 14, 'Prednisone 5mg', 1.30, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 400, NULL, 'CORTICOSTEROID', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2018-09-00T00:00:00+08:00'), (545, 5, 14, 'Omeprazele 20mg', 7.00, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 72, NULL, 'HYPERACIDITY (PANGANGASIM NG SIKMURA)', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2020-02-00T00:00:00+08:00'), (546, 5, 14, 'Omeprazele 40mg', 10.00, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 119, NULL, 'HYPERACIDITY (PANGANGASIM NG SIKMURA)', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2020-04-00T00:00:00+08:00'), (547, 5, 14, 'Agmaset 44mg', 25.00, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 160, NULL, 'SUPPLEMENT FOR JOINT & BONE', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2020-01-00T00:00:00+08:00'), (548, 5, 14, 'Alanerve', 65.00, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 165, NULL, 'SUPPLEMENT FOR JOINT & BONE', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2018-06-00T00:00:00+08:00'), (549, 5, 14, 'Artiflex', 16.00, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 780, NULL, 'SUPPLEMENT FOR JOINT & BONE', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2019-05-00T00:00:00+08:00'), (550, 5, 14, 'Calcium Plus 800/6 (KIRKLAND)', 6.00, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 1, NULL, 'SUPPLEMENT FOR JOINT & BONE', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2020-08-00T00:00:00+08:00'), (551, 5, 14, 'CALCIUMADE', 9.00, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 2800, NULL, 'SUPPLEMENT FOR JOINT & BONE', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2019-08-00T00:00:00+08:00'), (552, 5, 14, 'Glucosamine Sulfate 500mg (Exact)', 12.00, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 1, NULL, 'SUPPLEMENT FOR JOINT & BONE', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2019-12-00T00:00:00+08:00'), (553, 5, 14, 'Glucosamine Sulfate 750mg (KIRKLAND)', 10.00, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 1, NULL, 'SUPPLEMENT FOR JOINT & BONE', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2021-03-00T00:00:00+08:00'), (554, 5, 14, 'Piascledine', 38.00, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 945, NULL, 'SUPPLEMENT FOR JOINT & BONE', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2020-01-00T00:00:00+08:00'), (555, 5, 14, 'Viartril-S 500mg', 20.00, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 2467, NULL, 'SUPPLEMENT FOR JOINT & BONE', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2018-12-00T00:00:00+08:00'), (556, 5, 14, '<NAME>', 60.00, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 242, NULL, 'SUPPLEMENT FOR JOINT & BONE', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2019-11-00T00:00:00+08:00'), (557, 5, 14, 'Sovit-Cee 500mg (Sodium Ascorbate)', 5.00, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 226, NULL, 'VITAMINS', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2019-01-00T00:00:00+08:00'), (558, 5, 14, '<NAME> 30g', 430.00, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 1, NULL, 'ANTI-INFLAMMATORY GEL/CREAM', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2022-05-00T00:00:00+08:00'), (559, 5, 14, '<NAME> 20g (Diclofenac)', 250.00, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 15, NULL, 'ANTI-INFLAMMATORY GEL/CREAM', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2019-11-00T00:00:00+08:00'), (560, 5, 14, '<NAME> 40g', 280.00, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 44, NULL, 'ANTI-INFLAMMATORY GEL/CREAM', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2022-03-00T00:00:00+08:00'), (561, 5, 14, 'Vigel Cream 15g', 150.00, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 240, NULL, 'ANTI-INFLAMMATORY GEL/CREAM', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2020-07-00T00:00:00+08:00'), (562, 5, 14, 'Dehydrosol Powd.', 15.00, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 25, NULL, 'ANTI-INFLAMMATORY GEL/CREAM', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2021-04-00T00:00:00+08:00'), (563, 5, 14, 'Synvisc 3 inj.', 25000.00, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 9, NULL, 'ANTI-INFLAMMATORY GEL/CREAM', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2019-11-00T00:00:00+08:00'), (564, 5, 14, 'Angioflux 250mg', 32.00, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 1, NULL, 'ANTI-INFLAMMATORY/ANALGESIC', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2020-10-00T00:00:00+08:00'), (565, 5, 14, 'Zerodol - P 100/500mg', 20.00, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 1, NULL, 'ANTI-INFLAMMATORY/ANALGESIC', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2019-08-00T00:00:00+08:00'), (566, 5, 14, 'Dycon SR 100mg (Diclofenac Na)', 13.00, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 1, NULL, 'ANTI-INFLAMMATORY/ANALGESIC', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2018-09-00T00:00:00+08:00'), (567, 5, 14, '<NAME>', 15.00, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 1, NULL, 'SUPPLEMENT FOR JOINT & BONE', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2019-12-00T00:00:00+08:00'), (568, 5, 14, '<NAME>', 22.00, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 1, NULL, 'SUPPLEMENT FOR JOINT & BONE', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2019-05-00T00:00:00+08:00'), (569, 5, 14, 'Diclofenac 50mg', 5.00, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 1, NULL, 'ANTI-INFLAMMATORY/ANALGESIC', NULL, 0, 0, NULL, 1, NULL, NULL, 0, '2021-01-00T00:00:00+08:00'); CREATE TABLE product_type ( product_type_id INTEGER PRIMARY KEY, product_type_name TEXT ); INSERT INTO product_type (product_type_id, product_type_name) VALUES (1, 'All'), (2, 'Books'), (3, 'Beverages'), (4, 'Books/Beverages'), (5, 'Promos'), (6, 'Comics'), (7, 'Manga'), (8, 'Toys & Collectibles'), (9, 'Textbooks'), (10, 'Children''s'), (11, 'Food'), (12, 'Miscellaneous'), (13, 'NON-MED'), (14, 'MED'); CREATE TABLE cart ( cart_id INTEGER PRIMARY KEY, product_id INTEGER, quantity INTEGER, price REAL, purchased_datetime_stamp TEXT ); COMMIT; ======================= File: db/usbong_store20180427.sql ======================= BEGIN; CREATE TABLE fields ( fields_id INTEGER PRIMARY KEY, fields_name TEXT, product_type_id INTEGER ); INSERT INTO fields (fields_id, fields_name, product_type_id) VALUES (1, 'name', 1), (2, 'price', 1), (3,'supplier', 1), (4, 'description', 1), (5, 'image_location', 1), (6, 'author', 2), (7, 'language', 2); CREATE TABLE merchant ( merchant_id INTEGER PRIMARY KEY, merchant_name TEXT, merchant_motto TEXT, merchant_motto_font_color TEXT ); INSERT INTO merchant (merchant_id, merchant_name, merchant_motto, merchant_motto_font_color) VALUES (1, 'Usbong Specialty Bookstore', 'Uplifting Human Lives', '#6f5630'), (2, 'RetroCC', 'Keep Reading.<br>Keep Collecting.', '#FFFFFF'), (3, 'Adarna House, Inc', 'Una sa Filipino', '#4f4c41'), (4, 'Usbong Mart', 'Uplifting Human Lives', '#6f5630'), (5, 'Marikina Orthopedic Specialty Clinic', 'Marikina Orthopedic Specialty Clinic', '#4f4c41'), (6, 'Pinoydrones', 'We don''t just sell drones, We sell an experience.', '#FFFFFF'); CREATE TABLE product ( product_id INTEGER PRIMARY KEY, merchant_id INTEGER, product_type_id INTEGER, name TEXT, price INTEGER, previous_price INTEGER, language TEXT, author TEXT, supplier TEXT, description TEXT, image_location TEXT, format TEXT, quantity_in_stock INTEGER, translator TEXT, product_overview TEXT, pages INTEGER, product_view_num INTEGER, quantity_sold INTEGER, external_url TEXT, show INTEGER, publisher TEXT, released_date TEXT, is_essential_reading INTEGER ); INSERT INTO product (product_id, merchant_id, product_type_id, name, price, previous_price, language, author, supplier, description, image_location, format, quantity_in_stock, translator, product_overview, pages, product_view_num, quantity_sold, external_url, show, publisher, released_date, is_essential_reading) VALUES (1, 1, 2, 'The Remains of the Day', 400, NULL, 'English', '<NAME>', NULL, 'Used - Acceptable', NULL, 'Hardcover', 1, '', 'The novelist, <NAME>, has said, ''''A novel may not give us facts that are true, [but] what it tells us about experience, the emotion that it conveys, is something that we recognize as true. And sometimes, very important emotions, feelings are conveyed in a novel that cannot be conveyed in more factual stories, or in factual books. I think most importantly, perhaps, a key to it, I think, a novel can tell us how it feels to be in a certain situation. A work of history or journalism can tell us that some people starved in a particular time and place. But, perhaps, it cannot convey the pain of starving, or losing someone close to you or your child to starvation... We need someone to tell us how it felt... Is it true that it feels like that to be in that situation, or is this not true? I think we still have to ask that question. But I think that''s why we turn to stories, because we feel there''s something missing in just the factual account.''''', NULL, 42, 0, NULL, 1, NULL, NULL, 0), (2, 1, 2, 'The Daydreamer', 400, NULL, 'English', '<NAME>', NULL, 'Used - Acceptable', NULL, 'Paperback', 1, '', 'While we know ''''Google'''' as the search engine giant, Peter, the protagonist in this book, discovered ''''Googol'''', which is pronounced somewhat similarly, while thinking about the largest number in the world. A ''''Googol'''' is ten multiplied by ten a hundred times. Moreover, ''''Googolplex'''' is ten multiplied by ten a googol number of times! But what I really remember about this book is the story about how Peter became friends with the school bully by realizing that he and his classmates only dreamed him up to be strong and powerful, because in reality, he is a nice, ordinary little boy just like any of them.', NULL, 24, 0, NULL, 1, NULL, NULL, 0), (3, 1, 2, 'Myths to Live By', 400, NULL, 'English', '<NAME>', NULL, 'Used - Acceptable', NULL, 'Paperback', 1, '', 'Here is a quotation from the book, which you are free to agree or disagree. ''''All societies are evil, sorrowful, inequitable; and so they will always be. So if you really want to help this world, what you will have to teach is how to live in it. And that no one can do who has not himself learned how to live in it in the joyful sorrow and sorrowful joy of the knowledge of life as it is.''''', NULL, 26, 0, NULL, 1, NULL, NULL, 0), (4, 1, 2, 'The Seasons of a Man''s Life', 500, NULL, 'English', '<NAME> al.', NULL, 'Used - Acceptable', NULL, 'Paperback', 1, '', 'This book provides a more or less general picture of the so-called ''''seasons'''' of a man''s life. It shows examples of various men who set out to realize their dream or ideal life, only to discover later in life that they must confront and eventually accept the reality that they may not be able to actually fulfill that initial dream. One example that I can remember is the academic who wanted to receive recognition for his work by receiving the Nobel prize, but to his great disappointment was beaten to it by a rival group. He later found solace in providing mentorship to the younger generation of scientists in his field.', NULL, 35, 0, NULL, 1, NULL, NULL, 0), (5, 1, 2, 'The Last Lecture', 400, NULL, 'English', '<NAME> et al.', NULL, 'Used - Acceptable', NULL, 'Paperback', 1, '', 'While the ''''Last Lecture'''' doesn''t necessarily mean that it''s a professor''s last lecture, and is simply a way for senior professors at Carnegie Mellon University to share wisdom to younger students and faculty, for <NAME>, it really was somewhat of a last lecture, because he was already grappling with pancreatic cancer and his chance of survival was low. This book offers his insights about living.', NULL, 23, 0, NULL, 1, NULL, NULL, 0), (6, 1, 2, 'The Innovators', 600, NULL, 'English', '<NAME>', NULL, 'Used - Very Good', NULL, 'Paperback', 1, '', 'This book chronicles the many people who contributed to the development of an important tool that is the computer and the many innovations that went with it. It was interesting for me to discover glimpses of inventors as humans, working together to build things that would amplify even further their capabilities and shape the world forever. ', NULL, 38, 0, NULL, 1, NULL, NULL, 0), (7, 1, 2, '<NAME>', 500, NULL, 'English', '<NAME>', NULL, 'Used - Acceptable', NULL, 'Paperback', 1, '', 'This book offers glimpses of <NAME>'' life as a human person, warts and all. I particularly liked discovering that despite the wealth that he was able to accumulate in his life, he decided that he didn''t want to change his simple, yet efficient lifestyle, only for the sake of being able to live the rich life that is glamorized by media. <br><br> p.s. I like the iPAD + pencil combo.', NULL, 26, 0, NULL, 1, NULL, NULL, 0), (8, 1, 9, 'Tokyo University''s English', 1000, NULL, 'Japanese/English', '<NAME>', NULL, 'Used - Acceptable', NULL, 'Paperback', 0, '', 'While this book is intended for Japanese students who''ll be taking the Tokyo University entrance exam, it can be used by Japanese language learners as well. The sample readings are in English, while the translation and explanations are in Japanese. The articles are also quite interesting. I particularly remember the one about how our hopes and fears are ''''often illusions promising to change our way of life, but leaving us exactly as we were before.''''', NULL, 48, 0, NULL, 1, NULL, NULL, 0), (9, 1, 2, 'Siddhartha', 300, NULL, 'English', '<NAME>', NULL, 'Used - Very Good', NULL, 'Paperback', 1, '', 'This story relates the transitions a person undertook to achieve the state of everlasting peace. He first lived the life of a scholar, and then became an ascetic, and then a merchant, and then a boatman. I found it particularly interesting to learn how an ascetic could become a merchant. As it turns out, having the ability to read and write, as well as the patience to wait and fast, instead of having to seek any kind of work due to being driven by hunger, proved useful to this transition. Another key idea that I got from the book is that there are things that cannot be taught in words, but must truly be experienced for another person to understand.', NULL, 44, 0, NULL, 1, NULL, NULL, 1), (10, 1, 2, 'The Montessori Method', 400, NULL, 'English', '<NAME>', NULL, 'Used - Acceptable', NULL, 'Paperback', 1, '', 'The first dawn of real discipline comes through action. When a child has learned to respond naturally through action that is aimed towards an objective, that is, action that is no longer erratic, he is no more the child that he was at first, but an individual. When, further, he has freed himself from being dependent on others due to his own inferiority, he has overcome himself and the limits of his age, and has made a great step forward by conquering his future while in the present.', NULL, 39, 0, NULL, 1, NULL, NULL, 1), (11, 1, 2, 'The Soul of a New Machine', 400, NULL, 'English', '<NAME>', NULL, 'Used - Acceptable', NULL, 'Hardcover', 1, '', 'What is the soul of a new machine? It is the collective soul etched in silicon and microcode of a team of dedicated engineers who brought the machine to life. In the end, ''''It''s just a computer. It''s really a small thing in the world, you know.''''', NULL, 37, 0, NULL, 1, NULL, NULL, 0), (12, 1, 2, 'Outliers: The Story of Success', 400, NULL, 'English', '<NAME>', NULL, 'Used - Acceptable', NULL, 'Hardcover', 1, '', 'There are two things that make rice farming meaningful. First, there is a clear relationship between effort and reward, in that the harder you work a rice field, the more it yields. Second, its complexity is akin to running a small business that is composed of a family workforce, who must hedge uncertainty through seed selection, building and managing a sophisticated irrigation system, and at the same time coordinating the complicated process of crop harvesting and crop preparation.', NULL, 28, 0, NULL, 1, NULL, NULL, 0), (13, 1, 2, '<NAME>', 500, NULL, 'English', '<NAME>', NULL, 'Used - Acceptable', NULL, 'Paperback', 1, NULL, '<p>Where do innovations actually come from? As it turns out, much technology is not invented solely locally and is not done by a lone individual. Instead, it is borrowed from other societies and from other inventors who''ve gone before. The spread of useful invention depends on whether a society that learns about it is receptive to it and adopts it. Societies lacking the invention often find themselves at a disadvantage in relation to the receptive society, even becoming overwhelmed and replaced if the disadvantage is sufficiently great.</p><p>技术革新是从哪里来的? 原来,许多技术不是国内独立发明的,也不是一个人做的。反而,是从别的社会与上一代的发明家借的。推广有用的发明在于观察社会是否接受,採用它。缺发明的社会常对接受社会不利,而若太差,被压倒也替换。</p>', NULL, 34, 0, NULL, 1, '', '', 1), (14, 1, 2, 'The Tao of Pooh', 300, NULL, 'English', '<NAME>', NULL, 'Used - Acceptable', NULL, 'Paperback', 1, '', 'To Laozi, the universe was not a setter of traps, but a teacher of valuable lessons. While it would be arrogant to attempt to adequately put how the universe operates into words, its nature could be understood. And the natural result of being able to appreciate, learn from, and work with whatever happens in everyday life is happiness.', NULL, 35, 0, NULL, 1, NULL, NULL, 1), (15, 1, 2, 'The Different Drum', 400, NULL, 'English', '<NAME>, M.D.', NULL, 'Used - Acceptable', NULL, 'Paperback', 1, '', 'The reality of human nature is that we are all profoundly different. This is due to our capacity to be molded by culture and experience in extremely variable ways. At the same time, it is this same capacity that opens the way for all of us to *transformation*, which paradoxically, is both the basic cause of war and the basic cure for war.', NULL, 49, 0, NULL, 1, NULL, NULL, 1), (16, 1, 2, 'The Lives of a Cell', 300, NULL, 'English', '<NAME>', NULL, 'Used - Acceptable', NULL, 'Paperback', 1, '', 'The sky is a miraculous achievement. It is, after all, far and away the grandest product of collaboration in all of nature. Earth would not be alive as we know it without such cooperation. Moreover, the shelter it provides prevents millions of meteorites from pounding us like the powdered surface of the moon. While we may not be sensitive enough to hear it, we find solace in knowing that the sound is there above, ''like the random noise of rain on the roof at night.''', NULL, 35, 0, NULL, 1, NULL, NULL, 1), (17, 1, 2, 'The Plague', 400, NULL, 'English', '<NAME>', NULL, 'Used - Acceptable', NULL, 'Paperback', 1, '', 'The town of Oran is hit by a devastating plague. Everyone is locked in the town. Nobody comes in, nobody goes out. Gripped by this circumstance, the people are challenged to confront their strongly held beliefs. Meanwhile, a group of tenacious men and women work together to fight the plague, hoping that they''ll eventually figure out a cure to put an end to it. Eventually, indeed, the plague is brought to a stop. But how? Could it be divine intervention? It''s not what you think.', NULL, 37, 0, NULL, 1, NULL, NULL, 1), (18, 1, 2, 'Living Language: French', 500, NULL, 'English', '<NAME>', NULL, 'Used - Acceptable', NULL, 'Paperback', 1, '', 'While the book may be dated, e.g. the currency is not in euros, I found the sequence of chapters relevant to one who is learning French. The chapters start with a dialogue, then an explanation of certain grammar points, then some exercises, and finally a cultural note, which all provide a much better glimpse of French culture. Using tools like Google Translate to help you with the pronunciation, you should be able to gradually learn to speak, read, and understand French as you go through this book.', NULL, 40, 0, NULL, 1, NULL, NULL, 0), (19, 1, 2, 'Starting Point, 1979-1996', 850, NULL, 'English', 'Hayao Miyazaki', NULL, 'New', NULL, 'Paperback', 1, '<NAME>/<NAME>', 'I first got a copy of this book (Japanese version) while studying in Japan as an exchange student. I wanted to eventually be able to read it in the original. About 10 years later, I was indeed able to read the chapter on ''''Animation and Manga Movies''''. It was a pleasant surprise that my Japanese language ability had improved to the extent that I could already read such texts. I then translated the chapter for my class on Japanese Films. Having said this, it is still fun even now to just randomly flip a page and read insights from MiyazakiSAN.', NULL, 33, 1, NULL, 1, NULL, NULL, 0), (20, 1, 2, 'Turning Point, 1997-2008', 1400, NULL, 'English', 'Hayao Miyazaki', NULL, 'New', NULL, 'Hardcover', 1, '<NAME>/<NAME>', 'I first got a copy of the first book, ''''Starting Point, 1979-1996 (Japanese version)'''', while studying in Japan as an exchange student. I wanted to eventually be able to read it in the original. About 10 years later, I was indeed able to read the chapter on ''''Animation and Manga Movies''''. It was a pleasant surprise that my Japanese language ability had improved to the extent that I could already read such texts. I then translated the chapter for my class on Japanese Films. Not long after, I got a copy of this book in the original Japanese. It is indeed fun to just randomly flip a page and read insights from MiyazakiSAN.', NULL, 30, 0, NULL, 1, NULL, NULL, 0), (21, 1, 2, 'Made in Japan', 400, NULL, 'English', 'Akio Morita et al.', NULL, 'Used - Acceptable', NULL, 'Paperback', 1, '<NAME>/<NAME>', 'Here''s my English translation of an excerpt taken from an interview with Akio Morita on NHK''s 「あの人に会いたい」(I want to meet that person).<br> 「私は日本製品を売ろうとしていたが、 ドイツ人の目にはこの傘が日本製品を象徴していると」''''I was trying to sell Japanese products, but in the eyes of Germans, Japanese products were small umbrellas that are put on top of ice creams!''''<br> 「この傘がメイドインジャパンだったわけです」 ''''This umbrella represented products made in Japan.''''<br> 「それ以来、私はメイドインジャパンのイメージを変えなければと一生懸命やってきた」 ''''After that, I did my very best to change the ''Made in Japan'' image.''''', NULL, 32, 0, NULL, 1, NULL, NULL, 1), (22, 1, 2, 'Wikinomics', 400, NULL, 'English', '<NAME>/<NAME>', NULL, 'Used - Acceptable', NULL, 'Hardcover', 1, NULL, 'This book provides an optimistic view on how technology, particularly the internet, is enabling people to massively collaborate. While we know that technology is a double-edged sword, that is, it can be used for good or ill depending on its wielder, one is left with a positive and optimistic feeling that things are getting better instead of worse after reading this book. ', NULL, 36, 0, NULL, 1, NULL, NULL, 0), (23, 1, 2, 'The Dancing Wu Li Masters', 400, NULL, 'English', '<NAME>', NULL, 'Used - Acceptable', NULL, 'Paperback', 1, NULL, 'This book is a must-read for anyone who wants to understand Physics, that is, not the Physics that students commonly learn in school, where there are equations that one must solve in a sort of computer-like way, without really understanding deeply what kind of thinking and perspective brought about those equations in the first place. One question that this book asks is, what is a living thing? If we break down a human person into very, very tiny, little pieces, we''ll find that a rock is made up of those very tiny, little pieces as well. And yet, we do not call a rock a living thing. Why is that? Eventually, if you continue asking such questions, you''ll arrive with the answer that we don''t know. And the book concludes with an invitation to an opening towards eastern culture. ', NULL, 31, 0, NULL, 1, NULL, NULL, 1), (24, 1, 10, '<NAME>', 320, 400, 'French', 'Antoine de Saint-Exupéry', NULL, 'Used - Acceptable', NULL, 'Paperback', 1, NULL, 'This book''s often quoted phrase, «On ne voit bien qu''avec le cœur. L''essentiel est invisible pour les yeux. (We can only see well with our hearts. What is essential is invisible to the eye.)» reminds us that a person can be vain, difficult, and demanding, but it is the quality time that we spent for that person that makes him or her special and unique from all the other persons in the world.', NULL, 165, 0, NULL, 1, NULL, NULL, 1), (25, 1, 2, 'Founders at Work', 500, NULL, 'English', '<NAME>', NULL, 'Used - Acceptable', NULL, 'Hardcover', 1, NULL, 'Reading this book gives a person an idea of what founders of startups had to undergo to be able to achieve what they''ve achieved. It contains interviews upon interviews of founders of companies that even now we still recognize and whose services we still use. I hope that this book gives you a better appreciation and respect for company founders, and inspires you to become one someday.', NULL, 44, 0, NULL, 1, NULL, NULL, 1), (26, 1, 2, 'Standard First Aid & Personal Safety', 500, NULL, 'English', 'American Red Cross', NULL, 'Used - Acceptable', NULL, 'Paperback', 0, NULL, 'While there are copies of First Aid guides, which a person can download free-of-charge online, this printed copy shows ways of how an ordinary person, without having to prescribe any medicine, can provide first aid when needed. Examples include applying various bandages, positioning a person in certain ways, and so on. What is most important, however, is achieving a calm and tranquil state of mind to act and do what must be done even during times of accidents or disaster. Hopefully, this book helps you attain such a state of presence.', NULL, 30, 0, NULL, 1, NULL, NULL, 1), (27, 1, 9, 'HSK Level 5 Sample Exam', 1500, NULL, 'Mandarin/Japanese', 'Confucius Institute (Hanban)', NULL, 'Used - Acceptable', NULL, 'Paperback', 0, '株式会社スプリックス', 'This book is a good learning tool not only for those who''ll be taking the HSK Level 5 exam, but also those who simply enjoy reading interesting texts or articles from a variety of fields. The texts are in Mandarin (Simplified), while the translation and explanations are in Japanese. One story that I remember from this book is the one about the business man, his son, and their donkey. The lesson it shared was that it is difficult to please everybody. And if you mistakenly think that you can satisfy everyone, you''ll realize that you won''t be happy and the people you wanted to satisfy won''t be satisfied either. ', NULL, 31, 0, NULL, 1, NULL, NULL, 0), (28, 4, 3, 'M&S Earl Grey Tea', 295, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 1, NULL, '<NAME> has this to say about tea. It is from the chapter on ''''Tea'''' from the book, <b><a href=\\''https://store.usbong.ph/w/The-Salmon-of-Doubt-Douglas-Adams/69\\''>The Salmon of Doubt</a></b>. ''''Drink it. After a few moments you will begin to think that the place you''ve come to isn''t maybe quite so strange and crazy after all.''''', NULL, 65, 0, NULL, 1, NULL, NULL, 0), (29, 4, 3, 'UCC Coffee (Rich Blend)', 580, NULL, 'Japanese', NULL, NULL, NULL, NULL, NULL, 0, NULL, 'The Finns or the Finnish people are said to be heavy coffee drinkers. Perhaps it''s due to the seemingly predominantly stark climate they''re in. Yet other than the Finnish sauna, what better way to celebrate life than the smell of freshly brewed coffee for 2 at home?', NULL, 69, 0, NULL, 1, NULL, NULL, 0), (30, 4, 3,'sencha (Green Tea)', 225, NULL, 'Japanese', NULL, NULL, NULL, NULL, NULL, 1, NULL, 'While at present, Filipinos in general favor coffee over tea, I hope that someday we would all appreciate the simple and calming effects of drinking Japanese green tea. While other teas may contain plenty of caffeine, or would easily cause molds to form if not consumed quickly, green tea offers few, if at all, caffeine, such that one can drink it even before going to sleep, and can store it in room temperature without molds forming. If you find that you''ve made too much green tea, you can put it inside the refrigerator and drink it later as cold tea, without the disadvantage of too much added sugar found in commercialized iced teas.', NULL, 70, 0, NULL, 1, NULL, NULL, 0), (31, 1, 5, 'PROMO-Le Petit Prince, Living Language French, The Plague', 1080, NULL, 'French/English', 'Saint-Exupéry, <NAME>', NULL, 'Used - Acceptable', NULL, 'Paperback', 1, NULL, NULL, NULL, 190, 0, NULL, 1, NULL, NULL, 0), (32, 1, 5, 'PROMO-Wikinomics, Guns, Germs, and Steel, The Soul of a New Machine, The Different Drum', 1490, NULL, 'English', 'Tapscott/Williams, <NAME>', NULL, 'Used - Acceptable', NULL, 'Mixed', 1, NULL, NULL, NULL, 27, 0, NULL, 1, NULL, NULL, 0), (33, 1, 5, 'PROMO-Made in Japan, The Soul of a New Machine, Founders at Work, Outliers', 1490, NULL, 'English', 'Morita et al., <NAME>', NULL, 'Used - Acceptable', NULL, 'Mixed', 1, NULL, NULL, NULL, 75, 0, NULL, 1, NULL, NULL, 0), (34, 1, 5, 'PROMO-Starting Point, Turning Point', 2180, NULL, 'English', '<NAME>', NULL, 'New', NULL, 'Mixed', 1, '<NAME> and <NAME>', NULL, NULL, 36, 1, NULL, 1, NULL, NULL, 0), (35, 1, 5, 'PROMO-<NAME>, The Innovators', 1025, NULL, 'English', '<NAME>', NULL, 'Used - Very Good', NULL, 'Paperback', 1, NULL, NULL, NULL, 39, 1, NULL, 1, NULL, NULL, 0), (36, 2, 6, 'ACTION COMICS 1-52 (complete set)', 8000, NULL, 'English', NULL, NULL, 'new, 1-52 + extras, VF-NM', NULL, 'Paperback', 1, NULL, NULL, NULL, 57, 0, NULL, 1, NULL, NULL, 0), (37, 2, 6, 'Silver Surfer vol 1 (complete set)', 32000, NULL, 'English', NULL, NULL, 'VG-F', NULL, 'Paperback', 1, NULL, '<br> 1-18 (Complete)', NULL, 37, 0, NULL, 1, NULL, NULL, 0), (38, 2, 6, 'Batman Superman set', 3000, NULL, 'English', NULL, NULL, 'VF-NM', NULL, 'Paperback', 1, NULL, '<br>1-31, annual 1-2, future''s end 1, missing issue 32', 0, 54, 0, NULL, 1, NULL, NULL, 0), (39, 2, 6, 'ULTIMATE FALLOUT set', 1800, NULL, 'English', NULL, NULL, 'VF-NM', NULL, 'Paperback', 1, NULL, 'Ultimate Fallout 1-6<br> Issue 4 1st appearance Miles Morales<br> Death of Spider-man 2nd print', NULL, 42, 0, NULL, 1, NULL, NULL, 0), (40, 2, 6, 'KLAUS boom studios', 1200, NULL, 'English', NULL, NULL, 'complete set 1-7, VF-NM', NULL, NULL, 1, NULL, NULL, NULL, 26, 0, NULL, 1, NULL, NULL, 0), (41, 2, 6, 'Empire of the Dead', 1500, NULL, 'English', NULL, NULL, 'VF', NULL, 'Paperback', 1, NULL, '<br> Complete 1st arc, 1-5', NULL, 30, 0, NULL, 1, NULL, NULL, 0), (42, 2, 6, 'Fairest (complete set)', 3500, 4000, 'English', NULL, NULL, 'VF', NULL, 'Paperback', 1, NULL, NULL, NULL, 36, 0, NULL, 1, NULL, NULL, 0), (43, 2, 6, 'Batman and Robin New 52 set', 6000, NULL, 'English', NULL, NULL, 'VF-NM', NULL, 'Paperback', 1, NULL, '<br>Complete set of Batman and Robin new 52', NULL, 55, 0, NULL, 1, NULL, NULL, 0), (44, 1, 7, 'One Piece Manga set (1-20)', 2405, 3700, 'Japanese', NULL, NULL, 'Used - Acceptable', NULL, 'Paperback', 1, NULL, 'I started collecting manga (and retro video games) when I first went to Japan on my own as an exchange student. However, it was only about 10 years later that I actually sat down and read the manga''s (and played the video games; not just tested them to see if they worked). I had set out to learn Japanese language and culture, because I was very much into Japanese pop culture. But during that time when I was learning, I hardly had time left to enjoy the things which got me learning in the first place. While what urged me to go back and enjoy the manga and the video games is another story for another time, One Piece is one of the manga''s that I returned to reading after that more or less 10 year period of serious learning.', NULL, 53, 0, NULL, 1, NULL, NULL, 0), (45, 1, 7, 'Conan Manga set (1-9)', 1082, 1665, 'Japanese', NULL, NULL, 'Used - Acceptable', NULL, 'Paperback', 1, NULL, NULL, NULL, 71, 0, NULL, 1, NULL, NULL, 0), (46, 1, 7, 'Rurouni Kenshin Manga set (1-27 complete)', 3510, 5400, 'Japanese', NULL, NULL, 'Used - Good', NULL, 'Paperback', 1, NULL, 'If you''re like most Filipinos, you''ve probably seen the anime first, before having read the manga. Of course, if you''re part of the younger generation, you may have likely seen the films first before either the anime or the manga. In any case, I found the anime more toned down than the manga in terms of the harsh reality of life. Having said this, this manga set should still offer good reading material, especially for nihongo learners. As to my favorite character in the series, that''s another story for another time.', NULL, 48, 0, NULL, 1, NULL, NULL, 0), (47, 2, 8, 'DAREDEVIL', 800, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL, 42, 0, NULL, 1, NULL, NULL, 0), (48, 2, 8, 'Spider-man Marvel Toybiz 90s', 700, NULL, 'English', NULL, NULL, 'New', NULL, NULL, 1, NULL, 'MOC', NULL, 41, 0, NULL, 1, NULL, NULL, 0), (49, 2, 8, 'Marvel Legends Wave 1 X-MEN BAF Juggernaut', 10000, NULL, 'English', NULL, NULL, 'VF-NM', NULL, NULL, 0, NULL, NULL, NULL, 34, 0, NULL, 1, NULL, NULL, 0), (50, 1, 9,'shimbun de manabu nihongo (with CDs)', 1900, 2700, 'Japanese', 'Mizutani Osamu et al.', NULL, 'New', NULL, 'Paperback', 2, NULL, NULL, NULL, 41, 0, NULL, 1, NULL, NULL, 0), (51, 1, 9, 'kanzen masta- 2kyuu', 910, 1296, 'Japanese', '3A Corporation', NULL, 'New', NULL, 'Paperback', 2, NULL, NULL, NULL, 33, 0, NULL, 1, NULL, NULL, 0), (52, 1, 9, 'kanzen masta- 1kyuu', 910, 1296, 'Japanese', '3A Corporation', NULL, 'New', NULL, 'Paperback', 2, NULL, NULL, NULL, 36, 0, NULL, 1, NULL, NULL, 0), (53, 1, 9, 'kanji look and learn', 950, 1350, 'Japanese', 'Eri Banno et al. (The Japan Times)', NULL, 'New', NULL, 'Paperback', 1, NULL, 'This book contains 512 Kanji characters with drawings or illustrations, mnemonic hints, the correct stroke order, as well as their various readings, to help the student master this incredible invention that should cover up to N2 of the Japanese Language Proficiency Test (JLPT).', NULL, 39, 0, NULL, 1, NULL, NULL, 0), (54, 1, 9, 'genki II 2nd ed (with CD)', 2650, 3780, 'Japanese', 'Eri Banno et al. (The Japan Times)', NULL, 'New', NULL, 'Paperback', 2, NULL, 'This is one of the textbooks my classmates and I used back when I was an exchange student in Japan. I was so determined to learn the Japanese language that even before arriving in Japan, I had already taken several classes. <br><br>Actually, I started learning nihongo on my own when I was in 4th year high school. After I graduated, I took language classes in Ortigas. There I met my first Filipino teacher in nihongo. He advised me to apply in the exchange programs offered in universities. This is what he did as a student at De La Salle University (DLSU). <br><br>I continued taking classes in Ortigas every Saturday during my time in college, while making sure that I arrive on time for ROTC (Reserve Officers'' Training Course). At the time, we didn''t have any alternative to ROTC, unlike university students these days. When I finally took my first foreign language class in college, I already had some background. <br><br>Eventually, I was fortunate enough to be accepted as a student in Japan for 2 semesters in my junior year. When I took the placement test, I earned enough points to land on a Japanese Language and Culture class that used this textbook. <br><br>I never used the <b><a href=''https://store.usbong.ph/w/genki-I-2nd-ed-with-CD-Eri-Banno-et-al.-The-Japan-Times/55''>first Genki textbook</a></b>, until several years later, when I became a teacher. To tell you the truth, I didn''t know I''d become a teacher. I didn''t really set out to be one. But I guess I''m getting ahead of myself, because that''s another story for another time.', NULL, 40, 0, NULL, 1, NULL, NULL, 0), (55, 1, 9, 'genki I 2nd ed (with CD)', 2650, 3780, 'Japanese', 'Eri Banno et al. (The Japan Times)', NULL, 'New', NULL, 'Paperback', 2, NULL, NULL, NULL, 33, 0, NULL, 1, NULL, NULL, 0), (56, 1, 9, 'erin (with DVD) vol 3', 1820, 2592, 'Japanese', 'The Japan Foundation', NULL, 'New', NULL, 'Paperback', 2, NULL, 'This is volume 3 of the erin series. It contains manga, cultural notes, basic and advanced skits (translated from Japanese to English, Portuguese, Korean, and Simplified Mandarin) as well as their videos in DVD, as they share the story of erin, an international student, studying in a high school in Japan and living with a Japanese host family.', NULL, 32, 0, NULL, 1, NULL, NULL, 0), (57, 1, 9, 'erin (with DVD) vol 2', 1820, 2592, 'Japanese', 'The Japan Foundation', NULL, 'New', NULL, 'Paperback', 2, NULL, 'This is volume 2 of the erin series. It contains manga, cultural notes, basic and advanced skits (translated from Japanese to English, Portuguese, Korean, and Simplified Mandarin) as well as their videos in DVD, as they share the story of erin, an international student, studying in a high school in Japan and living with a Japanese host family.', NULL, 43, 0, NULL, 1, NULL, NULL, 0), (58, 1, 9, 'erin (with DVD) vol 1', 1820, 2592, 'Japanese', 'The Japan Foundation', NULL, 'New', NULL, 'Paperback', 2, NULL, 'This is volume 1 of the erin series. It contains manga, cultural notes, basic and advanced skits (translated from Japanese to English, Portuguese, Korean, and Simplified Mandarin) as well as their videos in DVD, as they share the story of erin, an international student, studying in a high school in Japan and living with a Japanese host family.', NULL, 43, 0, NULL, 1, NULL, NULL, 0), (59, 1, 2, 'kenshuui junjou monogatari', 350, NULL, 'Japanese', 'Keiichi Kawafuchi', NULL, 'New', NULL, 'Paperback', 1, NULL, '''''Honest Tales of a Medical Resident: Don''t Call Me Doctor!'''', by <NAME>, relates the author''s own experiences as a resident in a university hospital. The road that he took to become a medical doctor wasn''t straight-forward. He first worked in various and odd jobs, even turning into a hikikomori (someone who withdraws from society), before deciding at 30 to become a medical doctor. He eventually graduated at 37 years old from Kyoto University''s Medical School, and is now a freelance internist and writer. Although reviews may be mixed (one side likes the book, the other side doesn''t), I found the author''s experiences and musings quite honest and frank.', NULL, 38, 0, NULL, 1, NULL, NULL, 0), (60, 1, 2, '<NAME>', 700, NULL, 'English', '<NAME>', NULL, 'Used - Acceptable', NULL, 'Paperback', 2, NULL, 'This book shows through historical examples of real persons who''ve stumbled upon the paradoxes of logic, and have emerged with masterpieces that defy reason. I highly recommend this book to people who are stuck in the realm of thinking, and have yet to appreciate the beauty of what is beyond logic.', NULL, 45, 1, NULL, 1, NULL, NULL, 1), (61, 1, 2, 'The Intelligent Investor', 550, NULL, 'English', '<NAME>', NULL, 'Used - Acceptable', NULL, 'Hardcover', 2, NULL, 'One key idea from the book is this: Unlike many people, who think that money in investment is made out of buying and selling of stocks, real money is actually made, as it has been done since the past, out of owning and holding securities. From these, one receives interest and dividends as well as increases in value.', NULL, 28, 0, NULL, 1, NULL, NULL, 1), (63, 1, 2, 'The Hero with a Thousand Faces', 600, NULL, 'English', '<NAME>', NULL, 'Used - Acceptable', NULL, 'Paperback', 1, NULL, 'Have you ever wondered why we tell each other stories? <br><br> According to the author, there is a pattern in the stories humankind has told time and time again since the ancient past. <br><br> Stories about love where out of the many who have tried and failed, emerges a hero who would be able to defeat the hideous ogre, which may symbolize the dear damsel''s parents, and triumphantly save the princess and be able to live together in everlasting bliss. But if so many have failed, how does the hero in fact do this incredible and seemingly insurmountable task?', NULL, 37, 0, NULL, 1, NULL, NULL, 1), (64, 1, 2, 'The Seasons of a Woman''s Life', 500, NULL, 'English', '<NAME> al.', NULL, 'Used - Acceptable', NULL, 'Paperback', 1, NULL, 'From the team that brought out the book, ''''The Seasons of a Man''s Life'''', comes another notable work that provides a more or less general picture of the so-called ''''seasons'''' of a woman''s life as she lives her 20s, 30s, and 40s. An impression that I got from this book is the difficult reality of simply living one''s life, especially for women. It is indeed full of disappointments and heartaches, yet can be turned into triumphs where one emerges much stronger and less naive about the world and a woman''s place in it.', NULL, 29, 0, NULL, 1, NULL, NULL, 0), (65, 1, 2, 'A New Earth', 500, NULL, 'English', '<NAME>', NULL, 'Used - Acceptable', NULL, 'Paperback', 1, NULL, 'The author''s message doesn''t necessarily deviate from the one that is brought forth in eastern philosophy. And if from this book you are able to have a better appreciation of life and our world, with all the pain and imperfections that come along with it, then I believe that we''ve gained one more peaceful person, and our world is so much better for it.', NULL, 65, 0, NULL, 1, NULL, NULL, 0), (66, 1, 2, 'The Richest Man in Babylon', 300, NULL, 'English', '<NAME>', NULL, 'Used - Acceptable', NULL, 'Paperback', 1, NULL, 'This book offers guidance to becoming wealthy. The lessons are brought out using stories revolving in the great ancient city of Babylon. I often find myself rereading and rereading this book to make sure that I am able to internalize what I''ve learned. One key lesson from the book is the setting aside of no less than 10% of one''s income. Even with only 10pesos saved everyday for 30 days you could already accumulate 300pesos! Afterwards, it is important to make your money work and earn more for you by investing it in honorable and trustworthy people who can keep safe the principal, yet provide you with adequate returns for years and years to come.<br><br>''''Babylon became the wealthiest city of the ancient world because its citizens were the richest people of their time.''''', NULL, 38, 1, NULL, 1, NULL, NULL, 1), (67, 1, 7, 'Full Metal Alchemist Manga set (1-27 complete)', 3705, 5700, 'Japanese', 'Hiromu Arakawa', NULL, 'Used - Very Good', NULL, 'Paperback', 1, NULL, NULL, NULL, 57, 0, NULL, 1, NULL, NULL, 0), (68, 1, 7, 'Ranma Manga set (1-38 complete)', 4550, 7000, 'Japanese', '<NAME>', NULL, 'Used - Very Good', NULL, 'Paperback', 1, NULL, NULL, NULL, 37, 0, NULL, 1, NULL, NULL, 0), (69, 1, 2, 'The Salmon of Doubt', 400, NULL, 'English', '<NAME>', NULL, 'Used - Acceptable', NULL, 'Paperback', 1, NULL, 'The author wrote a chapter on ''''Tea''''. This is what he has to say: ''''Drink it. After a few moments you will begin to think that the place you''ve come to isn''t maybe quite so strange and crazy after all.''''', NULL, 32, 0, NULL, 1, NULL, NULL, 0), (70, 1, 2, 'Banker to the Poor', 400, NULL, 'English', '<NAME>', NULL, 'Used - Acceptable', NULL, 'Paperback', 1, NULL, 'In one of my travels in Southeast Asia, I was fortunate to have met a Bangladeshi who was attending the same conference I was attending on ICTD (Information and Communication Technologies and Development). He was kind enough to have treated me to a scrumptious vegetarian meal after accompanying him to a mall to have our travellers cheques exchanged and get himself a new sim card for use during his stay in the country.<br><br> I remember mentioning to him <NAME> whom he knew, since they''re both from Bangladesh. <br><br> While it is always better to be cautious with strangers, given the right environment, it can be good to meet and interact with other people and learn from them too. <br><br> <NAME> has said: ''''Who has given the ultimate verdict that people are motivated only by money--that the desire to do great things for the world can''t be just as powerful a driving force in human behavior?''''', NULL, 44, 0, NULL, 1, NULL, NULL, 0), (71, 1, 2, 'Delivering Happiness', 500, NULL, 'English', '<NAME>', NULL, 'Used - Acceptable', NULL, 'Hardcover', 3, NULL, 'The author shares the story of how he and his team built the online store, Zappos.com, which was later acquired by Amazon.com. I found it interesting to realize that when everyone is selling the same products at more or less the same price, what would set the company apart would none other than be the customer experience or the company''s customer service.', NULL, 43, 0, NULL, 1, NULL, NULL, 0), (72, 1, 9,'software kaihatsu gijutsusha 2008 ed', 2700, NULL, 'Japanese', 'nikkei BP company', NULL, 'Used - Acceptable', NULL, 'Paperback', 0, NULL, NULL, NULL, 25, 0, NULL, 1, NULL, NULL, 0), (73, 1, 2, 'Surgeons Do Not Cry', 500, NULL, 'English', '<NAME>', NULL, 'Used - Acceptable', NULL, 'Paperback', 0, NULL, '''''Learn from the People''''', NULL, 33, 0, NULL, 1, NULL, NULL, 1), (74, 1, 2, '<NAME>', 500, NULL, 'English', '<NAME>', NULL, 'Used - Acceptable', NULL, 'Paperback', 0, NULL, 'It was interesting for me to discover the life story of Mr. <NAME> Jr, and how he was able to build an empire from the ground-up. <br><br> Sometime ago, I was with my dad on our way to a conference in Macau. As we were waiting for our call to board the Cebu Pac plane, my dad quickly recognized Mr. <NAME> Jr sitting quietly, and he humbly introduced himself and I to him. <br><br> When he learned that we were going to a conference in Macau, his eyes widened, and, somehow, he reminded me of <NAME>. <br><br> Years later, I would meet, somewhat serendipitously, his son. <br><br> Having said this, the book mentions that the common business sectors of the top Philippine Listed Holding Firms include: 1) Banking and Finance, 2) Hotels, Malls and Apartments, 3) Manufacturing, and 4) Real Estate and Property Development.', NULL, 30, 0, NULL, 1, NULL, NULL, 1), (75, 1, 2, 'The Millionaire Next Door', 400, NULL, 'English', '<NAME>/<NAME>', NULL, 'Used - Acceptable', NULL, 'Paperback', 5, NULL, 'Along with ''''The Richest Man in Babylon'''', this is a book that I often find myself rereading and rereading. <br><br> A key idea from the book is the importance of frugality. Moreover, for a family to become financially independent, either the wife or the husband should be thriftier than his or her already thrifty spouse. <br><br> I should also add that the book advises that more valuable than money are: good health, longevity, happiness, a loving family, self-reliance, and fine friends.', NULL, 29, 0, NULL, 1, NULL, NULL, 1), (76, 1, 2, 'Managing in a Time of Great Change', 500, NULL, 'English', '<NAME>', NULL, 'Used - Acceptable', NULL, 'Paperback', 2, NULL, 'I learned many things from this book. Here are some of them:<br><br> 1) It has been said that the Japanese owe their success to running the modern corporation as a family. <NAME> adds that the overseas Chinese owe their success to running their family as a modern corporation.<br><br> 2) People have always worked in teams, because very few people could work effectively by themselves. ''''The farmer had to have a wife, and the farmwife had to have a husband.'''' Both of them worked as a team with their employees, the hired hands. The craftsman, too, had to have a wife. ''''He took care of the craft work, she took care of the customers, the apprentices, and the business altogether.'''' Both of them worked as a team with journeymen and apprentices.', NULL, 27, 0, NULL, 1, NULL, NULL, 1), (77, 1, 2, 'Direct from Dell', 500, NULL, 'English', '<NAME> (with <NAME>)', NULL, 'Used - Acceptable', NULL, 'Paperback', 1, NULL, '<NAME> shares the story of how he and his team built Dell Computer Corporation. I particularly liked the part about his company''s early days, and how he started by buying cheap components and upgrading computers himself to sell them to customers at a much lower cost than resellers who simply bought assembled computers and sold them with an added overhead fee. Focusing on what customers actually want, instead of what a person thinks they want, is one of the many things that I learned from reading this book.', NULL, 37, 0, NULL, 1, NULL, NULL, 0), (78, 1, 2, 'The HP Way', 500, NULL, 'English', '<NAME>', NULL, 'Used - Acceptable', NULL, 'Paperback', 1, NULL, 'After doing Computer Science for 10 years, I learned that there will be always something to add, something to fix, and something to improve on. And if you''re the type of person who dislikes finding out that you''ve got to fix another bug, then you''re better off in another industry.<br><br> Given this circumstance, we may ask why anyone would want to put his or herself in such a system. And we can say that because it''s fun. It''s fun because we''re with a company of good friends, building something together.<br><br> ''''...the best job can be done when the manager has a genuine and thorough understanding of the work. I don''t see how managers can even understand what standards to observe, what performance to require, and how to measure results unless they understand in some detail the specific nature of the work they are trying to supervise.''''', NULL, 31, 0, NULL, 1, NULL, NULL, 0), (79, 3, 10, '<NAME>', 180, 260, 'Filipino/English','<NAME>/<NAME>', 'Adarna House, Inc.', 'New', NULL, 'Paperback', 99, NULL, 'Story by <NAME>.<br>Illustrations by <NAME>.<br><br>How was the world created? Where did man come from? Read three legends, from the Samal, Ifugaw, and Tagalog and Visayan, that explain the origins of the world and mankind. <br><br> Paano nilikha ang mundo? Saan nanggaling ang tao? Basahin ang tatlong alamat, mula sa mga Samal, Ifugaw, at Tagalog at Bisaya, na nagpapaliwanag ng pinagmulan ng daigdig at ng tao.', 32, 92, 0, NULL, 1, NULL, NULL, 0), (80, 3, 10, '<NAME>, Kidhat, Pirok, ug Piyong', 180, 260, 'Filipino/Cebuano','<NAME>/<NAME>', 'Adarna House, Inc.', 'New', NULL, 'Paperback', 99, NULL, 'Story by <NAME>.<br>Illustrations by <NAME>.<br><br>Once, four fishermen rowed their boat in a glass of water in search of a bright star. They were Open, Wink, Blink, and Close. Follow their exciting adventure as they go after their star.<br><br> Diha kadto''y upat ka mangingisda nga namangka sa usa ka basong tubig aron pangitaon ang usa ka tahom nga bitoon. Sila si Lurat, Kidhat, Pirok, ug Piyong. Kutas ang ilang panimpalad sa pamangka una nila nakit-an ang ilang gipangandoy nga bitoon.', 32, 27, 0, NULL, 1, NULL, NULL, 0), (81, 3, 10, 'Can We Live Without Trees', 230, 310, 'English', '<NAME>/<NAME>', 'Adarna House, Inc.', 'New', NULL, 'Paperback', 99, NULL, 'Text by <NAME>.<br>Illustrations by <NAME>.<br><br>Here is a reference book about how important trees are to humans and all living things, how biologically diverse the Philippines is, and how we can help save our forests. Find out whether we can really live without trees.', 40, 31, 0, NULL, 1, NULL, NULL, 0), (82, 3, 10, 'Florante at Laura', 280, 360, 'Filipino', '<NAME>/<NAME>', 'Adarna House, Inc.', 'New', NULL, 'Paperback', 99, NULL, 'Written by <NAME>.<br>With annotations by <NAME><br><br>BAGONG SALIKSIK sa pagtuklas ng totoong teksto ni Balagtas, batay sa masinop na pagsusuri sa pinakamatandang edisyon ng Florante at Laura noong ika-19 siglo.', 152, 130, 0, NULL, 1, NULL, NULL, 0), (83, 3, 10, 'Displaced', 330, 410, 'English', '<NAME>/<NAME>', 'Adarna House, Inc.', 'New', NULL, 'Paperback', 99, NULL, 'Written by <NAME>.<br>Illustrations by <NAME>.<br><br>Elay is in her last year of high school. As if things weren''t complicated enough, her mother comes home after years of separation, and her best friend is not acting like a friend at all.<br><br>2012 NBDB Highly Recommended Supplementary Material', 160, 24, 0, NULL, 1, NULL, NULL, 0), (84, 3, 10, 'Mga Tala sa Dagat', 330, 410, 'Filipino', '<NAME>/<NAME>', 'Adarna House, Inc.', 'New', NULL, 'Paperback', 99, '<NAME>', 'Written by <NAME><br> Translated by <NAME><br><br> Isang pag-iibigan ang nabuo sa pagitan ng prinsesa at isang mangingisda. Isang bata ang kailangang isuko ang paglalaro at pag-aaral, alang-alang sa pagiging pinakamahusay na mangingisda ng bayan. Nauugnay ang lahat ng ito ng isang pangako, isang pangako tungkol sa higanteng dagat na may mga dala-dalang mga tala. Ito ang kuwento ng isang pamilya ng mga mangingisda at ng kanilang tadhanang nakatali sa dagat.', 100, 31, 0, NULL, 1, NULL, NULL, 0), (85, 3, 10, '<NAME> (Complete Text)', 330, 410, 'Filipino', '<NAME> (Editor)', 'Adarna House, Inc.', 'New', NULL, 'Paperback', 99, NULL, 'Edited and annotated by <NAME><br><br> Narito ang orihinal na korido at buong kuwento ng Ibong Adarna. Bagong saliksik. Bagong pag-aaral. Dagdag na patnubay para sa guro at modernong mambabasa.', 268, 69, 0, NULL, 1, NULL, NULL, 0), (86, 3, 10, 'Si <NAME> at ang Tiyanak ng Tabon', 255, 335, 'Filipino', '<NAME>', 'Adarna House, Inc.', 'New', NULL, 'Paperback', 99, NULL, 'Sa tournament ng TALA Online sa bayan ng Balanga, namatay ang lahat ng manlalaro maliban kay Janus. Sunod-sunod pa ang naging kaso ng pagkamatay ng mga kabataan sa computer shops sa iba''t ibang panig ng bansa. Kinontak si Janus ng nagpakilalang Joey, isa rin umano sa mga nakaligtas sa paglalaro ng TALA na gaya niya. Hindi inasahan ni Janus ang mga matutuklasan niya mula rito na mag-uugnay sa kanya sa misteryo ng kinahuhumalingan niyang RPG—at sa alamat ng Tiyanak mula sa Tábon!<br><br> 2015 National Book Award, Novel in Filipino<br> 2016 National Children''s Book Award, Best Reads for Kids', 180, 23, 0, NULL, 1, NULL, NULL, 0), (87, 3, 10, 'Si <NAME> at ang Labanang Manananggal-Mambabarang', 280, 360, 'Filipino', '<NAME>', 'Adarna House, Inc.', 'New', NULL, 'Paperback', 99, NULL, 'Apat na buwan na si Janus sa mansiyon nina <NAME> sa Angono pero naroon pa rin ang sakit ng dilang-karayom ng manananggal sa puso niya dahil sa pagkawala ng mga mahal sa buhay at sapilitang paglayo kay Mica. Simula ng Christmas break nang mawasak ang proteksiyon ng mansiyon laban sa Tiyanak at sa mga kampon nito. Matinding barang ba ito? Nawawala rin si Mira, ang isa sa kambal na baganing kasing-edad ni Janus at inampon din nina Manong Joey. Ipinagtapat naman ni Renzo kay Janus ang matagal na palang sinusundan ni Manong Isyo: bumalik sa mapa ng utak ng dalawang manong ang brain imprint ng Papa ni Janus at maaaring buhay pa pala ito! <br><br> Additional Information:<br> Ikalawang libro sa serye ng <NAME>', 204, 39, 0, NULL, 1, NULL, NULL, 0), (88, 3, 10, 'Buwan, <NAME>', 300, 380, 'Filipino', '<NAME>/<NAME>', 'Adarna House, Inc.', 'New', NULL, 'Paperback', 99, NULL, 'Poems by <NAME><br> With illustrations by <NAME><br><br> A collection of poems for children, written by National Artist for Literature Rio Alma. <br><br> Isang koleksiyon ng mga tulang pambata ni Rio Alma, Pambansang Alagad ng Sining.', 120, 45, 0, NULL, 1, NULL, NULL, 0), (89, 3, 6, 'Light', 410, NULL, '(wordless)', '<NAME>', 'Adarna House, Inc.', 'New', NULL, 'Paperback', 99, NULL, 'Story and illustrations by <NAME><br><br> This wordless comic book follows the exploits of a backpack-toting adventurer in a quest to find a mysterious treasure. Framed in black, the illustrations offer delightful bursts of color and are sure to entertain readers of any age. <br><br> 2016 National Book Award, Best Book of Graphic Literature (Wordless)', 114, 30, 0, NULL, 1, NULL, NULL, 0), (90, 3, 6, 'Sixty Six', 435, NULL, 'Filipino', '<NAME>/<NAME>', 'Adarna House, Inc.', 'New', NULL, 'Paperback', 99, NULL, 'Written by <NAME><br> Illustrated by <NAME><br><br> Kuwento ni Celestino Cabal. Kabebertdey niya lang. Mayroon siyang natanggap na regalo na ngayo''y unti-unti niyang binubuksan. Ika nga ng matatanda, ''Huli man daw at magaling, maihahabol din.''', 148, 25, 0, NULL, 1, NULL, NULL, 0), (91, 3, 7, 'Si <NAME> at ang Tiyanak ng Tabon (Manga)', 410, NULL, 'Filipino', '<NAME>/<NAME>/<NAME>', 'Adarna House, Inc.', 'New', NULL, 'Paperback', 99, NULL, 'Based on the novel by <NAME><br> Adaptation by <NAME><br> Illustrations by <NAME><br><br> Ang akala ni Janus, pangkaraniwang laro lang ang TALA Online. Sunod-sunod ang pagbabago sa buhay niya matapos ang kahindik-hindik na pangyayari sa RPG tournament sa sinalihan niya. Pero nang matuklasan niya ang tunay na kaugnayan ng larong ito sa alamat ng Tiyanak ng Tabon, wala na siyang magawa kundi ipagpatuloy ang paglalaro!', 125, 27, 0, NULL, 1, NULL, NULL, 0), (92, 3, 10, 'Detective Boys of Masangkay: Ang Mangkukulam', 355, 435, 'Filipino', '<NAME>/<NAME>', 'Adarna House, Inc.', 'New', NULL, 'Paperback', 99, NULL, 'Story by <NAME><br> Illustrations by <NAME><br><br> Nawawala ang alagang pusa ni Ate Lotlot at ang alagang tuta ni Junjun. Ninakaw ang mga sinampay ni Aling Cora. Pinatay ang mga panabong na manok ni <NAME>. Na-kidnap ang sikat na Shino Kid. May isang mangkukulam. May isang dalagitang bagong lipat. <br><br> May tatlong binatilyong fans ni Detective Conan. Sila ang lulutas sa lahat ng misteryong bumabalot sa Barangay Masangkay.', 216, 40, 0, NULL, 1, NULL, NULL, 0), (93, 3, 10, 'Piagsugpatan: Stories of the Mandaya', 280, 360, 'English', 'Marcy Dans Lee et al.', 'Adarna House, Inc.', 'New', NULL, 'Paperback', 99, NULL, 'Retellings by <NAME><br> Illustrations by <NAME>, <NAME>, <NAME>, <NAME><br><br> For the Mandaya people, piagsugpatan or the horizon is a part of their lives. Piagsugpatan bridges the three material worlds: Langit, Lupa, at Ugsuban. In this book are eight stories that will help bridge the ancient Mandaya worldview with today''s young readers.', 90, 26, 0, NULL, 1, NULL, NULL, 0), (94, 3, 10, 'Si Tito Libro at Ako', 280, 360, 'Filipino', '<NAME>/<NAME>/<NAME>', 'Adarna House, Inc.', 'New', NULL, 'Paperback', 99, '<NAME>', 'Story by <NAME><br> Translated by <NAME><br> Illustrations by JC Galag<br><br> Plano ng siyam na taóng gulang na si Yasmin na makapagbasá ng isang libro kada araw, habambuhay. Palaging may tamang libro para sa kaniya si Tito Libro, ang may-ari ng aklatan sa kanto. Pero biglang ipinasara ang aklat ni Tito Libro at kailangang huminto ni Yasmin sa pagbabasa para tulungan siya. Ano nga ba ang magagawa ni Yasmin at ng kaniyang mga kaibigan sa gitna ng nalalapit na eleksiyon? Matutulungan kaya sila ng artistang si <NAME> na tumatakbong Mayor?', 115, 32, 0, NULL, 1, NULL, NULL, 0), (95, 3, 10, 'Supremo', 280, 360, 'Filipino', '<NAME>/<NAME> ', 'Adarna House, Inc.', 'New', NULL, 'Paperback', 99, NULL, 'Story by <NAME><br> With illustrations by <NAME><br><br> ''Supremo Andro!''<br><br> ''Yan ang gustong marinig ni Andro pagtuntong niya ng Grade 6. Kaya naisip niyang tumakbo bilang Supremo ng Katipunan.<br><br> Hindi niya inakala na marami palang dapat gawin bago maging Supremo. Hindi niya inaasahan ang mga matututuhan niya bago maging pinuno.<br><br> Matupad kaya ang kaniyang pangarap na maging Supremo?<br><br> 2016 National Children''s Book Award, Best Reads for Kids', 105, 42, 0, NULL, 1, NULL, NULL, 0), (96, 3, 10, 'P<NAME>', 280, 360, 'English', 'Xi Zuq/Al Estrella', 'Adarna House, Inc.', 'New', NULL, 'Paperback', 99, NULL, 'APAKOPO APANG HAPARIPI SAPA IPISKUPUL. <br><br> Ito ang secret code na nakita ni Andro sa poster para sa Clubs Day ng kanilang paaralan. Akala niya magagawa niyang tuklasin ito kasama ni Miyo. Na dapat ay kasama rin niya sa paghahanda ng booth nila sa Comics Club. Pero parang may iba kay Miyo, at may mga lihim pa itong hindi niya alam. <br><br> Matuklasan kaya niya ang mga lihim na ito?', 105, 178, 0, NULL, 1, NULL, NULL, 0), (97, 3, 10, 'Ang Lihim ng San Esteban', 280, 360, 'Filipino', '<NAME>/<NAME>', 'Adarna House, Inc.', 'New', NULL, 'Paperback', 99, NULL, 'Story by Annette <NAME><br> Translation by <NAME><br> <br> Unang beses magbabakasyon ni Jacobo sa San Esteban sa Ilocos, at magkahalong pananabik at kaba ang dala ng biyahe papunta sa probinsiya ng mga magulang niya. Siguradong marami siyang matutuklasan tungkol sa kasaysayan ng kaniyang pamilya mula kay Lola Carmen! Ngunit hindi niya inaasahang may mas malaking lihim sa mga lumang bahay at multo ng San Esteban. Ang mga ito kaya ang susi sa misteryong pilit na ikinukubli ni Lola Carmen?', 100, 37, 0, NULL, 1, NULL, NULL, 0), (98, 3, 10, 'Can We Live on Mars', 230, 310, 'English', '<NAME>/Bru', 'Adarna House, Inc.', 'New', NULL, 'Paperback', 99, NULL, 'Text by <NAME><br> Illustrations by Bru<br> <br> At the rate that people are exploring space, will it take long before we actually start living on Mars? Discover the beginnings of astronomy, the different kinds of heavenly bodies, and the many space explorations taking place. Find out whether we can live on Mars.<br><br> 2010 Best Reads for Kids, 1st National Children''s Book Awards', 40, 29, 0, NULL, 1, NULL, NULL, 0), (99, 3, 10, 'Can We Drink the Ocean', 230, 310, 'English', '<NAME>/<NAME>', 'Adarna House, Inc.', 'New', NULL, 'Paperback', 99, NULL, 'Text by <NAME><br> Illustrations by <NAME><br> <br> If 70 percent of the world is made up of water, why is everyone worrying about it running out? Discover the properties of water, along with its cycle, treatment, distribution, and how you can help conserve it. Find out whether we can drink the ocean.', 40, 27, 0, NULL, 1, NULL, NULL, 0), (100, 3, 10, 'Can We Plug Into Lightning', 230, 310, 'English', '<NAME>/<NAME>', 'Adarna House, Inc.', 'New', NULL, 'Paperback', 99, NULL, 'Text by <NAME><br> Illustrations by <NAME>-Doctolero<br> <br> They say that lightning is made of electricity. Is that where the electricity of a light bulb comes from? Discover how a light bulb works, the sources of energy, how energy is changed to electricity, and how electricity travels to our home.', 40, 20, 0, NULL, 1, NULL, NULL, 0), (101, 3, 10, 'Guardians of Tradition: The Gawad sa Manlilikha ng Bayan', 230, 310, 'English', '<NAME>/<NAME>/<NAME>', 'Adarna House, Inc.', 'New', NULL, 'Paperback', 99, NULL, 'Text by <NAME><br> Illustrations by <NAME><br> Photos by <NAME><br> <br> Join Banog and Kiko as they discover the Philippines'' National Living Treasures: <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, and <NAME>. Read about these people''s dedication to their craft and the tradition of their forebears.', 32, 36, 0, NULL, 1, NULL, NULL, 0), (102, 3, 10, '<NAME>', 200, 280, 'Filipino', '<NAME>/<NAME>', 'Adarna House, Inc.', 'New', NULL, 'Paperback', 99, NULL, 'Written by Liwliwa Malabed<br> Illustrated by <NAME><br> <br> Ano ang dapat gawin kapag may bagyo, lindol, sumabog na bulkan, o sunog? Ang aklat na ito ang maghahanda sa iyo sa anumang sakuna!', 44, 43, 0, NULL, 1, NULL, NULL, 0), (103, 3, 10, '<NAME>', 830, 910, 'Filipino', 'Adarna House, Inc.', 'Adarna House, Inc.', 'New', NULL, 'Paperback', 99, NULL, 'A Filipino dictionary for high school, Diksiyon<NAME> was created to be the partner of students in their study of Philippine language and literature. It contains unfamiliar words found in El Filibusterismo, Noli Me Tangere, and Florante at Laura. To make it easier to understand, main entries also include sample sentences. It also contains entries that represent art, culture, and local beliefs of the different ethnic groups in the Philippines. Apart from being an instrument towards discovering how rich the Filipino language is, Diksiyonaryong Adarna also aims to instill in students a love for their own language.', 800, 24, 0, NULL, 1, NULL, NULL, 0), (104, 3, 10, 'What Kids Should Know About Andres and the Katipunan', 230, 310, 'English', 'Weng Cahiles/Isa Natividad', 'Adarna House, Inc.', 'New', NULL, 'Paperback', 99, NULL, 'Author: <NAME><br> Illustrator: Isa Natividad<br> <br> Who was <NAME>? How was Andres as a brother, a husband, and as a revolutionary leader? Here is a handy reference for children on the life of the Supremo and the Katipunan. <br><br> 2014 Best Read for Kids, 3rd National Children''s Book Awards', 48, 24, 0, NULL, 1, NULL, NULL, 0), (105, 3, 6, 'Piko', 410, NULL, 'Filipino/English', '<NAME> (Editor) et al.', 'Adarna House, Inc.', 'New', NULL, 'Paperback', 99, NULL, 'Edited by <NAME> <br><br> A Filipino comic book for kids, this is a collection of 20 visual stories from 22 creators. <br><br> Awit ng Paggala (Laraine Gazmen & <NAME>)<br> Captain Old vs Pambatang Komiks (<NAME>)<br> Dressing Up with Dolly (Trizha Ko)<br> The Sculptor (Rommel Estanislao)<br> Limang Kuwentong _ _ _ _ _ (<NAME> & Apol Sta. Maria)<br> Ang Panaginip ni <NAME> (<NAME>)<br> Lucky (<NAME>)<br> Iñigo''s Day Out (<NAME> & <NAME>)<br> Salamin (Josel Nicolas)<br> Kukote Ko (<NAME> with Karize Uy)<br> The Magic Brush (Daniela Go)<br> Treat (<NAME> & <NAME>)<br> Imposible (JP Palabon)<br> Hotcakes X Jimbob at ang Ulan (Josel Nicolas)<br> Si Ella at ang Sigwa (<NAME>, K<NAME>an, & Karize Uy)<br> Ang Kahon (Bong Redila)<br> Salamin Part 2 (Josel Nicolas)<br> Awit ng Pagbalik (<NAME> & Laraine Gazmen)', 96, 33, 0, NULL, 1, NULL, NULL, 0), (106, 3, 10, '<NAME>', 180, 260, 'Filipino/English', '<NAME>/<NAME>', 'Adarna House, Inc.', 'New', NULL, 'Paperback', 99, NULL, 'Story by <NAME><br> Illustrations by <NAME><br> <br> Hati kami ni Kuya sa anumang pagkain. Pero bakit palaging mas marami at mas malaki ang napupunta sa kaniya? Ganito ba talaga ang hating kapatid? <br><br> Kuya and I always share food. But why is his share always bigger? Is this what fair share means? <br><br> 2014 Best Read for Kids, 3rd National Children''s Book Awards', 32, 88, 0, NULL, 1, NULL, NULL, 0), (107, 3, 10, '<NAME>', 180, 260, 'Filipino', '<NAME>/<NAME>', 'Adarna House, Inc.', 'New', NULL, 'Paperback', 99, NULL, '''''Kung Linggo, nag-iimbita ako ng tigre...'''' <br><br> Naglalaman ang librong ito ng tula tungkol sa mga pambihirang pangyayari tuwing kasama ng isang bata ang kaniyang pang-Linggong kalaro.', 32, 40, 0, NULL, 1, NULL, NULL, 0), (108, 3, 10, 'Pag-abot ni Kolor sa Lungsod', 180, 260, 'Cebuano/Filipino', '<NAME>', 'Adarna House, Inc.', 'New', NULL, 'Paperback', 99, '<NAME>', 'Kaniadto hugaw ug subo ang lungsod sa Abog. Tapolan man god manglimpiyo ang mga tawo dinhi. Nausab lang ang tanan dihang miabot sa ilang dapit ang usa ka mamimintal nga subling gahatag og kolor sa palibot. <br><br> Additional Information: <br> Hinubad sa Cebuano ni <NAME> ug Dr. <NAME>', 32, 35, 0, NULL, 1, NULL, NULL, 0), (109, 3, 10, 'Si Ambongan', 180, 260, 'Cebuano/Filipino', 'L<NAME>onio/<NAME>', 'Adarna House, Inc.', 'New', NULL, 'Paperback', 99, NULL, 'Adaptation by Lamberto Antonio<br> Illustrations by J.<NAME> Peña<br> <br> Kini ang sugid sa kabayanihan ni Ambongan, usa ka batang nagpuyo sa Mactan sa panahon sa pag-abot ni Magellan. Pinauyon kining sugid sa Makisig, The Little Hero of Mactan nga sinulat ni <NAME>aneta kinsa maoy nakadaog sa unang ganti sa indigay sa panulat og sigulanong pangbata.', 32, 90, 0, NULL, 1, NULL, NULL, 0), (110, 3, 10, 'Si Diwayen, <NAME> ang mga Espanyol', 180, 260, 'Filipino/English', '<NAME>/<NAME>', 'Adarna House, Inc.', 'New', NULL, 'Paperback', 99, NULL, 'Story by <NAME><br> Illustrations by Paolo Lim<br> <br> Lunhaw and Diwayen are friends. But their fates are just too different: Lunhaw is a princess, while Diwayen is a slave. Will Diwayen ever taste true freedom? <br><br> Magkaibigan si Lunhaw at si Diwayen. Ngunit sadyang magkaiba ang kanilang kapalaran: prinsesa si Lunhaw habang alipin naman si Diwayen. Makamit kaya ni Diwayen ang tunay na kalayaan? <br><br> Additional Information:<br> Featured in the Batang Historyador series are stories of the challenges, dreams, and awakening of five children from five different relevant points of Philippine history. Each story is a glimpse in the way of life and rights of the children during these periods, and a look back at the colorful past of the country.', 32, 22, 0, NULL, 1, NULL, NULL, 0), (111, 1, 8, 'Scratchbuild Revolution Hobbymate 12th Anniversary Edition', 3500, NULL, 'English', NULL, 'USA Gundam Store', 'New', NULL, 'Paperback', 1, NULL, NULL, NULL, 32, 0, NULL, 1, NULL, NULL, 0), (112, 1, 2, 'Tuesdays with Morrie', 300, NULL, 'English', '<NAME>', NULL, 'Used - Acceptable', NULL, 'Paperback', 1, NULL, '''''The way to get meaning into your life is to devote yourself to loving others, devote yourself to your community around you, and devote yourself to creating something that gives you purpose and meaning.''''', NULL, 23, 0, NULL, 1, NULL, NULL, 1), (113, 1, 6, 'Watchmen', 500, NULL, 'English', '<NAME>/<NAME>', NULL, 'Used - Acceptable', NULL, 'Paperback', 1, NULL, 'In the midst of a global crisis, where people and nations are in conflict with each other, how do you get everyone to resolve their differences, and be united as one community?', NULL, 26, 0, NULL, 1, NULL, NULL, 0), (114, 1, 2, 'The Alchemist', 350, NULL, 'English', 'P<NAME>', NULL, 'Used - Acceptable', NULL, 'Paperback', 1, NULL, 'Brazilian writer, <NAME>, was 39 years old when he wrote ''''The Alchemist''''. It was one of the many books that he wrote after coming from a pilgrimage in ''''El camino''''. One of the things that I remember after reading this book is that the universe helps each person to realize his or her dream. <br><br> In life, there comes a point when we find ourselves locked in a system where we feel that instead of helping us realize our dream, the universe seems to be conspiring against us. And the worst part is that the moment you believe this lie, it becomes a reality. <br><br> While it may be true that the infinite possibilities of life have already been written down, and therefore, there may be times when we may feel that we have not been given much choice on the path that we take, by being good and kind to as many people as we can, naturally, effortlessly, that is, not forced, we can learn to trust that things are going well, as they should.', NULL, 23, 0, NULL, 1, NULL, NULL, 1), (115, 1, 2, 'Made in America', 350, NULL, 'English', '<NAME>/<NAME>', NULL, 'Used - Acceptable', NULL, 'Paperback', 1, NULL, 'This is a book which after finishing reading, I started reading again from the beginning. It shares the story of <NAME> and how he and his team built the retail giant, Wal-Mart. I highly recommend this book to anyone who wants to understand the retail industry and the history of its development in the American context.<br><br>Here are 3 key lessons: 1) the US heavily imports its goods from Asia because their cost and quality are much more competitive abroad (this reminds me of the situation in the Philippines), 2) a successful IPO can wipe off debt and make many people millionaires, and 3) Even if many people become millionaires and after having lowered the cost of goods down to a cheap level, yet still guarantee customer satisfaction, there will always be people who, one way or another, would remain economically poor and would rather receive handouts from rich people. This third one is an important insight for those who like Usbong also have a mission to defeat poverty.', NULL, 33, 0, NULL, 1, NULL, NULL, 1), (116, 1, 2, '<NAME>', 400, NULL, 'German/English', 'Goethe/<NAME>', NULL, 'Used - Acceptable', NULL, 'Paperback', 1, '<NAME>', 'In this classic masterpiece, we find Dr. Faust, a middle-aged scholar and scientist who has promised the devil his soul in exchange for finding the true meaning of life. It took the German poet, Goethe, his whole life to complete this poem. And the poem does show how Goethe''s way of thinking evolved as he aged from the time he began writing it at age 20, until he finished it just before he passed away at 83. <br><br> If you haven''t read it, or have yet to hear the story, consider this: if you were given a choice to live any life you want, e.g. become the wealthiest, be loved by anyone, become the most powerful, and in exchange, you''ll have to die, would you take it? <br><br> This version includes the original German and English translation.', NULL, 33, 0, NULL, 1, NULL, NULL, 0), (117, 1, 2, 'Blink', 300, NULL, 'English', '<NAME>', NULL, 'Used - Acceptable', NULL, 'Paperback', 1, NULL, '''''The Power of Thinking Without Thinking''''', NULL, 39, 0, NULL, 1, NULL, NULL, 0), (118, 1, 2, 'The Tipping Point', 300, NULL, 'English', '<NAME>', NULL, 'Used - Acceptable', NULL, 'Paperback', 1, NULL, NULL, NULL, 20, 0, NULL, 1, NULL, NULL, 0), (119, 1, 8, 'The Art of the Matrix', 500, NULL, 'English', NULL, NULL, 'Used - Very Good', NULL, 'Paperback', 1, NULL, 'This Matrix collectible contains concept designs, shooting script (final draft before filming), scene notes, as well as deleted script excerpts. If you haven''t yet seen the film, here''s something to ponder on: if you were given two pills, one pill leads you to the truth about everything, which is grim and far from anything ideal, while the other leads you back to the fantasy world where all your dreams can come true, which would you take?', NULL, 43, 0, NULL, 1, NULL, NULL, 0), (120, 1, 9, 'BJT Business Japanese Proficiency Test Listening and Reading Comprehension (with 2 CDs)', 1170, NULL, 'Japanese', 'JETRO', NULL, 'Used - Acceptable', NULL, 'Paperback', 1, NULL, 'This is one of three BJT (Business Japanese Test) reviewers that I bought to prepare for the exam. I had passed the highest level of the Japanese Language Proficiency Test (JLPT) in about 5 years time, after I formally began studying the language, yet I knew that my nihongo was far from perfect. <br><br>Passing the JLPT offered some sort of an assurance to employers and schools that a student is able to effectively use the language at a level somewhat equivalent to a high school student. However, for specialized words that are learned in university, graduate school, and the workplace, the student will have to learn to pick them up his or herself. Little did I know that what I lacked wasn''t really more complicated words, but understanding of Japanese culture. <br><br>I never did get to take the BJT. Somehow, I found myself out of the corporate world to which I am ever grateful for the many hard lessons that I''ve learned, and in school, teaching Japanese language and culture (at least from what I can understand) to high school students. <br><br>It will take me several more years before the cultural aspect of Japan really began to dawn on me. I cannot say that I fully understand it, but I do know that my becoming a teacher helped me.', NULL, 65, 0, NULL, 1, NULL, NULL, 0), (121, 1, 9, 'BJT Business Japanese Proficiency Test Official Guide (with CD)', 820, NULL, 'Japanese', 'JETRO', NULL, 'Used - Acceptable', NULL, 'Paperback', 1, NULL, 'This is one of three BJT (Business Japanese Test) reviewers that I bought to prepare for the exam. I had passed the highest level of the Japanese Language Proficiency Test (JLPT) in about 5 years time, after I formally began studying the language, yet I knew that my nihongo was far from perfect. <br><br>Passing the JLPT offered some sort of an assurance to employers and schools that a student is able to effectively use the language at a level somewhat equivalent to a high school student. However, for specialized words that are learned in university, graduate school, and the workplace, the student will have to learn to pick them up his or herself. Little did I know that what I lacked wasn''t really more complicated words, but understanding of Japanese culture. <br><br>I never did get to take the BJT. Somehow, I found myself out of the corporate world to which I am ever grateful for the many hard lessons that I''ve learned, and in school, teaching Japanese language and culture (at least from what I can understand) to high school students. <br><br>It will take me several more years before the cultural aspect of Japan really began to dawn on me. I cannot say that I fully understand it, but I do know that my becoming a teacher helped me.', NULL, 55, 0, NULL, 1, NULL, NULL, 0), (122, 1, 9, 'BJT Business Japanese Proficiency Test-Practice Test and Strategies (with CD)', 1100, NULL, 'Japanese', 'JAL Academy', NULL, 'Used - Acceptable', NULL, 'Paperback', 1, NULL, 'This is one of three BJT (Business Japanese Test) reviewers that I bought to prepare for the exam. I had passed the highest level of the Japanese Language Proficiency Test (JLPT) in about 5 years time, after I formally began studying the language, yet I knew that my nihongo was far from perfect. <br><br>Passing the JLPT offered some sort of an assurance to employers and schools that a student is able to effectively use the language at a level somewhat equivalent to a high school student. However, for specialized words that are learned in university, graduate school, and the workplace, the student will have to learn to pick them up his or herself. Little did I know that what I lacked wasn''t really more complicated words, but understanding of Japanese culture. <br><br>I never did get to take the BJT. Somehow, I found myself out of the corporate world to which I am ever grateful for the many hard lessons that I''ve learned, and in school, teaching Japanese language and culture (at least from what I can understand) to high school students. <br><br>It will take me several more years before the cultural aspect of Japan really began to dawn on me. I cannot say that I fully understand it, but I do know that my becoming a teacher helped me.', NULL, 51, 0, NULL, 1, NULL, NULL, 0), (123, 4, 11, 'Hondashi 1kg', 870, NULL, 'Japanese/Mandarin', NULL, NULL, 'New', NULL, NULL, 1, NULL, 'This is a necessary ingredient for many Japanese cuisines.<br><br>Expiration: Dec. 16, 2018', NULL, 61, 0, NULL, 1, NULL, NULL, 0), (125, 4, 11, 'Golden Curry Regular Hot', 235, NULL, 'Japanese', NULL, NULL, 'New', NULL, NULL, 1, NULL, 'Recipe:<br> 1) Put chopped potatoes, carrots, onions, thinly sliced meat into a pot of water that is only 1 inch higher when all the ingredients are in place.<br> 2) Cover the pot and boil the ingredients.<br> 3) When the potatoes and the carrots can be easily pierced using a wooden chopstick, break into 4 smaller cubes 1 of the 2 big cubes of Golden Curry, put them in the pot, and boil until they melt.<br> 4) In low heat, mix from time to time until it becomes thick. <br><br> Expiration: Feb. 1, 2019', NULL, 44, 0, NULL, 1, NULL, NULL, 0), (126, 4, 11, 'Kikkoman Soy Sauce Naturally Brewed 1Litre', 350, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 1, NULL, 'Combined with water and plenty of sugar, this forms a vital ingredient to any Japanese cuisine, such as yasai itame (sautéed mixed vegetables). I also like adding this sauce''s combination to boiled chopped daikon and carrots.', NULL, 34, 0, NULL, 1, NULL, NULL, 0), (127, 4, 11, 'Spam 340g', 220, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 1, NULL, 'I remember my American professor in Japan calmly joking that while we commonly know spam as unsolicited emails from strangers, Spam, the food, is actually amazingly popular in the state of Hawaii.', NULL, 27, 0, NULL, 1, NULL, NULL, 0), (128, 4, 11, 'Heinz Tomato Ketchup', 115, NULL, 'English', NULL, NULL, 'New', NULL, NULL, 1, NULL, 'I often find myself putting a lot of this Heinz Tomato Ketchup when I eat my home-made club house sandwich. Simply delicious. <br><br> Net Weight: 20 Oz<br> Expiration: July 7, 2018', NULL, 62, 0, NULL, 1, NULL, NULL, 0), (129, 4, 12, 'Schick Exact 2 Razors 2plus1', 125, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 1, NULL, 'It is said that a Zen Buddhist monk carried only a few things with him. One of those things is a razor for shaving. ', NULL, 29, 0, NULL, 1, NULL, NULL, 0), (130, 4, 11, 'Nissin Cup Noodles with Shrimp 64g', 115, NULL, 'English', NULL, NULL, 'New', NULL, NULL, 1, NULL, 'During my brief stay in UTown (University Town), Singapore, I brought with me a number of Nissin Cup Noodles, because I didn''t want to spend too much time and energy looking for food that would cost way beyond my budget. As it turned out, UTown has a wonderful cafeteria which sold authentic noodle soups that cost more or less the same as the Nissin Cup Noodles I brought. Still, it is good to come prepared. Just add hot water, wait for 5mins, and you''re ready to eat!', NULL, 27, 0, NULL, 1, NULL, NULL, 0), (131, 4, 12, 'Safeguard Value Pack 3x135g', 180, NULL, 'English', NULL, NULL, 'New', NULL, NULL, 1, NULL, 'We''ve been using Safeguard soap since I can remember. It is difficult to imagine a world without it.', NULL, 29, 0, NULL, 1, NULL, NULL, 0), (132, 4, 12, 'Old Spice High Endurance Dry Cream Pure Sport 45g', 296, NULL, 'English', NULL, NULL, 'New', NULL, NULL, 1, NULL, 'I remember saying as a kid that only people who stink use deodorants. While honestly true, deodorants were made precisely because people didn''t want to stink...', NULL, 31, 0, NULL, 1, NULL, NULL, 0), (133, 4, 11, 'JBC Happy Peanuts 100g', 100, NULL, 'English', NULL, NULL, 'New', NULL, NULL, 1, NULL, NULL, NULL, 44, 0, NULL, 1, NULL, NULL, 0), (134, 1, 8, 'The Legend of Zelda Hyrule Historia', 2000, NULL, 'English', NULL, NULL, 'Used - Very Good', NULL, NULL, 1, NULL, 'There was a time when I could say that I''ve played all the Zelda games for the Gameboy. Now, with all the Nintendo consoles, new and not-so-new, I must admit that I have yet to catch up. This book provides a historia of the development of this wonderful game from its early beginnings until Skyward Sword. It includes character designs, concept art, and a manga towards the end. What I particularly like about the Zelda series is that unlike other role-playing games, a person need not have to spend time ''''leveling-up''''. Instead, he or she must use his wit to solve puzzles and defeat bosses, which can be quickly achieved if one understands the way.', NULL, 35, 0, NULL, 1, NULL, NULL, 0), (135, 4, 11,'marukome dashiiri katsuo kombu miso 1kg', 250, NULL, 'Japanese', NULL, NULL, NULL, NULL, NULL, 1, NULL, 'Miso shiru or Miso soup is a common--we can say--even daily food in Japan. Moreover, unlike other miso''s sold in the market, this already contains hondashi, so there is no more need to add it, and the soup will still have an authentic taste. ', NULL, 31, 0, NULL, 1, NULL, NULL, 0), (136, 4, 11, 'yakisoba sauce 1,200g', 350, NULL, 'Japanese', NULL, NULL, NULL, NULL, NULL, 1, NULL, 'Although the carton says that it''s yakisoba (stir-fried noodles) sauce, one can use this sauce for other food as well. For example, as a sort of teriyaki sauce for chicken, fish, and other types of meat.<br><br> Expiration: May 8, 2019', NULL, 30, 0, NULL, 1, NULL, NULL, 0), (137, 4, 11, 'kewpie Japanese mayonnaise 500g', 275, NULL, 'Japanese', NULL, NULL, NULL, NULL, NULL, 1, NULL, 'Kewpie Japanese mayonnaise has a distinct taste when compared to mayonnaise sold in the local market. In Japan, there is even a name for people who like mayonnaise. It''s ''''mayo-ra''''.', NULL, 39, 0, NULL, 1, NULL, NULL, 0), (138, 4, 11, 'The Original Hotcake Mix Fluffy n Tasty', 135, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 1, NULL, 'I remember in Hayao Miyazaki''s Kiki''s Delivery Service, the protagonist, Kiki, went out to a far away town to learn to become independent. Because she had a tight budget, she mostly ate hot cakes. At some point in the film, she lamented that she didn''t know what she''d do if she became a grandma and still no customers appeared. On a happy note, she and her elder sister-like friend flipped hot cakes and ate them for dinner during one of their stays in a forest cabin.', NULL, 38, 0, NULL, 1, NULL, NULL, 0), (139, 4, 11, 'McCormick Iodized Salt 140g', 100, NULL, 'English', NULL, NULL, 'New', NULL, NULL, 1, NULL, 'Iodized salt prevents iodine deficiency disorders. According to the World Health Organization (WHO), ''''Iodine is essential for healthy brain development in the fetus and young child. Iodine deficiency negatively affects the health of women, as well as economic productivity and quality of life.'''' <br><br> Reference:<br> <a href=''''http://www.who.int/elena/titles/salt_iodization/en/'''' target=''''_blank''''>http://www.who.int/elena/titles/salt_iodization/en/</a>; last accessed: 20170821', NULL, 28, 0, NULL, 1, NULL, NULL, 0), (140, 4, 12, 'izumi Glass Teapot with Strainer 700ml', 158, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 1, NULL, 'This izumi Glass Teapot with Strainer combines well with sencha (Green Tea). Just put enough sencha leaves to cover the bottom part of the strainer, fill the teapot with hot water (yes, the water needs to be really hot, not warm), and then wait for 3mins. You''ll see that the color of the water will turn lime green. It should now be ready to drink. If you wait longer, the color of the water will eventually turn brown. It will still be drinkable, but it may already be cold.', NULL, 215, 0, NULL, 1, NULL, NULL, 0), (141, 4, 5, 'PROMO-sencha (Green Tea), izumi Glass Teapot with Strainer 700ml', 312, 383, 'English', NULL, NULL, NULL, NULL, NULL, 1, NULL, 'This izumi Glass Teapot with Strainer combines well with sencha (Green Tea). Just put enough sencha leaves to cover the bottom part of the strainer, fill the teapot with hot water (yes, the water needs to be really hot, not warm), and then wait for 3mins. You''ll see that the color of the water will turn lime green. It should now be ready to drink. If you wait longer, the color of the water will eventually turn brown. It will still be drinkable, but it may already be tepid.', NULL, 45, 0, NULL, 1, NULL, NULL, 0), (142, 1, 5, 'PROMO-erin (with DVDs) vol 1-3', 5320, 7776, 'Japanese', NULL, NULL, NULL, NULL, 'Paperback', 1, NULL, 'This erin series contains manga, cultural notes, basic and advanced skits (translated from Japanese to English, Portuguese, Korean, and Simplified Mandarin) as well as their videos in DVDs, as they share the story of erin, an international student, studying in a high school in Japan and living with a Japanese host family.', NULL, 60, 0, NULL, 1, NULL, NULL, 0), (143, 1, 7, 'Nodame Manga set (1-25 complete)', 3250, 5000, 'Japanese', NULL, NULL, 'Used - Good', NULL, NULL, 1, NULL, NULL, NULL, 62, 0, NULL, 1, NULL, NULL, 0), (144, 1, 5, 'PROMO-kanzen masta- 1kyuu and 2kyuu', 1750, 1820, 'Japanese', NULL, NULL, 'New', NULL, NULL, 1, NULL, 'These two books are invaluable reference guides pertaining to the intricate grammar structure of the Japanese language. As a reference guide, I do not recommend reading them from cover to cover, but referring to them when one encounters a new or perplexing grammar pattern. These should not only be helpful in passing N2 and N1 of the Japanese Language Proficiency Test (JLPT), but also in achieving mastery of the ever evolving Japanese language.', NULL, 60, 0, NULL, 1, NULL, NULL, 0), (145, 3, 10, 'Alpabetong Filipino', 180, 260, 'Filipino', '<NAME>/<NAME>', NULL, 'New', NULL, 'Paperback', 99, NULL, 'Story by <NAME><br> Illustrations by <NAME><br> <br> Isa sa mga unang libro ng bata, tungkol sa alpabetong Filipino, na nagtatampok ng mga halimbawang salita para sa bawat titik.', 32, 71, 0, NULL, 1, NULL, NULL, 0), (146, 3, 10, 'Ang Alamat ng Palay', 180, 260, 'Filipino/English', '<NAME>/<NAME>', NULL, 'New', NULL, 'Paperback', 99, NULL, 'Story by <NAME><br> Illustrations by <NAME><br> <br> Rice is very important to the Filipino, which is why there are so many legends regarding the grain. One of these stories is of husband-and-wife Banag and Danas, and how agriculture began in the Philippines. <br><br> Napakahalaga ng bigas sa mga Filipino. Kaya naman napakaraming alamat tungkol sa palay. Isa na rito ang kuwento ng mag-asawang Banag at Danas, at kung paano nagsimula ang agrikultura sa Filipinas.', 32, 215, 0, NULL, 1, NULL, NULL, 0), (147, 3, 10, 'Alamat ng Ampalaya', 180, 260, 'Filipino/English', '<NAME>/<NAME>', NULL, 'New', NULL, 'Paperback', 99, NULL, 'Story by <NAME><br> Illustrations by <NAME>-Albano<br> <br> This is an original story on the legend of the bitter gourd. The story excites the imagination of children and warns them against the evil of envy and greed. <br><br> Isang orihinal na kuwento tungkol sa alamat ng ampalaya, pinupukaw nito ang imahinasyon ng mga bata at binabalaan sila sa kasamaang dulot ng pagkainggit at kasakiman. <br><br> Finalist – 1995 PBBY-Salanga Prize', 32, 87, 0, NULL, 1, NULL, NULL, 0), (148, 3, 10, '<NAME>', 180, 260, 'Filipino/English', '<NAME>/<NAME>', NULL, 'New', NULL, 'Paperback', 99, NULL, 'Story by <NAME><br> Illustrations by <NAME><br> <br> ''Charge!'' shouts <NAME>, raising his arms that shook with fat. He dreams of playing the revolutionary hero <NAME> for the school play. Do lead roles only go to skinny people? <br><br> ''Sugod, mga kapatid!'' sigaw ni <NAME>, sabay taas ng mga braso niyang umaalog sa taba. Pangarap niyang gumanap bilang Andres Bonifacio sa dula. Ngunit payat nga lang ba ang maaaring maging bida?', 32, 34, 0, NULL, 1, NULL, NULL, 0), (149, 3, 10, 'Naging Manlililok si Wigan', 180, 260, 'Filipino', 'Felice Prudente Sta. Maria et al.', NULL, 'New', NULL, 'Paperback', 99, NULL, 'Story by Felice Prudente Sta. Maria<br> Illustrations by <NAME><br> Translation by <NAME><br> <br> Along with other Ifugaw farmers, Wigan farms on the highlands'' magnificent payyo. When his crops suddenly and unexpectedly fail, he asks help from the gods in heaven. It is through these gods that Wigan learns to create a bul-ol, and begins the art of sculpture. <br><br> Isa si Wigan sa mga Ifugaw na nagsasaka sa dakilang payyo. Nang hindi maging sapat ang kaniyang ani, agad siyang humingi ng tulong sa mga diyos sa kalangitan. Sa tulong ng mga diyos, natutuhan niyang lumikha ng bul-ol: dito nagsimula ang sining ng paglililok <br><br> Published in partnership with Filipinas Heritage Library and National Commission on Culture and Arts', 32, 31, 0, NULL, 1, NULL, NULL, 0), (150, 3, 10, 'Si Pilandok at ang Manok na Nangingitlog ng Ginto', 180, 260, 'Filipino/English', '<NAME>/<NAME>', NULL, 'New', NULL, 'Paperback', 99, NULL, 'Retelling by <NAME><br> Illustrations by <NAME>-Albano<br> <br> Pilandok is a well-loved folk hero especially popular in the Muslim areas. His name is the Filipino equivalent for the mouse deer. In folk tales, Pilandok is portrayed as a clever creature who loves to play tricks—and his tricks often land him in difficult situations! However, it is also because of his wit that he is saved, unscathed, every time. <br><br> Isang kilalang tauhan si Pilandok sa mga kuwentong bayan ng Timog, lalo na sa lugar ng mga Muslim. Ang kaniyang pangalan ay ang salin para sa ''mouse deer.'' Sa mga kuwentong bayan, si Pilandok ay matalino at palabiro kaya''t malimit siyang nalalagay sa panganib. Ngunit, ang kaniyang katalinuhan din ang sumasagip sa kaniya.', 32, 27, 0, NULL, 1, NULL, NULL, 0), (151, 1, 12, 'Best Buy Popsicle Sticks 100pieces Red', 122, NULL, 'English', NULL, NULL, 'New', NULL, NULL, 99, NULL, 'If you already have a glue gun with glue sticks, you can already start building all sorts of nifty stuff with 100pieces of popsicle sticks. For example, miniature houses, boats, buildings, just to name a few. And you can easily find many more DIY (Do-It-Yourself) examples on Youtube. I recommend 7 year olds to start building things with popsicle sticks, together with their parents.<br><br>Check out our PROMOS category if you want to get all 3 items (glue gun, glue sticks, and popsicle sticks) in one go!', NULL, 66, 0, NULL, 1, NULL, NULL, 0), (152, 1, 12, 'Best Buy Popsicle Sticks 100pieces Yellow', 122, NULL, 'English', NULL, NULL, 'New', NULL, NULL, 99, NULL, 'If you already have a glue gun with glue sticks, you can already start building all sorts of nifty stuff with 100pieces of popsicle sticks. For example, miniature houses, boats, buildings, just to name a few. And you can easily find many more DIY (Do-It-Yourself) examples on Youtube. I recommend 7 year olds to start building things with popsicle sticks, together with their parents.<br><br>Check out our PROMOS category if you want to get all 3 items (glue gun, glue sticks, and popsicle sticks) in one go!', NULL, 50, 0, NULL, 1, NULL, NULL, 0), (153, 1, 12, 'Best Buy Popsicle Sticks 300pieces Yellow', 206, NULL, 'English', NULL, NULL, 'New', NULL, NULL, 99, NULL, 'If you already have a glue gun with glue sticks, you can already start building all sorts of nifty stuff with 300pieces of popsicle sticks. For example, miniature houses, boats, buildings, just to name a few. And you can easily find many more DIY (Do-It-Yourself) examples on Youtube. I recommend 7 year olds to start building things with popsicle sticks, together with their parents.<br><br>Check out our PROMOS category if you want to get all 3 items (glue gun, glue sticks, and popsicle sticks) in one go!', NULL, 57, 0, NULL, 1, NULL, NULL, 0), (154, 1, 12, 'Glue Gun Small Acura ZD-5', 200, NULL, 'English', NULL, NULL, 'New', NULL, NULL, 99, NULL, 'If you already have glue sticks and popsicle sticks, you can already start building all sorts of nifty stuff. For example, miniature houses, boats, buildings, just to name a few. And you can easily find many more DIY (Do-It-Yourself) examples on Youtube. I recommend 7 year olds to start building things with popsicle sticks, together with their parents.<br><br>Check out our PROMOS category if you want to get all 3 items (glue gun, glue sticks, and popsicle sticks) in one go! ', NULL, 56, 0, NULL, 1, NULL, NULL, 0), (155, 1, 12, 'Glue Stick Small 6pieces', 96, NULL, 'English', NULL, NULL, 'New', NULL, NULL, 99, NULL, 'If you already have a glue gun and popsicle sticks, you can already start building all sorts of nifty stuff. For example, miniature houses, boats, buildings, just to name a few. And you can easily find many more DIY (Do-It-Yourself) examples on Youtube. I recommend 7 year olds to start building things with popsicle sticks, together with their parents.<br><br>Check out our PROMOS category if you want to get all 3 items (glue gun, glue sticks, and popsicle sticks) in one go! ', NULL, 54, 0, NULL, 1, NULL, NULL, 0), (156, 1, 5, 'PROMO-Glue Gun, Glue Sticks 6pieces, Popsicle Sticks 100pieces', 274, NULL, 'English', NULL, NULL, 'New', NULL, NULL, 99, NULL, 'With these 3 items, you can build all sorts of nifty stuff. For example, miniature houses, boats, buildings, just to name a few. And you can easily find many more DIY (Do-It-Yourself) examples on Youtube. I recommend 7 year olds to start building things with popsicle sticks, together with their parents.', NULL, 59, 0, NULL, 1, NULL, NULL, 0), (157, 1, 2, 'The Sandman Book of Dreams', 375, NULL, 'English', '<NAME>/<NAME> (Eds.)', NULL, NULL, NULL, 'Paperback', 3, NULL, 'This book contains over 16 short stories from various authors who have been inspired by the bestselling graphic novel, ''''The Sandman'''', by <NAME>.<br><br> Edited by Neil, himself, and <NAME>, I particularly like ''''The Mender of Broken Dreams'''' by <NAME>. Collins.', NULL, 37, 0, NULL, 1, NULL, NULL, 1), (158, 2, 6, 'Fantastic four forever story arc set', 800, NULL, 'English', NULL, NULL, 'VF-NM', NULL, 'Paperback', 1, NULL, '<br>issues 600-604', NULL, 33, 0, NULL, 1, NULL, NULL, 0), (159, 2, 6, 'amazing spider-man comics lot', 800, NULL, 'English', NULL, NULL, 'VF-NM', NULL, 'Paperback', 1, NULL, '<br> issues 674-681', NULL, 55, 0, NULL, 1, NULL, NULL, 0), (160, 2, 6,'superior spider-man complete goblin nation story arc', 1000, NULL, 'English', NULL, NULL, 'VF', NULL, 'Paperback', 1, NULL, '<br>issues 27-31', NULL, 27, 0, NULL, 1, NULL, NULL, 0), (161, 2, 6,'spider-man no turning back story arc', 600, NULL, 'English', NULL, NULL, 'VF-NM', NULL, 'Paperback', 1, NULL, '<br> complete no turning back story arc<br> issues 688-691', NULL, 23, 0, NULL, 1, NULL, NULL, 0), (162, 2, 6,'spider-man ends of the earth story arc', 1200, NULL, 'English', NULL, NULL, 'VF-NM', NULL, 'Paperback', 1, NULL, '<br>complete ends of the earth story arc<br> issues 682-687', NULL, 26, 0, NULL, 1, NULL, NULL, 0), (163, 2, 6, 'Spider-man spider island story arc set', 1200, NULL, 'English', NULL, NULL, 'VF-NM', NULL, 'Paperback', 1, NULL, '<br>spider-man complete spider island comic set<br> issues 666-673', NULL, 31, 0, NULL, 1, NULL, NULL, 0), (164, 2, 6, 'civil war II', 1400, NULL, 'English', NULL, NULL, 'NM', NULL, 'Paperback', 1, NULL, '<br>civil war II complete set<br> issues 0-8', NULL, 29, 0, NULL, 1, NULL, NULL, 0), (165, 2, 6, 'battleworld thors set', 400, NULL, 'English', NULL, NULL, 'VF-NM', NULL, 'Paperback', 1, NULL, '<br>complete set 1-4', NULL, 28, 0, NULL, 1, NULL, NULL, 0), (166, 2, 6, 'dc comics presents deadman story arc', 500, NULL, 'English', NULL, NULL, 'VF-NM', NULL, 'Paperback', 1, NULL, '<br>1st story arc of dc comics presents new 52<br> deadman<br> 1-5 ', NULL, 27, 0, NULL, 1, NULL, NULL, 0), (167, 2, 6, 'warland comics set + extra', 1200, NULL, 'English', NULL, NULL, 'VG-F', NULL, 'Paperback', 1, NULL, '<br>all you see in the pic is included', NULL, 0, 0, NULL, 1, NULL, NULL, 0), (168, 2, 6, 'green lantern new 52', 400, NULL, 'English', NULL, NULL, 'VF-NM', NULL, 'Paperback', 1, NULL, '<br>1-5', NULL, 26, 0, NULL, 1, NULL, NULL, 0), (169, 2, 6, 'captain atom new 52', 300, NULL, 'English', NULL, NULL, 'VF-NM', NULL, 'Paperback', 1, NULL, '<br>1-5', NULL, 33, 0, NULL, 1, NULL, NULL, 0), (170, 2, 6,'spaceman set', 900, NULL, 'English', NULL, NULL, 'VF-NM', NULL, 'Paperback', 1, NULL, '<br>complete 1-9', NULL, 25, 0, NULL, 1, NULL, NULL, 0), (171, 2, 6, 'penguin pain and prejudice set', 600, NULL, 'English', NULL, NULL, 'VF-NM', NULL, 'Paperback', 1, NULL, '<br>1-5 complete', NULL, 27, 0, NULL, 1, NULL, NULL, 0), (172, 2, 6,'superman new 52', 600, NULL, 'English', NULL, NULL, 'VF-NM', NULL, 'Paperback', 1, NULL, '<br>1-6', NULL, 32, 0, NULL, 1, NULL, NULL, 0), (173, 2, 6, 'green arrow new 52 number 1', 400, NULL, 'English', NULL, NULL, 'NM', NULL, 'Paperback', 1, NULL, NULL, NULL, 28, 0, NULL, 1, NULL, NULL, 0), (174, 2, 6, 'animal man new 52', 450, NULL, 'English', NULL, NULL, 'VF', NULL, 'Paperback', 1, NULL, '<br>1-5<br> issue 1 is 2nd print', NULL, 56, 0, NULL, 1, NULL, NULL, 0), (175, 2, 6,'swamp thing new 52', 400, NULL, 'English', NULL, NULL, 'VF', NULL, 'Paperback', 1, NULL, '<br>1-5', NULL, 29, 0, NULL, 1, NULL, NULL, 0), (176, 2, 6, 'x-men number 12', 8000, NULL, 'English', NULL, NULL, 'VG', NULL, 'Paperback', 1, NULL, '<br>BEST OFFER AVAILABLE<br> 1st appearance juggernaut', NULL, 27, 0, NULL, 1, NULL, NULL, 0), (177, 2, 6, 'ultimate comics new spider-man set', 4500, NULL, 'English', NULL, NULL, 'VF-NM', NULL, 'Paperback', 1, NULL, '<br>complete set 1-28', NULL, 30, 0, NULL, 1, NULL, NULL, 0), (178, 2, 6,'spider-men complete set', 1200, NULL, 'English', NULL, NULL, 'VF-NM', NULL, 'Paperback', 1, NULL, '<br>complete set<br> 1-5', NULL, 35, 0, NULL, 1, NULL, NULL, 0), (179, 2, 6, 'INDESTRUCTIBLE hulk set', 1500, NULL, 'English', NULL, NULL, 'F', NULL, 'Paperback', 1, NULL, '<br>complete set 1-20 + extras', NULL, 36, 0, NULL, 1, NULL, NULL, 0), (180, 2, 6,'sub-mariner number 8', 900, NULL, 'English', NULL, NULL, 'VG-F', NULL, 'Paperback', 1, NULL, '<br>BEST OFFER AVAILABLE', NULL, 28, 0, NULL, 1, NULL, NULL, 0), (181, 2, 8, 'BTAS killer croc', 800, NULL, 'English', NULL, NULL, 'New', NULL, NULL, 1, NULL, NULL, NULL, 50, 0, NULL, 1, NULL, NULL, 0), (182, 2, 8, 'punisher art print', 1000, NULL, 'English', NULL, NULL, 'New', NULL, NULL, 1, NULL,'signed by artist <NAME><br> 11''''x17''''', NULL, 28, 0, NULL, 1, NULL, NULL, 0), (183, 2, 8, 'BTAS Mr. Freeze', 800, NULL, 'English', NULL, NULL, 'New', NULL, NULL, 1, NULL, NULL, NULL, 45, 0, NULL, 1, NULL, NULL, 0), (184, 2, 8, 'BTAS scarecrow', 800, NULL, 'English', NULL, NULL, 'New', NULL, NULL, 1, NULL, NULL, NULL, 61, 0, NULL, 1, NULL, NULL, 0), (185, 2, 8, 'captain america cards', 200, NULL, 'English', NULL, NULL, 'New', NULL, NULL, 1, NULL, NULL, NULL, 28, 0, NULL, 1, NULL, NULL, 0), (186, 2, 8, 'Venom marvel toybiz 90s', 700, NULL, 'English', NULL, NULL, 'New', NULL, NULL, 1, NULL, 'MOC', NULL, 27, 0, NULL, 1, NULL, NULL, 0), (187, 2, 8, 'Morbius', 400, NULL, 'English', NULL, NULL, 'New', NULL, NULL, 1, NULL, NULL, NULL, 25, 0, NULL, 1, NULL, NULL, 0), (188, 2, 8, 'Rogue', 400, NULL, 'English', NULL, NULL, 'New', NULL, NULL, 1, NULL, NULL, NULL, 26, 0, NULL, 1, NULL, NULL, 0), (189, 2, 8, 'Carnage', 600, NULL, 'English', NULL, NULL, 'New', NULL, '', 1, NULL, NULL, NULL, 25, 0, NULL, 1, NULL, NULL, 0), (190, 2, 8, 'captain america art print', 1000, NULL, 'English', NULL, NULL, 'New', NULL, NULL, 1, NULL,'signed by artist <NAME><br> 11''''x17''''', NULL, 30, 0, NULL, 1, NULL, NULL, 0), (191, 2, 8,'silver surfer', 800, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL, 25, 0, NULL, 1, NULL, NULL, 0), (192, 2, 8, 'US agent', 500, NULL, 'English', NULL, NULL, 'New', NULL, NULL, 1, NULL, NULL, NULL, 26, 0, NULL, 1, NULL, NULL, 0), (193, 2, 8, 'talking venom', 700, NULL, 'English', NULL, NULL, 'New', NULL, NULL, 1, NULL, 'in good working condition', NULL, 25, 0, NULL, 1, NULL, NULL, 0), (194, 2, 8, 'deathlok', 650, NULL, 'English', NULL, NULL, 'New', NULL, NULL, 1, NULL, NULL, NULL, 30, 0, NULL, 1, NULL, NULL, 0), (195, 2, 8,'scarlet spider', 850, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL, 26, 0, NULL, 1, NULL, NULL, 0), (196, 2, 8, 'green goblin marvel 90s', 400, NULL, 'English', NULL, NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL, 34, 0, NULL, 1, NULL, NULL, 0), (197, 2, 8, 'black widow marvel 90s', 400, NULL, 'English', NULL, NULL, 'New', NULL, NULL, 1, NULL, NULL, NULL, 53, 0, NULL, 1, NULL, NULL, 0), (198, 2, 8, 'captain marvel', 600, NULL, 'English', NULL, NULL, 'New', NULL, NULL, 1, NULL, NULL, NULL, 27, 0, NULL, 1, NULL, NULL, 0), (199, 2, 8, 'iron fist marvel 90s', 800, NULL, 'English', NULL, NULL, 'New', NULL, NULL, 1, NULL, NULL, NULL, 24, 0, NULL, 1, NULL, NULL, 0), (200, 2, 8, 'Falcon marvel 90s', 500, NULL, 'English', NULL, NULL, 'New', NULL, NULL, 1, NULL, NULL, NULL, 29, 0, NULL, 1, NULL, NULL, 0), (201, 2, 8, 'bullseye and electra', 700, NULL, 'English', NULL, NULL, 'New', NULL, NULL, 1, NULL, NULL, NULL, 59, 0, NULL, 1, NULL, NULL, 0), (202, 2, 8, 'cyclops and jean grey marvel 90s', 700, NULL, 'English', NULL, NULL, 'New', NULL, NULL, 1, NULL, NULL, NULL, 32, 0, NULL, 1, NULL, NULL, 0), (203, 2, 8, 'DD marvel toybiz 90s', 500, NULL, 'English', NULL, NULL, 'New', NULL, NULL, 1, NULL, NULL, NULL, 28, 0, NULL, 1, NULL, NULL, 0), (204, 2, 8,'metal gear liquid snake action figure', 1500, NULL, 'English', NULL, NULL, 'New', NULL, NULL, 1, NULL, 'complete and in good condition', NULL, 28, 0, NULL, 1, NULL, NULL, 0), (205, 2, 8, 'green goblin marvel toybiz 90s', 600, NULL, 'English', NULL, NULL, 'New', NULL, NULL, 1, NULL, 'MOC', NULL, 28, 0, NULL, 1, NULL, NULL, 0), (206, 4, 12, 'head and shoulders apple fresh shampoo 170ml', 196, NULL, 'English', NULL, NULL, 'New', NULL, NULL, 99, NULL, NULL, NULL, 29, 0, NULL, 1, NULL, NULL, 0), (207, 4, 11, 'Ligo Sardines Easy Open Tomato Chili 155g 6cans', 166, NULL, 'English', NULL, NULL, 'New', NULL, NULL, 99, NULL, 'I remember when I did homestay in the mountains of Antipolo, I saw people combining sardines with instant noodles. It was an inexpensive recipe for the people there. Now that I''m living in a valley in the Philippines, I still eat sardines, particularly Ligo Sardines with tomato and chili sauce, because when I don''t want to spend time preparing and cooking food, I can just pick a can, open it using its built-in opener, pour the contents on top of steaming rice, and then, without having to cook or heat it anymore, I''m already ready to eat. ', NULL, 78, 0, NULL, 1, NULL, NULL, 0), (208, 1, 2, 'A Truck Full of Money', 500, NULL, 'English', '<NAME>', NULL, 'Used - Very Good', NULL, 'Paperback', 1, NULL, NULL, NULL, 46, 0, NULL, 1, NULL, NULL, 0), (209, 1, 2, 'Made to Stick', 550, NULL, 'English', 'Chip Heath/<NAME>', NULL, 'Used - Good', NULL, 'Paperback', 2, NULL, 'I have often seen Chip and Dan Heath''s book, ''''Made to Stick'''', mentioned by other authors. It describes six key qualities of an idea for it to stick: <b>''''SUCCES''''</b><br><br> 1) <b>S</b>implicity<br> 2) <b>U</b>nexpectedness<br> 3) <b>C</b>oncreteness<br> 4) <b>C</b>redibility<br> 5) <b>E</b>motional<br> 6) <b>S</b>tories<br> <br> But for you to understand what the authors mean by these words, you may actually have to get a copy of the book and read their examples.', NULL, 34, 0, NULL, 1, NULL, NULL, 0), (210, 1, 2, 'Mountains Beyond Mountains', 500, NULL, 'English', 'Tracy Kidder', NULL, 'Used - Good', NULL, 'Hardcover', 1, NULL, NULL, NULL, 26, 0, NULL, 1, NULL, NULL, 0), (211, 1, 2, 'My Stroke of Insight', 500, NULL, 'English', '<NAME>, Ph.D.', NULL, 'Used - Good', NULL, 'Hardcover', 1, NULL, NULL, NULL, 30, 0, NULL, 1, NULL, NULL, 0), (212, 1, 2, 'Presentation Zen', 500, NULL, 'English', '<NAME>', NULL, 'Used - Good', NULL, 'Paperback', 2, NULL, 'I remember taking the author''s class back in Japan as an exchange student. It was on cross-cultural communication. We discussed about direct and indirect communication, how some cultures are more high-touch than others, and so on. We also had to write a journal of our soujourn. <br><br> Two things I remember about our teacher: 1) he was a big promoter of Apple products, like the MacBook, and 2) whenever we met, he would greet me by my first name. The second one stuck with me after I returned to my home country, the Philippines. I remember testing it out by greeting people I met with their first names. I had a feeling that somehow, the person had to also remember what my first name was, and in that way, remembered me. <br><br> His book, ''''Presentation Zen'''', offers advice on how to make aesthetically appealing presentations by drawing from the teachings of Zen. If you want to learn about Zen ''''and the Art of Making Great Presentations'''', you can check out this book. ', NULL, 37, 0, NULL, 1, NULL, NULL, 0), (213, 1, 2, 'Surely You''re Joking, <NAME>', 500, NULL, 'English', '<NAME>', NULL, 'Used - Good', NULL, 'Paperback', 2, NULL, NULL, NULL, 29, 0, NULL, 1, NULL, NULL, 1), (214, 1, 2, 'The Pleasure of Finding Things Out', 500, NULL, 'English', '<NAME>', NULL, 'Used - Good', NULL, 'Paperback', 2, NULL, NULL, NULL, 25, 0, NULL, 1, NULL, NULL, 0), (215, 1, 2, 'The Road Less Traveled', 350, NULL, 'English', '<NAME>, M.D.', NULL, 'Used - Good', NULL, 'Paperback', 2, NULL, 'I have more books from the author, albeit I haven''t read all of them. <br><br> I may have likely first read <NAME> from Theology of Marriage class, particularly this book, ''''The Road Less Traveled''''. <br><br> Years later, I would read the other portions of the same book, and find the story about Orestes (and the Furies/Eumenides) quite interesting.', NULL, 35, 0, NULL, 1, NULL, NULL, 1), (216, 1, 2, 'The Youngest Science', 400, NULL, 'English', '<NAME>', NULL, 'Used - Good', NULL, 'Hardcover', 1, NULL, NULL, NULL, 24, 0, NULL, 1, NULL, NULL, 0), (217, 1, 2, 'When All You''ve Ever Wanted Isn''t Enough', 400, NULL, 'English', '<NAME>', NULL, 'Used - Very Good', NULL, 'Paperback', 1, NULL, NULL, NULL, 23, 0, NULL, 1, NULL, NULL, 1), (218, 1, 2, 'The Myth of Sisyphus', 400, NULL, 'English', '<NAME>', NULL, 'Used - Acceptable', NULL, 'Paperback', 1, NULL, NULL, NULL, 25, 0, NULL, 1, NULL, NULL, 0), (219, 1, 2, 'Musicophilia', 500, NULL, 'English', '<NAME>', NULL, 'Used - Acceptable', NULL, 'Hardcover', 2, NULL, NULL, NULL, 24, 0, NULL, 1, NULL, NULL, 0), (220, 1, 2, 'Thinking, Fast and Slow', 950, NULL, 'English', '<NAME>', NULL, 'Used - Acceptable', NULL, 'Hardcover', 1, NULL, NULL, NULL, 25, 0, NULL, 1, NULL, NULL, 0), (221, 1, 2, 'The World is Flat
1,514
页面 3.怕刷新,刷新请求,需要服务端配合; 监听事件:popstate history.back() history.forward() history.go() ``` ## 路由钩子 ### 路由解析流程? ```js 1、导航被触发 2、在失活的组件里调用离开守卫 beforeRouterleave 3、调用全局的 beforeEach 守卫 4、在重用的组件里调用 beforeRouteUpdate 守卫 5、在路由配置里调用 beforEnter //路由独享 6、解析异步路由组件 7、在被激活的组件里调用 beforeRouteEnter 8、调用全局的 beforeResolve 守卫 9、导航被确认 10、调用全局的 afterEach 钩子 11、触发 DOM 更新 12、在创建好的实例调用 beforeRouteEnter 守卫中传给 next 的回调函数 作者:woniu12 链接:https://www.jianshu.com/p/96cfc1b9ff21 来源:简书 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 ``` ![img](../image/20190616165857285.png) 1. 全局守卫 - router.beforeEach 全局前置守卫 ```js const router = new VueRouter({... }) router.beforeEach((to, from, next) => { //... }) ``` `to: Route:`即将要进入的目标 路由对象 `from: Route:` 当前导航正要离开的路由 next: Function:`一定要调用该方法来`resolve`这个钩子。执行效果`依赖 next 方法的调用参数。 - router.beforeResolve 全局解析守卫 ```js 在导航被确认之前,同时在所有组件内守卫和异步路由组件被解析之后,解析守卫就被调用。 ``` - router. afterEach 全局后置钩子 ```js 不会接受 next 函数也不会改变导航本身: router.afterEach((to, from) => { //... }) ``` 3. 路由独享守卫 - beforeEnter ```js const router = new VueRouter({ routes: [ { path: '/foo', component: Foo, beforeEnter: (to, from, next) => { //... } } ] }) ``` 4. 组件内守卫 - beforeRouteEnter 不能获取组件实例this;next(vm=>{可获取实例}) - beforeRouteUpdate - beforeRouteLeave ```js const Foo = { template: `...`, beforeRouteEnter (to, from, next) { // 在渲染该组件的对应路由被 confirm 前调用 // 不!能!获取组件实例 `this` // 因为当守卫执行前,组件实例还没被创建 }, //不过,你可以通过传一个回调给 next来访问组件实例。 //在导航被确认的时候执行回调,并且把组件实例作为回调方法的参数。 beforeRouteEnter (to, from, next) { next(vm => { // 通过 `vm` 访问组件实例 }) }, beforeRouteUpdate (to, from, next) { // 在当前路由改变,但是该组件被复用时调用 // 举例来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候, // 由于会渲染同样的 Foo 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。 // 可以访问组件实例 `this` }, // 该组件离开跳转到另外的组件时触发该钩子,常应用于用户表单,当用户填了一部分内容,需要提醒用户是否离开页面 beforeRouteLeave(to, from, next){ beforeRouteLeave (to, from, next) { // 导航离开该组件的对应路由时调用 // 可以访问组件实例 `this` } } ``` ## vue-router是如何响应 路由参数变化的: ```js https://blog.csdn.net/weixin_41639609/article/details/88721627 watch: { '$route' (to, from) { // 对路由变化作出响应... } } ``` ```js beforeRouteUpdate (to, from, next) { // react to route changes... // don't forget to call next() } ``` ## $route和$router的区别 ``` 答:$route是“路由信息对象”,包括path,params,hash,query,fullPath,matched,name等路由信息参数。而$router是“路由实例”对象包括了路由的跳转方法,钩子函数等。 ``` # keep-alive ```js 是 Vue 内置的一个组件,防止重新渲染,把组件缓存; 参数解释 include - 字符串或正则表达式,只有名称匹配的组件会被缓存 exclude - 字符串或正则表达式,任何名称匹配的组件都不会被缓存 <!-- 逗号分隔字符串,只有组件a与b被缓存。 --> <keep-alive include="a,b"> <component></component> </keep-alive> <!-- 正则表达式 (需要使用 v-bind,符合匹配规则的都会被缓存) --> <keep-alive :include="/a|b/"> <component></component> </keep-alive> <!-- Array (需要使用 v-bind,被包含的都会被缓存) --> <keep-alive :include="['a', 'b']"> <component></component> </keep-alive> ``` # vue高阶组件 [http://hcysun.me/2018/01/05/%E6%8E%A2%E7%B4%A2Vue%E9%AB%98%E9%98%B6%E7%BB%84%E4%BB%B6/](http://hcysun.me/2018/01/05/探索Vue高阶组件/) https://blog.csdn.net/z609373067/article/details/81258966 ```js function WithConsole (WrappedComponent) { return { mounted () { console.log('I have already mounted') }, props: WrappedComponent.props, render (h) { const slots = Object.keys(this.$slots) .reduce((arr, key) => arr.concat(this.$slots[key]), []) .map(vnode => { vnode.context = this._self return vnode }) return h(WrappedComponent, { on: this.$listeners, props: this.$props, // 透传 scopedSlots scopedSlots: this.$scopedSlots, attrs: this.$attrs }, slots) } } } ``` ======================= File: 问题/问题.md ======================= # 1.vue首次打开慢问题 解决: ```js 1.路由改成异步加载,按需加载 2.打包时不生成.map文件 3.打包时进行压缩打包-gzip,生成gz文件 4.内部引用改成外部链接,使用cdn 5.去掉console.log ``` 详情: - >1. 路由改成异步加载,按需加载 > >```js >{ > path:'', > component:()=>import('./login') >} >``` > >2. 打包时不生成.map文件 > >```js >vue.config.js > >const path = require("path"); >const CompressionWebpackPlugin = require("compression-webpack-plugin"); >const productionGzipExtensions = ["js", "css"]; >const isProduction = process.env.NODE_ENV === "production"; > >module.exports = { >baseUrl: process.env.NODE_ENV === "production"? "./" : "", >// productionSourceMap: process.env.NODE_ENV === "production"? false : true, >productionSourceMap: false,//不打包出map文件 >configureWebpack: config => { >if (isProduction) { >config.plugins.push( > new CompressionWebpackPlugin({ > algorithm: "gzip", > test: new RegExp("\\.(" + productionGzipExtensions.join("|") + ")$"), > threshold: 10240, > minRatio: 0.8 > }) >); >} >} >}; >``` > >3. 打包时进行压缩打包-gzip > >```js >也称 http压缩 >流程 >1.找到 config/index.js >2.找到 productionGzip: false >3.将 false 改为 true >4.npm i -D compression-webpack-plugin >5.重新允许 npm run build >6.可以看到生成了一些 gz 文件 >7.其他都不用变,把原来的代码和新生成的 gz 文件一并提交到服务器上就行了 >8.找运维给服务器开启 gzip 即可 >``` > >```js >安装: > npm i -D compression-webpack-plugin >``` > >```js >vue.config.js > >const path = require('path') >const CompressionWebpackPlugin = require('compression-webpack-plugin') >const productionGzipExtensions = ['js', 'css'] >const isProduction = process.env.NODE_ENV === 'production' > >module.exports = { >configureWebpack: config => { >if (isProduction) { >config.plugins.push(new CompressionWebpackPlugin({ > algorithm: 'gzip', > test: new RegExp('\\.(' + productionGzipExtensions.join('|') + ')$'), > threshold: 10240, > minRatio: 0.8 > }) >) >} >} >} >``` > >写法二![img](../image/1035310-20180929165250419-525080601.png) > >```js >const path = require('path'); >const CompressionPlugin = require('compression-webpack-plugin'); >module.exports = { > >/*从这里开始添加*/ >configureWebpack: config => { > if(process.env.NODE_ENV === 'production'){ > return { > plugins: [new CompressionPlugin({ > test: /\.js$|\.html$|\.css/, > threshold: 10240, > deleteOriginalAssets: false > })] > } > } >} >/*到这里结束*/ > >}; >``` > >```js >如果浏览器支持Gzip则请求头设置: >浏览器请求头:设置 Accept-Encoding: gzip > >服务器响应:设置 Content-Encoding:gzip >https://www.cnblogs.com/LO-ME/p/7377082.html > >本地http-server模拟响应gz文件:运行命令 >http-server -gzip -o >``` > > > >4. 内部引用改成外部链接,使用cdn > >```js >https://cdn.bootcss.com/mint-ui/2.21/index.js > ><script >src="https://code.jquery.com/jquery-3.1.0.js" >integrity="<KEY> >crossorigin="anonymous"> ></script> > >module.exports = { >//... >externals: { >jquery: 'jQuery' >} >}; > >externals中的key是用于import,value表示的在全局中访问到该对象,就是window.echarts >``` > > > >5. 去掉console.log > >```js >npm install terser-webpack-plugin -D > >module.export = { >configureWebpack: (config)=>{ >if(process.env.NODE_ENV === 'production'){ >config.optimization.minimizer[0].options.terserOptions.compress.drop_console = true >} >} >} > >``` > > > >```js >const path = require('path'); >const CompressionWebpackPlugin = require('compression-webpack-plugin'); >const isProduction = process.env.NODE_ENV === 'production'; > >module.exports = { >configureWebpack: config => { >// 生产模式 >if (isProduction) { > config.externals = { > 'vue': 'Vue', > 'vue-router': 'VueRouter', > 'moment':'moment' > } > // 打包生产.gz包 > config.plugins.push(new CompressionWebpackPlugin({ > algorithm: 'gzip', > test: new RegExp('\\.(' + productionGzipExtensions.join('|') + ')$'), > threshold: 10240, > minRatio: 0.8 > })) > // 添加自定义代码压缩配置 > config.plugins.push( > new UglifyJsPlugin({ > uglifyOptions: { > compress: { > warnings: false, > drop_debugger: true, > drop_console: true, > }, > }, > sourceMap: false, > parallel: true, > }) > ) >} >} > >使用免费的CDN上线没有多久就GG不能用等悲惨故事! >``` > > ======================= File: 13、工具/工具.md ======================= <reponame>WALL-E-WEB/-notes-<filename>13、工具/工具.md # 工具Typora 移动端调试 ```js https://github.com/liriliri/eruda/blob/master/doc/README_CN.md html中加入如下 <script src="//cdn.bootcss.com/eruda/1.5.2/eruda.min.js"></script> <script>eruda.init();</script> ``` 墙 ```js https://www.baacloud32.com/ ``` 思维导图 ```js http://www.mindline.cn/ MindNode ``` 内网穿透 ```js https://www.ngrok.cc/ ``` 映射ip ```js https://jingyan.baidu.com/article/5bbb5a1b15c97c13eba1798a.html ``` 多图转雪碧图 ```js https://www.toptal.com/developers/css/sprite-generator ``` 图片压缩 ```js https://www.upyun.com/webp ``` js30秒练习 ``` https://www.30secondsofcode.org/js/t/object/p/1/ ``` vscode ``` Comment Translate 翻译工具 ``` 加密插件 ```js crypto-js ``` 软件下载 ```js 素材兔 https://www.sucaitu.cc/ ``` 代码练习 ```js https://www.30secondsofcode.org/js/p/1/ ``` 钉图工具 ``` Snipaste ``` 模拟数据工具 ```js Easy Mock https://www.studyinghome.com/ ``` 插件 ``` WOW.js //动画 velocity.js // 动画 ``` 翻墙 ``` Baacloud ``` [廖雪峰的官方网站](https://www.liaoxuefeng.com/) ``` https://www.liaoxuefeng.com/ ``` 获取地址参数 ```js getUrlparam = (param) => { const reg = new RegExp('(^|&)' + param + '=([^&]*)(&|$)'); const r = window.location.search.substr(1).match(reg) || window.location.hash.substring((window.location.hash.search(/\?/)) + 1).match(reg); if (r!= null) { return decodeURIComponent(r[2]); } return null }; ``` https://blog.csdn.net/weixin_45416117/article/details/98348132 资源下载网站 ``` http://uyi2.com/ ``` finalShell ```js https://blog.csdn.net/dya110699/article/details/82561531 进入:tomcat9/中的bin再执行;//而不是根目录bin 关闭: bash startup.sh 启动: bash shutdown.sh  ls 查看信息 cd 进入文件夹 cd.. 返回 //小写 ``` vutur格式换行 ```json "vetur.format.defaultFormatter.html": "js-beautify-html", "vetur.format.defaultFormatterOptions": {   "js-beautify-html": {     "wrap_attributes": "force-aligned",   } }, 注: // 对属性进行换行。 // - auto: 仅在超出行长度时才对属性进行换行。 // - force: 对除第一个属性外的其他每个属性进行换行。 // - force-aligned: 对除第一个属性外的其他每个属性进行换行,并保持对齐。 // - force-expand-multiline: 对每个属性进行换行。 // - aligned-multiple: 当超出折行长度时,将属性进行垂直对齐。 ``` 代码变图 ``` https://carbon.now.sh/ ``` 展示位置地图 ``` http://api.map.baidu.com/lbsapi/creatmap/index.html ``` 富文本编辑器 ``` Tinymce ``` vue国外博客 ``` https://vuedose.tips/ https://alexjover.com/blog/ ``` mitojs ``` 用户行为记录 ``` java书单 ``` https://github.com/itwanger/JavaBooks ``` Apifox ``` Apifox = Postman + Swagger + Mock + JMeter ``` 原子css框架tailwindcss ``` https://www.tailwindcss.cn/docs/responsive-design ``` ======================= File: 14、设计模式/设计模式.md ======================= <reponame>WALL-E-WEB/-notes-<filename>14、设计模式/设计模式.md 《JavaScript设计模式与开发实践》书籍笔记。 # 状态模式 ```js https://github.com/jakesgordon/javascript-state-machine javascript-state-machine ``` ```js var Light = function() { this.currState = FSM.off; this.button = null; } Light.prototype.init = function() { var button = document.createElement('button'); var self = this; button.innerHTML = '已关灯'; this.button = docuemnt.body.appendChild(button); this.button.onclick = function() { self.currState.buttonWasPressed.call(self); } } var FSM = { off: { buttonWasPressed: function() { console.log('关灯'); this.currState = FSM.on; } }, on: { buttonWasPressed: function() { console.log('开灯'); this.currState = FSM.off; } } } var light = new Light(); light.init(); ``` # 模版方法模式 ```js // 类似 java 抽象类 var Parent = function(){}; parent.prototype.method1 = function(){ throw new Error('必须重写方法method1') }; parent.prototype.method2 = function(){ throw new Error('必须重写方法method2') }; parent.prototype.inti = function(){ this.method1(); this.method2(); }; var Child = function(){}; Child.prototype = new Parent(); Child.prototype.method1 = function(){}; // 重写 Child.prototype.method2 = function(){}; // 重写 var child = new Child(); child.init(); ``` 实现方式2 ```js var Parent = function(params){ var method1 =params.method1 || function(){ throw new Error('必须重写方法method1') }; var method2 = params.method2 ||function(){ throw new Error('必须重写方法method2') }; var F = function(){}; F.prototype.init = function(){ method1(); method2(); } return F; }; var Child = new Parent({ method1:function(){}, method2:function(){}, }); Child.init(); ``` # 享元模式 ``` 为了解决性能问题 ``` # 职责链模式 ``` ``` ======================= File: 07、Node/Nodejs.md ======================= <filename>07、Node/Nodejs.md # NodeJS 是一种不需要在浏览器执行的技术; ​ 1.内置了谷歌的V8引擎-高效率的执行 js代码; ​ 2.内置模块 就是写好的 Js代码,类似于jquery.js; 数据库,微服务(Docker); ipconfig 查看ip地址 cls 清屏 ## require-加载规则 ```js require('模块标识') 1.缓存优先, 2. 模块 1.第三方模块: 2.核心模块:已转为二进制,本质是文件 3.引用:'./xxx'; ``` ## npm ```js cnpm-淘宝 npm.taobao.org npm install --global cnpm //使用淘宝镜像 后面使用cnpm npm install 包名 --registry=https://registry.npm.taobao.org 加载改为: npm config set registry https://registry.npm.taobao.org npm init npm init -y //跳过导向一步到位,直到创建依赖项创建 npm install --save 包名 下载并保存依赖项 npm i -S 包名 npm uninstall --save 包名 删除 npm un -S 包名 npm 命令 --help 查看是否成功 npm config list ``` ## 文件系统 #### 文件删除 ```js const fs = require('fs'); fs.unlink("./tex.txt",err)=>{ if(err!=null){ console.log(err.message); }else{ console.log("成功"); } } ``` #### 文件读取 ```js const fs = require('fs'); //异步 第一个参数:读取文件路径; 第二个参数是:一个回调函数 成功: data 数据 err 错误对象 err.message; fs.readFile('url',{encoding:'utf-8'},(err,data)=>{ if(err == null){ console.log(data); }else { cosole.log(err.message); } }); url是相对于小黑框的执行路径而言; url = nodejs执行所在的位置+url; 问题:相对路径不准确,绝对不可移动; 解决: __dirname 执行js文件 所在 的绝对路径//两个下划线 __filename 执行js文件 本身的绝对路径//两个下划线 let filePath = _dirname+'./aa.txt'; ``` #### writeFile() ```js 第一个参数:文件路径; 第二个参数:文件内容; 第三个参数:回调函数; fs.writeFile('url','写入内容',(err)=>{ if(err){ //失败 }else{ //成功 } }) ``` ## path模块-路径 ```js const path = require('path'); let filePath = path.join(__dirname,'url'); 拼接路径 导入本地包 const path = require('path'); // const dbpath = path.join(__dirname, 'utils', 'db.js'); //通过path方法 导入其他包 const db = require(dbpath);//导入包 ``` ## http ```js const http = require("http"); let serverobj =http.createServer((request,reponse)=> { }) request:请求报文,包含浏览器发来的数据 reponse:响应报文对象,包含了和准备了要发送到浏览器的数据 serverobj.listen(8080,(err)=>{ }) locallhost:3747;浏览器请求 request对象,请求报文, request.url:文件路径 request.method:get,post request.headers: request.headers.host:请求记录; ``` ```js 什么是服务器软件? 用来和浏览器软件做通信的软件,接受 分析 业务处理,,, ip 和端口的作用? ip:互联网中唯一标识; port:在电脑中 唯一标识 使用http模块, 1.导包;const http = require("http"); 2.创建;服务器对象 3.启动;服务器软件监听;serverlisten(3747,(err)=>{}); 启动服务器时执行 ``` ## 创建本地服务器 ```js var fs = require("fs"); var path = require("path"); var http = require("http"); var serverobj = createServer((request,response)=>{ var filepath = path.join(__dirname,request.url); fs.readFile(filepath,{'utf-8'},(err,data)=>{ }) }); serverobj.listen(3747,(err)=>{ }) 1.加载核心模块 var http = require("http"); 2.创建 var server = http.cearteServer((request,reponse)=>{ }); 3.服务要干嘛 server.on('request',function(request,response){ console.log('收到客户请求'+request.url); response.write('holllll') response.write('nodejs') response.end(); }) 4.绑定端口号,启动服务 server.listen(3000,function(){ }) resquest.setHearder('Content-Type','text/html;charset-utf-8') ``` ## request-请求报文 ```js request.url 请求的路径 request.method 请求的方式 get/post request.query.key 获取get发送的url?后的key=value request.post request.setHeader('content-type', 'text/html'); 设置 reuqest.getHeader('content-type');// text/html; 获取 reuqest.removeHeader('content-type');//移除 request.headers 打印全部请求头信息--对象形式 request.rawHeaders 全部头信息--数组形式 request.httpVersion 请求的协议方式 ``` ## response-响应报文 ``` response.header response.setHeader(属性名,属性值); response.wriete(); response.end() ``` ## get/post ```js method = 'GET/POST' GET:把数据放到url; POGT:把数据放到 请求报文体 中; 应用场景: GET:为了获取服务器数据;(获取) POST:为了修改改正服务器数据;(提交) ``` ## Express ```js www.express.com.cn //1.下载 //2.导包 const express = require('express'); const body-parser = require('body-parser');//用户post //2.1设置 web 文件夹 为 静态资源文件夹,浏览器可以直接访问 app.use(express.static('web')); //2.2 注册 body-parser 中间件:自动 帮我们把 浏览器 发送来的 post 数据 封装到 request.body 中 app.use(bodyParser.urlencoded({ extended: false })) // parse application/x-www-form-urlencoded app.use(bodyParser.json()) // parse application/json //3. 创建服务器 const app = express(); // 4.注册路由 // 4.1向浏览器发送 响应数据 app.get('/htmll',(req,res)=>{ //1.字符串 res.send('sdfsdfsdsdfdfdfsdf');//写在报文体 //2.JSON // let obj = {name:'kk',age:'dddd'}; // res.send(obj); //JSON.parse(obj)里面执行 }); //4.2获取 浏览器发送来的 get 参数,并打印 app.get('/url',(req,res)=>{ console.log(req.query) }) //4.3post app.post('/reg',function (req,res) { console.log(req.body); console.log(req.body.txtName); console.log(req.body.txtPwd); }) // 5. // 6.启动,设置端口 app.listen(3747,(err)=>{ if (err==null) { console.log('success'); }else{ console.log('启动 失败'); } }) ``` ## multer ```js https://github.com/expressjs/multer/blob/master/doc/README-zh-cn.md //1.导包 //1.1 导入 express 包 const express = require('express') //1.2 创建 express服务器程序对象 const app = express() //1.3 创建 multer 对象,并设置 上传文件夹 var multer = require('multer') var upload = multer({ dest: 'uploads/' })-----------创建文件夹 //2.1设置 web 文件夹 为 静态资源文件夹,浏览器可以直接访问 app.use(express.static('web')); //3.注册路由 (url -> 处理函数 的关系) // 3.3 获取 浏览器 发送来的 post 参数,并打印 app.post('/upload', upload.single('file01'), function (req, res) {-----注册路由 // req.file 是 `file01` 文件的信息 console.log(req.file); // req.body 将具有文本域数据,如果存在的话 console.log(req.body); res.send('上传成功啦~~~' + req.file.filename); }) ``` ```js req.files 是 `photos` 文件数组的信息 { fieldname: 'icon', originalname: '6385682971224b4c33e8e3507fd7a279.png', encoding: '7bit', mimetype: 'image/png', destination: 'uploads', filename: '8c9c56da992fc02ab691a7dca0d0c63e', path: 'uploads\\8c9c56da992fc02ab691a7dca0d0c63e', size: 25978 } ``` ```js req.body 将具有文本域数据,如果存在的话 [Object: null prototype] { name: 'walle', sikll: 'kuku' } ``` # express ## 中间件 - 特点: 1. 使用app.use 注册中间件 函数—-本质是一个函数; 2. 中间件函数有三个固定的参数(request,response,next()); 3. 中间件中 必须调用 next()函数,!!一般放在所有业务执行之后; 4. 【面向切面编程】中间件,不论哪个路由被请求都会 先执行 中间件; ```js 中间件 app.use(function(request,response,next){ }) app.use(express.static('web/'));//暴露文件 app.use(bodyParser.urlencoded({extende:false})); app.use(bodyParser.json()); ``` Router() ```js const express = require('express') let myRouter = express.Router() myRouter.use(function(req,res,next){ next() }) myRouter.get('/htmss',function(req,res){ }) module.exports = myRouter -------------------------- 导入: const myrouter = require('./01myrouter.js') app.use(myrouter) //自定义路由模块 注册 ``` ## hash ```js hash.js npm搜索 ``` # cookie ```js const cookieParser = require('cookie-parser') 注册cookie中间件 app.use(cookieParser()) res.cookie() backurl:'/index' 返回链接 ``` # cookie-session ``` session模块包含cookie-parser所有方法 app.use(cookiesession({ name:'sessionId', keys:['<KEY>'] })) ``` ## 图片验证 ``` svg-captcha ``` ## connect-multipary ```js bodyparser 不支持formdata ``` # 跨域 ```js 浏览器会针对 异步对象 的 异步请求 做 跨域请求. --1.请求添加如下:响应报文加如下 response.setHeader('Access-Control-Allow-Origin','*') 添加到响应报文,允许跨域访问 --2.下载包解决,原理如1; npm i cors const cors = require('cors') 注册cors跨域中间件 app.use(cors()); --3.解决:利用创建script的src请求;避开对http对异步跨域检测 $.ajax({ url:'', method:'get', dataType:'jsonp',//ajax不再使用异步请求,而是使用script标签去请求 cache:false, //不使用缓存,原理:是url产生随机数 success:function(backdata){ eval(backData); } }) 以上操作原理如下: let strhtml = '<script src="跨域地址"></script>' $('body').append(strhtml) --4.通过src写入参数传入服务器, let strhtml = '<script src="跨域地址?fn=fnname"></script>' $('body').append(strhtml) 服务端: let jsmethodname = req.query.fn res.send(jsmethodname +'(参数)') ``` # JSONP ``` ``` # promise 三个状态 ```js pending:进行中 fulfilled:成功 rejected:失败 ``` ```js const fs = require('fs'); function getPromise(fileName) { return new Promise((resolve, reject) => { //读文件 fs.readFile(`./etc/${fileName}.txt`, (err, data) => { if (err == null) { //读文件没有出错(异步成功) resolve(data); } else { //失败 reject(err); } }); }); } //需求: 要先读a, 读完a后读b, 读完b后读c. getPromise('a').then((data)=>{ console.log(data.toString()); //继续读b return getPromise('b'); }).then((data)=>{ console.log(data.toString()); //继续读c return getPromise('c'); }).then((data)=>{ console.log(data.toString()); }).catch((err)=>{ //catch方法用来捕获错误信息的 }); promise 是一个构造函数 //必须传入一个回调函数,两个参数resolve,reject //把需要异步的代码放到这个构造函数里 //没有错执行resolve //错执行reject //一旦创建即执行 let pm = new Promise((resolve,reject)=>{ fs.readFile('url',(error,data)=>{ if(error){ reject(error) }else{ resolve(data) } }) }) // pm.then((data)=>{ //里面调用数据传入resolve(data) }).then((data)=>{ }) ``` catch ```js 用于捕获错误信息 ``` ## all方法 ```js /读a/b/c文件的promise let pa = getPromise('a'); let pb = getPromise('b'); let pc = getPromise('c'); // 把这三个promise对象,搞成一个promise对象. let pAll = Promise.all([pa,pb,pc]); // 三个promise都异步成功后,才去执行pAll.then的第一个参数函数. // 只要有一个失败了,就去执行catch里面的函数. pAll.then((data)=>{ console.log(data.toString()); }).catch((err)=>{ console.log(err); }); ``` ## race方法 ```js 与all类似 只需一个成功就执行 // 三个promise只需要有一个异步请求成功了,就会去执行p.then的第一个参数函数. // 都失败了,就去执行catch里面的函数. const p = Promise.race([pa, pb, pc]); p.then((data)=>{ console.log(data.toString()); }).catch((err)=>{ console.log(err); }); ``` # 数据库 ```js -- 1.查询 select * from heroinfo -- 2.新增 insert into heroinfo(name,skill,icon) values('孙悟空','金箍棒','3.jpg' ) --3.删除 delete from heroinfo where id=3 delete from heroinfo where id>1 and id<=4 --4.修改 update heroinfo set skill = '七十二变' where id=5 update heroinfo set skill = '77变',icon= '7.jpg' where id = 5 ``` ## mysql ```js var mysql = require('mysql') var connection = mysql.createConnection({//创建连接 host:'127.0.0.1', port:3306,//默认3306,可不写 user:'root', password:'<PASSWORD>', database://数据库名 }) connection.connect()//连接 connection.query('数据库操作语句',function(err,res,fields){ }) connection.end()//关闭连接 ``` ```js 返回 select的返回: [ RowDataPacket { Id: 3, name: 'pppp', skill:'sss', icon:'sss' }, RowDataPacket { Id: 4, name: 'pppp', skill: 'kk', icon: 'kk' }, RowDataPacket { Id: 5, name: 'pppp', skill: 'kuku', icon: 'kk' }, RowDataPacket { Id: 6, name: 'pppp', skill: 'kk', icon: 'kk' } ] insert:的返回 OkPacket{ fieldCount:0 affectedRows: 0,//受影响行数,新增,修改,删除 insertId: 0, //新增操作会 返回新增行id serverStatus: 2,//服务器状态 warningCount: 0, message: '', protocol41: true, changedRows: 0 } ``` # 获取异步值方法 ```js /* * @Description: In User Settings Edit * @Author: your name * @Date: 2019-08-28 19:35:16 * @LastEditTime: 2019-08-28 19:35:25 * @LastEditors: Please set LastEditors */ //1.调函数 function getSomething(cb) { var r = 0; setTimeout(function () { r = 2; cb(r); }, 10); } function compute(x) { alert(x * 2); } getSomething(compute); //2.promise //专门解决由于回调函数引起的问题 function getSomething() { var r = 0; return new Promise(function (resolve) { setTimeout(function () { r = 2; resolve(r); }, 10); }); } function compute(x) { alert(x * 2); } getSomething().then(compute); //3.generator //有中断函数执行的能力 function getSomething() { var r = 0; setTimeout(function () { r = 2; it.next(r); }, 10); } function* compute(it) { var x = yield getSomething(); alert(x * 2); } var it = compute(); it.next(); //4.promise + generator //promise加generator,才是异步的完美方式 function getSomething() { var r = 0; return new Promise(function (resolve) { setTimeout(function () { r = 2; resolve(r); }, 10); }); } function* compute() { var x = yield getSomething(); alert(x * 2); } var it = compute(); it.next().value.then(function (value) { it.next(value); }); //5.async //终极方案:async。 function getSomething() { var r = 0; return new Promise(function (resolve) { setTimeout(function () { r = 2; resolve(r); }, 10); }); } async function compute() { var x = await getSomething(); alert(x * 2); } compute(); ``` # 案例 ### 1.http-简单文件服务器 ```js const http = require('http'); const mime = require('mime'); const path = require('path') const fs = require('fs'); const serverobj = http.createServer((request, response) => { let urlstr = request.url; //获取请求/后的链接 //根据链接 获取mime值, let mimeval = mime.getType(urlstr); //设置response headers中的 Content-Type response.setHeader('Content-Type', mimeval); let filepath = path.join(__dirname, urlstr); //获取地址 fs.readFile(filepath, (err, data) => { if (err == null) { console.log(data); response.end(data); }else{ console.log('请求失败'); } }) }) serverobj.listen(3747,(err)=>{ if(err==null){ console.log('success') } }) ``` ### 2.重定向 ```js const http = require('http'); const url = require('url'); const mime = require('mime'); const server = http.createServer((request,response)=>{ // 如果 浏览器请求的 是页面 9,就发送 302 给 浏览器,告诉他 跳转到 2.html if (request.url.indexOf('9.html')>-1) { // 向 响应报文 头 中 添加 location ,告诉浏览器 要跳转的目标 response.setHeader('location','2.html'); // 向响应报文头中 设置 状态码为 302 response.writeHead(302,'move'); }else if(request.url.indexOf('10.html')>-1){ let mimeval = mime.getType(request.url);//根据获取的url尾部,获取Content-type response.setHeader('Content-type',mimeval+";charset=utf-8") response.write('<script>alert("要跳转了"); window.location = "2.html";</script>'); } response.end(); }) server.listen(3747,(err)=>{ if (err==null) { console.log('启动成功'); }else { console.log('启动失败'); } }) ``` ### 3.获取get数据 ```js <html> <head> <title></title> <meta charset='UTF-8' /> </head> <body> <!-- 表单 Get 方式提交数据 --> <form action="http://192.168.14.134:3747/2.html" method="GET"> <input type="text" name="txtName"> <input type="password" name="<PASSWORD>"> <br> <input type="submit" value="提交"> </form> </body> </html> const http = require('http'); const url = require('url'); const serverobj = http.createServer((request,response)=>{ //a. 获取 浏览器 用 get 方式 传来的 数据 let urlstr = request.url; console.log(urlstr) //b. 使用 url.parse 方法,将 请求的 路径中的 get 参数 转成 对象,存入 url对象.query属性中 let urlobj = url.parse(urlstr,true); console.log(urlobj); }) serverobj.listen(3747,(err)=>{ if (err==null) { console.log('success'); }else{ console.log(' failures'); } }) ``` ### 4.path模块生成路径 ```js const path = require('path'); const fs = require('fs'); //文件夹路径+文件路径 拼接 let filePath = path.join(__dirname,'文件路径'); fs.readFile(filePath,'utf-8',(err,data)=>{ if(err == null){ console.log(data); }else{ cosole.log(err.messge) } }) ``` ### 5.数据库操作封装 ```js const mysql = require('mysql') const connInfo={ host:'127.0.0.1', database:'新数据库2', user:'root', password:'<PASSWORD>' } module.exports = { getHero:function(fn){ let connection = mysql.createConnection(connInfo) connection.connect() connection.query('select * from hero',fn) connection.end() }, addHero:function({name,skill,icon},fn){ let connection = mysql.createConnection(connInfo) connection.connect() connection.query(`insert into hero(name,skill,icon) value('${name}','${skill}','${icon}')`,fn) connection.end() }, deleteHero:function(id,fn){ let connection = mysql.createConnection(connInfo) connection.connect() connection.query(`delete from hero where id=${id}`,fn) connection.end() }, updateHero:function({name,skill,icon,id},fn){ let connection = mysql.createConnection(connInfo) connection.connect() connection.query(`update hero set name = '${name}',skill = '${skill}',icon = '${icon}' where id = ${id}`,fn) connection.end() } } ``` # ES6 ## let 与 const ```js let 无法变量提升 无法重复声明 可以重新赋值 有块级作用域 const 1.无法变量提升 \* 2.无法重复声明 \* 3.无法重新赋值 \* 4.有块级作用域 \* 5.必须声明时就要赋值 ``` ## 解构 ```js ES6 允许按照一定模式,从数组和对象中提取值,对变量进行赋值,这被称为解构(Destructuring)。 这种写法属于“模式匹配” let [foo, [[bar], baz]] = [1, [[2], 3]]; foo // 1 bar // 2 baz // 3 1.解构不成功返回 undefined 2.不完全解构 let [x, y] = [1, 2, 3]; x // 1 y // 2 let [a, [b], d] = [1, [2, 3], 4]; a // 1 b // 2 d // 4 3.如果等号的右边不是数组/对象(不可遍历的结构 /Iterator 接口),会报错; ``` ### 对象解构赋值 ```js 而对象的属性没有次序,变量必须与属性同名, let { bar, foo } = { foo: 'aaa', bar: 'bbb' }; foo // "aaa" bar // "bbb" // 例一 let { log, sin, cos } = Math; 上面代码的例一将Math对象的对数、正弦、余弦三个方法,赋值到对应的变量上 // 例二 const { log } = console; log('hello') // hello 例二将console.log赋值到log变量 let obj = {}; let arr = []; ({ foo: obj.prop, bar: arr[0] } = { foo: 123, bar: true }); obj // {prop:123} arr // [true] ------------默认赋值---做边有值则不覆盖,无则赋值 var {x = 3} = {}; x // 3 var {x, y = 5} = {x: 1}; x // 1 y // 5 var {x: y = 3} = {}; y // 3 var {x: y = 3} = {x: 5}; y // 5 var {x = 3} = {x: undefined}; x // 3 var {x = 3} = {x: null}; x // null 注意点: // 正确的写法 //声明语句不能用() let x; ({x} = {x: 1}); // 错误的写法 let x; {x} = {x: 1}; // SyntaxError: syntax error ``` ### 字符串解构 ```js 字符串被转换成了一个类似数组的对象。 const [a, b, c, d, e] = 'hello'; a // "h" b // "e" c // "l" d // "l" e // "o" 类似数组的对象都有一个length属性,因此还可以对这个属性解构赋值。 let {length : len} = 'hello'; len // 5 ``` ### 函数参数解构赋值 ```js function move({x = 0, y = 0} = {}) { return [x, y]; } move({x: 3, y: 8}); // [3, 8] move({x: 3}); // [3, 0] move({}); // [0, 0] move(); // [0, 0] function move({x, y} = { x: 0, y: 0 }) { return [x, y]; } move({x: 3, y: 8}); // [3, 8] move({x: 3}); // [3, undefined] move({}); // [undefined, undefined] move(); // [0, 0] ``` ### 解构用途 ```js http://es6.ruanyifeng.com/?search=%E3%80%8AGenerator+%E5%87%BD%E6%95%B0%E3%80%8B&x=6&y=3#docs/destructuring 1.变量交换值: [x, y] = [y, x]; 2.函数返回多个值: function example() { return { foo: 1, bar: 2 }; } let { foo, bar } = example(); 3.函数参数的定义: function f({x, y, z}) {... } f({z: 3, y: 2, x: 1}); 4.提取JSON数据: let jsonData = { id: 42, status: "OK", data: [867, 5309] }; let { id, status, data: number } = jsonData; ``` ## 箭头函数 ```js var f = v => v; // 等同于 var f = function (v) { return v; }; var sum = (num1, num2) => num1 + num2; // 等同于 var sum = function(num1, num2) { return num1 + num2; }; var sum = (num1, num2) => { return num1 + num2; } ``` ### 展开运算符 ```js let chinaPerson = { skin: 'yellow', hair: 'black', sayHi: '吃了没' } let zhubo = { skill: '唱,跳,rap', habbit: '打篮球' } let newObj ={ ...chinaPerson, // 将 chinaPerson 的成员 都添加到此 ...zhubo // 将 zhubo 的成员 都添加到此 }; ``` ### 模板字符串 ```js 可以挖坑 ${表达式} ``` # ES6 简要 ## 01. ES6简介 ### 1.1 什么是ES6 ​ ES6其实就是在ES5的基础之上新增了一些语法和提供多了一些api, 使用ES6新增的语法和api, 我们可以快速实现一些功能,而不必使用ES5中写很多代码的方式来实现。比如我要判断1个字符串是否以指定的字符串开始,在ES6中,直接为字符串对象新增了1个方法`startsWtih`就可以轻松的实现这个功能。 ```javascript var str = "heima good"; var res = str.startsWith("hei"); //判断字符串str是否以hei开头 //res就是1个bool值,代表str是否以"hei"开头 ``` ​ ES6就是这么高效,为JavaScripter提供了快速高效的编码方式. ### 1.2 ES6的兼容性 ​ ES6标准于2015年6月正式发布, 经过四年的发展,PC桌面端的主流浏览器最新版本都对ES6实现了最大化的兼容,移动端浏览器基本上实现了对ES6的兼容,NodeJS对ES6绝大部分语法进行了实现。 ​ ES6兼容情况一览表: [传送门](<http://kangax.github.io/compat-table/es6/>) ​ 对于少部分语法不兼容的情况(主要是PC桌面端浏览器), 我们可以使用编译器(如Babel)将我们写的ES6代码转换为ES5的代码,以便让低版本的浏览器可以兼容。具体如何使用Babel,我们将在后续的章节为大家介绍。 ## 02. let与const ### 2.1 他们是什么? ​ `let`与`const`是ES6新增的两个关键字,他们的作用和`var`的作用一样,是用来声明变量的 ```javascript var a = 1; let b = 2; const c = "i love heima"; ``` ### 2.2 let与const的区别 ​ 使用`let`声明的变量,后续可以重新为其赋值;使用`const`声明的变量,要求在声明的同时就进行初始化,但是后续无法再为这个变量进行重新赋值。 ```javascript let a = 10; a = 20; let b; b = "jack"; const c = 10; c = 20; //错误,c是const声明的,变量不能再重新赋值 const d; //错误,使用const声明的变量,必须在声明的同时就初始化. ``` **特别注意**,`const`变量指向1个对象的时候,这个变量的值不能变,但是这个变量指向的对象可以修改. ```javascript const person = { name: "jack", age: 19, gender: "male" }; person.name = "rose"; //可以,并没有修改person变量的值,修改的是person指向的对象的属性的值. person = { name: "rose", age: 18, gender: "female" }; //错误,person变量是被const修饰的,不能再为其赋值. ``` ### 2.3 与var的区别 使用`let`和`const`声明的变量不存在变量提升,有自己的作用域 - 其所在的大括弧中。 ```javascript let a = 1; { let b = 2; console.log(c);//报错,提示变量c未定义 const c = 3; //变量b、c只能在声明b、c变量中的大括弧中访问。 //并且也不存在变量提升 console.log(a); //可以访问 console.log(b);//可以访问 console.log(c); //可以访问 } console.log(a); //可以访问 console.log(b);//不可以访问 console.log(c); //不可以访问` ``` ### 2.4 使用建议 - 能使用const就不要使用let - 能使用let就不要使用var ​ 其实大多数情况下,我们声明的变量后续都不会再重新赋值,所以这种情况,建议使用`const`;如果变量的值后续需要更改,可以使用`let`; `var`关键字请彻底废弃。 ## 03. 箭头函数 ​ 箭头函数是我们之前学习的函数的一种简写方式。 ### 3.1 箭头函数的书写规则 ​ 将普通函数的`function`关键字删掉, 在小括弧与大括弧中间加上1个箭头`=>`,用法与普通函数一样。 ```javascript const add = function (a, b){ const result = a + b; return result; } const sayHi = (a, b) => { const result = a + b; return result; } ``` ![](../../../%E5%89%8D%E7%AB%AF41%E6%9C%9F/07.node-JS/node.js%E9%A2%84%E4%B9%A0%E8%B5%84%E6%96%99/day01/02-%E5%85%B6%E4%BB%96%E8%B5%84%E6%96%99/es6/media/01-arrow.gif) 箭头函数的作用: 让我们声明函数的时候,使用更少的代码,看起来更简洁。 ### 3.2 更简洁的写法 - a. 如果参数只有1个,那么包围参数的小括弧可以省略 ```javascript const isEven = num => { if(num % 2 == 0){ return true; }else{ return false } } ``` - b. 如果函数体只有一句代码,那么包围函数体的大括弧可以省略,并且这句代码的结果会自动作为返回值返回 ```javascript const isEven = num => num % 2 == 0; const res = isEven(10); ``` ### 3.3 箭头函数的使用场景 - 箭头函数本身是1个匿名函数,所以如果你要二次使用,必须得有个变量保存起来. - 箭头函数在回调函数中被经常使用到,代码会显得更简洁。 ```javascript setTimeout(()=>console.log(1),1000); ``` ### 3.4 箭头函数使用注意 - 函数体内的`this`对象,就是定义时所在的对象,而不是使用时所在的对象。 - 不可以使用`arguments`对象,该对象在函数体内不存在。如果要用,可以用 rest 参数代替。 ## 04. 字符串 ### 4.1 模板字符串 ​ 声明字符串我们可以使用单引号和双引号来表示,在ES6中新增了一种声明方式,使用1对撇号来表示。 ```javascript let msg = `大家好, 我是小明 \n哈哈,你好啊 这是1个模板字符串哦 `; ``` - 模板字符串,支持换行,等操作,撇号中的内容会被原样识别。 - 模板字符串还支持变量替换 ```javascript let name1 = "杜子腾"; let name2 = "秦寿生"; let msg = `孔子东游,见两小儿辩斗,问其故。 ${name1}曰:“我以日始出时去人近,而日中时远也。” ${name2}以日初出远,而日中时近也。 ${name1}曰:“日初出大如车盖,及日中则如盘盂,此不为远者小而近者大乎?” ${name2}曰:“日初出沧沧凉凉,及其日中如探汤,此不为近者热而远者凉乎?” 孔子不能决也。 ${name1+"和"+name2}笑曰:“孰为汝多知乎?” `; ``` ### 4.2 字符串新增方法 - `includes()`方法 是否包含子串 - `startsWith()`方法 以指定的串开始 - `endsWith()`方法 以指定的串结尾 - `repeat()`方法 将字符串重复 - `padStart()`方法 头部补全 - `padEnd()`方法 尾部补全 ## 05. 数值Number > ES6为Number新增了一些方法,方便我们更加方便操作Number数据. - `Number.isFinite()` 用来检查一个数值是否为有限的(finite),即不是`Infinity` - `Number.isNaN()` 用来检查一个值是否为`NaN` - es6将全局方法`parseInt()`和`parseFloat()`,移植到`Number`对象上面,行为完全保持不变 - `Number.isInteger()` 用来判断一个数值是否为整数。 ## 06. Math类 ES6对Math对象新增了很多数学方法. [传送门](http://es6.ruanyifeng.com/#docs/number#Math-%E5%AF%B9%E8%B1%A1%E7%9A%84%E6%89%A9%E5%B1%95) 并且新增了1个算术运算符 - 指数运算符 ( ** ) ```javascript const a = 2; const b = 3; const c = 2 ** 3; //2的3次方. ``` ## 07. 函数 ### 7.1 参数默认值 ​ 在声明函数的时候,允许对函数的参数赋一个默认值, 当调用函数时,如果不为指定默认值的参数传值,那么在函数执行的时候,参数的值就是默认值 ```javascript const add = (a, b = 20) => { const res = a + b; console.log(res); } add(10);//在调用函数的时候,只为第1个参数传值,而没有为第2个参数传值。那么第2个参数的值就是其默认值20 add(10, 5);//如果两个参数都传了值,那么参数的值就是传入的值。 ``` ​ 需要注意的是, 如果函数的参数带了默认值,那么带了默认值的参数必须写在参数列表的最后 ```javascript const add = (a = 10, b) => { //报错,带默认值的参数必须放在参数列表的最后. } ``` ​ 这样,别人在调用我们写的函数的时候,一眼就能看出哪些参数是必传参数,哪些参数是可选参数。 ### 7.2 参数是1个对象的时候 ​ 当1个函数的参数是1个对象的时候,按照我们之前的写法,调用者很难知道这个对象的属性有哪些。比如,jQuery的ajax方法,这个方法我们都知道要传入1个对象,但是这个对象要准备哪些属性呢? 除了看文档,真的没有别的方法。在ES6中,为我们提供了一种写法,让调用者看到我们函数的形参就知道要传入哪些属性,代码演示如下 ```javascript //参数直接使用1个大括弧围起来,把属性写在其中. 这就表示参数是1个对象,这个对象中有这么些属性 const ajax = ({url, method, data}) =>{ console.log(url, method, data) } ajax({ url: "aa", method: "get", data: { name: "jack", age: 18 } }); ``` ### 7.3 rest参数(可变参数) ​ 当我们需要某1个函数可以接收任意多个参数的时候,我们之前的做法要么是使用arguments,要么是使用1个数组,在ES6中,借鉴了其它语言中非常流行的一种做法,那就是rest参数. ​ 当形参前面加上`...` 三个点, 就表示这是1个rest参数,这是1个数组,它可以接收多余的实参到这个数组中。 ```javascript const add = (a, b,...args) => { //args就是1个rest参数,它是1个数组,用来存储传入的额外参数. let sum = a + b; for(let index in args){ sum += args[index]; } console.log(sum); } add(1, 2, 3, 4, 5, 6, 7, 8); //1和2分别传给了参数a和b, 后面的所有参数都传给了args数组. ``` ​ **需要注意的是,rest参数只能放在参数列表的最后,并且1个函数最多只能有1个rest参数** ### 7.4 函数参数的尾逗号 ​ 在ES6中,允许在参数列表的最后也加上1个逗号,用来让我们的代码变的可读性更高。 ```javascript const add = (a, b, c,) => { return a + b + c; } add(10,20,30,); ``` ## 08. 数组 ### 8.1 扩展运算符 ​ 其实叫做`展开运算符`更容易理解一些,它可以将1个数组中的元素展开, 一般用在函数的传参中。 ```javascript const add = (a, b, c) => { return a + b + c; } const arr = [10, 20, 30]; add(...arr); //将数组arr展开成单独的10,20,30,传给add函数 ``` ### 8.2 常用扩展方法 - `includes()`, 判断数组中是否包含指定的元素 - `flat()`, 当数组中包含1个数组时,可以将里面的数组拉平,变成1个一维数组。参数代表拉平的层数。`Infinity` 其它方法扩展。 [传送门](<http://es6.ruanyifeng.com/#docs/array>) ## 09. 对象 ### 9.1 属性简洁表示法 ​ 声明对象的时候,如果属性名和属性值都是一样的变量,可以使用简写的形式,代码演示如下。 ```javascript ES5写法: var name = "jack"; var age = 19; var gender = "男"; var person = { name: name, age: age, gender: gender, sayHi: function(){ console.log("你好,hi..."); } } ES6简写形式 const name = "jack"; const age = 19; const gender = "男"; const person = { name, age, gender, //如果属性名,和属性的值使用的是同1个变量,可以这样简写 sayHi(){ console.log("你好,hi..."); }//对象方法也可以简写. } ``` ### 9.2 属性名表达式 在ES5中,要为对象新增1个属性,可以使用这样的代码 ```javascript const p1 = { name: "jack", age: 18 } p1.gender = "男"; p1["weight"] = 140; ``` 在ES6中,为对象新增属性,属性可以使用表达式,像下面这样 ```javascript const p1 = { name: "jack", age: 18 } p1["gen"+"der"] = "男"; p1["wei"+"ght"] = 140; p1["say"+"hi"] = () => { console.log("hi....") } ``` 最终对象是这样的,属性名可以使用拼接。 ![](../../../%E5%89%8D%E7%AB%AF41%E6%9C%9F/07.node-JS/node.js%E9%A2%84%E4%B9%A0%E8%B5%84%E6%96%99/day01/02-%E5%85%B6%E4%BB%96%E8%B5%84%E6%96%99/es6/media/01.png) ### 9.3 属性的可枚举 #### 引入 ​ `for in`可以遍历对象的属性包括方法 ```javascript const p1 = { name: "jack", age: 19, sayHi(){console.log("hi...")} } for(let key in p1){ console.log(p1[key]); } ``` 结果如下 ![](../../../%E5%89%8D%E7%AB%AF41%E6%9C%9F/07.node-JS/node.js%E9%A2%84%E4%B9%A0%E8%B5%84%E6%96%99/day01/02-%E5%85%B6%E4%BB%96%E8%B5%84%E6%96%99/es6/media/02.png) 但是,你有没有想过一个问题,p1对象中只有这些成员吗?还有从父类继承过来的`toString`方法没有被遍历出来,是继承的属性不能被遍历吗? 用代码证实一下 ```javascript function Animal (name) { this.name = name || 'Animal'; this.sleep = function(){ console.log(this.name + '正在睡觉!'); } } Animal.prototype.eat = function(food) { console.log(this.name + '正在吃:' + food); }; Animal.prototype.type = "哺乳动物"; function Cat(){ } Cat.prototype = new Animal(); Cat.prototype.name = "cat" var c1 = new Cat(); for(let key in c1){ console.log(c1[key]); }//证实父类的属性可以被遍历. ``` 证实父类的属性可以被遍历 ![](../../../%E5%89%8D%E7%AB%AF41%E6%9C%9F/07.node-JS/node.js%E9%A2%84%E4%B9%A0%E8%B5%84%E6%96%99/day01/02-%E5%85%B6%E4%BB%96%E8%B5%84%E6%96%99/es6/media/03.png) 那究竟什么样的属性才可以被遍历呢? #### 属性描述对象 > 对象的每一个属性,其实都有1个描述对象,这个描述对象来保存这个属性的描述信息(是否能被遍历,是否可读,默认值...)。 使用 *Object.getOwnPropertyDescriptor()*方法可以获取对象的属性的描述方法. ```javascript const p1 = { name: "jack", age: 19, sayHi(){ console.log("hi..."); } } const desc = Object.getOwnPropertyDescriptor(p1, "name"); //获取p1对象的name属性的描述对象 ``` 属性描述对象描述这个属性的信息如下。 ![](../../../%E5%89%8D%E7%AB%AF41%E6%9C%9F/07.node-JS/node.js%E9%A2%84%E4%B9%A0%E8%B5%84%E6%96%99/day01/02-%E5%85%B6%E4%BB%96%E8%B5%84%E6%96%99/es6/media/04.png) ​ 只有当属性的描述对象的`enumerable`值为`true`的时候,这个属性才会被允许遍历。 ​ 那属性的描述对象的`enumerable`值什么时候才有可能为`false`呢? ​ 当我们使用`Object.getOwnPropertyDescriptor()` 为对象定义属性的时候,可以指定描述对象的`enumerable`的值 ```javascript const p1 = { name: "jack", age: 19, sayHi(){ console.log("hi..."); } } //参数1 要设定属性的对象 //参数2 要设定的属性的名 //参数3 描述对象 Object.defineProperty(p1, "gender", { enumerable: false, value: "男" }); ``` ​ 此时,新增的属性就不能被`for in`遍历了. #### 属性遍历 ##### `for in` 遍历对象 ​ 循环遍历对象自身的和继承的可枚举属性 ##### `Object.keys(obj)` ​ 返回一个数组,包括对象自身的(不含继承的)所有可枚举属性的键名。 ##### `Object.getOwnPropertyNames(obj)` ​ 返回一个数组,包含对象自身的所有属性(包括不可枚举属性)的键名。 ## 10. set > Set是1个类似于数组的数据结构,与数组不同的是,Set中的数据不允许重复,当向Set中添加1个已经存在的数据时,不会成功。 ```javascript const set = new Set(); set.add(1); set.add(2); set.add(3); set.add(2);//不会添加成功,但是不会报错 ``` 常用方法 - `size`属性返回set中数据的个数 - `add()` - `delete()` - `has()` - `clear()` 遍历操作 - `keys()` - `values()` - `entries()` - `forEach()` ### WeakSet > WeakSet和Set一样,都是存储不可重复的数据,与Set的区别有两点 > > 1. WeakSet中只能存储对象. > 2. WeakSet中存储的对象都是弱引用,当外部没有变量指向对象的时候,即使被WeakSet所引用,对象也会被回收。 ## 11. Map > 键值对存储数据,和js中的对象类似,不同的是,js对象中的键只能是字符串,而map中的键可以是任意类型. ```javascript const map = new Map(); const p1 = { name: "jack" } const p2 = { name: "rose" } map.set(p1, p2); //以p1为键,将p2存储到Map对象中. ``` ### 常用方法 - `size`属性 获取Map中键值对的个数 - `set(key, value)` 添加键值对, `key`和`value`可以是任意的类型. 该方法返回当前Map对象. - `get()`根据键获取键对应的值、 - `has(key)` - `delete(key)` - `clear()` - `keys()` - `values()` - `entries()` - `foreach()` ### WeakMap > 与Map类似,WeakMap也是用来存储键值对的集合,与Map的区别有两点 > > 1. WeakMap只接受对象作为键名(null除外) > 2. 其次,`WeakMap`的键名所指向的对象,不计入垃圾回收机制。 ## 12. 迭代器 在ES6中新增了一种遍历方式叫做`for...of`,可以使用它来遍历数组、Map、Set等. ```javascript const arr = [10,20,30,40,50,60,70,80,90,100]; for(let item of arr){ console.log(item); } const set = new Set(arr); for(let item of set){ console.log(item); } const map = new Map(); map.set("name", "jack"); map.set("age", 19); map.set("gender", "男"); for(let item of map){ console.log(item); } ``` 能否使用`for...of`循环遍历我们自己写的对象吗? ```javascript const p1 = { name: "jack", age: 19, gender: "男" } for(let item of p1){ console.log(item); } //报错 无法使用for of遍历p1对象. ``` ![](../../../%E5%89%8D%E7%AB%AF41%E6%9C%9F/07.node-JS/node.js%E9%A2%84%E4%B9%A0%E8%B5%84%E6%96%99/day01/02-%E5%85%B6%E4%BB%96%E8%B5%84%E6%96%99/es6/media/06.png) ### 12.1 for...of的原理 ​ 在使用`for..of`遍历1个对象的时候,先调用这个对象的`Symbol.iterator`方法,这个方法返回1个`迭代器`。每遍历一次,就会调用`迭代器`对象的`next`方法,这个方法会返回1个对象,这个对象包含两个属性,一个是`value`,指定本次遍历得到的结果,还有一个属性是`done`,bool值,代表遍历是否结束,每调用一次`next`方法, 就返回下1个被遍历的值,直到最后一个元素。 ```javascript const arr = [10,20,30,40,50,60,70,80,90,100]; const set = new Set(arr); //1.调用set对象的遍历器方法,返回1个迭代器对象. const iterator = set[Symbol.iterator](); //iterator就是这个迭代器对象. while(true){ let item = iterator.next(); if(item.done){ break; } console.log(item.value); } ``` ### 12.2 实现自己的迭代器 知道了`for...of`的原理后, 如果我们希望我们自己的对象也能被`for...of`遍历,那么就可以这么做 - 为对象添加1个`[Symbol.iterator]`方法。 - 这个方法返回1个对象 - 这个对象需要有1个next方法 - 这个next方法返回1个对象,对象包含`vulue`属性,表示本次遍历的值,包含1个`done`属性,表示本次遍历结束后是否还有数据。 然后保证下次调用next方法的时候 返回的是下1个数据. ```javascript const hmSet = { data: [10,20,30,40,50,60,70,80,90,100], [Symbol.iterator](){ const that = this; let index = 0; return { next: function(){ return { value: that.data[index++], done: index == that.data.lenght + 1 } } } } } for(let item of hmSet){ console.log(item); } ``` ### 12.3 原生实现了迭代器的对象 - Array - Map - Set - String - TypedArray - 函数的 arguments 对象 - NodeList 对象 也就是说,这些对象是可以直接用`for...of`来遍历的。 ======================= File: 面试/js面试题.md ======================= # html-css ## html有哪些常用标签: ```html header nav section article aside footer ``` ## 简述一下html语义化理解: - ```js 让页面的内容结构化,结构更清晰,便于阅读、维护和理解 ``` ## html5新特性,移除了哪些元素 - ```js ``` ## 什么是盒子模型:画出盒子模型 - ``` margin border padding content ``` ## 行内元素有哪些,块级元素有哪些,空元素有哪些 - ```js 行内元素:span, i, em, 块级元素:div,h,ul,li,ol ``` ## display有哪些值,说明他们的作用 - ```js 块转行内:display:inline; 行内转块:display:block; 块、行内元素转换为行内块: display: inline-block; 隐藏:display:none; flex布局:display:flex; ``` ## css选择器有哪些 - ``` ``` ## 解释css sprites 精灵图 雪碧图 - ```js ``` ## 清除浮动的方式: - ``` 单伪类清除: .clearfix::after { content:"."; /*小点兼容低版本火狐*/ display:block; clear:both; height:0; /*去除点的高度*/ visibility:hidden; /*去除小点*/ } .clearfix { *zoom:1; /*兼容低版本IE*/ } ``` ## Flex布局有哪些常见属性: ``` flex-direction: row(默认值):主轴为水平方向,起点在左端。 row-reverse:主轴为水平方向,起点在右端。 column:主轴为垂直方向,起点在上沿。 column-reverse:主轴为垂直方向,起点在下沿。 flex-wrap: nowrap; wrap; wrap-reverse; flex-flow justify-content: flex-start; lex-end; center;space-between;space-around align-items: flex-start; align-content: flex-start; lex-end; center;space-between;space-around ``` ## 水平居中有哪些方法: ```css position:absolute; top:50%; left:50%; margin-top:-50px; margin-left:-50px; position:absolute; top:50%; left:50%; transfrom:translate(-50%,-50%); display:flex; justify-content:center; align-item:center; ``` ## 移动端怎么做适配: ``` 1.媒体查询。 2.js 动态设置 html 的 font-size(rem 为单位)。 3.淘宝提供的解决方案 flexible.js(rem 为单位)。 rem 淘宝适配方案+postcss-pxtorem ``` 2-js 动态设置 ```js <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0" /> (function(doc, win) { var docEl = doc.documentElement, resizeEvt = 'orientationchange' in window? 'orientationchange' :'resize', recalc = function() { var clientWidth = docEl.clientWidth; if (!clientWidth) return; // 设置设计稿的宽度clientWidth为750 if (clientWidth >= 750) { docEl.style.fontSize = '75px'; } else { // 设置设计稿的宽度clientWidth为750 docEl.style.fontSize = 75 * (clientWidth / 750) + 'px'; }; }; if (!doc.addEventListener) return; win.addEventListener(resizeEvt, recalc, false); doc.addEventListener('DOMContentLoaded', recalc, false); })(document, window); ``` 3-淘宝提供的解决方案 flexible.js(rem 为单位)。 ```js // 首先是一个立即执行函数,执行时传入的参数是window和document (function flexible (window, document) { var docEl = document.documentElement // 返回文档的root元素 var dpr = window.devicePixelRatio || 1 // 获取设备的dpr,即当前设置下物理像素与虚拟像素的比值 // 调整body标签的fontSize,fontSize = (12 * dpr) + 'px' // 设置默认字体大小,默认的字体大小继承自body function setBodyFontSize () { if (document.body) { document.body.style.fontSize = (12 * dpr) + 'px' } else { document.addEventListener('DOMContentLoaded', setBodyFontSize) } } setBodyFontSize(); // set 1rem = viewWidth / 10 // 设置root元素的fontSize = 其clientWidth / 10 + ‘px’ function setRemUnit () { var rem = docEl.clientWidth / 10 docEl.style.fontSize = rem + 'px' } setRemUnit() // 当我们页面尺寸大小发生变化的时候,要重新设置下rem 的大小 window.addEventListener('resize', setRemUnit) // pageshow 是我们重新加载页面触发的事件 window.addEventListener('pageshow', function(e) { // e.persisted 返回的是true 就是说如果这个页面是从缓存取过来的页面,也需要从新计算一下rem 的大小 if (e.persisted) { setRemUnit() } }) // 检测0.5px的支持,支持则root元素的class中有hairlines if (dpr >= 2) { var fakeBody = document.createElement('body') var testElement = document.createElement('div') testElement.style.border = '.5px solid transparent' fakeBody.appendChild(testElement) docEl.appendChild(fakeBody) if (testElement.offsetHeight === 1) { docEl.classList.add('hairlines') } docEl.removeChild(fakeBody) } }(window, document)) ``` ```js ;(function(win, lib) { var doc = win.document; var docEl = doc.documentElement; var metaEl = doc.querySelector('meta[name="viewport"]'); var flexibleEl = doc.querySelector('meta[name="flexible"]'); var dpr = 0; var scale = 0; var tid; var flexible = lib.flexible || (lib.flexible = {}); if (metaEl) { console.warn('将根据已有的meta标签来设置缩放比例'); var match = metaEl.getAttribute('content').match(/initial\-scale=([\d\.]+)/); if (match) { scale = parseFloat(match[1]); dpr = parseInt(1 / scale); } } else if (flexibleEl) { var content = flexibleEl.getAttribute('content'); if (content) { var initialDpr = content.match(/initial\-dpr=([\d\.]+)/); var maximumDpr = content.match(/maximum\-dpr=([\d\.]+)/); if (initialDpr) { dpr = parseFloat(initialDpr[1]); scale = parseFloat((1 / dpr).toFixed(2)); } if (maximumDpr) { dpr = parseFloat(maximumDpr[1]); scale = parseFloat((1 / dpr).toFixed(2)); } } } if (!dpr &&!scale) { var isAndroid = win.navigator.appVersion.match(/android/gi); var isIPhone = win.navigator.appVersion.match(/iphone/gi); var devicePixelRatio = win.devicePixelRatio; if (isIPhone) { // iOS下,对于2和3的屏,用2倍的方案,其余的用1倍方案 if (devicePixelRatio >= 3 && (!dpr || dpr >= 3)) { dpr = 3; } else if (devicePixelRatio >= 2 && (!dpr || dpr >= 2)){ dpr = 2; } else { dpr = 1; } } else { // 其他设备下,仍旧使用1倍的方案 dpr = 1; } scale = 1 / dpr; } docEl.setAttribute('data-dpr', dpr); if (!metaEl) { metaEl = doc.createElement('meta'); metaEl.setAttribute('name', 'viewport'); metaEl.setAttribute('content', 'initial-scale=' + scale + ', maximum-scale=' + scale + ', minimum-scale=' + scale + ', user-scalable=no'); if (docEl.firstElementChild) { docEl.firstElementChild.appendChild(metaEl); } else { var wrap = doc.createElement('div'); wrap.appendChild(metaEl); doc.write(wrap.innerHTML); } } function refreshRem(){ var width = docEl.getBoundingClientRect().width; if (width / dpr > 540) { width = 540 * dpr; } var rem = width / 10; docEl.style.fontSize = rem + 'px'; flexible.rem = win.rem = rem; } win.addEventListener('resize', function() { clearTimeout(tid); tid = setTimeout(refreshRem, 300); }, false); win.addEventListener('pageshow', function(e) { if (e.persisted) { clearTimeout(tid); tid = setTimeout(refreshRem, 300); } }, false); if (doc.readyState === 'complete') { doc.body.style.fontSize = 12 * dpr + 'px'; } else { doc.addEventListener('DOMContentLoaded', function(e) { doc.body.style.fontSize = 12 * dpr + 'px'; }, false); } refreshRem(); flexible.dpr = win.dpr = dpr; flexible.refreshRem = refreshRem; flexible.rem2px = function(d) { var val = parseFloat(d) * this.rem; if (typeof d ==='string' && d.match(/rem$/)) { val += 'px'; } return val; } flexible.px2rem = function(d) { var val = parseFloat(d) / this.rem; if (typeof d ==='string' && d.match(/px$/)) { 2 val +='rem'; } return val; } })(window, window['lib'] || (window['lib'] = {})); ``` ## 简述px,em,rem - ``` PX px像素(Pixel) em 相对父级文fontsize; 1em = 父fontsize; rem 相对html的fontsize大小; 1rem = html fontsize ``` # js ## 原型链 ![1559057933326](../image/1559057933326-1574858855016.png) ## 原型继承方式 ### 1原型链继承 - ```js function SuperType() { this.property = true; } SuperType.prototype.getSuperValue = function() { return this.property; } function SubType() { this.Subproperty = false; } SubType.prototype = new SuperType(); // 继承了SuperType SubType.prototype.getSubValue = function() { return this.Subproperty ; } var instance = new SubType(); alert(instance.getSuperValue()) // true ``` **优缺点:** ```js 继承原理:通过让子类的原型等于父类的实例,来实现继承。 优点:继承了超类型的构造函数的所有属性和方法。 缺点:1、在创建子类实例时,无法向超类型的构造函数传参,继承单一。    2、所有新实例都会共享父类实例的属性。 ``` ### 2构造函数继承 - ```js function SuperType() { this.colors = ['red', 'blue', 'green']; } function SubType() { SuperType.call(this); // 继承了SuperType } var instance1 = new SubType(); instance1.colors.push('black'); console.log(instance1.colors); // ['red', 'blue', 'green', 'black'] ``` **优缺点:** ```js 继承原理:改变子类的this,通过call指向父类; 优点:可以在子类构造函数中,向超类型构造函数传递参数。 缺点:只继承了父类构造函数的属性,没有继承父类原型的属性。所有的方法都在构造函数中定义,无法实现复用,影响性能。 ``` ### 3组合继承 - ```js function SuperType(name) { this.name = name; this.colors = ['red','blue','green']; } SuperType.prototype.sayNAme = function() { alert(this.name); } function SubType(name,age) { SuperType.call(this, name); // 继承属性 this.age = age; } SubType.prototype = new SuperType(); // 继承方法 SubType.prototype.constructor = SubType; SubType.prototype.sayAge = function() { alert(this.age); } var instance1 = new SubType('xxx', 15); instance1.colors.push('black'); console.log(instance1.colors); // ['red','blue','green','black'] instance1.sayNAme(); // xxx instance1.sayAge(); // 15 ``` **优缺点:** ```js 使用原型链实现对原型属性和方法的继承,通过构造函数来实现对实例属性的继承。这样既通过在原型上定义方法实现了函数的复用,又能够保证每个实例都有它自己的属性。 缺点:调用两次父类构造函数。 ``` ### 4寄生组合继承 - ```js function create(prototype) { function Super() {} Super.prototype = prototype return new Super() } function Programmer(age, name) { Person.call(this, age) this.name = name } Programmer.prototype = create(Person.prototype) Programmer.prototype.constructor = Programmer // 修复构造函数指向 let jon = new Programmer(18, 'jon') jon.name // jon ``` **优缺点:** ```js 子类构造函数复制父类的自身属性和方法,子类原型只接受父类的原型属性和方法 ``` ## cookies,sessionStorage和localStorage - ``` cookie:数据始终在同源的http请求中携带; 大小4k; ``` localStorage:存储持久数据,浏览器关闭后数据不丢失除非主动删除数据;大小5M; sessionStorage:数据在当前浏览器窗口关闭后自动删除;大小5M; indexDB:大小无限; ``` ​ 浏览器的同源策略 - ``` 同协议 同地址 同端口 ``` 正则表达式,匹配以字母开头,后面可以是数字6-30? - ``` ``` 统计字符串出现最多的字母aaacccdddddffff - ``` ``` AJAX的原理 - ```js ``` js原生对象有哪些 - ``` ``` 对象声明三种方式: - ``` ``` 前端优化有哪些: - ```js ``` ## promise ``` Promise三种状态:状态一旦改变将不可更改 pending:promise初始化时; resolved:执行resolve rejected:执行reject ``` ```js class HD { static PENDING = "pending"; static FULFILLED = "fulfilled"; static REJECTED = "rejected"; constructor(executor) { this.status = HD.PENDING; this.value = null; executor(this.resolve.bind(this), this.reject.bind(this)); } resolve(value) { if (this.status == HD.PENDING) { this.status = HD.FULFILLED; this.value = value; console.log(this); console.log('resolve'); console.log(value); } } reject(value) { if (this.status == HD.PENDING) { this.status = HD.REJECTED; this.value = value; } } then(onFulfilled, onRejected) { if (this.status == HD.FULFILLED) { onFulfilled(this.value); } if (this.status == HD.REJECTED) { onRejected(this.value); } } }; let p = new HD((resolve, reject) => { resolve("后盾人"); }); console.log(p); ``` virtual dom ```js 减少渲染次数,提高渲染效率; 核心api: h:创建虚拟dom节点; patch: 通过diff算法计算虚拟dom的差异,更新视图; ``` # ES6 es6有哪些新特性: ``` ``` 数组有哪些常见的api: ``` ``` # vue vue的v-model的原理是? 双向绑定是分两个数据传递方向: ``` ``` vue的生命周期: ``` ``` vue组件传递如何传递: 父>子: ``` ``` 子>父: ``` ``` 兄弟互传: ```js ``` virtual dom ``` virtual dom的好处: 减少页面渲染的次数;提高渲染效率; ``` # xss 和 csrf ## xss ```js https://www.cnblogs.com/tugenhua0707/p/10909284.html http://www.ruanyifeng.com/blog/2016/09/csp.html ``` ```js Cross Site Scripting 跨站脚本攻击 恶意攻击者在web页面中会插入一些恶意的script代码。 ``` 1. **xss防御html编码** ``` 编码规则:将 & < > "'/ 转义为实体字符 ``` 2. **XSS 防御HTML Attribute编码** ``` 编码规则:除了字母、数字、字符以外,使用 &#x;16进制格式来转义ASCII值小于256所有的字符。 ``` 3. **XSS防御之javascript编码** ```js 编码规则:JavaScript编码将字符编码成\x+16进制的形式,对款字节编码成Unicode function encodeForJavascript(str) { let encoded = ''; for(let i = 0; i < str.length; i++) { let cc = hex = str[i]; if (!/[A-Za-z0-9]/.test(str[i]) && str.charCodeAt(i) < 256) { hex = '\\x' + cc.charCodeAt().toString(16); } encoded += hex; } return encoded; }; XSS 防御HTML Attribute编码中我们是可以防御XSS攻击,但是它只能防御的是HTML通用属性,并不是全部属性,在html中还存在很多支持协议解析的html属性,比如 onclick, onerror, href, src 等这些, ``` 4. **XSS 防御之 URL 编码** ```js 将不可信数据作为url参数值时需要经行url编码 使用encodeURIComponent(url) ``` 5. **XSS 防御之 CSS 编码** ```css 编码规则:除了字母数字字符以外,使用\XXXXXX格式来转义ASCII值小于256的所有字符。 background-img:url() function encodeForCSS (attr, str){ let encoded = ''; for (let i = 0; i < str.length; i++) { let ch = str.charAt(i); if (!ch.match(/[a-zA-Z0-9]/) { let hex = str.charCodeAt(i).toString(16); let pad = '000000'.substr((hex.length)); encoded += '\\' + pad + hex; } else { encoded += ch; } } return encoded; }; ``` ### 解决方案: **开启CSP网页安全政策防止XSS攻击** ```html <meta http-equiv="Content-Security-Policy" content=""> <meta http-equiv="Content-Security-Policy" content=" default-src http: https: *.xxx.com'self' 'unsafe-inline' ; style-src'self' 'unsafe-inline' *.yyy.com; script-src'self' 'unsafe-inline' 'unsafe-eval' ; "> ``` ## CSRF CSRF跨站点请求伪造(Cross—Site Request Forgery) ```js 验证 HTTP Referer 字段; HTTP 请求头Referer 记录请求的来源地址 后台验证; 在请求地址中添加 token 并验证; 防止请求伪造 ``` # HTTP ## 常见状态码 ``` ``` # 小程序 小程序生命周期 ``` ``` ## 小程序优化 - 代码层面 - 拆分组件; - 图片压缩,图片用网络地址; - 移除未使用的代码; - 避免频繁setData; - 使用wxs进行视图层逻辑; - 项目层面 - 小程序分包;会按需加载; - 分包预加载; - 尽量升级版本库 - 周期性更新数据 ======================= File: 企业微信开发/企业微信开发.md ======================= <filename>企业微信开发/企业微信开发.md # 登陆 ## 1.本地调试方式 ![image-20200402173201234](E:%5CWall-E%5C%E7%AC%94%E8%AE%B0%5C-notes-%5C%E4%BC%81%E4%B8%9A%E5%BE%AE%E4%BF%A1%E5%BC%80%E5%8F%91%5Cimage-20200402173201234.png) 1.先配置可信域名;需要备案; 2.修改host文件; ``` 管理员身份打开记事本;打开如下hosts文件; ``` ![image-20200402173438598](E:%5CWall-E%5C%E7%AC%94%E8%AE%B0%5C-notes-%5C%E4%BC%81%E4%B8%9A%E5%BE%AE%E4%BF%A1%E5%BC%80%E5%8F%91%5Cimage-20200402173438598.png) ![image-20200402173535927](E:%5CWall-E%5C%E7%AC%94%E8%AE%B0%5C-notes-%5C%E4%BC%81%E4%B8%9A%E5%BE%AE%E4%BF%A1%E5%BC%80%E5%8F%91%5Cimage-20200402173535927.png) # 应用推送消息 ```js 企业安装应用后>腾讯推送消息至回数据回调 > 通过临时授权码>换永久授权>获取安装应用的企业信息token等等 > 调发送消息 ``` ======================= File: 17、Dart-Flutter/Dart-flutter.md ======================= # Dart ## 变量 ```js var name = 1 //可重复赋值 final name = new Date.now() //不可重复赋值,可为表达式 const name = 1 //不可重复赋值,常量 final a = const [] //创建常量值端构造函数 String name = '1' //指定类型 ``` ## 数据类型 ```dart Number int doulbe // 类型 num String Boolean List (也被称为 Array) Map //对象 Set //无序数组 唯一值 Rune (用于在字符串中表示 Unicode 字符) Symbol ``` - int ``` 移位<< >> 按位与^ 按位或| assert((3 << 1) == 6); // 0011 << 1 == 0110 assert((3 >> 1) == 1); // 0011 >> 1 == 0001 assert((3 | 4) == 7); // 0011 | 0100 == 0111 ``` - String ```dart https://www.cnblogs.com/lxlx1798/p/11280106.html $表达式 var name = 'walle' print('abc$name'); // abcwalle + 拼接 ''' ''', """ """ 保持换行空格样式; ``` - Boolean ```dart // 检查空字符串。 var fullName = ''; assert(fullName.isEmpty); // 检查 0 值。 var hitPoints = 0; assert(hitPoints <= 0); // 检查 null 值。 var unicorn; assert(unicorn == null); // 检查 NaN 。 var iMeantToDoThis = 0 / 0; assert(iMeantToDoThis.isNaN); ``` - Set ```dart var names = <String>{}; // Set<String> names = {}; // 这样也是可以的。 // var names = {}; // 这样会创建一个 Map ,而不是 Set 。 ``` - Map ```dart var gifts = Map(); var gifts =new Map(); //new 可选 gifts['first'] = 'partridge'; 常量声明 final constantMap = const { 2: 'helium', 10: 'neon', 18: 'argon', }; ``` ## Map 创建 ```dart 创建Map: var map1 = {"first":"Dart",1:true,true:"2"}; 创建不可变Map: var map2 = const{"first":"Dart",1:true,true:"2"}; 构造创建:var map3 = new Map(); ``` ```dart 常用属性: keys 获取所有的key值 values 获取所有的value值 isEmpty 是否为空 isNotEmpty 是否不为空 常用方法: remove(key) 删除指定key的数据 addAll({...}) 合并映射 给映射内增加属性 containsValue 查看映射内的值 返回true/false forEach map where any every 常用操作 [],length,keys,values, containsKey, containsValue, remove,forEach ``` ## 数据转换 ```dart String --> int var one = int.parse('1') String --> double var one = double.parse('1') // int -> String String oneAsString = 1.toString(); assert(oneAsString == '1'); // double -> String String piAsString = 3.14159.toStringAsFixed(2); assert(piAsString == '3.14'); ``` ## 函数 ```dart bool isNoble(int atomicNumber) { return _nobleGases[atomicNumber]!= null; } isNoble(atomicNumber) { return _nobleGases[atomicNumber]!= null; } bool isNoble(int atomicNumber) => _nobleGases[atomicNumber]!= null; ``` - 参数 ```dart 可选参数 String say(String from, String msg, [String device]) { var result = '$from says $msg'; if (device!= null) { result = '$result with a $device'; } return result; } ``` ```dart 默认参数 void enableFlags({bool bold = false, bool hidden = false}) {...} ``` ```dart list map 默认参数 void doStuff( {List<int> list = const [1, 2, 3], Map<String, String> gifts = const { 'first': 'paper', 'second': 'cotton', 'third': 'leather' }}) { print('list: $list'); print('gifts: $gifts'); } ``` ## String ``` https://www.cnblogs.com/lxlx1798/p/11280106.html ``` ## 类 封装 继承 多态 ```dart class Person { // 变量 String name = 'walle'; int age = 13; // new 时传入参数 Person(this.name, this.age); //与初始化二存一 // 命名构造函数 且传入参数 Person.now(a, b) { this.age = a; this.name = b; } // 初始化 // Person() // : age = 18, // name = "walle" { // print(age); // } // 私有属性,方法 为文件时有效 int _flag; void _run() { print(this._flag); } // 静态 static int age2 = 200; //调用 静态不用 this ;age2外部可访问 static void func(){} //无法访问非静态方法和属性 // get 类似计算属性 String get reutnName { return this.name; } // set set setAge(num b) { this.age = b; } void fun(a) { print("${age}:${this.name}+$a"); } } main() { var p1 = new Person('w', 10); var age2 = Person.age2; //访问静态 var func = Person.func(); //访问静态方法 var p2 = new Person.now(1,'s'); p1.fun(22); print(p1.name); } ``` ```dart ? 条件运算符 //判断类属性,方法是否为空 安全操作 as 类型转换 //(p as className).name is 类型判断 // .. 级联操作 Person p1 new Person() p1..name="walle" ..age=30; ``` ### 继承 ```dart class Web extends Person{ String sex; // 给Person 传参数 //Web(String name, int age) : super(name, age); Web(String name, int age, String sex) : super(name, age){ this.sex = sex; } //重写父类属性 @override void fun(a){ super.age; //调用父类属性 方法 } } ``` ### 多态 - 抽象类 方法 ```dart 多态: 每个子类有不同的表现; //子类必须定义抽象方法; abstract class Doer { //抽象类 不能实例化,只有子类可以实例化 // 定义实例变量和方法... void doSomething(); // 定义一个抽象方法。 void func(){ //抽象类的方法 } } class EffectiveDoer extends Doer { void doSomething() { // 提供方法实现,所以这里的方法就不是抽象方法了... } } ``` 接口 ```dart class Impostor implements Person { get _name => ''; String greet(String who) => 'Hi $who. Do you know who I am?'; } ``` ------ ## 定时器 ```dart import 'dart:async'; Timer timeoutId; const timeout = const Duration(seconds: 5); print('currentTime='+DateTime.now().toString()); // 当前时间 timeoutId = Timer(timeout, () { //callback function print('afterTimer='+DateTime.now().toString()); // 5s之后 }); const timeout = const Duration(seconds: 1); timeoutId = Timer.periodic(timeout, (timer) { //callback function //1s 回调一次 print('afterTimer='+DateTime.now().toString()); timer.cancel(); // 取消定时器 } ``` 清除定时器 ``` @override void dispose() { super.dispose(); timeoutId.cancel(); } ``` # flutter hello world ```dart import 'package:flutter/material.dart'; void main() => runApp(new MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return new MaterialApp( title: 'Welcome to Flutter', home: new Scaffold( appBar: new AppBar( title: new Text('Welcome to Flutter'), ), body: new Center( child: new Text('Hello World'), ), ), ); } } ``` 命令 ``` flutter ctrate 项目名称 // 创建项目 flutter packages get // 类似 npm i flutter run // 运行 ``` ## 生命周期 ``` 上图就是 State 的生命周期图。 StatefulWidget.createState() Framework 调用会通过调用 StatefulWidget.createState() 来创建一个 State。 initState() 新创建的 State 会和一个 BuildContext 产生关联,此时认为 State 已经被安装好了,initState() 函数将会被调用。 通常,我们可以重写这个函数,进行初始化操作。 didChangeDependencies() 在 initState() 调用结束后,这个函数会被调用。 事实上,当 State 对象的依赖关系发生变化时,这个函数总会被 Framework 调用。 build() 经过以上步骤,系统认为一个 State 已经准备好了,就会调用 build() 来构建视图。 我们需要在这个函数中,返回一个 Widget。 deactivate() 当 State 被暂时从视图树中移除时,会调用这个函数。 页面切换时,也会调用它,因为此时 State 在视图树中的位置发生了变化,需要先暂时移除后添加。 ⚠️注意,重写的时候必须要调用 super.deactivate()。 dispose() 当 State 被永久的从视图树中移除,Framework 会调用该函数。 在销毁前触发,我们可以在这里进行最终的资源释放。 在调用这个函数之前,总会先调用 deactivate()。 ⚠️注意,重写的时候必须要调用 super.dispose()。 didUpdateWidget(covariant T oldWidget) 当 widget 的配置发生变化时,会调用这个函数。 比如,Hot-reload 的时候就会调用这个函数。 这个函数调用后,会调用 build()。 setState() 当我需要更新 State 的视图时,需要手动调用这个函数,它会触发 build() 。 ``` ``` 当sestate 执行时会触发 build; initstate build dispose ``` ## 事件event ```dart gesturedetector 点击: onTapDown: 用户手指按下 onTapUp: 手指抬起 onTap: 点击完成 onTapCancel: 按下过程取消 双击: onDoubleTap: 双击 长按: onLongPress: 在屏幕上保持一段时间 纵向拖拽: onVerticalDragStart: 接触并开始纵向移动 onVerticalDragUpdate: 移动 onVerticalDragEnd: 结束 横向拖拽: onHorizontlDragStart: 接触并开始纵向移动 onHorizontlDragUpdate: 移动 onHorizontlDragEnd: 结束 globalPosition 获取相对屏幕位置 localPosition 相对于Widget位置信息 ``` ```dart body:Listener( onPointerDown:(event){ event.position // 屏幕中位置 event.localPosition // 在组件中的位置 } ) 指针事件: onPointerDownEvent onPointerMoveEvent onPoiinterUpEvent onPointerCancelEvent ``` ```dart Inkwell 和 GestureDetector区别 new InkWell( child: new Text("Click me!"), onTap: () { // 单击 }, onDoubleTap: () { // 双击 }, onLongPress: () { // 长按 } ); GestureDetector: 是无状态组件 无水波纹 Inkwell: 水波纹 widget 可自定义水波纹: Ink( highlightColor: Colors.purple[800], //颜色在最上层 会覆盖 splashColor:Color.red ) ``` 事件传递 ```dart event_bus //第三方库 ``` ## StatelessWidget ## StatefullWidget ```dart StatelessWidget //无状态 StatefullWidget //可变状态 ``` ## MaterialApp https://api.flutter.dev/flutter/material/MaterialApp-class.html ```dart MaterialApp({ Key key, this.title = '', // 设备用于为用户识别应用程序的单行描述 this.home, // 应用程序默认路由的小部件,用来定义当前应用打开的时候,所显示的界面 this.color, // 在操作系统界面中应用程序使用的主色。 this.theme, // 应用程序小部件使用的颜色。 this.routes = const <String, WidgetBuilder>{}, // 应用程序的顶级路由表 this.navigatorKey, // 在构建导航器时使用的键。 this.initialRoute, // 如果构建了导航器,则显示的第一个路由的名称 this.onGenerateRoute, // 应用程序导航到指定路由时使用的路由生成器回调 this.onUnknownRoute, // 当 onGenerateRoute 无法生成路由(initialRoute除外)时调用 this.navigatorObservers = const <NavigatorObserver>[], // 为该应用程序创建的导航器的观察者列表 this.builder, // 用于在导航器上面插入小部件,但在由WidgetsApp小部件创建的其他小部件下面插入小部件,或用于完全替换导航器 this.onGenerateTitle, // 如果非空,则调用此回调函数来生成应用程序的标题字符串,否则使用标题。 this.locale, // 此应用程序本地化小部件的初始区域设置基于此值。 this.localizationsDelegates, // 这个应用程序本地化小部件的委托。 this.localeListResolutionCallback, // 这个回调负责在应用程序启动时以及用户更改设备的区域设置时选择应用程序的区域设置。 this.localeResolutionCallback, // this.supportedLocales = const <Locale>[Locale('en', 'US')], // 此应用程序已本地化的地区列表 this.debugShowMaterialGrid = false, // 打开绘制基线网格材质应用程序的网格纸覆盖 this.showPerformanceOverlay = false, // 打开性能叠加 this.checkerboardRasterCacheImages = false, // 打开栅格缓存图像的棋盘格 this.checkerboardOffscreenLayers = false, // 打开渲染到屏幕外位图的图层的棋盘格 this.showSemanticsDebugger = false, // 打开显示框架报告的可访问性信息的覆盖 this.debugShowCheckedModeBanner = true, // 在选中模式下打开一个小的“DEBUG”横幅,表示应用程序处于选中模式 }) ``` ```dart import 'package:flutter/material.dart'; void main() => runApp(new MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return new MaterialApp( title: 'Welcome to Flutter', theme:new ThemeData( primaryColor: Colors. ), ); } } ``` | key | type | detail | | ----- | --------- | ---------------------------- | | title | String | 为用户识别应用程序的单行描述 | | theme | ThemeData | | | | | | ThemeData ```dart factory ThemeData({ Brightness brightness, // 应用整体主题的亮度。用于按钮之类的小部件,以确定在不使用主色或强调色时选择什么颜色。 MaterialColor primarySwatch,// 定义一个单一的颜色以及十个色度的色块。 Color primaryColor, // 应用程序主要部分的背景颜色(toolbars、tab bars 等) Brightness primaryColorBrightness, // primaryColor的亮度。用于确定文本的颜色和放置在主颜色之上的图标(例如工具栏文本)。 Color primaryColorLight, // primaryColor的浅色版 Color primaryColorDark, // primaryColor的深色版 Color accentColor, // 小部件的前景色(旋钮、文本、覆盖边缘效果等)。 Brightness accentColorBrightness, // accentColor的亮度。 Color canvasColor, // MaterialType.canvas 的默认颜色 Color scaffoldBackgroundColor, // Scaffold的默认颜色。典型Material应用程序或应用程序内页面的背景颜色。 Color bottomAppBarColor, // BottomAppBar的默认颜色 Color cardColor, // Card的颜色 Color dividerColor, // Divider和PopupMenuDivider的颜色,也用于ListTile之间、DataTable的行之间等。 Color highlightColor, // 选中在泼墨动画期间使用的突出显示颜色,或用于指示菜单中的项。 Color splashColor, // 墨水飞溅的颜色。InkWell InteractiveInkFeatureFactory splashFactory, // 定义由InkWell和InkResponse反应产生的墨溅的外观。 Color selectedRowColor, // 用于突出显示选定行的颜色。 Color unselectedWidgetColor, // 用于处于非活动(但已启用)状态的小部件的颜色。例如,未选中的复选框。通常与accentColor形成对比。也看到disabledColor。 Color disabledColor, // 禁用状态下部件的颜色,无论其当前状态如何。例如,一个禁用的复选框(可以选中或未选中)。 Color buttonColor, // RaisedButton按钮中使用的Material 的默认填充颜色。 ButtonThemeData buttonTheme, // 定义按钮部件的默认配置,如RaisedButton和FlatButton。 Color secondaryHeaderColor, // 选定行时PaginatedDataTable标题的颜色。 Color textSelectionColor, // 文本框中文本选择的颜色,如TextField Color cursorColor, // 文本框中光标的颜色,如TextField Color textSelectionHandleColor, // 用于调整当前选定的文本部分的句柄的颜色。 Color backgroundColor, // 与主色形成对比的颜色,例如用作进度条的剩余部分。 Color dialogBackgroundColor, // Dialog 元素的背景颜色 Color indicatorColor, // 选项卡中选定的选项卡指示器的颜色。 Color hintColor, // 用于提示文本或占位符文本的颜色,例如在TextField中。 Color errorColor, // 用于输入验证错误的颜色,例如在TextField中 Color toggleableActiveColor, // 用于突出显示Switch、Radio和Checkbox等可切换小部件的活动状态的颜色。 String fontFamily, // 文本字体 TextTheme textTheme, // 文本的颜色与卡片和画布的颜色形成对比。 TextTheme primaryTextTheme, // 与primaryColor形成对比的文本主题 TextTheme accentTextTheme, // 与accentColor形成对比的文本主题。 InputDecorationTheme inputDecorationTheme, // 基于这个主题的 InputDecorator、TextField和TextFormField的默认InputDecoration值。 IconThemeData iconTheme, // 与卡片和画布颜色形成对比的图标主题 IconThemeData primaryIconTheme, // 与primaryColor形成对比的图标主题 IconThemeData accentIconTheme, // 与accentColor形成对比的图标主题。 SliderThemeData sliderTheme, // 用于呈现Slider的颜色和形状 TabBarTheme tabBarTheme, // 用于自定义选项卡栏指示器的大小、形状和颜色的主题。 CardTheme cardTheme, // Card的颜色和样式 ChipThemeData chipTheme, // Chip的颜色和样式 TargetPlatform platform, MaterialTapTargetSize materialTapTargetSize, // 配置某些Material部件的命中测试大小 PageTransitionsTheme pageTransitionsTheme, AppBarTheme appBarTheme, // 用于自定义Appbar的颜色、高度、亮度、iconTheme和textTheme的主题。 BottomAppBarTheme bottomAppBarTheme, // 自定义BottomAppBar的形状、高度和颜色的主题。 ColorScheme colorScheme, // 拥有13种颜色,可用于配置大多数组件的颜色。 DialogTheme dialogTheme, // 自定义Dialog的主题形状 Typography typography, // 用于配置TextTheme、primaryTextTheme和accentTextTheme的颜色和几何TextTheme值。 CupertinoThemeData cupertinoOverrideTheme }) ``` AppBarTheme ```dart const AppBarTheme({ this.brightness, this.color, // 背景颜色 this.elevation, // 阴影辐射范围 default 4.0 this.shadowColor, this.iconTheme, this.actionsIconTheme, this.textTheme, this.centerTitle, }); ``` ## Scaffold ![image-20200704124550478](Dart-flutter.assets/image-20200704124550478.png) ## appbar ```dart AppBar({ Key key, this.leading, //widget类型,即可任意设计样式,表示左侧leading区域,通常为icon,如返回icon this.automaticallyImplyLeading = true, // 如果leading!=null,该属性不生效;如果leading==null且为true,左侧leading区域留白;如果leading==null且为false,左侧leading区域扩展给title区域使用 this.title,//widget类型,即可任意设计样式,表示中间title区域,通常为标题栏 this.actions,// List<Widget>类型,即可任意设计样式,表示右侧actions区域,可放置多个widget,通常为icon,如搜索icon、菜单icon this.flexibleSpace, this.bottom, //PreferredSizeWidget类型,appbar底部区域,通常为Tab控件 this.elevation, //阴影高度,默认为4 this.shape,//ShapeBorder 类型,表示描边形状 this.backgroundColor, //Color类型,背景色 this.brightness,//Brightness类型,表示当前appbar主题是亮或暗色调,有dark和light两个值,可影响系统状态栏的图标颜色 this.iconTheme, //IconThemeData类型,可影响包括leading、title、actions中icon的颜色、透明度,及leading中的icon大小。 this.actionsIconTheme, this.textTheme,// TextTheme类型,文本主题样式,可设置appbar中文本的许多样式,如字体大小、颜色、前景色、背景色等... this.primary = true,//true时,appBar会以系统状态栏高度为间距显示在下方;false时,会和状态栏重叠,相当于全屏显示。 this.centerTitle, // boolean 类型,表示标题是否居中显示 this.titleSpacing = NavigationToolbar.kMiddleSpacing,//title区域水平方向与leading和actions的间距(padding) this.toolbarOpacity = 1.0,//toolbar区域透明度 this.bottomOpacity = 1.0,//bottom区域透明度 } ``` ## 显示隐藏状态 ```dart import 'package:flutter/services.dart'; //显示底部栏(隐藏顶部状态栏) // SystemChrome.setEnabledSystemUIOverlays([SystemUiOverlay.bottom]); //显示顶部栏(隐藏底部栏) // SystemChrome.setEnabledSystemUIOverlays([SystemUiOverlay.top]); //隐藏底部栏和顶部状态栏 SystemChrome.setEnabledSystemUIOverlays([]); ``` ## 底部导航栏 ```dart import 'package:flutter/material.dart'; class BottomBar extends StatefulWidget { @override BottomBarState createState() => BottomBarState(); } class BottomBarState extends State<BottomBar> { @override Widget build(BuildContext context) { return BottomNavigationBar( items: [ BottomNavigationBarItem( icon: Icon( Icons.home, color: Colors.blue, ), title: Text('HOME', style: TextStyle(color: Colors.blue))), BottomNavigationBarItem( icon: Icon( Icons.home, color: Colors.blue, ), title: Text('HOME', style: TextStyle(color: Colors.blue))) ], ); } } mixin StateBottomBar {} ``` ``` import 'package:flutter/material.dart'; import './pages/main_BottomBar/main_BottomBar.dart'; void main() => runApp(new MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return new MaterialApp( title: 'Welcome to Flutter', home: new Scaffold( appBar: new AppBar( title: new Text('Welcome to Flutster'), ), body: new Center( // child: new Text( // 'Hello Worlds', // textDirection: TextDirection.ltr, // style: TextStyle( // fontSize: 14.0, color: Color.fromRGBO(255, 122, 122,.5)), // ), heightFactor: 1, widthFactor: 1, // child: new HomeContent(), // child: new ImageCom(), child: ListView( children: <Widget>[ ListTile( title: Text('title'), subtitle: Text('data'), trailing: Text('trailing'), isThreeLine: true, dense: true, onLongPress: () { print('222'); }, ), TextField( decoration: InputDecoration( hintText: 'dddd', border: OutlineInputBorder(), labelText: '用户')), SizedBox(height: 20), TextField( obscureText: true, decoration: InputDecoration( hintText: 'dddd', border: OutlineInputBorder(), labelText: '用户')), // MyInput() ], ), // child: new PaddingTestRoute(), ), bottomNavigationBar:BottomBar(), ), ); } } ``` ## SliverAppBar ```dart const SliverAppBar({ Key key, this.leading,//左侧的图标或文字,多为返回箭头 this.automaticallyImplyLeading = true,//没有leading为true的时候,默认返回箭头,没有leading且为false,则显示title this.title,//标题 this.actions,//标题右侧的操作 this.flexibleSpace,//可以理解为SliverAppBar的背景内容区 this.bottom,//SliverAppBar的底部区 this.elevation,//阴影 this.forceElevated = false,//是否显示阴影 this.backgroundColor,//背景颜色 this.brightness,//状态栏主题,默认Brightness.dark,可选参数light this.iconTheme,//SliverAppBar图标主题 this.actionsIconTheme,//action图标主题 this.textTheme,//文字主题 this.primary = true,//是否显示在状态栏的下面,false就会占领状态栏的高度 this.centerTitle,//标题是否居中显示 this.titleSpacing = NavigationToolbar.kMiddleSpacing,//标题横向间距 this.expandedHeight,//合并的高度,默认是状态栏的高度加AppBar的高度 this.floating = false,//滑动时是否悬浮 this.pinned = false,//标题栏是否固定 this.snap = false,//配合floating使用 }) ``` 滚动到指定位置 ```dart onTap: () { _pageScroll.animateTo( _pageScroll.position.minScrollExtent, //滚动到顶部部 duration: const Duration(milliseconds: 300), curve: Curves.easeOut, ); }, ``` ## Dialog ```dart https://juejin.im/post/6844903822028963847 Future<T> showDialog<T>({ @required BuildContext context, // 点击 dialog 外部是否可消失 bool barrierDismissible = true, // 构建 Dialog 视图 WidgetBuilder builder, }) 如果要更新 dialog中的视图 科技加一层StatefulBuilder建立自身的 setstate; ``` ```dart showDialog<Future>( context: context, barrierDismissible: false, useRootNavigator: true, useSafeArea: true, builder: (BuildContext context) { BuildContext iscontext = context; // 父级的 bool isShowPhone = true; return StatefulBuilder(builder: (context, state // 自己的setstate) { return Widget } } ``` ## Widget ### Text ```dart Text( "Text组件的使用", style: TextStyle( // 文字颜色 color: Color(0xfff0000), // none 不显示装饰线条,underline 字体下方,overline 字体上方,lineThrough穿过文字 decoration: TextDecoration.none, // solid 直线,double 双下划线,dotted 虚线,dashed 点下划线,wavy 波浪线 decorationStyle: TextDecorationStyle.solid, // 装饰线的颜色 decorationColor: Colors.red, // 文字大小 fontSize: 15.0, // normal 正常,italic 斜体 fontStyle: FontStyle.normal, // 字体的粗细 fontWeight: FontWeight.bold, // 文字间的宽度 letterSpacing: 1.0, // 文本行与行的高度,作为字体大小的倍数(取值1~2,如1.2) height: 1, //对齐文本的水平线: //TextBaseline.alphabetic:文本基线是标准的字母基线 //TextBaseline.ideographic:文字基线是表意字基线; //如果字符本身超出了alphabetic 基线,那么ideograhpic基线位置在字符本身的底部。 textBaseline: TextBaseline.alphabetic), // 段落的间距样式 strutStyle: StrutStyle( fontFamily:'serif', fontFamilyFallback: ['monospace','serif'], fontSize: 20, height: 2, leading: 2.0, fontWeight: FontWeight.w300, fontStyle: FontStyle.normal, forceStrutHeight: true, debugLabel: 'text demo', ), // 文字对齐方式 textAlign: TextAlign.center, // 文字排列方向 ltr 左到右,rtl右到左 textDirection: TextDirection.ltr, // 用于选择区域特定字形的语言环境 locale: Locale('zh_CN'), // 软包裹 ,文字是否应该在软断行出断行 softWrap: false, // 如何处理视觉溢出:clip 剪切溢出的文本以修复其容器。ellipsis 使用省略号表示文本已溢出。fade 将溢出的文本淡化为透明。 overflow: TextOverflow.clip, // 文字的缩放比例 textScaleFactor: 1.0, // 文本要跨越的可选最大行数, maxLines: 2, // 图像的语义描述,用于向Andoid上的TalkBack和iOS上的VoiceOver提供图像描述 semanticsLabel: 'text demo', textWidthBasis: TextWidthBasis.longestLine, ) ``` ## Offstage ``` 控制child是否显示 const Offstage({ Key key, this.offstage = true, Widget child }) ``` ## PreferredSize ``` Scaffold( appBar: PreferredSize( child: AppBar( ), preferredSize: Size.fromHeight(screenSize.height * 0.07)) ); ``` ## tabber ```dart Key key, @required this.tabs, this.controller, this.isScrollable = false, //是否可滚动 this.indicatorColor, //指示器颜色 this.indicatorWeight = 2.0, //指示器厚度 this.indicatorPadding = EdgeInsets.zero,//底部指示器的Padding this.indicator, //指示器decoration,例如边框等 this.indicatorSize, //指示器大小计算方式 this.labelColor, this.labelStyle, this.labelPadding, this.unselectedLabelColor, this.unselectedLabelStyle, this.dragStartBehavior = DragStartBehavior.start, this.mouseCursor, this.onTap, this.physics, ``` ## SliverAppBar ```dart const SliverAppBar({ Key key, this.leading,//左侧的图标或文字,多为返回箭头 this.automaticallyImplyLeading = true,//没有leading为true的时候,默认返回箭头,没有leading且为false,则显示title this.title,//标题 this.actions,//标题右侧的操作 this.flexibleSpace,//可以理解为SliverAppBar的背景内容区 this.bottom,//SliverAppBar的底部区 this.elevation,//阴影 this.forceElevated = false,//是否显示阴影 this.backgroundColor,//背景颜色 this.brightness,//状态栏主题,默认Brightness.dark,可选参数light this.iconTheme,//SliverAppBar图标主题 this.actionsIconTheme,//action图标主题 this.textTheme,//文字主题 this.primary = true,//是否显示在状态栏的下面,false就会占领状态栏的高度 this.centerTitle,//标题是否居中显示 this.titleSpacing = NavigationToolbar.kMiddleSpacing,//标题横向间距 this.expandedHeight,//合并的高度,默认是状态栏的高度加AppBar的高度 this.floating = false,//滑动时是否悬浮 this.pinned = false,//标题栏是否固定 this.snap = false,//配合floating使用 }) ``` ```dart body: new CustomScrollView( slivers: <Widget>[ new SliverAppBar( leading: GestureDetector( child: Icon(Icons.arrow_back), onTap: () => Navigator.pop(context), ), //左侧按钮 /** * 如果没有leading,automaticallyImplyLeading为true,就会默认返回箭头 * 如果 没有leading 且为false,空间留给title * 如果有leading,这个参数就无效了 */ automaticallyImplyLeading: true, // title: Text('大标题'), //标题 centerTitle: true, //标题是否居中 actions: [Icon(Icons.archive)], //右侧的内容和点击事件啥的 elevation: 4, //阴影的高度 forceElevated: false, //是否显示阴影 backgroundColor: Colors.green, //背景颜色 brightness: Brightness.dark, //黑底白字,lignt 白底黑字 iconTheme: IconThemeData( color: Colors.red, size: 30, opacity: 1), //所有的icon的样式,不仅仅是左侧的,右侧的也会改变 textTheme: TextTheme(), //字体样式 primary: true, // appbar是否显示在屏幕的最上面,为false是显示在最上面,为true就显示在状态栏的下面 titleSpacing: 16, //标题两边的空白区域 expandedHeight: 200.0, //默认高度是状态栏和导航栏的高度,如果有滚动视差的话,要大于前两者的高度 floating: false, //滑动到最上面,再滑动是否隐藏导航栏的文字和标题等的具体内容,为true是隐藏,为false是不隐藏 pinned: true, //是否固定导航栏,为true是固定,为false是不固定,往上滑,导航栏可以隐藏 snap: false, //只跟floating相对应,如果为true,floating必须为true,也就是向下滑动一点儿,整个大背景就会动画显示全部,网上滑动整个导航栏的内容就会消失 flexibleSpace: new FlexibleSpaceBar( title: new Text("随内容一起滑动的头部"), centerTitle: true, collapseMode: CollapseMode.pin, ), ), new SliverFixedExtentList( itemExtent: 150.0, delegate: new SliverChildBuilderDelegate((context, index) => new ListTile( title: new Text("List item $index"), )), ) ], ), ``` ```dart 滚动 浮动 http://www.ptbird.cn/flutter-customscrollview-floating-appbar.html ``` 示例 ```dart TabController _controller; @override void initState() { super.initState(); _controller = TabController( length: _tabValues.length, vsync: ScrollableState(), ); } Container( child: TabBar( tabs: _tabValues.map((f) { return Text(f); }).toList(), controller: _controller, indicatorColor: Colors.red, indicatorSize: TabBarIndicatorSize.tab, isScrollable: true, labelColor: Colors.red, unselectedLabelColor: Colors.black, indicatorWeight: 5.0, labelStyle: TextStyle(height: 2), ), ), Container( // width: 750, height: 600.0, // 非body时 需要指定高度 child: TabBarView( controller: _controller, children: _tabValues.map((f) { return Center( child: Text(f), ); }).toList(), ), ), ``` ## 主题ThemeData ```dart factory ThemeData({ Brightness brightness, // 应用整体主题的亮度。用于按钮之类的小部件,以确定在不使用主色或强调色时选择什么颜色。 MaterialColor primarySwatch,// 定义一个单一的颜色以及十个色度的色块。 Color primaryColor, // 应用程序主要部分的背景颜色(toolbars、tab bars 等) Brightness primaryColorBrightness, // primaryColor的亮度。用于确定文本的颜色和放置在主颜色之上的图标(例如工具栏文本)。 Color primaryColorLight, // primaryColor的浅色版 Color primaryColorDark, // primaryColor的深色版 Color accentColor, // 小部件的前景色(旋钮、文本、覆盖边缘效果等)。 Brightness accentColorBrightness, // accentColor的亮度。 Color canvasColor, // MaterialType.canvas 的默认颜色 Color scaffoldBackgroundColor, // Scaffold的默认颜色。典型Material应用程序或应用程序内页面的背景颜色。 Color bottomAppBarColor, // BottomAppBar的默认颜色 Color cardColor, // Card的颜色 Color dividerColor, // Divider和PopupMenuDivider的颜色,也用于ListTile之间、DataTable的行之间等。 Color highlightColor, // 选中在泼墨动画期间使用的突出显示颜色,或用于指示菜单中的项。 Color splashColor, // 墨水飞溅的颜色。InkWell InteractiveInkFeatureFactory splashFactory, // 定义由InkWell和InkResponse反应产生的墨溅的外观。 Color selectedRowColor, // 用于突出显示选定行的颜色。 Color unselectedWidgetColor, // 用于处于非活动(但已启用)状态的小部件的颜色。例如,未选中的复选框。通常与accentColor形成对比。也看到disabledColor。 Color disabledColor, // 禁用状态下部件的颜色,无论其当前状态如何。例如,一个禁用的复选框(可以选中或未选中)。 Color buttonColor, // RaisedButton按钮中使用的Material 的默认填充颜色。 ButtonThemeData buttonTheme, // 定义按钮部件的默认配置,如RaisedButton和FlatButton。 Color secondaryHeaderColor, // 选定行时PaginatedDataTable标题的颜色。 Color textSelectionColor, // 文本框中文本选择的颜色,如TextField Color cursorColor, // 文本框中光标的颜色,如TextField Color textSelectionHandleColor, // 用于调整当前选定的文本部分的句柄的颜色。 Color backgroundColor, // 与主色形成对比的颜色,例如用作进度条的剩余部分。 Color dialogBackgroundColor, // Dialog 元素的背景颜色 Color indicatorColor, // 选项卡中选定的选项卡指示器的颜色。 Color hintColor, // 用于提示文本或占位符文本的颜色,例如在TextField中。 Color errorColor, // 用于输入验证错误的颜色,例如在TextField中 Color toggleableActiveColor, // 用于突出显示Switch、Radio和Checkbox等可切换小部件的活动状态的颜色。 String fontFamily, // 文本字体 TextTheme textTheme, // 文本的颜色与卡片和画布的颜色形成对比。 TextTheme primaryTextTheme, // 与primaryColor形成对比的文本主题 TextTheme accentTextTheme, // 与accentColor形成对比的文本主题。 InputDecorationTheme inputDecorationTheme, // 基于这个主题的 InputDecorator、TextField和TextFormField的默认InputDecoration值。 IconThemeData iconTheme, // 与卡片和画布颜色形成对比的图标主题 IconThemeData primaryIconTheme, // 与primaryColor形成对比的图标主题 IconThemeData accentIconTheme, // 与accentColor形成对比的图标主题。 SliderThemeData sliderTheme, // 用于呈现Slider的颜色和形状 TabBarTheme tabBarTheme, // 用于自定义选项卡栏指示器的大小、形状和颜色的主题。 CardTheme cardTheme, // Card的颜色和样式 ChipThemeData chipTheme, // Chip的颜色和样式 TargetPlatform platform, MaterialTapTargetSize materialTapTargetSize, // 配置某些Material部件的命中测试大小 PageTransitionsTheme pageTransitionsTheme, AppBarTheme appBarTheme, // 用于自定义Appbar的颜色、高度、亮度、iconTheme和textTheme的主题。 BottomAppBarTheme bottomAppBarTheme, // 自定义BottomAppBar的形状、高度和颜色的主题。 ColorScheme colorScheme, // 拥有13种颜色,可用于配置大多数组件的颜色。 DialogTheme dialogTheme, // 自定义Dialog的主题形状 Typography typography, // 用于配置TextTheme、primaryTextTheme和accentTextTheme的颜色和几何TextTheme值。 CupertinoThemeData cupertinoOverrideTheme }) ``` ## safearea ``` 屏幕适配 ``` ## webview ``` 插件 https://pub.dev/packages/webview_flutter ``` ```dart 拦截返回 import 'package:flutter/material.dart'; import 'package:webview_flutter/webview_flutter.dart'; class Case extends StatefulWidget { Case({Key key, this.title}) : super(key: key); final String title; @override _CaseState createState() => _CaseState(); } class _CaseState extends State<Case> { String url = 'https://m.jia.top/sz/design/index?hideLeftArrow=1'; WebViewController _webViewController; Future<bool> _requestPop() { // Navigator.of(context).pop(100); ///弹出页面并传回int值100,用于上一个界面的回调 // return new Future.value(false); Future canGoBack = _webViewController.canGoBack(); canGoBack.then((str) { if (str) { _webViewController.goBack(); } else { Navigator.of(context).pop(); } }); } @override Widget build(BuildContext context) { return WillPopScope( child: WebView( initialUrl: url, javascriptMode: JavascriptMode.unrestricted, onWebViewCreated: (WebViewController webViewController) { // 在WebView创建完成后会产生一个 webViewController _webViewController = webViewController; }, ), onWillPop: _requestPop, ); } } ``` ## 布局 ### container 绘制顺序 1. transform 2. decoration 3. child 4. foregroundDecoration ```dart class HomeContent extends StatelessWidget { @override Widget build(BuildContext context) { return Container( child: Text('ss'), height: 200.0, width: 300.0, padding:EdgeInsets.all(20.0), alignment:Alignment.centerRight, decoration: BoxDecoration( color: Colors.yellow, border: Border.all( width: 1.0, color: Colors.blue, )), ); } } ``` | | | | | ---- | ---- | ---- | | | | | | | | | | | | | ### Align ```dart const Align({ Key key, this.alignment = Alignment.center, this.widthFactor, this.heightFactor, Widget child, }) ``` ### Row ```dart Row({ Key key, // 主轴 水平方向 MainAxisAlignment mainAxisAlignment = MainAxisAlignment.start, MainAxisSize mainAxisSize = MainAxisSize.max, // 主轴 垂直方向 CrossAxisAlignment crossAxisAlignment = CrossAxisAlignment.center, TextDirection textDirection, VerticalDirection verticalDirection = VerticalDirection.down, TextBaseline textBaseline, List<Widget> children = const <Widget>[], }) ``` ### Column ```dart Column({ Key key, // 主轴 垂直方向 MainAxisAlignment mainAxisAlignment = MainAxisAlignment.start, // 盒子 max=block min=aline MainAxisSize mainAxisSize = MainAxisSize.max, // 副轴 水平方向 CrossAxisAlignment crossAxisAlignment = CrossAxisAlignment.center, TextDirection textDirection, // item 排序方式 VerticalDirection verticalDirection = VerticalDirection.down, TextBaseline textBaseline, List<Widget> children = const <Widget>[], }) ``` ### Expanded ```dart body:Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Center(child:Text('I am JSPang')), // 当前元素 最大占据 Expanded(child:Center(child:Text('my website is jspang.com'))), Center(child:Text('I love coding')) ], ) ``` ### CircleAvatar ```dart const CircleAvatar({ Key key, this.child, this.backgroundColor, this.backgroundImage, this.onBackgroundImageError, this.foregroundColor, this.radius, this.minRadius, this.maxRadius, }) ``` ### Stack ```dart Stack({ Key key, this.alignment = AlignmentDirectional.topStart, this.textDirection, this.fit = StackFit.loose, this.overflow = Overflow.clip, List<Widget> children = const <Widget>[], }) var stack = new Stack( children: <Widget>[ new CircleAvatar( backgroundImage: new NetworkImage('http://jspang.com/static//myimg/blogtouxiang.jpg'), radius: 100.0, ), new Positioned( top:10.0, left:10.0, child: new Text('JSPang.com'), ), new Positioned( // 定位 bottom:10.0, right:10.0, child: new Text('技术胖'), ) ], ); ``` sliverList sliverAppBar pageview.builder 有懒加载 ## Wrap | | | | | ------------------ | ---- | ---- | | direction | axis | | | alignment | | | | runSpacing | | | | runAlignment | | | | crossAxisAlignment | | | | VerticalDirection | | | | textDirection | | | | children | | | ```dart Wrap({ Key key, this.direction = Axis.horizontal, //排列方向,默认水平方向排列 this.alignment = WrapAlignment.start, //子控件在主轴上的对齐方式 this.spacing = 0.0, //主轴上子控件中间的间距 this.runAlignment = WrapAlignment.start, //子控件在交叉轴上的对齐方式 this.runSpacing = 0.0, //交叉轴上子控件之间的间距 this.crossAxisAlignment = WrapCrossAlignment.start, //交叉轴上子控件的对齐方式 this.textDirection, //textDirection水平方向上子控件的起始位置 this.verticalDirection = VerticalDirection.down, //垂直方向上子控件的其实位置 List<Widget> children = const <Widget>[], //要显示的子控件集合 }) ``` ### 辅助布局 #### center ``` ``` | | | | | ---- | ---- | ---- | | | | | | | | | | | | | #### SizeBox #### AspectRatio #### FractionallySizedBox #### card ## Transform ```dart Transform( origin: Offset(57.w / 2, 34.h / 2), transform: Matrix4.rotationZ(pi / 2), child: Image.asset( 'images/next.png', width: 57.w, height: 34.h, ), ), ``` ## 辅助样式 color ```dart Color _bottombarcolor = Color(0xFFF63515); ``` ### padding ```dart 用法: Padding( padding: const EdgeInsets.all(10.0), child: Text("title") ) 属性: padding: EdgeInsets.all(10.0); //全部 padding: EdgeInsets.only( //padding-top: left:20.0, top:20.0, right:20.0, bottom:20.0, ); EdgeInsets.symmetric( vertical:100.0, //垂直方向 padding-top/bottom 100 horizontal:100.0 //水平方向 ); EdgeInsets.fromLTRB( left:10.0, top:10.0, right:10.0, bottom:10.0, ) ``` ### Alignment ```dart const Align({ Key key, this.alignment = Alignment.center, this.widthFactor, this.heightFactor, Widget child }) alignment: Alignment.center, Alignment.topLeft, Alignment.topCenter, Alignment.topRight, Alignment.centerLeft, Alignment(x,y), //中心为(0,0) (1,1)为右下角 ``` ### textDirection ```dart // 文字排列方式 textDirection: TextDirection.ltr; TextDirection.rtl; ``` ### BoxFit ```dart fit: BoxFit.fit //全图显示 充满父容器 BoxFit.contain //全图显示 显示原比例 可能会有空隙 BoxFit.cover //显示可能拉伸,可能裁切,充满 BoxFit.fitWidth //宽度充满 会拉伸 BoxFit.fitHeight //高度充满 BoxFit.scaleDown //不允许显示超过源图片大小,可小不可大 ``` ### Icon ```dart Icon( Icons.search, color: Color(0xffcccccc), size:18.0, ), ``` BoxDecoration ``` gradient:LinearGradient() //.渐变 ``` ## image - Image.asset 本地 ```dart Image.asset( String name, { Key key, AssetBundle bundle, this.frameBuilder, this.errorBuilder, this.semanticLabel, this.excludeFromSemantics = false, double scale, this.width, this.height, this.color, this.colorBlendMode, this.fit, |-BoxFit.cover //不变形 this.alignment = Alignment.center, this.repeat = ImageRepeat.noRepeat, this.centerSlice, this.matchTextDirection = false, this.gaplessPlayback = false, String package, this.filterQuality = FilterQuality.low, int cacheWidth, int cacheHeight, }) ``` ```dart lib同级目录下 创建images文件 |-images |-2.0x |-3.0x |-a.png new Image.asset('images/logo.png') ``` ``` pubspec.yaml flutter: # The following line ensures that the Material Icons font is # included with your application, so that you can use the icons in # the material Icons class. uses-material-design: true assets: - images/logo.png - images/2.0x/logo.png - images/3.0x/logo.png ``` - Image.network 网路 ```dart new Image.network ('https://test.jpg')) ``` - Image.file ```dart 加载本地图片 new Image.file(new File('/storage/xxx/xxx/test.jpg')) ``` ## form ```dart class MyStatefulWidget extends StatefulWidget { MyStatefulWidget({Key key}) : super(key: key); @override _MyStatefulWidgetState createState() => _MyStatefulWidgetState(); } class _MyStatefulWidgetState extends State<MyStatefulWidget> { final _formKey = GlobalKey<FormState>(); var userName = new TextEditingController(); // 声明 @override void initState() { super.initState(); userName.text = '22220'; } var flag = true; @override Widget build(BuildContext context) { return Form( key: _formKey, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ TextFormField( decoration: const InputDecoration( hintText: 'Enter your email', ), validator: (value) { if (value.isEmpty) { return 'Please enter some text'; } return null; }, controller: userName, //绑定 onChanged: (value){ print('$value'); print(userName.text); // 双向绑定 }, ), Padding( padding: const EdgeInsets.symmetric(vertical: 16.0), child: RaisedButton( onPressed: () { // Validate will return true if the form is valid, or false if // the form is invalid. if (_formKey.currentState.validate()) { // Process data. print('sss'); } }, child: Text('Submit'), ), ), Checkbox(value:this.flag, onChanged: (value){ setState(() { this.flag = value; print(!value); }); }) ], ), ); } } ``` ### input ```dart const TextField({ Key key, this.controller, //编辑框的控制器,跟文本框的交互一般都通过该属性完成,如果不创建的话默认会自动创建 this.focusNode, //用于管理焦点 this.decoration = const InputDecoration(), //输入框的装饰器,用来修改外观 TextInputType keyboardType, //设置输入类型,不同的输入类型键盘不一样 this.textInputAction, //用于控制键盘动作(一般位于右下角,默认是完成) this.textCapitalization = TextCapitalization.none, this.style, //输入的文本样式 this.textAlign = TextAlign.start, //输入的文本位置 this.textDirection, //输入的文字排列方向,一般不会修改这个属性 this.autofocus = false, //是否自动获取焦点 this.obscureText = false, //是否隐藏输入的文字,一般用在密码输入框中 this.autocorrect = true, //是否自动校验 this.maxLines = 1, //最大行 this.maxLength, //能输入的最大字符个数 this.maxLengthEnforced = true, //配合maxLength一起使用,在达到最大长度时是否阻止输入 this.onChanged, //输入文本发生变化时的回调 this.onEditingComplete, //点击键盘完成按钮时触发的回调,该回调没有参数,(){} this.onSubmitted, //同样是点击键盘完成按钮时触发的回调,该回调有参数,参数即为当前输入框中的值。(String){} this.inputFormatters, //对输入文本的校验 this.enabled, //输入框是否可用 this.cursorWidth = 2.0, //光标的宽度 this.cursorRadius, //光标的圆角 this.cursorColor, //光标的颜色 this.keyboardAppearance, this.scrollPadding = const EdgeInsets.all(20.0), this.dragStartBehavior = DragStartBehavior.down, this.enableInteractiveSelection, this.onTap, //点击输入框时的回调(){} this.buildCounter, }) ``` ### 表单验证 ``` https://www.jianshu.com/p/3fb613ffac22 ``` checkbox ``` RadioListTile( value: 1, onChanged: (v) { setState(() { this.sex = v; }); }, groupValue: this.sex, ), ``` ``` RadioListTile( groupValue: this.sex, onChanged: (value) { print(value); setState(() { this.sex = value; }); }, value: 1, title: Text('sss'), ), ``` ### TextField ``` https://www.cnblogs.com/joe235/p/11711653.html ``` 复制粘贴设置成中文 ``` -pubspec.yaml dependencies: flutter: sdk: flutter flutter_localizations: sdk: flutter ``` ```dart return MaterialApp( localizationsDelegates: [ GlobalMaterialLocalizations.delegate, GlobalWidgetsLocalizations.delegate, ], supportedLocales: [ const Locale('zh', 'CN'), const Locale('en', 'US'), ] } ``` ```dart Key key, this.controller, // 控制正在编辑文本 this.focusNode, // 获取键盘焦点 this.decoration = const InputDecoration(), // 边框装饰 TextInputType keyboardType, // 键盘类型 this.textInputAction, // 键盘的操作按钮类型 this.textCapitalization = TextCapitalization.none, // 配置大小写键盘 this.style, // 输入文本样式 this.textAlign = TextAlign.start, // 对齐方式 this.textDirection, // 文本方向 this.autofocus = false, // 是否自动对焦 this.obscureText = false, // 是否隐藏内容,例如密码格式 this.autocorrect = true, // 是否自动校正 this.maxLines = 1, // 最大行数 this.maxLength, // 允许输入的最大长度 this.maxLengthEnforced = true, // 是否允许超过输入最大长度 this.onChanged, // 文本内容变更时回调 this.onEditingComplete, // 提交内容时回调 this.onSubmitted, // 用户提示完成时回调 this.inputFormatters, // 验证及格式 this.enabled, // 是否不可点击 this.cursorWidth = 2.0, // 光标宽度 this.cursorRadius, // 光标圆角弧度 this.cursorColor, // 光标颜色 this.keyboardAppearance, // 键盘亮度 this.scrollPadding = const EdgeInsets.all(20.0), // 滚动到视图中时,填充边距 this.enableInteractiveSelection, // 长按是否展示【剪切/复制/粘贴菜单LengthLimitingTextInputFormatter】 this.onTap, ``` ```dart import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; ///整理 //TextField 输入文本 decoration 配置边框样式以及提示文本分析篇 class TextFeildHomePage5 extends StatefulWidget { @override State<StatefulWidget> createState() { return TextFeildHomePageState(); } } class TextFeildHomePageState extends State { ///用来控制 TextField 焦点的获取与关闭 FocusNode focusNode = new FocusNode(); ///文本输入框是否可编辑 bool isEnable = true; @override void initState() { super.initState(); ///添加获取焦点与失去焦点的兼听 focusNode.addListener((){ ///当前兼听的 TextFeild 是否获取了输入焦点 bool hasFocus = focusNode.hasFocus; ///当前 focusNode 是否添加了兼听 bool hasListeners = focusNode.hasListeners; print("focusNode 兼听 hasFocus:$hasFocus hasListeners:$hasListeners"); }); /// WidgetsBinding 它能监听到第一帧绘制完成,第一帧绘制完成标志着已经Build完成 WidgetsBinding.instance.addPostFrameCallback((_) { ///获取输入框焦点 FocusScope.of(context).requestFocus(focusNode); }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( actions: <Widget>[ FlatButton(child: Text("获取焦点"),onPressed: (){ FocusScope.of(context).requestFocus(focusNode); },), FlatButton(child: Text("失去焦点"),onPressed: (){ focusNode.unfocus(); },), FlatButton(child: Text("编辑"),onPressed: (){ setState(() { isEnable = true; }); },), FlatButton(child: Text("不可编辑"),onPressed: (){ setState(() { isEnable = false; }); },), ], ), body: Container( ///SizedBox 用来限制一个固定 width height 的空间 child: SizedBox( width: 400, height: 130, child: Container( color: Colors.white24, ///距离顶部 margin: EdgeInsets.only(top: 30), padding: EdgeInsets.all(10), ///Alignment 用来对齐 Widget alignment: Alignment(0, 0), ///文本输入框 child: TextField( ///是否可编辑 enabled: isEnable, ///焦点获取 focusNode: focusNode, ///用来配置 TextField 的样式风格 decoration: InputDecoration( ///设置输入文本框的提示文字 ///输入框获取焦点时 并且没有输入文字时 hintText: "请输入用户名", ///设置输入文本框的提示文字的样式 hintStyle: TextStyle(color: Colors.grey,textBaseline: TextBaseline.ideographic,), ///输入框内的提示 输入框没有获取焦点时显示 labelText: "用户名", labelStyle: TextStyle(color: Colors.blue), ///显示在输入框下面的文字 helperText: "这里是帮助提示语", helperStyle: TextStyle(color: Colors.green), ///显示在输入框下面的文字 ///会覆盖了 helperText 内容 errorText: "这里是错误文本提示", errorStyle: TextStyle(color: Colors.red), ///输入框获取焦点时才会显示出来 输入文本的前面 prefixText: "prefix", prefixStyle: TextStyle(color: Colors.deepPurple), ///输入框获取焦点时才会显示出来 输入文本的后面 suffixText: "suf ", suffixStyle: TextStyle(color: Colors.black), ///文本输入框右下角显示的文本 ///文字计数器默认使用 counterText: "count", counterStyle:TextStyle(color: Colors.deepPurple[800]), ///输入文字前的小图标 prefixIcon: Icon(Icons.phone), ///输入文字后面的小图标 suffixIcon: Icon(Icons.close), ///与 prefixText 不能同时设置 // prefix: Text("A"), /// 与 suffixText 不能同时设置 // suffix: Text("B"), ///设置边框 /// InputBorder.none 无下划线 /// OutlineInputBorder 上下左右 都有边框 /// UnderlineInputBorder 只有下边框 默认使用的就是下边框 border: OutlineInputBorder( ///设置边框四个角的弧度 borderRadius: BorderRadius.all(Radius.circular(10)), ///用来配置边框的样式 borderSide: BorderSide( ///设置边框的颜色 color: Colors.red, ///设置边框的粗细 width: 2.0, ), ), ///设置输入框可编辑时的边框样式 enabledBorder: OutlineInputBorder( ///设置边框四个角的弧度 borderRadius: BorderRadius.all(Radius.circular(10)), ///用来配置边框的样式 borderSide: BorderSide( ///设置边框的颜色 color: Colors.blue, ///设置边框的粗细 width: 2.0, ), ), disabledBorder: OutlineInputBorder( ///设置边框四个角的弧度 borderRadius: BorderRadius.all(Radius.circular(10)), ///用来配置边框的样式 borderSide: BorderSide( ///设置边框的颜色 color: Colors.red, ///设置边框的粗细 width: 2.0, ), ), ///用来配置输入框获取焦点时的颜色 focusedBorder: OutlineInputBorder( ///设置边框四个角的弧度 borderRadius: BorderRadius.all(Radius.circular(20)), ///用来配置边框的样式 borderSide: BorderSide( ///设置边框的颜色 color: Colors.green, ///设置边框的粗细 width: 2.0, ), ), ), ), ), ), ), ); } } ``` ### 失去焦点 ```dart GestureDetector( behavior: HitTestBehavior.translucent, onTap: () { FocusScope.of(context).requestFocus(FocusNode()); }, ) ``` ## 点击事件 ```dart InkWell,GestureDetector,RaisedButton。 ``` # GestureDetector ```dart GestureDetector behavior: HitTestBehavior.opaque // 事件可穿透 HitTestBehavior.deferToChild // child处理事件 HitTestBehavior.translucent // 自己和child都可以响应事件 ``` # redux ```dart redux: ^4.0.0+3 ``` main.dart ```dart import 'package:redux/redux.dart'; class MyApp extends StatelessWidget { final store = new Store<AppState>( appReducer, ); MyApp(); ... } ``` store/init.dart ```dart import 'package:flutter/material.dart'; import 'package:redux/redux.dart'; class AppState { String token; ThemeData themeData; AppState({this.token, this.themeData}); } AppState appReducer(state, action) { return AppState( token: UpdateToken(state.token, action), themeData: UpdateTheme(state.themeData, action), ); } final UpdateToken = combineReducers<String>([TypedReducer<String, TokenAction>(_refToken)]); final UpdateTheme = combineReducers<ThemeData>( [TypedReducer<ThemeData, ThenmeAction>(_refTheme)]); // 更新 String _refToken(String token, action) { token = action.token; return token; } ThemeData _refTheme(ThemeData themeData, action) { themeData = action.themeData; return themeData; } // set new state class TokenAction { final token; TokenAction(this.token); } class ThenmeAction { final themeData; ThenmeAction(this.themeData); } ``` 更新视图方法 ``` flutter_redux: ^0.7.0 ``` ```dart class MyApp extends StatelessWidget { final store = new Store<AppState>( appReducer, // 初始化 initialState:AppState( themeData:ThemeData(), ), ); MyApp(); ... @override Widget build(BuildContext context) { return Storeprovider( store:store, child:StoreBuilder<Appstate>(builder:(context,store){ return MaterialApp( theme:store.state.themeDate, ); }), ); } } ``` # routes MaterialPageRoute `MaterialPageRoute`继承自`PageRoute`类,`PageRoute`类是一个抽象类,表示占有整个屏幕空间的一个模态路由页面,它还定义了路由构建及切换时过渡动画的相关接口及属性。`MaterialPageRoute` 是Material组件库提供的组件,它可以针对不同平台,实现与平台页面切换动画风格一致的路由切换动画: ``` MaterialPageRoute({ WidgetBuilder builder, RouteSettings settings, bool maintainState = true, bool fullscreenDialog = false, //返回按键变X }); ``` - `builder` 是一个WidgetBuilder类型的回调函数,它的作用是构建路由页面的具体内容,返回值是一个widget。我们通常要实现此回调,返回新路由的实例。 - `settings` 包含路由的配置信息,如路由名称、是否初始路由(首页)。 - `maintainState`:默认情况下,当入栈一个新路由时,原来的路由仍然会被保存在内存中,如果想在路由没用的时候释放其所占用的所有资源,可以设置`maintainState`为false。 - `fullscreenDialog`表示新的路由页面是否是一个全屏的模态对话框,在iOS中,如果`fullscreenDialog`为`true`,新页面将会从屏幕底部滑入(而不是水平方向)。 普通路由: ```dart import '../home/HomeTest.dart'; //进入 navigattor.of(context).push(MaterialPageRoute( builder:(context){ return HomeTest() } )) //进入 Navigator.push( context, MaterialPageRoute(builder: (context) { return HomeTest(); }), ); //返回 Navigator.of(context).pop(); Navigator.of().pushNamed('/home') //命名路由 ``` 普通路由传值: ```dart Navigator.push( context, MaterialPageRoute( builder: (context) { return HomeTest(title:'wo'); }, ), ); // 传值 class HomeTest extends StatefulWidget { HomeTest({Key key, this.title}) : super(key: key); final String title; //接收 @override _HomeTestState createState() => _HomeTestState(); } class _HomeTestState extends State<HomeTest> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title:Text(widget.title), // 赋值 ), body: Text('data'), ); } } ``` 命名路由: ```dart 申明: main.dart import 'package:flutter/material.dart'; import './routers/router.dart'; import './home/HomeTest.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( routes:{ '/home':(context)=>HomeTest(), //申明 全局引用 }, initialRoute: "/", onGenerateRoute: onGenerateRoute, ); } }; 页面调用: Navigator.pushNamed(context, '/home',); ``` 动态图命名路由传值: ``` Navigator.pushNamed(context, '/HomeTest',arguments: {'title':'4444'}); 传参数; ``` ``` import 'package:flutter/material.dart'; import '../Tabs/Tabs.dart'; //配置路由 import '../home/HomeTest.dart'; 动态路由配置: final routes = { '/': (context) => Tabs(), '/HomeTest': (context, {arguments}) => HomeTest(arguments: arguments), }; // ignore: top_level_function_literal_block var onGenerateRoute = (RouteSettings settings) { // 统一处理 final String name = settings.name; final Function pageContentBuilder = routes[name]; if (pageContentBuilder!= null) { if (settings.arguments!= null) { print(name); final Route route = MaterialPageRoute( builder: (context) => pageContentBuilder(context, arguments: settings.arguments)); return route; } else { final Route route = MaterialPageRoute(builder: (context) => pageContentBuilder(context)); return route; } } }; ``` ```dart import 'package:flutter/material.dart'; class HomeTest extends StatefulWidget { final arguments; // 接收 HomeTest({Key key, this.arguments}) : super(key: key); @override _HomeTestState createState() => _HomeTestState(); } class _HomeTestState extends State<HomeTest> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.arguments['title']), //使用 ), body: FloatingActionButton( child: Text('2'), onPressed: () { Navigator.of(context).pop(); }, ), ); } } ``` 页面返回返回参数: ```dart Navigator.of(context).pop('返回'); // 传参 写法一: Navigator.push( context, MaterialPageRoute( builder: (context) { return HomeTest(arguments:{'title':'mytitle'}); }, // fullscreenDialog: true, ), ).then((value){ print('222222'); print(value); }); 写法二: Future future = Navigator.pushNamed( context, '/HomeTest', arguments: {'title': '上个页面的title'}, ); future.then((value) { print('value--------'); print(value); }); 写法三: Navigator.of(context).pushNamed( '/HomeTest', arguments: {'title': '上个页面的title'}, ).then((value) { print(value); print('999'); }); 注:点击顶部返回,手机手势返回;不能捕获参数; ``` 钩子 ``` onGenerateRoute(settings) onUnkonwnRoute //不存在路由 ``` 例 ``` routes:{ '/home':(context)=>About() }, initialRoute:'/', //默认路径 onGenerateRoute:(settings){ if(settings.name == '/home'){ return MaterialPageRoute( builder:(context)=>HOme(settings.arguments) ); } }, onUnkonwnRoute(){ return MaterialPageRoute( builder:(context)=>Eer(settings.arguments) ); } ``` ```dart import 'package:flutter/material.dart'; import '../Tabs/Tabs.dart'; //配置路由 final routes = { '/': (context) => Tabs(), }; //固定写法 var onGenerateRoute = (RouteSettings settings) { // 统一处理 final String name = settings.name; final Function pageContentBuilder = routes[name]; if (pageContentBuilder!= null) { if (settings.arguments!= null) { final Route route = MaterialPageRoute( builder: (context) => pageContentBuilder(context, arguments: settings.arguments)); return route; } else { final Route route = MaterialPageRoute(builder: (context) => pageContentBuilder(context)); return route; } } }; ``` ## pushNamedAndRemoveUntil ```dart //前进 Navigator.of(context) .pushNamedAndRemoveUntil( “跳转路径”, ModalRoute.withName('/demo'),//清除旧栈需要保留的栈 不清除就不写这句 arguments:{"data":“233”}//传值 ); Navigator.of(context) .pushNamedAndRemoveUntil( '/', // new page ModalRoute.withName('/Welcome') //当前页面 关闭页面 ); Navigator.pushNamedAndRemoveUntil( context, "跳转路径", (route) => false,//true保留跳转的当前栈 false 不保留 ); ``` ## pushReplacementNamed ```dart 替换当前页面 Navigator.of(context).pushReplacementNamed('/screen4'); Navigator.pushReplacementNamed(context, '/settings/brightness'); ``` ## fractionsizedbox ``` 百分 ``` # bottomNavigationBar ```dart import 'package:flutter/material.dart'; import './Category.dart'; import './Home.dart'; import './My.dart'; import './User.dart'; class Tabs extends StatefulWidget { Tabs({Key key, this.title}) : super(key: key); final String title; @override _TabsState createState() => _TabsState(); } class _TabsState extends State<Tabs> { int _currentIndex = 0; List _TabsPages = [Home(), Category(), My(), User()]; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: _TabsPages[this._currentIndex], bottomNavigationBar: BottomNavigationBar( currentIndex: this._currentIndex, onTap: (index) { setState(() { this._currentIndex = index; }); }, type: BottomNavigationBarType.fixed, // 多个底部导航栏需要配置 items: [ BottomNavigationBarItem( title: Text("首页"), icon: Icon(Icons.home), ), BottomNavigationBarItem( title: Text("分类"), icon: Icon(Icons.category), ), BottomNavigationBarItem( title: Text("购物车"), icon: Icon(Icons.shopping_cart), ), BottomNavigationBarItem( title: Text("我的"), icon: Icon(Icons.people), ), ]), ); } } ``` ```dart main.dart import 'package:flutter/material.dart'; import "./Tabs/Tabs.dart"; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.red, visualDensity: VisualDensity.adaptivePlatformDensity, ), home: Tabs(title: 'walle JD'), ); } } ``` # 获取定位 1. 申请高德key; 2. 创建应用; 3. 获取sha1,获取包名; 4. ``` keytool -list -v -keystore F:/androiddebugkey.jks ``` 5. 声明权限; ``` 参考:https://blog.csdn.net/qq_42772570/article/details/101671009 https://blog.csdn.net/Gemini_Kanon/article/details/104628500?utm_medium=distribute.pc_aggpage_search_result.none-task-blog-2~all~sobaiduend~default-4-104628500.nonecase&utm_term=flutter%20%E8%8E%B7%E5%8F%96%E4%BD%8D%E7%BD%AE%E4%BF%A1%E6%81%AF&spm=1000.2123.3001.4430 https://lbs.amap.com/faq/android/map-sdk/create-project/43112 ``` 参考:https://blog.csdn.net/qq_44749053/article/details/101102785 ``` 依赖: amap_location: ^0.2.0 permission_handler: ^3.2.0 // 权限判断 引入: import 'package:amap_location/amap_location.dart'; import 'package:permission_handler/permission_handler.dart'; //权限 ``` ```dart 检查权限: //检测权限状态 void checkPersmission() async { // 申请权限 Map<PermissionGroup, PermissionStatus> permissions = await PermissionHandler() .requestPermissions([PermissionGroup.location]); // 申请结果 PermissionStatus permission = await PermissionHandler() .checkPermissionStatus(PermissionGroup.location); if (permission == PermissionStatus.granted) { _getLocation(); } else { print('定位权限申请被拒绝'); bool isOpened = await PermissionHandler().openAppSettings(); //打开应用设置 } } ``` ```dart 监听: void _getLocation() async { //先启动一下 await AMapLocationClient.startup(new AMapLocationOption( desiredAccuracy: CLLocationAccuracy.kCLLocationAccuracyHundredMeters)); //直接获取定位 var result = await AMapLocationClient.getLocation(true); print('result--$result'); print(""" 经度:${result.longitude} 纬度:${result.latitude} """); var lat = result.latitude; var lng = result.longitude; if (lat.toString().isNotEmpty && lng.toString().isNotEmpty) { } else { print('获取位置失败,请检测GPS是否开启!'); } // 关闭 // AMapLocationClient.stopLocation(); //停止定位 //监听定位 // AMapLocationClient.onLocationUpate.listen((AMapLocation loc) { // if (!mounted) return; // setState(() { // print(""" // 经度:${result.longitude} // 纬度:${result.latitude} // """); // }); // }); // 开始监听 // AMapLocationClient.startLocation(); } ``` android下的 build.gradle ```dart defaultConfig { // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). applicationId "com.example.myjd" minSdkVersion 16 targetSdkVersion 28 versionCode flutterVersionCode.toInteger() versionName flutterVersionName +manifestPlaceholders = [ AMAP_KEY : "d7aba329530bff4dce38b06aed63db8d", /// 高德地图key ] } dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" +implementation 'com.amap.api:location:latest.integration' // 高德地图依赖 +implementation 'androidx.appcompat:appcompat:1.0.0' } ``` android下的>src>AndroidManifest.xml ```dart <application> ... +<meta-data android:name="com.amap.api.v2.apikey" android:value="d7aba329530bff4dce38b06aed--高德的key" /> +<service android:name="com.amap.api.location.APSService"></service> </application> ``` android下的>src>main>profile>AndroidManifest.xml ```dart <!--用于访问GPS定位--> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission> <!--用于获取运营商信息,用于支持提供运营商信息相关的接口--> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission> <!--用于访问wifi网络信息,wifi信息会用于进行网络定位--> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission> ``` # 问题 'getAppBarWidget' can't be assigned to the parameter type 'PreferredSizeWidget'. ```dart import 'package:flutter/material.dart'; class HomeAppBar extends StatelessWidget implements PreferredSizeWidget { //加入 接口PreferredSizeWidget @override Widget build(BuildContext context) { return PreferredSize( child: AppBar( title: Image.asset('images/jd.png'), backgroundColor: Colors.red, actions: <Widget>[ Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Icon(Icons.crop_free), Text('扫一扫', style: TextStyle(fontSize: 6.0)) ], ), Padding(padding: EdgeInsetsDirectional.fromSTEB(0, 0, 10, 0)), Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Icon(Icons.sms), Text('消息', style: TextStyle(fontSize: 6.0)) ], ), Padding(padding: EdgeInsetsDirectional.fromSTEB(0, 0, 20, 0)) ], ), preferredSize: Size.fromHeight(44), ); } // final String name; // HomeAppBar({Key key, @required this.name}) :super(key: key); @override // TODO: implement preferredSize Size get preferredSize => getSize(); getSize() { return new Size(100.0, 44.0); } } ``` ## 去除顶部半透明 ![360截图20200427015824935.png](Dart-flutter.assets/4158227332-5ea654ce483c9_articlex.png) ```kotlin package com.example.helloflutter import io.flutter.embedding.android.FlutterActivity //---增加部分 import android.os.Build; import android.os.Bundle; //----end class MainActivity: FlutterActivity() { //-----增加部分 //设置状态栏沉浸式透明(修改flutter状态栏黑色半透明为全透明) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { window.statusBarColor = 0 } } //---- end } ``` ## flutter_swiper 裁剪border radius ```dart 外层加入: PhysicalModel( color: Colors.transparent, borderRadius: BorderRadius.circular(12), clipBehavior: Clip.antiAlias, ) ``` ## BottomNavigation切换保持 ```dart class _TabsState extends State<Tabs> { int _currentIndex = 0; List _TabsPages = [Home(), Category(), My(), User()]; var _pageController = PageController(); // 一 @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("flutter ZJ"), ), body: PageView.builder( // 二 physics: NeverScrollableScrollPhysics(), //禁止页面左右滑动切换 controller: _pageController, onPageChanged: (int index) { if (index!= _currentIndex) { setState(() { _currentIndex = index; }); } }, //回调函数 itemCount: _TabsPages.length, itemBuilder: (context, index) => _TabsPages[index]),// 三 bottomNavigationBar: BottomNavigationBar( currentIndex: this._currentIndex, onTap: (index) { setState(() { _pageController.jumpToPage(index); }); }, type: BottomNavigationBarType.fixed, items: [ BottomNavigationBarItem( title: Text("首页"), icon: Icon(Icons.home), ), //.... ]), ); } } ``` ```dart 子页面 class _HomeState extends State<Home> with AutomaticKeepAliveClientMixin { // AutomaticKeepAliveClientMixin @override bool get wantKeepAlive => true; // } ``` ``` https://blog.csdn.net/qq_32687703/article/details/95645331?utm_medium=distribute.pc_aggpage_search_result.none-task-blog-2~all~first_rank_v2~rank_v28-6-95645331.nonecase&utm_term=flutter%20%E5%BD%93%E5%89%8D%E9%A1%B5%E9%9D%A2%E6%98%AF%E5%90%A6%E5%8F%AF%E8%A7%81&spm=1000.2123.3001.4430 ``` ``` https://blog.csdn.net/c6e5uli1n/article/details/104666263 ``` # flutter 插件 ### 国外论坛 ``` https://dev.to/ ``` ### 工具集 ``` https://dev.to/parabeac/5-tools-to-supercharge-your-flutter-development-1m0l ``` ### flutter_swiper 地址:https://pub.dev/packages/flutter_swiper ```dart import 'package:flutter/material.dart'; import 'package:flutter_swiper/flutter_swiper.dart'; class Home extends StatefulWidget { Home({Key key, this.title}) : super(key: key); final String title; @override _HomeState createState() => _HomeState(); } class _HomeState extends State<Home> { var title; Widget _swiperview() { List<String> imgList = [ "https://zhijia-pro.oss-cn-shenzhen.aliyuncs.com/h5/ad/AI%E9%A3%8E%E6%A0%BCh5.png", "https://zhijia-pro.oss-cn-shenzhen.aliyuncs.com/h5/ad/AI%E6%99%BA%E9%80%89%20%28h5%29.png", "https://zhijia-pro.oss-cn-shenzhen.aliyuncs.com/h5/ad/0%E5%85%83%E6%90%9E%E5%AE%9A%E8%AE%BE%E8%AE%A1h5.png", ]; return Container( // 必须设置宽高 或AspectRatio 设置宽高比 child: AspectRatio( aspectRatio: 540 / 216, child: Swiper( itemBuilder: (BuildContext context, int index) { return new Image.network( imgList[index], fit: BoxFit.cover, ); }, itemCount: imgList.length, // pagination: new SwiperPagination(), pagination: SwiperPagination( builder: RectSwiperPaginationBuilder( size: Size(20.0, 8.0), activeSize: Size(20.0, 8.0), activeColor: Colors.white, color: Colors.black, ), alignment: Alignment.bottomCenter, ), // control: new SwiperControl(), autoplay: true, loop: true, // viewportFraction: 0.8, // scale: 0.9, ), ), ); } @override Widget build(BuildContext context) { return ListView( children: [ _swiperview(), ], ); } } ``` ### flutter_screenutil ``` dependencies: flutter: sdk: flutter # 添加依赖 flutter_screenutil: ^2.3.0 ``` ``` import 'package:flutter_screenutil/flutter_screenutil.dart'; ``` ``` https://pub.dev/packages/flutter_screenutil ``` ``` // 需要放入build 中; 要放入路由之后; ScreenUtil.init(context, width: 750, height: 1334, allowFontScaling: false); width: ScreenUtil().setWidth(335), height: ScreenUtil().setHeight(221), ``` ### 调试工具 ``` https://flutter.dev/docs/development/tools/devtools/vscode ``` 获取设备信息 ``` https://segmentfault.com/a/1190000014913010?utm_source=index-hottest device_info: ``` 定位 ``` amap_location: ``` permission_handler ``` 权限 ``` # 打包 参考:https://www.jianshu.com/p/04eb531da438 ```dart 项目根目录/android/app/src/main/AndroidManifest.xml android:label="flutter_app" //配置APP的名称,支持中文 android:icon="@mipmap/ic_launcher" //APP图标的文件名称,所以这个图标文件名可以在这个地方配置 ``` 生成 keystore ``` 在VScode输入flutter doctor -v找到Android toolchain栏目下的Java binary at:,复制这个标题项的地址。 我Mac的地址是/Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java 在VScode的终端输入查询到的java根目录地址以及keytool -genkey -v -keystore F:/key.jks -keyalg RSA -keysize 2048 -validity 10000 -alias key 即:/Applications/'Android Studio.app'/Contents/jre/jdk/Contents/Home/bin/keytool -genkey -v -keystore ~/key.jks -keyalg RSA -keysize 2048 -validity 10000 -alias key 回车后,他会要求你输入密钥库口令,记住你的口令,稍后会用到。 继续操作后,还会要求你的密钥密码,同样也要记住这个密码。 之后在你的user目录下生成key.jks.这个key.jks路径可以在上面的命令行中修改。记住这个文件不能共享给任何人! 有了这个key.jks文件后,可以到项目目录下的android文件夹下,创建一个名为key.properties的文件,并打开粘贴下面的代码。 ``` ### build.gradle ```dart buildscript { ext.kotlin_version = '1.3.50' repositories { // google() // jcenter() maven { url 'https://maven.aliyun.com/repository/google' } maven { url 'https://maven.aliyun.com/repository/jcenter' } maven { url 'http://maven.aliyun.com/nexus/content/groups/public' } } dependencies { classpath 'com.android.tools.build:gradle:3.5.0' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" } } allprojects { repositories { // google() // jcenter() maven { url 'https://maven.aliyun.com/repository/google' } maven { url 'https://maven.aliyun.com/repository/jcenter' } maven { url 'http://maven.aliyun.com/nexus/content/groups/public' } } } rootProject.buildDir = '../build' subprojects { project.buildDir = "${rootProject.buildDir}/${project.name}" } subprojects { project.evaluationDependsOn(':app') } task clean(type: Delete) { delete rootProject.buildDir } ``` app下 build.gradle ``` def localProperties = new Properties() def localPropertiesFile = rootProject.file('local.properties') if (localPropertiesFile.exists()) { localPropertiesFile.withReader('UTF-8') { reader -> localProperties.load(reader) } } def flutterRoot = localProperties.getProperty('flutter.sdk') if (flutterRoot == null) { throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.") } def flutterVersionCode = localProperties.getProperty('flutter.versionCode') if (flutterVersionCode == null) { flutterVersionCode = '1' } def flutterVersionName = localProperties.getProperty('flutter.versionName') if (flutterVersionName == null) { flutterVersionName = '1.0' } apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle" def keystorePropertiesFile = rootProject.file("key.properties") def keystoreProperties = new Properties() keystoreProperties.load(new FileInputStream(keystorePropertiesFile)) android { compileSdkVersion 28 sourceSets { main.java.srcDirs +='src/main/kotlin' } lintOptions { disable 'InvalidPackage' checkReleaseBuilds false //新增 } defaultConfig { // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). applicationId "com.example.myjd" minSdkVersion 16 targetSdkVersion 28 versionCode flutterVersionCode.toInteger() versionName flutterVersionName } signingConfigs { release { keyAlias keystoreProperties['keyAlias'] keyPassword keystoreProperties['keyPassword'] storeFile file(keystoreProperties['storeFile']) storePassword keystoreProperties['storePassword'] } } buildTypes { release { // TODO: Add your own signing config for the release build. // Signing with the debug keys for now, so `flutter run --release` works. signingConfig signingConfigs.release // signingConfig signingConfigs.debug } } } flutter { source '../..' } dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" } ``` android 目录下 创建key.properties ``` storePassword=<PASSWORD> keyPassword=<PASSWORD> keyAlias=key storeFile=F:/key.jks ``` 打包命令 ``` flutter build apk ``` 在线生成图标 ``` https://appiconmaker.co/Home/ https://icon.wuruihong.com 代码插件:flutter_launcher_icons https://pub.dev/packages/flutter_launcher_icons#-readme-tab- ``` 声明 ``` <!--用于进行网络定位--> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission> <!--用于访问GPS定位--> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission> <!--用于获取运营商信息,用于支持提供运营商信息相关的接口--> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission> <!--用于访问wifi网络信息,wifi信息会用于进行网络定位--> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission> <!--用于获取wifi的获取权限,wifi信息会用来进行网络定位--> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission> <!--用于访问网络,网络定位需要上网--> <uses-permission android:name="android.permission.INTERNET"></uses-permission> <!--用于读取手机当前的状态--> <uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission> <!--用于写入缓存数据到扩展存储卡--> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission> <!--用于申请调用A-GPS模块--> <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS"></uses-permission> <!--用于申请获取蓝牙信息进行室内定位--> <uses-permission android:name="android.permission.BLUETOOTH"></uses-permission> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"></uses-permission> ``` # 教程 ``` 这个项目屌 收录了Flutter 300多个组件演示 https://github.com/toly1994328/FlutterUnit ``` ``` http://laomengit.com/ ``` ``` 咸鱼技术分享 https://www.yuque.com/xytech/flutter/lgxv30 ``` 一、试用期个人工作总结: 1.2020年8月7日,有幸加入公司技术部,在工作三个月中在团队的指导与合作下,快速熟悉公司业务、工作内容以及未来公司开发方向。现将我试用期的工作内容做简要小结: 一、个人工作内容总结: 1.8月负责pc端页面商户后台的页面开: - 其中完成两个项目从0到1的项目架构搭建; - 完成了pc业主端20+页面的交互,联调; - 完了pc商户端登录模块、招标、内容管理、活动活理、关于公司、设置等各个大小模块; 2.9月份负责业主端改版,商户功能修复优化: - 为了更好支持seo,以及美化,对pc端进行重构与页面改版;采用mvc开发方式与后户端配合,静态页面采用jquery完成了重写,以及页面改版迭代; - 完成pc商户端相关bug修复;微信扫码登录、绑定的功能迭代;期间对项目结构优化分离、打包压缩优化,减少项目包大小,提升首页加载时间; 3.10月份负责微信小程序,头条小程序开发,bos后台、app: - 采用uniapp开发小程序;完成了大数据报价,在线报价,首页和其余的webview跳转等页面; - 其中完成微信小程序和头条小程序,百度小程序所有页面的三端完美适配;完成了微信小程序与头条小程序的上线发布 - 完成了bos后台广告管理与字典、黑白名单模块的开发; - 使用flutter跨平台开发app;完成了项目架构的搭建,初步完成了首页与webview,解决了打包问题; 二、对以后工作的计划: 1.增强flutter语言开发效率,完成安卓与ios所需功能的开发; 2.学习krpano的使用,为开发全景展示做准备; 3.学习webGL,具备将3Dmax文件导入到web中进行展示,以及相应功能的开发能力; ======================= File: 16、前端性能/前端性能.md ======================= <reponame>WALL-E-WEB/-notes- # 性能评测工具 1.pagespeed insights https://developers.google.cn/speed/pagespeed/insights/ 2.chrome user experience report 3.google searchconsole speedreport 4.fireperf audit panel performance budget profile panel lighthouse cl your speedtoolbox 优化 1.pagespeed insights https://developers.google.cn/speed/pagespeed/insights/ 2.chrome user experience report 3.google searchconsole speedreport 4.fireperf audit panel performance budget profle panel lighthouse cl your speedtoolbox 优化 ======================= File: 01、HTML-CSS/html-css.md ======================= <reponame>WALL-E-WEB/-notes- # HTML-CSS ## HTML固定结构代码 ```javascript <!DOCTYPE html> <html> <head> <title>网页标题</title> </head> <body> </body> </html> ``` ```html <!DOCTYPE html> 指定当前文档类型为html5版本 <html lang="en"> 页面的一个根节点,网页从哪里开始到哪里结束 <head> 头部标签,用来存放页面辅助型标签,例如:title,meta,base,style,link等 <title> 网页标题标签,被head标签包裹,让页面拥有标题 <body> 主体标签,所有页面的内容,都是存放在这个标签内部 ``` ```html <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0 user-scalable=no"> name="viewport" //视口 content="width=device-width //适配宽度 initial-scale=1.0 //网页加载不缩放 user-scalable=no //禁止用户手动缩放 <meta http-equiv="X-UA-Compatible" content="ie=edge"> <meta name="description" content="描述说明"> <meta name="keyword" content="关键字"> <title>王昌然</title> //标题 <link rel="shortcut icon" href=""> //头标图标 <link rel="stylesheet" href="./css/base.css"> <link rel="stylesheet" href="./css/common.css"> <link rel="stylesheet" href="./css/index.css"> <link rel="stylesheet" href="./fonts/iconfont.css"> //字体图标 ``` ### viewport ```html width:控制 viewport 的大小,可以指定的一个值,如果 600,或者特殊的值,如 device-width 为设备的宽度(单位为缩放为 100% 时的 CSS 的像素)。 height:和 width 相对应,指定高度。 initial-scale:初始缩放比例,也即是当页面第一次 load 的时候缩放比例。 maximum-scale:允许用户缩放到的最大比例。 minimum-scale:允许用户缩放到的最小比例。 user-scalable:用户是否可以手动缩放。 以下实例演示了使用viewport和没使用viewport在移动端上的效果: ``` ``` 空格合并现象: 浏览器会换行以及空格符号不敏感,不管你有几个空格,或者换行都只会编译成一个空格 ``` ## HTML标签 | 标签 | 描述 | | --------------------------- | :----------------------------------------- | | <h1···h6> <h1···h6> | 标题标签 | | <p> </p> | 段落标签 | | <hr/> | 水平线标签(建议加/) | | <br/> | 换行(建议加/) | | <pre> </pre> | 文字格式需要保留,例如原文中的换行,空格等 | | <blcokquote> </blcokquote> | 需要引用大段的文字,那么建议使用blockquote | | <div> </div> | 独自占据一整行 | | <span> </span> | 一行可以显示多个 | | 列表标签———— | ——————————————————————— | | <ul></ul> <li> </li> | 无序标签 type=“disc/circle/square” | | <ol></ol> <li> </li> | 有序标签type=“a/A/i/I“ | | <dl></dl><dt></dt><dd></dd> | 自定义 | | 文本格式化标签———— | ——————————————————————— | | <b></b> <strong></strong> | 文字加粗 | | <i></i> <em></em> | 文字斜体 | | <s></s> <del></del> | 加删除线 | | <u></u> <ins></ins> | 加下划线 | ## **html标签-拓展** ```javascript 反方向输出文字 <bdo dir="rtl"> Here is some Hebrew text </bdo> <q>文字</q> 输出:"文字" (自带双引号) <blockquote> 文本 </blockquote> 浏览器会插入换行和margin。(margin-left=40px;top=16px) ``` ## ul列表样式 | 属性 | 描述 | | ------------------- | ------------------------------------------------------------ | | list-style-type | circle、square、、、、、改变圆点样式-查询 | | list-style-position | inside、outside 小圆点内外显示 | | list-style-image | list-style-image:url('sqpurple.gif') | | list-style | 可以设置的属性(按顺序):<br /> list-style-type, list-style-position, list-style-image. | | | | | list-style | | | -------------------- | --------------------------------------------------------- | | disc | 标记是实心圆 | | circle | 标记是空心圆 | | square | 标记是实心方块 | | decimal | 标记是数字 | | decimal-leading-zero | 0开头的数字标记。(01, 02, 03, 等) | | lower-roman | 小写罗马数字(i, ii, iii, iv, v, 等) | | upper-roman | 小写罗马数字(I, II, III, IV, V, 等) | | lower-alpha | 小写英文字母The marker is lower-alpha (a, b, c, d, e, 等) | | upper-alpha | (A, B, C, D, E, 等) | | lower-greek | 小写希腊字母(alpha, beta, gamma, 等) | | lower-latin | 小写拉丁字母(a, b, c, d, e, 等) | | upper-latin | 大写拉丁字母(A, B, C, D, E, 等) | | hebrew | 传统的希伯来编号方式 | ## **img标签** ### 1、img标签 ```html 语法结构: <img src="图片路径" width="104" height="142" > ``` | 属性名 | 属性值 | 作用描述 | | :------------: | :----------------------------------------------------------: | :----------------------------------------------------------: | | src | 图片路径url | 使img标签通过路径找到图片 | | alt | 文字 | 图片加载失败,显示描述文本 | | title | 文字 | 鼠标悬停时,显示描述文本 | | width | 像素值 | 设置图片的宽度 | | height | 像素值 | 设置图片的高度 | | align | bottom(默认)<br />middle<br />top<br />left 左浮动<br />right 右浮动 | 图片对齐方式 | | border | px、% | 控制圆角 | | 响应式图片 | | {max-width:100%;<br />height:auto;} | | filter | !待了解 | 滤镜 | | vertical-align | 文字与中线对齐 | vertical-align:middle<br />默认vertical-align:baseline基线对齐 | 问题:h标签中h>a>img;可能出现图片与a标签不能对齐; 原因:忘记给body加line-height:1; ### **2、img拓展**-图像映射 ```javascript 图像映射 <img src="../i/eg_planets.jpg" tppabs="http://www.w3school.com.cn/i/eg_planets.jpg" border="0" usemap="#planetmap" alt="Planets" /> <map name="planetmap" id="planetmap"> <area shape="circle" coords="180,139,14" href ="../example/html/venus.html" tppabs="http://www.w3school.com.cn/example/html/venus.html" target ="_blank" alt="Venus" /> <area shape="circle" coords="129,161,10" href ="../example/html/mercur.html" tppabs="http://www.w3school.com.cn/example/html/mercur.html" target ="_blank" alt="Mercury" /> <area shape="rect" coords="0,0,110,260" href ="../example/html/sun.html" tppabs="http://www.w3school.com.cn/example/html/sun.html" target ="_blank" alt="Sun" /> </map> 注:位于w3c “HTML图像”进一步掌握。 圆形:shape="circle",coords="x,y,z" 这里的 x 和 y 定义了圆心的位置("0,0" 是图像左上角的坐标),r 是以像素为单位的圆形半径。 多边形:shape="polygon",coords="x1,y1,x2,y2,x3,y3,..." 每一对 "x,y" 坐标都定义了多边形的一个顶点("0,0" 是图像左上角的坐标)。定义三角形至少需要三组坐标;高纬多边形则需要更多数量的顶点。 多边形会自动封闭,因此在列表的结尾不需要重复第一个坐标来闭合整个区域。 矩形:shape="rectangle",coords="x1,y1,x2,y2" 第一个坐标是矩形的一个角的顶点坐标,另一对坐标是对角的顶点坐标,"0,0" 是图像左上角的坐标。请注意,定义矩形实际上是定义带有四个顶点的多边形的一种简化方法。 还需进一步了解。 ``` ## **a标签** ### 1、语法结构 ```css <a href=”跳转目标页面路径“ target=”目标页面打开方式“>文本或者图片</a> ``` ### 2、a标签的使用方式 ``` 1.本地链接跳转,直接设置本地路径即可。 2.网络地址跳转,需要注意域名完整。 3.网络资源跳转,设置资源网络路径。 4.空链接:#号代替路径,点击不会跳转。 ``` ### 3、target属性 ```css target属性,可以控制跳转页面的打开方式,两种方式: _self:直接打开页面,不保留原来的页面,默认方式。 _blank:打开新的窗口跳转,保留原来的页面。 ``` ### 4、base标签 ```css 可以统一控制页面上所有a标签的跳转方式。(前提,a标签本身没有设置target属性) 语法结构: <head> <base target="_blank"> </head> ``` ### 5、锚点定位 ``` 语法结构: <a href="#id名">内容</a> 其中的逻辑,主要是通过标签的唯一标识id,进行定位。 ``` ### 6、清除a标签样式 ```css 清除a标签下划线: text-decoration:none -------------------------- 移动端-清除点击高亮样式: -webkit-tap-highlight-color: transparent; ``` ### 7、a标签伪类 ``` - :link /* 未访问的链接 */ - :visited /* 已访问的链接 */ - :hover /* 鼠标移动到链接上 */ - :active /* 选定的链接 */ 注意顺序:lv包包hao ``` ```js btn.onclick = function(){ window.location.href="地址" } ``` ## **路径** ``` 绝对路径 完整的文件路径(带有盘符的路径,就是绝对路径); 完整的网络地址; 相对路径 1.同一目录下结构。 <img src="heima.png"> 2.下一级目录结构。 <img src="image/heima.png"> 3.上一级目录结构。 <img src="../heima.png"> ``` ## **转义符** ![image-20190221193125475](D:\前端41期\3.前端瓦力-总结\image\image-20190221193125475.png) # HTML 布局 ## **table表格 左右 布局** ```javascript <table border="0" width="100%" cellpadding="10"> <tr> <td width="50%" valign="top"> This is some text. This is some text. </td> <td width="50%" valign="top"> Another text. Another text. Another text. </td> </tr> </table> ``` ## **垂直布局frameset** ```javascript <!DOCTYPE html> <html> <frameset cols="25%,50%,25%"> <frame src="表单练习.htm"> 注:文件格式htm,非html <frame src="表单练习.htm"> <frame src="表单练习.htm"> </frameset> </html> cols、rows和表格table中的使用方式相同。 可以实现多种布局。 frame中添加,不显示边框 noresize="noresize" 不支持的浏览器用<noframes> 标签 好像是不安全,基本不用。 ``` # 表格table ### **1.创建表格的基本语法:** ```javascript <table> <tr> <td>单元格内的文字</td> ... </tr> ... </table> ``` ``` 1. table用于定义一个表格标签。 2. tr标签 用于定义表格中的行,必须嵌套在 table标签中。 3. td 用于定义表格中的单元格,必须嵌套在<tr></tr>标签中。 4. 表头标签<th></th>;替代相应的单元格标签<td></td>;自动加粗、居中。 ``` ### **2.table** | 标签名 | 定义 | 说明 | | ------------------- | -------------- | -------------------------------------------- | | <table></table> | 表格标签 | 就是一个四方的盒子 | | <tr></tr> | 表格行标签 | 行标签要再table标签内部才有意义 | | <td></td> | 单元格标签 | 单元格标签是个容器级元素,可以放任何东西 | | <th></th> | 表头单元格标签 | 它还是一个单元格,但是里面的文字会居中且加粗 | | <caption></caption> | 表格标题标签 | 表格的标题,跟着表格一起走,和表格居中对齐 | | clospan | 合并属性 | 跨列合并 | | rowspan | 合并属性 | 跨行合并 | ``` <td valign="top"> 内容上对齐 ``` ### **3.表格table属性** | 属性名 | 含义 | 常用属性值 | | --------------- | ------------------------------------------------------------ | ------------------------------------ | | border | 边框 | px | | cellspacing | 设置单元格与单元格之间边框之间的空白间距 | px(默认2px) | | cellpadding | 设置单元格内容与单元格边框之间的空白间距 | px(默认1px) | | width | 设置宽度 | px | | height | 设置高度 | px | | align | 设置表格在网页中的水平对齐方式 | left、center、right | | ———— | 拓展—— | ———— | | <thead></thead> | 用来放标题之类的东西。<thead> 内部必须拥有 <tr> 标签! | | | <tbody></tbody> | 用于定义表格的主体 | | | <tfoot></tfoot> | 放表格的脚注之类 | | | frame=“ ” | box 全部显示框<br />above 上显示横框<br />below 下横框<br />hsides 横框<br />vsides 竖框 | | | caption-side | 设置标题位置:left、top、bottom、right | | | border-collapse | collapse:合并为一条边框<br />separate:默认拥有两条边框<br />inherit:从父级继承<br />css属性 | 表格的边框是否被合并为一个单一的边框 | 关于talbl设置height、width: table:height设置的是最小值;width是最大值,但图片除外,图片会撑大表格width; tr不起作用;会平分总height值; td设置最小值,内容可超出; 特点:以容纳内容为先;后考虑设置的宽高; # input控件 ### **input属性值** | 属性 | 属性值 | 描述 | | ----------- | ------------------------------------------------------------ | ---------------------------- | | | text | 单行文本输入框 | | | password | 密码输入框 | | type | radio | 单选按钮 | | | checkbox | f复选框 | | | button | 普通按钮 (可单独左标签) | | | submit | 提交按钮 | | | reset | 重置按钮(form里) | | | image | 图像形式按钮 | | | file<br />this.files[0](获取上传的文件内容)<br />获取文件属性<br />URL.createObjectURL(icon)获取上传文件的地址(创建url) | 文件域(选择文件) | | name | 由用户自定义 | 控件的名称 | | value | 由用户自定义 | input控件中默认的文本 | | size | | 多用width设置宽度 | | checked | 标签内加入 checked="checked" | 选择控件中指定默认选项 | | maxlength | | 控件输入最多字符数 | | placeholder | 显示提示文字 | input::placeholder选中该属性 | | | transition: 0.5s;设置动画时长 | | | outinline | outinline:none | 取消点击样式 | | | border:none | 取消边框样式 | | :focus | | 点击输入框时改变样式 | | box-sizing | box-sizing-border-box | 呈现边框和内边距一起计算 | | | !如何改变input初始样式,学习 | | | multiple | 标签中加入此可多选 | | ``` input::placeholder { color: red; } 改变input文字颜色; ``` ### **label标签**(元素绑定) ```javascript 第一种用法就是用label直接包括input表单。 <label> 用户名: <input type="radio" name="usename" value="请输入用户名"> </label> 第二种用法 for 属性规定 label 与哪个表单元素绑定。 <label for="sex">男</label> <input type="radio" id="sex"> ``` ### 拓展-自定义复选框 ```css 利用:把伪类after作为勾选框,通过checked伪类、改变after样式。 <input type="checkbox" id="awesome" /> <label for="awesome">Awesome!</label> -------------------------------------------- input[type="checkbox"] + label::before { content: '\a0'; /* 不换行空格 */ display: inline-block; vertical-align:.2em; width:.8em; height:.8em; margin-right:.2em; border-radius:.2em; background: silver; text-indent:.15em; line-height:.65; } input[type="checkbox"]:checked + label::before { content: '\2713'; background: yellowgreen; } // 隐藏自带选框。 input[type="checkbox"] { position: absolute; clip: rect(0,0,0,0); } ``` ### textarea控件(文本域) ``` <textarea name="" id="" cols="30" rows="10"> 文本内容 </textarea> cols每行字符数 rows显示行数 清除拖动:resize:none; 注: 设置拖动:resize: horizontal; 可用于div等,也可通过伪类覆盖右下角拖动样式。 ``` ### **select下拉列表** ```javascript 出生年月:<select multiple> //multiple可点击ctr进行多选 <option>选项1</option> <option>选项2</option> <option>选项3</option> ... </select> - 注意: 1. <select>中至少包含一对 option 2. 在option 中定义selected =" selected "时,当前项即为默认选中项。 ``` **form表单域** ```javascript <form action="url地址" method="提交方式get/post" name="表单名称"> 各种表单控件 </form> ``` ### **表单-拓展** ```javascript <fieldset> <legend>健康信息:</legend> <form> <label>身高:<input type="text" /></label> <label>体重:<input type="text" /></label> </form> </fieldset> 在数据周围绘制一个带标题的框 ``` # CSS引入 css引入方式 | 引入类型 | | | ---------------- | ------------------------------------------------------------ | | 行内样式表 | <标签名 style="属性1:属性值1; 属性2:属性值2; 属性3:属性值3;"> 内容 </标签名> | | 内联(嵌)样式表 | < style type="text/CSS"><br />选择器 {属性1:属性值1; 属性2:属性值2; 属性3:属性值3;} </style> | | 外链样式 | <head><br/> <link href="CSS文件的路径" rel="stylesheet" /><br/></head> | ``` 注:link标签需要放在head头部标签中 ``` ``` href:定义所链接外部样式表文件的URL,可以是相对路径,也可以是绝对路径。 type:定义所链接文档的类型,在这里需要指定为“text/CSS”,表示链接的外部文件为CSS样式表。 rel:定义当前文档与被链接文档之间的关系,在这里需要指定为“stylesheet”,表示被链接的文档是一个样式表文件。 ``` # css选择器 | 选择器类型 | | | ---------------------- | ------------------------------------------------------------ | | 标签-选择器 | span | | 类-选择器 |.类目 | | 多类名-选择器 | | | id-选择器 | # | | 通配-符选择器 | * | | 交集-选择器 |.a.b | | 并集-选择器 |.a,.b | | 后代-选择器 |.a .b.c | | 子代-选择器 | div > ul > li | | 链接伪类 | :link /* 未访问的链接 */<br /> :visited /* 已访问的链接 */<br /> :hover /* 鼠标移动到链接上 */<br /> :active /* 选定的链接 */ | | 结构(位置伪类)选择器 | :first-child 选取属于其父元素的首个子元素的指定选择器<br />:last-child 选取属于其父元素的最后一个子元素的指定选择器<br />:nth-child(n)匹配属于其父元素的第 N 个子元素且为该元素,不论元素的类型<br />:not(:nth-child(n+4))小于第4子元素<br />:nth-last-child(n)<br />:nth-of-type() 父元素下第N个该元素 | | 属性选择器 | div[class^=font] 表示 font 开始位置就行了<br />div[class$=footer] 表示 footer 结束位置就行了<br />div[class*=tao] 表示tao 在任意位置都可以 | | 伪元素选择器 | E::first-letter 文本的第一个单词或字<br />E::first-line 文本第一行<br />E::selection 可改变选中文本的样式; | | | E::before和E::after | | | input[type="text"] | # CSS三大特性 ## 层叠性 ``` 当多个相同的选择器(权重相同),发生属性冲突,后面的属性会把前面的覆盖,后来者居上 ``` ## 继承性 ``` 存在父子关系的盒子,子元素会继承父元素的部分属性 ​ 1.a标签: 不继承颜色 ​ 2.h系列标签: 不继承字体大小 ``` ## 优先级 ``` 继承性 < 通配符 < 标签选择器 < 类选择器 < id选择器 < 行内式 < !important ​ !important:对继承是没有效果的. 在属性值后加. ``` # 标签显示模式 ## **块级元素特点** 1. 独自占据一行 2. 可以设置宽高 3. 如果块级元素没有设置宽度,那么宽度默认等于父盒子。 4. 塌陷。 ``` margin的垂直塌陷:垂直方向的margin,会重叠,不是相加,取最大值. 包含塌陷: 存在父子关系的盒子,给子元素添加margin-top的时候,会把父元素带跑; 给父元素加: 1.加上边框border; 2.上内边距padding; 3.给父元素设置: overflow:hidden; ``` ``` 常见的块元素有<h1>~<h6>、<p>、<div>、<ul>、<ol>、<li>等,其中<div>标签是最典型的块元素。 ``` ## **行内元素(inline-level)** 1.可以一行显示多个 2.不能设置宽高,宽高由内容决定 ``` 常见的行内元素有<a>、<strong>、<b>、<em>、<i>、<del>、<s>、<ins>、<u>、<span>等,其中<span>标签最典型的行内元素。 ``` ## **行内块元素(inline-block)** 1. ``` 1. 一行显示多个 2. 可以设置宽高 3. 垂直方向的padding margin无效; 行内块元素: input img 注:回车符编译成一个空格,行内元素并排排列会有缝隙.浮动可解决. ``` ## **标签显示模式转换** **display** ```html 块转行内:display:inline; 行内转块:display:block; 块、行内元素转换为行内块: display: inline-block; 浮动float:转换为inline-block; position:absolute:转为inline-block; ``` # 盒子模型 margin、border、padding、content ## margin外边距 ``` 垂直方向的margin,会重叠,不是相加,取最大值. margin的垂直塌陷: 包含塌陷: 存在父子关系的盒子,给子元素添加margin-top的时候,会把父元素带跑; 1.加上边框border; 2.上内边距padding; 3.给父元素设置: overflow:hidden; ``` ## width:min-content 设置宽度为内容宽度。 # border属性 ## border属性 | | | | ------------- | ------------------------------------------------------------ | | border-style | none、solid单实线、 dashed虚线、dotted点线、double双实线 | | border-width | px 设置宽度 | | border-color | 颜色值、#十六进制、rgb(r,g,b)、 rgb(r%,g%,b%) | | 连写一 | border:1px solid color; | | 连写二 | border-top(方位):1px solid color; | | | border-方位-样式(style、weigth、color) | | border-radius | 设置圆角;设置椭圆角border-radius:75px /50px;<br />border-radius:50%;<br />border-radius:左上px 右上px 右下px 左下px;<br />border-radius:左上px 右上px 右下px 左下px(x轴) / 左上px 右上px 右下px 左下px(y轴);<br />糖果按钮http://simurai.com/archive/button | | border-image | | | | | | box-shadow | x y 模糊距离 阴影尺寸 阴影颜色 内/外阴影(inset、outset); | | outline | outline:5px solid color;<br />outline-offset:15px; 可设置负值,outline距离调整。不受radius影响。 | 内盒初始化 ```js * { box-sizing: border-box; -webkit-tap-highlight-color: rgba(0, 0, 0, 0); } *:before, *:after { box-sizing: border-box; } ``` # 投影box-shadow ## box-shadow | | | | ----------------------- | ------------------------------------------------------------ | | box-shadow | x y 模糊距离 阴影尺寸 阴影颜色 内/外阴影(inset、outset(默认));可叠加 | | **filter**: drop-shadow | **filter**: drop-shadow(2px 2px 10px rgba(0,0,0,.5)); | ​ box-shadow:盒子阴影;只对盒子阴影。可阴影叠加。 ​ filter: drop-shadow:阴影;盒子有尖角、透明、、、按图形阴影;不能阴影叠加。 ​ 同样的数值box-shadow更深; ## 内圆角 外方角解决方案 ```css <----方案一、父子盒子、子border-radius----> <----方案二、一个盒子--边框用outline(不随radius变化)、box-shadow填充边角-------> background: tan; border-radius:.8em; padding: 1em; box-shadow: 0 0 0.6em #655; outline:.6em solid #655; 注:box-shadow最小填补距离为(√2-1)r =~ 0.42xr 裁剪元素: clip-path: polygon(0% 0%, 100% 0%, 80% 100%, 0% 100%); ``` # CSS字体样式font属性 | 属性 | 说明 | | ---------------- | ------------------------------------------------------------ | | font-size | 设置字号,常用单位:em、px | | font-family | p{ font-family:"微软雅黑";} (尽量使用系统默认字体)escape() 来测试属于什么字体 | | font-weight | 字体粗细,属性值:normal(400)、bold(700)、<br />bolder、lighter、100~900(100的整数倍)。(b 和 strong 标签) | | font-style | 字体倾斜属性值:normal、italic、oblique | | 综合设置字体样式 | 选择器{font: font-style font-weight font-size/line-height font-family;} | | color | color:#343434;<br />color:rgb(255,0,0);<br />color:red; | | font-variant | 小型大写之母体 small-caps | | | | ``` 文字抗锯齿: -webkit-font-smoothing: 属性: none 关闭抗锯齿,字体边缘犀利。 antialiased 字体平滑。 subpixel-antialiased 默认值 【火狐浏览器】 -moz-osx-font-smoothing 属性: auto 览器只能选择字体渲染表现。 grayscale 灰度抗锯齿渲染。 ``` # CSS文本样式text属性 ## 文本样式属性 | | | | ------------------------ | ------------------------------------------------------------ | | line-height | 行间距 | | letter-spacing | 文字之间间隔(一个字母、一个文字为单位) | | word-spacing | 单词之间空白-对中文无效 | | text-align | 水平对齐方式left、center、right | | text-align:justify | 两端对齐无效解决方法:<br />加::after{<br />content:“‘;<br />display:inline-block;<br />width:100%;}<br />问题原因:只对最后一行的前一行有效。 | | text-align-last: justify | 文本两端对齐。一行两端对齐方式。 | | vertical-align | 设置元素的垂直对齐 (行元素)baseline基线,top,bottom,midden | | text-indent | 首行缩进 单位:em、px | | text-decoration | 文本的装饰:<br />none 默认。(清除a标签下划线)<br />underline 定义文本下的一条线<br />overline 定义文本上的一条线<br />line-through 定义穿过文本下的一条线。 | | text-transform | 大小写转换 属性值:<br />capitalize 首字母大写、<br />uppercase 转大写、<br />lowercase 转小写 | | writing-mode | 文字书写方向:横向、竖向<br />lr-tb 左-右 上-下;(横排 左到右)<br />tb-lr 上-下 右-左;(竖排 右到左)<br />vertical-rl<br />vertical-lr<br />horizontal-tb | | text-shadow | text-shadow:X Y 模糊 颜色;<br />text-shadow:2px 2px 8px #FF0000; | | overflow | hidden隐藏 scroll 滚动条\auto自动 | | white-space:nowrap | div中文字不换行 | | white-space:normal | 默认,文字单词自动换行.字母数字不换行. | | text-overflow:ellipsis | 超出显示省略号 | | user-select:none | 不可选择文本 | -webkit-user-select:none; -moz-user-select:none; -ms-user-select:none;文本超出-省略号 ```html overflow:hidden; white-space:nowrap; text-overflow:ellipsis; word-break:break-all ``` ```html 多行超出省略 text-overflow:-o-ellipsis-lastline;//Opera 10.60 overflow: hidden; text-overflow: ellipsis; display: -webkit-box; //必须,将对象作为弹性伸缩盒子模型显示 -webkit-line-clamp:3; //Webkit支持 line-clam:2; //限制行数 -webkit-box-orient: vertical; //必须,设置或检索伸缩盒子元素的排列方式 word-break:break-all 可设置p标签行数,超出隐藏省略号; js方法: $(".figcaption").each(function(i){ var divH = $(this).height(); var $p = $("p", $(this)).eq(0); while ($p.outerHeight() > divH) { $p.text($p.text().replace(/(\s)*([a-zA-Z0-9]+|\W)(\.\.\.)?$/, "...")); }; }); ``` ```css /*文案显示,一行多余省略、二行多余省略、三行多余省略*/ .three-line { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 3; word-break: break-all; overflow: hidden; } .two-line { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; /* word-break: break-all; */ word-wrap: break-word; overflow: hidden; } .one-line { white-space: nowrap; text-overflow: ellipsis; overflow: hidden; } ``` ## 文字镂空 ```js background-clip: border-box|padding-box|content-box; background-clip: text; -webkit-background-clip: text; -webkit-text-fill-color: transparent; //设置背景颜色透明,不继承 -webkit-text-stroke: 2px #fff;//连写,文字描边 -webkit-mask-image: url(./img/txtpattern.png);//可不要 ``` ## 拓展-文本栏格解决方案 ```css padding:.5em; line-height: 1.5; background: rgb(4, 161, 12); background-size: auto 3em; //size为 line-height 的两倍。 background-origin: content-box; background-image: linear-gradient(rgba(0,0,0,.2) 50%, transparent 0); ``` ## 拓展-文字凹凸效果 ```css 利用text-shadow文字投影; 凹字体:文字下投影亮色; 凸字体:文字上投影深色; text-shadow: 0 -1px 1px black; 伪3D文字: text-shadow: 0 1px hsl(0,0%,85%), 0 2px hsl(0,0%,80%), 0 3px hsl(0,0%,75%), 0 4px hsl(0,0%,70%), 0 5px hsl(0,0%,65%), 0 5px 10px black; 多层投影叠加,最后一层模糊。 ``` ## 文字竖排 ```css 竖排 左右: writing-mode: vertical-lr; writing-mode: tb-lr; 竖排 右左: writing-mode: tb-lr; ``` # CSS背景-background | 属性 | 作用 | 值 | | -------------------------- | ------------ | ------------------------------------------------------------ | | background-color | 背景颜色 | --transparent设置透明背景 | | background-image | 背景图片 | background-image : url(“images/demo.png”) | | background-repeat | 是否平铺 | repeat / no-repeat / repeat-x / repeat-y | | background-position | 背景位置 | background-position:x y ;top center ····<br />background-positionX<br />background-positionY | | background-attachment | 是否固定 | scroll默认 / fixed 固定 | | 背景透明 | | background: rgba(0,0,0,0.3);<br />opacity: 0.4; | | 背景简写-------- | | background:url(image.jpg) repeat-y scroll center top 颜色 | | background-size | 背景图片大小 | px / % / cover整体填充 / contain按图比例填充,会留边 | | background-origin | 背景指定区域 | border-box padding-box content-box (写在连写后面) | | 设置多个背景(后可添参数) | | background-image : url(“demo.png”),url(“demo.png”); | | background-clip | 背景裁剪 | border-box padding-box content-box | | clip:rect | | clip:rect(上 右 下 左) | | clip:-path:polygon() | 多边形裁剪 | (四个点坐标) | | background:linear-gradient | 渐变 | linear-gradient(right / 90deg, #00dbde, #fc00ff); | | repeating-conic-gradient | 圆锥渐变 | background: repeating-conic-gradient(svg) | ```javascript Bennett Feely 的图案库 http:// bennettfeely.com/gradients ``` ```javascript 几种定位方法: <----background-position:方案-----> background:url(image.jpg) repeat-y scroll center top 颜色; <----background-origin: 方案2-----> background: url("code-pirate.svg") no-repeat bottom right #58a ; background-origin: content-box; <----calc():/计算/ 方案3-----> background: url("./01.png") no-repeat calc(100% - 200px) calc(100% - 100px) red ; ``` ```javascript 制作网格: background: #58a; background-image: linear-gradient(white 1px, transparent 0), linear-gradient(90deg, white 1px, transparent 0); background-size: 30px 30px; ``` # pre ```css 保留格式,且能换行   white-space: pre-wrap; /*css-3*/    white-space: -moz-pre-wrap; /*Mozilla,since1999*/    white-space: -pre-wrap; /*Opera4-6*/    white-space: -o-pre-wrap; /*Opera7*/    word-wrap: break-word; /*InternetExplorer5.5+*/ ``` ## 背景渐变linear-gradient ```javascript 背景渐变 兼容: -webkit-linear-gradient -o-linear-gradient -moz-linear-gradient background: linear-gradient(#fb3 33.3%,#58a 0, #58a 66.6%, yellowgreen 0); background-size: 100% 45px; size小,自动平铺,后面数值为0,则从上一个颜色位置开始。 background:linear-gradient(to right, #00dbde, #fc00ff); 默认是to bottom; background: repeating-linear-gradient(45deg,#fb3, #58a 30px); 循环渐变; background: repeating-radial-gradient(45deg,#fb3, #58a 30px); 圆循环渐变; background: repeating-linear-gradient(60deg,#fb3, #fb3 15px, #58a 0, #58a 30px); 双色条纹(无渐变); background: linear-gradient(to left bottom,transparent 50%, rgba(0,0,0,.4) 0)no-repeat 100% 0 / 2em 2em; //产生尖角 /后是background-size ``` ## 背景图+渐变 方法一、 原理: https://www.cnblogs.com/iverson666/p/6042872.html ``` background:url(./) repeat,linear-gradient(to right,#ccc,#fff); 注意:背景图 要写在 背景颜色前; ``` 方法二、 多添加一个标签; ## 弧度切角 ```javascript background: radial-gradient(circle at top left, transparent 0, transparent 20px, #f15a24 0) top left, radial-gradient(circle at top right, transparent 0, transparent 20px, #f15a24 0) top right, radial-gradient(circle at bottom right, transparent 0, transparent 20px, #f15a24 0) bottom right, radial-gradient(circle at bottom left, transparent 0, transparent 20px, #f15a24 0) bottom left; background-size: 50% 50%; background-repeat: no-repeat; --------- css3 的 mask ``` ## 倾斜-transform: skew(-45deg) ## 平行四边形transform: skew(-45deg); ```javascript 倾斜:父级倾斜;文字倾斜回来; <a href="#yolo" class="button"> <div>Click me</div> </a> .button { transform: skewX(-45deg); } .button > div { transform: skewX(45deg); } 倾斜:利用伪类元素倾斜;不影响文字; .button { position: relative; /* 其他的文字颜色、内边距等样式…… */ } .button::before { content: ''; position: absolute; top: 0; right: 0; bottom: 0; left: 0; } ``` ## 棱形 ```javascript tranform:rotate(45deg); 旋转 裁剪: clip-path: polygon(50% 0, 100% 50%, 50% 100%, 0 50%); (分别为四个点的坐标)。 ``` # 添加小图标方法 1.背景:同盒子添加padding,添加背景图片定位; 2.伪类:用::before\::after,转inline-block设置宽高;加入背景;(input不能添加伪类) 3.添加i标签,添加背景图定位; 4.字体图标; 5.input类标签,可设置文字为0,消除文字;再添加背景图标。 ```html 引入: <link rel="stylesheet" href="./iconfont.css"> 选取图标类名: <span class="iconfont icon-xxx">&#x33;</span> 或输入图标Unicode: <span class="iconfont icon-xxx">&#x33;</span> ``` # 浮动float ## 浮动特点 元素的浮动是指 设置了浮动属性的元素会脱离标准流(文档流)的控制,移动到其父元素中指定位置的过程。 浮动元素拥有inline-block元素特性。 ``` 选择器{float:属性值;} 值:left\right\none; ``` ## 浮动的影响 会使没有设置高度的父元素高度为零。父元素没有设置高度,当所有的子元素都浮动了,那么父元素会失去高度。 ## 清除浮动方法 | 清除浮动的影响-方法 | 说明 | | -------------------------------------- | ---------------------------------- | | 父元素添加高度 | 固定高度可以。动态高度不能自动撑开 | | 父元素添加:overflow:hidden | 不用 | | 在子元素最后添加额外标签设置clear:both | 添加多余的标签,导致标签冗余。 | | 伪类清除 | 利用后添加标签法方法; | ``` 单伪类清除: .clearfix::after { content:"."; /*小点兼容低版本火狐*/ display:block; clear:both; height:0; /*去除点的高度*/ visibility:hidden; /*去除小点*/ } .clearfix { *zoom:1; /*兼容低版本IE*/ } _____________________________________ 双伪清除法: .clearfix::before ,.clearfix::after { content:""; display:block; } .clearfix::after { clear:both; } .clearfix { *zoom:1; } ``` # 定位position ## position特点 1.实现模式转换,拥有行内块的特点 2.脱离标准流,不占据标准流的位置 | | | | ------------------ | ------------------------------------------------------ | | position:fixed | 固定定位 | | position:relative | 相对定位 <br />1.不能实现模式转换<br/>2.不能脱离标准流 | | position:absolute | 绝对定位 | | z-index | 叠放次序 | | position:static | 标准流 | 固定定位元素默认参考body。 ## 定位居中方法 ```js 方法一: 子 先走父元素的一半,再往回走自己的一半: position:absolute; top:50%; left:50%; margin-top:-小盒子一半height; margin-left:-小盒子一半width; -------------------------- 方法二:子 position:absolute; top:50%; left:50%; transform:translate(-50%,-50%); 注:需要兼容,-webkit-,-moz-,-ms-,-o-; -------------------------- 方法三:子 position:absolute; margin:auto; left:0; right:0 top:0; bottom:0; -------------------------- 方法四:display:table-cell 父元素: display:table-cell; vertical-align: middle; text-align: center; 子元素: display:inline-block; -------------------------- 方法五:display:flex;父元素设置。 justify-content:center; align-items:center; 方法六:http://www.ruanyifeng.com/blog/2019/03/grid-layout-tutorial.html Grid ``` ## 层级z-index 层级:标准流《浮动《定位《越往后越高 # 鼠标样式cursor ```css cursor:default 默认箭头 cursor:pointer 小手 cursor:text 光标 cursor:move 移动光标 cursor:wait 等待 cursor:not-allowed 静止 cursor:help 帮助 cursor:n-resize;向上改变大小 cursor:s-resize: 向下 cursor:e-resize: 向右 cursor:w-resize: 向左 North East West Souuth cursor:nw-resize: 向上左 cursor:ne-resize: 向上右 cursor:se-resize: 向下右 cursor:sw-resize: 向下左 :focus 选择输入框;类似hover用法; ``` # 动画 ## transition ```html transition:all 1s linear 延迟s; 配合hover使用。 :focus linear 规定以相同速度开始至结束的过渡效果(等于 cubic-bezier(0,0,1,1))。 ease 规定慢速开始,然后变快,然后慢速结束的过渡效果(cubic-bezier(0.25,0.1,0.25,1))。 ease-in 规定以慢速开始的过渡效果(等于 cubic-bezier(0.42,0,1,1))。 ease-out 规定以慢速结束的过渡效果(等于 cubic-bezier(0,0,0.58,1))。 ease-in-out 规定以慢速开始和结束的过渡效果(等于 cubic-bezier(0.42,0,0.58,1))。 cubic-bezier(n,n,n,n) 在 cubic-bezier 函数中定义自己的值。可能的值是 0 至 1 之间的数值。 贝塞尔曲线 https://cubic-bezier.com/ ``` ## 2D转换transform | | | | | ----------------------------------- | -------- | ---------------- | | transform:translate(Xpx,Ypx) | 位移 | 百分比相对于自身 | | transform:scale(2,4) | 大小缩放 | | | transform:rotate(30deg) | 旋转 | | | transform:perspective | 视距 | | | transform:skew(xdeg,ydeg) | 倾斜/ | | | transtion-origin: | | | | transform:matrix() 如下对于的矩阵: | | | | matrix(1,0,0,1,x,y) | 位移 | | | matrix(x,0,0,y,0,0) | 缩放 | | | matrix(x,0,0,y,0,0) 待确定0 | 旋转 | | | matrix(1,tan(y),tan(x),1,0,0) | 变形 | | ```css matrix(a,b,c,d,e,f) ax+cy+e=x` bx+dy+f=y` matrix(a,b,c,d,e,f) ``` ## transition3D | | | | | --------------------------------------------------------- | ---- | ---- | | transform:translate(Xpx) translate(Ypx) translate(zpx); | | | | 必须设置 | | | | | | | ```css transform:translate(Xpx) translate(Ypx) translate(zpx); transform:rotate(Xdeg) rotate(Ydeg) rotate(Zdeg); //没有逗号。 必须设置视距; perspective:800px,一般给父元素加。图片给body设置; 视距 a.以后开发中,如果3D效果不对,一般原因就是把视距添加到运动的父盒子上去了 b.解决方案:把视距添加到不动的父元素上,如果还不行就继续往上级父元素加. transform-style: preserve-3d; //开启3D效果显示:默认浏览器没有开启 ``` ## animation ```css 动画路径: @keyframes name{ from { } to { } } ------------------------- @keyframes name{ 50% { //百分比相对animation设置的时间 } 100% { } } ------------------------- animation:name 1s linear 次数(infinite循环); animation: name duration timing-function delay iteration-count direction; animation: name // animation-duration //花费的时间,以秒或毫秒计 animation-timing-function //速度曲线 linear ease(低速) ease-in ease-out ease-in-out animation-delay //开始之前的延迟 3s animation-iteration-count //应该播放的次数 infinite animation-direction //轮流反向播放动画 alternate ``` # ==移动端web== ## meta标签viewport介绍 ```html <meta name="viewport" content="width=device-width, initial-scale=1.0,user-scalable=no"> name="viewport" //网页窗口的大小 content="width=device-width //适配宽度 initial-scale=1.0 //网页加载不缩放 user-scalable=no" //禁止用户手动缩放 ``` 代码顺序:https://www.cnblogs.com/huangshan-huangshan/p/5723707.html 位置-大小-背景-字体-其他; ![1570982193856](../image/1570982193856.png) ## 流式布局 宽度设置百分比。 min-width; max-width; ## <u>弹性布局flex</u> ​ 工具:focusky动画演示大师。 特点: 查看兼容:caniuse.com 兼容工具:postCss 兼容:display:-webkit-box; 默认:X为主轴;Y为次轴; ​ 主轴内容不超出,次轴内容会超出。 | | | | | ----------------------------- | ---------------------------- | ---------------------------------- | | display:flex | 父元素设置 | 子元素可设置以下属性 | | flex-direction 子元素排列方式 | 父元素设置 | 改变主轴方向 | | | row(默认) | 横向排列 | | | row-reverse | 横向翻转 | | | column | 纵向 | | | column-reverse | 纵向翻转 | | | | | | justify-content 内容 对齐 | 主轴对齐方式 | | | | center | 居中 | | | space-between | 两端 | | | space-around | 拉手布局(子盒子左右两边间距相同) | | | flex-start | 局左 (默认) | | | flex-end | 居右 | | | | | | align-items 纵向排列对齐 | 次轴对齐方式 | | | | center | 居中 | | | flex-start | 顶部 默认 | | | flex-end | 底部 | | | baseline | 基线(文字) | | | stretch | 平铺(默认) | | | | | | flex-wrap 包裹方式 | 子元素超过父元素才能换行 | | | | nowrap 默认 | 不换行 | | | wrap | 换行 | | | | | | align-content | 多行对齐方式垂直排列 | 只对多行 | | | stretch | 拉伸(默认) | | | center | 居中 | | | flex-start | 顶部 | | | flex-end | 底部 | | | space-between | 两端 | | | space-around | 拉手布局(子盒子左右两边间距相同) | | | | | | flex-flow | "flex-direction" "flex-wrap" | 简写 | | | | | | flex:1; | 子元素分父元素的份数 | 子元素设置。设置宽高无效。 | | align-self: | 设置个别子元素次轴对齐方式 | | | | center | | | order:number(默认0) | 标记元素排序大小 | 元素 从小到大排列 | | | | | ## rem rem-相对HTML根元素字体大小; em-相对当前父元素字体大小; ```css html { font-size:16px; } 大部分浏览器默认字体是16px; 一个P标签设置12px的字体大小那么用rem表示; p { font-size: 0.75rem; //12÷16=0.75(rem) } 计算方式: px/根字体大小=rem ``` 实现宽高等比例缩放。一个相对单位rem=当前屏幕宽度1/10;(通过js实现) ```javascript (function(){ var calc = function(){ var rem = document.documentElement.clientWidth/10; document.documentElement.style.fontSize = rem + 'px'; rem = document.documentElement.clientWidth > 750?37.5:rem; console.log(rem); } calc(); window.addEventListener('resize',calc); })(); ``` rem+sass换算: ```css @function px2rem($px){ $rem : 37.5px; @return ($px/$rem) + rem; } ``` cssrem设置 ```js vscode 首选项 搜索cssrem 设置font-size ``` ## less 引入less文件:@import "one"; 变量:@w=100px;引用:width:@w; 混合:.w { 属性:值;}。 引用:.w(); 嵌套: 伪类选择:&:hover ## media查询-响应式布局 https://www.runoob.com/cssref/css3-pr-mediaquery.html 25个经典响应式网站::<http://www.daqianduan.com/4614.html?tdsourcetag=s_pcqq_aiomsg 媒体查询: ```html 标准写法: @media screen and (width:1000px) { } 简写: @media(width:1000px){ } 区间查询:大于等于1200px时显示; @media (min-width:1200px){ } 范围设定: @media(min-width:100px) and ( max-width:1000px){ } 注: 书写顺序: max-width为判断时,从大写到小; min-width为判断时,从小写到大; 原因:权重相同,同时满足条件,后面会覆盖前面。 引入样式方式: <linkrel="stylesheet" type="text/css" href="styleB.css" media="screen and (min-width: 600px) and (max-width: 800px)"> 宽度大于600小于800时,应用styleB.css ``` 设备类型 | 设备类型 | 屏幕尺寸 | 版心 | | -------- | -------- | ---- | | 大PC | >=1200px | 1170 | | 小pc | 992-1200 | 970 | | 平板 | 768-992 | 750 | | 手机 | <768 | 100% | ## 响应式布局bootstrap 官方网:www.bootcss.com **Bootstrap栅格系统介绍:**随着屏幕或视口(viewport)尺寸的增加,系统会自动分为最多12列。 通过定义好的类名控制不同视口所展现的内容,选择显示(visible-md-1)、隐藏(hidden-md)、宽度(col-md-)。减少媒体查询设置过多样式。 | | <768px | ≥768px | ≥992px | ≥1200px | | --------------- | --------------- | ------------ | ------------ | ------------ | |.container | 100% | 750px | 970px | 1170px | |.row | | | | | | 类名前缀 |.col-xs- |.col-ms- |.col-md- |.col-lg- | | 偏移(offsets) | col-md-offset-4 | | | | | 显示visible |.visible-xs- |.visible-ms- |.visible-md- |.visible-lg- | | 隐藏hidden |.hidden-xs |.hidden-sm |.hidden-md |.hidden-lg | ```html 注意:引入文件。 <link rel="stylesheet" href="./css/bootstrap.min.css"> //bootstrap-css文件 <script src="./js/bootstrap.min.js"></script> //bootstrap-js文件 <script src="./js/jquery-1.12.4.min.js"></script> //JQ-js文件 ``` ```javascript 拓展:一行显示7等份; <style> .col-lg-1{ width: 14.2857%; } </style> <div class="container-fluid"> <div class="row"> <div class="col-lg-1"></div> <div class="col-lg-1"></div> <div class="col-lg-1"></div> <div class="col-lg-1"></div> <div class="col-lg-1"></div> <div class="col-lg-1"></div> <div class="col-lg-1"></div> </div> </div> 思路: 源码文件设置.col-lg-1为1/12=8.3333%; 7等分:设置.col-lg-1为 1/7=14.2857%; ``` ## 富文本框的实现 ```html <div contenteditable="true" id="rich-editor"></div> ``` 移动端代替hover ```js document.body.addEventListener('touchstart', function () {}) :hover 换成 :ative ``` # DOMContentLoaded 与 load事件 DOMContentLoaded 意思就是:当初始的 HTML 文档被完全加载和解析完成之后,DOMContentLoaded 事件被触发,而无需等待样式表、图像和子框架的完成加载 ### load 意思就是:当一个资源及其依赖资源已完成加载时,将触发load事件。 # 1px解决方案 1.after ```css 4边 &.hairline { position: relative; &::after { content: ""; position: absolute; box-sizing: border-box; right: -50%; bottom: -50%; left: -50%; top: -50%; border: 1px solid red; transform: scale(0.5); } } .setBorderAll{ position: relative; &:after{ content:" "; position:absolute; top: 0; left: 0; width: 200%; height: 200%; transform: scale(0.5); transform-origin: left top; box-sizing: border-box; border: 1px solid #E5E5E5; border-radius: 4px; } } 1条 .setOnePx{ position: relative; &::after{ position: absolute; content: ''; background-color: #e5e5e5; display: block; width: 100%; height: 1px; /*no*/ transform: scale(1, 0.5); top: 0; left: 0; } } ``` 2.border + border-image ```css border: 1px solid transparent; border-image: url('./../../image/96.jpg') 2 repeat; ``` 3.box-shadow ``` box-shadow: 0 -1px 1px -1px #e5e5e5, //上边线 1px 0 1px -1px #e5e5e5, //右边线 0 1px 1px -1px #e5e5e5, //下边线 -1px 0 1px -1px #e5e5e5; //左边线 ``` 4.viewport的scale ```js 不适用于viewport var viewport = document.querySelector("meta[name=viewport]"); //下面是根据设备像素设置viewport if (window.devicePixelRatio == 1) { viewport.setAttribute('content', 'width=device-width,initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no'); } if (window.devicePixelRatio == 2) { viewport.setAttribute('content', 'width=device-width,initial-scale=0.5, maximum-scale=0.5, minimum-scale=0.5, user-scalable=no'); } if (window.devicePixelRatio == 3) { viewport.setAttribute('content', 'width=device-width,initial-scale=0.3333333333333333, maximum-scale=0.3333333333333333, minimum-scale=0.3333333333333333, user-scalable=no'); } var docEl = document.documentElement; var fontsize = 32* (docEl.clientWidth / 750) + 'px'; docEl.style.fontSize = fontsize; ``` ```js .scale-hairline-common(@color, @top, @right, @bottom, @left) { content: ''; position: absolute; background-color: @color; display: block; z-index: 1; top: @top; right: @right; bottom: @bottom; left: @left; } .hairline(@direction, @color: @border-color-base) when (@direction = 'top') { border-top: 1PX solid @color; //大写PX不会转换rem html:not([data-scale]) & { @media (min-resolution: 2dppx) { border-top: none; &::before { .scale-hairline-common(@color, 0, auto, auto, 0); width: 100%; height: 1PX; transform-origin: 50% 50%; transform: scaleY(0.5); @media (min-resolution: 3dppx) { transform: scaleY(0.33); } } } } } ``` ======================= File: 09、React/react.md ======================= # react入门 ## JSX语法 jsx语法是一种类似于html标签的语法,它的作用相当于是让我们在JavaScript代码中直接写html代码,但是jsx不完全是html,它是 JavaScrip 的一种扩展语法,它具有 JavaScript 的全部能力,我们还可在jsx代码中插入变量或者表达式,用jsx语法写出来的语句是一个对象,我们可以将它存为一个变量,这个变量作为ReactDOM对象的render方法的第一个参数。 ```javascript let el = <h1>Hello world!</h1>; ReactDOM.render( el, document.getElementById('root') ) ``` #### 基本语法示例 jsx的结构还可以写得更复杂,可以是嵌套结构,如果是嵌套结构,需要有唯一的一个外层标签。标签中如果是单个的标签,在结尾要加“/”,在jsx中可以通过“{}”插入变量,表达式或者函数调用。 ```javascript <script type="text/babel"> let iNum01 = 10; let sTr = 'abc123456'; function fnRev(s){ return s.split('').reverse().join(''); } let el = ( <div> {/* jsx注释定义方法 */} <h3>jsx语法</h3> {/* 插入变量及运算 */} <p>{ iNum01+5 }</p> {/* 插入表达式 */} <p>{ sTr.split('').reverse().join('') }</p> {/* 插入函数调用 */} <p>{ fnRev(sTr) }</p> {/* 插入三元运算表达式 */} <p>{ ok?'YES':'NO' }</p> </div> ); ReactDOM.render( el, document.getElementById('root') ) </script> ``` #### 标签属性定义方法 jsx中指定标签的属性值建议用双引号,不能不用引号,其中class属性需要写成className,属性值如果是可变的,也可以写成“{}”的形式,里面可以和上面写法一样。 标签如果是单个的,在结尾一定要加“/” ```javascript {/* 定义class */} <p className="sty01">使用样式</p> {/* 单个标签,结尾要加“/” */} <img src={user.avatarUrl} /> ``` #### 使用行间样式 行间样式一般不建议使用,但是有的组件结构中会少量用到,定义的方式是在“{}”中,将样式属性写成对象的键值对形式,值可以不加单位,直接写成数字,带“-”的属性名要写成驼峰式。 ``` <p style={{width:'300px',height:200,color:'#ddd',backgroundColor:'hotpink'}}>这是一个使用style样式的段落</p> ``` ## 函数组件和参数props 组件可以理解成是一个组成页面的部件或者零件,每个部件都有自己完整的结构和功能,多个部件拼装在一起就可以组成一个页面,从组件的实现来看,组件最终是要返回一个jsx对象,组件有两种定义方式:一种是函数式定义,一种是类定义。 #### 函数式定义组件 通过函数来定义一个组件,组件名称首字母要大写,函数可以接收一个参数props,这个props是一个对象,这个对象中的属性是通过在使用组件时传入的,函数最终需要返回一个jsx对象。 ```javascript // 定义不含props参数的组件 function Welcome(){ return <h1>Hello,Tom</h1> } // 定义含props参数的组件,props是一个对象,在使用组件时通过属性的方式传入 function WelcomeName(props){ return <h1>Hello, {props.name}</h1>; } ``` #### 组件渲染 组件渲染和jsx对象一样,我们可以通过ReactDOM.render()方法来渲染组件,组件以标签的方式使用,可以写成单个标签或者双标签,写成单个便签,结尾要加"/" ```javascript // ReactDOM.render(<Welcome />,document.getElementById('root'); ReactDOM.render(<WelcomeName name="Sara" />,document.getElementById('root'); ``` #### 组件的变换写法 定义函数可以用匿名函数赋值的形式,而匿名函数又可以改写成箭头函数的形式,另外,props是一个对象,所以,在传参时也可以使用解构赋值的形式,所以,上面的两个组件可以改写成下面的形式: ``` const Welcome = ()=><h1>Hello,Tom</h1>; const WelcomeName = ({name})=><h1>Hello,{name}</h1>; ``` #### 组件组合 可以在一个组件内,拼装其他的组件,从而组合成一个更大的组件 ```javascript function WelcomeName(props) { return <h1>Hello, {props.name}</h1>; } function App() { return ( <div> <WelcomeName name="Sara" /> <WelcomeName name="Cahal" /> <WelcomeName name="Edite" /> </div> ); } ReactDOM.render( <App />, document.getElementById('root') ); ``` ## es6语法之类和类的继承 定义react组件会用到es6语法中类的写法,所以先来了解一下这些写法 #### 基于原型的类和类的继承定义方法 es6之前,javascript中是通过函数和原型的方式来模拟类和类继承,写法如下: ```javascript function Person(name,age){ this.name = name; this.age = age; } Person.prototype.showname = function(){ alert('我的名字是:'+ this.name) } Person.prototype.showage = function(){ alert('我的年龄是:'+ this.age) } var Andy = new Person('刘德华',60); alert(Andy.name); Andy.showage(); function Student(name,age,school){ Person.call(this,name,age); this.school = school; } Student.prototype = new Person(); Student.prototype.showschool = function(){ alert('我的学校是:'+this.school); } var Xiaoming = new Student('小明',15,'深圳一中'); alert(Xiaoming.name); alert(Xiaoming.school); Xiaoming.showname(); Xiaoming.showage(); Xiaoming.showschool(); ``` #### es6类和类的继承定义方法 es6中增加了class语法来大大简化了类的创建和类的继承。 ```javascript // 定义类,类的首字母要大写 class Person { // 定义构造函数 constructor(name,age){ this.name = name; this.age = age; } // 定义方法 showname(){ alert('我的名字是:' + this.name); } showage(){ alert('我的年龄是:' + this.age); } } // 通过类实例化对象 let Andy = new Person('刘德华',55); // 调用对象的方法 Andy.showname(); Andy.showage(); // 定义类继承Person类 class Student extends Person{ constructor(name,age,school){ super(name,age); this.school = school; } showschool(){ alert('我的学校是:' + this.school); } }; // 通过类实例化对象 let Tom = new Student('小明','16','北京一中'); // 调用对象的方法 Tom.showname(); Tom.showschool(); ``` ## 类组件 类组件就是通过es6类的方式来定义组件,组件的名称首字母需要大写,定义的类,需要继承于React.Component类,类组件最少需要有一个render方法,这个方法会返回一个jsx对象,类里面使用的props属性是在React.Component类上面继承过来的,所以可以直接使用。 ```javascript class WelcomeName extends React.Component { render() { return <h1>Hello, {this.props.name}</h1>; } } ``` 类组件的使用方式和函数式组件使用方式相同,可以直接渲染出来,也可以组合使用: ```javascript ReactDOM.render(<WelcomeName name="Sara" />,document.getElementById('root'); ``` 这样定义的组件相对于函数式定义的组件没有什么优势,我们其实可以在这种组件的基础上增加方法和属性,让它有更多的功能。 ## 绑定事件 React绑定事件和JavaScript中的行间事件类似,事件绑定是写在标签中的,但是,React事件是在原生事件的基础上做了封装,它的事件使用**驼峰命名**,而不是全部小写。事件需要传递一个函数作为事件处理程序,这个函数在哪里定义呢?我们可以通过类定义组件,将这个函数作为一个方法定义在组件中。 定义一个点击能弹出名称的组件: ```javascript class Helloname extends React.Component { fnHello(){ alert('Hello,Tom'); } render(){ return ( <input type="button" value="打招呼" onClick={this.fnHello} /> ) } } ReactDOM.render(<Helloname />, document.getElementById('root')); ``` 如果想把这个组件定义成可以传递名称参数的,可以定义如下: ```javascript class Helloname extends React.Component { fnHello(){ alert(this.props.name); } render(){ return ( // 按钮在调用方法时,此时的this默认会指向这个按钮,所以在绑定事件时,需要绑定this <input type="button" value="打招呼" onClick={this.fnHello.bind(this)} /> ) } } ReactDOM.render(<Helloname name="Tom" />, document.getElementById('root')); ``` 上面绑定this的方式实在是很麻烦,所以我们可以在定义方法的时候使用箭头函数来绑定this ```javascript class Helloname extends React.Component { // 改成箭头函数的形式来绑定this fnHello=()=>{ alert(this.props.name); } // 改成箭头函数,同时还需要传参 fnHello2=content=>{ alert(content + this.props.name); } render(){ return ( <div> {* 这里的fnHello就不需要绑定this了 *} <input type="button" value="打招呼" onClick={this.fnHello} /> {* 这里的fnHello2通过绑定一个箭头函数来调用需要传参的函数*} <input type="button" value="打招呼2" onClick={()=>{this.fnHello2('Hello,')}} /> </div> ) } } ReactDOM.render(<Helloname name="Tom" />, document.getElementById('root')); ``` ## 状态 组件如果需要定义默认属性呢?而且这个默认属性还是可变的呢?这个就是组件的状态属性了,状态属性默认名称是state,这个属性需要在组件定义时初始化,所以我们需要使用类的构造函数来对这个属性进行初始化。拥有state属性的组件叫做有状态组件,没有state属性的组件叫做无状态组件。所以用函数方式定义的组件都是无状态组件,用类的方式定义的组件,定义了state就是有状态组件,没定义state就是无状态组件。 定义一个点击按钮数字递增的 ```javascript class Increase extends React.Component{ constructor(props){ super(props); this.state = { iNum:10 } } fnAdd=()=>{ // 设置state里面的值用setState // setState里面可以直接传递一个对象,对象可以是整体或者是部分的state中的键值对 // setState里面还可以传递一个函数,函数需要返回一个对象 // 设置值时想引用state最新的值用setState里面传递的函数中的state this.setState(state=>({iNum:state.iNum+1})); } render(){ return ( <div> <p>{ this.state.iNum }</p> <input type="button" value="递增" onClick={this.fnAdd} /> </div> ) } } ReactDOM.render( <Increase />, document.getElementById('root') ); ``` #### state注意点 1、不能直接修改state的值,应该用setState代替 ```javascript // 下面写法是不会更新组件,是错误的 this.state.iNum = 11; // 应该写成setState的形式,里面接收一个修改后的对象,这个对象可以是完整的state对象, // 也可以是针对个别几个键值对的对象 this.setState({iNum: 11}); ``` 2、出于性能考虑,React 可能会把多个 setState() 调用合并成一个调用。因为 this.props 和 this.state 可能会异步更新,所以你不要依赖他们的值来更新下一个状态。可以使用函数的形式,函数的参数中传递的第一个参数是state上一个状态的值,我们可以在这个值基础上修改。 ```javascript this.setState((state,props)=>({ iNum:state.iNum+1 })); ``` #### 课堂实例 # react进阶 ## 新增数组方法、属性表达式 #### map() 方法 map方法可以分别处理数组中的成员,返回一个新数组,也可以用于遍历数组 ```javascript let aList = ['a','b','c']; // 第一个参数是数组的成员值,第二个参数是成员的索引值 aList.map(function(item,i){ alert(i +'|'+ item); }) ``` #### includes() 方法 includes方法返回一个布尔值,表示某个数组是否包含给定的值 ```javascript [1, 2, 3].includes(2) // true [1, 2, 3].includes(4) // false [1, 2, NaN].includes(NaN) // true ``` #### filter() 方法 和map类似,filter方法接收一个函数。但是和map不同的是, filter把传入的函数依次作用于每个元素,然后根据返回值是 true 还是false决定保留还是丢弃该元素。 ```javascript let aList01 = [1, 2, 4, 5, 6, 9, 10, 15]; let aList02 = aList01.filter(function (x) { return x % 2!== 0; }); alert(aList02); // 1, 5, 9, 15 ``` #### find() 方法 该方法主要应用于查找第一个符合条件的数组元素。它的参数是一个回调函数。在回调函数中可以写你要查找元素的条件,当条件成立为true时,返回该元素。如果没有符合条件的元素,返回值为undefined。 ``` const myArr=[1,2,3,4,5,6]; var v=myArr.find(value=>value>4); console.log(v);// 5 ``` #### 扩展运算符(...) 扩展运算符(...),它用于把一个数组转化为用逗号分隔的参数序列 ```javascript let arr = [1,2,3]; let arr2 = [...arr,4]; console.log(arr2) // [1,2,3,4] ``` #### 属性名表达式 对象的属性名可以通过中括号写成值或者变量的形式: ```javascript let propKey = 'foo'; let obj = { [propKey]: true, ['a' + 'bc']: 123 }; alert(obj.foo); // true alert(obj.abc); // 123 ``` ## 列表渲染 如何拼装数组中的数据放入页面呢?可以将数组中的数据通过数组遍历渲染成一个jsx对象,在通过React渲染这个对象就可以了。 ```javascript let aList = ['红海','复联3','碟中谍6','熊出没']; let el = ( <ul> { aList.map((item,i)=><li key={i}>{ item }</li>) } </ul> ); ReactDOM.render( el, document.getElementById('root') ) ``` 通过map方法遍历数组中的成员,map方法的第二个参数是数组中的索引值,在循环生成li结构时,需要给每个li加上一个key,这个key的值可以用数组中的成员索引值。 ## 条件渲染 根据条件渲染不同的结构,就是条件渲染,条件渲染有下面几种创建形式: #### 组件内根据条件返回不同结构 ```javascript function Loginstate(props){ if(props.isLogin==true){ return <h2>欢迎回来!</h2> }else{ return <h2>请登录!</h2> } } ReactDOM.render(<Loginstate isLogin={true}/>,document.getElementById('root')); ``` #### 组件内根据条件返回不同子组件 ```javascript function Login(props){ return <h2>欢迎回来!</h2> } function Logout(props){ return <h2>请登录!</h2> } function Loginstate2(props){ if(props.isLogin==true){ return <Login /> }else{ return <Logout /> } } ReactDOM.render(<Loginstate2 isLogin={true}/>,document.getElementById('root')); ``` #### 和运算符 && 一起使用 “&&”符号左边是条件运算式或者布尔值,右边是结构,如果左边为真,就生成右边的结构,如果为假,这一句整体忽略。 ```javascript class Notice extends React.Component{ constructor(props){ super(props); this.state={ username:'张大山', messages:[ '新邮件', '新的待办' ] } } render(){ return( <div> <h2>你好,{this.state.username}</h2> { this.state.messages.length>0 && <p>你有{this.state.messages.length}条消息</p> } </div> ) } } ReactDOM.render(<Notice />,document.getElementById('root')); ``` ## 表单数据绑定 表单元件对应着数据,而且这些数据都是变化的,所以我们会将表单元件的数据对应于组件中的state属性值,让它们之间的值实现双向数据绑定的效果,要实现这个效果,需要在表单元件上绑定onchange事件,来将state中的值改变为表单元件中的值,同时也需要将表单的value属性值,设置为等于state中的属性值。这种表单的值和state中的值进行绑定的组件叫做受控组件。 #### 文本框绑定示例: ```javascript class Myform extends React.Component { constructor(props){ super(props); this.state = { username:'', password:'' }; } // e指的是系统自动产生的事件对象 // e.target指的是发生事件的元素 fnChange=e=>{ this.setState({ // 使用属性名称表达式 [e.target.name]:e.target.value }) } render(){ return( <form> <p> <label>用户名:</label> { this.state.username } <br /> <input name="username" type="text" value={this.state.username} onChange={this.fnChange} /> </p> <p> <label>密码:</label> { this.state.password } <br /> <input name="password" type="password" value={this.state.password} onChange={this.fnChange} /> </p> </form> ); } } ReactDOM.render( <Myform />, document.getElementById('root') ); ``` ## Refs操作元素,文件上传 #### Refs操作元素 有时候还是需要访问dom节点的,react提供了Refs方式,方便我们访问dom节点。 Refs 是使用 React.createRef() 创建的,并通过 ref
1,515
.h ======================= /** * Copyright 2020-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. */ #ifndef MINDSPORE_MINDSPORE_CCSRC_DEBUG_DATA_DUMP_E_2_E_DUMP_H_ #define MINDSPORE_MINDSPORE_CCSRC_DEBUG_DATA_DUMP_E_2_E_DUMP_H_ #include <dirent.h> #include <stdlib.h> #include <map> #include <string> #include "backend/session/kernel_graph.h" #include "runtime/device/device_address.h" #include "debug/data_dump/dump_json_parser.h" #include "debug/data_dump/dump_utils.h" #ifdef ENABLE_D #include "proto/dump_data.pb.h" #endif #ifndef ENABLE_DEBUGGER class Debugger; #endif namespace mindspore { class E2eDump { public: E2eDump() = default; ~E2eDump() = default; static void DumpSetup(const session::KernelGraph *graph); static void UpdateIterMindRTDump(); static void DumpRunIter(const KernelGraphPtr &graph_ptr, uint32_t rank_id = 0); static void DumpData(const session::KernelGraph *graph, uint32_t rank_id, const Debugger *debugger = nullptr); static void DumpConstantData(const session::KernelGraph *graph, const std::string &cst_dump_path, const Debugger *debugger = nullptr); static void DumpConstantData(const session::KernelGraph *graph, uint32_t rank_id, const Debugger *debugger = nullptr); static bool DumpParametersData(const session::KernelGraph *graph, uint32_t rank_id, const Debugger *debugger); static bool DumpSingleNodeData(const CNodePtr &node, uint32_t graph_id, uint32_t rank_id, const Debugger *debugger = nullptr); static bool isDatasetGraph(const session::KernelGraph *graph); // Dump data when task error. static void DumpInputImpl(const CNodePtr &node, bool trans_flag, const std::string &dump_path, std::string *kernel_name, const Debugger *debugger); static void DumpOutputImpl(const CNodePtr &node, bool trans_flag, const std::string &dump_path, std::string *kernel_name, const Debugger *debugger); static bool DumpDirExists(const std::string &dump_path); #ifdef ENABLE_D static void DumpTensorToFile(const std::string &dump_path, const debugger::dump::DumpData &dump_data, char *data_ptr); static void DumpOpDebugToFile(const std::string &dump_path, const debugger::dump::DumpData &dump_data, char *data_ptr); #endif private: static void DumpOutput(const session::KernelGraph *graph, const std::string &dump_path, const Debugger *debugger); static void DumpOutputSingleNode(const CNodePtr &node, const std::string &dump_path, const Debugger *debugger); static void DumpInput(const session::KernelGraph *graph, const std::string &dump_path, const Debugger *debugger); static void DumpInputSingleNode(const CNodePtr &node, const std::string &dump_path, const Debugger *debugger); static void DumpParameters(const session::KernelGraph *graph, const std::string &dump_path, const Debugger *debugger); static void DumpGPUMemToFile(const std::string &file_path, const std::string &original_kernel_name, const device::DeviceAddress &addr, const ShapeVector &int_shapes, const TypeId &host_type, const TypeId &device_type, bool trans_flag, size_t slot, const Debugger *debugger); static bool IsDeviceTargetGPU(); static void DumpSingleAnfNode(const AnfNodePtr &anf_node, const size_t output_index, const std::string &dump_path, bool trans_flag, const Debugger *debugger); static void UpdateIterDumpSetup(const session::KernelGraph *graph, bool sink_mode); #ifdef ENABLE_D static nlohmann::json ParseOverflowInfo(char *data_ptr); template <typename T> static bool ConvertFormatForTensorAndDump(std::string dump_path, const T &tensor, char *data_ptr, const std::string &io, uint32_t slot); #endif inline static unsigned int starting_graph_id = INT32_MAX; }; } // namespace mindspore #endif // MINDSPORE_MINDSPORE_CCSRC_DEBUG_DATA_DUMP_E_2_E_DUMP_UTIL_H_ ======================= File: mindspore/ccsrc/backend/kernel_compiler/cpu/nnacl/intrinsics/sse/TiledC4MatMulFp32.c ======================= <reponame>PowerOlive/mindspore /** * Copyright 2020 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if defined(ENABLE_SSE) &&!defined(ENABLE_AVX) #include "nnacl/intrinsics/ms_simd_instructions.h" #include "nnacl/fp32/common_func_fp32.h" static inline void TiledC4MatmulFp32_Transfer(__m128 *dst1, __m128 *dst2, __m128 *dst3, __m128 *dst4, const __m128 weight, const float v1, const float v2, const float v3, const float v4) { *dst1 = _mm_add_ps(*dst1, _mm_mul_ps(weight, _mm_set_ps1(v1))); *dst2 = _mm_add_ps(*dst2, _mm_mul_ps(weight, _mm_set_ps1(v2))); *dst3 = _mm_add_ps(*dst3, _mm_mul_ps(weight, _mm_set_ps1(v3))); *dst4 = _mm_add_ps(*dst4, _mm_mul_ps(weight, _mm_set_ps1(v4))); } static inline void TiledC4MatmulFp32_LoadData(__m128 *src1, __m128 *src2, __m128 *src3, __m128 *src4, const float *src) { *src1 = _mm_loadu_ps(src); *src2 = _mm_loadu_ps(src + 4); *src3 = _mm_loadu_ps(src + 8); *src4 = _mm_loadu_ps(src + 12); } void TiledC4MatmulFp32(float *dst, const float *src, const float *weight, size_t cal_num, size_t ic4, size_t oc4) { const float *src_tmp = src; for (int i = 0; i < oc4; ++i) { float *dst_tmp = dst; src = src_tmp; size_t ic4_tmp = ic4 - 1; __m128 src1 = _mm_loadu_ps(src); __m128 src2 = _mm_loadu_ps(src + 4); __m128 src3 = _mm_loadu_ps(src + 8); __m128 src4 = _mm_loadu_ps(src + 12); src += 16; __m128 weight_data[4]; weight_data[0] = _mm_loadu_ps(weight); weight_data[1] = _mm_loadu_ps(weight + 4); weight_data[2] = _mm_loadu_ps(weight + 8); weight_data[3] = _mm_loadu_ps(weight + 12); weight += 16; __m128 dst1 = _mm_mul_ps(weight_data[0], _mm_set_ps1(MS_F32X4_GETI(src1, 0))); __m128 dst2 = _mm_mul_ps(weight_data[0], _mm_set_ps1(MS_F32X4_GETI(src2, 0))); __m128 dst3 = _mm_mul_ps(weight_data[0], _mm_set_ps1(MS_F32X4_GETI(src3, 0))); __m128 dst4 = _mm_mul_ps(weight_data[0], _mm_set_ps1(MS_F32X4_GETI(src4, 0))); for (int j = 1; j < 4; ++j) { TiledC4MatmulFp32_Transfer(&dst1, &dst2, &dst3, &dst4, weight_data[j], MS_F32X4_GETI(src1, j), MS_F32X4_GETI(src2, j), MS_F32X4_GETI(src3, j), MS_F32X4_GETI(src4, j)); } TiledC4MatmulFp32_LoadData(&src1, &src2, &src3, &src4, src); src += 16; __m128 dst5 = _mm_mul_ps(weight_data[0], _mm_set_ps1(MS_F32X4_GETI(src1, 0))); __m128 dst6 = _mm_mul_ps(weight_data[0], _mm_set_ps1(MS_F32X4_GETI(src2, 0))); __m128 dst7 = _mm_mul_ps(weight_data[0], _mm_set_ps1(MS_F32X4_GETI(src3, 0))); __m128 dst8 = _mm_mul_ps(weight_data[0], _mm_set_ps1(MS_F32X4_GETI(src4, 0))); for (int j = 1; j < 4; ++j) { TiledC4MatmulFp32_Transfer(&dst5, &dst6, &dst7, &dst8, weight_data[j], MS_F32X4_GETI(src1, j), MS_F32X4_GETI(src2, j), MS_F32X4_GETI(src3, j), MS_F32X4_GETI(src4, j)); } if (ic4_tmp!= 0) { ic4_tmp -= 1; TiledC4MatmulFp32_LoadData(&src1, &src2, &src3, &src4, src); src += 16; weight_data[0] = _mm_loadu_ps(weight); weight_data[1] = _mm_loadu_ps(weight + 4); weight += 8; dst1 = _mm_add_ps(dst1, _mm_mul_ps(weight_data[0], _mm_set_ps1(MS_F32X4_GETI(src1, 0)))); dst2 = _mm_add_ps(dst2, _mm_mul_ps(weight_data[0], _mm_set_ps1(MS_F32X4_GETI(src2, 0)))); for (; ic4_tmp!= 0; ic4_tmp -= 1) { dst3 = _mm_add_ps(dst3, _mm_mul_ps(weight_data[0], _mm_set_ps1(MS_F32X4_GETI(src3, 0)))); dst4 = _mm_add_ps(dst4, _mm_mul_ps(weight_data[0], _mm_set_ps1(MS_F32X4_GETI(src4, 0)))); TiledC4MatmulFp32_Transfer(&dst1, &dst2, &dst3, &dst4, weight_data[1], MS_F32X4_GETI(src1, 1), MS_F32X4_GETI(src2, 1), MS_F32X4_GETI(src3, 1), MS_F32X4_GETI(src4, 1)); weight_data[2] = _mm_loadu_ps(weight); weight_data[3] = _mm_loadu_ps(weight + 4); weight += 8; TiledC4MatmulFp32_Transfer(&dst1, &dst2, &dst3, &dst4, weight_data[2], MS_F32X4_GETI(src1, 2), MS_F32X4_GETI(src2, 2), MS_F32X4_GETI(src3, 2), MS_F32X4_GETI(src4, 2)); dst1 = _mm_add_ps(dst1, _mm_mul_ps(weight_data[3], _mm_set_ps1(MS_F32X4_GETI(src1, 3)))); dst2 = _mm_add_ps(dst2, _mm_mul_ps(weight_data[3], _mm_set_ps1(MS_F32X4_GETI(src2, 3)))); src1 = _mm_loadu_ps(src); src2 = _mm_loadu_ps(src + 4); dst3 = _mm_add_ps(dst3, _mm_mul_ps(weight_data[3], _mm_set_ps1(MS_F32X4_GETI(src3, 3)))); dst4 = _mm_add_ps(dst4, _mm_mul_ps(weight_data[3], _mm_set_ps1(MS_F32X4_GETI(src4, 3)))); src3 = _mm_loadu_ps(src + 8); src4 = _mm_loadu_ps(src + 12); src += 16; TiledC4MatmulFp32_Transfer(&dst5, &dst6, &dst7, &dst8, weight_data[0], MS_F32X4_GETI(src1, 0), MS_F32X4_GETI(src2, 0), MS_F32X4_GETI(src3, 0), MS_F32X4_GETI(src4, 0)); TiledC4MatmulFp32_Transfer(&dst5, &dst6, &dst7, &dst8, weight_data[1], MS_F32X4_GETI(src1, 1), MS_F32X4_GETI(src2, 1), MS_F32X4_GETI(src3, 1), MS_F32X4_GETI(src4, 1)); TiledC4MatmulFp32_Transfer(&dst5, &dst6, &dst7, &dst8, weight_data[2], MS_F32X4_GETI(src1, 2), MS_F32X4_GETI(src2, 2), MS_F32X4_GETI(src3, 2), MS_F32X4_GETI(src4, 2)); weight_data[0] = _mm_loadu_ps(weight); weight_data[1] = _mm_loadu_ps(weight + 4); weight += 8; TiledC4MatmulFp32_Transfer(&dst5, &dst6, &dst7, &dst8, weight_data[3], MS_F32X4_GETI(src1, 3), MS_F32X4_GETI(src2, 3), MS_F32X4_GETI(src3, 3), MS_F32X4_GETI(src4, 3)); TiledC4MatmulFp32_LoadData(&src1, &src2, &src3, &src4, src); src += 16; dst1 = _mm_add_ps(dst1, _mm_mul_ps(weight_data[0], _mm_set_ps1(MS_F32X4_GETI(src1, 0)))); dst2 = _mm_add_ps(dst2, _mm_mul_ps(weight_data[0], _mm_set_ps1(MS_F32X4_GETI(src2, 0)))); } dst3 = _mm_add_ps(dst3, _mm_mul_ps(weight_data[0], _mm_set_ps1(MS_F32X4_GETI(src3, 0)))); dst4 = _mm_add_ps(dst4, _mm_mul_ps(weight_data[0], _mm_set_ps1(MS_F32X4_GETI(src4, 0)))); TiledC4MatmulFp32_Transfer(&dst1, &dst2, &dst3, &dst4, weight_data[1], MS_F32X4_GETI(src1, 1), MS_F32X4_GETI(src2, 1), MS_F32X4_GETI(src3, 1), MS_F32X4_GETI(src4, 1)); weight_data[2] = _mm_loadu_ps(weight); weight_data[3] = _mm_loadu_ps(weight + 4); weight += 8; TiledC4MatmulFp32_Transfer(&dst1, &dst2, &dst3, &dst4, weight_data[2], MS_F32X4_GETI(src1, 2), MS_F32X4_GETI(src2, 2), MS_F32X4_GETI(src3, 2), MS_F32X4_GETI(src4, 2)); TiledC4MatmulFp32_Transfer(&dst1, &dst2, &dst3, &dst4, weight_data[3], MS_F32X4_GETI(src1, 3), MS_F32X4_GETI(src2, 3), MS_F32X4_GETI(src3, 3), MS_F32X4_GETI(src4, 3)); TiledC4MatmulFp32_LoadData(&src1, &src2, &src3, &src4, src); src += 16; for (int j = 0; j < 4; ++j) { TiledC4MatmulFp32_Transfer(&dst5, &dst6, &dst7, &dst8, weight_data[j], MS_F32X4_GETI(src1, j), MS_F32X4_GETI(src2, j), MS_F32X4_GETI(src3, j), MS_F32X4_GETI(src4, j)); } } _mm_storeu_ps(dst, dst1); _mm_storeu_ps(dst + 4, dst2); _mm_storeu_ps(dst + 8, dst3); _mm_storeu_ps(dst + 12, dst4); _mm_storeu_ps(dst + 16, dst5); _mm_storeu_ps(dst + 20, dst6); _mm_storeu_ps(dst + 24, dst7); _mm_storeu_ps(dst + 28, dst8); dst = dst_tmp + cal_num; } } #endif ======================= File: mindspore/ccsrc/backend/kernel_compiler/cpu/nnacl/int8/layer_norm_int8.c ======================= /** * Copyright 2020 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "nnacl/int8/layer_norm_int8.h" void LayerNormGammaAndBetaInt8(int8_t *dst, const int8_t *src, const float *gamma_data, const float *beta_data, const LayerNormQuantArg *quant, int num, const float mean, const float deno) { for (int i = 0; i < num; i++) { float fp32_src = (src[i] - quant->in_zp_) * quant->in_scale_; float fp32_dst = (fp32_src - mean) * deno; fp32_dst = fp32_dst * gamma_data[i] + beta_data[i]; int32_t int32_dst = (int32_t)round(fp32_dst * 1.0 / quant->out_scale_ + quant->out_zp_); dst[i] = (int8_t)MSMAX(MSMIN(int32_dst, 127), -128); } } /* * origin : (x-mean) / sqrt(variance + epsilon) * gamma + beta * quant : (x-mean) / sqrt(sum(x * x) - mean * mean) * gamma + beta * * */ int LayerNormInt8(const int8_t *src_data, const float *gamma_data, const float *beta_data, int8_t *dst_data, const LayerNormParameter *param, const LayerNormQuantArg *quant, int task_id) { if (src_data == NULL || dst_data == NULL || gamma_data == NULL || beta_data == NULL) { return NNACL_NULL_PTR; } NNACL_CHECK_ZERO_RETURN_ERR(param->params_inner_size_); NNACL_CHECK_ZERO_RETURN_ERR(param->params_outer_size_); int step = UP_DIV(param->norm_outer_size_, param->op_parameter_.thread_num_); int thread_end = MSMIN((task_id + 1) * step, param->norm_outer_size_); for (int i = task_id * step; i < thread_end; i++) { const int8_t *src_norm = src_data + i * param->norm_inner_size_; int8_t *dst_norm = dst_data + i * param->norm_inner_size_; float mean = 0.0f; float square_mean = 0.0f; for (int j = 0; j < param->norm_inner_size_; j++) { float float_src = (src_norm[j] - quant->in_zp_) * quant->in_scale_; mean += float_src; square_mean += float_src * float_src; } mean /= (float)param->norm_inner_size_; square_mean /= (float)param->norm_inner_size_; const float deno = 1 / sqrtf(square_mean - mean * mean + param->epsilon_); if (param->norm_outer_size_ <= param->params_outer_size_) { for (int x = 0; x < param->norm_inner_size_ / param->params_inner_size_; x++) { const int8_t *src_param = src_norm + x * param->params_inner_size_; int8_t *dst_param = dst_norm + x * param->params_inner_size_; LayerNormGammaAndBetaInt8(dst_param, src_param, gamma_data, beta_data, quant, param->norm_inner_size_, mean, deno); } } else { int x = i / param->params_outer_size_; const float *gamma = gamma_data + x * param->norm_inner_size_; const float *beta = beta_data + x * param->norm_inner_size_; LayerNormGammaAndBetaInt8(dst_norm, src_norm, gamma, beta, quant, param->norm_inner_size_, mean, deno); } } return NNACL_OK; } ======================= File: mindspore/ccsrc/backend/kernel_compiler/gpu/arrays/strided_slice_gpu_common.h ======================= /** * Copyright 2020-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. */ #ifndef MINDSPORE_CCSRC_BACKEND_KERNEL_COMPILER_GPU_ARRAYS_STRIDED_SLICE_GPU_COMMON_H_ #define MINDSPORE_CCSRC_BACKEND_KERNEL_COMPILER_GPU_ARRAYS_STRIDED_SLICE_GPU_COMMON_H_ #include <vector> #include <algorithm> #include "backend/session/anf_runtime_algorithm.h" #include "backend/kernel_compiler/common_utils.h" namespace mindspore { namespace kernel { constexpr size_t MAX_DIMS = 8; class StridedSliceGpuCommon { public: StridedSliceGpuCommon() : null_output_(false) {} ~StridedSliceGpuCommon() = default; void CollectInfo(const CNodePtr &kernel_node) { begin_ = AnfAlgo::GetNodeAttr<std::vector<int64_t>>(kernel_node, kAttrBegin); end_ = AnfAlgo::GetNodeAttr<std::vector<int64_t>>(kernel_node, kAttrEnd); strides_ = AnfAlgo::GetNodeAttr<std::vector<int64_t>>(kernel_node, kAttrStrides); FillEmptyDims(kernel_node, &begin_, &end_, &strides_, &input_shape_); ParseStrideSliceMasks(kernel_node, &begin_, &end_, &strides_, input_shape_); FillOutputDim(); null_output_ = IsNullOutput(); } protected: void FillOutputDim() { for (size_t i = 0; i < MAX_DIMS; i++) { if (begin_[i] <= end_[i] && strides_[i] > 0) { output_shape_.push_back((end_[i] - 1 - begin_[i]) / strides_[i] + 1); } else if (begin_[i] > end_[i] && strides_[i] < 0) { output_shape_.push_back((end_[i] - begin_[i] + 1) / strides_[i] + 1); } else { output_shape_.push_back(0); } } } bool IsNullOutput() { for (size_t i = 0; i < MAX_DIMS; i++) { if (begin_[i] >= end_[i] && strides_[i] > 0) { return true; } if (begin_[i] < end_[i] && strides_[i] < 0) { return true; } } return false; } std::vector<int64_t> begin_; std::vector<int64_t> end_; std::vector<int64_t> strides_; std::vector<size_t> input_shape_; std::vector<size_t> output_shape_; bool null_output_; std::vector<size_t> input_size_list_; std::vector<size_t> output_size_list_; std::vector<size_t> workspace_size_list_; }; } // namespace kernel } // namespace mindspore #endif // MINDSPORE_CCSRC_BACKEND_KERNEL_COMPILER_GPU_ARRAYS_STRIDED_SLICE_GPU_COMMON_H_ ======================= File: mindspore/ccsrc/distributed/rpc/tcp/connection_pool.h ======================= <filename>mindspore/ccsrc/distributed/rpc/tcp/connection_pool.h /** * 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. */ #ifndef MINDSPORE_CCSRC_DISTRIBUTED_RPC_TCP_CONNECTION_POOL_H_ #define MINDSPORE_CCSRC_DISTRIBUTED_RPC_TCP_CONNECTION_POOL_H_ #include <map> #include <set> #include <string> #include "distributed/rpc/tcp/constants.h" #include "distributed/rpc/tcp/connection.h" namespace mindspore { namespace distributed { namespace rpc { struct ConnectionInfo { int socket_fd; std::string from; std::string to; DeleteCallBack delete_callback; }; /* * Maintains a collection of reusable connections. */ class ConnectionPool { public: ConnectionPool() : double_link_(false) {} ~ConnectionPool(); // Get the singleton instance of ConnectionPool. static ConnectionPool *GetConnectionPool(); /* * Operations for ConnectionInfo. */ void AddConnInfo(int socket_fd, const AID &sAid, const AID &dAid, DeleteCallBack delcb); bool ReverseConnInfo(int from_socket_fd, int to_socket_fd); /* * Operations for Connection. */ // Add a connection. void AddConnection(Connection *conn); // Find connection. Connection *ExactFindConnection(const std::string &to, bool remoteLink); Connection *FindConnection(const std::string &to, bool remoteLink); Connection *FindConnection(const std::string &to, bool remoteLink, bool exactNotRemote); Connection *FindMaxConnection(); Connection *FindFastConnection(); // Delete connection. void ExactDeleteConnection(const std::string &to, bool remoteLink); void DeleteAllConnections(std::map<std::string, Connection *> *alllinks); // Close connection. void CloseConnection(Connection *conn); void SetConnPriority(const std::string &to, bool remoteLink, ConnectionPriority pri); // Single link or double link. void SetLinkPattern(bool linkPattern); void ResetAllConnMetrics(); private: ConnectionInfo *FindConnInfo(int socket_fd, const AID &sAid, const AID &dAid); void DeleteConnInfo(int socket_fd); void DeleteConnInfo(const std::string &to, int socket_fd); void DeleteAllConnInfos(); bool double_link_; // to_url=tcp@ip:port, event struct std::map<std::string, Connection *> local_conns_; // Maintains the remote connections by remote server addresses. std::map<std::string, Connection *> remote_conns_; // each to_url has two fds at most, and each fd has multiple linkinfos std::map<int, std::set<ConnectionInfo *>> conn_infos_; static ConnectionPool *conn_pool; friend class Connection; friend class TCPComm; }; } // namespace rpc } // namespace distributed } // namespace mindspore #endif ======================= File: mindspore/ccsrc/frontend/optimizer/auto_monad_eliminate.h ======================= <reponame>PowerOlive/mindspore /** * 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. */ #ifndef MINDSPORE_CCSRC_FRONTEND_OPTIMIZER_AUTO_MONAD_ELIMINATOR_H_ #define MINDSPORE_CCSRC_FRONTEND_OPTIMIZER_AUTO_MONAD_ELIMINATOR_H_ #include "ir/anf.h" #include "ir/manager.h" #include "frontend/optimizer/optimizer.h" namespace mindspore { namespace opt { class AutoMonadEliminator { public: AutoMonadEliminator() = default; virtual ~AutoMonadEliminator() = default; bool operator()(const FuncGraphPtr &root, const OptimizerPtr &optimizer) { auto manager = optimizer->manager(); MS_EXCEPTION_IF_NULL(manager); manager->AddFuncGraph(root); // Never report change. (void)ReplaceAutoMonadNode(manager); (void)EliminateAutoMonadNode(manager); return false; } private: bool ReplaceAutoMonadNode(const FuncGraphManagerPtr &manager) const; bool EliminateAutoMonadNode(const FuncGraphManagerPtr &manager) const; }; } // namespace opt } // namespace mindspore #endif // MINDSPORE_CCSRC_FRONTEND_OPTIMIZER_AUTO_MONAD_ELIMINATOR_H_ ======================= File: mindspore/lite/tools/benchmark/nnie/src/nnie_cfg_parser.h ======================= /** * 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. */ #ifndef MINDSPORE_LITE_TOOLS_BENCHMARK_NNIE_NNIE_CFG_PARSER_H_ #define MINDSPORE_LITE_TOOLS_BENCHMARK_NNIE_NNIE_CFG_PARSER_H_ #include <vector> namespace mindspore { namespace nnie { /** * Flags is a config container. * Member objects: * 1.time_step_: step num only for rnn or lstm model. Default is 1. * 2.max_roi_num_: maximum number of ROI area, which is single picture supports, must be greater than 0.Default is 300. * 3.core_ids_: running kernels' id, support multi-core, separated by commas when setting, such as {0, 1, 2}. * each element must be a integer, wch meet such inequality 0 <= val < 8. * Default is {0}. */ class Flags { public: Flags() = default; ~Flags() = default; void Init(); public: int time_step_{1}; int max_roi_num_{300}; std::vector<int> core_ids_{0}; }; } // namespace nnie } // namespace mindspore #endif ======================= File: mindspore/ccsrc/backend/kernel_compiler/gpu/sponge/pme/ifft_3d_kernel.h ======================= /** * 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. */ #ifndef MINDSPORE_CCSRC_BACKEND_KERNEL_COMPILER_GPU_SPONGE_PME_IFFT_3D_KERNEL_H_ #define MINDSPORE_CCSRC_BACKEND_KERNEL_COMPILER_GPU_SPONGE_PME_IFFT_3D_KERNEL_H_ #include <cuda_runtime_api.h> #include <cufft.h> #include <vector> #include <string> #include <map> #include "backend/kernel_compiler/gpu/gpu_kernel.h" #include "backend/kernel_compiler/gpu/gpu_kernel_factory.h" #include "runtime/device/gpu/cuda_common.h" #include "backend/kernel_compiler/gpu/cuda_impl/sponge/pme/ifft_3d_impl.cuh" namespace mindspore { namespace kernel { template <typename T> using Complex = mindspore::utils::Complex<T>; template <typename T> class IFFT3DGpuKernel : public GpuKernel { public: IFFT3DGpuKernel() = default; ~IFFT3DGpuKernel() override = default; bool Init(const CNodePtr &kernel_node) override { fftx = static_cast<int>(GetAttr<int64_t>(kernel_node, "fftx")); ffty = static_cast<int>(GetAttr<int64_t>(kernel_node, "ffty")); fftz = static_cast<int>(GetAttr<int64_t>(kernel_node, "fftz")); Nfft = fftx * ffty * fftz; Nall = fftx * ffty * (fftz - 1) * 2; cufftPlan3d(&FFT_plan_c2r, fftx, ffty, (fftz - 1) * 2, CUFFT_C2R); InitSizeLists(); return true; } const std::vector<size_t> &GetInputSizeList() const override { return input_size_list_; } const std::vector<size_t> &GetOutputSizeList() const override { return output_size_list_; } const std::vector<size_t> &GetWorkspaceSizeList() const override { return workspace_size_list_; } bool Launch(const std::vector<AddressPtr> &inputs, const std::vector<AddressPtr> &workspace, const std::vector<AddressPtr> &outputs, void *stream_ptr) override { auto input_tensor = GetDeviceAddress<Complex<T>>(inputs, 0); auto output_tensor = GetDeviceAddress<T>(outputs, 0); cufftSetStream(FFT_plan_c2r, reinterpret_cast<cudaStream_t>(stream_ptr)); IFFT3D<T>(Nfft, input_tensor, output_tensor, FFT_plan_c2r, reinterpret_cast<cudaStream_t>(stream_ptr)); return true; } protected: void InitSizeLists() override { input_size_list_.push_back(Nfft * sizeof(Complex<T>)); output_size_list_.push_back(Nall * sizeof(T)); } private: std::vector<size_t> input_size_list_; std::vector<size_t> output_size_list_; std::vector<size_t> workspace_size_list_; int fftx; int ffty; int fftz; int Nall; int Nfft; cufftHandle FFT_plan_c2r; }; } // namespace kernel } // namespace mindspore #endif ======================= File: mindspore/lite/tools/optimizer/parallel/spliter.h ======================= <gh_stars>1000+ /** * 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. */ #ifndef MINDSPORE_LITE_TOOLS_OPTIMIZER_PARALLEL_SPLITER_H #define MINDSPORE_LITE_TOOLS_OPTIMIZER_PARALLEL_SPLITER_H #include <vector> #include <string> #include <set> #include <unordered_map> #include "schema/inner/model_generated.h" #include "utils/utils.h" #include "tools/optimizer/common/gllo_utils.h" #include "tools/converter/converter_flags.h" #include "include/context.h" #include "include/lite_types.h" namespace mindspore { namespace opt { struct IntCompare { bool operator()(const int &lhs, const int &rhs) const { return lhs > rhs; } }; class Spliter { public: static Spliter *GetInstance(); Spliter(const Spliter &) = delete; Spliter &operator=(const Spliter &) = delete; // record the global numbers of matched multi_conv nodes void RecordGraphInfo(const FuncGraphPtr &func_graph); // update current input node's output. if candidate node has been recorded, we will be ignore it, otherwise record it. void UpdateNodeOutputs(const std::string &input_node_name, const AnfNodePtr &candidate_output); // update current node's input shapes. void UpdateNodeInputShapes(const std::string &node_name, const std::vector<ShapeVector> &input_shapes); // update current node's output shapes. void UpdateNodeOutputShapes(const std::string &node_name, const std::vector<ShapeVector> &output_shapes); std::unordered_map<std::string, std::vector<AnfNodePtr>> graph_node_outputs() const { return graph_node_outputs_; } std::unordered_map<std::string, std::vector<ShapeVector>> graph_node_output_shapes() const { return graph_node_output_shapes_; } std::unordered_map<std::string, std::vector<ShapeVector>> graph_node_input_shapes() const { return graph_node_input_shapes_; } std::set<int, IntCompare> graph_match_multi_numbers() const { return match_numbers_; } std::unordered_map<AnfNodePtr, std::set<AnfNodePtr>> nodes_inputs() const { return nodes_inputs_; } std::unordered_map<AnfNodePtr, std::set<AnfNodePtr>> nodes_outputs() const { return nodes_outputs_; } void VisitNodesInputs(const FuncGraphPtr &func_graph); void VisitNodesOutputs(const FuncGraphPtr &func_graph); private: Spliter() = default; virtual ~Spliter() = default; private: std::unordered_map<std::string, std::vector<AnfNodePtr>> graph_node_outputs_; std::unordered_map<std::string, std::vector<ShapeVector>> graph_node_output_shapes_; std::unordered_map<std::string, std::vector<ShapeVector>> graph_node_input_shapes_; std::unordered_map<AnfNodePtr, std::set<AnfNodePtr>> nodes_inputs_; std::unordered_map<AnfNodePtr, std::set<AnfNodePtr>> nodes_outputs_; std::unordered_map<AnfNodePtr, bool> match_visited_; std::set<int, IntCompare> match_numbers_; }; } // namespace opt } // namespace mindspore #endif // MINDSPORE_LITE_TOOLS_OPTIMIZER_PARALLEL_SPLITER_H ======================= File: mindspore/ccsrc/runtime/device/ascend/executor/hccl_dynamic_kernel.h ======================= <filename>mindspore/ccsrc/runtime/device/ascend/executor/hccl_dynamic_kernel.h /** * Copyright 2020 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef MINDSPORE_MINDSPORE_CCSRC_RUNTIME_DEVICE_ASCEND_EXECUTOR_HCCL_DYNAMIC_KERNEL_H_ #define MINDSPORE_MINDSPORE_CCSRC_RUNTIME_DEVICE_ASCEND_EXECUTOR_HCCL_DYNAMIC_KERNEL_H_ #include <condition_variable> #include <string> #include "runtime/device/executor/dynamic_kernel.h" #include "utils/ms_utils.h" namespace mindspore { namespace device { namespace ascend { class HcclDynamicKernel : public DynamicKernel { public: HcclDynamicKernel(const std::string &hccl_type, void *input_ptr, void *output_ptr, uint64_t count, int32_t data_type, int32_t op_type, int32_t root, void *stream, const CNodePtr &cnode_ptr) : DynamicKernel(stream, cnode_ptr), hccl_type_(hccl_type), input_ptr_(input_ptr), output_ptr_(output_ptr), count_(count), data_type_(data_type), op_type_(op_type), root_(root) {} ~HcclDynamicKernel() override = default; void UpdateArgs() override; void Execute() override; void PostExecute() override; private: std::string hccl_type_; void *input_ptr_; void *output_ptr_; uint64_t count_{0}; int32_t data_type_{0}; int32_t op_type_{0}; int32_t root_{0}; std::mutex hccl_mutex_; std::condition_variable cond_; void StaticShapeExecute(); }; } // namespace ascend } // namespace device } // namespace mindspore #endif // MINDSPORE_MINDSPORE_CCSRC_RUNTIME_DEVICE_ASCEND_EXECUTOR_HCCL_DYNAMIC_KERNEL_H_ ======================= File: mindspore/lite/tools/optimizer/const_fold/fold_utils.h ======================= /** * 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. */ #ifndef MINDSPORE_LITE_TOOLS_OPTIMIZER_CONST_FOLD_FOLD_UTILS_H_ #define MINDSPORE_LITE_TOOLS_OPTIMIZER_CONST_FOLD_FOLD_UTILS_H_ #include <memory> #include "ir/anf.h" #include "include/api/context.h" #include "include/registry/converter_context.h" #include "src/inner_context.h" namespace mindspore { namespace opt { class ConstFoldProcessor { public: explicit ConstFoldProcessor(converter::FmkType fmk_type = converter::kFmkTypeMs, bool train_flag = false) : fmk_type_(fmk_type), train_flag_(train_flag) {} int DoConstantFold(const FuncGraphPtr &func_graph, const CNodePtr &cnode); ~ConstFoldProcessor() = default; private: bool Init(); converter::FmkType fmk_type_{converter::kFmkTypeMs}; bool train_flag_{false}; std::shared_ptr<lite::InnerContext> context_{nullptr}; std::shared_ptr<mindspore::Context> ms_context_{nullptr}; }; } // namespace opt } // namespace mindspore #endif // MINDSPORE_LITE_TOOLS_OPTIMIZER_CONST_FOLD_FOLD_UTILS_H_ ======================= File: mindspore/ccsrc/backend/optimizer/ascend/ir_fusion/lamb_next_mv_with_decay_rule.h ======================= /** * Copyright 2020 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef MINDSPORE_CCSRC_BACKEND_OPTIMIZER_ASCEND_IR_FUSION_LAMB_NEXT_MV_WITH_DECAY_RULE_H_ #define MINDSPORE_CCSRC_BACKEND_OPTIMIZER_ASCEND_IR_FUSION_LAMB_NEXT_MV_WITH_DECAY_RULE_H_ #include <vector> #include <memory> #include <string> #include "backend/optimizer/common/optimizer.h" #include "backend/optimizer/common/helper.h" namespace mindspore { namespace opt { class LambNextMVWithDecayRule : public MultipleOutputPatternProcessPass { public: explicit LambNextMVWithDecayRule(const std::string &name = "", bool multigraph = true) : MultipleOutputPatternProcessPass(name, multigraph) { for (size_t i = 0; i < kLambNextMVWithDecayInputNum; ++i) { input_vars_.push_back(std::make_shared<Var>()); } for (size_t i = 0; i < kLambNextMVWithDecayConstantMulInputNum; ++i) { constant_mul_input_vars_.push_back(std::make_shared<Var>()); } constant_add2_y_ = std::make_shared<Var>(); mul4_var_ = std::make_shared<Var>(std::make_shared<Primitive>(prim::kPrimMul->name())); real_div0_var_ = std::make_shared<Var>(std::make_shared<Primitive>(kRealDivOpName)); real_div1_var_ = std::make_shared<Var>(std::make_shared<Primitive>(kRealDivOpName)); add0_var_ = std::make_shared<Var>(std::make_shared<Primitive>(prim::kPrimAdd->name())); add1_var_ = std::make_shared<Var>(std::make_shared<Primitive>(prim::kPrimAdd->name())); } ~LambNextMVWithDecayRule() override = default; const BaseRef DefinePattern() const override = 0; BaseRef DefineAnotherPattern() const override = 0; const AnfNodePtr Process(const FuncGraphPtr &, const AnfNodePtr &, const EquivPtr &) const override; bool IsShareNodes(const EquivPtr &equiv1, const EquivPtr &equiv2) const override; protected: AnfNodePtr GetLambNextMVWithDecayOutput(const FuncGraphPtr &func_graph, const AnfNodePtr &new_node, const AnfNodePtr &add3, const AnfNodePtr &add5, const EquivPtr &equiv) const; AnfNodePtr CreateLambNextMVWithDecayNode(const FuncGraphPtr &func_graph, const AnfNodePtr &add3, const AnfNodePtr &add5, const EquivPtr &equiv) const; std::vector<VarPtr> input_vars_; std::vector<VarPtr> constant_mul_input_vars_; // nodes which two patterns share VarPtr constant_add2_y_; VarPtr mul4_var_; VarPtr real_div0_var_; VarPtr real_div1_var_; // part of output nodes VarPtr add0_var_; VarPtr add1_var_; }; class LambNextMVWithDecayRuleCond1 : public LambNextMVWithDecayRule { public: explicit LambNextMVWithDecayRuleCond1(bool multigraph = true) : LambNextMVWithDecayRule("lamb_next_mv_with_decay_rule_cond1", multigraph) {} ~LambNextMVWithDecayRuleCond1() override = default; const BaseRef DefinePattern() const override; BaseRef DefineAnotherPattern() const override; }; class LambNextMVWithDecayRuleCond2 : public LambNextMVWithDecayRule { public: explicit LambNextMVWithDecayRuleCond2(bool multigraph = true) : LambNextMVWithDecayRule("lamb_next_mv_with_decay_rule_cond2", multigraph) {} ~LambNextMVWithDecayRuleCond2() override = default; const BaseRef DefinePattern() const override; BaseRef DefineAnotherPattern() const override; }; class LambNextMVWithDecayRuleCond3 : public LambNextMVWithDecayRule { public: explicit LambNextMVWithDecayRuleCond3(bool multigraph = true) : LambNextMVWithDecayRule("lamb_next_mv_with_decay_rule_cond3", multigraph) {} ~LambNextMVWithDecayRuleCond3() override = default; const BaseRef DefinePattern() const override; BaseRef DefineAnotherPattern() const override; }; class LambNextMVWithDecayRuleCond4 : public LambNextMVWithDecayRule { public: explicit LambNextMVWithDecayRuleCond4(bool multigraph = true) : LambNextMVWithDecayRule("lamb_next_mv_with_decay_rule_cond4", multigraph) {} ~LambNextMVWithDecayRuleCond4() override = default; const BaseRef DefinePattern() const override; BaseRef DefineAnotherPattern() const override; }; } // namespace opt } // namespace mindspore #endif // MINDSPORE_CCSRC_BACKEND_OPTIMIZER_ASCEND_IR_FUSION_LAMB_NEXT_MV_WITH_DECAY_RULE_H_ ======================= File: mindspore/ccsrc/backend/kernel_compiler/aicpu/aicpu_ops/common/kernel_base.h ======================= /** * 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. */ #ifndef AICPU_OPS_AICPU_COMMON_KERNEL_BASE_H_ #define AICPU_OPS_AICPU_COMMON_KERNEL_BASE_H_ #include <cstdint> #include <vector> #include <string> #include "common/kernel_util.h" #include "aicpu/common/aicpu_task_struct.h" #include "securec/include/securec.h" #include "common/tensor.h" #include "cce/fwk_adpt_struct.h" #include "common/kernel_log.h" #include "proto/aicpu_tensor.pb.h" namespace aicpu { class KernelBase { public: explicit KernelBase(const std::string &kernel_name); ~KernelBase() = default; uint32_t Compute(void *param); size_t GetDataTypeSize(::aicpuops::DataType data_type); protected: virtual uint32_t ParseKernelParam() = 0; virtual uint32_t DoCompute() = 0; template <typename T> uint32_t ParseExtendParam(T *param_var, std::string param_name); uint32_t ParseNodeDef(); uint32_t ParseExtInfo(); uint32_t ParseExtShapeType(FWKAdapter::ExtInfo *ext_info); uint32_t ParseExtInputShape(FWKAdapter::ExtInfo *ext_info); uint32_t ParseExtOutputShape(FWKAdapter::ExtInfo *ext_info); uint32_t UpdateInputShape(); uint32_t UpdateOutputShape(); private: KernelBase(const KernelBase &) = delete; KernelBase &operator=(const KernelBase &) = delete; KernelBase(KernelBase &&) = delete; KernelBase &operator=(KernelBase &&) = delete; uint32_t ParseParam(void *param); protected: std::string kernel_name_; std::vector<uintptr_t> io_addrs_; uint32_t extend_param_len_; uint8_t *extend_param_base_; AicpuParamHead *param_head_; bool unknow_shape_; aicpuops::NodeDef node_def_; std::vector<FWKAdapter::ShapeAndType *> input_shape_and_type_; std::vector<FWKAdapter::ShapeAndType *> output_shape_and_type_; }; } // namespace aicpu #endif // AICPU_OPS_AICPU_COMMON_KERNEL_BASE_H_ ======================= File: mindspore/lite/examples/quick_start_c/main.c ======================= /** * 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. */ #include <stdlib.h> #include <stdio.h> #include "include/c_api/model_c.h" int GenerateInputDataWithRandom(MSTensorHandleArray inputs) { for (size_t i = 0; i < inputs.handle_num; ++i) { float *input_data = (float *)MSTensorGetMutableData(inputs.handle_list[i]); if (input_data == NULL) { printf("MSTensorGetMutableData failed.\n"); return kMSStatusLiteError; } int64_t num = MSTensorGetElementNum(inputs.handle_list[i]); const int divisor = 10; for (size_t j = 0; j < num; j++) { input_data[j] = (float)(rand() % divisor) / divisor; // 0--0.9f } } return kMSStatusSuccess; } int QuickStart(int argc, const char **argv) { if (argc < 2) { printf("Model file must be provided.\n"); return kMSStatusLiteError; } // Create and init context, add CPU device info MSContextHandle context = MSContextCreate(); if (context == NULL) { printf("MSContextCreate failed.\n"); return kMSStatusLiteError; } const int thread_num = 2; MSContextSetThreadNum(context, thread_num); MSContextSetThreadAffinityMode(context, 1); MSDeviceInfoHandle cpu_device_info = MSDeviceInfoCreate(kMSDeviceTypeCPU); if (cpu_device_info == NULL) { printf("MSDeviceInfoCreate failed.\n"); MSContextDestroy(&context); return kMSStatusLiteError; } MSDeviceInfoSetEnableFP16(cpu_device_info, false); MSContextAddDeviceInfo(context, cpu_device_info); // Create model MSModelHandle model = MSModelCreate(); if (model == NULL) { printf("MSModelCreate failed.\n"); MSContextDestroy(&context); return kMSStatusLiteError; } // Build model int ret = MSModelBuildFromFile(model, argv[1], kMSModelTypeMindIR, context); if (ret!= kMSStatusSuccess) { printf("MSModelBuildFromFile failed, ret: %d.\n", ret); MSModelDestroy(&model); return ret; } // Get Inputs MSTensorHandleArray inputs = MSModelGetInputs(model); if (inputs.handle_list == NULL) { printf("MSModelGetInputs failed, ret: %d.\n", ret); MSModelDestroy(&model); return ret; } // Generate random data as input data. ret = GenerateInputDataWithRandom(inputs); if (ret!= kMSStatusSuccess) { printf("GenerateInputDataWithRandom failed, ret: %d.\n", ret); MSModelDestroy(&model); return ret; } // Model Predict MSTensorHandleArray outputs; ret = MSModelPredict(model, inputs, &outputs, NULL, NULL); if (ret!= kMSStatusSuccess) { printf("MSModelPredict failed, ret: %d.\n", ret); MSModelDestroy(&model); return ret; } // Print Output Tensor Data. for (size_t i = 0; i < inputs.handle_num; ++i) { MSTensorHandle tensor = inputs.handle_list[i]; int64_t element_num = MSTensorGetElementNum(tensor); printf("Tensor name: %s, elements num: %ld.\n", MSTensorGetName(tensor), element_num); const float *data = (const float *)MSTensorGetData(tensor); printf("output data is:\n"); const int max_print_num = 50; for (int j = 0; j < element_num && j <= max_print_num; ++j) { printf("%f ", data[i]); } printf("\n"); } // Delete model. MSModelDestroy(&model); return kMSStatusSuccess; } int main(int argc, const char **argv) { return QuickStart(argc, argv); } ======================= File: mindspore/ccsrc/backend/kernel_compiler/cpu/nnacl/fp32/attention_fp32.c ======================= <filename>mindspore/ccsrc/backend/kernel_compiler/cpu/nnacl/fp32/attention_fp32.c /** * 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. */ #include "nnacl/fp32/attention_fp32.h" #include <string.h> #include <math.h> #include "nnacl/fp32/matmul_fp32.h" #include "nnacl/fp32/add_fp32.h" #include "nnacl/fp32/transpose_fp32.h" #include "nnacl/fp32/softmax_fp32.h" #include "nnacl/errorcode.h" int InitMatrix(Matrix *matrix, int batch, int row, int col, bool is_trans) { if (matrix == NULL) { return NNACL_NULL_PTR; } matrix->batch_ = batch; matrix->row_ = row; matrix->col_ = col; matrix->is_transpose_ = is_trans; matrix->data_ = NULL; matrix->packed_data_ = NULL; return NNACL_OK; } size_t LeftMatrixPackElementSize(Matrix *matrix, int row_tile) { if (matrix == NULL) { return 0; } int real_row = matrix->is_transpose_? matrix->col_ : matrix->row_; int deep = matrix->is_transpose_? matrix->row_ : matrix->col_; bool vec_matmul = real_row == 1; int row_align = vec_matmul? 1 : UP_ROUND(real_row, row_tile); int dst_area = row_align * deep; matrix->packed_row_ = row_align; matrix->packed_col_ = deep; return matrix->batch_ * dst_area; } size_t RightMatrixPackElementSize(Matrix *matrix, int col_tile) { if (matrix == NULL) { return 0; } int deep = matrix->is_transpose_? matrix->col_ : matrix->row_; int real_col = matrix->is_transpose_? matrix->row_ : matrix->col_; bool vec_matmul = deep == 1; int col_align = vec_matmul? real_col : UP_ROUND(real_col, col_tile); int dst_area = deep * col_align; matrix->packed_row_ = deep; matrix->packed_col_ = col_align; return matrix->batch_ * dst_area; } int PackLeftMatrix(Matrix *matrix, int row_tile) { if (matrix == NULL || matrix->data_ == NULL || row_tile == 0) { return NNACL_NULL_PTR; } int real_row = matrix->is_transpose_? matrix->col_ : matrix->row_; int deep = matrix->is_transpose_? matrix->row_ : matrix->col_; bool vec_matmul = real_row == 1; int row_align = vec_matmul? 1 : UP_ROUND(real_row, row_tile); int src_area = matrix->row_ * matrix->col_; int dst_area = row_align * deep; bool malloced = false; if (matrix->packed_data_ == NULL) { matrix->packed_data_ = (float *)malloc(dst_area * matrix->batch_ * sizeof(float)); if (matrix->packed_data_ == NULL) { return NNACL_NULL_PTR; } malloced = true; } if (vec_matmul) { memcpy(matrix->packed_data_, matrix->data_, matrix->batch_ * dst_area * sizeof(float)); } else { for (int i = 0; i < matrix->batch_; i++) { const float *cur_src = matrix->data_ + i * src_area; float *cur_dst = matrix->packed_data_ + i * dst_area; switch (row_tile) { case C6NUM: if (matrix->is_transpose_) { RowMajor2Row6Major(cur_src, cur_dst, real_row, deep); } else { RowMajor2Col6Major(cur_src, cur_dst, real_row, deep); } break; case C4NUM: if (matrix->is_transpose_) { RowMajor2Row4Major(cur_src, cur_dst, real_row, deep); } else { RowMajor2Col4Major(cur_src, cur_dst, real_row, deep); } break; case C12NUM: if (matrix->is_transpose_) { RowMajor2Row12Major(cur_src, cur_dst, real_row, deep); } else { RowMajor2Col12Major(cur_src, cur_dst, real_row, deep); } break; default: if (malloced) { free(matrix->packed_data_); matrix->packed_data_ = NULL; return NNACL_ERR; } break; } } } matrix->packed_row_ = row_align; matrix->packed_col_ = deep; return NNACL_OK; } int PackRightMatrix(Matrix *matrix, int col_tile) { if (matrix == NULL || matrix->data_ == NULL || col_tile == 0) { return NNACL_NULL_PTR; } int deep = matrix->is_transpose_? matrix->col_ : matrix->row_; int real_col = matrix->is_transpose_? matrix->row_ : matrix->col_; bool vec_matmul = deep == 1; int col_align = vec_matmul? real_col : UP_ROUND(real_col, col_tile); int src_area = matrix->row_ * matrix->col_; int dst_area = deep * col_align; bool malloced = false; if (matrix->packed_data_ == NULL) { matrix->packed_data_ = (float *)malloc(dst_area * matrix->batch_ * sizeof(float)); if (matrix->packed_data_ == NULL) { return NNACL_NULL_PTR; } malloced = true; } if (vec_matmul) { memcpy(matrix->packed_data_, matrix->data_, matrix->batch_ * dst_area * sizeof(float)); } else { for (int i = 0; i < matrix->batch_; i++) { const float *cur_src = matrix->data_ + i * src_area; float *cur_dst = matrix->packed_data_ + i * dst_area; switch (col_tile) { case C16NUM: if (matrix->is_transpose_) { RowMajor2Col16Major(cur_src, cur_dst, deep, real_col); } else { RowMajor2Row16Major(cur_src, cur_dst, deep, real_col); } break; case C4NUM: if (matrix->is_transpose_) { RowMajor2Col4Major(cur_src, cur_dst, deep, real_col); } else { RowMajor2Row4Major(cur_src, cur_dst, deep, real_col); } break; case C8NUM: if (matrix->is_transpose_) { RowMajor2Col8Major(cur_src, cur_dst, deep, real_col); } else { RowMajor2Row8Major(cur_src, cur_dst, deep, real_col); } break; default: if (malloced) { free(matrix->packed_data_); matrix->packed_data_ = NULL; return NNACL_ERR; } break; } } } matrix->packed_row_ = deep; matrix->packed_col_ = col_align; return NNACL_OK; } int PackAttentionBias(Matrix *matrix, int tile) { if (matrix == NULL || matrix->batch_!= 1 || matrix->row_!= 1 || matrix->data_ == NULL) { return NNACL_PARAM_INVALID; } if (tile == 0) { return NNACL_OK; } int size = matrix->col_; float *src = matrix->data_; int size_align = UP_ROUND(size, tile); if (size_align <= 0) { return NNACL_ERR; } matrix->packed_data_ = (float *)malloc(size_align * sizeof(float)); if (matrix->packed_data_ == NULL) { return NNACL_NULL_PTR; } matrix->packed_row_ = matrix->row_; matrix->packed_col_ = size_align; memset(matrix->packed_data_, 0, size_align * sizeof(float)); memcpy(matrix->packed_data_, src, size * sizeof(float)); return NNACL_OK; } static void RelativeShiftPad(const float *input_data, float *output_data, const int *input_shape, int tid, int thread_num) { int row = input_shape[0]; int col = input_shape[1]; int out_area = row * (col + 1); memset(output_data, 0, out_area * sizeof(float)); for (int r = tid; r < row; r += thread_num) { float *dst = output_data + r * (col + 1); const float *src = input_data + r * col; memcpy(dst, src, col * sizeof(float)); } int tile = row % thread_num; for (int r = row - tile; r < row; r++) { float *dst = output_data + r * (col + 1); const float *src = input_data + r * col; memcpy(dst, src, col * sizeof(float)); } } static void RelativeShiftSlice(const float *input_data, float *output_data, const int *input_shape, int tid, int thread_num) { int row = input_shape[0]; int col = input_shape[1]; int begin = row; memset(output_data, 0, row * row * sizeof(float)); for (int r = tid; r < row; r += thread_num) { float *dst = output_data + r * row; const float *src = input_data + r * col + begin; memcpy(dst, src, (col / 2) * sizeof(float)); } int tile = row % thread_num; for (int r = row - tile; r < row; r++) { float *dst = output_data + r * row; const float *src = input_data + r * col + begin; memcpy(dst, src, (col / 2) * sizeof(float)); } } static void RelativeShift(const Matrix *x, float *pad_buf, float *slice_buf) { int x_area = x->row_ * x->col_; int pad_area = x->row_ * (x->col_ + 1); int slice_area = x->row_ * (x->col_ / 2); int input_shape[] = {x->row_, x->col_}; memset(slice_buf, 0, x->batch_ * x->row_ * (x->col_ / 2) * sizeof(float)); for (int i = 0; i < x->batch_; i++) { float *cur_x_data = x->data_ + i * x_area; memset(pad_buf, 0, pad_area * sizeof(float)); // pad: [row, col + 1] RelativeShiftPad(cur_x_data, pad_buf, input_shape, 0, 1); // reshape: [col + 1, row] // slice last row: [col, row] // reshape: [row, col] // slice col -> [row, row + col / 2]: [row, col / 2] float *cur_slice_data = slice_buf + i * slice_area; RelativeShiftSlice(pad_buf, cur_slice_data, input_shape, 0, 1); } } static void ElementOptAddDiv(const float *input0, const float *input1, const float input2, float *output, const int batch, const int area) { int index = 0; const float mul = 1 / input2; for (int b = 0; b < batch; b++) { const float *cur_input0 = input0 + b * area; const float *cur_input1 = input1 + b * area; float *cur_output = output + b * area; #ifdef ENABLE_NEON for (; index <= area - 4; index += C4NUM) { float32x4_t vin0 = vld1q_f32(cur_input0 + index); float32x4_t vin1 = vld1q_f32(cur_input1 + index); float32x4_t vout = vaddq_f32(vin0, vin1); vout = vmulq_n_f32(vout, mul); vst1q_f32(cur_output + index, vout); } #endif for (; index < area; index++) { cur_output[index] += (cur_input0[index] + cur_input1[index]) * mul; } } } static bool GetTransposeParameter(TransposeParameter *param, const int in_shape[], int in_shape_len, const int out_shape[], int out_shape_len, const int perm[], int perm_len) { param->num_axes_ = perm_len; size_t shape_size = 1; for (int i = 0; i < perm_len; i++) { param->perm_[i] = perm[i]; shape_size *= perm[i]; // check overflow } param->data_num_ = (int)shape_size; // check overflow param->strides_[param->num_axes_ - 1] = 1; param->out_strides_[param->num_axes_ - 1] = 1; if (param->num_axes_ - 1 >= in_shape_len) { return false; } if (param->num_axes_ - 1 >= out_shape_len) { return false; } for (int i = param->num_axes_ - 2; i >= 0; i--) { param->strides_[i] = in_shape[i + 1] * param->strides_[i + 1]; param->out_strides_[i] = out_shape[i + 1] * param->out_strides_[i + 1]; } return true; } void QWithPosition(RelativePositionAttentionParameter *param, Matrix *q_mat, const Matrix *wq_mat, Matrix *bq_mat, Matrix *q2wq_mat, Matrix *pu_mat, Matrix *pv_mat, Matrix *q2wq_with_pos_mat, Matrix *q2wq_with_pu_trans_mat, Matrix *q2wq_with_pv_trans_mat) { int num_heads = param->num_heads_; int d_model = param->d_model_; int batch = param->batch_; int depth = d_model / num_heads; // Q * WQ int q_area = q_mat->packed_row_ * q_mat->packed_col_; int wq_area = wq_mat->packed_row_ * wq_mat->packed_col_; int q2wq_area = q2wq_mat->row_ * q2wq_mat->col_ * q2wq_mat->batch_ / param->batch_; float *q2wq_data = q2wq_mat->data_; memset(q2wq_data, 0, param->batch_ * q2wq_area * sizeof(float)); for (int i = 0; i < param->batch_; i++) { float *cur_q = q_mat->packed_data_ + i * q_area; float *cur_wq = wq_mat->packed_data_ + i * wq_area; float *cur_q2wq = q2wq_data + i * q2wq_area; MatMulOpt(cur_q, cur_wq, cur_q2wq, bq_mat->packed_data_, ActType_No, q_mat->col_, q_mat->row_, wq_mat->col_, wq_mat->col_, OutType_Nhwc); } // transpose param init TransposeParameter q_with_pos_trans_param; int q_with_pos_trans_in_shape[] = {batch, param->q_seq_, num_heads, depth}; int q_with_pos_trans_out_shape[] = {batch, num_heads, param->q_seq_, depth}; int q_with_pos_perm[] = {0, 2, 1, 3}; (void)GetTransposeParameter(&q_with_pos_trans_param, q_with_pos_trans_in_shape, 4, q_with_pos_trans_out_shape, 4, q_with_pos_perm, 4); int q2wq_reshaped_area = q2wq_mat->row_ * q2wq_mat->col_; // Q_WQ + POS_U { float *q_with_pu = q2wq_with_pos_mat->data_; int q_with_pu_area = q2wq_with_pos_mat->row_ * q2wq_with_pos_mat->col_; memset(q_with_pu, 0, q2wq_with_pos_mat->batch_ * q_with_pu_area * sizeof(float)); for (int i = 0; i < q2wq_with_pos_mat->batch_; i++) { float *cur_qw = q2wq_data + i * q2wq_reshaped_area; float *cur_q_with_pu = q_with_pu + i * q_with_pu_area; ElementAdd(cur_qw, pu_mat->packed_data_, cur_q_with_pu, q_with_pu_area); } // Q_WITH_U perm [0,2,1,3] float *q_with_pu_trans = q2wq_with_pu_trans_mat->data_; size_t q_with_pu_trans_data_size = q2wq_with_pu_trans_mat->batch_ * q2wq_with_pu_trans_mat->row_ * q2wq_with_pu_trans_mat->col_ * sizeof(float); memset(q_with_pu_trans, 0, q_with_pu_trans_data_size); TransposeDimsFp32(q_with_pu, q_with_pu_trans, q_with_pos_trans_out_shape, &q_with_pos_trans_param, 0, 1); } // Q_WQ + POS_V { float *q_with_pv = q2wq_with_pos_mat->data_; int q_with_pv_area = q2wq_with_pos_mat->row_ * q2wq_with_pos_mat->col_; memset(q_with_pv, 0, q2wq_with_pos_mat->batch_ * q_with_pv_area * sizeof(float)); for (int i = 0; i < q2wq_with_pos_mat->batch_; i++) { float *cur_qw = q2wq_data + i * q2wq_reshaped_area; float *cur_q_with_pv = q_with_pv + i * q_with_pv_area; ElementAdd(cur_qw, pv_mat->packed_data_, cur_q_with_pv, q_with_pv_area); } // Q_WITH_V perm [0,2,1,3] float *q_with_pv_trans = q2wq_with_pv_trans_mat->data_; size_t q_with_pv_trans_data_size = q2wq_with_pv_trans_mat->batch_ * q2wq_with_pv_trans_mat->row_ * q2wq_with_pv_trans_mat->col_ * sizeof(float); memset(q_with_pv_trans, 0, q_with_pv_trans_data_size); TransposeDimsFp32(q_with_pv, q_with_pv_trans, q_with_pos_trans_out_shape, &q_with_pos_trans_param, 0, 1); } } void KMulWeightK(RelativePositionAttentionParameter *param, Matrix *k_mat, const Matrix *wk_mat, Matrix *bk_mat, Matrix *k2wk_mat, Matrix *k2wk_trans_mat) { int num_heads = param->num_heads_; int d_model = param->d_model_; int batch = param->batch_; int depth = d_model / num_heads; // K * WK int k_area = k_mat->packed_row_ * k_mat->packed_col_; int wk_area = wk_mat->packed_row_ * wk_mat->packed_col_; int k2wk_area = k2wk_mat->row_ * k2wk_mat->col_ * k2wk_mat->batch_ / param->batch_; float *k2wk = k2wk_mat->data_; memset(k2wk, 0, param->batch_ * k2wk_area * sizeof(float)); for (int i = 0; i < param->batch_; i++) { float *cur_k = k_mat->packed_data_ + i * k_area; float *cur_wk = wk_mat->packed_data_ + i * wk_area; float *cur_k2wk = k2wk + i * k2wk_area; MatMulOpt(cur_k, cur_wk, cur_k2wk, bk_mat->packed_data_, ActType_No, k_mat->col_, k_mat->row_, wk_mat->col_, wk_mat->col_, OutType_Nhwc); } // K * WK perm [0,2,3,1] float *k2wk_trans_data = k2wk_trans_mat->data_; int k2wk_trans_area = k2wk_trans_mat->row_ * k2wk_trans_mat->col_; memset(k2wk_trans_data, 0, k2wk_trans_mat->batch_ * k2wk_trans_area * sizeof(float)); TransposeParameter k2wk_trans_param; int k2wk_in_shape[] = {batch, param->k_seq_, num_heads, depth}; int k2wk_out_shape[] = {batch, num_heads, depth, param->k_seq_}; int k2wk_perm[] = {0, 2, 3, 1}; (void)GetTransposeParameter(&k2wk_trans_param, k2wk_in_shape, 4, k2wk_out_shape, 4, k2wk_perm, 4); TransposeDimsFp32(k2wk, k2wk_trans_data, k2wk_out_shape, &k2wk_trans_param, 0, 1); } void VMulWeightV(RelativePositionAttentionParameter *param, Matrix *v_mat, const Matrix *wv_mat, Matrix *bv_mat, Matrix *v2wv_mat, Matrix *v2wv_trans_mat) { int num_heads = param->num_heads_; int d_model = param->d_model_; int batch = param->batch_; int depth = d_model / num_heads; // V * WV int v_area = v_mat->packed_row_ * v_mat->packed_col_; int wv_area = wv_mat->packed_row_ * wv_mat->packed_col_; int v2wv_area = v2wv_mat->row_ * v2wv_mat->col_ * v2wv_mat->batch_ / param->batch_; float *v2wv = v2wv_mat->data_; memset(v2wv, 0, param->batch_ * v2wv_area * sizeof(float)); for (int i = 0; i < param->batch_; i++) { float *cur_v = v_mat->packed_data_ + i * v_area; float *cur_wv = wv_mat->packed_data_ + i * wv_area; float *cur_v2wv = v2wv + i * v2wv_area; MatMulOpt(cur_v, cur_wv, cur_v2wv, bv_mat->packed_data_, ActType_No, v_mat->col_, v_mat->row_, wv_mat->col_, wv_mat->col_, OutType_Nhwc); } // V * WV perm [0,2,1,3] float *v2wv_trans_data = v2wv_trans_mat->data_; int v2wv_trans_area = v2wv_trans_mat->row_ * v2wv_trans_mat->col_; memset(v2wv_trans_data, 0, v2wv_trans_mat->batch_ * v2wv_trans_area * sizeof(float)); TransposeParameter v2wv_trans_param; int v2wv_in_shape[] = {batch, param->v_seq_, num_heads, depth}; int v2wv_out_shape[] = {batch, num_heads, param->v_seq_, depth}; int v2wv_perm[] = {0, 2, 1, 3}; (void)GetTransposeParameter(&v2wv_trans_param, v2wv_in_shape, 4, v2wv_out_shape, 4, v2wv_perm, 4); TransposeDimsFp32(v2wv, v2wv_trans_data, v2wv_out_shape, &v2wv_trans_param, 0, 1); } void PMulWeightP(RelativePositionAttentionParameter *param, Matrix *p_mat, const Matrix *wp_mat, Matrix *p2wp_mat, Matrix *p2wp_trans_mat) { int num_heads = param->num_heads_; int d_model = param->d_model_; int batch = param->batch_; int depth = d_model / num_heads; // P * WP int p_area = p_mat->packed_row_ * p_mat->packed_col_; int wp_area = wp_mat->packed_row_ * wp_mat->packed_col_; int p2wp_area = p2wp_mat->row_ * p2wp_mat->col_ * p2wp_mat->batch_ / param->batch_; float *p2wp_data = p2wp_mat->data_; memset(p2wp_data, 0, param->batch_ * p2wp_area * sizeof(float)); for (int i = 0; i < param->batch_; i++) { float *cur_p = p_mat->packed_data_ + i * p_area; float *cur_wp = wp_mat->packed_data_ + i * wp_area; float *cur_p2wp = p2wp_data + i * p2wp_area; MatMulOpt(cur_p, cur_wp, cur_p2wp, NULL, ActType_No, p_mat->col_, p_mat->row_, wp_mat->col_, wp_mat->col_, OutType_Nhwc); } // P * WP perm [0,2,3,1] float *p2wp_trans_data = p2wp_trans_mat->data_; int p2wp_trans_area = p2wp_trans_mat->row_ * p2wp_trans_mat->col_; memset(p2wp_trans_data, 0, p2wp_trans_mat->batch_ * p2wp_trans_area * sizeof(float)); TransposeParameter p2wp_trans_param; int p2wp_in_shape[] = {batch, param->p_seq_, num_heads, depth}; int p2wp_out_shape[] = {batch, num_heads, depth, param->p_seq_}; int p2wp_perm[] = {0, 2, 3, 1}; (void)GetTransposeParameter(&p2wp_trans_param, p2wp_in_shape, 4, p2wp_out_shape, 4, p2wp_perm, 4); TransposeDimsFp32(p2wp_data, p2wp_trans_data, p2wp_out_shape, &p2wp_trans_param, 0, 1); } void CalculateLogits(RelativePositionAttentionParameter *param, Matrix *q2wq_with_pu_trans_mat, Matrix *q2wq_with_pv_trans_mat, Matrix *k2wk_trans_mat, Matrix *p2wp_trans_mat, Matrix *logits_with_u_mat, Matrix *logits_with_v_mat, Matrix *logits_with_v_pad_mat, Matrix *logits_with_v_shifted_mat, Matrix *logits_mat) { int num_heads = param->num_heads_; int d_model = param->d_model_; int depth = d_model / num_heads; // pack Q_WITH_U as left_matrix // since we malloc dst data, pack function can not be failed (void)PackLeftMatrix(q2wq_with_pu_trans_mat, param->row_tile_); // pack Q_WITH_V as left_matrix (void)PackLeftMatrix(q2wq_with_pv_trans_mat, param->row_tile_); // pack K * WK as right_matrix (void)PackRightMatrix(k2wk_trans_mat, param->col_tile_); // pack P * WP as right_matrix (void)PackRightMatrix(p2wp_trans_mat, param->col_tile_); // q_with_pu * k = logits_with_u MatMulOpt(q2wq_with_pu_trans_mat->packed_data_, k2wk_trans_mat->packed_data_, logits_with_u_mat->data_, NULL, ActType_No, q2wq_with_pu_trans_mat->col_, logits_with_u_mat->row_, logits_with_u_mat->col_, logits_with_u_mat->col_, OutType_Nhwc); // q_with_pv * p = logits_with_v MatMulOpt(q2wq_with_pv_trans_mat->packed_data_, p2wp_trans_mat->packed_data_, logits_with_v_mat->data_, NULL, ActType_No, q2wq_with_pv_trans_mat->col_, logits_with_v_mat->row_, logits_with_v_mat->col_, logits_with_v_mat->col_, OutType_Nhwc); // relative shift logits_with_v float *pad_buf = logits_with_v_pad_mat->data_; float *logits_with_v_shifted_data = logits_with_v_shifted_mat->data_; RelativeShift(logits_with_v_mat, pad_buf, logits_with_v_shifted_data); // logits = (logits_with_u + logits_with_v) / sqrt(depth) float *logits_buffer = logits_mat->data_; ElementOptAddDiv(logits_with_u_mat->data_, logits_with_v_shifted_data, 1 / sqrt(depth), logits_buffer, logits_with_u_mat->batch_, logits_with_u_mat->row_ * logits_with_u_mat->col_); } void RelPosAttention(RelativePositionAttentionParameter *param, Matrix *logits_mat, Matrix *softmax_mat, Matrix *v2wv_trans_mat, Matrix *logits2v_mat, Matrix *logits2v_trans_mat, const Matrix *wo_mat, Matrix *bo_mat, Matrix *output_mat) { int num_heads = param->num_heads_; int d_model = param->d_model_; int batch = param->batch_; int depth = d_model / num_heads; float *logits_buffer = logits_mat->data_; // softmax(logits) SoftmaxLastAxis(logits_buffer, softmax_mat->data_, batch * num_heads * softmax_mat->row_, softmax_mat->col_); // logits * v (void)PackLeftMatrix(softmax_mat, param->row_tile_); (void)PackRightMatrix(v2wv_trans_mat, param->col_tile_); int softmax_logits_area = softmax_mat->packed_row_ * softmax_mat->packed_col_; int v2wv_area = v2wv_trans_mat->packed_row_ * v2wv_trans_mat->packed_col_; int logits2v_area = logits2v_mat->row_ * logits2v_mat->col_; float *logits2v_data = logits2v_mat->data_; memset(logits2v_data, 0, logits2v_mat->batch_ * logits2v_area * sizeof(float)); for (int i = 0; i < logits2v_mat->batch_; i++) { float *cur_logits = softmax_mat->packed_data_ + i * softmax_logits_area; float *cur_v2wv = v2wv_trans_mat->packed_data_ + i * v2wv_area; float *cur_logits2v = logits2v_data + i * logits2v_area; MatMulOpt(cur_logits, cur_v2wv, cur_logits2v, NULL, ActType_No, softmax_mat->col_, softmax_mat->row_, v2wv_trans_mat->col_, v2wv_trans_mat->col_, OutType_Nhwc); } // multi_head output perm [0,2,1,3] float *logits2v_trans_data = logits2v_trans_mat->data_; int logits2v_trans_area = logits2v_trans_mat->row_ * logits2v_trans_mat->col_; memset(logits2v_trans_data, 0, logits2v_trans_mat->batch_ * logits2v_trans_area * sizeof(float)); TransposeParameter logits2v_trans_param; int logits2v_trans_in_shape[] = {batch, num_heads, param->q_seq_, depth}; int logits2v_trans_out_shape[] = {batch, param->q_seq_, num_heads, depth}; int logits2v_trans_perm[] = {0, 2, 1, 3}; (void)GetTransposeParameter(&logits2v_trans_param, logits2v_trans_in_shape, 4, logits2v_trans_out_shape, 4, logits2v_trans_perm, 4); TransposeDimsFp32(logits2v_data, logits2v_trans_data, logits2v_trans_out_shape, &logits2v_trans_param, 0, 1); // concat = reshape [batch, -1, d_model] logits2v_trans_mat->batch_ = batch; logits2v_trans_mat->row_ = param->q_seq_; logits2v_trans_mat->col_ = param->d_model_; // * o (void)PackLeftMatrix(logits2v_trans_mat, param->row_tile_); int concat_out_area = logits2v_trans_mat->packed_row_ * logits2v_trans_mat->packed_col_; int wo_area = wo_mat->packed_row_ * wo_mat->packed_col_; int output_area = output_mat->row_ * output_mat->col_; for (int i = 0; i < output_mat->batch_; i++) { float *cur_concat_out = logits2v_trans_mat->packed_data_ + i * concat_out_area; float *cur_wo = wo_mat->packed_data_ + i * wo_area; float *cur_output = output_mat->data_ + i * output_area; MatMulOpt(cur_concat_out, cur_wo, cur_output, bo_mat->packed_data_, ActType_No, logits2v_trans_mat->col_, logits2v_trans_mat->row_, wo_mat->col_, wo_mat->col_, OutType_Nhwc); } } ======================= File: mindspore/ccsrc/minddata/dataset/util/arena.h ======================= <reponame>PowerOlive/mindspore /** * Copyright 2019 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. */ #ifndef MINDSPORE_CCSRC_MINDDATA_DATASET_UTIL_ARENA_H_ #define MINDSPORE_CCSRC_MINDDATA_DATASET_UTIL_ARENA_H_ #include <memory> #include <mutex> #include <utility> #include "minddata/dataset/util/allocator.h" #include "minddata/dataset/util/memory_pool.h" #include "minddata/dataset/util/treap.h" #ifdef ENABLE_GPUQUE #include <cuda_runtime_api.h> #endif #define ARENA_LOG_BLK_SZ (6u) #define ARENA_BLK_SZ (static_cast<uint16_t>(1u << ARENA_LOG_BLK_SZ)) #define ARENA_WALL_OVERHEAD_SZ 32 namespace mindspore { namespace dataset { /// This is a memory arena based on a treap data structure. /// The constructor of the Arena takes the size of the initial memory size (in MB). /// Internally we divide the memory into multiple blocks. Each block is 64 bytes. /// The treap contains all the free blocks with the relative memory address as key /// and the size of the block as priority. /// /// Initially the treap has only one root which is the whole memory piece. /// /// For memory suballocation, we pop the root node of the treap which contains the largest free block. /// We allocate what we need and return the rest back to the treap. We search for the first fit instead /// of the best fit so to give us a constant time in memory allocation. /// /// When a block of memory is freed. It is joined with the blocks before and after (if they are available) to /// form a bigger block. /// At the lowest level, we don't really care where the memory is coming from. /// This allows other class to make use of Arena method and override the origin of the /// memory, say from some unix shared memory instead. /// \note Implementation class is not thread safe. Caller needs to ensure proper serialization class ArenaImpl { public: /// Constructor /// \param ptr The start of the memory address /// \param sz Size of the memory block we manage ArenaImpl(void *ptr, size_t sz); ~ArenaImpl() { ptr_ = nullptr; } /// \brief Allocate a sub block /// \param n Size requested /// \param p pointer to where the result is stored /// \return Status object. Status Allocate(size_t n, void **p); /// \brief Enlarge or shrink a sub block /// \param old_sz Original size /// \param new_sz New size /// \return Status object Status Reallocate(void **, size_t old_sz, size_t new_sz); /// \brief Free a sub block /// \param Address of the block to be freed. void Deallocate(void *); /// \brief Calculate % free of the memory /// \return Percent free int PercentFree() const; /// \brief What is the maximum we can support in allocate. /// \return Max value uint64_t get_max_size() const { return (size_in_bytes_ - ARENA_WALL_OVERHEAD_SZ); } /// \brief Get the start of the address. Read only /// \return Start of the address block const void *get_base_addr() const { return ptr_; } static uint64_t SizeToBlk(uint64_t sz); friend std::ostream &operator<<(std::ostream &os, const ArenaImpl &s); private: size_t size_in_bytes_; Treap<uint64_t, uint64_t> tr_; void *ptr_; void *get_user_addr(void *base_addr) const { return reinterpret_cast<char *>(base_addr) + ARENA_WALL_OVERHEAD_SZ; } void *get_base_addr(void *user_addr) const { return reinterpret_cast<char *>(user_addr) - ARENA_WALL_OVERHEAD_SZ; } std::pair<std::pair<uint64_t, uint64_t>, bool> FindPrevBlk(uint64_t addr); bool BlockEnlarge(uint64_t *addr, uint64_t old_sz, uint64_t new_sz); Status FreeAndAlloc(void **pp, size_t old_sz, size_t new_sz); }; /// \brief This version of Arena allocates from private memory class Arena : public MemoryPool { public: // Disable copy and assignment constructor Arena(const Arena &) = delete; Arena &operator=(const Arena &) = delete; ~Arena() override { #ifdef ENABLE_GPUQUE if (is_cuda_malloc_) { if (ptr_!= nullptr) { (void)cudaFreeHost(ptr_); } } #else if (ptr_!= nullptr) { free(ptr_); } ptr_ = nullptr; #endif } /// As a derived class of MemoryPool, we have to implement the following. /// But we simply transfer the call to the implementation class Status Allocate(size_t size, void **pVoid) override { std::unique_lock<std::mutex> lock(mux_); return impl_->Allocate(size, pVoid); } Status Reallocate(void **pVoid, size_t old_sz, size_t new_sz) override { std::unique_lock<std::mutex> lock(mux_); return impl_->Reallocate(pVoid, old_sz, new_sz); } void Deallocate(void *pVoid) override { std::unique_lock<std::mutex> lock(mux_); impl_->Deallocate(pVoid); } uint64_t get_max_size() const override { return impl_->get_max_size(); } int PercentFree() const override { std::unique_lock<std::mutex> lock(mux_); return impl_->PercentFree(); } /// \return Return the start of the memory block const void *get_base_addr() const { return impl_->get_base_addr(); } /// \brief Dump the memory allocation block. friend std::ostream &operator<<(std::ostream &os, const Arena &s) { os << *(s.impl_); return os; } #ifdef ENABLE_GPUQUE /// The only method to create an arena. static Status CreateArena(std::shared_ptr<Arena> *p_ba, size_t val_in_MB = 4096, bool is_cuda_malloc = false); #else /// The only method to create an arena. static Status CreateArena(std::shared_ptr<Arena> *p_ba, size_t val_in_MB = 4096); #endif protected: mutable std::mutex mux_; std::unique_ptr<ArenaImpl> impl_; void *ptr_; size_t size_in_MB_; #ifdef ENABLE_GPUQUE bool is_cuda_malloc_; explicit Arena(size_t val_in_MB = 4096, bool is_cuda_malloc = false); #else explicit Arena(size_t val_in_MB = 4096); #endif Status Init(); }; } // namespace dataset } // namespace mindspore #endif // MINDSPORE_CCSRC_MINDDATA_DATASET_UTIL_ARENA_H_ ======================= File: mindspore/ccsrc/backend/optimizer/mem_reuse/mem_swap_manager.h ======================= /** * Copyright 2020-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. */ #ifndef MINDSPORE_CCSRC_BACKEND_OPTIMIZER_MEM_REUSE_MEM_SWAP_MANAGER_H_ #define MINDSPORE_CCSRC_BACKEND_OPTIMIZER_MEM_REUSE_MEM_SWAP_MANAGER_H_ #include <map> #include <memory> #include <vector> #include <utility> #include "utils/hash_map.h" #include "utils/hash_set.h" #include "backend/optimizer/mem_reuse/mem_copy_manager.h" using PerformPair = std::pair<float, float>; namespace mindspore { namespace device { namespace memswap { class MemSwapManager { public: explicit MemSwapManager(const MemCopyManagerPtr &mem_copy_manager) : tensor_size_threshold_(0), tensor_size_threshold_idx_(0), tensor_size_num_(1), distance_threshold_(1), distance_decay_step_(1), retreat_count_(0) { mem_copy_manager_ = mem_copy_manager; } MemSwapManager(const MemSwapManager &) = delete; MemSwapManager &operator=(const MemSwapManager &) = delete; ~MemSwapManager() = default; bool Init(const mindspore::session::KernelGraph *kernel_graph); void AddMemSwapTask(SwapKind swap_kind, const DeviceAddressPtr &device_address, const HostAddress &host_address, bool mock, bool profiling = false, float *cost_time = nullptr) const; bool SyncMemCopyStream(SwapKind swap_kind) const; DeviceAddressPtr UpdateSwapQueue(SwapKind swap_kind, bool mock) const; bool RetreatSwapInfo(); void AdjustSwapInPos(const AnfNodePtr &kernel, size_t index); bool trigger_swap() const { return trigger_swap_; } bool mem_swap_init() const { return mem_swap_initialized_; } void AddKernelExecutionPerform(const AnfNodePtr &kernel, float perform); float QueryKernelExecutionPerform(const AnfNodePtr &kernel) const; void AddKernelSwapPerform(const AnfNodePtr &kernel, size_t output_idx, const PerformPair &perform); const PerformPair &QueryKernelSwapPerform(const AnfNodePtr &kernel, size_t output_idx) const; bool QueryKernelTriggerSwap(const AnfNodePtr &kernel) const; bool QueryKernelTriggerSwapIn(const AnfNodePtr &kernel) const; size_t QueryKernelTriggerSwapInTaskNum(const AnfNodePtr &kernel) const; const AnfNodePtr QueryKernelByTopoOrder(size_t index) const; size_t QueryKernelTopoOrder(const AnfNodePtr &kernel) const; const MemSwapInfoSet &QueryKernelMemSwapInfo(const AnfNodePtr &kernel) const; void AssignHostMemory(); const HostAddress &QueryKernelHostAddr(const AnfNodePtr &kernel, size_t output_idx) const; void AddKernelHostAddrIsDirty(const AnfNodePtr &kernel, size_t output_idx, bool dirty); bool QueryKernelHostAddrIsDirty(const AnfNodePtr &kernel, size_t output_idx) const; void ResetHostAddrIsDirty(); bool AllocHostPinnedMem(size_t size, void **addr) const; void ReleaseHostPinnedMem(); void ClearSwapQueue(bool mock) const; void DumpSwapInfo() const; void DumpUserNodes() const; private: KernelExecutionInfo &SearchKernelExecutionInfo(const AnfNodePtr &kernel) const; void AddSwapInfo(); void ResetSwapInfo(); void SaveUserKernelTopoOrder(); bool InitSwapThreshold(size_t swap_mem_size); void RetreatSwapThreshold(); void CacheCurSwapInfoSet(const AnfNodePtr &kernel); void AddFirstTimeMovePos(const AnfNodePtr &kernel, size_t index, bool first_time); bool QueryFirstTimeMovePos(const AnfNodePtr &kernel, size_t index) const; size_t BestSwapInPerformPos(const AnfNodePtr &trigger_kernel, const MemSwapInfo &mem_swap_info) const; void MoveSwapInfoPos(size_t des_pos, size_t src_pos, const MemSwapInfo &mem_swap_info); void AddKernelMemSwapInfo(const AnfNodePtr &kernel, const MemSwapInfo &mem_swap_info); void RemoveKernelMemSwapInfo(const AnfNodePtr &kernel, const MemSwapInfo &mem_swap_info); bool CheckDistanceBetweenKernels(const TensorInfo &tensor_info) const; std::vector<std::pair<size_t, size_t>> CheckDistanceBetweenKernelsWithIdx(const TensorInfo &tensor_info) const; bool IsCommunicationRelevantOp(const AnfNodePtr &kernel) const; bool IsInplaceRelevantOp(const TensorInfo &tensor); std::vector<CNodePtr> execution_order_; std::vector<TensorInfo> ordered_tensors_; mindspore::HashMap<void *, KernelExecutionInfo> kernel_execution_info_; mindspore::HashMap<void *, std::map<size_t, PerformPair>> kernel_swap_perform_; // Key: trigger swap kernel, value: MemSwapInfoSet of kernel need to be swapped mindspore::HashMap<void *, MemSwapInfoSet> mem_swap_info_map_; std::vector<HostAddress> host_addrs_list_; // Key: cache kernel address, value: lists of first time move pos or not std::map<void *, std::vector<bool>> kernel_first_move_cache_map_; std::vector<MemSwapInfo> mem_swap_info_cache_list_; std::pair<size_t, size_t> best_and_cur_pos_cache_; size_t tensor_size_threshold_; size_t tensor_size_threshold_idx_; size_t tensor_size_num_; size_t distance_threshold_; size_t distance_decay_step_; size_t retreat_count_; MemCopyManagerPtr mem_copy_manager_{nullptr}; const mindspore::session::KernelGraph *kernel_graph_{nullptr}; bool mem_swap_initialized_{false}; bool swap_info_already_set_{false}; bool trigger_swap_{false}; static constexpr size_t kDistanceInitFactor = 3; static constexpr size_t kDistanceLowerBound = 3; // The upper bound of count for searching memory swap scheme recurrently. static constexpr size_t kRetreatCountMax = 50; }; using MemSwapManagerPtr = std::shared_ptr<MemSwapManager>; } // namespace memswap } // namespace device } // namespace mindspore #endif // MINDSPORE_CCSRC_BACKEND_OPTIMIZER_MEM_REUSE_MEM_SWAP_MANAGER_H_ ======================= File: mindspore/ccsrc/backend/optimizer/somas/somas.h ======================= <reponame>PowerOlive/mindspore<gh_stars>0 /** * Copyright 2020-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. */ #ifndef MINDSPORE_CCSRC_BACKEND_OPTIMIZER_SOMAS_SOMAS_H_ #define MINDSPORE_CCSRC_BACKEND_OPTIMIZER_SOMAS_SOMAS_H_ #include <map> #include <memory> #include <string> #include <utility> #include <vector> #include "utils/hash_map.h" #include "utils/hash_set.h" #include "backend/kernel_compiler/tbe/tbe_utils.h" #include "backend/optimizer/somas/somas_node.h" #include "backend/optimizer/somas/somas_solver_pre.h" #include "backend/optimizer/somas/somas_stream.h" #include "backend/optimizer/somas/somas_parameter.h" #include "backend/session/anf_runtime_algorithm.h" #include "backend/session/kernel_graph.h" namespace mindspore { namespace somas { class Somas { public: // Constructors/Destructors Somas() = default; Somas(const Somas &) = delete; Somas &operator=(const Somas &) = delete; ~Somas() = default; bool Allocate(const session::KernelGraph *graph); size_t GetTotalMemSize() { return mem_offset_; } void set_mem_base_addr(uint8_t *mem_base_addr) { mem_base_addr_ = mem_base_addr; } uint8_t *GetNodeOutputPtr(const AnfNodePtr &node, size_t index) const; uint8_t *GetNodeWorkSpacePtr(const AnfNodePtr &node, size_t index) const; std::string SomasInfo(bool calc_hash = false) const; std::string SomasMemory() const; void DumpSomasInfoIR(const string filename) const; void DumpSomasMemoryIR(const string &filename) const; static bool NodeSort(const SomasNodePtr &node1, const SomasNodePtr &node2); #ifndef ENABLE_SECURITY void ConvertToProfilingNode(uint32_t graph_id); #endif private: std::vector<DynamicBitSet> reuse_matrix_; // hash id std::string hash_id_; // Maps mindspore::HashMap<size_t, SomasTensorPtr> tensors_map_; std::map<void *, std::vector<SomasNodePtr>> nodes_map_; std::map<void *, vector<SomasParameterPtr>> parameters_map_; // Vectors std::vector<SomasNodePtr> nodes_list_; std::vector<SomasStreamPtr> streams_list_; std::vector<SomasTensorPtr> tensors_list_; std::vector<SomasParameterPtr> parameters_list_; // Stream groups std::vector<vector<uint32_t>> streams_groups_; // event info map std::map<size_t, std::pair<CNodePtr, CNodePtr>> event_map_; // Solver TensorsDescMap solver_tensor_desc_map_; SomasSolverPrePtr somas_solver_; // Contiguous list std::vector<vector<size_t>> contiguous_tensors_list_; // Ref lists std::vector<vector<size_t>> ref_node_constraints_; std::vector<vector<size_t>> ref_overlap_constraints_; // total Offset size_t mem_offset_{0}; // Memory base addr uint8_t *mem_base_addr_{nullptr}; // Save debug info bool save_graphs_{false}; std::string save_graphs_path_; // statistic info size_t upper_bound_{0}; size_t lower_bound_{0}; size_t workspace_total_size_{0}; size_t comm_input_total_size_{0}; size_t comm_output_total_size_{0}; size_t lifelong_all_total_size_{0}; size_t lifelong_start_total_size_{0}; size_t lifelong_end_total_size_{0}; bool InitSomasTensors(const session::KernelGraph *graph); void InitBasicInfo(const session::KernelGraph *graph); void InitSomasStreamAndNode(const session::KernelGraph *graph); void InitSomasOutputAndWorkspaceTensors(const session::KernelGraph *graph); void InitSomasInputTensors(const session::KernelGraph *graph); void InitSomasEventInfos(); void GetNextOutputProcess(const session::KernelGraph *graph); void IndependentNodeOutputProcess(const session::KernelGraph *graph); #ifndef ENABLE_SECURITY void SummaryInputProcess(const session::KernelGraph *graph); #endif void RefNodeProcess(const session::KernelGraph *graph); void NonTaskSplitProcess(const session::KernelGraph *graph); void UnReuseNodeProcess(const session::KernelGraph *graph); SomasTensorPtr CreateGapTensor(size_t gap_tensor_id); void GenContiguousList(const session::KernelGraph *graph); void ComputeConflictPairs(); bool Assign(const session::KernelGraph *graph); std::string Offline() const; void DumpOfflineIR(const string filename) const; std::string GetSplitName(const string &scope_name) const; size_t CalcLowerBound() const; void GenGraphStatisticInfo(); SomasParameterPtr GetSomasParameter(const AnfNodePtr &node, size_t index); SomasParameterPtr CreateSomasParameter(const AnfNodePtr &node, size_t index); void InitCommonNodeInputs(bool is_all_nop_node, const CNodePtr &kernel); void InitAtomicCleanInputs(bool is_all_nop_node, const CNodePtr &kernel); void ComputeOneTensorConflicts(const std::shared_ptr<SomasTensor> &calc_tensor, const std::vector<SomasTensorPtr> &all_tensors_list, const vector<DynamicBitSet> &nodes_dependency, std::vector<DynamicBitSet> *tensor_relation) const; void ComputeMultiTensorConflicts(const std::vector<SomasTensorPtr> &calc_tensors_list, const std::vector<SomasTensorPtr> &all_tensors_list, const vector<DynamicBitSet> &nodes_dependency, std::vector<DynamicBitSet> *tensor_relation) const; void UpdateTensorDestinations(); void UpdateRefTensorsConflict(); void UpdateRefOverlapTensorsConflicts(); void UpdateRefTensorsOffset(); void UpdateContiguousTensorsOffset(const std::map<size_t, size_t> &contiguous_ref_list_map); void DumpParameters(std::ostringstream &oss) const; void DumpTensors(std::ostringstream &oss) const; void DumpNodes(std::ostringstream &oss) const; std::map<size_t, size_t> GetContiguousListContainRefTensor(); std::map<size_t, size_t> GetRefTensorsInContiguousList(); bool SaveSomasResult(const session::KernelGraph *graph); bool VerifySomasResult(const session::KernelGraph *graph, const nlohmann::json &somas_json) const; bool LoadSomasResult(const session::KernelGraph *graph, const string &filename); bool UpdateTensorsOffset(const std::vector<nlohmann::json> &tensors_json); bool CalcSomasModelHash(const session::KernelGraph *graph); void UpdateInputTensor(SomasNodePtr node, SomasNodePtr pre_somas_node, SomasTensorPtr input_somas_tensor) const; bool LoadSomasCache(const session::KernelGraph *graph); }; using SomasPtr = std::shared_ptr<Somas>; } // namespace somas } // namespace mindspore #endif // MINDSPORE_CCSRC_BACKEND_OPTIMIZER_SOMAS_SOMAS_H_ ======================= File: mindspore/ccsrc/pipeline/jit/parse/parse_dynamic.h ======================= <reponame>PowerOlive/mindspore<filename>mindspore/ccsrc/pipeline/jit/parse/parse_dynamic.h<gh_stars>1000+ /** * This is the C++ adaptation and derivative work of Myia (https://github.com/mila-iqia/myia/). * * 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. */ #ifndef MINDSPORE_CCSRC_PIPELINE_JIT_PARSE_PARSE_DYNAMIC_H_ #define MINDSPORE_CCSRC_PIPELINE_JIT_PARSE_PARSE_DYNAMIC_H_ #include <vector> #include <memory> #include <string> #include "pipeline/jit/parse/parse.h" namespace mindspore::parse { class DynamicParser { public: DynamicParser() = default; ~DynamicParser() = default; // Check cell struct static bool IsDynamicCell(const py::object &cell); private: static std::string GetCellInfo(const py::object &cell); static void ParseInputArgs(const std::shared_ptr<parse::ParseFunctionAst> &ast, const py::object &fn_node); static bool ParseBodyContext(const std::shared_ptr<parse::ParseFunctionAst> &ast, const py::object &fn_node, const std::vector<std::string> &compare_prim = {}); static bool ParseIfWhileExprNode(const std::shared_ptr<parse::ParseFunctionAst> &ast, const py::object &node); static bool ParseAssignExprNode(const std::shared_ptr<parse::ParseFunctionAst> &ast, const py::object &node); static bool ParseAugAssignExprNode(const std::shared_ptr<parse::ParseFunctionAst> &ast, const py::object &node, const std::vector<std::string> &compare_prim = {}); static bool ParseForExprNode(const std::shared_ptr<parse::ParseFunctionAst> &ast, const py::object &node); static std::string ParseNodeName(const std::shared_ptr<parse::ParseFunctionAst> &ast, const py::object &node, parse::AstMainType type); }; } // namespace mindspore::parse #endif ======================= File: mindspore/lite/tools/benchmark/benchmark_c_api.h ======================= <filename>mindspore/lite/tools/benchmark/benchmark_c_api.h /** * 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. */ #ifndef MINDSPORE_LITE_TOOLS_BENCHMARK_BENCHMARK_C_API_H_ #define MINDSPORE_LITE_TOOLS_BENCHMARK_BENCHMARK_C_API_H_ #include <vector> #include <string> #include "tools/benchmark/benchmark_base.h" #include "include/c_api/model_c.h" #include "include/c_api/context_c.h" #ifdef __cplusplus extern "C" { #endif bool TimeBeforeCallback(const MSTensorHandleArray inputs, const MSTensorHandleArray outputs, const MSCallBackParamC kernel_Info); bool TimeAfterCallback(const MSTensorHandleArray inputs, const MSTensorHandleArray outputs, const MSCallBackParamC kernel_Info); #ifdef __cplusplus } #endif using mindspore::lite::BenchmarkBase; using mindspore::lite::BenchmarkFlags; namespace mindspore::tools { class MS_API BenchmarkCApi : public BenchmarkBase { public: explicit BenchmarkCApi(BenchmarkFlags *flags) : BenchmarkBase(flags) {} virtual ~BenchmarkCApi() { MSModelDestroy(&model_); } int RunBenchmark() override; int LoadInput() override; protected: int CompareDataGetTotalBiasAndSize(const std::string &name, MSTensorHandle tensor, float *total_bias, int *total_size); int InitContext(); int GenerateInputData() override; int ReadInputFile() override; int GetDataTypeByTensorName(const std::string &tensor_name) override; int CompareOutput() override; int InitTimeProfilingCallbackParameter() override; int InitPerfProfilingCallbackParameter() override; int InitDumpTensorDataCallbackParameter() override; int InitPrintTensorDataCallbackParameter() override; int PrintInputData(); int MarkPerformance(); int MarkAccuracy(); private: MSModelHandle model_ = nullptr; MSContextHandle context_ = nullptr; MSTensorHandleArray inputs_; MSTensorHandleArray outputs_; MSKernelCallBackC before_call_back_ = nullptr; MSKernelCallBackC after_call_back_ = nullptr; }; } // namespace mindspore::tools #endif // MINDSPORE_LITE_TOOLS_BENCHMARK_BENCHMARK_C_API_H_ ======================= File: mindspore/ccsrc/minddata/dataset/text/char_n_gram.h ======================= /** * 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. */ #ifndef MINDSPORE_CCSRC_MINDDATA_DATASET_TEXT_CHAR_N_GRAM_H_ #define MINDSPORE_CCSRC_MINDDATA_DATASET_TEXT_CHAR_N_GRAM_H_ #include <algorithm> #include <functional> #include <memory> #include <string> #include <unordered_map> #include <utility> #include <vector> #include "minddata/dataset/text/vectors.h" namespace mindspore { namespace dataset { /// \brief Build CharNGram vectors from reading a Pre-train word vectors. class CharNGram : public Vectors { public: // Constructor. CharNGram() = default; /// Constructor. /// \param[in] map A map between string and vector. /// \param[in] dim Dimension of the vectors. CharNGram(const std::unordered_map<std::string, std::vector<float>> &map, int32_t dim); // Destructor. ~CharNGram() = default; /// \brief Build CharNGram from reading a CharNGram pre-train vector file. /// \param[out] char_n_gram CharNGram object which contains the pre-train vectors. /// \param[in] path Path to the CharNGram pre-trained word vector file. /// \param[in] max_vectors This can be used to limit the number of pre-trained vectors loaded (default=0, no limit). static Status BuildFromFile(std::shared_ptr<CharNGram> *char_n_gram, const std::string &path, int32_t max_vectors = 0); /// \brief Look up embedding vectors of token. /// \param[in] token A token to be looked up. /// \param[in] unk_init In case of the token is out-of-vectors (OOV), the result will be initialized with `unk_init`. /// (default={}, means to initialize with zero vectors). /// \param[in] lower_case_backup Whether to look up the token in the lower case (Default = false). /// \return The vector of the input token. std::vector<float> Lookup(const std::string &token, const std::vector<float> &unk_init = {}, bool lower_case_backup = false); }; } // namespace dataset } // namespace mindspore #endif // MINDSPORE_CCSRC_MINDDATA_DATASET_TEXT_CHAR_N_GRAM_H_ ======================= File: mindspore/lite/micro/coder/opcoders/nnacl/int8/batchnorm_int8_coder.h ======================= /** * 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. */ #ifndef MINDSPORE_LITE_MICRO_CODER_OPCODERS_NNACL_BATCHNORM_INT8_CODER_H_ #define MINDSPORE_LITE_MICRO_CODER_OPCODERS_NNACL_BATCHNORM_INT8_CODER_H_ #include <cstring> #include <vector> #include "coder/opcoders/op_coder.h" #include "nnacl/batchnorm_parameter.h" namespace mindspore::lite::micro::nnacl { class BatchNormInt8Coder final : public OperatorCoder { public: BatchNormInt8Coder(const std::vector<Tensor *> &in_tensors, const std::vector<Tensor *> &out_tensors, const Model::Node *node, size_t node_index, Target target) : OperatorCoder(in_tensors, out_tensors, node, node_index, target) { batchnorm_param_ = reinterpret_cast<BatchNormParameter *>(parameter_); } ~BatchNormInt8Coder() override = default; int Prepare(CoderContext *const context) override; int DoCode(CoderContext *context) override; private: int InitConstTensor(); int InitFusedConstTensor(); float *alpha_addr_{nullptr}; float *beta_addr_{nullptr}; BatchNormParameter *batchnorm_param_; }; } // namespace mindspore::lite::micro::nnacl #endif // MINDSPORE_LITE_MICRO_CODER_OPCODERS_NNACL_BATCHNORM_INT8_CODER_H_ ======================= File: mindspore/ccsrc/backend/kernel_compiler/aicpu/aicpu_ops/aicpu_sharder/aicpu_context.h ======================= <filename>mindspore/ccsrc/backend/kernel_compiler/aicpu/aicpu_ops/aicpu_sharder/aicpu_context.h<gh_stars>1-10 /** * 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. */ #ifndef AICPU_OPS_AICPU_CONTEXT_H_ #define AICPU_OPS_AICPU_CONTEXT_H_ #include <sys/types.h> #include <cstdint> #include <string> #include <map> #include <functional> #include "common/kernel_util.h" namespace aicpu { typedef struct { uint32_t device_id; // device id uint32_t tsId; // ts id pid_t host_pid; // host pid uint32_t vf_id; // vf id } aicpuContext_t; enum AicpuRunMode : uint32_t { PROCESS_PCIE_MODE = 0, // 1910/1980/1951 dc, with host mode PROCESS_SOCKET_MODE = 1, // MDC THREAD_MODE = 2, // ctrlcpu/minirc/lhisi INVALID_MODE, }; typedef struct { uint32_t stream_id; uint64_t task_id; } streamAndTaskId_t; typedef enum { AICPU_ERROR_NONE = 0, // success AICPU_ERROR_FAILED = 1, // failed } status_t; enum CtxType : int32_t { CTX_DEFAULT = 0, CTX_PROF, CTX_DEBUG }; constexpr auto kContextKeyOpName = "opname"; constexpr auto kContextKeyPhaseOneFlag = "phaseOne"; constexpr auto kContextKeyWaitType = "waitType"; constexpr auto kContextKeyWaitId = "waitId"; constexpr auto kContextKeyStartTick = "startTick"; constexpr auto kContextKeyDrvSubmitTick = "drvSubmitTick"; constexpr auto kContextKeyDrvSchedTick = "drvSchedTick"; constexpr auto kContextKeyKernelType = "kernelType"; /** * set aicpu context for current thread. * @param [in]ctx aicpu context * @return status whether this operation success */ AICPU_VISIBILITY_API status_t aicpuSetContext(aicpuContext_t *ctx); /** * get aicpu context from current thread. * @param [out]ctx aicpu context * @return status whether this operation success */ AICPU_VISIBILITY_API status_t aicpuGetContext(aicpuContext_t *ctx); /** * init context for task monitor, called in compute process start. * @param [in]aicpu_core_cnt aicpu core number * @return status whether this operation success */ status_t InitTaskMonitorContext(uint32_t aicpu_core_cnt); /** * set aicpu thread index for task monitor, called in thread callback function. * @param [in]thread_index aicpu thread index * @return status whether this operation success */ status_t SetAicpuThreadIndex(uint32_t thread_index); /** * get aicpu thread index. * @return uint32 */ uint32_t GetAicpuThreadIndex(); /** * set op name for task monitor. * called in libtf_kernels.so(tf op) or libaicpu_processer.so(others) or cpu kernel framework. * @param [in]opname op name * @return status whether this operation success */ status_t __attribute__((weak)) SetOpname(const std::string &opname); /** * get op name for task monitor * @param [in]thread_index thread index * @param [out]opname op name * @return status whether this operation success */ status_t GetOpname(uint32_t thread_index, std::string *opname); /** * get task and stream id. * @param [in]task_id task id. * @param [in]stream_id stream id. * @return status whether this operation success */ status_t __attribute__((weak)) GetTaskAndStreamId(uint64_t *task_id, uint32_t *stream_id); /** * set task and stream id. * @param [in]task_id task id. * @param [in]stream_id stream id. * @return status whether this operation success */ status_t __attribute__((weak)) SetTaskAndStreamId(uint64_t task_id, uint32_t stream_id); /** * set thread local context of key * @param [in]key context key * @param [in]value context value * @return status whether this operation success * @note Deprecated from 20201216, Replaced by SetThreadCtxInfo */ status_t __attribute__((weak)) SetThreadLocalCtx(const std::string &key, const std::string &value); /** * get thread local context of key * @param [in]key context key * @param [out]value context value * @return status whether this operation success * @note Deprecated from 20201216, Replaced by GetThreadCtxInfo */ status_t GetThreadLocalCtx(const std::string &key, std::string *value); /** * remove local context of key * @param [in]key context key * @return status whether this operation success * @note Deprecated from 20201216, Replaced by RemoveThreadCtxInfo */ status_t RemoveThreadLocalCtx(const std::string &key); /** * get all thread context info of type * @param [in]type: ctx type * @param [in]thread_index: thread index * @return const std::map<std::string, std::string> &: all thread context info */ const std::map<std::string, std::string> &GetAllThreadCtxInfo(aicpu::CtxType type, uint32_t thread_index); /** * set run mode. * @param [in]run_mode: run mode. * @return status whether this operation success */ status_t __attribute__((weak)) SetAicpuRunMode(uint32_t run_mode); /** * get run mode. * @param [out]run_mode: run mode. * @return status whether this operation success */ status_t __attribute__((weak)) GetAicpuRunMode(uint32_t *run_mode); /** * Register callback function by event_id and subevent_id * @param event_id event id * @param subevent_id subevent id * @param func call back function */ status_t __attribute__((weak)) RegisterEventCallback(uint32_t event_id, uint32_t subevent_id, std::function<void(void *)> func); /** * Do callback function by event_id and subevent_id * @param event_id event id * @param subevent_id subevent id * @param param event param */ status_t __attribute__((weak)) DoEventCallback(uint32_t event_id, uint32_t subevent_id, void *param); /** * Unregister callback function by event_id and subevent_id * @param event_id event id * @param subevent_id subevent id */ status_t __attribute__((weak)) UnRegisterCallback(uint32_t event_id, uint32_t subevent_id); } // namespace aicpu extern "C" { /** * set thread context info of type * @param [in]type: ctx type * @param [in]key: key of context info * @param [in]value: value of context info * @return status whether this operation success */ AICPU_VISIBILITY_API aicpu::status_t SetThreadCtxInfo(aicpu::CtxType type, const std::string &key, const std::string &value); /** * get thread context info of type * @param [in]type: ctx type * @param [in]key: key of context info * @param [out]value: value of context info * @return status whether this operation success */ AICPU_VISIBILITY_API aicpu::status_t GetThreadCtxInfo(aicpu::CtxType type, const std::string &key, std::string *value); /** * remove thread context info of type * @param [in]type: ctx type * @param [in]key: key of context info * @return status whether this operation success */ AICPU_VISIBILITY_API aicpu::status_t RemoveThreadCtxInfo(aicpu::CtxType type, const std::string &key); } #endif // AICPU_OPS_AICPU_CONTEXT_H_ ======================= File: mindspore/ccsrc/cxx_api/model/acl/acl_vm/acl_multi_graph_session.h ======================= /** * 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. */ #ifndef MINDSPORE_CCSRC_CXX_API_ACL_VM_ACL_MULTI_GRAPH_SESSION_H #define MINDSPORE_CCSRC_CXX_API_ACL_VM_ACL_MULTI_GRAPH_SESSION_H #include <deque> #include <vector> #include <map> #include <memory> #include "include/api/types.h" #include "include/api/cell.h" #include "backend/session/session_basic.h" namespace mindspore { class AclModelOptions; namespace session { class MultiGraphAclSession : public session::SessionBasic { public: MultiGraphAclSession() = default; ~MultiGraphAclSession() override = default; void Init(uint32_t device_id) override; GraphId CompileGraphImpl(const AnfNodePtrList &lst, const AnfNodePtrList &outputs) override; void RunGraph(GraphId graph_id, const std::vector<MSTensor> &inputs, VectorRef *outputs); void SetOptions(const std::shared_ptr<AclModelOptions> &options) { options_ = options; } private: VectorRef ConstructOutputRef(GraphId graph_id, std::deque<MSTensor> *out_tensors); VectorRef ConstructOutputRefByTupleNode(const CNodePtr &tuple_node, std::deque<MSTensor> *out_tensors); std::map<GraphId, GraphCell> graphs_ = {}; std::map<GraphId, KernelGraphPtr> kernel_graphs_ = {}; std::shared_ptr<AclModelOptions> options_ = nullptr; }; } // namespace session } // namespace mindspore #endif // MINDSPORE_CCSRC_CXX_API_ACL_VM_ACL_MULTI_GRAPH_SESSION_H ======================= File: mindspore/ccsrc/backend/kernel_compiler/aicpu/aicpu_ops/common/distinct_uniform_int_distribution.h ======================= <reponame>PowerOlive/mindspore /** * 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. */ #ifndef AICPU_OPS_AICPU_DISTINCT_UNIFORM_INT_DISTRIBUTION_H_ #define AICPU_OPS_AICPU_DISTINCT_UNIFORM_INT_DISTRIBUTION_H_ #include <random> #include <unordered_set> namespace aicpu { template <typename IntType = int> class distinct_uniform_int_distribution { public: using result_type = IntType; private: using set_type = std::unordered_set<result_type>; using distr_type = std::uniform_int_distribution<result_type>; public: distinct_uniform_int_distribution(result_type inf, result_type sup) : inf_(inf), sup_(sup), range_(sup_ - inf_ + 1), distr_(inf_, sup_) {} ~distinct_uniform_int_distribution() = default; void reset() { uset_.clear(); distr_.reset(); } template <typename Generator> result_type exec(Generator *engine) { if (!(uset_.size() < range_)) { std::terminate(); } result_type res; do { res = distr_(*engine); } while (uset_.count(res) > 0); uset_.insert(res); return res; } private: const result_type inf_; const result_type sup_; const size_t range_; distr_type distr_; set_type uset_; }; } // namespace aicpu #endif // AICPU_OPS_AICPU_DISTINCT_UNIFORM_INT_DISTRIBUTION_H_ ======================= File: mindspore/lite/tools/benchmark/nnie/src/nnie_common.h ======================= /** * 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. */ #ifndef MINDSPORE_LITE_SRC_RUNTIME_AGENT_NNIE_NNIE_COMMON_H_ #define MINDSPORE_LITE_SRC_RUNTIME_AGENT_NNIE_NNIE_COMMON_H_ #include <iostream> #include <string> #include <vector> #include "include/api/types.h" #include "include/mpi_vb.h" #include "include/hi_comm_svp.h" #include "include/hi_nnie.h" #include "include/mpi_nnie.h" #include "include/ir/dtype/type_id.h" namespace mindspore { namespace nnie { #define NNIE_ALIGN_16 16 #define NNIE_ALIGN16(u32Num) ((u32Num + NNIE_ALIGN_16 - 1) / NNIE_ALIGN_16 * NNIE_ALIGN_16) #define NNIE_ALIGN_32 32 #define NNIE_ALIGN32(u32Num) ((u32Num + NNIE_ALIGN_32 - 1) / NNIE_ALIGN_32 * NNIE_ALIGN_32) #define NNIE_CONVERT_64BIT_ADDR(Type, Addr) reinterpret_cast<Type *>((HI_UL)(Addr)) #define NNIE_QUANT_BASE 4096 #define NNIE_COORDI_NUM 4 #define NNIE_EACH_SEG_STEP_ADDR_NUM 2 #define NNIE_REPORT_NAME_LENGTH 64 typedef struct { SVP_NNIE_MODEL_S model_; SVP_MEM_INFO_S model_buf_; // store Model file } NnieModel; typedef struct { SVP_SRC_BLOB_S src_[SVP_NNIE_MAX_INPUT_NUM]; SVP_DST_BLOB_S dst_[SVP_NNIE_MAX_OUTPUT_NUM]; } NnieSegData; typedef struct { bool src_node_[SVP_NNIE_MAX_INPUT_NUM]; bool dst_node_[SVP_NNIE_MAX_OUTPUT_NUM]; } NNIEMemSegInfo; typedef struct { NNIEMemSegInfo seg_[SVP_NNIE_MAX_NET_SEG_NUM]; } NNIEMemCfg; typedef struct { SVP_NNIE_MODEL_S *model_; HI_U32 task_buf_size_[SVP_NNIE_MAX_NET_SEG_NUM]; SVP_MEM_INFO_S task_buf_; SVP_MEM_INFO_S tmp_buf_; SVP_MEM_INFO_S step_buf_; // store Lstm step info SVP_SRC_BLOB_S rpn_bbox_; NnieSegData seg_data_[SVP_NNIE_MAX_NET_SEG_NUM]; // each seg's input and output blob SVP_NNIE_FORWARD_CTRL_S forward_ctrl_[SVP_NNIE_MAX_NET_SEG_NUM]; SVP_NNIE_FORWARD_WITHBBOX_CTRL_S forward_with_bbox_ctrl_[SVP_NNIE_MAX_NET_SEG_NUM]; NNIEMemCfg mem_cfg_; } NnieParam; typedef struct { HI_VOID *data_ptr_; HI_U32 max_input_num_; HI_U32 max_roi_num_; HI_U32 step_; HI_U64 step_vir_addr_[NNIE_EACH_SEG_STEP_ADDR_NUM * SVP_NNIE_MAX_NET_SEG_NUM]; // virtual addr of LSTM's or RNN's step buffer SVP_NNIE_ID_E nnie_core_id_[SVP_NNIE_MAX_NET_SEG_NUM]; } NnieCfg; typedef struct { HI_U32 seg_idx_; HI_U32 node_idx_; } NnieDataIndex; typedef struct { HI_U32 src_size_[SVP_NNIE_MAX_INPUT_NUM]; HI_U32 dst_size_[SVP_NNIE_MAX_OUTPUT_NUM]; } NnieBlobSize; typedef struct { NnieModel model_; NnieParam param_; NnieCfg cfg_; NnieDataIndex run_idx_; } NnieRunCfg; int NnieCommCreate(NnieRunCfg *nnie_run_cfg, char *model_buf, int size, const std::vector<mindspore::MSTensor> &inputs); size_t GetFillIndex(const std::vector<mindspore::MSTensor> &inputs, size_t input_size, const HI_CHAR *name); void NnieCommDelete(NnieParam *pstNnieParamm, NnieModel *nnie_model); int NnieCommRun(NnieRunCfg *nnie_run_cfg, bool run_box); int NnieCommFillData(NnieRunCfg *nnie_run_cfg, void *data, mindspore::DataType dtype, int64_t *shape, int size, int id); int NnieCommGetOutputData(NnieRunCfg *nnie_run_cfg, float *data, int64_t *shape, int size, int tensor_index); } // namespace nnie } // namespace mindspore #endif // MINDSPORE_LITE_SRC_RUNTIME_AGENT_NNIE_NNIE_COMMON_H_ ======================= File: mindspore/ccsrc/backend/kernel_compiler/cpu/nnacl/fp16_grad/dropout_grad.c ======================= <gh_stars>1000+ /** * 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. */ #include "nnacl/fp16_grad/dropout_grad.h" void DropoutFp16Grad(const float16_t *yt_ptr, const float16_t *mask, float16_t *output_ptr, int length, float16_t scale) { for (int i = 0; i < length; i++) { output_ptr[i] = yt_ptr[i] * mask[i] * scale; } } ======================= File: mindspore/ccsrc/backend/kernel_compiler/cpu/nnacl/intrinsics/sse/WinogradPostFuncBiasReluC4.c ======================= <reponame>PowerOlive/mindspore<filename>mindspore/ccsrc/backend/kernel_compiler/cpu/nnacl/intrinsics/sse/WinogradPostFuncBiasReluC4.c<gh_stars>1-10 /** * 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. */ #if defined(ENABLE_SSE) &&!defined(ENABLE_AVX) #include "nnacl/intrinsics/ms_simd_instructions.h" #include "nnacl/fp32/common_func_fp32.h" #include "nnacl/intrinsics/sse/sse_common.h" void WinogradPostFuncBiasReluC4(float *dst, const float *src, const float *bias, size_t oc4div, size_t oc4mod, size_t plane_size, size_t plane_stride, size_t relu_type) { size_t stride = oc4div + oc4mod; plane_stride /= sizeof(float); int loop_c4 = 0; size_t src_stride = plane_size * C4NUM + plane_stride; for (; loop_c4 <= (int)(oc4div)-C16NUM; loop_c4 += C16NUM) { size_t plane_size_tmp = plane_size; float *dst_c4 = dst + loop_c4; __m128 bias1 = _mm_setzero_ps(); __m128 bias2 = _mm_setzero_ps(); __m128 bias3 = _mm_setzero_ps(); __m128 bias4 = _mm_setzero_ps(); if (bias!= NULL) { bias1 = _mm_loadu_ps(bias); bias2 = _mm_loadu_ps(bias + C4NUM); bias3 = _mm_loadu_ps(bias + C8NUM); bias4 = _mm_loadu_ps(bias + C12NUM); bias += C16NUM; } for (; plane_size_tmp >= C4NUM; plane_size_tmp -= C4NUM) { __m128 src1 = _mm_loadu_ps(src); __m128 src2 = _mm_loadu_ps(src + C4NUM); __m128 src5 = _mm_loadu_ps(src + src_stride); __m128 src6 = _mm_loadu_ps(src + src_stride + C4NUM); __m128 src9 = _mm_loadu_ps(src + src_stride * C2NUM); __m128 src10 = _mm_loadu_ps(src + src_stride * C2NUM + C4NUM); __m128 src13 = _mm_loadu_ps(src + src_stride * C3NUM); __m128 src14 = _mm_loadu_ps(src + src_stride * C3NUM + C4NUM); src1 = _mm_add_ps(src1, bias1); src2 = _mm_add_ps(src2, bias1); src5 = _mm_add_ps(src5, bias2); src6 = _mm_add_ps(src6, bias2); src9 = _mm_add_ps(src9, bias3); src10 = _mm_add_ps(src10, bias3); src13 = _mm_add_ps(src13, bias4); src14 = _mm_add_ps(src14, bias4); ActBlock8(&src1, &src2, &src5, &src6, &src9, &src10, &src13, &src14, relu_type); _mm_storeu_ps(dst_c4, src1); _mm_storeu_ps(dst_c4 + C4NUM, src5); _mm_storeu_ps(dst_c4 + C8NUM, src9); _mm_storeu_ps(dst_c4 + C12NUM, src13); dst_c4 += stride; _mm_storeu_ps(dst_c4, src2); _mm_storeu_ps(dst_c4 + C4NUM, src6); _mm_storeu_ps(dst_c4 + C8NUM, src10); _mm_storeu_ps(dst_c4 + C12NUM, src14); dst_c4 += stride; __m128 src3 = _mm_loadu_ps(src + C8NUM); __m128 src4 = _mm_loadu_ps(src + C12NUM); __m128 src7 = _mm_loadu_ps(src + src_stride + C8NUM); __m128 src8 = _mm_loadu_ps(src + src_stride + C12NUM); __m128 src11 = _mm_loadu_ps(src + src_stride * C2NUM + C8NUM); __m128 src12 = _mm_loadu_ps(src + src_stride * C2NUM + C12NUM); __m128 src15 = _mm_loadu_ps(src + src_stride * C3NUM + C8NUM); __m128 src16 = _mm_loadu_ps(src + src_stride * C3NUM + C12NUM); src3 = _mm_add_ps(src3, bias1); src4 = _mm_add_ps(src4, bias1); src7 = _mm_add_ps(src7, bias2); src8 = _mm_add_ps(src8, bias2); src11 = _mm_add_ps(src11, bias3); src12 = _mm_add_ps(src12, bias3); src15 = _mm_add_ps(src15, bias4); src16 = _mm_add_ps(src16, bias4); ActBlock8(&src3, &src4, &src7, &src8, &src11, &src12, &src15, &src16, relu_type); _mm_storeu_ps(dst_c4, src3); _mm_storeu_ps(dst_c4 + C4NUM, src7); _mm_storeu_ps(dst_c4 + C8NUM, src11); _mm_storeu_ps(dst_c4 + C12NUM, src15); dst_c4 += stride; _mm_storeu_ps(dst_c4, src4); _mm_storeu_ps(dst_c4 + C4NUM, src8); _mm_storeu_ps(dst_c4 + C8NUM, src12); _mm_storeu_ps(dst_c4 + C12NUM, src16); dst_c4 += stride; src += C16NUM; } for (; plane_size_tmp > 0; plane_size_tmp -= 1) { __m128 src1 = _mm_loadu_ps(src); __m128 src2 = _mm_loadu_ps(src + src_stride); __m128 src3 = _mm_loadu_ps(src + src_stride * C2NUM); __m128 src4 = _mm_loadu_ps(src + src_stride * C3NUM); src1 = _mm_add_ps(src1, bias1); src2 = _mm_add_ps(src2, bias2); src3 = _mm_add_ps(src3, bias3); src4 = _mm_add_ps(src4, bias4); ActBlock4(&src1, &src2, &src3, &src4, relu_type == 1, relu_type == C3NUM); _mm_storeu_ps(dst_c4, src1); _mm_storeu_ps(dst_c4 + C4NUM, src2); _mm_storeu_ps(dst_c4 + C8NUM, src3); _mm_storeu_ps(dst_c4 + C12NUM, src4); dst_c4 += stride; src += C4NUM; } src += plane_stride; src += C3NUM * src_stride; } for (; loop_c4 <= (int)(oc4div)-C12NUM; loop_c4 += C12NUM) { size_t plane_size_tmp = plane_size; float *dst_c4 = dst + loop_c4; __m128 bias1 = _mm_setzero_ps(); __m128 bias2 = _mm_setzero_ps(); __m128 bias3 = _mm_setzero_ps(); if (bias!= NULL) { bias1 = _mm_loadu_ps(bias); bias2 = _mm_loadu_ps(bias + C4NUM); bias3 = _mm_loadu_ps(bias + C8NUM); bias += C12NUM; } for (; plane_size_tmp >= C4NUM; plane_size_tmp -= C4NUM) { __m128 src1 = _mm_loadu_ps(src); __m128 src2 = _mm_loadu_ps(src + C4NUM); __m128 src3 = _mm_loadu_ps(src + C8NUM); __m128 src4 = _mm_loadu_ps(src + C12NUM); __m128 src5 = _mm_loadu_ps(src + src_stride); __m128 src6 = _mm_loadu_ps(src + src_stride + C4NUM); __m128 src7 = _mm_loadu_ps(src + src_stride + C8NUM); __m128 src8 = _mm_loadu_ps(src + src_stride + C12NUM); __m128 src9 = _mm_loadu_ps(src + src_stride * C2NUM); __m128 src10 = _mm_loadu_ps(src + src_stride * C2NUM + C4NUM); __m128 src11 = _mm_loadu_ps(src + src_stride * C2NUM + C8NUM); __m128 src12 = _mm_loadu_ps(src + src_stride * C2NUM + C12NUM); src += C16NUM; src1 = _mm_add_ps(src1, bias1); src2 = _mm_add_ps(src2, bias1); src3 = _mm_add_ps(src3, bias1); src4 = _mm_add_ps(src4, bias1); src5 = _mm_add_ps(src5, bias2); src6 = _mm_add_ps(src6, bias2); src7 = _mm_add_ps(src7, bias2); src8 = _mm_add_ps(src8, bias2); src9 = _mm_add_ps(src9, bias3); src10 = _mm_add_ps(src10, bias3); src11 = _mm_add_ps(src11, bias3); src12 = _mm_add_ps(src12, bias3); ActBlock12(&src1, &src2, &src3, &src4, &src5, &src6, &src7, &src8, &src9, &src10, &src11, &src12, relu_type == 1, relu_type == C3NUM); _mm_storeu_ps(dst_c4, src1); _mm_storeu_ps(dst_c4 + C4NUM, src5); _mm_storeu_ps(dst_c4 + C8NUM, src9); dst_c4 += stride; _mm_storeu_ps(dst_c4, src2); _mm_storeu_ps(dst_c4 + C4NUM, src6); _mm_storeu_ps(dst_c4 + C8NUM, src10); dst_c4 += stride; _mm_storeu_ps(dst_c4, src3); _mm_storeu_ps(dst_c4 + C4NUM, src7); _mm_storeu_ps(dst_c4 + C8NUM, src11); dst_c4 += stride; _mm_storeu_ps(dst_c4, src4); _mm_storeu_ps(dst_c4 + C4NUM, src8); _mm_storeu_ps(dst_c4 + C8NUM, src12); dst_c4 += stride; } for (; plane_size_tmp > 0; plane_size_tmp -= 1) { __m128 src1 = _mm_loadu_ps(src); __m128 src2 = _mm_loadu_ps(src + src_stride); __m128 src3 = _mm_loadu_ps(src + src_stride * C2NUM); src1 = _mm_add_ps(src1, bias1); src2 = _mm_add_ps(src2, bias2); src3 = _mm_add_ps(src3, bias3); ActBlock1(&src1, relu_type == 1, relu_type == C3NUM); ActBlock1(&src2, relu_type == 1, relu_type == C3NUM); ActBlock1(&src3, relu_type == 1, relu_type == C3NUM); _mm_storeu_ps(dst_c4, src1); _mm_storeu_ps(dst_c4 + C4NUM, src2); _mm_storeu_ps(dst_c4 + C8NUM, src3); dst_c4 += stride; src += C4NUM; } src += plane_stride; src += C2NUM * src_stride; } for (; loop_c4 <= (int)(oc4div)-C8NUM; loop_c4 += C8NUM) { size_t plane_size_tmp = plane_size; float *dst_c4 = dst + loop_c4; __m128 bias1 = _mm_setzero_ps(); __m128 bias2 = _mm_setzero_ps(); if (bias!= NULL) { bias1 = _mm_loadu_ps(bias); bias2 = _mm_loadu_ps(bias + C4NUM); bias += C8NUM; } for (; plane_size_tmp >= C4NUM; plane_size_tmp -= C4NUM) { __m128 src1 = _mm_loadu_ps(src); __m128 src2 = _mm_loadu_ps(src + C4NUM); __m128 src3 = _mm_loadu_ps(src + C8NUM); __m128 src4 = _mm_loadu_ps(src + C12NUM); __m128 src5 = _mm_loadu_ps(src + src_stride); __m128 src6 = _mm_loadu_ps(src + src_stride + C4NUM); __m128 src7 = _mm_loadu_ps(src + src_stride + C8NUM); __m128 src8 = _mm_loadu_ps(src + src_stride + C12NUM); src += C16NUM; src1 = _mm_add_ps(src1, bias1); src2 = _mm_add_ps(src2, bias1); src3 = _mm_add_ps(src3, bias1); src4 = _mm_add_ps(src4, bias1); src5 = _mm_add_ps(src5, bias2); src6 = _mm_add_ps(src6, bias2); src7 = _mm_add_ps(src7, bias2); src8 = _mm_add_ps(src8, bias2); ActBlock8(&src1, &src2, &src3, &src4, &src5, &src6, &src7, &src8, relu_type); _mm_storeu_ps(dst_c4, src1); _mm_storeu_ps(dst_c4 + C4NUM, src5); dst_c4 += stride; _mm_storeu_ps(dst_c4, src2); _mm_storeu_ps(dst_c4 + C4NUM, src6); dst_c4 += stride; _mm_storeu_ps(dst_c4, src3); _mm_storeu_ps(dst_c4 + C4NUM, src7); dst_c4 += stride; _mm_storeu_ps(dst_c4, src4); _mm_storeu_ps(dst_c4 + C4NUM, src8); dst_c4 += stride; } for (; plane_size_tmp > 0; plane_size_tmp -= 1) { __m128 src1 = _mm_loadu_ps(src); __m128 src2 = _mm_loadu_ps(src + src_stride); src1 = _mm_add_ps(src1, bias1); src2 = _mm_add_ps(src2, bias2); ActBlock1(&src1, relu_type == 1, relu_type == C3NUM); ActBlock1(&src2, relu_type == 1, relu_type == C3NUM); _mm_storeu_ps(dst_c4, src1); _mm_storeu_ps(dst_c4 + C4NUM, src2); dst_c4 += stride; src += C4NUM; } src += plane_stride; src += src_stride; } for (; loop_c4 < (int)(oc4div); loop_c4 += C4NUM) { size_t plane_size_tmp = plane_size; float *dst_c4 = dst + loop_c4; __m128 bias1 = _mm_setzero_ps(); if (bias!= NULL) { bias1 = _mm_loadu_ps(bias); bias += C4NUM; } for (; plane_size_tmp >= C4NUM; plane_size_tmp -= C4NUM) { __m128 src1 = _mm_loadu_ps(src); __m128 src2 = _mm_loadu_ps(src + C4NUM); __m128 src3 = _mm_loadu_ps(src + 8); __m128 src4 = _mm_loadu_ps(src + 12); src += C16NUM; src1 = _mm_add_ps(src1, bias1); src2 = _mm_add_ps(src2, bias1); src3 = _mm_add_ps(src3, bias1); src4 = _mm_add_ps(src4, bias1); ActBlock4(&src1, &src2, &src3, &src4, relu_type == 1, relu_type == C3NUM); _mm_storeu_ps(dst_c4, src1); dst_c4 += stride; _mm_storeu_ps(dst_c4, src2); dst_c4 += stride; _mm_storeu_ps(dst_c4, src3); dst_c4 += stride; _mm_storeu_ps(dst_c4, src4); dst_c4 += stride; } for (; plane_size_tmp > 0; plane_size_tmp -= 1) { __m128 src1 = _mm_loadu_ps(src); src1 = _mm_add_ps(src1, bias1); ActBlock1(&src1, relu_type == 1, relu_type == C3NUM); _mm_storeu_ps(dst_c4, src1); dst_c4 += stride; src += C4NUM; } src += plane_stride; } if (oc4mod == 0) { return; } __m128 bias1 = _mm_setzero_ps(); if (bias!= NULL) { bias1 = _mm_loadu_ps(bias); bias += C4NUM; } float *dst_c1 = dst + oc4div; for (size_t plane_size_tmp = plane_size; plane_size_tmp > 0; plane_size_tmp -= 1) { __m128 src1 = _mm_loadu_ps(src); src += C4NUM; src1 = _mm_add_ps(src1, bias1); ActBlock1(&src1, relu_type == 1, relu_type == C3NUM); switch (oc4mod) { case 1: _mm_store_ss(dst_c1, src1); dst_c1 += stride; break; case C2NUM: _mm_storel_pi((__m64 *)(dst_c1), src1); dst_c1 += stride; break; case C3NUM: _mm_storel_pi((__m64 *)(dst_c1), src1); src1 = _mm_unpackhi_ps(src1, src1); _mm_store_ss(dst_c1 + C2NUM, src1); dst_c1 += stride; break; case C4NUM: _mm_storeu_ps(dst_c1, src1); dst_c1 += stride; break; } } } #endif ======================= File: mindspore/ccsrc/minddata/dataset/engine/tree_adapter_lite.h ======================= /** * 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. */ #ifndef MINDSPORE_CCSRC_MINDDATA_DATASET_ENGINE_TREE_ADAPTER_LITE_H_ #define MINDSPORE_CCSRC_MINDDATA_DATASET_ENGINE_TREE_ADAPTER_LITE_H_ #include <memory> #include <string> #include <unordered_map> #include <utility> #include <vector> #include "minddata/dataset/engine/ir/datasetops/dataset_node.h" namespace mindspore { namespace dataset { class TensorRow; class DatasetNode; class TreeAdapterLite { public: TreeAdapterLite(); ~TreeAdapterLite() = default; Status BuildTree(std::shared_ptr<DatasetNode> root_ir); // Get rows equal to num_rows Status GetNextRow(TensorRow *const row); std::unordered_map<std::string, int32_t> GetColumnNameMap() const { return tree_->root()->column_name_id_map(); } private: // This RECURSIVE function walks the (optimized) IR tree in DFS to build its corresponding Execution tree. Status BuildExecutionTreeRecur(std::shared_ptr<DatasetNode> ir, std::shared_ptr<DatasetOp> *op); std::shared_ptr<DatasetOp> root_; // current connector capacity of root op, used for profiling std::unique_ptr<ExecutionTree> tree_; }; } // namespace dataset } // namespace mindspore #endif // MINDSPORE_CCSRC_MINDDATA_DATASET_ENGINE_TREE_ADAPTER_LITE_H_ ======================= File: mindspore/lite/tools/benchmark/dpico/src/custom_fp32.h ======================= /** * 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. */ #ifndef MINDSPORE_LITE_SRC_RUNTIME_KERNEL_ARM_FP32_CUSTOM_H_ #define MINDSPORE_LITE_SRC_RUNTIME_KERNEL_ARM_FP32_CUSTOM_H_ #include <sys/stat.h> #include <cmath> #include <iostream> #include <fstream> #include <cstring> #include <map> #include <sstream> #include <vector> #include <string> #include <thread> #include "include/api/kernel.h" #include "include/svp_acl.h" #include "include/svp_acl_mdl.h" #include "include/svp_acl_ext.h" #include "src/common_utils.h" #include "src/custom_infer.h" using mindspore::kernel::Kernel; namespace mindspore { namespace lite { class CustomCPUKernel : public Kernel { public: CustomCPUKernel(const std::vector<MSTensor> &inputs, const std::vector<MSTensor> &outputs, const mindspore::schema::Primitive *primitive, const mindspore::Context *ctx) : Kernel(inputs, outputs, primitive, ctx) { std::map<std::string, std::string> attrs; ExtractAttrsFromPrimitive(primitive, &attrs); for (auto &item : attrs) { SetAttr(item.first, item.second); } num_of_om_model_++; } ~CustomCPUKernel() override; int Prepare() override; int ReSize() override; int Execute() override; private: Result DetermineBatchSize(); int LoadModelAndInitResource(); Result LoadModel(); Result PrepareDevice(); Result CreateInputs(); Result CreateOutputs(); Result SetDetParas(); Result GetStrideParam(size_t *devSize, int index, size_t *stride, svp_acl_mdl_io_dims *dims); Result CreateInput(void *inputDataBuffer, size_t bufferSize, int stride); void *GetDeviceBufferOfTensor(const svp_acl_mdl_io_dims &dims, const size_t &stride, size_t dataSize); Result CreateTaskBufAndWorkBuf(); Result CreateBuf(int index); Result GetInputDims(int index, svp_acl_mdl_io_dims *dims); size_t GetInputDataSize(int index); Result PreExecute(); Result DeviceExecute(); Result CopyTensorsToNpuWithStride(); void DumpModelOutputResultToTensor(); void WriteOutputToTensor(size_t index, size_t output_tensor_index); void OutputModelResult(); void PrintResultToTensor(const std::vector<std::vector<float>> &boxValue); void UpdateDetParas(); void UnloadModel(); void DestroyInput(); void DestroyOutput(); void TerminateDevice(); private: uint32_t model_id_ = 0; void *model_mem_ptr_ = nullptr; bool load_flag_ = false; // model load flag svp_acl_mdl_desc *model_desc_ = nullptr; svp_acl_mdl_dataset *input_ = nullptr; svp_acl_mdl_dataset *output_ = nullptr; svp_acl_rt_stream stream_; std::vector<void *> inputs_data_in_npu_; size_t recurrent_total_t = 1; bool is_recurrent_net_ = false; // true: batch is 1, false: not support Total_t bool is_detection_net_ = false; size_t batch_size_ = 1; bool prepared_ = false; float *det_param_buf_float_ = nullptr; static size_t num_of_om_model_; static dpico::CustomInterface custom_infershape_; static DpicoConfigParamExtractor dpico_config_param_extractor_; static DpicoContextManager dpico_context_manager_; static DpicoAicpuThreadManager dpico_aicpu_thread_manager_; }; } // namespace lite } // namespace mindspore #endif // MINDSPORE_LITE_SRC_RUNTIME_KERNEL_ARM_FP32_CUSTOM_H_ ======================= File: mindspore/lite/tools/benchmark/nnie/src/custom_fp32.h ======================= /** * 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. */ #ifndef MINDSPORE_LITE_SRC_RUNTIME_KERNEL_ARM_FP32_CUSTOM_H_ #define MINDSPORE_LITE_SRC_RUNTIME_KERNEL_ARM_FP32_CUSTOM_H_ #include <vector> #include <string> #include "include/schema/model_generated.h" #include "include/context.h" #include "include/api/kernel.h" #include "src/custom_infer.h" using mindspore::kernel::Kernel; using mindspore::tensor::MSTensor; namespace mindspore { namespace nnie { class CustomCPUKernel : public Kernel { public: CustomCPUKernel(int seg_id, bool forward_bbox, const std::vector<MSTensor> &inputs, const std::vector<MSTensor> &outputs, const mindspore::schema::Primitive *primitive, const mindspore::Context *ctx) : Kernel(inputs, outputs, primitive, ctx), seg_id_(seg_id), forward_bbox_(forward_bbox) { if (forward_bbox) { roi_used_ = true; } } ~CustomCPUKernel() override; int Prepare() override; int ReSize() override; int Execute() override; int seg_id(void) const { return seg_id_; } void set_seg_id(int id) { seg_id_ = id; } int forward_bbox(void) const { return forward_bbox_; } void set_forward_bbox(bool flag) { forward_bbox_ = flag; } private: static bool load_model_; static int run_seg_; static bool roi_used_; int seg_id_ = 0; bool forward_bbox_ = false; std::vector<std::vector<int64_t>> outputs_shapes_; }; } // namespace nnie } // namespace mindspore #endif // MINDSPORE_LITE_SRC_RUNTIME_KERNEL_ARM_FP32_CUSTOM_H_ ======================= File: mindspore/core/utils/singleton.h ======================= <reponame>PowerOlive/mindspore /** * 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. */ #ifndef MINDSPORE_CORE_UTILS_SINGLETON_H_ #define MINDSPORE_CORE_UTILS_SINGLETON_H_ namespace mindspore { template <typename T> class Singleton { public: explicit Singleton(T &&) = delete; explicit Singleton(const T &) = delete; void operator=(const T &) = delete; // thread safety implement template <typename... _Args> static T &Instance(_Args... args) { static T instance(args...); return instance; } protected: Singleton() = default; virtual ~Singleton() = default; }; } // namespace mindspore #endif // MINDSPORE_CORE_UTILS_SINGLETON_H_ ======================= File: mindspore/ccsrc/minddata/dataset/audio/kernels/biquad_op.h ======================= <gh_stars>1000+ /** * 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. */ #ifndef MINDSPORE_CCSRC_MINDDATA_DATASET_AUDIO_KERNELS_BIQUAD_OP_H_ #define MINDSPORE_CCSRC_MINDDATA_DATASET_AUDIO_KERNELS_BIQUAD_OP_H_ #include <memory> #include <string> #include <vector> #include "minddata/dataset/core/tensor.h" #include "minddata/dataset/kernels/tensor_op.h" #include "minddata/dataset/util/status.h" namespace mindspore { namespace dataset { class BiquadOp : public TensorOp { public: BiquadOp(float b0, float b1, float b2, float a0, float a1, float a2) : b0_(b0), b1_(b1), b2_(b2), a0_(a0), a1_(a1), a2_(a2) {} ~BiquadOp() override = default; void Print(std::ostream &out) const override { out << Name() << ": b0: " << b0_ << ", b1: " << b1_ << ", b2: " << b2_ << ", a0: " << a0_ << ", a1: " << a1_ << ", a2: " << a2_ << std::endl; } Status Compute(const std::shared_ptr<Tensor> &input, std::shared_ptr<Tensor> *output) override; std::string Name() const override { return kBiquadOp; } private: float b0_; float b1_; float b2_; float a0_; float a1_; float a2_; }; } // namespace dataset } // namespace mindspore #endif // MINDSPORE_CCSRC_MINDDATA_DATASET_AUDIO_KERNELS_BIQUAD_OP_H_ ======================= File: mindspore/ccsrc/frontend/parallel/auto_parallel/rec_core/rec_generate_strategy.h ======================= /** * Copyright 2020 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef PARALLEL_AUTO_PARALLEL_REC_GENERATE_STRATEGY_H_ #define PARALLEL_AUTO_PARALLEL_REC_GENERATE_STRATEGY_H_ #include <memory> #include <string> #include <utility> #include <vector> #include "frontend/parallel/auto_parallel/rec_core/rec_graph.h" #include "frontend/parallel/ops_info/operator_info.h" namespace mindspore { namespace parallel { void GenerateStrategy(const std::shared_ptr<Graph> &graph, const std::vector<std::shared_ptr<OperatorInfo>> &ops, const std::shared_ptr<std::vector<std::vector<size_t>>> &eli_list, const std::vector<std::vector<std::string>> &input_tensor_names, const std::shared_ptr<std::vector<size_t>> &index_list, bool is_training, const std::vector<std::vector<size_t>> &shared_tensors_ops); Dimensions PrepareMatMulStrategy(const std::shared_ptr<Graph> &graph, const size_t iter_graph, bool transpose_a, bool transpose_b, size_t iter_op_inputs); Strategys PrepareMatMul(const std::shared_ptr<Graph> &graph, const std::vector<std::shared_ptr<OperatorInfo>> &ops, const size_t iter_graph, const size_t iter_ops); Strategys PrepareBiasAdd(const std::shared_ptr<Dimensions> &s); Strategys PrepareStridedSlice(const std::vector<std::shared_ptr<OperatorInfo>> &ops, const size_t iter_ops, Dimensions basic_stra); Strategys PrepareSoftMax(const std::vector<std::shared_ptr<OperatorInfo>> &ops, const size_t iter_ops, Dimensions basic_stra); Strategys PrepareOneHot(const std::vector<std::shared_ptr<OperatorInfo>> &ops, const size_t iter_ops, Dimensions s); Strategys PrepareAxisRelatedStrategy(const std::shared_ptr<Graph> &graph, const std::vector<std::shared_ptr<OperatorInfo>> &ops, const size_t iter_graph, const size_t iter_ops); Strategys PrepareGatherV2(const std::vector<std::shared_ptr<OperatorInfo>> &ops, const size_t iter_ops, Dimensions s); Dimensions PrepareGatherV2OutputStrategy(const std::vector<std::shared_ptr<OperatorInfo>> &ops, const size_t incoming_op_index); Strategys PrepareL2Normalize(const std::vector<std::shared_ptr<OperatorInfo>> &ops, const size_t iter_ops, Dimensions s); Strategys MakeRecSearchStrategy(const std::shared_ptr<Graph> &graph, const std::vector<std::shared_ptr<OperatorInfo>> &ops, const size_t iter_graph, const size_t iter_ops); Strategys CheckBroadcast(const std::vector<std::shared_ptr<OperatorInfo>> &ops, const size_t iter_ops, Dimensions s); Dimensions ApplyBroadcast(const std::vector<std::shared_ptr<OperatorInfo>> &ops, const size_t iter_ops, Dimensions s, size_t first_tensor_dim, size_t second_tensor_dim, bool broadcast_first_tensor); Strategys CheckDivisible(const std::vector<std::shared_ptr<OperatorInfo>> &ops, const size_t iter_ops, Dimensions s); Strategys MakeDataParallelStrategy(const std::shared_ptr<Graph> &graph, const std::vector<std::shared_ptr<OperatorInfo>> &ops, const size_t iter_graph, const size_t iter_ops); Strategys MakeFullBatchStrategy(const std::shared_ptr<Graph> &graph, const std::vector<std::shared_ptr<OperatorInfo>> &ops, const size_t iter_graph, const size_t iter_ops); void SetBackToRawStrategy(const std::shared_ptr<OperatorInfo> &op); Strategys PrepareStrategy(const std::shared_ptr<Graph> &graph, const std::vector<std::shared_ptr<OperatorInfo>> &ops, const size_t iter_graph, const size_t iter_ops); void GeneratePartitionedOperatorStrategy(const std::shared_ptr<Graph> &graph, const std::vector<std::shared_ptr<OperatorInfo>> &ops, const std::shared_ptr<std::vector<size_t>> &index_list); size_t FindIndexOfOperatorIncoming(const std::vector<std::vector<std::string>> &input_tensor_names, const size_t iter_ops); Dimensions CopyIncomingOperatorOutputStrategy(const std::shared_ptr<Graph> &graph, const std::vector<std::shared_ptr<OperatorInfo>> &ops, const size_t iter_ops, const size_t iter_graph, const size_t incoming_op_index); Dimensions PrepareReshapeOutputStrategy(const std::vector<std::shared_ptr<OperatorInfo>> &ops, const size_t incoming_op_index); Dimensions PrepareTransposeOutputStrategy(const std::vector<std::shared_ptr<OperatorInfo>> &ops, const size_t incoming_op_index); Dimensions PrepareExpandDimsOutputStrategy(const std::vector<std::shared_ptr<OperatorInfo>> &ops, const size_t incoming_op_index); Dimensions PrepareIncompingArithmeticOpeartorInputStrategy(const std::vector<std::shared_ptr<OperatorInfo>> &ops, const size_t incoming_op_index); Dimensions PrepareIncomingOperatorInputStrategy(const std::vector<std::shared_ptr<OperatorInfo>> &ops, const size_t incoming_op_index); Dimensions GetAxisList(const std::vector<std::shared_ptr<OperatorInfo>> &ops, const int64_t iter_ops); Dimensions ModifyStrategyIfSqueezeIncoming(const std::vector<std::shared_ptr<OperatorInfo>> &ops, const size_t incoming_op_index, Dimensions s); bool GetKeepDims(const std::vector<std::shared_ptr<OperatorInfo>> &ops, const size_t iter_ops); Dimensions GetDimList(const std::vector<std::shared_ptr<OperatorInfo>> &ops, const size_t iter_ops); Dimensions ModifyStrategyIfReduceIncoming(const std::vector<std::shared_ptr<OperatorInfo>> &ops, const size_t incoming_op_index, Dimensions s); Dimensions GetDimListFromAttrs(const std::vector<std::shared_ptr<OperatorInfo>> &ops, const size_t iter_ops); Dimensions ModifyStrategyIfArgIncoming(const std::vector<std::shared_ptr<OperatorInfo>> &ops, const size_t incoming_op_index, Dimensions s); Dimensions CopyIncomingOperatorInputStrategy(const std::vector<std::shared_ptr<OperatorInfo>> &ops, const size_t iter_ops, const size_t incoming_op_index); Strategys GenerateStrategiesFromStrategy(const std::vector<std::shared_ptr<OperatorInfo>> &ops, const size_t iter_ops, Dimensions basic_stra); void GenerateEliminatedOperatorStrategyForward(const std::shared_ptr<Graph> &graph, const std::vector<std::shared_ptr<OperatorInfo>> &ops, const std::vector<std::vector<std::string>> &input_tensor_names, const std::shared_ptr<std::vector<size_t>> &index_list, const std::shared_ptr<std::vector<size_t>> &no_stra_op_list); Dimensions ModifyStrategyIfSqueezeOutgoing(const std::vector<std::shared_ptr<OperatorInfo>> &ops, const size_t iter_ops, Dimensions s); Dimensions CopyOutgoingOperatorInputStrategy(const std::vector<std::shared_ptr<OperatorInfo>> &ops, const std::vector<std::vector<std::string>> &input_tensor_names, const size_t iter_ops); void GenerateEliminatedOperatorStrategyBackward(const std::vector<std::shared_ptr<OperatorInfo>> &ops, const std::vector<std::vector<std::string>> &input_tensor_names, const std::shared_ptr<std::vector<size_t>> &no_stra_op_list); void GenerateRemainingOperatorStrategy(const std::shared_ptr<Graph> &graph, const std::vector<std::shared_ptr<OperatorInfo>> &ops, const std::vector<std::vector<std::string>> &input_tensor_names, const std::shared_ptr<std::vector<size_t>> &index_list, const std::shared_ptr<std::vector<size_t>> &no_stra_op_list); void ModifySharingTensorOps(const std::vector<std::shared_ptr<OperatorInfo>> &ops, const std::vector<std::vector<size_t>> &shared_tensors_ops); } // namespace parallel } // namespace mindspore #endif // PARALLEL_AUTO_PARALLEL_REC_GENERATE_STRATEGY_H_ ======================= File: mindspore/ccsrc/minddata/dataset/engine/datasetops/source/iwslt_op.h ======================= /** * 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. */ #ifndef MINDSPORE_CCSRC_MINDDATA_DATASET_ENGINE_DATASETOPS_SOURCE_IWSLT_OP_H_ #define MINDSPORE_CCSRC_MINDDATA_DATASET_ENGINE_DATASETOPS_SOURCE_IWSLT_OP_H_ #include <memory> #include <string> #include <vector> #include "./tinyxml2.h" #include "debug/common.h" #include "minddata/dataset/engine/data_schema.h" #include "minddata/dataset/engine/datasetops/parallel_op.h" #include "minddata/dataset/engine/datasetops/source/io_block.h" #include "minddata/dataset/engine/datasetops/source/nonmappable_leaf_op.h" #include "minddata/dataset/engine/jagged_connector.h" using tinyxml2::XMLDocument; using tinyxml2::XMLElement; using tinyxml2::XMLError; namespace mindspore { namespace dataset { class JaggedConnector; /// \class IWSLTOp. /// \brief A Op derived class to represent IWSLT Op. class IWSLTOp : public NonMappableLeafOp { public: enum IWSLTType { kIWSLT2016, kIWSLT2017 }; /// \brief Constructor of IWSLTOp. /// \param[in] num_workers Number of worker threads reading data from yelp_review files. /// \param[in] num_samples The number of samples to be included in the dataset. /// \param[in] worker_connector_size Size of each internal queue. /// \param[in] op_connector_size Size of each queue in the connector that the child operator pulls from. /// \param[in] shuffle_files Whether or not to shuffle the files before reading data. /// \param[in] num_devices Number of devices that the dataset should be divided into. /// \param[in] device_id The device ID within num_devices. /// \param[in] data_schema Schema of dataset. /// \param[in] type Type of data set read. /// \param[in] dataset_dir Path to the root directory that contains the dataset. /// \param[in] usage Usage of this dataset, can be "train", "test", "valid" or "all" data. /// \param[in] language_pair List containing src and tgt language. /// \param[in] valid_set A string to identify validation set. /// \param[in] test_set A string to identify test set. IWSLTOp(int32_t num_workers, int64_t num_samples, int32_t worker_connector_size, int32_t op_connector_size, bool shuffle_files, int32_t num_devices, int32_t device_id, std::unique_ptr<DataSchema>, IWSLTType type, const std::string &dataset_dir, const std::string &usage, const std::vector<std::string> &language_pair, const std::string &valid_set, const std::string &test_set); /// \brief Destructor. ~IWSLTOp() = default; /// \brief A print method typically used for debugging. /// \param[out] out The output stream to write output to. /// \param[in] show_all A bool to control if you want to show all info or just a summary. void Print(std::ostream &out, bool show_all) const override; /// \brief Instantiates the internal queues and connectors. /// \return Status The error code returned. Status Init() override; /// \brief Function to count the number of samples in the IWSLT dataset. /// \param[in] type IWSLT data set version, which can be kIWSLT2016 and kIWSLT2017. /// \param[in] dataset_dir Path to the root directory that contains the dataset. /// \param[in] usage Part of dataset of IWSLT2017, can be "train", "valid", "test" or "all". /// \param[in] language_pair List containing src and tgt language. /// \param[in] valid_set A string to identify validation set. /// \param[in] test_set A string to identify test set. /// \param[out] count The total number of rows in file. /// \return Status The status code returned. static Status CountTotalRows(IWSLTType type, const std::string &dataset_dir, const std::string &usage, const std::vector<std::string> &language_pair, const std::string &valid_set, const std::string &test_set, int64_t *count); /// \brief Op name getter. /// \return std::string Name of the current Op. std::string Name() const override { return "IWSLTOp"; } /// \brief DatasetName name getter. /// \param[in] upper If true, the return value is uppercase, otherwise, it is lowercase. /// \return std::string DatasetName of the current Op. std::string DatasetName(bool upper = false) const { return upper? "IWSLT" : "iwslt"; } // \brief File names getter. // \return std::vector<std::string> Vector of the input file names. std::vector<std::string> FileNames() { return src_target_file_list_; } private: /// \brief Split string based on a character delimiter. /// \param[in] s The input string. /// \param[in] delim The delimiter. /// \return std::vector<std::string> The result after segmentation. std::vector<std::string> Split(const std::string &s, const std::string &delim); /// \brief Remove the characters specified at the beginning and end. /// \param[in] text The input string. /// \param[in] character The removed character. /// \return Status The status code returned. Status Trim(std::string *text, const std::string &character); /// \brief Function to count the number of samples in one data file. /// \param[in] file Path to the data file. /// \return int64_t The total number of rows in file. int64_t CountFileRows(const std::string &file); /// \brief Parses a single row and puts the data into a tensor table. /// \param[in] line The content of the row. /// \param[out] out_row Output tensor. /// \param[in] index The id of the row filled in the tensor table. /// \return Status The status code returned. Status LoadTensor(const std::string &line, TensorRow *out_row, size_t index); /// \brief Reads a IWSLT file and loads the data into multiple TensorRows. /// \param[in] file The file to read. /// \param[in] start_offset The start offset of file. /// \param[in] end_offset The end offset of file. /// \param[in] worker_id The id of the worker that is executing this function. /// \return Status The status code returned. Status LoadFile(const std::string &file, int64_t start_offset, int64_t end_offset, int32_t worker_id) override; /// \brief Fill the IOBlockQueue. /// \param[in] i_keys Keys of file to fill to the IOBlockQueue. /// \return Status The status code returned. Status FillIOBlockQueue(const std::vector<int64_t> &i_keys) override; /// \brief Calculate number of rows in each shard. /// \return Status The status code returned. Status CalculateNumRowsPerShard() override; /// \brief Private function for computing the assignment of the column name map. /// \return Status The status code returned. Status ComputeColMap() override; /// \brief Write the data of the source file and the target file to a new file after cleaning. /// \param[in] src_file_path Source file path. /// \param[in] target_file_path Target file path. /// \param[in] new_file_path Write data to new file path. /// \return Status The status code returned. Status CleanXmlFile(const std::string &src_file_path, const std::string &target_file_path, const std::string &new_file_path); /// \brief Determine whether the centent contains the specified label. /// \param[in] content This content to be determined. /// \return bool If it contains, return true, otherwise, return false. bool IsContainTags(const std::string &content); /// \brief Write the data of the source file and the target file to a new file after cleaning. /// \param[in] src_file_path Source file path. /// \param[in] target_file_path Target file path. /// \param[in] new_file_path Write data to new file path. /// \return Status The status code returned. Status CleanTagFile(const std::string &file_path, const std::string &target_file_path, const std::string &new_file_path); // \brief Get all files in the dataset_dir_. // \return Status The status code returned. Status GetFiles(); /// \brief Generate IWSLT2016 training data set file list. /// \param[in] dir The directory where the files are stored. /// \param[in] src_language The source language type. /// \param[in] target_language The target language type. /// \param[in] suffix The file suffix. /// \return std::string The file path. std::string GenerateIWSLT2016TagsFileName(Path dir, const std::string &src_language, const std::string &target_language, const std::string &suffix); /// \brief Generate IWSLT2016 valid data set or test data set file list. /// \param[in] dir The directory where the files are stored. /// \param[in] src_language The source language type. /// \param[in] target_language The target language type. /// \param[in] set_type The type of data set read. /// \param[in] suffix The file suffix. /// \return std::string The file path. std::string GenerateIWSLT2016XMLFileName(Path dir, const std::string &src_language, const std::string &target_language, const std::string &set_type, const std::string &suffix); /// \brief Generate IWSLT2017 training data set file list. /// \param[in] dir The directory where the files are stored. /// \param[in] src_language The source language type. /// \param[in] target_language The target language type. /// \param[in] suffix The file suffix. /// \return std::string The file path. std::string GenerateIWSLT2017TagsFileName(Path dir, const std::string &src_language, const std::string &target_language, const std::string &suffix); /// \brief Generate IWSLT2016 valid data set or test data set file list. /// \param[in] dir The directory where the files are stored. /// \param[in] src_language The source language type. /// \param[in] target_language The target language type. /// \param[in] set_type The type of data set read. /// \param[in] suffix The file suffix. /// \return std::string The file path. std::string GenerateIWSLT2017XMLFileName(Path dir, const std::string &src_language, const std::string &target_language, const std::string &set_type, const std::string &suffix); /// \brief Generate new file path and write data. /// \param[in] src_path_list The source file path. /// \param[in] target_path_list The target file path. /// \param[out] src_target_file_list The newly generated file path list. /// \return Status The status code returned. Status GenerateNewFile(const std::vector<std::string> &src_file_list, const std::vector<std::string> &target_file_list, std::vector<std::string> *src_target_file_list); IWSLTType iwslt_type_; std::unique_ptr<DataSchema> data_schema_; std::vector<std::string> src_target_file_list_; std::string dataset_dir_; std::string usage_; std::vector<std::string> language_pair_; std::string valid_set_; std::string test_set_; }; } // namespace dataset } // namespace mindspore #endif // MINDSPORE_CCSRC_MINDDATA_DATASET_ENGINE_DATASETOPS_SOURCE_IWSLT_OP_H_ ======================= File: mindspore/ccsrc/minddata/dataset/engine/datasetops/source/speech_commands_op.h ======================= <filename>mindspore/ccsrc/minddata/dataset/engine/datasetops/source/speech_commands_op.h<gh_stars>1-10 /** * 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. */ #ifndef MINDSPORE_CCSRC_MINDDATA_DATASET_ENGINE_DATASETOPS_SOURCE_SPEECH_COMMANDS_OP_H_ #define MINDSPORE_CCSRC_MINDDATA_DATASET_ENGINE_DATASETOPS_SOURCE_SPEECH_COMMANDS_OP_H_ #include <map> #include <memory> #include <set> #include <string> #include <utility> #include <vector> #include "minddata/dataset/core/tensor.h" #include "minddata/dataset/engine/data_schema.h" #include "minddata/dataset/engine/datasetops/parallel_op.h" #include "minddata/dataset/engine/datasetops/source/mappable_leaf_op.h" #include "minddata/dataset/engine/datasetops/source/sampler/sampler.h" #include "minddata/dataset/util/services.h" #include "minddata/dataset/util/status.h" #include "minddata/dataset/util/wait_post.h" namespace mindspore { namespace dataset { class SpeechCommandsOp : public MappableLeafOp { public: /// Constructor. /// \param[in] std::string - dataset_dir - directory of SpeechCommands dataset. /// \param[in] std::string - usage - directory of SpeechCommands dataset. /// \param[in] uint32_t - num_workers - Num of workers reading audios in parallel. /// \param[in] uint32_t - queue_size - connector queue size. /// \param[in] std::unique_ptr<DataSchema> - data_schema - data schema of SpeechCommands dataset. /// \param[in] std::unique_ptr<Sampler> - sampler - sampler tells SpeechCommands what to read. SpeechCommandsOp(const std::string &dataset_dir, const std::string &usage, int32_t num_workers, int32_t queue_size, std::unique_ptr<DataSchema> data_schema, std::shared_ptr<SamplerRT> sampler); /// Destructor. ~SpeechCommandsOp() override = default; /// A print method typically used for debugging. /// \param[out] out - out stream. /// \param[in] show_all - whether to show all information. void Print(std::ostream &out, bool show_all) const override; /// Function to count the number of samples in the SpeechCommands dataset. /// \param[in] num_rows output arg that will hold the actual dataset size. /// \return Status - The status code returned. Status CountTotalRows(int64_t *num_rows); /// Op name getter. /// \return Name of the current Op. std::string Name() const override { return "SpeechCommandsOp"; } private: /// Load a tensor row. /// \param[in] row_id - row id. /// \param[in] trow - waveform & sample_rate & label & speaker_id & utterance_number /// read into this tensor row. /// \return Status - The status code returned. Status LoadTensorRow(row_id_type row_id, TensorRow *trow) override; /// \param[in] pf_path - the real path of root directory. /// \param[in] pf_usage - usage. /// \return Status - The status code returned. Status ParseFileList(const std::string &pf_path, const std::string &pf_usage); /// Called first when function is called. /// \return Status - The status code returned. Status PrepareData(); /// Walk all folders to read all ".wav" files. /// \param[in] walk_path - real path to traverse. /// \return Status - The status code returned. Status WalkAllFiles(const std::string &walk_path); /// Get detail info of wave filename by regex. /// \param[in] file_path - wave file path. /// \param[out] label - label. /// \param[out] speaker_id - speaker id. /// \param[out] utterance_number - utterance number. /// \return Status - The status code returned. Status GetFileInfo(const std::string &file_path, std::string *label, std::string *speaker_id, int32_t *utterance_number); // Private function for computing the assignment of the column name map. /// \return Status - The status code returned. Status ComputeColMap() override; std::string dataset_dir_; std::string usage_; // can only be "test", "train", "valid" or "all". std::unique_ptr<DataSchema> data_schema_; std::set<std::string> all_wave_files; // all wave files in dataset_dir. std::set<std::string> loaded_names; // loaded file names from txt files. std::vector<std::string> selected_files_vec; // vector of filenames for sequential loading. }; } // namespace dataset } // namespace mindspore #endif // MINDSPORE_CCSRC_MINDDATA_DATASET_ENGINE_DATASETOPS_SOURCE_SPEECH_COMMANDS_OP_H_ ======================= File: mindspore/core/mindapi/ir/func_graph.h ======================= /** * 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. */ #ifndef MINDSPORE_CORE_MINDAPI_IR_FUNC_GRAPH_H_ #define MINDSPORE_CORE_MINDAPI_IR_FUNC_GRAPH_H_ #include <vector> #include <string> #include <utility> #include <memory> #include "mindapi/base/base.h" #include "mindapi/ir/common.h" #include "mindapi/ir/anf.h" #include "mindapi/ir/primitive.h" #include "mindapi/ir/value.h" #include "mindapi/ir/utils.h" namespace mindspore { class FuncGraphManager; } namespace mindspore::api { /// \brief FuncGraph defines interface for a function graph. class MIND_API FuncGraph : public Value { public: MIND_API_BASE_MEMBER(FuncGraph); /// \brief Get the input parameters. /// /// \return Input parameters of this graph. std::vector<AnfNodePtr> get_inputs() const; /// \brief Get all parameters. /// /// \return All parameters of this graph. std::vector<AnfNodePtr> parameters() const; /// \brief Adds a parameter to this graph. /// /// \param[in] p The parameter to be added. void add_parameter(const ParameterPtr &p); /// \brief Adds a new parameter to this graph. /// /// \return The new added parameter. ParameterPtr add_parameter(); /// \brief Get the output node. /// /// \return The output node, nullptr if output not set. AnfNodePtr output() const; /// \brief Get the return CNode. /// /// \return The return CNode, nullptr if no return node. CNodePtr get_return() const; /// \brief Set the output node. /// /// \param[in] value The output node to be set. /// \param[in] force_new_ret If true, a new return node is always created. void set_output(const AnfNodePtr &value, bool force_new_ret = false); /// \brief Set the return node. /// /// \param[in] cnode The return CNode to be set. void set_return(const CNodePtr &cnode); /// \brief Creates a new CNode in this graph. /// /// \param[in] inputs The input nodes of the new CNode. /// /// \return The created CNode. CNodePtr NewCNode(const std::vector<AnfNodePtr> &inputs = std::vector<AnfNodePtr>()); /// \brief Creates a new primitive CNode in this graph. /// /// \param[in] primitive The primitive of the new CNode. /// \param[in] prim_inputs The argument inputs of the primitive CNode. /// /// \return The created primitive CNode. CNodePtr NewCNode(const PrimitivePtr &primitive, const std::vector<AnfNodePtr> &prim_inputs); /// \brief Get all nodes in this graph. /// /// \return All nodes in this graph. std::vector<AnfNodePtr> nodes() const; /// \brief Check whether an attribute is set for this graph. /// /// \param[in] key The attribute key (name). /// /// \return True if the attribute with the given key is set, false otherwise. bool has_attr(const std::string &key) const; /// \brief Get an attribute value by its key. /// /// \param[in] key The attribute key (name). /// /// \return The attribute value for the given key, nullptr if attribute not found. ValuePtr get_attr(const std::string &key) const; /// \brief Set an attribute value. /// /// \param[in] key The attribute key (name). /// \param[in] value The attribute value. void set_attr(const std::string &key, const ValuePtr &value); /// \brief Get the manager for this graph. /// /// \return The manager of this graph, nullptr if not set. FuncGraphManagerPtr manager() const; /// \brief Creates an empty function graph. /// /// \return The created function graph. static FuncGraphPtr Create(); /// \brief Topological sort a graph from the given end node. /// /// \param[in] node The end node of the graph to be sorted. /// /// \return The sorted nodes. static std::vector<AnfNodePtr> TopoSort(const AnfNodePtr &node); }; /// \brief FuncGraphManager defines interface for function graph management. class MIND_API FuncGraphManager { public: /// \brief Create FuncGraphManager with the given implementor object. /// /// \param[in] impl The pointer to the implementor object. explicit FuncGraphManager(const std::shared_ptr<mindspore::FuncGraphManager> &impl); /// \brief Get the shared_ptr to the underly implementation object. /// /// \return The shared_ptr to the underly implementation object. const std::shared_ptr<mindspore::FuncGraphManager> &impl() const { return impl_; } /// \brief Replace an old node with a new node, related edges are all updated. /// /// \param[in] old_node The old node to be replaced. /// \param[in] new_node The new node that replace the old one. /// /// \return True if the node is successfully replaced, false otherwise. bool Replace(const AnfNodePtr &old_node, const AnfNodePtr &new_node); /// \brief Change an existed edge by replace its input node. /// /// \param[in] node The output node of the edge. /// \param[in] index The input index in output node. /// \param[in] value The new input node of the edge. void SetEdge(const AnfNodePtr &node, int index, const AnfNodePtr &value); /// \brief Adds a new edge between the given two nodes. /// /// \param[in] node The output node of the edge. /// \param[in] value The input node of the edge. void AddEdge(const AnfNodePtr &node, const AnfNodePtr &value); /// \brief Find users of the given node. /// /// \param[in] node The node. /// /// \return Users of the given node, empty if user not found. std::vector<std::pair<AnfNodePtr, int>> GetUsers(const AnfNodePtr &node) const; /// \brief Manage the give function graph. /// /// \param[in] func_graph The function graph to be managed. /// \param[in] manage If true, the created manager will be set in the graph. /// /// \return The manager that manages the given function graph. static FuncGraphManagerPtr Manage(const FuncGraphPtr &func_graph, bool manage = true); private: const std::shared_ptr<mindspore::FuncGraphManager> impl_; }; } // namespace mindspore::api #endif // MINDSPORE_CORE_MINDAPI_IR_FUNC_GRAPH_H_ ======================= File: mindspore/ccsrc/backend/kernel_compiler/cpu/nnacl/fp16/range_fp16.h ======================= <filename>mindspore/ccsrc/backend/kernel_compiler/cpu/nnacl/fp16/range_fp16.h /** * 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. */ #ifndef MINDSPORE_NNACL_FP16_RANGE_FP16_H_ #define MINDSPORE_NNACL_FP16_RANGE_FP16_H_ #include "nnacl/op_base.h" #ifdef __cplusplus extern "C" { #endif inline void RangeFp16(float16_t *output_ptr, float16_t start, float16_t delta, int nums) { for (int i = 0; i < nums; ++i, start += delta) { output_ptr[i] = start; } } #ifdef __cplusplus } #endif #endif // MINDSPORE_NNACL_FP16_RANGE_FP16_H_ ======================= File: mindspore/lite/tools/common/tensor_util.h ======================= /** * Copyright 2020-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. */ #ifndef MINDSPORE_LITE_TOOLS_COMMON_TENSOR_UTIL_H #define MINDSPORE_LITE_TOOLS_COMMON_TENSOR_UTIL_H #include <cmath> #include <unordered_map> #include <memory> #include <algorithm> #include <utility> #include <string> #include <vector> #include <random> #include <cfloat> #include "schema/inner/model_generated.h" #include "src/common/log_adapter.h" #include "ir/dtype/type_id.h" #include "ir/tensor.h" #include "src/common/utils.h" #include "tools/common/statistic_utils.h" #include "src/tensor.h" namespace mindspore { namespace lite { using schema::CNodeT; using schema::Format; using schema::FusedBatchNormT; using schema::MetaGraphT; using schema::QuantParamT; using schema::TensorT; std::unique_ptr<QuantParamT> GetTensorQuantParam(const std::unique_ptr<TensorT> &tensor); tensor::TensorPtr CreateTensorInfo(const void *data, size_t data_size, const std::vector<int64_t> &shape, TypeId data_type); AbstractBasePtr CreateTensorAbstract(const std::vector<int64_t> &shape, TypeId data_type); int SetParameterAbstractAndParam(const ParameterPtr &parameter, const void *data, size_t data_size, const std::vector<int64_t> &shape, TypeId data_type); int SetTensorData(const tensor::TensorPtr &tensor_info, const void *data, size_t data_size); std::unique_ptr<schema::TensorT> CreateTensorTFromTensorInfo(const tensor::TensorPtr &tensor_info, const std::string &tensor_name = ""); int UpdateTensorTFromTensorInfo(const tensor::TensorPtr &src_tensor, std::unique_ptr<schema::TensorT> *dst_tensor); int InitParameterFromTensorInfo(const ParameterPtr &param_node, const tensor::TensorPtr &tensor_info); size_t GetElementSize(const TensorT &tensor); size_t GetElementSize(const TypeId &dataType); size_t GetShapeSize(const TensorT &tensor); size_t GetShapeSize(const std::vector<int32_t> &shape); std::unique_ptr<TensorT> CopyTensorDefT(const std::unique_ptr<TensorT> &); size_t GetRefCount(schema::MetaGraphT *graphT, uint32_t tensorIdx); std::unique_ptr<schema::QuantParamT> CopyQuantParamT(const std::unique_ptr<schema::QuantParamT> &srcQuantParam); int GenerateRandomData(mindspore::tensor::MSTensor *tensors); int GenerateRandomData(size_t size, void *data, int data_type); template <typename T, typename Distribution> void FillInputData(size_t size, void *data, Distribution distribution) { std::mt19937 random_engine; MS_ASSERT(data!= nullptr); size_t elements_num = size / sizeof(T); (void)std::generate_n(static_cast<T *>(data), elements_num, [&]() { return static_cast<T>(distribution(random_engine)); }); } struct CheckTensor { CheckTensor(const std::string &tensor_name, const std::vector<size_t> &shape, const std::vector<float> &data, const std::vector<std::string> &strings_data = {""}) { this->tensor_name = tensor_name; this->shape = shape; this->data = data; this->strings_data = strings_data; } std::string tensor_name; std::vector<size_t> shape; std::vector<float> data; std::vector<std::string> strings_data; }; // tensorData need to be converter first template <typename T> float CompareDataByCosineDistance(const std::unordered_map<String, mindspore::tensor::MSTensor *> &calib_tensors, const std::unordered_map<String, mindspore::tensor::MSTensor *> &out_tensors) { if (calib_tensors.empty() || out_tensors.empty()) { MS_LOG(ERROR) << "calib or out tenor is empty."; return RET_ERROR; } float total_cos = 0; for (const auto &calib : calib_tensors) { size_t error_count = 0; float mean_error = 0; auto calib_tensor = calib.second; auto calib_data = static_cast<const T *>(calib_tensor->data()); auto out_tensor_iter = out_tensors.find(calib_tensor->tensor_name()); if (out_tensor_iter == out_tensors.end()) { MS_LOG(ERROR) << "Cant find " << calib_tensor->tensor_name() << " in out_tensors"; return RET_ERROR; } auto out_tensor = out_tensor_iter->second; auto out_data = static_cast<const T *>(out_tensor->data()); auto cos = mindspore::lite::GetCosSimilarity<T>(calib_data, out_data, out_tensor->ElementsNum()); total_cos += cos; MS_LOG(INFO) << "tensor_name:" << calib_tensor->tensor_name() << " cos_sim: " << mean_error << " error_count:" << error_count; } return total_cos / calib_tensors.size(); } template <typename T> float CompareData(const std::unordered_map<String, mindspore::tensor::MSTensor *> &calib_tensors, const std::unordered_map<String, mindspore::tensor::MSTensor *> &out_tensors) { if (calib_tensors.empty() || out_tensors.empty()) { MS_LOG(ERROR) << "calib or out tenor is empty."; return RET_ERROR; } float total_meam_error = 0; for (const auto &calib : calib_tensors) { size_t error_count = 0; float mean_error = 0; auto calib_tensor = calib.second; auto calib_data = static_cast<const T *>(calib_tensor->data()); auto out_tensor_iter = out_tensors.find(calib_tensor->tensor_name()); if (out_tensor_iter == out_tensors.end()) { MS_LOG(ERROR) << "Cant find " << calib_tensor->tensor_name() << " in out_tensors"; return RET_ERROR; } auto out_tensor = out_tensor_iter->second; auto out_data = static_cast<const T *>(out_tensor->data()); for (int j = 0; j < calib_tensor->ElementsNum(); j++) { if (std::is_same<T, float>::value && (std::isnan(out_data[j]) || std::isinf(out_data[j]))) { MS_LOG(ERROR) << "Output tensor has nan or inf data, compare fail"; return RET_ERROR; } constexpr float relativeTolerance = 1e-5; constexpr float absoluteTolerance = 1e-8; auto tolerance = absoluteTolerance + relativeTolerance * fabs(calib_data[j]); auto absolute_error = std::fabs(out_data[j] - calib_data[j]); if (absolute_error > tolerance) { if (fabs(calib_data[j] - 0.0f) < FLT_EPSILON) { if (absolute_error > 1e-5) { mean_error += absolute_error; error_count++; } else { continue; } } else { // just assume that atol = rtol mean_error += absolute_error / (fabs(calib_data[j]) + FLT_MIN); error_count++; } } } if (mean_error > 0.0f) { mean_error /= error_count; } total_meam_error += std::abs(mean_error); MS_LOG(INFO) << "tensor_name:" << calib_tensor->tensor_name() << " mean_error: " << mean_error << " error_count:" << error_count; } return total_meam_error / calib_tensors.size(); } } // namespace lite } // namespace mindspore #endif // MINDSPORE_LITE_TOOLS_COMMON_TENSOR_UTIL_H ======================= File: mindspore/ccsrc/minddata/dataset/kernels/image/cutmix_batch_op.h ======================= /** * Copyright 2020 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef MINDSPORE_CCSRC_MINDDATA_DATASET_KERNELS_IMAGE_CUTMIXBATCH_OP_H_ #define MINDSPORE_CCSRC_MINDDATA_DATASET_KERNELS_IMAGE_CUTMIXBATCH_OP_H_ #include <memory> #include <vector> #include <random> #include <string> #include "minddata/dataset/core/tensor.h" #include "minddata/dataset/kernels/tensor_op.h" #include "minddata/dataset/util/status.h" namespace mindspore { namespace dataset { class CutMixBatchOp : public TensorOp { public: explicit CutMixBatchOp(ImageBatchFormat image_batch_format, float alpha, float prob); ~CutMixBatchOp() override = default; void Print(std::ostream &out) const override; void GetCropBox(int width, int height, float lam, int *x, int *y, int *crop_width, int *crop_height); Status Compute(const TensorRow &input, TensorRow *output) override; std::string Name() const override { return kCutMixBatchOp; } private: /// \brief Helper function used in Compute to validate the input TensorRow. /// \param[in] input Input TensorRow of CutMixBatchOp /// \returns Status Status ValidateCutMixBatch(const TensorRow &input); /// \brief Helper function used in Compute to compute each image. /// \param[in] input Input TensorRow of CutMixBatchOp. /// \param[in] rand_indx_i The i-th generated random index as the start address of the input image. /// \param[in] lam A random variable follow Beta distribution, used in GetCropBox. /// \param[in] label_lam Lambda used for labels, will be updated after computing each image. /// \param[in] image_i The result of the i-th computed image. /// \returns Status Status ComputeImage(const TensorRow &input, const int64_t rand_indx_i, const float lam, float *label_lam, std::shared_ptr<Tensor> *image_i); /// \brief Helper function used in Compute to compute each label corresponding to each image. /// \param[in] input Input TensorRow of CutMixBatchOp. /// \param[in] rand_indx_i The i-th generated random index as the start address of the input image. /// \param[in] index_i The i-th label to be generated, corresponding to the i-th computed image. /// \param[in] row_labels Number of rows of the label. /// \param[in] num_classes Number of class of the label. /// \param[in] label_shape_size The size of the label shape from input TensorRow. /// \param[in] label_lam Lambda used for setting the location. /// \param[in] out_labels The output of the i-th label, corresponding to the i-th computed image. /// \returns Status Status ComputeLabel(const TensorRow &input, const int64_t rand_indx_i, const int64_t index_i, const int64_t row_labels, const int64_t num_classes, const std::size_t label_shape_size, const float label_lam, std::shared_ptr<Tensor> *out_labels); float alpha_; float prob_; ImageBatchFormat image_batch_format_; std::mt19937 rnd_; }; } // namespace dataset } // namespace mindspore #endif // MINDSPORE_CCSRC_MINDDATA_DATASET_KERNELS_IMAGE_CUTMIXBATCH_OP_H_ ======================= File: mindspore/ccsrc/minddata/dataset/engine/datasetops/source/lj_speech_op.h ======================= <filename>mindspore/ccsrc/minddata/dataset/engine/datasetops/source/lj_speech_op.h /** * 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. */ #ifndef MINDSPORE_CCSRC_MINDDATA_DATASET_ENGINE_DATASETOPS_SOURCE_LJ_SPEECH_OP_H_ #define MINDSPORE_CCSRC_MINDDATA_DATASET_ENGINE_DATASETOPS_SOURCE_LJ_SPEECH_OP_H_ #include <memory> #include <string> #include <vector> #include "minddata/dataset/core/tensor.h" #include "minddata/dataset/engine/data_schema.h" #include "minddata/dataset/engine/datasetops/source/mappable_leaf_op.h" #include "minddata/dataset/engine/datasetops/source/sampler/sampler.h" #include "minddata/dataset/util/services.h" #include "minddata/dataset/util/status.h" #include "minddata/dataset/util/wait_post.h" namespace mindspore { namespace dataset { /// \brief Read LJSpeech dataset. class LJSpeechOp : public MappableLeafOp { public: /// \brief Constructor. /// \param[in] file_dir Directory of lj_speech dataset. /// \param[in] num_workers Number of workers reading audios in parallel. /// \param[in] queue_size Connector queue size. /// \param[in] data_schema Data schema of lj_speech dataset. /// \param[in] sampler Sampler tells LJSpeechOp what to read. LJSpeechOp(const std::string &file_dir, int32_t num_workers, int32_t queue_size, std::unique_ptr<DataSchema> data_schema, std::shared_ptr<SamplerRT> sampler); /// \brief Destructor. ~LJSpeechOp() = default; /// \brief A print method typically used for debugging. /// \param[out] out The output stream to write output to. /// \param[in] show_all A bool to control if you want to show all info or just a summary. void Print(std::ostream &out, bool show_all) const override; /// \brief Function to count the number of samples in the LJSpeech dataset. /// \param[in] dir Path to the directory of LJSpeech dataset. /// \param[out] count Output arg that will hold the actual dataset size. /// \return Status static Status CountTotalRows(const std::string &dir, int64_t *count); /// \brief Op name getter. /// \return Name of the current Op. std::string Name() const override { return "LJSpeechOp"; } protected: /// \brief Called first when function is called. /// \return Status Status PrepareData() override; private: /// \brief Load a tensor row. /// \param[in] index Index need to load. /// \param[out] trow Waveform & sample_rate & transcription & normalized_transcription read into this tensor row. /// \return Status the status code returned. Status LoadTensorRow(row_id_type index, TensorRow *trow) override; /// \brief Private function for computing the assignment of the column name map. /// \return Status Status ComputeColMap() override; std::string folder_path_; std::unique_ptr<DataSchema> data_schema_; std::vector<std::vector<std::string>> meta_info_list_; // the shape is (N, 3) }; } // namespace dataset } // namespace mindspore #endif // MINDSPORE_CCSRC_MINDDATA_DATASET_ENGINE_DATASETOPS_SOURCE_LJ_SPEECH_OP_H_ ======================= File: mindspore/ccsrc/minddata/dataset/callback/py_ds_callback.h ======================= /** * Copyright 2020 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef MINDSPORE_CCSRC_MINDDATA_DATASET_PY_DS_CALLBACK_H #define MINDSPORE_CCSRC_MINDDATA_DATASET_PY_DS_CALLBACK_H #include <memory> #include <utility> #include <vector> #include "minddata/dataset/callback/ds_callback.h" #include "minddata/dataset/util/status.h" #include "pybind11/pybind11.h" namespace mindspore { namespace dataset { namespace py = pybind11; class PyDSCallback : public DSCallback { public: /// \brief constructor for PyDSCallback. This callback is for python front end explicit PyDSCallback(int32_t step_size = 1) : DSCallback(step_size), begin_needed_(false), epoch_begin_needed_(false), step_begin_needed_(false), end_needed_(false), epoch_end_needed_(false), step_end_needed_(false) {} ~PyDSCallback() = default; void SetBegin(const py::function &f); void SetEnd(const py::function &f); void SetEpochBegin(const py::function &f); void SetEpochEnd(const py::function &f); void SetStepBegin(const py::function &f); void SetStepEnd(const py::function &f); /// \brief actual callback function for begin, needs to be overridden in the derived class /// \param cb_param, callback parameter passed in from DatasetOp when calling the callback /// \return Status Status DSBegin(const CallbackParam &cb_param) override; /// \brief actual callback function for epoch_begin, needs to be overridden in the derived class /// \param cb_param, callback parameter passed in from DatasetOp when calling the callback /// \return Status Status DSEpochBegin(const CallbackParam &cb_param) override; /// \brief actual callback function for step_begin, needs to be overridden in the derived class /// \param cb_param, callback parameter passed in from DatasetOp when calling the callback /// \return Status Status DSNStepBegin(const CallbackParam &cb_param) override; /// \brief actual callback function for end, needs to be overridden in the derived class /// \param cb_param, callback parameter passed in from DatasetOp when calling the callback /// \return Status Status DSEnd(const CallbackParam &cb_param) override; /// \brief actual callback function epoch_end begin, needs to be overridden in the derived class /// \param cb_param, callback parameter passed in from DatasetOp when calling the callback /// \return Status Status DSEpochEnd(const CallbackParam &cb_param) override; /// \brief actual callback function for step_end, needs to be overridden in the derived class /// \param cb_param, callback parameter passed in from DatasetOp when calling the callback /// \return Status Status DSNStepEnd(const CallbackParam &cb_param) override; /// \brief predicate function, whether begin callback is needed /// \return bool bool IsBeginNeeded() override; /// \brief predicate function, whether epoch_begin callback is needed /// \return bool bool IsEpochBeginNeeded() override; /// \brief predicate function, whether step_begin callback is needed /// \return bool bool IsNStepBeginNeeded() override; /// \brief predicate function, whether end callback is needed /// \return bool bool IsEndNeeded() override; /// \brief predicate function, whether epoch_end callback is needed /// \return bool bool IsEpochEndNeeded() override; /// \brief predicate function, whether step_end callback is needed /// \return bool bool IsNStepEndNeeded() override; /// \brief helper function to acquire GIL then execute a pyfunc /// \param f the python function /// \param cb_param /// \return Status static Status ExecutePyfunc(py::function f, const CallbackParam &cb_param); private: py::function begin_func_; py::function epoch_begin_func_; py::function step_begin_func_; py::function end_func_; py::function epoch_end_func_; py::function step_end_func_; bool begin_needed_; bool epoch_begin_needed_; bool step_begin_needed_; bool end_needed_; bool epoch_end_needed_; bool step_end_needed_; }; } // namespace dataset } // namespace mindspore #endif // MINDSPORE_CCSRC_MINDDATA_DATASET_PY_DS_CALLBACK_H ======================= File: mindspore/lite/tools/converter/adapter/dpico/src/calib_data_generator.h ======================= /** * 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. */ #ifndef DPICO_SRC_CALIB_DATA_GENERATOR_H_ #define DPICO_SRC_CALIB_DATA_GENERATOR_H_ #include <fstream> #include <numeric> #include <vector> #include <string> #include <functional> #include <map> #include <memory> #include <utility> #include "include/registry/converter_context.h" #include "common/data_transpose_utils.h" #include "ir/anf.h" #include "include/errorcode.h" #include "common/check_base.h" namespace mindspore { namespace dpico { struct OpAttr { std::string data_type; size_t input_output_idx; std::vector<int32_t> shape; std::string format; }; struct DumpOpInfo { std::string origin_op_name; std::string dump_op_name; int input_index; int output_index; }; class CalibDataGenerator { public: explicit CalibDataGenerator(int dump_level = 0, const std::map<AnfNodePtr, std::pair<CNodePtr, int>> &control_flow_inputs = {}) : dump_level_(dump_level), control_flow_inputs_(control_flow_inputs) {} ~CalibDataGenerator() = default; int Run(const AnfNodePtrList &graph_inputs, const AnfNodePtrList &nodes); private: int GenerateDumpConfig(const std::string &dump_cfg_path, const std::vector<DumpOpInfo> &dump_infos); std::string GetInputShapesStr(const AnfNodePtrList &graph_inputs); std::vector<std::string> GetInDataFileList(const AnfNodePtrList &graph_inputs); int DumpKernelsData(const std::string &dump_cfg_path, const std::vector<std::string> &in_data_file_list, const std::string &input_shapes_str); STATUS ParseAttrFromFilename(struct OpAttr *op_attr, const std::string &file_name, bool is_input); int TransBinsToTxt(const std::vector<DumpOpInfo> &dump_infos); template <typename T> int ReadBinToOfstream(const std::string &file_path, const struct OpAttr &op_attr, std::ofstream &ofs) { std::ifstream ifs; ifs.open(file_path, std::ifstream::in | std::ios::binary); if (!ifs.is_open() ||!ifs.good()) { MS_LOG(ERROR) << "open file failed. " << file_path; return RET_ERROR; } size_t shape_size = 1; for (size_t i = 0; i < op_attr.shape.size(); i++) { if (op_attr.shape.at(i) < 0) { MS_LOG(ERROR) << "dim val should be greater than 0"; return RET_ERROR; } if (SIZE_MUL_OVERFLOW(shape_size, static_cast<size_t>(op_attr.shape.at(i)))) { MS_LOG(ERROR) << "size_t mul overflow."; return RET_ERROR; } shape_size *= static_cast<size_t>(op_attr.shape.at(i)); } ifs.seekg(0, std::ios::end); size_t file_size = ifs.tellg(); if (file_size!= shape_size * sizeof(T)) { MS_LOG(ERROR) << "file size " << file_size << " is not equal to shape size " << shape_size; return RET_ERROR; } auto raw_datas = std::make_unique<T[]>(shape_size); if (raw_datas == nullptr) { MS_LOG(ERROR) << "new T failed."; return RET_ERROR; } ifs.seekg(0, std::ios::beg); ifs.read(reinterpret_cast<char *>(raw_datas.get()), shape_size * sizeof(T)); ifs.close(); if (op_attr.format == "NHWC" && op_attr.shape.size() == kDims4) { auto dst_datas = std::make_unique<T[]>(shape_size); if (dst_datas == nullptr) { MS_LOG(ERROR) << "new T failed."; return RET_ERROR; } if (memcpy_s(dst_datas.get(), shape_size * sizeof(T), raw_datas.get(), shape_size * sizeof(T))!= EOK) { MS_LOG(ERROR) << "memcpy_s failed."; return RET_ERROR; } if (NHWC2NCHW<T>(raw_datas.get(), dst_datas.get(), op_attr.shape)!= RET_OK) { MS_LOG(ERROR) << "NHWC to NCHW failed."; return RET_ERROR; } for (size_t i = 0; i < shape_size; i++) { ofs << dst_datas.get()[i] <<''; } } else { for (size_t i = 0; i < shape_size; i++) { ofs << raw_datas.get()[i] <<''; } } return RET_OK; } int dump_level_; std::map<AnfNodePtr, std::pair<CNodePtr, int>> control_flow_inputs_; }; } // namespace dpico } // namespace mindspore #endif // DPICO_SRC_CALIB_DATA_GENERATOR_H_ ======================= File: mindspore/ccsrc/common/thread_pool.h ======================= /** * Copyright 2020 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef MINDSPORE_CCSRC_COMMON_THREAD_POOL_H_ #define MINDSPORE_CCSRC_COMMON_THREAD_POOL_H_ #include <mutex> #include <condition_variable> #include <thread> #include <vector> #include <queue> #include <string> #include <atomic> #include <memory> #include <utility> #include <functional> #include <iostream> #include "utils/log_adapter.h" namespace mindspore { namespace common { enum Status { FAIL = -1, SUCCESS = 0 }; using Task = std::function<int()>; struct ThreadContext { std::mutex mutex; std::condition_variable cond_var; const Task *task{nullptr}; }; class ThreadPool { public: ~ThreadPool(); ThreadPool(const ThreadPool &) = delete; ThreadPool &operator=(const ThreadPool &) = delete; static ThreadPool &GetInstance(); bool SyncRun(const std::vector<Task> &tasks); size_t GetSyncRunThreadNum() { return max_thread_num_; } void ClearThreadPool(); private: ThreadPool(); void SyncRunLoop(const std::shared_ptr<ThreadContext> &context); size_t max_thread_num_{1}; std::mutex pool_mtx_; std::atomic_bool exit_run_ = {false}; std::vector<std::thread> sync_run_threads_{}; std::vector<std::shared_ptr<ThreadContext>> contexts_; }; } // namespace common } // namespace mindspore #endif // MINDSPORE_CCSRC_COMMON_THREAD_POOL_H_ ======================= File: mindspore/ccsrc/backend/kernel_compiler/cpu/nnacl/infer/split_with_over_lap_infer.c ======================= <filename>mindspore/ccsrc/backend/kernel_compiler/cpu/nnacl/infer/split_with_over_lap_infer.c /** * 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. */ #include "nnacl/infer/split_with_over_lap_infer.h" #include "nnacl/infer/infer_register.h" #include "nnacl/op_base.h" int SplitWithOverlapInferShape(const TensorC *const *inputs, size_t inputs_size, TensorC **outputs, size_t outputs_size, OpParameter *parameter) { int check_ret = CheckAugmentWithMinSize(inputs, inputs_size, outputs, outputs_size, parameter, 1, 1); if (check_ret!= NNACL_OK) { return check_ret; } if (!InferFlag(inputs, inputs_size)) { return NNACL_INFER_INVALID; } const TensorC *input = inputs[0]; SplitWithOverlapParameter *param = (SplitWithOverlapParameter *)parameter; int split_dim = param->split_dim_; int number_split = param->num_split_; if (outputs_size!= number_split) { return NNACL_ERR; } int ratio[SPLIT_MAX_SLICE_NUM]; int extend_top[SPLIT_MAX_SLICE_NUM]; int extend_bottom[SPLIT_MAX_SLICE_NUM]; for (int i = 0; i < number_split; ++i) { ratio[i] = param->ratio_[i]; extend_top[i] = param->extend_top_[i]; extend_bottom[i] = param->extend_bottom_[i]; } const int *input_shape = input->shape_; int split_dim_size = input_shape[split_dim]; int total_block_count = 0; for (int i = 0; i < number_split; i++) { total_block_count += ratio[i]; } int borders[MAX_SHAPE_SIZE]; borders[0] = 0; int visited_block = 0; for (int i = 0; i < number_split - 1; i++) { visited_block += ratio[i]; MS_CHECK_FALSE(INT_MUL_OVERFLOW(split_dim_size, visited_block) || total_block_count == 0, NNACL_ERR); int cur_border = UP_DIV(split_dim_size * visited_block, total_block_count); borders[i + 1] = cur_border; } borders[number_split] = split_dim_size; for (int i = 0; i < number_split; ++i) { int output_shape[MAX_SHAPE_SIZE]; for (int dim = 0; dim < input->shape_size_; dim++) { if (dim == split_dim) { int splited_size = borders[i + 1] - borders[i]; splited_size += (extend_top[i] + extend_bottom[i]); output_shape[dim] = splited_size; } else { output_shape[dim] = input_shape[dim]; } } SetShapeArray(outputs[i], output_shape, input->shape_size_); SetDataTypeFormat(outputs[i], input); } return NNACL_OK; } REG_INFER(SplitWithOverlap, PrimType_SplitWithOverlap, SplitWithOverlapInferShape) ======================= File: include/api/dual_abi_helper.h ======================= <filename>include/api/dual_abi_helper.h<gh_stars>100-1000 /** * 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. */ #ifndef MINDSPORE_INCLUDE_API_DUAL_ABI_HELPER_H_ #define MINDSPORE_INCLUDE_API_DUAL_ABI_HELPER_H_ #include <algorithm> #include <iterator> #include <map> #include <memory> #include <string> #include <set> #include <unordered_map> #include <utility> #include <vector> namespace mindspore { inline std::vector<char> StringToChar(const std::string &s) { return std::vector<char>(s.begin(), s.end()); } inline std::string CharToString(const std::vector<char> &c) { return std::string(c.begin(), c.end()); } inline std::pair<std::vector<char>, int32_t> PairStringToChar(const std::pair<std::string, int32_t> &s) { return std::pair<std::vector<char>, int32_t>(std::vector<char>(s.first.begin(), s.first.end()), s.second); } inline std::pair<std::string, int32_t> PairCharToString(const std::pair<std::vector<char>, int32_t> &c) { return std::pair<std::string, int32_t>(std::string(c.first.begin(), c.first.end()), c.second); } inline std::vector<std::vector<char>> VectorStringToChar(const std::vector<std::string> &s) { std::vector<std::vector<char>> ret; std::transform(s.begin(), s.end(), std::back_inserter(ret), [](auto str) { return std::vector<char>(str.begin(), str.end()); }); return ret; } inline std::vector<std::string> VectorCharToString(const std::vector<std::vector<char>> &c) { std::vector<std::string> ret; std::transform(c.begin(), c.end(), std::back_inserter(ret), [](auto ch) { return std::string(ch.begin(), ch.end()); }); return ret; } inline std::set<std::vector<char>> SetStringToChar(const std::set<std::string> &s) { std::set<std::vector<char>> ret; std::transform(s.begin(), s.end(), std::inserter(ret, ret.begin()), [](auto str) { return std::vector<char>(str.begin(), str.end()); }); return ret; } inline std::set<std::string> SetCharToString(const std::set<std::vector<char>> &c) { std::set<std::string> ret; std::transform(c.begin(), c.end(), std::inserter(ret, ret.begin()), [](auto ch) { return std::string(ch.begin(), ch.end()); }); return ret; } inline std::map<std::vector<char>, int32_t> MapStringToChar(const std::map<std::string, int32_t> &s) { std::map<std::vector<char>, int32_t> ret; std::transform(s.begin(), s.end(), std::inserter(ret, ret.begin()), [](auto str) { return std::pair<std::vector<char>, int32_t>(std::vector<char>(str.first.begin(), str.first.end()), str.second); }); return ret; } inline std::map<std::string, int32_t> MapCharToString(const std::map<std::vector<char>, int32_t> &c) { std::map<std::string, int32_t> ret; std::transform(c.begin(), c.end(), std::inserter(ret, ret.begin()), [](auto ch) { return std::pair<std::string, int32_t>(std::string(ch.first.begin(), ch.first.end()), ch.second); }); return ret; } inline std::map<std::vector<char>, std::vector<char>> UnorderedMapStringToChar( const std::unordered_map<std::string, std::string> &s) { std::map<std::vector<char>, std::vector<char>> ret; std::transform(s.begin(), s.end(), std::inserter(ret, ret.begin()), [](auto str) { return std::pair<std::vector<char>, std::vector<char>>(std::vector<char>(str.first.begin(), str.first.end()), std::vector<char>(str.second.begin(), str.second.end())); }); return ret; } inline std::unordered_map<std::string, std::string> UnorderedMapCharToString( const std::map<std::vector<char>, std::vector<char>> &c) { std::unordered_map<std::string, std::string> ret; std::transform(c.begin(), c.end(), std::inserter(ret, ret.begin()), [](auto ch) { return std::pair<std::string, std::string>(std::string(ch.first.begin(), ch.first.end()), std::string(ch.second.begin(), ch.second.end())); }); return ret; } inline std::map<std::vector<char>, std::vector<char>> MapStringToVectorChar( const std::map<std::string, std::string> &s) { std::map<std::vector<char>, std::vector<char>> ret; std::transform(s.begin(), s.end(), std::inserter(ret, ret.begin()), [](auto str) { return std::pair<std::vector<char>, std::vector<char>>(std::vector<char>(str.first.begin(), str.first.end()), std::vector<char>(str.second.begin(), str.second.end())); }); return ret; } inline std::map<std::string, std::string> MapVectorCharToString( const std::map<std::vector<char>, std::vector<char>> &c) { std::map<std::string, std::string> ret; std::transform(c.begin(), c.end(), std::inserter(ret, ret.begin()), [](auto ch) { return std::pair<std::string, std::string>(std::string(ch.first.begin(), ch.first.end()), std::string(ch.second.begin(), ch.second.end())); }); return ret; } inline std::vector<std::pair<std::vector<char>, std::vector<int32_t>>> ClassIndexStringToChar( const std::vector<std::pair<std::string, std::vector<int32_t>>> &s) { std::vector<std::pair<std::vector<char>, std::vector<int32_t>>> ret; std::transform(s.begin(), s.end(), std::back_inserter(ret), [](auto str) { return std::pair<std::vector<char>, std::vector<int32_t>>(std::vector<char>(str.first.begin(), str.first.end()), str.second); }); return ret; } inline std::vector<std::pair<std::string, std::vector<int32_t>>> ClassIndexCharToString( const std::vector<std::pair<std::vector<char>, std::vector<int32_t>>> &c) { std::vector<std::pair<std::string, std::vector<int32_t>>> ret; std::transform(c.begin(), c.end(), std::back_inserter(ret), [](auto ch) { return std::pair<std::string, std::vector<int32_t>>(std::string(ch.first.begin(), ch.first.end()), ch.second); }); return ret; } inline std::vector<std::pair<std::vector<char>, int64_t>> PairStringInt64ToPairCharInt64( const std::vector<std::pair<std::string, int64_t>> &s) { std::vector<std::pair<std::vector<char>, int64_t>> ret; std::transform(s.begin(), s.end(), std::back_inserter(ret), [](auto str) { return std::pair<std::vector<char>, int64_t>(std::vector<char>(str.first.begin(), str.first.end()), str.second); }); return ret; } template <class T> inline std::map<std::vector<char>, T> PadInfoStringToChar(const std::map<std::string, T> &s_pad_info) { std::map<std::vector<char>, T> ret; std::transform(s_pad_info.begin(), s_pad_info.end(), std::inserter(ret, ret.begin()), [](auto str) { return std::pair<std::vector<char>, T>(std::vector<char>(str.first.begin(), str.first.end()), str.second); }); return ret; } template <class T> inline std::map<std::string, T> PadInfoCharToString(const std::map<std::vector<char>, T> &c_pad_info) { std::map<std::string, T> ret; std::transform(c_pad_info.begin(), c_pad_info.end(), std::inserter(ret, ret.begin()), [](auto ch) { return std::pair<std::string, T>(std::string(ch.first.begin(), ch.first.end()), ch.second); }); return ret; } template <class T> inline void TensorMapCharToString(const std::map<std::vector<char>, T> *c, std::unordered_map<std::string, T> *s) { if (c == nullptr || s == nullptr) { return; } for (auto ch : *c) { auto key = std::string(ch.first.begin(), ch.first.end()); auto val = ch.second; s->insert(std::pair<std::string, T>(key, val)); } } } // namespace mindspore #endif // MINDSPORE_INCLUDE_API_DUAL_ABI_HELPER_H_ ======================= File: mindspore/ccsrc/frontend/optimizer/irpass/specialize_transform.h ======================= <gh_stars>1-10 /** * Copyright 2020-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. */ #ifndef MINDSPORE_CCSRC_FRONTEND_OPTIMIZER_IRPASS_SPECIALIZE_TRANSFORM_H_ #define MINDSPORE_CCSRC_FRONTEND_OPTIMIZER_IRPASS_SPECIALIZE_TRANSFORM_H_ #include <map> #include <vector> #include <memory> #include <utility> #include <tuple> #include "utils/hash_map.h" #include "frontend/optimizer/irpass.h" #include "frontend/optimizer/optimizer.h" #include "frontend/optimizer/anf_visitor.h" #include "ir/manager.h" #include "ir/func_graph.h" #include "ir/func_graph_cloner.h" #include "frontend/operator/ops.h" namespace mindspore { namespace opt { namespace irpass { namespace internal { class SpecializeTransform { public: SpecializeTransform() : cache_() {} ~SpecializeTransform() = default; FuncGraphPtr operator()(const FuncGraphPtr &func_graph, const std::vector<ValuePtr> &need_eliminate_args) { if (cache_.count(func_graph) == 0) { cache_[func_graph] = {}; } auto &cache = cache_[func_graph]; const auto &key = need_eliminate_args; if (cache.count(key) == 0) { auto mng = func_graph->manager(); MS_EXCEPTION_IF_NULL(mng); FuncGraphPtr new_fg = TransformableClone(func_graph, std::make_shared<TraceTransform>("sp")); mng->AddFuncGraph(new_fg); std::vector<AnfNodePtr> params = new_fg->parameters(); std::vector<AnfNodePtr> new_params; for (size_t i = 0; i < need_eliminate_args.size(); i++) { // keep the parameter if (need_eliminate_args[i] == nullptr) { new_params.push_back(params[i]); continue; } // replace the parameter with arg in new_fg without changing origin func_graph. mng->Replace(params[i], NewReplaceValueNode(need_eliminate_args[i])); } mng->SetParameters(new_fg, new_params); cache[key] = new_fg; } return cache[key]; } private: mindspore::HashMap<FuncGraphPtr, std::map<std::vector<ValuePtr>, FuncGraphPtr>> cache_; static ValueNodePtr NewReplaceValueNode(const ValuePtr &value) { MS_EXCEPTION_IF_NULL(value); if (value->isa<FuncGraph>() || value->isa<Primitive>() || value->isa<parse::NameSpace>()) { return NewValueNode(value); } if (value->isa<tensor::Tensor>()) { auto &const_tensor = *(value->cast<tensor::TensorPtr>()); auto const_tensor_ptr = std::make_shared<tensor::Tensor>(const_tensor); return NewValueNode(const_tensor_ptr); } MS_LOG(EXCEPTION) << "Unexpected value:" << value->ToString(); } }; } // namespace internal // {G, Xs} class SpecializeOnGraphArguments : public AnfVisitor { public: SpecializeOnGraphArguments() : specialize_transform_() {} ~SpecializeOnGraphArguments() override = default; AnfNodePtr operator()(const OptimizerPtr &, const AnfNodePtr &node) override { if (!node->isa<CNode>() || node->func_graph() == nullptr) { return nullptr; } auto &inputs = node->cast<CNodePtr>()->inputs(); if (!IsValueNode<FuncGraph>(inputs[0])) { return nullptr; } auto inp0_fg = GetValueNode<FuncGraphPtr>(inputs[0]); if (inp0_fg == nullptr || inp0_fg->has_flag(FUNC_GRAPH_FLAG_DEFER_INLINE) || inp0_fg->recursive()) { return nullptr; } std::vector<ValuePtr> need_eliminated_args; std::vector<AnfNodePtr> new_xs; bool hasVNode = false; for (size_t i = 1; i < inputs.size(); i++) { if (IsValueNode<FuncGraph>(inputs[i]) || IsValueNode<Primitive>(inputs[i]) || IsValueNode<tensor::Tensor>(inputs[i]) || IsValueNode<parse::NameSpace>(inputs[i])) { need_eliminated_args.push_back(GetValueNode(inputs[i])); hasVNode = true; } else { need_eliminated_args.emplace_back(nullptr); new_xs.push_back(inputs[i]); } } if (!hasVNode) { return nullptr; } auto new_fg = specialize_transform_(inp0_fg, need_eliminated_args); (void)new_xs.insert(new_xs.begin(), NewValueNode(new_fg)); return node->func_graph()->NewCNode(new_xs); } private: internal::SpecializeTransform specialize_transform_; }; } // namespace irpass } // namespace opt } // namespace mindspore #endif // MINDSPORE_CCSRC_FRONTEND_OPTIMIZER_IRPASS_SPECIALIZE_TRANSFORM_H_ ======================= File: include/c_api/context_c.h ======================= <gh_stars>1-10 /** * 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. */ #ifndef MINDSPORE_INCLUDE_C_API_CONTEXT_C_H #define MINDSPORE_INCLUDE_C_API_CONTEXT_C_H #include <stddef.h> #include <stdint.h> #include <stdbool.h> #include "include/c_api/types_c.h" #ifdef __cplusplus extern "C" { #endif typedef void *MSContextHandle; typedef void *MSDeviceInfoHandle; /// \brief Create a context object. /// /// \return Context object handle. MS_API MSContextHandle MSContextCreate(); /// \brief Destroy the context object. /// /// \param[in] context Context object handle address. MS_API void MSContextDestroy(MSContextHandle *context); /// \brief Set the number of threads at runtime. /// /// \param[in] context Context object handle. /// \param[in] thread_num the number of threads at runtime. MS_API void MSContextSetThreadNum(MSContextHandle context, int32_t thread_num); /// \brief Obtain the current thread number setting. /// /// \param[in] context Context object handle. /// /// \return The current thread number setting. MS_API int32_t MSContextGetThreadNum(const MSContextHandle context); /// \brief Set the thread affinity to CPU cores. /// /// \param[in] context Context object handle. /// \param[in] mode: 0: no affinities, 1: big cores first, 2: little cores first MS_API void MSContextSetThreadAffinityMode(MSContextHandle context, int mode); /// \brief Obtain the thread affinity of CPU cores. /// /// \param[in] context Context object handle. /// /// \return Thread affinity to CPU cores. 0: no affinities, 1: big cores first, 2: little cores first MS_API int MSContextGetThreadAffinityMode(const MSContextHandle context); /// \brief Set the thread lists to CPU cores. /// /// \note If core_list and mode are set by MSContextSetThreadAffinityMode at the same time, /// the core_list is effective, but the mode is not effective. /// /// \param[in] context Context object handle. /// \param[in] core_list: a array of thread core lists. /// \param[in] core_num The number of core. MS_API void MSContextSetThreadAffinityCoreList(MSContextHandle context, const int32_t *core_list, size_t core_num); /// \brief Obtain the thread lists of CPU cores. /// /// \param[in] context Context object handle. /// \param[out] core_num The number of core. /// /// \return a array of thread core lists. MS_API const int32_t *MSContextGetThreadAffinityCoreList(const MSContextHandle context, size_t *core_num); /// \brief Set the status whether to perform model inference or training in parallel. /// /// \param[in] context Context object handle. /// \param[in] is_parallel: true, parallel; false, not in parallel. MS_API void MSContextSetEnableParallel(MSContextHandle context, bool is_parallel); /// \brief Obtain the status whether to perform model inference or training in parallel. /// /// \param[in] context Context object handle. /// /// \return Bool value that indicates whether in parallel. MS_API bool MSContextGetEnableParallel(const MSContextHandle context); /// \brief Add device info to context object. /// /// \param[in] context Context object handle. /// \param[in] device_info Device info object handle. MS_API void MSContextAddDeviceInfo(MSContextHandle context, MSDeviceInfoHandle device_info); /// \brief Create a device info object. /// /// \param[in] device_info Device info object handle. /// /// \return Device info object handle. MS_API MSDeviceInfoHandle MSDeviceInfoCreate(MSDeviceType device_type); /// \brief Destroy the device info object. /// /// \param[in] device_info Device info object handle address. MS_API void MSDeviceInfoDestroy(MSDeviceInfoHandle *device_info); /// \brief Set provider's name. /// /// \param[in] device_info Device info object handle. /// \param[in] provider define the provider's name. MS_API void MSDeviceInfoSetProvider(MSDeviceInfoHandle device_info, const char *provider); /// \brief Obtain provider's name /// /// \param[in] device_info Device info object handle. /// /// \return provider's name. MS_API const char *MSDeviceInfoGetProvider(const MSDeviceInfoHandle device_info); /// \brief Set provider's device type. /// /// \param[in] device_info Device info object handle. /// \param[in] device define the provider's device type. EG: CPU. MS_API void MSDeviceInfoSetProviderDevice(MSDeviceInfoHandle device_info, const char *device); /// \brief Obtain provider's device type. /// /// \param[in] device_info Device info object handle. /// /// \return provider's device type. MS_API const char *MSDeviceInfoGetProviderDevice(const MSDeviceInfoHandle device_info); /// \brief Obtain the device type of the device info. /// /// \param[in] device_info Device info object handle. /// /// \return Device Type of the device info. MS_API MSDeviceType MSDeviceInfoGetDeviceType(const MSDeviceInfoHandle device_info); /// \brief Set enables to perform the float16 inference, Only valid for CPU/GPU. /// /// \param[in] device_info Device info object handle. /// \param[in] is_fp16 Enable float16 inference or not. MS_API void MSDeviceInfoSetEnableFP16(MSDeviceInfoHandle device_info, bool is_fp16); /// \brief Obtain enables to perform the float16 inference, Only valid for CPU/GPU. /// /// \param[in] device_info Device info object handle. /// /// \return Whether enable float16 inference. MS_API bool MSDeviceInfoGetEnableFP16(const MSDeviceInfoHandle device_info); /// \brief Set the NPU frequency, Only valid for NPU. /// /// \param[in] device_info Device info object handle. /// \param[in] frequency Can be set to 1 (low power consumption), 2 (balanced), 3 (high performance), 4 (extreme /// performance), default as 3. MS_API void MSDeviceInfoSetFrequency(MSDeviceInfoHandle device_info, int frequency); /// \brief Obtain the NPU frequency, Only valid for NPU. /// /// \param[in] device_info Device info object handle. /// /// \return NPU frequency MS_API int MSDeviceInfoGetFrequency(const MSDeviceInfoHandle device_info); #ifdef __cplusplus } #endif #endif // MINDSPORE_INCLUDE_C_API_CONTEXT_C_H ======================= File: mindspore/ccsrc/minddata/mindrecord/include/shard_header.h ======================= /** * Copyright 2019 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. */ #ifndef MINDSPORE_CCSRC_MINDDATA_MINDRECORD_INCLUDE_SHARD_HEADER_H_ #define MINDSPORE_CCSRC_MINDDATA_MINDRECORD_INCLUDE_SHARD_HEADER_H_ #include <memory> #include <set> #include <string> #include <utility> #include <vector> #include "minddata/mindrecord/include/common/shard_utils.h" #include "minddata/mindrecord/include/shard_error.h" #include "minddata/mindrecord/include/shard_index.h" #include "minddata/mindrecord/include/shard_page.h" #include "minddata/mindrecord/include/shard_schema.h" #include "minddata/mindrecord/include/shard_statistics.h" namespace mindspore { namespace mindrecord { class __attribute__((visibility("default"))) ShardHeader { public: ShardHeader(); ~ShardHeader() = default; Status BuildDataset(const std::vector<std::string> &file_paths, bool load_dataset = true); static Status BuildSingleHeader(const std::string &file_path, std::shared_ptr<json> *header_ptr); /// \brief add the schema and save it /// \param[in] schema the schema needs to be added /// \return the last schema's id int AddSchema(std::shared_ptr<Schema> schema); /// \brief add the statistic and save it /// \param[in] statistic the statistic needs to be added /// \return the last statistic's id void AddStatistic(std::shared_ptr<Statistics> statistic); /// \brief create index and add fields which from schema for each schema /// \param[in] fields the index fields needs to be added /// \return SUCCESS if add successfully, FAILED if not Status AddIndexFields(std::vector<std::pair<uint64_t, std::string>> fields); Status AddIndexFields(const std::vector<std::string> &fields); /// \brief get the schema /// \return the schema std::vector<std::shared_ptr<Schema>> GetSchemas(); /// \brief get Statistics /// \return the Statistic std::vector<std::shared_ptr<Statistics>> GetStatistics(); /// \brief add the statistic and save it /// \param[in] statistic info of slim size /// \return null int64_t GetSlimSizeStatistic(const json &slim_size_json); /// \brief get the fields of the index /// \return the fields of the index std::vector<std::pair<uint64_t, std::string>> GetFields(); /// \brief get the index /// \return the index std::shared_ptr<Index> GetIndex(); /// \brief get the schema by schemaid /// \param[in] schema_id the id of schema needs to be got /// \param[in] schema_ptr the schema obtained by schemaId /// \return Status Status GetSchemaByID(int64_t schema_id, std::shared_ptr<Schema> *schema_ptr); /// \brief get the filepath to shard by shardID /// \param[in] shardID the id of shard which filepath needs to be obtained /// \return the filepath obtained by shardID std::string GetShardAddressByID(int64_t shard_id); /// \brief get the statistic by statistic id /// \param[in] statistic_id the id of statistic needs to be get /// \param[in] statistics_ptr the statistics obtained by statistic id /// \return Status Status GetStatisticByID(int64_t statistic_id, std::shared_ptr<Statistics> *statistics_ptr); Status InitByFiles(const std::vector<std::string> &file_paths); void SetIndex(Index index) { index_ = std::make_shared<Index>(index); } Status GetPage(const int &shard_id, const int &page_id, std::shared_ptr<Page> *page_ptr); Status SetPage(const std::shared_ptr<Page> &new_page); Status AddPage(const std::shared_ptr<Page> &new_page); int64_t GetLastPageId(const int &shard_id); int GetLastPageIdByType(const int &shard_id, const std::string &page_type); Status GetPageByGroupId(const int &group_id, const int &shard_id, std::shared_ptr<Page> *page_ptr); std::vector<std::string> GetShardAddresses() const { return shard_addresses_; } int GetShardCount() const { return shard_count_; } int GetSchemaCount() const { return schema_.size(); } uint64_t GetHeaderSize() const { return header_size_; } uint64_t GetPageSize() const { return page_size_; } uint64_t GetCompressionSize() const { return compression_size_; } void SetHeaderSize(const uint64_t &header_size) { header_size_ = header_size; } void SetPageSize(const uint64_t &page_size) { page_size_ = page_size; } void SetCompressionSize(const uint64_t &compression_size) { compression_size_ = compression_size; } std::vector<std::string> SerializeHeader(); Status PagesToFile(const std::string dump_file_name); Status FileToPages(const std::string dump_file_name); static Status Initialize(const std::shared_ptr<ShardHeader> *header_ptr, const json &schema, const std::vector<std::string> &index_fields, std::vector<std::string> &blob_fields, uint64_t &schema_id); private: Status InitializeHeader(const std::vector<json> &headers, bool load_dataset); /// \brief get the headers from all the shard data /// \param[in] the shard data real path /// \param[in] the headers which read from the shard data /// \return SUCCESS/FAILED Status GetHeaders(const vector<string> &real_addresses, std::vector<json> &headers); Status ValidateField(const std::vector<std::string> &field_name, json schema, const uint64_t &schema_id); /// \brief check the binary file status static Status CheckFileStatus(const std::string &path); static Status ValidateHeader(const std::string &path, std::shared_ptr<json> *header_ptr); void GetHeadersOneTask(int start, int end, std::vector<json> &headers, const vector<string> &realAddresses); Status ParseIndexFields(const json &index_fields); Status CheckIndexField(const std::string &field, const json &schema); Status ParsePage(const json &page, int shard_index, bool load_dataset); Status ParseStatistics(const json &statistics); Status ParseSchema(const json &schema); void ParseShardAddress(const json &address); std::string SerializeIndexFields(); std::vector<std::string> SerializePage(); std::string SerializeStatistics(); std::string SerializeSchema(); std::string SerializeShardAddress(); std::shared_ptr<Index> InitIndexPtr(); Status GetAllSchemaID(std::set<uint64_t> &bucket_count); uint32_t shard_count_; uint64_t header_size_; uint64_t page_size_; uint64_t compression_size_; std::shared_ptr<Index> index_; std::vector<std::string> shard_addresses_; std::vector<std::shared_ptr<Schema>> schema_; std::vector<std::shared_ptr<Statistics>> statistics_; std::vector<std::vector<std::shared_ptr<Page>>> pages_; }; } // namespace mindrecord } // namespace mindspore #endif // MINDSPORE_CCSRC_MINDDATA_MINDRECORD_INCLUDE_SHARD_HEADER_H_ ======================= File: mindspore/lite/tools/optimizer/graph/node_infershape.h ======================= /** * 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. */ #ifndef MINDSPORE_LITE_TOOLS_OPTIMIZER_GRAPH_NODE_INFERSHAPE_H_ #define MINDSPORE_LITE_TOOLS_OPTIMIZER_GRAPH_NODE_INFERSHAPE_H_ #include <vector> #include <memory> #include <string> #include <map> #include "schema/inner/model_generated.h" #include "src/tensor.h" #include "tools/anf_exporter/fetch_content.h" #include "tools/converter/converter_flags.h" #include "tools/optimizer/common/format_utils.h" using mindspore::converter::FmkType; namespace mindspore { namespace opt { class NodeInferShape { public: explicit NodeInferShape(FmkType fmk_type = converter::kFmkTypeMs, bool train_flag = false) : fmk_type_(fmk_type), train_flag_(train_flag) {} virtual ~NodeInferShape() = default; void Init(FmkType fmk_type, bool train_flag) { fmk_type_ = fmk_type; train_flag_ = train_flag; } STATUS InferShape(const CNodePtr &cnode); bool JudgeOpSupportInfer(const CNodePtr &cnode); std::vector<int> GetInputShape(const CNodePtr &cnode, size_t index); std::vector<int> GetIntVecInput(const CNodePtr &cnode, size_t index); private: STATUS SetCNodeAbstract(const std::shared_ptr<CNode> &cnode, const std::vector<lite::Tensor *> &outputs, int status); abstract::AbstractBasePtr ConvertLiteTensorToAbstract(lite::Tensor *tensor); abstract::AbstractBasePtr ConvertTensorListToAbstract(lite::Tensor *tensor); FmkType fmk_type_{converter::kFmkTypeMs}; bool train_flag_{false}; }; } // namespace opt } // namespace mindspore #endif // MINDSPORE_LITE_TOOLS_OPTIMIZER_GRAPH_NODE_INFERSHAPE_H_ ======================= File: mindspore/ccsrc/fl/server/iteration.h ======================= /** * 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. */ #ifndef MINDSPORE_CCSRC_FL_SERVER_ITERATION_H_ #define MINDSPORE_CCSRC_FL_SERVER_ITERATION_H_ #include <memory> #include <vector> #include <string> #include "ps/core/communicator/communicator_base.h" #include "fl/server/common.h" #include "fl/server/round.h" #include "fl/server/local_meta_store.h" #include "fl/server/iteration_metrics.h" #include "fl/server/server_recovery.h" namespace mindspore { namespace fl { namespace server { enum class IterationState { // This iteration is still in process. kRunning, // This iteration is completed and the next iteration is not started yet. kCompleted }; // The time duration between retrying when sending prepare for next iteration request failed. constexpr uint32_t kRetryDurationForPrepareForNextIter = 500; class IterationMetrics; // In server's logic, Iteration is the minimum execution unit. For each execution, it consists of multiple kinds of // Rounds, only after all the rounds are finished, this iteration is considered as completed. class Iteration { public: static Iteration &GetInstance() { static Iteration instance; return instance; } // Register callbacks for other servers to synchronize iteration information from leader server. void RegisterMessageCallback(const std::shared_ptr<ps::core::TcpCommunicator> &communicator); // Register event callback for iteration state synchronization. void RegisterEventCallback(const std::shared_ptr<ps::core::ServerNode> &server_node); // Add a round for the iteration. This method will be called multiple times for each round. void AddRound(const std::shared_ptr<Round> &round); // Initialize all the rounds in the iteration. void InitRounds(const std::vector<std::shared_ptr<ps::core::CommunicatorBase>> &communicators, const TimeOutCb &timeout_cb, const FinishIterCb &finish_iteration_cb); // Release all the round objects in Iteration instance. Used for reinitializing round and round kernels. void ClearRounds(); // Notify move_to_next_thread_ to move to next iteration. void NotifyNext(bool is_last_iter_valid, const std::string &reason); // This method will control servers to proceed to next iteration. // There's communication between leader and follower servers in this method. // The server moves to the next iteration only after the last round finishes or the timer expires. void MoveToNextIteration(bool is_last_iter_valid, const std::string &reason); // Set current iteration state to running and trigger the event. void SetIterationRunning(); // Set current iteration state to end and trigger the event. void SetIterationEnd(); // The barrier function for elastic scaling. The scaling out/in operation should be done only after this iteration is // completed. void ScalingBarrier(); // Reinitialize rounds after scaling operations are done. // The server number after scaling is required in some rounds. bool ReInitForScaling(uint32_t server_num, uint32_t server_rank); // After hyper-parameters are updated, some rounds and kernels should be reinitialized. bool ReInitForUpdatingHyperParams(const std::vector<RoundConfig> &updated_rounds_config); const std::vector<std::shared_ptr<Round>> &rounds() const; bool is_last_iteration_valid() const; // Set the instance metrics which will be called for each iteration. void set_metrics(const std::shared_ptr<IterationMetrics> &metrics); void set_loss(float loss); void set_accuracy(float accuracy); // Return state of current training job instance. InstanceState instance_state() const; // Return whether current instance is being updated. bool IsInstanceBeingUpdated() const; // EnableFLS/disableFLS the current training instance. bool EnableServerInstance(std::string *result); bool DisableServerInstance(std::string *result); // Finish current instance and start a new one. FLPlan could be changed in this method. bool NewInstance(const nlohmann::json &new_instance_json, std::string *result); // Query information of current instance. bool QueryInstance(std::string *result); // Need to wait all the rounds to finish before proceed to next iteration. void WaitAllRoundsFinish() const; // Set server's recovery handler. void set_recovery_handler(const std::shared_ptr<ServerRecovery> &server_recovery); // Synchronize server iteration after another server's recovery is completed. bool SyncAfterRecovery(uint64_t iteration_num); // The round kernels whose Launch method has not returned yet. std::atomic_uint32_t running_round_num_; private: Iteration() : running_round_num_(0), server_node_(nullptr), communicator_(nullptr), iteration_state_(IterationState::kCompleted), start_timestamp_(0), complete_timestamp_(0), iteration_loop_count_(0), iteration_num_(1), is_last_iteration_valid_(true), move_to_next_reason_(""), move_to_next_thread_running_(true), pinned_iter_num_(0), metrics_(nullptr), instance_state_(InstanceState::kRunning), is_instance_being_updated_(false), loss_(0.0), accuracy_(0.0), joined_client_num_(0), rejected_client_num_(0), time_cost_(0) { LocalMetaStore::GetInstance().set_curr_iter_num(iteration_num_); } ~Iteration(); Iteration(const Iteration &) = delete; Iteration &operator=(const Iteration &) = delete; // The server does not need to handle the iteration events for now. void ProcessIterationRunningEvent() {} void ProcessIterationEndEvent() {} // Synchronize iteration from the leader server(Rank 0). bool SyncIteration(uint32_t rank); void HandleSyncIterationRequest(const std::shared_ptr<ps::core::MessageHandler> &message); // The request for moving to next iteration is not reentrant. bool IsMoveToNextIterRequestReentrant(uint64_t iteration_num); // The methods for moving to next iteration for all the servers. // Step 1: follower servers notify leader server that they need to move to next iteration. bool NotifyLeaderMoveToNextIteration(bool is_last_iter_valid, const std::string &reason); void HandleNotifyLeaderMoveToNextIterRequest(const std::shared_ptr<ps::core::MessageHandler> &message); // Step 2: leader server broadcasts to all follower servers to prepare for next iteration and switch to safemode.. bool BroadcastPrepareForNextIterRequest(bool is_last_iter_valid, const std::string &reason); void HandlePrepareForNextIterRequest(const std::shared_ptr<ps::core::MessageHandler> &message); // The server prepare for the next iteration. This method will switch the server to safemode. void PrepareForNextIter(); // Step 3: leader server broadcasts to all follower servers to move to next iteration. bool BroadcastMoveToNextIterRequest(bool is_last_iter_valid, const std::string &reason); void HandleMoveToNextIterRequest(const std::shared_ptr<ps::core::MessageHandler> &message); // Move to next iteration. Store last iterations model and reset all the rounds. void Next(bool is_iteration_valid, const std::string &reason); // Step 4: leader server broadcasts to all follower servers to end last iteration and cancel the safemode. bool BroadcastEndLastIterRequest(uint64_t iteration_num); void HandleEndLastIterRequest(const std::shared_ptr<ps::core::MessageHandler> &message); // The server end the last iteration. This method will increase the iteration number and cancel the safemode. void EndLastIter(); // Drop current iteration and move to the next immediately. bool ForciblyMoveToNextIteration(); // Summarize metrics for the completed iteration, including iteration time cost, accuracy, loss, etc. bool SummarizeIteration(); // Update server's hyper-parameters according to the given serialized json(hyper_params_data). bool UpdateHyperParams(const nlohmann::json &json); // Reinitialize rounds and round kernels. bool ReInitRounds(); std::shared_ptr<ps::core::ServerNode> server_node_; std::shared_ptr<ps::core::TcpCommunicator> communicator_; // All the rounds in the server. std::vector<std::shared_ptr<Round>> rounds_; // The recovery object for server. std::shared_ptr<ServerRecovery> server_recovery_; // The iteration is either running or completed at any time. std::mutex iteration_state_mtx_; std::condition_variable iteration_state_cv_; std::atomic<IterationState> iteration_state_; uint64_t start_timestamp_; uint64_t complete_timestamp_; // The count of iteration loops which are completed. size_t iteration_loop_count_; // Server's current iteration number. size_t iteration_num_; // Whether last iteration is successfully finished and the reason. bool is_last_iteration_valid_; std::string move_to_next_reason_; // It will be notified by rounds that the instance moves to the next iteration. std::thread move_to_next_thread_; std::atomic_bool move_to_next_thread_running_; std::mutex next_iteration_mutex_; std::condition_variable next_iteration_cv_; // To avoid Next method is called multiple times in one iteration, we should mark the iteration number. uint64_t pinned_iter_num_; std::mutex pinned_mtx_; std::shared_ptr<IterationMetrics> metrics_; // The state for current instance. std::atomic<InstanceState> instance_state_; // Every instance is not reentrant. // This flag represents whether the instance is being updated. std::mutex instance_mtx_; bool is_instance_being_updated_; // The training loss after this federated learning iteration, passed by worker. float loss_; // The evaluation result after this federated learning iteration, passed by worker. float accuracy_; // The number of clients which join the federated aggregation. size_t joined_client_num_; // The number of clients which are not involved in federated aggregation. size_t rejected_client_num_; // The time cost in millisecond for this completed iteration. uint64_t time_cost_; }; } // namespace server } // namespace fl } // namespace mindspore #endif // MINDSPORE_CCSRC_FL_SERVER_ITERATION_H_ ======================= File: mindspore/ccsrc/minddata/dataset/engine/datasetops/source/kmnist_op.h ======================= /** * 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. */ #ifndef MINDSPORE_CCSRC_MINDDATA_DATASET_ENGINE_DATASETOPS_SOURCE_KMNIST_OP_H_ #define MINDSPORE_CCSRC_MINDDATA_DATASET_ENGINE_DATASETOPS_SOURCE_KMNIST_OP_H_ #include <algorithm> #include <memory> #include <string> #include <utility> #include "minddata/dataset/engine/datasetops/source/mnist_op.h" namespace mindspore { namespace dataset { /// \brief Forward declares. template <typename T> class Queue; class KMnistOp : public MnistOp { public: /// \brief Constructor. /// \param[in] usage Usage of this dataset, can be 'train', 'test' or 'all'. /// \param[in] num_workers Number of workers reading images in parallel. /// \param[in] folder_path Dir directory of kmnist. /// \param[in] queue_size Connector queue size. /// \param[in] data_schema The schema of the kmnist dataset. /// \param[in] Sampler Tells KMnistOp what to read. KMnistOp(const std::string &usage, int32_t num_workers, const std::string &folder_path, int32_t queue_size, std::unique_ptr<DataSchema> data_schema, std::shared_ptr<SamplerRT> sampler); /// \brief Destructor. ~KMnistOp() = default; /// \brief Function to count the number of samples in the KMNIST dataset. /// \param[in] dir Path to the KMNIST directory. /// \param[in] usage Usage of this dataset, can be 'train', 'test' or 'all'. /// \param[in] count Output arg that will hold the minimum of the actual dataset size and numSamples. /// \return
1,516
the installer to transition a modal dialog box to another dialog box. The installer removes the present dialog box and creates the new one with the name indicated in the argument. ms.assetid: bd1aa465-55a0-4983-8c71-7e7075ee9dfb title: NewDialog ControlEvent ms.topic: article ms.date: 05/31/2018 --- # NewDialog ControlEvent This event notifies the installer to transition a modal dialog box to another dialog box. The installer removes the present dialog box and creates the new one with the name indicated in the argument. This event can be published by a [PushButton Control](pushbutton-control.md)or a [SelectionTree control](selectiontree-control.md). This event should be authored into the [ControlEvent table](controlevent-table.md). This ControlEvent requires the user interface to be run at the [*full UI*](f-gly.md) level. This event will not work with a [*reduced UI*](r-gly.md) or [*basic UI*](b-gly.md). For information, see [User Interface Levels](user-interface-levels.md). ## Published By This ControlEvent is published by the installer. ## Argument A string that is the name of the new dialog. ## Action on Subscribers This ControlEvent does not perform an action on subscribers. ## Typical Use A [PushButton](pushbutton-control.md) control on a modal dialog box is tied to this event in the [ControlEvent](controlevent-table.md) table to signal a transition to the next or previous dialog box of the same wizard sequence.     ======================= File: desktop-src/Msi/ice73.md ======================= --- description: ICE73 verifies that your package does not reuse package codes, upgrade codes, or product codes of the Windows Installer SDK samples. Packages should never reuse the package, upgrade, or product codes of another product. ms.assetid: a04429c2-ff9e-4ec8-8d07-faf1479f4920 title: ICE73 ms.topic: article ms.date: 05/31/2018 --- # ICE73 ICE73 verifies that your package does not reuse package codes, upgrade codes, or product codes of the Windows Installer SDK samples. Packages should never reuse the package, upgrade, or product codes of another product. ## Result ICE73 outputs a warning if your product's package reuses a package or product code of a Windows Installer SDK sample. ## Example ICE73 reports the following errors for the example shown: ``` syntax This package reuses the '{80F7E030-A751-11D2-A7D4-006097C99860}' ProductCode of the orca.msi 1.0 Windows Installer SDK package. This package reuses the '{000C1101-0000-0000-C000-000000000047}' Package Code of the msispy.msi 1.0 Windows Installer SDK package. This package reuses the '{8FC7****-88A0-4b41-82B8-8905D4AA904C}' Upgrade Code of a 1.1 Windows Installer SDK package. ``` > [!Note] > The asterisks (\*\*\*\*) in the GUID represent the range of GUIDs reserved for subsequent Windows Installer SDK packages.   To fix the errors, generate a new unique GUID for your package's product and package codes. You will also need a new unique GUID for your package's upgrade code. [Summary Information Stream](summary-information-stream.md) (partial) | Property | Value | |----------------|----------------------------------------| | PID\_REVNUMBER | {000C1101-0000-0000-C000-000000000047} |   [Property Table](property-table.md) (partial) | Property | Value | |------------------------------------|----------------------------------------| | [**ProductCode**](productcode.md) | {80F7E030-A751-11D2-A7D4-006097C99860} | | [**UpgradeCode**](upgradecode.md) | {8FC70000-88A0-4b41-82B8-8905D4AA904C} |   ## Related topics <dl> <dt> [Package Codes](package-codes.md) </dt> <dt> [Product Codes](product-codes.md) </dt> <dt> [**Revision Number Summary Property**](revision-number-summary.md) </dt> <dt> [**UpgradeCode Property**](upgradecode.md) </dt> <dt> [**ProductCode Property**](productcode.md) </dt> <dt> [ICE Reference](ice-reference.md) </dt> </dl>     ======================= File: desktop-src/Intl/using-special-characters-in-unicode.md ======================= --- description: Unicode has a few special characters and characters that have unusual meanings in text strings. ms.assetid: 0714abd0-b7dd-42c3-8ee8-295702087e3a title: Using Special Characters in Unicode ms.topic: article ms.date: 05/31/2018 --- # Using Special Characters in Unicode Unicode has a few special characters and characters that have unusual meanings in text strings. To avoid unexpected problems with these characters, use the rules provided in the following topics in your applications: - [Using ASCII Control Codes 0x000D and 0x000A](using-ascii-control-codes-0x000d-and-0x000a.md) - [Using Byte Order Marks](using-byte-order-marks.md) - [Using Escape Sequences and Control Characters](using-escape-sequences-and-control-characters.md) - [Using Line and Paragraph Separators](using-line-and-paragraph-separators.md) - [Using Nonspacing Characters and Diacritics](using-nonspacing-characters-and-diacritics.md) - [Using Null-terminated Strings](using-null-terminated-strings.md) ## Related topics <dl> <dt> [Using Unicode and Character Sets](using-unicode-and-character-sets.md) </dt> </dl>     ======================= File: desktop-src/direct3d9/id3dxcompressedanimationset--getsourcetickspersecond.md ======================= --- description: ID3DXCompressedAnimationSet::GetSourceTicksPerSecond method - Gets the number of animation key frame ticks that occur per second. ms.assetid: 72adba95-e52f-46d8-ab9e-8e06ccbf8d08 title: ID3DXCompressedAnimationSet::GetSourceTicksPerSecond method (D3dx9anim.h) ms.topic: reference ms.date: 05/31/2018 topic_type: - APIRef - kbSyntax api_name: - ID3DXCompressedAnimationSet.GetSourceTicksPerSecond api_type: - COM api_location: - d3dx9.lib - d3dx9.dll --- # ID3DXCompressedAnimationSet::GetSourceTicksPerSecond method Gets the number of animation key frame ticks that occur per second. ## Syntax ```C++ DOUBLE GetSourceTicksPerSecond(); ``` ## Parameters This method has no parameters. ## Return value Type: **[**DOUBLE**](../winprog/windows-data-types.md)** Number of animation key frame ticks that occur per second. ## Requirements | Requirement | Value | |--------------------|----------------------------------------------------------------------------------------| | Header<br/> | <dl> <dt>D3dx9anim.h</dt> </dl> | | Library<br/> | <dl> <dt>D3dx9.lib</dt> </dl> | ## See also <dl> <dt> [ID3DXCompressedAnimationSet](id3dxcompressedanimationset.md) </dt> </dl>     ======================= File: desktop-src/DevNotes/cscfindfirstfilew.md ======================= <filename>desktop-src/DevNotes/cscfindfirstfilew.md --- description: Searches for a file in the Offline Files cache that meets the specified criteria. ms.assetid: 09de6c55-fc37-4c0a-b5a0-ea73f06793d5 title: CSCFindFirstFileW function ms.topic: reference ms.date: 05/31/2018 topic_type: - APIRef - kbSyntax api_name: - CSCFindFirstFileW api_type: - DllExport api_location: - Cscmig.dll --- # CSCFindFirstFileW function \[This function is not supported and should not be used.\] Searches for a file in the Offline Files cache that meets the specified criteria. ## Syntax ```C++ HANDLE WINAPI CSCFindFirstFileW( _In_  LPCWSTR          lpszFileName, _Out_ WIN32_FIND_DATAW *lpFind32, _Out_ LPDWORD          lpdwStatus, _Out_ LPDWORD          lpdwPinCount, _Out_ LPDWORD          lpdwHintFlags, _Out_ FILETIME         *lpOrgFileTime ); ``` ## Parameters <dl> <dt> *lpszFileName* \[in\] </dt> <dd> A pointer to a null-terminated string that specifies a valid UNC directory or path. </dd> <dt> *lpFind32* \[out\] </dt> <dd> A pointer to the [**WIN32\_FIND\_DATA**](/windows/win32/api/minwinbase/ns-minwinbase-win32_find_dataa) structure that receives information about the file or subdirectory. </dd> <dt> *lpdwStatus* \[out\] </dt> <dd> An NTSTATUS code that indicates the status of the call. </dd> <dt> *lpdwPinCount* \[out\] </dt> <dd> This parameter is nonzero if the file has been made available offline or 0 otherwise. </dd> <dt> *lpdwHintFlags* \[out\] </dt> <dd> This parameter can be one of the following values. | Value | Meaning | |--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------| | <span id="FLAG_CSC_HINT_PIN_USER"></span><span id="flag_csc_hint_pin_user"></span><dl> <dt>**FLAG\_CSC\_HINT\_PIN\_USER**</dt> <dt>0x01</dt> </dl> | A user has made the file available offline.<br/> | | <span id="FLAG_CSC_HINT_PIN_INHERIT_USER"></span><span id="flag_csc_hint_pin_inherit_user"></span><dl> <dt>**FLAG\_CSC\_HINT\_PIN\_INHERIT\_USER**</dt> <dt>0x02</dt> </dl> | A user has made the parent available offline and marked the parent such that its children are available offline.<br/> | | <span id="FLAG_CSC_HINT_PIN_INHERIT_SYSTEM"></span><span id="flag_csc_hint_pin_inherit_system"></span><dl> <dt>**FLAG\_CSC\_HINT\_PIN\_INHERIT\_SYSTEM**</dt> <dt>0x04</dt> </dl> | An administrator or group policy has made the parent available offline and marked the parent such that its children are available offline.<br/> | | <span id="FLAG_CSC_HINT_PIN_SYSTEM"></span><span id="flag_csc_hint_pin_system"></span><dl> <dt>**FLAG\_CSC\_HINT\_PIN\_SYSTEM**</dt> <dt>0x10</dt> </dl> | An administrator or group policy has made the file available offline.<br/> |   </dd> <dt> *lpOrgFileTime* \[out\] </dt> <dd> A pointer to a [**FILETIME**](/windows/win32/api/minwinbase/ns-minwinbase-filetime) structure to receive the date and time information for the file or subdirectory. </dd> </dl> ## Return value If the function succeeds, the return value is a search handle used in a subsequent call to [**CSCFindNextFileW**](cscfindnextfilew.md) or [**CSCFindClose**](cscfindclose.md). If the function fails, the return value is **INVALID\_HANDLE\_VALUE**. ## Remarks This function has no associated import library or header file; you must call it using the [**LoadLibrary**](/windows/win32/api/libloaderapi/nf-libloaderapi-loadlibrarya) and [**GetProcAddress**](/windows/win32/api/libloaderapi/nf-libloaderapi-getprocaddress) functions. ## Requirements | Requirement | Value | |----------------|---------------------------------------------------------------------------------------| | DLL<br/> | <dl> <dt>Cscmig.dll</dt> </dl> |     ======================= File: desktop-src/SysMon/systemmonitor-updateinterval.md ======================= --- title: SystemMonitor.UpdateInterval property description: Retrieves or sets the length of time that SYSMON waits before the next time it collects counter data and updates the graph or report. ms.assetid: 297931e4-23ae-4384-a04a-9c1fa8aa1239 keywords: - UpdateInterval property SysMon - UpdateInterval property SysMon, SystemMonitor class - SystemMonitor class SysMon, UpdateInterval property topic_type: - apiref api_name: - SystemMonitor.UpdateInterval api_location: - Sysmon.ocx api_type: - COM ms.topic: reference ms.date: 05/31/2018 --- # SystemMonitor.UpdateInterval property Retrieves or sets the length of time that SYSMON waits before the next time it collects counter data and updates the graph or report. This property is read-only. ## Syntax ```VB Property UpdateInterval As Single ``` ## Property value Length of time, in seconds, that SYSMON waits before the next time it collects counter data and updates the graph or report. The minimum interval is 1 second (this is also the default value). The maximum value is 1,000,000. ## Remarks This property is relevant only when [**SystemMonitor.ManualUpdate**](systemmonitor-manualupdate.md) is set to False. ## Requirements | Requirement | Value | |-------------------------------------|---------------------------------------------------------------------------------------| | Minimum supported client<br/> | Windows 2000 Professional \[desktop apps only\]<br/> | | Minimum supported server<br/> | Windows 2000 Server \[desktop apps only\]<br/> | | DLL<br/> | <dl> <dt>Sysmon.ocx</dt> </dl> | ## See also <dl> <dt> [**SystemMonitor**](systemmonitor.md) </dt> </dl> ======================= File: desktop-src/direct3d12/id3dx12pipelineparsercallbacks-ibstripcutvaluecb.md ======================= --- title: ID3DX12PipelineParserCallbacks IBStripCutValueCb method (D3DX12.h) description: Calls the index buffer strip-cut value subobject callback of an object that implements this interface. ms.assetid: 702CA90A-FF20-4554-9469-C86428C203BC keywords: - IBStripCutValueCb method - IBStripCutValueCb method, ID3DX12PipelineParserCallbacks interface - ID3DX12PipelineParserCallbacks interface, IBStripCutValueCb method topic_type: - apiref api_name: - ID3DX12PipelineParserCallbacks.IBStripCutValueCb api_location: - D3D12.dll api_type: - COM ms.localizationpriority: low ms.topic: reference ms.date: 05/31/2018 --- # ID3DX12PipelineParserCallbacks::IBStripCutValueCb method Calls the index buffer strip-cut value subobject callback of an object that implements this interface. ## Syntax ```C++ void IBStripCutValueCb( D3D12_INDEX_BUFFER_STRIP_CUT_VALUE IBStripCutValue ); ``` ## Parameters <dl> <dt> *IBStripCutValue* </dt> <dd> Type: **[**D3D12\_INDEX\_BUFFER\_STRIP\_CUT\_VALUE**](/windows/desktop/api/d3d12/ne-d3d12-d3d12_index_buffer_strip_cut_value)** Details of the index buffer strip-cut value subobject parsed from a pipeline state stream. </dd> </dl> ## Return value Returns nothing. ## Requirements | Requirement | Value | |--------------------|--------------------------------------------------------------------------------------| | Header<br/> | <dl> <dt>D3DX12.h</dt> </dl> | | Library<br/> | <dl> <dt>D3D12.lib</dt> </dl> | | DLL<br/> | <dl> <dt>D3D12.dll</dt> </dl> | ## See also <dl> <dt> [Helper Interfaces for Direct3D 12](helper-interfaces-for-d3d12.md) </dt> <dt> [**ID3DX12PipelineParserCallbacks**](id3dx12pipelineparsercallbacks.md) </dt> <dt> [**D3D12\_INDEX\_BUFFER\_STRIP\_CUT\_VALUE**](/windows/desktop/api/d3d12/ne-d3d12-d3d12_index_buffer_strip_cut_value) </dt> </dl> ======================= File: desktop-src/shell/shellfolderitem-object.md ======================= --- description: Extends the FolderItem object. In addition to the properties and methods supported by FolderItem, ShellFolderItem has two additional methods. title: ShellFolderItem object (Shldisp.h) ms.topic: reference ms.date: 05/31/2018 topic_type: - APIRef - kbSyntax api_name: - ShellFolderItem api_type: - COM api_location: - Shell32.dll ms.assetid: 0e2f4c91-f9f9-4daa-a801-9c7fea8af738 --- # ShellFolderItem object Extends the [**FolderItem**](folderitem.md) object. In addition to the properties and methods supported by **FolderItem**, **ShellFolderItem** has two additional methods. ## Members The **ShellFolderItem** object has these types of members: - [Methods](#methods) ### Methods The **ShellFolderItem** object has these methods. | Method | Description | |:-------------------------------------------------------------|:----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | [**ExtendedProperty**](shellfolderitem-extendedproperty.md) | Gets the value of a property from an item's property set. The property can be specified either by name or by the property set's format identifier (FMTID) and property identifier (PID).<br/> | | [**InvokeVerbEx**](invokeverbex.md) | Executes a verb on a Shell item.<br/> |   ## Requirements | Requirement | Value | |-------------------------------------|---------------------------------------------------------------------------------------------------------------| | Minimum supported client<br/> | Windows 2000 Professional \[desktop apps only\]<br/> | | Minimum supported server<br/> | Windows 2000 Server \[desktop apps only\]<br/> | | Header<br/> | <dl> <dt>Shldisp.h</dt> </dl> | | IDL<br/> | <dl> <dt>Shldisp.idl</dt> </dl> | | DLL<br/> | <dl> <dt>Shell32.dll (version 5.0 or later)</dt> </dl> |     ======================= File: desktop-src/SensorsAPI/sensor-category-location.md ======================= --- description: The SENSOR\_CATEGORY\_LOCATION category contains sensors that provide geographic location information. ms.assetid: f82ce6da-fe2d-4931-99dc-4aeb2f0f3317 title: SENSOR_CATEGORY_LOCATION (Sensors.h) ms.topic: reference ms.date: 05/31/2018 --- # SENSOR\_CATEGORY\_LOCATION The SENSOR\_CATEGORY\_LOCATION category contains sensors that provide geographic location information. **Platform-Defined Sensor Types** This category includes the following platform-defined sensor types. | Sensor type | Description | |:--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:-------------------------------------------------------------------------------------------------------------------------------------------------| | <span id="SENSOR_TYPE_LOCATION_BROADCAST"></span><span id="sensor_type_location_broadcast"></span><dl> <dt>**SENSOR\_TYPE\_LOCATION\_BROADCAST**</dt> <dt>{D26988CF-5162-4039-BB17-4C58B698E44A}</dt> </dl> | Sensors that transmit location information by using transmissions such as television or radio frequencies. <br/> | | <span id="SENSOR_TYPE_LOCATION_DEAD_RECKONING"></span><span id="sensor_type_location_dead_reckoning"></span><dl> <dt>**SENSOR\_TYPE\_LOCATION\_DEAD\_RECKONING**</dt> <dt> {1A37D538-F28B-42DA-9FCE-A9D0A2A6D829}</dt> </dl> | Dead-reckoning sensors. These sensors first calculate the current location and then update the current location by using motion data.<br/> | | <span id="SENSOR_TYPE_LOCATION_GPS"></span><span id="sensor_type_location_gps"></span><dl> <dt>**SENSOR\_TYPE\_LOCATION\_GPS**</dt> <dt>{ED4CA589-327A-4FF9-A560-91DA4B48275E}</dt> </dl> | Global positioning system sensors.<br/> | | <span id="SENSOR_TYPE_LOCATION_LOOKUP"></span><span id="sensor_type_location_lookup"></span><dl> <dt>**SENSOR\_TYPE\_LOCATION\_LOOKUP**</dt> <dt>{3B2EAE4A-72CE-436D-96D2-3C5B8570E987}</dt> </dl> | Lookup sensors, such as those that provide information based on the user's IP address.<br/> | | <span id="SENSOR_TYPE_LOCATION_OTHER"></span><span id="sensor_type_location_other"></span><dl> <dt>**SENSOR\_TYPE\_LOCATION\_OTHER**</dt> <dt>{9B2D0566-0368-4F71-B88D-533F132031DE}</dt> </dl> | Other location sensors.<br/> | | <span id="SENSOR_TYPE_LOCATION_STATIC"></span><span id="sensor_type_location_static"></span><dl> <dt>**SENSOR\_TYPE\_LOCATION\_STATIC**</dt> <dt>{095F8184-0FA9-4445-8E6E-B70F320B6B4C}</dt> </dl> | Fixed-location sensors, such as those that use preset, user-provided information.<br/> | | <span id="SENSOR_TYPE_LOCATION_TRIANGULATION"></span><span id="sensor_type_location_triangulation"></span><dl> <dt>**SENSOR\_TYPE\_LOCATION\_TRIANGULATION**</dt> <dt>{691C341A-5406-4FE1-942F-2246CBEB39E0}</dt> </dl> | Triangulation sensors, such as those that determine current location based on cellular phone tower proximities.<br/> | **Platform-Defined Data Fields** Platform-defined property keys for this category are based on SENSOR\_DATA\_TYPE\_LOCATION\_GUID: {055C74D8-CA6F-47D6-95C6-1ED3637A0FF4} This category includes the following platform-defined data fields. | Data field name and PID | Description | |:-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | <span id="SENSOR_DATA_TYPE_ADDRESS1"></span><span id="sensor_data_type_address1"></span><dl> <dt>**SENSOR\_DATA\_TYPE\_ADDRESS1**</dt> <dt> (PID = 23) </dt> </dl> | **VT\_LPWSTR**<br/> Street address, first line.<br/> | | <span id="SENSOR_DATA_TYPE_ADDRESS2"></span><span id="sensor_data_type_address2"></span><dl> <dt>**SENSOR\_DATA\_TYPE\_ADDRESS2**</dt> <dt> (PID = 24) </dt> </dl> | **VT\_LPWSTR**<br/> Street address, second line.<br/> | | <span id="SENSOR_DATA_TYPE_ALTITUDE_ANTENNA_SEALEVEL_METERS"></span><span id="sensor_data_type_altitude_antenna_sealevel_meters"></span><dl> <dt>**SENSOR\_DATA\_TYPE\_ALTITUDE\_ANTENNA\_SEALEVEL\_METERS**</dt> <dt> (PID = 36) </dt> </dl> | **VT\_R8**<br/> Altitude of the antenna, referenced to sea level, in meters.<br/> | | <span id="SENSOR_DATA_TYPE_ALTITUDE_ELLIPSOID_ERROR_METERS"></span><span id="sensor_data_type_altitude_ellipsoid_error_meters"></span><dl> <dt>**SENSOR\_DATA\_TYPE\_ALTITUDE\_ELLIPSOID\_ERROR\_METERS**</dt> <dt>(PID = 29) </dt> </dl> | **VT\_R8**<br/> Altitude error referenced to the World Geodetic System (WGS 84) reference ellipsoid, in meters.<br/> | | <span id="SENSOR_DATA_TYPE_ALTITUDE_ELLIPSOID_METERS"></span><span id="sensor_data_type_altitude_ellipsoid_meters"></span><dl> <dt>**SENSOR\_DATA\_TYPE\_ALTITUDE\_ELLIPSOID\_METERS**</dt> <dt> (PID = 5) </dt> </dl> | **VT\_R8**<br/> Altitude referenced to the World Geodetic System (WGS 84) reference ellipsoid, in meters.<br/> | | <span id="SENSOR_DATA_TYPE_ALTITUDE_SEALEVEL_ERROR_METERS"></span><span id="sensor_data_type_altitude_sealevel_error_meters"></span><dl> <dt>**SENSOR\_DATA\_TYPE\_ALTITUDE\_SEALEVEL\_ERROR\_METERS**</dt> <dt> (PID = 30) </dt> </dl> | **VT\_R8**<br/> Altitude error referenced to sea level, in meters.<br/> | | <span id="SENSOR_DATA_TYPE_ALTITUDE_SEALEVEL_METERS"></span><span id="sensor_data_type_altitude_sealevel_meters"></span><dl> <dt>**SENSOR\_DATA\_TYPE\_ALTITUDE\_SEALEVEL\_METERS**</dt> <dt> (PID = 4) </dt> </dl> | **VT\_R8**<br/> Altitude referenced to sea level, in meters.<br/> | | <span id="SENSOR_DATA_TYPE_CITY"></span><span id="sensor_data_type_city"></span><dl> <dt>**SENSOR\_DATA\_TYPE\_CITY**</dt> <dt>(PID = 25) </dt> </dl> | **VT\_LPWSTR**<br/> City.<br/> | | <span id="SENSOR_DATA_TYPE_COUNTRY_REGION"></span><span id="sensor_data_type_country_region"></span><dl> <dt>**SENSOR\_DATA\_TYPE\_COUNTRY\_REGION**</dt> <dt> (PID = 28) </dt> </dl> | **VT\_LPWSTR**<br/> Country or region, represented as an ISO 3166 1-alpha-2 country/region code.<br/> | | <span id="SENSOR_DATA_TYPE_DGPS_DATA_AGE"></span><span id="sensor_data_type_dgps_data_age"></span><dl> <dt>**SENSOR\_DATA\_TYPE\_DGPS\_DATA\_AGE**</dt> <dt>(PID = 35) </dt> </dl> | **VT\_R8**<br/> Age of differential GPS data, in seconds.<br/> | | <span id="SENSOR_DATA_TYPE_DIFFERENTIAL_REFERENCE_STATION_ID"></span><span id="sensor_data_type_differential_reference_station_id"></span><dl> <dt>**SENSOR\_DATA\_TYPE\_DIFFERENTIAL\_REFERENCE\_STATION\_ID**</dt> <dt> (PID = 37) </dt> </dl> | **VT\_I4**<br/> ID of the differential reference station. The range is 0000 to 1023.<br/> | | <span id="SENSOR_DATA_TYPE_ERROR_RADIUS_METERS"></span><span id="sensor_data_type_error_radius_meters"></span><dl> <dt>**SENSOR\_DATA\_TYPE\_ERROR\_RADIUS\_METERS**</dt> <dt>(PID = 22) </dt> </dl> | **VT\_R8**<br/> Accuracy of latitude and longitude values, in meters. A value of zero means that the accuracy level is not known. The Location API gives priority to sensors that provide a non-zero value for this field. <br/> | | <span id="SENSOR_DATA_TYPE_FIX_QUALITY"></span><span id="sensor_data_type_fix_quality"></span><dl> <dt>**SENSOR\_DATA\_TYPE\_FIX\_QUALITY**</dt> <dt>(PID = 10) </dt> </dl> | **VT\_I4**<br/> Fix quality<br/> 0 = no fix<br/> 1 = GPS<br/> 2 = DGPS <br/> | | <span id="SENSOR_DATA_TYPE_FIX_TYPE"></span><span id="sensor_data_type_fix_type"></span><dl> <dt>**SENSOR\_DATA\_TYPE\_FIX\_TYPE**</dt> <dt>(PID = 11) </dt> </dl> | **VT\_I4**<br/> Fix type<br/> 0 = no fix<br/> 1 = GPS SPS Mode, fix valid<br/> 2 = DGPS SPS Mode, fix valid<br/> 3 = GPS PPS Mode, fix valid <br/> 4 = Real Time Kinematic <br/> 5 = Float RTK <br/> 6 = Estimated (dead reckoned)<br/> 7 = Manual Input Mode <br/> 8 = Simulator Mode <br/> | | <span id="SENSOR_DATA_TYPE_GEOIDAL_SEPARATION"></span><span id="sensor_data_type_geoidal_separation"></span><dl> <dt>**SENSOR\_DATA\_TYPE\_GEOIDAL\_SEPARATION**</dt> <dt> (PID = 34) </dt> </dl> | **VT\_R8**<br/> The difference between the WGS-84 ellipsoid and mean sea level. Values less than zero indicate that mean sea level is below the reference ellipsoid.<br/> | | <span id="SENSOR_DATA_TYPE_GPS_OPERATION_MODE"></span><span id="sensor_data_type_gps_operation_mode"></span><dl> <dt>**SENSOR\_DATA\_TYPE\_GPS\_OPERATION\_MODE**</dt> <dt>(PID = 32) </dt> </dl> | **VT\_I4**<br/> Operation mode.<br/> 0 = Manual. The GPS sensor is set to operate in 2-D or 3-D mode. <br/> 1 = Automatic. The GPS sensor can automatically switch between 2-D and 3-D modes. <br/> | | <span id="SENSOR_DATA_TYPE_GPS_SELECTION_MODE"></span><span id="sensor_data_type_gps_selection_mode"></span><dl> <dt>**SENSOR\_DATA\_TYPE\_GPS\_SELECTION\_MODE**</dt> <dt>(PID = 31) </dt> </dl> | **VT\_I4**<br/> Selection mode. <br/> 0 = Autonomous.<br/> 1 = DGPS.<br/> 2 = Estimated (dead reckoned).<br/> 3 = Manual input.<br/> 4 = Simulator. <br/> 5 = Data not valid. <br/> | | <span id="SENSOR_DATA_TYPE_GPS_STATUS"></span><span id="sensor_data_type_gps_status"></span><dl> <dt>**SENSOR\_DATA\_TYPE\_GPS\_STATUS**</dt> <dt> (PID = 33) </dt> </dl> | **VT\_I4**<br/> Current data status.<br/> 1 = Data is valid. <br/> 2 = Data is not valid.<br/> | | <span id="SENSOR_DATA_TYPE_HORIZONAL_DILUTION_OF_PRECISION"></span><span id="sensor_data_type_horizonal_dilution_of_precision"></span><dl> <dt>**SENSOR\_DATA\_TYPE\_HORIZONAL\_DILUTION\_OF\_PRECISION**</dt> <dt>(PID = 13) </dt> </dl> | **VT\_R8**<br/> Horizontal dilution of precision.<br/> | | <span id="SENSOR_DATA_TYPE_LATITUDE_DEGREES"></span><span id="sensor_data_type_latitude_degrees"></span><dl> <dt>**SENSOR\_DATA\_TYPE\_LATITUDE\_DEGREES**</dt> <dt> (PID = 2) </dt> </dl> | **VT\_R8**<br/> Degrees latitude. North is positive.<br/> | | <span id="SENSOR_DATA_TYPE_LONGITUDE_DEGREES"></span><span id="sensor_data_type_longitude_degrees"></span><dl> <dt>**SENSOR\_DATA\_TYPE\_LONGITUDE\_DEGREES**</dt> <dt> (PID = 3) </dt> </dl> | **VT\_R8**<br/> Degrees longitude. East is positive.<br/> | | <span id="SENSOR_DATA_TYPE_MAGNETIC_HEADING_DEGREES"></span><span id="sensor_data_type_magnetic_heading_degrees"></span><dl> <dt>**SENSOR\_DATA\_TYPE\_MAGNETIC\_HEADING\_DEGREES**</dt> <dt> (PID = 8) </dt> </dl> | **VT\_R8**<br/> Heading, in relation to magnetic north, in degrees.<br/> | | <span id="SENSOR_DATA_TYPE_MAGNETIC_VARIATION"></span><span id="sensor_data_type_magnetic_variation"></span><dl> <dt>**SENSOR\_DATA\_TYPE\_MAGNETIC\_VARIATION**</dt> <dt>(PID = 9) </dt> </dl> | **VT\_R8**<br/> Magnetic variation. East is positive.<br/> | | <span id="SENSOR_DATA_TYPE_NMEA_SENTENCE"></span><span id="sensor_data_type_nmea_sentence"></span><dl> <dt>**SENSOR\_DATA\_TYPE\_NMEA\_SENTENCE**</dt> <dt> (PID = 38) </dt> </dl> | **VT\_LPWSTR**<br/> The current NMEA sentence string.<br/> | | <span id="SENSOR_DATA_TYPE_POSITION_DILUTION_OF_PRECISION"></span><span id="sensor_data_type_position_dilution_of_precision"></span><dl> <dt>**SENSOR\_DATA\_TYPE\_POSITION\_DILUTION\_OF\_PRECISION**</dt> <dt>(PID = 12) </dt> </dl> | **VT\_R8**<br/> Position dilution of precision.<br/> | | <span id="SENSOR_DATA_TYPE_POSTALCODE"></span><span id="sensor_data_type_postalcode"></span><dl> <dt>**SENSOR\_DATA\_TYPE\_POSTALCODE**</dt> <dt> (PID = 27) </dt> </dl> | **VT\_LPWSTR**<br/> Postal code.<br/> | | <span id="SENSOR_DATA_TYPE_SATELLITES_IN_VIEW"></span><span id="sensor_data_type_satellites_in_view"></span><dl> <dt>**SENSOR\_DATA\_TYPE\_SATELLITES\_IN\_VIEW**</dt> <dt> (PID = 17) </dt> </dl> | **VT\_I4**<br/> Number of satellites in view.<br/> | | <span id="SENSOR_DATA_TYPE_SATELLITES_IN_VIEW_AZIMUTH"></span><span id="sensor_data_type_satellites_in_view_azimuth"></span><dl> <dt>**SENSOR\_DATA\_TYPE\_SATELLITES\_IN\_VIEW\_AZIMUTH**</dt> <dt>(PID = 20) </dt> </dl> | **VT\_VECTOR\|VT\_UI1**<br/> Counted array that contains the azimuth of each satellite in view.<br/> Data for vector types is always serialized as **VT\_UI1** (an array of unsigned, 1-byte characters). This data field actually contains each value as an IEEE 8-byte real value (**VT\_ R8**). Use -1 as a placeholder for empty values. <br/> For information about working with arrays, see [Retrieving Vector Types](retrieving-vector-types.md).<br/> | | <span id="SENSOR_DATA_TYPE_SATELLITES_IN_VIEW_ELEVATION"></span><span id="sensor_data_type_satellites_in_view_elevation"></span><dl> <dt>**SENSOR\_DATA\_TYPE\_SATELLITES\_IN\_VIEW\_ELEVATION**</dt> <dt>(PID = 19) </dt> </dl> | **VT\_VECTOR\|VT\_UI1**<br/> Counted array that contains the elevation of each satellite in view.<br/> Data for vector types is always serialized as **VT\_UI1** (an array of unsigned, 1-byte characters). This data field actually contains each value as an IEEE 8-byte real value (**VT\_R8**). Use -91 as a placeholder for empty values.<br/> For information about working with arrays, see [Retrieving Vector Types](retrieving-vector-types.md).<br/> | | <span id="SENSOR_DATA_TYPE_SATELLITES_IN_VIEW_ID"></span><span id="sensor_data_type_satellites_in_view_id"></span><dl> <dt>**SENSOR\_DATA\_TYPE\_SATELLITES\_IN\_VIEW\_ID**</dt> <dt> (PID = 39) </dt> </dl> | **VT\_VECTOR\|VT\_UI1**<br/> Counted array that contains the ID of each satellite in view.<br/> Data for vector types is always serialized as **VT\_UI1** (an array of unsigned, 1-byte characters). This data field actually contains each value as a 4-byte unsigned integer (**VT\_UI4**).<br/> For information about working with arrays, see [Retrieving Vector Types](retrieving-vector-types.md).<br/> | | <span id="SENSOR_DATA_TYPE_SATELLITES_IN_VIEW_PRNS"></span><span id="sensor_data_type_satellites_in_view_prns"></span><dl> <dt>**SENSOR\_DATA\_TYPE\_SATELLITES\_IN\_VIEW\_PRNS**</dt> <dt> (PID = 18) </dt> </dl> | **VT\_VECTOR\|VT\_UI1**<br/> Counted array that contains pseudorandom noise codes for satellites in view.<br/> Data for vector types is always serialized as **VT\_UI1** (an array of unsigned, 1-byte characters). This data field actually contains each value as a 4-byte unsigned integer (**VT\_UI4**). Use zero (0) as a placeholder for empty values.<br/> For information about working with arrays, see [Retrieving Vector Types](retrieving-vector-types.md).<br/> | | <span id="SENSOR_DATA_TYPE_SATELLITES_IN_VIEW_STN_RATIO"></span><span id="sensor_data_type_satellites_in_view_stn_ratio"></span><dl> <dt>**SENSOR\_DATA\_TYPE\_SATELLITES\_IN\_VIEW\_STN\_RATIO**</dt> <dt> (PID = 21) </dt> </dl> | **VT\_VECTOR\|VT\_UI1**<br/> Counted array that contains the signal-to-noise ratio for satellites in view.<br/> Data for vector types is always serialized as **VT\_UI1** (an array of unsigned, 1-byte characters). This data field actually contains each value as an IEEE 8-byte real value (**VT\_R8**). Use zero (0) as a placeholder for empty values.<br/> For information about working with arrays, see [Retrieving Vector Types](retrieving-vector-types.md).<br/> | | <span id="SENSOR_DATA_TYPE_SATELLITES_USED_COUNT"></span><span id="sensor_data_type_satellites_used_count"></span><dl> <dt>**SENSOR\_DATA\_TYPE\_SATELLITES\_USED\_COUNT**</dt> <dt>(PID = 15) </dt> </dl> | **VT\_I4**<br/> Number of satellites that are used in a solution.<br/> | | <span id="SENSOR_DATA_TYPE_SATELLITES_USED_PRNS"></span><span id="sensor_data_type_satellites_used_prns"></span><dl> <dt>**SENSOR\_DATA\_TYPE\_SATELLITES\_USED\_PRNS**</dt> <dt> (PID = 16) </dt> </dl> | **VT\_VECTOR\|VT\_UI1**<br/> Counted array that contains pseudorandom noise codes for satellites that are used in a solution.<br/> Data for vector types is always serialized as **VT\_UI1** (an array of unsigned, 1-byte characters). This data field must contain each value as a 4-byte unsigned integer (**VT\_UI4**). Use zero (0) as a placeholder for empty values.<br/> For information about working with arrays, see [Retrieving Vector Types](retrieving-vector-types.md).<br/> | | <span id="SENSOR_DATA_TYPE_SATELLITES_USED_PRNS_AND_CONSTELLATIONS"></span><span id="sensor_data_type_satellites_used_prns_and_constellations"></span><dl> <dt>**SENSOR\_DATA\_TYPE\_SATELLITES\_USED\_PRNS\_AND\_CONSTELLATIONS**</dt> <dt> (PID = 41) </dt> </dl> | **VT\_VECTOR\|VT\_UI2**<br/> Counted array that contains pseudorandom noise codes for satellites that are used in a solution.<br/> Data for vector types is always serialized as **VT\_UI2** (an array of unsigned, 2-byte characters). This data field must contain each value as a 4-byte unsigned integer (**VT\_UI4**). Use zero (0) as a placeholder for empty values.<br/> For information about working with arrays, see [Retrieving Vector Types](retrieving-vector-types.md).<br/> | | <span id="SENSOR_DATA_TYPE_SPEED_KNOTS"></span><span id="sensor_data_type_speed_knots"></span><dl> <dt>**SENSOR\_DATA\_TYPE\_SPEED\_KNOTS**</dt> <dt>(PID = 6) </dt> </dl> | **VT\_R8**<br/> Speed, in knots.<br/> | | <span id="SENSOR_DATA_TYPE_STATE_PROVINCE"></span><span id="sensor_data_type_state_province"></span><dl> <dt>**SENSOR\_DATA\_TYPE\_STATE\_PROVINCE**</dt> <dt>(PID = 26) </dt> </dl> | **VT\_LPWSTR**<br/> State/province.<br/> | | <span id="SENSOR_DATA_TYPE_TRUE_HEADING_DEGREES"></span><span id="sensor_data_type_true_heading_degrees"></span><dl> <dt>**SENSOR\_DATA\_TYPE\_TRUE\_HEADING\_DEGREES**</dt> <dt> (PID = 7) </dt> </dl> | **VT\_R8**<br/> Heading, in relation to true north, in degrees.<br/> | | <span id="SENSOR_DATA_TYPE_VERTICAL_DILUTION_OF_PRECISION"></span><span id="sensor_data_type_vertical_dilution_of_precision"></span><dl> <dt>**SENSOR\_DATA\_TYPE\_VERTICAL\_DILUTION\_OF\_PRECISION**</dt> <dt> (PID = 14) </dt> </dl> | **VT\_R8**<br/> Vertical dilution of precision.<br/> | ## Requirements | Requirement | Value | |-------------------------------------|--------------------------------------------------------------------------------------| | Minimum supported client<br/> | Windows 7 \[desktop apps only\]<br/> | | Minimum supported server<br/> | None supported<br/> | | Header<br/> | <dl> <dt>Sensors.h</dt> </dl> |     ======================= File: desktop-src/DirectShow/currentchapter-property.md ======================= <reponame>velden/win32<filename>desktop-src/DirectShow/currentchapter-property.md<gh_stars>100-1000 --- description: The CurrentChapter property retrieves the number of the chapter currently playing. ms.assetid: f810106b-a5da-44ac-87e6-1c21cf750d9f title: CurrentChapter Property ms.topic: reference ms.date: 05/31/2018 --- # CurrentChapter Property > [!Note] > This component is available for use in the Microsoft Windows 2000, Windows XP, and Windows Server 2003 operating systems. It may be altered or unavailable in subsequent versions.   The `CurrentChapter` property retrieves the number of the chapter currently playing. ``` syntax [ iCurChapter = ] MSWebDVD.CurrentChapter ``` ## Return Value Returns an integer value representing the current chapter in the current title. ## Remarks This property is read-only with no default value.     ======================= File: desktop-src/TermServ/irdvtaskpluginnotifysink.md ======================= --- title: IRDVTaskPluginNotifySink interface description: The IRDVTaskPluginNotifySink interface is used by the task agent to communicate with the trigger agent. ms.assetid: ccf19693-d3cc-4cf7-af35-947be047beeb ms.tgt_platform: multiple keywords: - IRDVTaskPluginNotifySink interface Remote Desktop Services - IRDVTaskPluginNotifySink interface Remote Desktop Services, described topic_type: - apiref api_name: - IRDVTaskPluginNotifySink api_type: - COM ms.topic: reference ms.date: 05/31/2018 api_location: --- # IRDVTaskPluginNotifySink interface The **IRDVTaskPluginNotifySink** interface is used by the task agent to communicate with the trigger agent. A pointer to this interface is passed to the task agent in the [**IRDVTaskPlugin::Initialize**](irdvtaskplugin-initialize.md) method. ## Members The **IRDVTaskPluginNotifySink** interface inherits from the [**IUnknown**](/windows/desktop/api/unknwn/nn-unknwn-iunknown) interface. **IRDVTaskPluginNotifySink** also has these types of members: - [Methods](#methods) ### Methods The **IRDVTaskPluginNotifySink** interface has these methods. | Method | Description | |:------------------------------------------------------------------------|:----------------------------------------------------------------------------------| | [**DeleteSchedule**](irdvtaskpluginnotifysink-deleteschedule.md) | Called by the task agent to delete a scheduled task.<br/> | | [**OnTaskStateChange**](irdvtaskpluginnotifysink-ontaskstatechange.md) | Used to notify the trigger agent that the state of a task has changed.<br/> | | [**OnTerminated**](irdvtaskpluginnotifysink-onterminated.md) | Called by the task agent to request that the task agent be shut down.<br/> | | [**ScheduleTask**](irdvtaskpluginnotifysink-scheduletask.md) | Called by the task agent to schedule a task.<br/> | ## Remarks Although this interface is supported on the operating systems identified in the Requirements below, it will only be used if the virtual machine is hosted on Windows Server 2012. ## Requirements | Requirement | Value | |-------------------------------------|-----------------------------------| | Minimum supported client<br/> | Windows 7 Enterprise<br/> | | Minimum supported server<br/> | Windows Server 2008 R2<br/> | ======================= File: desktop-src/wpd_sdk/mtp-extension-commands.md ======================= <filename>desktop-src/wpd_sdk/mtp-extension-commands.md --- description: MTP Extension Commands ms.assetid: DEE0E2D4-7727-4C26-A6B6-12F96CFCCA49 title: MTP Extension Commands ms.topic: article ms.date: 05/31/2018 --- # MTP Extension Commands ## In this section - [**WPD\_COMMAND\_MTP\_EXT\_END\_DATA\_TRANSFER command**](/windows/desktop/wpd_sdk/wpd-command-mtp-ext-end-data-transfer) - [**WPD\_COMMAND\_MTP\_EXT\_EXECUTE\_COMMAND\_WITH\_DATA\_TO\_READ command**](/windows/desktop/wpd_sdk/wpd-command-mtp-ext-execute-command-with-data-to-read) - [**WPD\_COMMAND\_MTP\_EXT\_EXECUTE\_COMMAND\_WITH\_DATA\_TO\_WRITE command**](/windows/desktop/wpd_sdk/wpd-command-mtp-ext-execute-command-with-data-to-write) - [**WPD\_COMMAND\_MTP\_EXT\_EXECUTE\_COMMAND\_WITHOUT\_DATA\_PHASE command**](/windows/desktop/wpd_sdk/wpd-command-mtp-ext-execute-command-without-data-phase) - [**WPD\_COMMAND\_MTP\_EXT\_GET\_SUPPORTED\_VENDOR\_OPCODES command**](/windows/desktop/wpd_sdk/wpd-command-mtp-ext-get-supported-vendor-opcodes) - [**WPD\_COMMAND\_MTP\_EXT\_GET\_VENDOR\_EXTENSION\_DESCRIPTION command**](/windows/desktop/wpd_sdk/wpd-command-mtp-ext-get-vendor-extension-description) - [**WPD\_COMMAND\_MTP\_EXT\_READ\_DATA command**](/windows/desktop/wpd_sdk/wpd-command-mtp-ext-read-data) - [**WPD\_COMMAND\_MTP\_EXT\_WRITE\_DATA command**](/windows/desktop/wpd_sdk/wpd-command-mtp-ext-write-data)     ======================= File: desktop-src/shell/how-to-create-icon-handlers.md ======================= <reponame>velden/win32 --- description: Describes how to create a handler for custom icon assignments. ms.assetid: 23ed3a21-cf62-4440-b983-fae23aa56890 title: How to Create Icon Handlers ms.topic: article ms.date: 05/31/2018 --- # How to Create Icon Handlers A [file type](fa-file-types.md) often has a custom icon associated with it, to make its members easily recognizable in Windows Explorer. The simplest way to assign a custom icon to a file type is to register the icon's file. However, an icon registered in this way will be the same for all members of the file type. You can have much more flexibility in assigning icons to the members of the file type by implementing an *icon handler*. An icon handler is a type of Shell extension handler that allows you to dynamically assign icons to the members of a file type. Every time a file of the type is displayed, the Shell queries the handler for the appropriate icon. For instance, an icon handler can assign different icons to different members of the file type, or vary the icon based on the current state of the file. The general procedures for implementing and registering a Shell extension handler are discussed in [Creating Shell Extension Handlers](handlers.md). This document focuses on those aspects of implementation that are specific to icon handlers. - [Implementing Icon Handlers](#step-1-implementing-icon-handlers) - [Implementing the IExtractIcon Interface](#step-2-implementing-the-iextracticon-interface) - [Registering Icon Handlers](#step-3-registering-icon-handlers) - [Related topics](#related-topics) ## Instructions ### Step 1: Implementing Icon Handlers Like all Shell extension handlers, icon handlers are in-process Component Object Model (COM) objects implemented as DLLs. They must export two interfaces in addition to [**IUnknown**](/windows/win32/api/unknwn/nn-unknwn-iunknown): [**IPersistFile**](/windows/win32/api/objidl/nn-objidl-ipersistfile) and [**IExtractIcon**](/windows/win32/api/shlobj_core/nn-shlobj_core-iextracticona). The Shell initializes the handler through its [**IPersistFile**](/windows/win32/api/objidl/nn-objidl-ipersistfile) interface. It uses this interface to request the handler's class identifier (CLSID) and provides it with the file's name. The rest of the operation takes place through the [**IExtractIcon**](/windows/win32/api/shlobj_core/nn-shlobj_core-iextracticona) interface. For a general discussion of how to implement Shell extension handlers, including the **IPersistFile** interface, see [Creating Shell Extension Handlers](handlers.md). The remainder of this document discusses how to implement the **IExtractIcon** interface. ### Step 2: Implementing the IExtractIcon Interface After the interface is initialized, the Shell uses the handler's [**IExtractIcon**](/windows/win32/api/shlobj_core/nn-shlobj_core-iextracticona) interface to request the appropriate icon. The interface has two methods: [**IExtractIcon::GetIconLocation**](/windows/win32/api/shlobj_core/nf-shlobj_core-iextracticona-geticonlocation) and [**IExtractIcon::Extract**](/windows/win32/api/shlobj_core/nf-shlobj_core-iextracticona-extract). Icons are identified by their location in the file system. The [**IExtractIcon::GetIconLocation**](/windows/win32/api/shlobj_core/nf-shlobj_core-iextracticona-geticonlocation) method is called to request this information. Set the *szIconFile* parameter to the file name. If there is more than one icon in the file, set *piIndex* to the icon's index. Assign appropriate values to the two flag variables. If you do not want to specify a file name, or if you do not want the Shell to extract the icon, set the **GIL\_NOTFILENAME** flag in the *pwFlags* parameter. You do not need to assign a value to *szIconFile*, but the handler must provide icon handles when the Shell calls [**IExtractIcon::Extract**](/windows/win32/api/shlobj_core/nf-shlobj_core-iextracticona-extract). If you return a file name, the Shell normally attempts to load the icon from its cache. To prevent the loading of a cached icon, set the **GIL\_DONTCACHE** flag in the *pwFlags* parameter. If a cached icon is not loaded, the Shell then calls [**IExtractIcon::Extract**](/windows/win32/api/shlobj_core/nf-shlobj_core-iextracticona-extract) to request the icon handle. If a file and index were specified by [**IExtractIcon::GetIconLocation**](/windows/win32/api/shlobj_core/nf-shlobj_core-iextracticona-geticonlocation), they are passed to [**IExtractIcon::Extract**](/windows/win32/api/shlobj_core/nf-shlobj_core-iextracticona-extract) in the *pszFile* and *nIconIndex* parameters, respectively. If a file name is provided, your handler can return S\_FALSE to have the Shell extract the icon. Otherwise, your handler must extract or otherwise produce large and small icons, and assign their HICON handles to the *phiconLarge* and *phiconSmall* parameters. The Shell adds the icons to its cache to expedite subsequent calls to the handler. ### Step 3: Registering Icon Handlers When you [statically register an icon](icon.md) for a [file type](fa-file-types.md), you create a **DefaultIcon** subkey under the ProgID for the file type. Its default value is set to the file that contains the icon. To register an icon handler, you must still have the **DefaultIcon** subkey, but its default value must be set to "%1". Add an **IconHandler** subkey to the **Shellex** subkey of the ProgID subkey, and set its default value to the string form of the handler's CLSID GUID. For a general discussion of how to register Shell extension handlers, see [Creating Shell Extension Handlers](handlers.md). The following example modifies the registry entry from [Customizing Icons](icon.md) so that the.myp file type now uses a shortcut menu handler instead of a statically defined icon. ``` HKEY_CLASSES_ROOT    .myp       (Default) = MyProgram.1    MyProgram.1       (Default) = MyProgram Application       DefaultIcon          (Default) = %1       Shellex          IconHandler             (Default) = {The handler's CLSID GUID} ``` ## Related topics <dl> <dt> [Creating Shell Extension Handlers](handlers.md) </dt> <dt> [**IPersistFile**](/windows/win32/api/objidl/nn-objidl-ipersistfile) </dt> <dt> [**IExtractIcon**](/windows/win32/api/shlobj_core/nn-shlobj_core-iextracticona) </dt> </dl>     ======================= File: desktop-src/printdocs/bindptproviderthunk.md ======================= <filename>desktop-src/printdocs/bindptproviderthunk.md<gh_stars>100-1000 --- description: Opens an instance of a print ticket provider. ms.assetid: 815cc360-8dcd-4c58-a64d-5d77436a8623 title: BindPTProviderThunk function ms.topic: reference ms.date: 05/31/2018 topic_type: - APIRef - kbSyntax api_name: - BindPTProviderThunk api_type: - DllExport api_location: - prntvpt.dll --- # BindPTProviderThunk function \[This function is not supported and might be disabled or deleted in future versions of Windows. [**PTOpenProviderEx**](/windows/desktop/api/prntvpt/nf-prntvpt-ptopenproviderex) provides equivalent functionality and should be used instead.\] Opens an instance of a print ticket provider. ## Syntax ```C++ HRESULT BindPTProviderThunk( _In_ LPTSTR pszPrinterName, _In_ INT maxVersion, _In_ INT prefVersion, _Out_ HPTPROVIDER *phProvider, _Out_ INT *usedVersion ); ``` ## Parameters <dl> <dt> *pszPrinterName* \[in\] </dt> <dd> The full name of a print queue. </dd> <dt> *maxVersion* \[in\] </dt> <dd> The latest version of the [Print Schema](./printschema.md) that the caller supports. </dd> <dt> *prefVersion* \[in\] </dt> <dd> The version of the [Print Schema](./printschema.md) requested by the caller. </dd> <dt> *phProvider* \[out\] </dt> <dd> A pointer to a handle to the print ticket provider. </dd> <dt> *usedVersion* \[out\] </dt> <dd> The version of the [Print Schema](./printschema.md) that the print ticket provider will use. </dd> </dl> ## Return value If the method succeeds, it returns **S\_OK**; otherwise, it returns an **HRESULT** error code. For more information about COM error codes, see [Error Handling](../com/error-handling-in-com.md). ## Remarks Before calling this function, the calling thread must initialize COM by calling [**CoInitializeEx**](/windows/desktop/api/combaseapi/nf-combaseapi-coinitializeex). ## Requirements | Requirement | Value | |-------------------------------------|----------------------------------------------------------------------------------------| | Minimum supported client<br/> | Windows XP \[desktop apps only\]<br/> | | Minimum supported server<br/> | Windows Server 2003 \[desktop apps only\]<br/> | | DLL<br/> | <dl> <dt>Prntvpt.dll</dt> </dl> | ## See also <dl> <dt> [Print Schema](./printschema.md) </dt> <dt> [**PTOpenProviderEx**](/windows/desktop/api/prntvpt/nf-prntvpt-ptopenproviderex) </dt> <dt> [Printing](printdocs-printing.md) </dt> <dt> [Print Spooler API Functions](printing-and-print-spooler-functions.md) </dt> </dl> ======================= File: desktop-src/NativeWiFi/wlan-profileschema-ssidconfig-wlanprofile-element.md ======================= --- description: Contains one or more SSIDs for wireless LANs. ms.assetid: f9c46db8-2933-48e1-8cb3-effeb13c43ed title: SSIDConfig (WLANProfile) Element ms.topic: reference ms.date: 05/31/2018 topic_type: - APIRef - kbSyntax api_name: - SSIDConfig api_type: - Schema api_location: --- # SSIDConfig (WLANProfile) Element The SSIDConfig (WLANProfile) element contains one or more SSIDs for wireless LANs. ``` syntax <xs:element name="SSIDConfig" maxOccurs="256" > <xs:complexType> <xs:sequence> <xs:element name="SSID" maxOccurs="256" > <xs:complexType> <xs:sequence> <xs:element name="hex" minOccurs="0" > <xs:simpleType> <xs:restriction base="hexBinary" > <xs:minLength value="1" /> <xs:maxLength value="32" /> </xs:restriction> </xs:simpleType> </xs:element> <xs:element name="name" minOccurs="0" > <xs:simpleType> <xs:restriction base="string" > <xs:minLength value="1" /> <xs:maxLength value="32" /> </xs:restriction> </xs:simpleType> </xs:element> <xs:any processContents="lax" minOccurs="0" maxOccurs="unbounded" namespace="##other" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="nonBroadcast" type="boolean" minOccurs="0" /> <xs:any processContents="lax" minOccurs="0" maxOccurs="unbounded" namespace="##other" /> </xs:sequence> </xs:complexType> </xs:element> ``` The **SSIDConfig** element is defined by the [**WLANProfile**](wlan-profileschema-wlanprofile-element.md) element. ## Child elements | Element | Type | Description | |----------------------------------------------------------------------------|-------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | [**hex**](wlan-profileschema-hex-ssid-element.md) | | Contains the SSID of a wireless LAN in hexadecimal format.<br/> | | [**name**](wlan-profileschema-name-ssid-element.md) | | Contains the (case-sensitive) name of the SSID of a wireless LAN.<br/> | | [**nonBroadcast**](wlan-profileschema-nonbroadcast-ssidconfig-element.md) | [boolean](/dotnet/api/system.boolean) | Indicates whether the network broadcasts its SSID.<br/> If [**connectionType**](wlan-profileschema-connectiontype-wlanprofile-element.md) is set to ESS, this value can be either **TRUE** or **FALSE**. The default value is **TRUE** if this element is absent.<br/> If [**connectionType**](wlan-profileschema-connectiontype-wlanprofile-element.md) is set to IBSS, this value must be **FALSE**.<br/> **Windows XP with SP3 and Wireless LAN API for Windows XP with SP2:** This element is not supported.<br/> | | [**SSID**](wlan-profileschema-ssid-ssidconfig-element.md) | | Contains an SSID for a wireless LAN.<br/> **Windows XP with SP3 and Wireless LAN API for Windows XP with SP2:** At most one [**SSID**](wlan-profileschema-ssid-ssidconfig-element.md) element can appear in a profile.<br/> | ## Examples To view sample profiles that use the **SSIDConfig** element, see [Wireless Profile Samples](wireless-profile-samples.md). ## Requirements | Requirement | Value | |-------------------------------------|---------------------------------------------------------------------| | Minimum supported client<br/> | Windows Vista, Windows XP with SP3 \[desktop apps only\]<br/> | | Minimum supported server<br/> | Windows Server 2008 \[desktop apps only\]<br/> | | Redistributable<br/> | Wireless LAN API for Windows XP with SP2<br/> | ## See also <dl> <dt> **Definition context of element in schema** </dt> <dt> [**WLANProfile**](wlan-profileschema-wlanprofile-element.md) </dt> <dt> **Possible immediate parent element in schema instance** </dt> <dt> [**WLANProfile**](wlan-profileschema-wlanprofile-element.md) </dt> </dl>     ======================= File: desktop-src/search/-search-sql-wildcards.md ======================= --- description: The CONTAINS predicate supports the use of the asterisk (\*) as a wildcard character to represent words and phrases. You can add the asterisk only at the end of the word or phrase. The presence of the asterisk enables the prefix-matching mode. ms.assetid: 9d141c7a-a721-416e-aa61-dabdb6533462 title: Using Wildcard Characters in the CONTAINS Predicate ms.topic: article ms.date: 05/31/2018 --- # Using Wildcard Characters in the CONTAINS Predicate The CONTAINS predicate supports the use of the asterisk (\*) as a wildcard character to represent words and phrases. You can add the asterisk only at the end of the word or phrase. The presence of the asterisk enables the prefix-matching mode. In this mode, matches are returned if the column contains the specified search word followed by zero or more other characters. If a phrase is provided, matches are detected if the column contains all the specified words with zero or more other characters following the final word. ## Examples The first example matches documents that have any word in the FileName column beginning with "serv". Example matching words include "server", "servers", and "service". ``` ...WHERE CONTAINS(System.FileName, '"serv*"') ``` The second example matches documents with any phrase in the FileName column that begins with "comp" and in which the next word begins with "serv". Example matching words include "comp server", "comp servers", and "comp service". ``` ...WHERE CONTAINS(System.FileName, '"comp serv*"') ``` The asterisk works only for prefix-matching and can be placed only at the end of the word or phrase; it does not work for suffix-matching. The following syntax is not valid and does not match documents with any word in the FileName column ending with "serve". ``` WHERE CONTAINS(System.FileName, '"*serve"') ``` ## Related topics <dl> <dt> **Reference** </dt> <dt> [FREETEXT Predicate](-search-sql-freetext.md) </dt> <dt> [WHERE Clause](-search-sql-where.md) </dt> </dl>     ======================= File: desktop-src/menurc/carets.md ======================= --- title: Carets description: This section discusses carets which are blinking lines, blocks, or bitmaps in the client area of a window. ms.assetid: 'vs|winui|~\winui\windowsuserinterface\resources\carets.htm' keywords: - resources,carets - carets,about - blinking lines - blinking blocks - blinking bitmaps ms.topic: article ms.date: 05/31/2018 --- # Carets A *caret* is a blinking line, block, or bitmap in the client area of a window. The caret typically indicates the place at which text or graphics will be inserted. The following illustration shows some common variations in the appearance of the caret. ![Shows 5 different ways a caret can appear.](images/cscrt-01.png) Applications can create a caret, change its blink time, and display, hide, or relocate the caret. ### In This Section | Name | Description | |----------------------------------------|---------------------------------------------------------------------------| | [About Carets](about-carets.md) | Discusses carets.<br/> | | [Using Carets](using-carets.md) | Code samples that show how to perform tasks related to carets.<br/> | | [Caret Reference](caret-reference.md) | Contains the API reference.<br/> | ### Caret Functions | Name | Description | |------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | [**CreateCaret**](/windows/desktop/api/Winuser/nf-winuser-createcaret) | Creates a new shape for the system caret and assigns ownership of the caret to the specified window. The caret shape can be a line, a block, or a bitmap. <br/> | | [**DestroyCaret**](/windows/desktop/api/Winuser/nf-winuser-destroycaret) | Destroys the caret's current shape, frees the caret from the window, and removes the caret from the screen. <br/> | | [**GetCaretBlinkTime**](/windows/desktop/api/Winuser/nf-winuser-getcaretblinktime) | Retrieves the time required to invert the caret's pixels. The user can set this value. <br/> | | [**GetCaretPos**](/windows/desktop/api/Winuser/nf-winuser-getcaretpos) | Copies the caret's position to the specified [**POINT**](/previous-versions//dd162805(v=vs.85)) structure. <br/> | | [**HideCaret**](/windows/desktop/api/Winuser/nf-winuser-hidecaret) | Removes the caret from the screen. Hiding a caret does not destroy its current shape or invalidate the insertion point. <br/> | | [**SetCaretBlinkTime**](/windows/desktop/api/Winuser/nf-winuser-setcaretblinktime) | Sets the caret blink time to the specified number of milliseconds. The blink time is the elapsed time, in milliseconds, required to invert the caret's pixels. <br/> | | [**SetCaretPos**](/windows/desktop/api/Winuser/nf-winuser-setcaretpos) | Moves the caret to the specified coordinates. If the window that owns the caret was created with the **CS\_OWNDC** class style, then the specified coordinates are subject to the mapping mode of the device context associated with that window. <br/> | | [**ShowCaret**](/windows/desktop/api/Winuser/nf-winuser-showcaret) | Makes the caret visible on the screen at the caret's current position. When the caret becomes visible, it begins flashing automatically. <br/> | ======================= File: desktop-src/TermServ/imsrdpclient5-geterrordescription.md ======================= <reponame>velden/win32<gh_stars>100-1000 --- title: IMsRdpClient5 GetErrorDescription method description: Retrieves the error description for the session disconnect events. ms.assetid: 8c8f7b10-7f79-4586-845e-e99f5ca81905 ms.tgt_platform: multiple keywords: - GetErrorDescription method Remote Desktop Services - GetErrorDescription method Remote Desktop Services, IMsRdpClient5 interface - IMsRdpClient5 interface Remote Desktop Services, GetErrorDescription method - GetErrorDescription method Remote Desktop Services, IMsRdpClient6 interface - IMsRdpClient6 interface Remote Desktop Services, GetErrorDescription method - GetErrorDescription method Remote Desktop Services, IMsRdpClient7 interface - IMsRdpClient7 interface Remote Desktop Services, GetErrorDescription method - GetErrorDescription method Remote Desktop Services, IMsRdpClient8 interface - IMsRdpClient8 interface Remote Desktop Services, GetErrorDescription method - GetErrorDescription method Remote Desktop Services, IMsRdpClient9 interface - IMsRdpClient9 interface Remote Desktop Services, GetErrorDescription method - GetErrorDescription method Remote Desktop Services, IMsRdpClient10 interface - IMsRdpClient10 interface Remote Desktop Services, GetErrorDescription method topic_type: - apiref api_name: - IMsRdpClient5.GetErrorDescription - IMsRdpClient6.GetErrorDescription - IMsRdpClient7.GetErrorDescription - IMsRdpClient8.GetErrorDescription - IMsRdpClient9.GetErrorDescription - IMsRdpClient10.GetErrorDescription api_location: - MsTscAx.dll api_type: - COM ms.topic: reference ms.date: 05/31/2018 --- # IMsRdpClient5::GetErrorDescription method Retrieves the error description for the session disconnect events. ## Syntax ```C++ HRESULT GetErrorDescription( [in] UINT disconnectReason, [in] UINT extendedDisconnectReason, [out] BSTR *pBstrErrorMsg ); ``` ## Parameters <dl> <dt> *disconnectReason* \[in\] </dt> <dd> The disconnect reason. </dd> <dt> *extendedDisconnectReason* \[in\] </dt> <dd> Provides detailed information about why a disconnect was initiated. </dd> <dt> *pBstrErrorMsg* \[out\] </dt> <dd> A pointer to a **BSTR** variable that receives the error message text. </dd> </dl> ## Return value This method does not return a value. ## Requirements | Requirement | Value | |-------------------------------------|----------------------------------------------------------------------------------------| | Minimum supported client<br/> | Windows Vista<br/> | | Minimum supported server<br/> | Windows Server 2008<br/> | | Type library<br/> | <dl> <dt>MsTscAx.dll</dt> </dl> | | DLL<br/> | <dl> <dt>MsTscAx.dll</dt> </dl> | | IID<br/> | IID\_IMsRdpClient5 is defined as 4eb5335b-6429-477d-b922-e06a28ecd8bf<br/> | ## See also <dl> <dt> [**IMsRdpClient5**](imsrdpclient5.md) </dt> <dt> [**IMsRdpClient6**](imsrdpclient6.md) </dt> <dt> [**IMsRdpClient7**](imsrdpclient7.md) </dt> <dt> [**IMsRdpClient8**](imsrdpclient8.md) </dt> <dt> [**IMsRdpClient9**](imsrdpclient9.md) </dt> <dt> [**IMsRdpClient10**](imsrdpclient10.md) </dt> </dl> ======================= File: desktop-src/SecProv/backuprecoveryinformationtoactivedirectory-win32-encryptablevolume.md ======================= <filename>desktop-src/SecProv/backuprecoveryinformationtoactivedirectory-win32-encryptablevolume.md --- description: Backs up recovery data to Active Directory. ms.assetid: 664562b3-5679-4185-8bbc-5d5350494707 title: BackupRecoveryInformationToActiveDirectory method of the Win32_EncryptableVolume class ms.topic: reference ms.date: 05/31/2018 topic_type: - APIRef - kbSyntax api_name: - Win32_EncryptableVolume.BackupRecoveryInformationToActiveDirectory api_type: - COM api_location: - Root\CIMV2\Security\MicrosoftVolumeEncryption --- # BackupRecoveryInformationToActiveDirectory method of the Win32\_EncryptableVolume class The **BackupRecoveryInformationToActiveDirectory** method of the [**Win32\_EncryptableVolume**](win32-encryptablevolume.md) class backs up recovery data to Active Directory. This method requires a numerical password protector to be present on the volume. Group Policy must also be configured to enable backup of recovery information to Active Directory. ## Syntax ```mof uint32 BackupRecoveryInformationToActiveDirectory( [in] string VolumeKeyProtectorID ); ``` ## Parameters <dl> <dt> *VolumeKeyProtectorID* \[in\] </dt> <dd> Type: **string** A unique string identifier used to manage an encrypted volume key protector. This key protector must be a numerical password protector. </dd> </dl> ## Return value Type: **uint32** This method returns one of the following codes or another error code if it fails. | Return code/value | Description | |----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------| | <dl> <dt>**S\_OK**</dt> <dt>0 (0x0)</dt> </dl> | The method was successful.<br/> | | <dl> <dt>**S\_FALSE**</dt> <dt>1 (0x1)</dt> </dl> | Group Policy does not permit the storage of recovery information to Active Directory.<br/> | | <dl> <dt>**FVE\_E\_NOT\_ACTIVATED**</dt> <dt>2150694920 (0x80310008)</dt> </dl> | BitLocker is not enabled on the volume. Add a key protector to enable BitLocker. <br/> | | <dl> <dt>**FVE\_E\_INVALID\_PROTECTOR\_TYPE**</dt> <dt>2150694970 (0x8031003A)</dt> </dl> | The specified key protector is not a numerical key protector. You must enter a numerical password protector. <br/> |   ## Requirements | Requirement | Value | |-------------------------------------|---------------------------------------------------------------------------------------------------------| | Minimum supported client<br/> | Windows 7 Enterprise, Windows 7 Ultimate \[desktop apps only\]<br/> | | Minimum supported server<br/> | Windows Server 2008 R2 \[desktop apps only\]<br/> | | Namespace<br/> | Root\\CIMV2\\Security\\MicrosoftVolumeEncryption<br/> | | MOF<br/> | <dl> <dt>Win32\_encryptablevolume.mof</dt> </dl> | ## See also <dl> <dt> [**Win32\_EncryptableVolume**](win32-encryptablevolume.md) </dt> </dl>     ======================= File: desktop-src/Wua_Sdk/using-the-windows-update-agent-api.md ======================= --- description: To use the Windows Update Agent (WUA) API, first create an instance of one of the interfaces by creating the object from the appropriate coclass. ms.assetid: b304971d-584a-4d0f-be5b-26f0ab315ec9 title: Using the Windows Update Agent API ms.topic: article ms.date: 05/31/2018 --- # Using the Windows Update Agent API To use the Windows Update Agent (WUA) API, first create an instance of one of the interfaces by creating the object from the appropriate coclass. The following topics describe how you can use the WUA API: > [!IMPORTANT] > > These scripts are intended to demonstrate the use of the Windows Update Agent APIs, and provide examples of how developers can use these APIs to solve problems. These scripts are not intended as production code, and the scripts themselves are not supported by Microsoft (though the underlying Windows Update Agent APIs are supported).   - [Windows Update Agent Object Model](windows-update-agent-object-model.md) - [Determining the Current Version of WUA](determining-the-current-version-of-wua.md) - [Updating the Windows Update Agent](updating-the-windows-update-agent.md) - [Updating Windows Update Agent Header Files](updating-windows-update-agent-header-files.md) - [Using WUA to Scan for Updates Offline](using-wua-to-scan-for-updates-offline.md) - [Secured Methods and Properties in the WUA API](secured-methods-and-properties-in-the-wua-api.md) - [Searching, Downloading, and Installing Updates](searching--downloading--and-installing-updates.md) - [Searching, Downloading, and Installing Specific Updates](searching--downloading--and-installing-specific-updates.md) - [Using WUA From a Remote Computer](using-wua-from-a-remote-computer.md) - [Guidelines for Asynchronous WUA Operations](guidelines-for-asynchronous-wua-operations.md) - [Using WUA from a Secondary Logon (Run As) Process](using-wua-from-a-secondary-logon--run-as--process.md) - [WUA Success and Error Codes](wua-success-and-error-codes-.md) - [WUA Networking Error Codes](wua-networking-error-codes-.md)     ======================= File: desktop-src/DevNotes/sdbopendatabase.md ======================= <gh_stars>100-1000 --- description: Opens the specified shim database. ms.assetid: 148181d7-a20a-467c-984b-e32013960783 title: SdbOpenDatabase function ms.topic: reference ms.date: 05/31/2018 topic_type: - APIRef - kbSyntax api_name: - SdbOpenDatabase api_type: - DllExport api_location: - Apphelp.dll --- # SdbOpenDatabase function Opens the specified shim database. ## Syntax ```C++ PDB WINAPI SdbOpenDatabase( _In_ LPCTSTR   pwszPath, _In_ PATH_TYPE eType ); ``` ## Parameters <dl> <dt> *pwszPath* \[in\] </dt> <dd> The database path. This parameter cannot be **NULL**. </dd> <dt> *eType* \[in\] </dt> <dd> The path type. See [**PATH\_TYPE**](path-type.md) for a list of values. </dd> </dl> ## Return value The function returns a handle to the shim database. ## Requirements | Requirement | Value | |-------------------------------------|----------------------------------------------------------------------------------------| | Minimum supported client<br/> | Windows XP \[desktop apps only\]<br/> | | Minimum supported server<br/> | Windows Server 2003 \[desktop apps only\]<br/> | | DLL<br/> | <dl> <dt>Apphelp.dll</dt> </dl> | ## See also <dl> <dt> [**SdbCreateDatabase**](sdbcreatedatabase.md) </dt> </dl>     ======================= File: desktop-src/DirectShow/avi-file-format.md ======================= --- description: AVI File Format ms.assetid: 986de213-4d25-4768-a6bc-37891cd38353 title: AVI File Format ms.topic: article ms.date: 05/31/2018 --- # AVI File Format This section describes the AVI file format. - [AVI RIFF File Reference](avi-riff-file-reference.md) - [DV Data in the AVI File Format](dv-data-in-the-avi-file-format.md) ## Related topics <dl> <dt> [Appendixes](appendixes.md) </dt> </dl>     ======================= File: desktop-src/Tapi/device-events-ovr.md ======================= --- description: TAPI responds to device changes such as a phone that has started ringing or a modem that has been removed by firing device events. ms.assetid: afa504ca-6e70-4076-a179-31002d3b38e2 title: Device Events (Telephony API) ms.topic: article ms.date: 05/31/2018 --- # Device Events (Telephony API) TAPI responds to device changes such as a phone that has started ringing or a modem that has been removed by firing device events. A TAPI application should respond to a device event by querying for the specific change that has occurred and then taking appropriate action. An application may screen for events it will receive using [event notification](event-notification.md). **TAPI 2.x:** Applications receive notification of device events using the [**LINE\_LINEDEVSTATE**](./line-linedevstate.md) message. The current status of an address is determined by calling [**lineGetAddressStatus**](/windows/win32/api/tapi/nf-tapi-linegetaddressstatus), which returns its information in a [**LINEADDRESSSTATUS**](/windows/win32/api/tapi/ns-tapi-lineaddressstatus) structure. The status of a specified open line device is obtained by calling [**lineGetLineDevStatus**](/windows/win32/api/tapi/nf-tapi-linegetlinedevstatus), which returns its information in a [**LINEDEVSTATUS**](/windows/win32/api/tapi/ns-tapi-linedevstatus) structure. **TAPI 3.x:** Applications receive an [**ADDRESS\_EVENT**](/windows/desktop/api/Tapi3if/ne-tapi3if-address_event) notification, which is processed using the [**ITAddressEvent**](/windows/desktop/api/tapi3if/nn-tapi3if-itaddressevent) interface. The [**ITAddressCapabilities**](/windows/desktop/api/tapi3if/nn-tapi3if-itaddresscapabilities) can then be used to acquire more detail information.     ======================= File: desktop-src/shell/mlwinhelp.md ======================= <reponame>velden/win32 --- description: Starts Windows Help (Winhelp.exe) and passes additional data that indicates the nature of the help requested by the application. ms.assetid: e7466832-f236-4567-b05d-37d25fe88ba2 title: MLWinHelp function ms.topic: reference ms.date: 05/31/2018 topic_type: - APIRef - kbSyntax api_name: - MLWinHelp - MLWinHelpA - MLWinHelpW api_type: - DllExport api_location: - Shlwapi.dll --- # MLWinHelp function \[This function is available through Windows XP and Windows Server 2003. It might be altered or unavailable in subsequent versions of Windows.\] Starts Windows Help (Winhelp.exe) and passes additional data that indicates the nature of the help requested by the application. ## Syntax ```C++ BOOL MLWinHelp( _In_ HWND      hWndMain, _In_ LPCTSTR   lpszHelp, _In_ UINT      uCommand, _In_ DWORD_PTR dwData ); ``` ## Parameters <dl> <dt> *hWndMain* \[in\] </dt> <dd> Type: **HWND** A handle to the window requesting help. The **MLWinHelp** function uses this handle to keep track of which applications have requested help. If the *uCommand* parameter specifies HELP\_CONTEXTMENU or HELP\_WM\_HELP, *hWndMain* identifies the control requesting help. </dd> <dt> *lpszHelp* \[in\] </dt> <dd> Type: **LPCTSTR** The address of a null-terminated string containing the path, if necessary, and the name of the help file that **MLWinHelp** is to display. The file name can be followed by an angle bracket (>) and the name of a secondary window if the topic is to be displayed in a secondary window rather than in the primary window. You must define the name of the secondary window in the \[WINDOWS\] section of the help project (.hpj) file. </dd> <dt> *uCommand* \[in\] </dt> <dd> Type: **UINT** The type of help requested. For a list of possible values and how they affect the value to place in the *dwData* parameter, see the Remarks section. </dd> <dt> *dwData* \[in\] </dt> <dd> Type: **DWORD\_PTR** Additional data. The value used depends on the value of the *uCommand* parameter. For a list of possible *dwData* values, see the Remarks section. </dd> </dl> ## Return value Type: **BOOL** Returns a nonzero value on success, or zero otherwise. To get extended error information, call [**GetLastError**](/windows/win32/api/errhandlingapi/nf-errhandlingapi-getlasterror). ## Remarks This function is not included in a header file and must be called by ordinal 395 for **MLWinHelpA** and 397 for **MLWinHelpW**. **MLWinHelp** is essentially a wrapper for [**WinHelp**](/windows/desktop/api/Winuser/nf-winuser-winhelpa). It attempts to obtain the path to the help file corresponding to the current UI language setting before calling **WinHelp**. If it succeeds, it passes that path. If it fails, it passes the path pointed to by *lpszHelp*. This function fails if called from any context but the current user. Before closing the window that requested help, the application must call **MLWinHelp** with the *uCommand* parameter set to HELP\_QUIT. Until all applications have done this, Windows Help will not terminate. Note that calling Windows Help with the HELP\_QUIT command is not necessary if you used the HELP\_CONTEXTPOPUP command to start Windows Help. The following table shows the possible values for the *uCommand* parameter and the corresponding formats of the *dwData* parameter. | *uCommand* | Action | *dwData* | |---------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | HELP\_COMMAND | Executes a help macro or macro string. | Address of a string that specifies the name of the help macro(s) to run. If the string specifies multiple macro names, the names must be separated by semicolons. You must use the short form of the macro name for some macros because Windows Help does not support the long name. | | HELP\_CONTENTS | Displays the topic specified by the Contents option in the \[OPTIONS\] section of the.hpj file. This command is for backward compatibility. New applications should provide a.cnt file and use the HELP\_FINDER command. | Ignored; set to 0. | | HELP\_CONTEXT | Displays the topic identified by the specified context identifier defined in the \[MAP\] section of the.hpj file. | Contains the context identifier for the topic. | | HELP\_CONTEXTMENU | Displays the **Help** menu for the selected window, then displays the topic for the selected control in a pop-up window. | Address of an array of **DWORD** pairs. The first **DWORD** in each pair is the control identifier, and the second is the context identifier for the topic. The array must be terminated by a pair of zeros {0,0}. If you do not want to add help to a particular control, set its context identifier to -1. | | HELP\_CONTEXTPOPUP | Displays the topic identified by the specified context identifier defined in the \[MAP\] section of the.hpj file in a pop-up window. | Contains the context identifier for a topic. | | HELP\_FINDER | Displays the **Help Topics** dialog box. | Ignored; set to 0. | | HELP\_FORCEFILE | Ensures that Windows Help is displaying the correct help file. If the incorrect help file is being displayed, Windows Help opens the correct one; otherwise, there is no action. | Ignored; set to 0. | | HELP\_HELPONHELP | Displays help on how to use Windows Help, if the Winhlp32.hlp file is available. | Ignored; set to 0. | | HELP\_INDEX | Displays the topic specified by the Contents option in the \[OPTIONS\] section of the.hpj file. This command is for backward compatibility. New applications should use the HELP\_FINDER command. | Ignored; set to 0. | | HELP\_KEY | Displays the topic in the keyword table that matches the specified keyword, if there is an exact match. If there is more than one match, displays the index with the topics listed in the **Topics Found** list box. | Address of a keyword string. Multiple keywords must be separated by semicolons. | | HELP\_MULTIKEY | Displays the topic specified by a keyword in an alternative keyword table. | Address of a [**MULTIKEYHELP**](/windows/win32/api/winuser/ns-winuser-multikeyhelpa) structure that specifies a table footnote character and a keyword. | | HELP\_PARTIALKEY | Displays the topic in the keyword table that matches the specified keyword, if there is an exact match. If there is more than one match, displays the **Topics Found** dialog box. To display the index without passing a keyword, use a pointer to an empty string. | Address of a keyword string. Multiple keywords must be separated by semicolons. | | HELP\_QUIT | Informs Windows Help that it is no longer needed. If no other applications have asked for help, Windows closes Windows Help. | Ignored; set to 0. | | HELP\_SETCONTENTS | Specifies the Contents topic. Windows Help displays this topic when the user clicks the **Contents** button if the help file does not have an associated.cnt file. | Contains the context identifier for the Contents topic. | | HELP\_SETPOPUP\_POS | Sets the position of the subsequent pop-up window. | Contains the position data. Use the [**MAKELONG**](/previous-versions/windows/desktop/legacy/ms632660(v=vs.85)) macro to concatenate the horizontal and vertical coordinates into a single value. The pop-up window is positioned as if the mouse cursor were at the specified point when the pop-up window was invoked. | | HELP\_SETWINPOS | Displays the Windows Help window, if it is minimized or in memory, and sets its size and position as specified. | Address of a [**HELPWININFO**](/windows/win32/api/winuser/ns-winuser-helpwininfoa) structure that specifies the size and position of either a primary or secondary help window. | | HELP\_TCARD | Indicates that a command is for a training card instance of Windows Help. Combine this command with other commands using the bitwise OR operator. | Depends on the command with which this command is combined. | | HELP\_WM\_HELP | Displays the topic for the control identified by the *hWndMain* parameter in a pop-up window. | Address of an array of **DWORD** pairs. The first **DWORD** in each pair is a control identifier, and the second is a context identifier for a topic. The array must be terminated by a pair of zeros {0,0}. If you do not want to add Help to a particular control, set its context identifier to -1. |   ## Requirements | Requirement | Value | |-------------------------------------|---------------------------------------------------------------------------------------------------------------| | Minimum supported client<br/> | Windows 2000 Professional, Windows XP \[desktop apps only\]<br/> | | Minimum supported server<br/> | Windows Server 2003 \[desktop apps only\]<br/> | | Header<br/> | <dl> <dt>None</dt> </dl> | | DLL<br/> | <dl> <dt>Shlwapi.dll (version 5.0 or later)</dt> </dl> | | Unicode and ANSI names<br/> | **MLWinHelpW** (Unicode) and **MLWinHelpA** (ANSI)<br/> | ## See also <dl> <dt> [**HELPWININFO**](/windows/win32/api/winuser/ns-winuser-helpwininfoa) </dt> <dt> [**MULTIKEYHELP**](/windows/win32/api/winuser/ns-winuser-multikeyhelpa) </dt> </dl>     ======================= File: desktop-src/SensorsAPI/using-logical-sensors.md ======================= <reponame>velden/win32 --- description: Using Logical Sensors ms.assetid: 97f4c44e-27dd-4f2a-b987-060bb2d9bc00 title: Using Logical Sensors ms.topic: article ms.date: 05/31/2018 --- # Using Logical Sensors To instantiate a device node for a logical sensor, or to reconnect to an existing logical sensor device node, an application or service must call [**ILogicalSensorManager::Connect**](/previous-versions/windows/desktop/legacy/dd374029(v=vs.85)). The *pPropertyStore* parameter for this method requires a pointer to an [IPropertyStore](/windows/win32/api/propsys/nn-propsys-ipropertystore) interface that contains the IDs for the sensor drivers to connect to. This means that you must create a property store and add this data to the store before calling this method. ### Connecting to the Logical Sensor To connect to a logical sensor, you must provide, at a minimum, a hardware ID, as defined in the sensor driver's.inf file, and a logical **GUID** that identifies the sensor. The platform uses this **GUID** to identify the sensor when you choose to disconnect from, or uninstall, the sensor device node. The following example code creates a helper method that connects to a specified logical sensor. The method parameters receive the sensor hardware ID and a unique **GUID** to identify the sensor. ```C++ HRESULT ConnectToLogicalSensor(PCWSTR* wszHardwareID, GUID guidLogicalID) { HRESULT hr = S_OK; ILogicalSensorManager* pLSM = NULL; IPropertyStore* pStore = NULL; PROPVARIANT pv = {}; // Create the property store. hr = PSCreateMemoryPropertyStore(IID_PPV_ARGS(&pStore)); if(SUCCEEDED(hr)) { // Create the logical sensor manager. hr = CoCreateInstance(CLSID_LogicalSensorManager, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&pLSM)); } // Fill in the values. if(SUCCEEDED(hr)) { hr = InitPropVariantFromStringVector(wszHardwareID, 1, &pv); } if(SUCCEEDED(hr)) { hr = pStore->SetValue(PKEY_Device_HardwareIds, pv); } if(SUCCEEDED(hr)) { hr = pStore->SetValue(PKEY_Device_CompatibleIds, pv); } if(SUCCEEDED(hr)) { // Connect to the logical sensor. hr = pLSM->Connect(guidLogicalID, pStore); } SafeRelease(&pStore); SafeRelease(&pLSM); return hr; } ``` ### Disconnecting from a Logical Sensor To disconnect from a logical sensor, you must provide the same logical ID that you used when you called [**Connect**](/previous-versions/windows/desktop/legacy/dd374029(v=vs.85)). The following example code creates a helper function that disconnects from a logical sensor. ```C++ HRESULT DisconnectFromLogicalSensor(GUID guidLogicalID) { HRESULT hr = S_OK; ILogicalSensorManager* pLSM = NULL; if(SUCCEEDED(hr)) { // Create the logical sensor manager. hr = CoCreateInstance(CLSID_LogicalSensorManager, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&pLSM)); } if(SUCCEEDED(hr)) { hr = pLSM->Disconnect(guidLogicalID); } SafeRelease(&pLSM); return hr; } ``` ### Uninstalling a Logical Sensor To uninstall a logical sensor, you must provide the same logical ID that you used when you called [**Connect**](/previous-versions/windows/desktop/legacy/dd374029(v=vs.85)). The following example code creates a helper function that uninstalls a logical sensor. ```C++ HRESULT UninstallLogicalSensor(REFGUID guidLogicalID) { HRESULT hr = S_OK; ILogicalSensorManager* pLSM; // Create the logical sensor manager. hr = CoCreateInstance(CLSID_LogicalSensorManager, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&pLSM)); if(SUCCEEDED(hr)) { hr = pLSM->Uninstall(guidLogicalID); } SafeRelease(&pLSM); return hr; } ``` ## Related topics <dl> <dt> [About Logical Sensors](about-logical-sensors.md) </dt> </dl>     ======================= File: desktop-src/Msi/import-files.md ======================= <filename>desktop-src/Msi/import-files.md --- description: The VBScript file WiImport.vbs is provided in the Windows SDK Components for Windows Installer Developers. This sample shows how to write a script to import tables into a Windows Installer database. ms.assetid: 37580bd6-30c7-4239-9717-223a381ba021 title: Import Files ms.topic: article ms.date: 05/31/2018 --- # Import Files The VBScript file WiImport.vbs is provided in the [Windows SDK Components for Windows Installer Developers](platform-sdk-components-for-windows-installer-developers.md). This sample shows how to write a script to import tables into a Windows Installer database. The script connects to an [**Installer**](installer-object.md) object, opens a database, processes a list of files, and commits the changes before closing the database. The sample demonstrates the use of: - [**OpenDatabase Method (Installer Object)**](installer-opendatabase.md) - [**LastErrorRecord method**](installer-lasterrorrecord.md) of the [**Installer object**](installer-object.md) - [**Import method**](database-import.md) - [**Commit method**](database-commit.md) of the [**Database object**](database-object.md) You'll require the CScript.exe or WScript.exe version of Windows Script Host to use this sample. To use CScript.exe to run this sample, use the following syntax at the command prompt. **cscript WiImport.vbs \[path to database\]\[path to folder\]\[options\] \[archive file list**\] Help is displayed if the first argument is /? or if too few arguments are specified. To redirect the output to a file, end the command line with VBS > \[path to file\].The sample returns a value of 0 for success, 1 if help is invoked, and 2 if the script fails. Specify the path to a Windows installer database that is to be created or that is to receive the imported tables. Specify the path to the folder containing the archive files of the tables that are being imported. List the names of the archive files that are being imported. Wildcard file names, such as \*.idt, can be used to import multiple files. The following options may be specified anywhere on the command line before the file list. | Option | Description | |---------------------|--------------------------------------------------------------------------------------------------------------------------------------| | no option specified | Import the list of table archive files from the specified folder into the Windows Installer database. | | /c | Create a Windows Installer database and then import the list of table archive files from the specified folder into the new database. |   For more information, see [Windows Installer Scripting Examples](windows-installer-scripting-examples.md) for additional scripting examples. For sample utilities that do not require Windows Script Host, see [Windows Installer Development Tools](windows-installer-development-tools.md). Note that [A Localization Example](a-localization-example.md) also demonstrates [Importing Localized Error and ActionText Tables](importing-localized-error-and-actiontext-tables.md).     ======================= File: desktop-src/Msi/removal-of-isolated-components.md ======================= --- description: Windows Installer performs the following actions during the removal of an application when the package contains isolated components. Typically, Component\_Shared is a DLL that is shared by Component\_Application and other client executables. ms.assetid: 26343a01-9a06-43d5-bbe3-959faf51739d title: Removal of Isolated Components ms.topic: article ms.date: 05/31/2018 --- # Removal of Isolated Components Windows Installer performs the following actions during the removal of an application when the package contains isolated components. Typically, Component\_Shared is a DLL that is shared by Component\_Application and other client executables. ## Uninstall - Remove the files of Component\_Shared from the folder containing Component\_Application only if Component\_Application is also being removed. - If the msidbComponentAttributesSharedDllRefCount bit is set in the [Component table](component-table.md) decrement the SharedDLL refcount. - Remove the.LOCAL zero-byte file from the folder containing Component\_Application. - Remove Component\_Application from the client list of Component\_Shared. - Remove all of the resources of Component\_Application as usual. If there are other products remaining on the client list of Component\_Shared: - Remove no files from the shared location of Component\_Shared. If the SharedDLL refcount for Component\_Shared is 0 after being decremented, or if there are no other remaining clients of Component\_Shared: - Remove the files of Component\_Shared from the shared location. - Process all uninstall actions with respect to this component.     ======================= File: desktop-src/SbsCs/side-by-side-assembly-functions.md ======================= --- description: The side-by-side assembly API uses the following functions to access the Side-by-Side Assembly interfaces. ms.assetid: 040a4f27-8fe9-4436-9c8a-ff58d1effd10 title: Side-by-Side Assembly Functions ms.topic: article ms.date: 05/31/2018 --- # Side-by-Side Assembly Functions The side-by-side assembly API uses the following functions to access the Side-by-Side Assembly interfaces. | Function | Description | |--------------------------------------------------------------|--------------------------------------------------------------------------------| | [**CreateAssemblyCache**](/windows/desktop/api/Winsxs/nf-winsxs-createassemblycache) | Obtains an instance of the [**IAssemblyCache**](/windows/desktop/api/winsxs/nn-winsxs-iassemblycache) interface. | | [**CreateAssemblyNameObject**](/windows/desktop/api/Winsxs/nf-winsxs-createassemblynameobject) | Obtains an instance of the [**IAssemblyName**](/windows/desktop/api/winsxs/nn-winsxs-iassemblyname) interface. |       ======================= File: desktop-src/Controls/tb-getrect.md ======================= --- title: TB_GETRECT message (Commctrl.h) description: Retrieves the bounding rectangle for a specified toolbar button. ms.assetid: a93885eb-7eb7-4434-ad51-80fb30d3bfa1 keywords: - TB_GETRECT message Windows Controls topic_type: - apiref api_name: - TB_GETRECT api_location: - Commctrl.h api_type: - HeaderDef ms.topic: reference ms.date: 05/31/2018 --- # TB\_GETRECT message Retrieves the bounding rectangle for a specified toolbar button. ## Parameters <dl> <dt> *wParam* </dt> <dd> Command identifier of the button. </dd> <dt> *lParam* </dt> <dd> Pointer to a [**RECT**](/previous-versions//dd162897(v=vs.85)) structure that will receive the bounding rectangle information. </dd> </dl> ## Return value Returns nonzero if successful, or zero otherwise. ## Remarks This message does not retrieve the bounding rectangle for buttons whose state is set to the [**TBSTATE\_HIDDEN**](toolbar-button-states.md) value. ## Requirements | Requirement | Value | |-------------------------------------|---------------------------------------------------------------------------------------| | Minimum supported client<br/> | Windows Vista \[desktop apps only\]<br/> | | Minimum supported server<br/> | Windows Server 2003 \[desktop apps only\]<br/> | | Header<br/> | <dl> <dt>Commctrl.h</dt> </dl> | ======================= File: desktop-src/Tapi/itconferenceblob-get-characterset.md ======================= <reponame>velden/win32 --- description: The get\_CharacterSet method gets a BLOB\_CHARACTER\_SET descriptor of the character set used in the current conference blob. ms.assetid: 9783d18c-79f6-4faa-b12d-9504c13d54e3 title: ITConferenceBlob::get_CharacterSet method (Sdpblb.h) ms.topic: reference ms.date: 05/31/2018 --- # ITConferenceBlob::get\_CharacterSet method \[ Rendezvous IP Telephony Conferencing controls and interfaces are not available for use in Windows Vista, Windows Server 2008, and subsequent versions of the operating system. The RTC Client API provides similar functionality.\] The **get\_CharacterSet** method gets a [**BLOB\_CHARACTER\_SET**](blob-character-set.md) descriptor of the character set used in the current conference blob. ## Syntax ```C++ HRESULT get_CharacterSet( [out] BLOB_CHARACTER_SET *pCharacterSet ); ``` ## Parameters <dl> <dt> *pCharacterSet* \[out\] </dt> <dd> Pointer to a [**BLOB\_CHARACTER\_SET**](blob-character-set.md) descriptor of the character set. </dd> </dl> ## Return value This method can return one of these values. | Return code | Description | |---------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------| | <dl> <dt>**S\_OK**</dt> </dl> | Method succeeded.<br/> | | <dl> <dt>**E\_POINTER**</dt> </dl> | The *pCharacterSet* parameter is not a valid pointer.<br/> | | <dl> <dt>**E\_OUTOFMEMORY**</dt> </dl> | Insufficient memory exists to perform the operation.<br/> | | <dl> <dt>**E\_FAIL**</dt> </dl> | Unspecified error.<br/> | | <dl> <dt>**E\_NOTIMPL**</dt> </dl> | This method is not yet implemented.<br/> | | <dl> <dt>**E\_INVALIDARG**</dt> </dl> | *pCharacterSet* is **NULL**.<br/> | | <dl> <dt>**(HRESULT) ERROR\_INVALID\_DATA**</dt> </dl> | The current character set is invalid or unavailable.<br/> | ## Requirements | Requirement | Value | |-------------------------|---------------------------------------------------------------------------------------| | TAPI version<br/> | Requires TAPI 3.0 or later<br/> | | Header<br/> | <dl> <dt>Sdpblb.h</dt> </dl> | | Library<br/> | <dl> <dt>Uuid.lib</dt> </dl> | | DLL<br/> | <dl> <dt>Sdpblb.dll</dt> </dl> | ## See also <dl> <dt> [**ITConferenceBlob**](itconferenceblob.md) </dt> <dt> [**BLOB\_CHARACTER\_SET**](blob-character-set.md) </dt> </dl> ======================= File: desktop-src/lwef/photo-wizards-bumper.md ======================= <reponame>velden/win32 --- title: Photo Wizards description: Photo Wizards ms.assetid: 5a692997-ad58-4dd9-8f1c-e22d1f98dc2c ms.topic: article ms.date: 05/31/2018 --- # Photo Wizards - [Online Printing Wizard](online-printing-wizard.md) - [Photo Printing Wizard](photo-printing-wizard.md)     ======================= File: desktop-src/WinSock/sample-code-for-a-service-provider-2.md ======================= --- description: This section contains a source code sample that demonstrates how to implement the GetXbyY functions using the new, protocol-independent RNR functions. ms.assetid: d6246d47-11c2-4e4b-8a2b-17fd9cb041fc title: Sample Code for a Service Provider ms.topic: article ms.date: 05/31/2018 --- # Sample Code for a Service Provider This section contains a source code sample that demonstrates how to implement the **GetXbyY** functions using the new, protocol-independent RNR functions. A developer should implement these functions as a starting point. To comply with the Windows Sockets specification, many more functions are needed. > [!IMPORTANT] > The following code is not guaranteed to compile.   ```C++ #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <winsock2.h> #include <Ws2tcpip.h> #include <windns.h> #include <svcguid.h> #include <stdio.h> // Link with ws2_32.lib #pragma comment(lib, "Ws2_32.lib") #undef WINSOCK_API_LINKAGE #define WINSOCK_API_LINKAGE __control_entrypoint(DllExport) /*++ xbyrnr.cpp GetXbyY emulation via new WinSock2 RNR. This source module shows code that is built into the WinSock2 DLL (ws2_32.dll). It demonstrates how the older GetXByY functions are mapped to the new WSALookupServiceBegin, WSALookupServiceNext, WSALookupServiceEnd functions. This module is not guaranteed to compile. It is provided as source code for RNR namespace service providers to understand what will be coming down to their code in response to the traditional GetXbyY calls. At this time, only gethostname gethostbyname gethostbyaddr getservbyname getservbyport are implemented in this manner. Warning: This is not provided as a template for either RNR applications or namespace providers. This code is only intended to illustrate what happens in the WinSock2 DLL to map the GetXbyY calls to the new RNR APIs. --*/ // The initial buffer size passed by getxbyy functions // to WSALookupServiceNext. If it is insuffucient for the query, // the amount specified by the provider is allocated and call is // repeated. // The initial buffer is allocated from stack, so we try to keep it // relatively small, but still for performance reasons we want to be able // to satisfy most of the calls with just this amount #define RNR_BUFFER_SIZE (sizeof(WSAQUERYSET) + 256) // // Forward declares // LPBLOB getxyDataEnt( PCHAR *pResults, DWORD dwSize, LPSTR lpszName, LPGUID lpType, LPSTR *lppName ); VOID FixList(PCHAR ** List, PCHAR Base); VOID UnpackHostEnt(struct hostent * hostent); VOID UnpackServEnt(struct servent * servent); GUID HostAddrByNameGuid = SVCID_INET_HOSTADDRBYNAME; GUID HostNameGuid = SVCID_HOSTNAME; GUID AddressGuid = SVCID_INET_HOSTADDRBYINETSTRING; GUID IANAGuid = SVCID_INET_SERVICEBYNAME; // // Utility to turn a list of offsets into a list of addresses. Used // to convert structures returned as BLOBs. // VOID FixList(PCHAR ** List, PCHAR Base) { if(*List) { PCHAR * Addr; Addr = *List = (PCHAR *)( ((DWORD)*List + Base) ); while(*Addr) { *Addr = (PCHAR)(((DWORD)*Addr + Base)); Addr++; } } } // // Routine to convert a hostent returned in a BLOB to one with // usable pointers. The structure is converted in-place. // VOID UnpackHostEnt(struct hostent * hostent) { PCHAR pch; pch = (PCHAR)hostent; if(hostent->h_name) { hostent->h_name = (PCHAR)((DWORD)hostent->h_name + pch); } FixList(&hostent->h_aliases, pch); FixList(&hostent->h_addr_list, pch); } // // Routine to unpack a servent returned in a BLOB to one with // usable pointers. The structure is converted in-place // VOID UnpackServEnt(struct servent * servent) { PCHAR pch; pch = (PCHAR)servent; FixList(&servent->s_aliases, pch); servent->s_name = (PCHAR)(DWORD(servent->s_name) + pch); servent->s_proto = (PCHAR)(DWORD(servent->s_proto) + pch); } WINSOCK_API_LINKAGE struct hostent FAR * WSAAPI gethostbyaddr( IN const char *addr, IN int len, IN int type ) /*++ Routine Description: Get host information corresponding to an address. Arguments: addr - A pointer to an address in network byte order. len - The length of the address, which must be 4 for PF_INET addresses. type - The type of the address, which must be PF_INET. Returns: If no error occurs, gethostbyaddr() returns a pointer to the hostent structure described above. Otherwise it returns a NULL pointer and a specific error code is stored with SetErrorCode(). --*/ { CHAR qbuf[DNS_MAX_NAME_BUFFER_LENGTH]; struct hostent *ph; LPBLOB pBlob; PCHAR pResults; CHAR localResults[RNR_BUFFER_SIZE]; INT ErrorCode; PTHREAD Thread; ErrorCode = PROLOG(&Thread); if(ErrorCode!= NO_ERROR) { SetLastError(ErrorCode); return(NULL); } if (!addr ) { SetLastError(WSAEINVAL); return(NULL); } pResults = localResults; // // NOTICE. Only handles current inet address forms. // (void)sprintf_s(qbuf, sizeof(qbuf); "%u.%u.%u.%u", ((unsigned)addr[0] & 0xff), ((unsigned)addr[1] & 0xff), ((unsigned)addr[2] & 0xff), ((unsigned)addr[3] & 0xff)); pBlob = getxyDataEnt(pResults, RNR_BUFFER_SIZE, qbuf, &AddressGuid, 0); if(pBlob) { ph = (struct hostent *)Thread->CopyHostEnt(pBlob); if(ph) { UnpackHostEnt(ph); } } else { ph = 0; if(GetLastError() == WSASERVICE_NOT_FOUND) { SetLastError(WSANO_ADDRESS); } } if (pResults!= localResults) delete pResults; return(ph); } // gethostbyaddr WINSOCK_API_LINKAGE struct hostent* FAR WSAAPI gethostbyname( IN const char FAR * name ) /*++ Routine Description: Get host information corresponding to a hostname. Arguments: name - A pointer to the null-terminated name of the host. Returns: If no error occurs, gethostbyname() returns a pointer to the hostent structure described above. Otherwise it returns a null pointer and a specific errorr code is stored with SetErrorCode(). --*/ { struct hostent * hent; LPBLOB pBlob; PCHAR pResults; CHAR localResults[RNR_BUFFER_SIZE]; INT ErrorCode; CHAR szLocalName[200]; // for storing the local name. This // is simply a big number assumed // to be large enough. This is used // only when the caller chooses not to // provide a name. PCHAR pszName; PDTHREAD Thread; ErrorCode = PROLOG(&Thread); if(ErrorCode!= NO_ERROR) { SetLastError(ErrorCode); return(NULL); } // // A NULL input name means look for the local name. So, // get it. // if(!name ||!*name) { if(gethostname(szLocalName, 200)!= NO_ERROR) { return(NULL); } pszName = szLocalName; } else { pszName = (PCHAR)name; } pResults = localResults; pBlob = getxyDataEnt( &pResults, RNR_BUFFER_SIZE, pszName, &HostAddrByNameGuid, 0); if(pBlob && (!name ||!*name ) ) { pBlob = getxyDataEnt( &pResults, RNR_BUFFER_SIZE, NULL, &HostAddrByNameGuid, 0); } if(pBlob ) { hent = (struct hostent *)Thread->CopyHostEnt(pBlob); if(hent) { UnpackHostEnt(hent); } } else { hent = 0; if(GetLastError() == WSASERVICE_NOT_FOUND) { SetLastError(WSAHOST_NOT_FOUND); } } if (pResults!=localResults) delete pResults; return(hent); } // gethostbyname WINSOCK_API_LINKAGE int WSAAPI gethostname( OUT char FAR * name, IN int namelen ) /*++ Routine Description: Return the standard host name for the local computer. Arguments: name - A pointer to a buffer that will receive the host name. namelen - The length of the buffer. Returns: Zero on success else SOCKET_ERROR. The error code is stored with SetErrorCode(). --*/ { PCHAR lpName; PCHAR pResults; CHAR localResults[RNR_BUFFER_SIZE]; INT ErrorCode; PDTHREAD Thread; ErrorCode = PROLOG(&Thread); if(ErrorCode!= NO_ERROR) { gSetLastError(ErrorCode); return(NULL); } pResults = localResults; if(getxyDataEnt(pResults, RNR_BUFFER_SIZE, NULL, &HostNameGuid, &lpName )) { INT iSize = strlen(lpName) + 1; if(iSize <= namelen) { memcpy(name, lpName, iSize); } else { SetLastError(WSAEFAULT); ErrorCode = SOCKET_ERROR; } } else { ErrorCode = SOCKET_ERROR; // assume LastError has been set } if (pResults!=localResults) delete pResults; return(ErrorCode); } // gethostname WINSOCK_API_LINKAGE struct servent FAR * WSAAPI getservbyport( IN int port, IN const char FAR * proto ) /*++ Routine Description: Get service information corresponding to a port and protocol. Arguments: port - The port for a service, in network byte order. proto - An optional pointer to a protocol name. If this is NULL, getservbyport() returns the first service entry for which the port matches the s_port. Otherwise getservbyport() matches both the port and the proto. Returns: If no error occurs, getservbyport() returns a pointer to the servent structure described above. Otherwise it returns a NULL pointer and a specific error code is stored with SetErrorCode(). --*/ { PCHAR pszTemp; struct servent * sent; LPBLOB pBlob; PCHAR pResults; CHAR localResults[RNR_BUFFER_SIZE]; INT ErrorCode; PDTHREAD Thread; ErrorCode = PROLOG(&Thread); if(ErrorCode!= NO_ERROR) { SetLastError(ErrorCode); return(NULL); } pResults = localResults; if(!proto) { proto = ""; } // // the 5 is the max number of digits in a port // pszTemp = new CHAR[strlen(proto) + 1 + 1 + 5]; sprintf_s(pszTemp, strlen(proto)+1+1+5, "%d/%s", (port & 0xffff), proto); pBlob = getxyDataEnt(pResults, RNR_BUFFER_SIZE, pszTemp, &IANAGuid, 0 ); delete pszTemp; if(!pBlob) { sent = 0; if(GetLastError() == WSATYPE_NOT_FOUND) { SetLastError(WSANO_DATA); } } else { sent = (struct servent *)Thread->CopyServEnt(pBlob); if(sent) { UnpackServEnt(sent); } } if (pResults!=localResults) delete pResults; return(sent); } // getservbyport WINSOCK_API_LINKAGE struct servent FAR * WSAAPI getservbyname( IN const char FAR * name, IN const char FAR * proto ) /*++ Routine Description: Get service information corresponding to a service name and protocol. Arguments: name - A pointer to a null-terminated service name. proto - An optional pointer to a null-terminated protocol name. If this pointer is NULL, getservbyname() returns the first service entry for which the name matches the s_name or one of the s_aliases. Otherwise getservbyname() matches both the name and the proto. Returns: If no error occurs, getservbyname() returns a pointer to the servent structure described above. Otherwise it returns a NULL pointer and a specific error code is stored with SetErrorCode(). --*/ { PCHAR pszTemp; struct servent * sent; LPBLOB pBlob; PCHAR pResults; CHAR localResults[RNR_BUFFER_SIZE]; INT ErrorCode; PDTHREAD Thread; ErrorCode = PROLOG(&Thread); if(ErrorCode!= NO_ERROR) { SetLastError(ErrorCode); return(NULL); } pResults = localResults; if(!proto) { proto = ""; } pszTemp = new CHAR[strlen(name) + strlen(proto) + 1 + 1]; sprintf_s(pszTemp, strlen(name)+strlen(proto)+1+1, "%s/%s", name, proto); pBlob = getxyDataEnt(pResults, RNR_BUFFER_SIZE, pszTemp, &IANAGuid, 0 ); delete pszTemp; if(!pBlob) { sent = 0; if(GetLastError() == WSATYPE_NOT_FOUND) { SetLastError(WSANO_DATA); } } else { sent = (struct servent *)Thread->CopyServEnt(pBlob); if(sent) { UnpackServEnt(sent); } } if (pResults!=localResults) delete pResults; return(sent); } // getservbyname // // Common routine for obtaining a xxxent buffer. Input is used to // execute the WSALookup series of APIs. // // Args: // pResults -- a buffer supplied by the caller to be used in // the WASLookup calls. This should be as large as // the caller can afford to offer. // dwLength -- number of bytes in pResults // lpszName -- pointer to the service name. May by NULL // lpType -- pointer to the service type. This should be one of // the SVCID_INET_xxxxx types. It may be anything // that produces a BLOB. // lppName -- pointer to pointer where the resulting name pointer // is stored. May be NULL if the name is not needed. // // Returns: // 0 -- No BLOB data was returned. In general, this means the // operation failed. Evev if the WSALookupNext succeeded // and returned a name, the name will not be returned. // else -- a pointer to the BLOB. // // // // The protocol restrictions list for all emulation operations. This // should limit the invoked providers to the set that know about // hostents and servents. If not, then the special SVCID_INET GUIDs // should take care of the remainder. // AFPROTOCOLS afp[2] = { {AF_INET, IPPROTO_UDP}, {AF_INET, IPPROTO_TCP} }; LPBLOB getxyDataEnt( PCHAR *pResults, DWORD dwLength, LPSTR lpszName, LPGUID lpType, LPSTR *lppName) { PWSAQUERYSETA pwsaq = (PWSAQUERYSETA)pResults; int err; HANDLE hRnR; LPBLOB pvRet = 0; INT Err = 0; // // create the query // memset(pwsaq, 0, sizeof(*pwsaq)); pwsaq->dwSize = sizeof(*pwsaq); pwsaq->lpszServiceInstanceName = lpszName; pwsaq->lpServiceClassId = lpType; pwsaq->dwNameSpace = NS_ALL; pwsaq->dwNumberOfProtocols = 2; pwsaq->lpafpProtocols = &afp[0]; err = WSALookupServiceBeginA(pwsaq, LUP_RETURN_BLOB | LUP_RETURN_NAME, &hRnR); if(err == NO_ERROR) { // // The query was accepted, so execute it via the Next call. // err = WSALookupServiceNextA( hRnR, 0, &dwLength, pwsaq); // // if NO_ERROR was returned and a BLOB is present, this // worked, just return the requested information. Otherwise, // invent an error or capture the transmitted one. // if(err == NO_ERROR) { if(pvRet = pwsaq->lpBlob) { if(lppName) { *lppName = pwsaq->lpszServiceInstanceName; } } else { err = WSANO_DATA; } } else { // // WSALookupServiceEnd clobbers LastError so save // it before closing the handle. // err = GetLastError(); } WSALookupServiceEnd(hRnR); // // if an error happened, stash the value in LastError // if(err!= NO_ERROR) { SetLastError(err); } } return(pvRet); } ```     ======================= File: desktop-src/TermServ/win32-rdshcollection-keyvaluedelete.md ======================= <reponame>velden/win32 --- title: KeyValueDelete method of the Win32_RDSHCollection class description: Deletes the specified key (and associated value) from the collection. ms.assetid: 968d6744-7b4a-45e5-87fb-90c408dbc771 ms.tgt_platform: multiple keywords: - KeyValueDelete method Remote Desktop Services - KeyValueDelete method Remote Desktop Services, Win32_RDSHCollection class - Win32_RDSHCollection class Remote Desktop Services, KeyValueDelete method topic_type: - apiref api_name: - Win32_RDSHCollection.KeyValueDelete api_location: - RDMS.dll api_type: - COM ms.topic: reference ms.date: 05/31/2018 --- # KeyValueDelete method of the Win32\_RDSHCollection class Deletes the specified key (and associated value) from the collection. ## Syntax ```mof uint32 KeyValueDelete( [in] string Key ); ``` ## Parameters <dl> <dt> *Key* \[in\] </dt> <dd> The key to delete. </dd> </dl> ## Requirements | Requirement | Value | |-------------------------------------|---------------------------------------------------------------------------------------------| | Minimum supported client<br/> | None supported<br/> | | Minimum supported server<br/> | Windows Server 2016<br/> | | Namespace<br/> | Root\\cimv2\\rdms<br/> | | MOF<br/> | <dl> <dt>RDManagement.mof</dt> </dl> | | DLL<br/> | <dl> <dt>RDMS.dll</dt> </dl> | ## See also <dl> <dt> [**Win32\_RDSHCollection**](win32-rdshcollection.md) </dt> </dl> ======================= File: desktop-src/TaskSchd/taskschedulerschema-tasktype-complextype.md ======================= <reponame>velden/win32 --- title: taskType Complex Type (Task Scheduler) description: Defines the child elements and sequencing information for the Task element. ms.assetid: 622b2bf4-c7e0-403c-bd6c-99b687c1d439 keywords: - taskType complex type Task Scheduler topic_type: - apiref api_name: - taskType api_type: - Schema ms.topic: reference ms.date: 05/31/2018 api_location: --- # taskType Complex Type Defines the child elements and sequencing information for the [**Task**](taskschedulerschema-task-element.md) element. ``` syntax <xs:complexType name="taskType"> <xs:all> <xs:element name="RegistrationInfo" type="registrationInfoType" minOccurs="0" /> <xs:element name="Triggers" type="triggersType" minOccurs="0" /> <xs:element name="Settings" type="settingsType" minOccurs="0" /> <xs:element name="Data" type="dataType" minOccurs="0" /> <xs:element name="Principals" type="principalsType" minOccurs="0" /> <xs:element name="Actions" type="actionsType" /> </xs:all> <xs:attribute name="version" type="versionType" use="optional" fixed="1.3" /> </xs:complexType> ``` ## Child elements | Element | Type | Description | |-----------------------------------------------------------------------------------|--------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------| | [**Actions**](taskschedulerschema-actions-tasktype-element.md) | [**actionsType**](taskschedulerschema-actionstype-complextype.md) | Specifies the actions performed by the task.<br/> | | [**Data**](taskschedulerschema-data-tasktype-element.md) | [**dataType**](taskschedulerschema-datatype-complextype.md) | Specifies addition data that is associated with the task, but is otherwise unused by the Task Scheduler service.<br/> | | [**Principals**](taskschedulerschema-principals-tasktype-element.md) | [**principalsType**](taskschedulerschema-principalstype-complextype.md) | Specifies the security contexts that can be used to run the task.<br/> | | [**RegistrationInfo**](taskschedulerschema-registrationinfo-tasktype-element.md) | [**registrationInfoType**](taskschedulerschema-registrationinfotype-complextype.md) | Specifies administrative information about the task, such as the author of the task and the date the task is registered.<br/> | | [**Settings**](taskschedulerschema-settings-tasktype-element.md) | [**settingsType**](taskschedulerschema-settingstype-complextype.md) | Specifies the settings that the Task Scheduler uses to perform the task.<br/> | | [**Triggers**](taskschedulerschema-triggers-tasktype-element.md) | [**triggersType**](taskschedulerschema-triggerstype-complextype.md) | Specifies the triggers that start the task.<br/> | ## Attributes | Name | Type | Description | |---------|-------------------------------------------------------------------|-----------------------------------------------| | version | [**versionType**](taskschedulerschema-versiontype-simpletype.md) | Specifies the version of the task.<br/> | ## Requirements | Requirement | Value | |-------------------------------------|------------------------------------------------------| | Minimum supported client<br/> | Windows Vista \[desktop apps only\]<br/> | | Minimum supported server<br/> | Windows Server 2008 \[desktop apps only\]<br/> | ## See also <dl> <dt> [Task Scheduler Schema Complex Types](task-scheduler-schema-complex-types.md) </dt> <dt> [Task Scheduler](task-scheduler-start-page.md) </dt> </dl> ======================= File: desktop-src/DevNotes/rtlprefixunicodestring.md ======================= <reponame>velden/win32 --- description: Compares two Unicode strings to determine whether one string is a prefix of the other. ms.assetid: 7D859C0A-2F72-49A4-8B49-130DCA103F37 title: RtlPrefixUnicodeString function (Ntddk.h) ms.topic: reference ms.date: 05/31/2018 topic_type: - APIRef - kbSyntax api_name: - RtlPrefixUnicodeString api_type: - DllExport api_location: - Ntdll.dll --- # RtlPrefixUnicodeString function Compares two Unicode strings to determine whether one string is a prefix of the other. ## Syntax ```C++ BOOLEAN RtlPrefixUnicodeString( _In_ PCUNICODE_STRING String1, _In_ PCUNICODE_STRING String2, _In_ BOOLEAN          CaseInSensitive ); ``` ## Parameters <dl> <dt> *String1* \[in\] </dt> <dd> Pointer to the first string, which might be a prefix of the buffered Unicode string at *String2*. </dd> <dt> *String2* \[in\] </dt> <dd> Pointer to the second string. </dd> <dt> *CaseInSensitive* \[in\] </dt> <dd> If **TRUE**, case should be ignored when doing the comparison. </dd> </dl> ## Return value **TRUE** if *String1* is a prefix of *String2*. ## Requirements | Requirement | Value | |-------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------| | Minimum supported client<br/> | Windows 2000 Professional \[desktop apps only\]<br/> | | Minimum supported server<br/> | Windows 2000 Server \[desktop apps only\]<br/> | | Target platform<br/> | <dl> <dt>[Universal](https://msdn.microsoft.com/Library/Windows/Hardware/EB2264A4-BAE8-446B-B9A5-19893936DDCA)</dt> </dl> | | Header<br/> | <dl> <dt>Ntddk.h (include Ntddk.h)</dt> </dl> | | Library<br/> | <dl> <dt>Ntdll.lib</dt> </dl> | | DLL<br/> | <dl> <dt>Ntdll.dll</dt> </dl> | ## See also <dl> <dt> [**RtlCompareUnicodeString**](rtlcompareunicodestring.md) </dt> </dl>     ======================= File: desktop-src/tablet/paragraphlinemetrics-element.md ======================= --- description: Contains information about the lines of a paragraph. ms.assetid: 6a36d7a1-c14a-42cd-81e1-1743673eca83 title: ParagraphLineMetrics Element ms.topic: reference ms.date: 05/31/2018 --- # ParagraphLineMetrics Element Contains information about the lines of a paragraph. ## Definition ``` syntax <xs:element name="ParagraphLineMetrics" type="ParagraphLineMetricsType" /> ``` ## Parent Elements [**Paragraph**](paragraph-element.md) ## Child Elements [**Baseline**](baseline-element.md) ## Attributes None. ## Element Information | Element | Value | |--------------|---------------------------------------------------------------------------------------| | Element type | [**ParagraphLineMetricsType**](paragraphlinemetricstype-complex-type.md) complexType | | Namespace | urn:schemas-microsoft-com:tabletpc:richink | | Schema name | Journal Reader |       ======================= File: desktop-src/SecAuthN/certificate-stores.md ======================= --- description: Both client and server certificates must be stored in a certificate store accessible by the application process. ms.assetid: 3be91b9b-ecc0-4cf2-88ca-77fd25d2dafc title: Certificate Stores ms.topic: article ms.date: 05/31/2018 --- # Certificate Stores Both [*client*](/windows/desktop/SecGloss/c-gly) and [*server certificates*](/windows/desktop/SecGloss/s-gly) must be stored in a [*certificate store*](/windows/desktop/SecGloss/c-gly) accessible by the application process. Typically, this is the My store, also known as the personal store. Client applications such as Internet Explorer normally use the My store of the current user while servers such as Internet Information Services (IIS) use the system My store of the local computer. The Root store and the [*certification authority*](/windows/desktop/SecGloss/c-gly) (CA) store are used when Schannel or an application builds a certificate chain to be sent to the remote computer. These stores are used to validate a received certificate chain. For more information, see [Performing Authentication Using Schannel](performing-authentication-using-schannel.md).     ======================= File: desktop-src/WMP/wmplibiwmpcdromrip-iwmpcdromrip-stoprip--vb-and-c.md ======================= --- title: IWMPCdromRip stopRip method description: The stopRip method stops the CD ripping process. ms.assetid: c2565d0d-1203-4bd3-9d43-58e971e6ec88 keywords: - stopRip method Windows Media Player - stopRip method Windows Media Player, IWMPCdromRip interface - IWMPCdromRip interface Windows Media Player, stopRip method topic_type: - apiref api_name: - IWMPCdromRip.stopRip api_location: - Interop.WMPLib.dll api_type: - COM ms.topic: reference ms.date: 05/31/2018 --- # IWMPCdromRip::stopRip method The **stopRip** method stops the CD ripping process. ## Syntax ```CSharp public void stopRip(); ``` ```VB Public Sub stopRip() Implements IWMPCdromRip.stopRip ``` ## Parameters This method has no parameters. ## Return value This method does not return a value. ## Requirements | Requirement | Value | |----------------------|------------------------------------------------------------------------------------------------------------------------| | Version<br/> | Windows Media Player 11.<br/> | | Namespace<br/> | **WMPLib**<br/> | | Assembly<br/> | <dl> <dt>Interop.WMPLib.dll (Interop.WMPLib.dll.dll)</dt> </dl> | ## See also <dl> <dt> [**IWMPCdromRip Interface (VB and C#)**](iwmpcdromrip--vb-and-c.md) </dt> <dt> [**IWMPCdromRip.startRip**](wmplibiwmpcdromrip-iwmpcdromrip-startrip--vb-and-c.md) </dt> <dt> [**Ripping a CD**](ripping-a-cd.md) </dt> </dl> ======================= File: desktop-src/Msi/setting-the-code-page-of-a-database.md ======================= <reponame>velden/win32<filename>desktop-src/Msi/setting-the-code-page-of-a-database.md --- description: Always set the code page of a database prior to adding any localization information. ms.assetid: 0d8aee30-989a-4093-8718-1bb90029c0fb title: Setting the Code Page of a Database ms.topic: article ms.date: 05/31/2018 --- # Setting the Code Page of a Database Always set the code page of a database prior to adding any localization information. Attempting to set the code page after entering data into the database is not recommended because this could corrupt extended characters. Localization can be greatly facilitated by starting with a database that is code page neutral. For details, see [Creating a database with a neutral code page](creating-a-database-with-a-neutral-code-page.md). You may determine the current code page of a database as described in [Determining an installation database's code page](determining-an-installation-database-s-code-page.md). See [Localizing the Error and ActionText Tables](localizing-the-error-and-actiontext-tables.md) for a list of numeric code pages. You may set the code page of a blank database, or a database with a neutral code page, by importing a text archive file having a non-neutral code page with [**MsiDatabaseImport**](/windows/desktop/api/Msiquery/nf-msiquery-msidatabaseimporta). This sets the code page of the database to the imported file's code page. All archive files subsequently imported into the database must then have the same code page as the first file. If a text archive file is exported from a database, the code page of the archive file is the same as the parent database. See [Code Page Handling of Imported and Exported Tables](code-page-handling-of-imported-and-exported-tables.md). The code page of any database may be set to a specified numeric code page by using [**MsiDatabaseImport**](/windows/desktop/api/Msiquery/nf-msiquery-msidatabaseimporta) to import a text archive file with the following format: Two blank lines; followed by a line containing the numeric code page, a tab delimiter, and the exact string: \_ForceCodepage. Note that with Windows 2000, this translates all of the strings in the database to the code page of \_ForceCodepage. This may be intended when localizing an existing database and translating all non-neutral strings to the new code page. However, this causes an error if the database contains non-neutral strings that are not to be translated. The utility WiLangId.vbs provides an example of how to set the code page of a package using the [**Import method**](database-import.md). A copy of WiLangId.vbs is provided in the Windows Installer SDK. You can use this utility to determine the language versions that are supported by the database (Package), the language the installer uses for any strings in the user interface that are not authored into the database (Product), or the single ANSI code page for the string pool (Codepage). For information on using WiLangId.vbs see the help page: [Manage Language and Codepage](manage-language-and-codepage.md). To determine the values of Product, Package, and Codepage, run WiLangId.vbs as follows. **cscript wilangid.vbs** *\[path to database\]* To set the Codepage of the package run the following command line. **cscript wilangid.vbs** *\[path to database\]* **Codepage** *\[value\]* For example, to set the Codepage of test.msi to the numeric ANSI code page value 1252, run the following command line. **cscript wilangid.vbs c:\\temp\\test.msi Codepage 1252**     ======================= File: desktop-src/direct3d9/d3dvertexblendflags.md ======================= <gh_stars>100-1000 --- description: Defines flags used to control the number or matrices that the system applies when performing multimatrix vertex blending. ms.assetid: 5314f455-ce5f-4ff5-81fc-d3dffc8705b7 title: D3DVERTEXBLENDFLAGS enumeration (D3D9Types.h) ms.topic: reference ms.date: 05/31/2018 topic_type: - APIRef - kbSyntax api_name: - D3DVERTEXBLENDFLAGS api_type: - HeaderDef api_location: - D3D9Types.h --- # D3DVERTEXBLENDFLAGS enumeration Defines flags used to control the number or matrices that the system applies when performing multimatrix vertex blending. ## Syntax ```C++ typedef enum D3DVERTEXBLENDFLAGS { D3DVBF_DISABLE   = 0, D3DVBF_1WEIGHTS  = 1, D3DVBF_2WEIGHTS  = 2, D3DVBF_3WEIGHTS  = 3, D3DVBF_TWEENING  = 255, D3DVBF_0WEIGHTS  = 256 } D3DVERTEXBLENDFLAGS, *LPD3DVERTEXBLENDFLAGS; ``` ## Constants <dl> <dt> <span id="D3DVBF_DISABLE"></span><span id="d3dvbf_disable"></span>**D3DVBF\_DISABLE** </dt> <dd> Disable vertex blending; apply only the world matrix set by the [**D3DTS\_WORLDMATRIX**](d3dts-worldmatrix.md) macro, where the index value for the transformation state is 0. </dd> <dt> <span id="D3DVBF_1WEIGHTS"></span><span id="d3dvbf_1weights"></span>**D3DVBF\_1WEIGHTS** </dt> <dd> Enable vertex blending between the two matrices set by the [**D3DTS\_WORLDMATRIX**](d3dts-worldmatrix.md) macro, where the index value for the transformation states are 0 and 1. </dd> <dt> <span id="D3DVBF_2WEIGHTS"></span><span id="d3dvbf_2weights"></span>**D3DVBF\_2WEIGHTS** </dt> <dd> Enable vertex blending between the three matrices set by the [**D3DTS\_WORLDMATRIX**](d3dts-worldmatrix.md) macro, where the index value for the transformation states are 0, 1, and 2. </dd> <dt> <span id="D3DVBF_3WEIGHTS"></span><span id="d3dvbf_3weights"></span>**D3DVBF\_3WEIGHTS** </dt> <dd> Enable vertex blending between the four matrices set by the [**D3DTS\_WORLDMATRIX**](d3dts-worldmatrix.md) macro, where the index value for the transformation states are 0, 1, 2, and 3. </dd> <dt> <span id="D3DVBF_TWEENING"></span><span id="d3dvbf_tweening"></span>**D3DVBF\_TWEENING** </dt> <dd> Vertex blending is done by using the value assigned to D3DRS\_TWEENFACTOR. </dd> <dt> <span id="D3DVBF_0WEIGHTS"></span><span id="d3dvbf_0weights"></span>**D3DVBF\_0WEIGHTS** </dt> <dd> Use a single matrix with a weight of 1.0. </dd> </dl> ## Remarks Members of this type are used with the D3DRS\_VERTEXBLEND render state. Geometry blending (multimatrix vertex blending) requires that your application use a vertex format that has blending (beta) weights for each vertex. ## Requirements | Requirement | Value | |-------------------|----------------------------------------------------------------------------------------| | Header<br/> | <dl> <dt>D3D9Types.h</dt> </dl> | ## See also <dl> <dt> [Direct3D Enumerations](dx9-graphics-reference-d3d-enums.md) </dt> <dt> [**D3DRENDERSTATETYPE**](./d3drenderstatetype.md) </dt> <dt> [**D3DTS\_WORLD**](d3dts-world.md) </dt> <dt> [**D3DTS\_WORLDn**](d3dts-worldn.md) </dt> <dt> [**D3DTS\_WORLDMATRIX**](d3dts-worldmatrix.md) </dt> </dl>     ======================= File: desktop-src/Tapi/itqosapplicationid-setqosapplicationid.md ======================= <gh_stars>100-1000 --- description: The SetQOSApplicationID method sets the QOS identifier for the application. ms.assetid: e25cf749-6673-47eb-b843-4066f475b8f1 title: ITQOSApplicationID::SetQOSApplicationID method (Ipmsp.h) ms.topic: reference ms.date: 05/31/2018 --- # ITQOSApplicationID::SetQOSApplicationID method \[ This method is not available for use in Windows Vista, Windows Server 2008, and subsequent versions of the operating system. The RTC Client API provides similar functionality.\] The **SetQOSApplicationID** method sets the QOS identifier for the application. ## Syntax ```C++ HRESULT SetQOSApplicationID( [in] BSTR pApplicationID, [in] BSTR pApplicationGUID, [in] BSTR pSubIDs ); ``` ## Parameters <dl> <dt> *pApplicationID* \[in\] </dt> <dd> Unique identifier for the application process. </dd> <dt> *pApplicationGUID* \[in\] </dt> <dd> Application GUID. </dd> <dt> *pSubIDs* \[in\] </dt> <dd> Sub-IDs associated with the current call. </dd> </dl> ## Return value This method can return one of these values. | Return code | Description | |-----------------------------------------------------------------------------------------------|-----------------------------------------------------------------| | <dl> <dt>**S\_OK**</dt> </dl> | Method succeeded.<br/> | | <dl> <dt>**E\_OUTOFMEMORY**</dt> </dl> | Insufficient memory exists to perform the operation.<br/> | ## Requirements | Requirement | Value | |-------------------------|--------------------------------------------------------------------------------------| | TAPI version<br/> | Requires TAPI 3.1<br/> | | Header<br/> | <dl> <dt>Ipmsp.h</dt> </dl> | | Library<br/> | <dl> <dt>Uuid.lib</dt> </dl> | | DLL<br/> | <dl> <dt>Tapi3.dll</dt> </dl> | ## See also <dl> <dt> [**ITQOSApplicationID**](itqosapplicationid.md) </dt> </dl> ======================= File: desktop-src/ADSchema/a-msds-bridgeheadserversused.md ======================= <reponame>velden/win32 --- title: ms-DS-BridgeHead-Servers-Used attribute description: List of bridge head servers used by KCC in the previous run. ms.assetid: f99e9ef2-1a64-49ab-b6b7-7613f3246e61 ms.tgt_platform: multiple keywords: - ms-DS-BridgeHead-Servers-Used attribute AD Schema - msDS-BridgeHeadServersUsed attribute AD Schema topic_type: - apiref api_name: - ms-DS-BridgeHead-Servers-Used api_type: - Schema ms.topic: reference ms.date: 05/31/2018 --- # ms-DS-BridgeHead-Servers-Used attribute List of bridge head servers used by KCC in the previous run. | Entry | Value | |-------------------|-------------------------------------------------| | CN | ms-DS-BridgeHead-Servers-Used | | Ldap-Display-Name | msDS-BridgeHeadServersUsed | | Size | \- | | Update Privilege | \- | | Update Frequency | \- | | Attribute-Id | 1.2.840.113556.1.4.2049 | | System-Id-Guid | 3ced1465-7b71-2541-8780-1e1ea6243a82 | | Syntax | [**Object(DN-Binary)**](s-object-dn-binary.md) | ## Implementations - [**Windows Server 2008**](#windows-server-2008) - [**Windows Server 2008 R2**](#windows-server-2008-r2) - [**Windows Server 2012**](#windows-server-2012) ## Windows Server 2008 | Entry | Value | |------------------------|-----------------------------------| | Link-Id | 2160 | | MAPI-Id | \- | | System-Only | False | | Is-Single-Valued | False | | Is Indexed | False | | In Global Catalog | False | | NT-Security-Descriptor | O:BAG:BAD:S: | | Range-Lower | \- | | Range-Upper | \- | | Search-Flags | 0x00000000 | | System-Flags | 0x00000019 | | Classes used in | [**Site**](c-site.md)<br/> | ## Windows Server 2008 R2 | Entry | Value | |------------------------|-----------------------------------| | Link-Id | 2160 | | MAPI-Id | \- | | System-Only | False | | Is-Single-Valued | False | | Is Indexed | False | | In Global Catalog | False | | NT-Security-Descriptor | O:BAG:BAD:S: | | Range-Lower | \- | | Range-Upper | \- | | Search-Flags | 0x00000000 | | System-Flags | 0x00000019 | | Classes used in | [**Site**](c-site.md)<br/> | ## Windows Server 2012 | Entry | Value | |------------------------|-----------------------------------| | Link-Id | 2160 | | MAPI-Id | \- | | System-Only | False | | Is-Single-Valued | False | | Is Indexed | False | | In Global Catalog | False | | NT-Security-Descriptor | O:BAG:BAD:S: | | Range-Lower | \- | | Range-Upper | \- | | Search-Flags | 0x00000000 | | System-Flags | 0x00000019 | | Classes used in | [**Site**](c-site.md)<br/> | ======================= File: desktop-src/Multimedia/capability.md ======================= <reponame>velden/win32 --- title: capability command description: The capability command requests information about a particular capability of a device. All MCI devices recognize this command. ms.assetid: 1b470473-0de6-41ba-9f6e-41f0b13ceaeb keywords: - capability command Windows Multimedia topic_type: - apiref api_name: - capability api_type: - NA ms.topic: reference ms.date: 05/31/2018 --- # capability command The capability command requests information about a particular capability of a device. All MCI devices recognize this command. To send this command, call the [**mciSendString**](/previous-versions//dd757161(v=vs.85)) function with the *lpszCommand* parameter set as follows. ``` syntax _stprintf_s( lpszCommand, TEXT("capability %s %s %s"), lpszDeviceID, lpszRequest, lpszFlags ); ``` ## Parameters <dl> <dt> <span id="lpszDeviceID"></span><span id="lpszdeviceid"></span><span id="LPSZDEVICEID"></span>*lpszDeviceID* </dt> <dd> Identifier of an MCI device. This identifier or alias is assigned when the device is opened. </dd> <dt> <span id="lpszRequest"></span><span id="lpszrequest"></span><span id="LPSZREQUEST"></span>*lpszRequest* </dt> <dd> Flag that identifies a device capability. The following table lists device types that recognize the **capability** command and the flags used by each type: <table> <colgroup> <col style="width: 33%" /> <col style="width: 33%" /> <col style="width: 33%" /> </colgroup> <thead> <tr class="header"> <th>Value</th> <th>Type</th> <th>Type</th> </tr> </thead> <tbody> <tr class="odd"> <td>cdaudio</td> <td><ul> <li>can eject</li> <li>can play</li> <li>can record</li> <li>can save</li> <li>compound device</li> </ul></td> <td><ul> <li>device type</li> <li>has audio</li> <li>has video</li> <li>uses files</li> </ul></td> </tr> <tr class="even"> <td>digitalvideo</td> <td><ul> <li>can eject</li> <li>can freeze</li> <li>can lock</li> <li>can play</li> <li>can record</li> <li>can reverse</li> <li>can save</li> <li>can stretch</li> <li>can stretch input</li> <li>can test</li> </ul></td> <td><ul> <li>compound device</li> <li>device type</li> <li>has audio</li> <li>has still</li> <li>has video</li> <li>maximum play rate</li> <li>minimum play rate</li> <li>uses files</li> <li>uses palettes</li> <li>windows</li> </ul></td> </tr> <tr class="odd"> <td>overlay</td> <td><ul> <li>can eject</li> <li>can freeze</li> <li>can play</li> <li>can record</li> <li>can save</li> <li>can stretch</li> </ul></td> <td><ul> <li>compound device</li> <li>device type</li> <li>has audio</li> <li>has video</li> <li>uses files</li> <li>windows</li> </ul></td> </tr> <tr class="even"> <td>sequencer</td> <td><ul> <li>can eject</li> <li>can play</li> <li>can record</li> <li>can save</li> <li>compound device</li> </ul></td> <td><ul> <li>device type</li> <li>has audio</li> <li>has video</li> <li>uses files</li> </ul></td> </tr> <tr class="odd"> <td>vcr</td> <td><ul> <li>can detect length</li> <li>can eject</li> <li>can freeze</li> <li>can monitor sources</li> <li>can play</li> <li>can preroll</li> <li>can preview</li> <li>can record</li> <li>can reverse</li> <li>can save</li> <li>can test</li> </ul></td> <td><ul> <li>clock increment rate</li> <li>compound device</li> <li>device type</li> <li>has audio</li> <li>has clock</li> <li>has timecode</li> <li>has video</li> <li>number of marks</li> <li>seek accuracy</li> <li>uses files</li> </ul></td> </tr> <tr class="even"> <td>videodisc</td> <td><ul> <li>can eject</li> <li>can play</li> <li>can record</li> <li>can reverse</li> <li>can save</li> <li>CAV</li> <li>CLV</li> <li>compound device</li> </ul></td> <td><ul> <li>device type</li> <li>fast play rate</li> <li>has audio</li> <li>has video</li> <li>normal play rate</li> <li>slow play rate</li> <li>uses files</li> </ul></td> </tr> <tr class="odd"> <td>waveaudio</td> <td><ul> <li>can eject</li> <li>can play</li> <li>can record</li> <li>can save</li> <li>compound device</li> <li>device type</li> </ul></td> <td><ul> <li>has audio</li> <li>has video</li> <li>inputs</li> <li>outputs</li> <li>uses files</li> </ul></td> </tr> </tbody> </table> The following table lists the flags that can be specified in the *lpszRequest* parameter and their meanings: <table> <colgroup> <col style="width: 50%" /> <col style="width: 50%" /> </colgroup> <thead> <tr class="header"> <th>Flags</th> <th>Meaning</th> </tr> </thead> <tbody> <tr class="odd"> <td>can detect length</td> <td>Returns <strong>TRUE</strong> if the device can detect the length of the media.</td> </tr> <tr class="even"> <td>can eject</td> <td>Returns <strong>TRUE</strong> if the device can eject the media.</td> </tr> <tr class="odd"> <td>can freeze</td> <td>Returns <strong>TRUE</strong> if the device can freeze data in the frame buffer.</td> </tr> <tr class="even"> <td>can lock</td> <td>Returns <strong>TRUE</strong> if the device can lock data.</td> </tr> <tr class="odd"> <td>can monitor sources</td> <td>Returns <strong>TRUE</strong> if the device can pass an input (source) to the monitored output, independent of the current input selection.</td> </tr> <tr class="even"> <td>can play</td> <td>Returns <strong>TRUE</strong> if the device can play.</td> </tr> <tr class="odd"> <td>can preroll</td> <td>Returns <strong>TRUE</strong> if the device supports the &quot;preroll&quot; flag with the <a href="cue.md">cue</a> command.</td> </tr> <tr class="even"> <td>can preview</td> <td>Returns <strong>TRUE</strong> if the device supports previews.</td> </tr> <tr class="odd"> <td>can record</td> <td>Returns <strong>TRUE</strong> if the device supports recording.</td> </tr> <tr class="even"> <td>can reverse</td> <td>Returns <strong>TRUE</strong> if the device can play in reverse.</td> </tr> <tr class="odd"> <td>can save</td> <td>Returns <strong>TRUE</strong> if the device can save data.</td> </tr> <tr class="even"> <td>can stretch</td> <td>Returns <strong>TRUE</strong> if the device can stretch frames to fill a given display rectangle.</td> </tr> <tr class="odd"> <td>can stretch input</td> <td>Returns <strong>TRUE</strong> if the device can resize an image in the process of digitizing it into the frame buffer.</td> </tr> <tr class="even"> <td>can test</td> <td>Returns <strong>TRUE</strong> if the device recognizes the test keyword.</td> </tr> <tr class="odd"> <td>cav</td> <td>When combined with other items, this flag specifies that the return information applies to CAV format videodiscs. This is the default if no videodisc is inserted.</td> </tr> <tr class="even"> <td>clock increment rate</td> <td>Returns the number of subdivisions the external clock supports per second. If the external clock is a millisecond clock, the return value is 1000. If the return value is 0, no clock is supported.</td> </tr> <tr class="odd"> <td>clv</td> <td>When combined with other items, this flag specifies that the return information applies to CLV format videodiscs.</td> </tr> <tr class="even"> <td>compound device</td> <td>Returns <strong>TRUE</strong> if the device supports an element name (filename).</td> </tr> <tr class="odd"> <td>device type</td> <td>Returns a device type name, which can be one of the following: <ul> <li>cdaudio</li> <li>dat</li> <li>digitalvideo</li> <li>other</li> <li>overlay</li> <li>scanner</li> <li>sequencer</li> <li>vcr</li> <li>videodisc</li> <li>waveaudio</li> </ul></td> </tr> <tr class="even"> <td>fast play rate</td> <td>Returns the fast play rate in frames per second, or zero if the device cannot play fast.</td> </tr> <tr class="odd"> <td>has audio</td> <td>Returns <strong>TRUE</strong> if the device supports audio playback.</td> </tr> <tr class="even"> <td>has clock</td> <td>Returns <strong>TRUE</strong> if the device has a clock.</td> </tr> <tr class="odd"> <td>has still</td> <td>Returns <strong>TRUE</strong> if the device treats files with a single image more efficiently than motion video files.</td> </tr> <tr class="even"> <td>has timecode</td> <td>Returns <strong>TRUE</strong> if the device is capable of supporting timecode, or if it is unknown.</td> </tr> <tr class="odd"> <td>has video</td> <td>Returns <strong>TRUE</strong> if the device supports video.</td> </tr> <tr class="even"> <td>inputs</td> <td>Returns the total number of input devices.</td> </tr> <tr class="odd"> <td>maximum play rate</td> <td>Returns the maximum play rate, in frames per second, for the device.</td> </tr> <tr class="even"> <td>minimum play rate</td> <td>Returns the minimum play rate, in frames per second, for the device.</td> </tr> <tr class="odd"> <td>normal play rate</td> <td>Returns the normal play rate, in frames per second, for the device.</td> </tr> <tr class="even"> <td>number of marks</td> <td>Returns the maximum number of marks that can be used; zero indicates that marks are unsupported.</td> </tr> <tr class="odd"> <td>outputs</td> <td>Returns the total number of output devices.</td> </tr> <tr class="even"> <td>seek accuracy</td> <td>Returns the expected accuracy of a search in frames; 0 indicates that the device is frame accurate, 1 indicates that the device expects to be within one frame of the indicated seek position, and so on.</td> </tr> <tr class="odd"> <td>slow play rate</td> <td>Returns the slow play rate in frames per second, or zero if the device cannot play slowly.</td> </tr> <tr class="even"> <td>uses files</td> <td>Returns <strong>TRUE</strong> if the data storage used by a compound device is a file.</td> </tr> <tr class="odd"> <td>uses palettes</td> <td>Returns <strong>TRUE</strong> if the device uses palettes.</td> </tr> <tr class="even"> <td>windows</td> <td>Returns the number of simultaneous display windows the device can support.</td> </tr> </tbody> </table> </dd> <dt> <span id="lpszFlags"></span><span id="lpszflags"></span><span id="LPSZFLAGS"></span>*lpszFlags* </dt> <dd> Can be "wait", "notify", or both. For digital-video and VCR devices, "test" can also be specified. For more information about these flags, see [The Wait, Notify, and Test Flags](the-wait-notify-and-test-flags.md). </dd> </dl> ## Return Value Returns information in the *lpszReturnString* parameter of the [**mciSendString**](/previous-versions//dd757161(v=vs.85)) function. The information is dependent on the request type. ## Examples The following command returns the device type of the "mysound" device. ``` syntax capability mysound device type ``` ## Requirements | Requirement | Value | |-------------------------------------|------------------------------------------------------------| | Minimum supported client<br/> | Windows 2000 Professional \[desktop apps only\]<br/> | | Minimum supported server<br/> | Windows 2000 Server \[desktop apps only\]<br/> | ## See also <dl> <dt> [MCI](mci.md) </dt> <dt> [MCI Command Strings](mci-command-strings.md) </dt> <dt> [cue](cue.md) </dt> </dl> ======================= File: desktop-src/wic/-wic-decoder-howto-createusingstream.md ======================= --- description: This topic describes how to create a bitmap decoder by using a stream. ms.assetid: 982d2110-ff2f-43e0-a931-cb2b8146ad0a title: How to Create a Decoder Using a Stream ms.topic: article ms.date: 05/31/2018 --- # How to Create a Decoder Using a Stream This topic describes how to create a bitmap decoder by using a stream. To create a bitmap decoder by using a stream 1. Load an image file into a stream. In this example, a stream is created for an application resource. In the application resource definition (.rc) file, define the resource. The following example defines an `Image` resource named `IDR_SAMPLE_IMAGE`. ```C++ IDR_SAMPLE_IMAGE IMAGE "turtle.jpg" ``` The resource will be added to the application's resources when the application is built. 2. Load the resource from the application. ```C++ HRESULT hr = S_OK; // WIC interface pointers. IWICStream *pIWICStream = NULL; IWICBitmapDecoder *pIDecoder = NULL; IWICBitmapFrameDecode *pIDecoderFrame = NULL; // Resource management. HRSRC imageResHandle = NULL; HGLOBAL imageResDataHandle = NULL; void *pImageFile = NULL; DWORD imageFileSize = 0; // Locate the resource in the application's executable. imageResHandle = FindResource( NULL, // This component. L"SampleImage", // Resource name. L"Image"); // Resource type. hr = (imageResHandle? S_OK : E_FAIL); // Load the resource to the HGLOBAL. if (SUCCEEDED(hr)){ imageResDataHandle = LoadResource(NULL, imageResHandle); hr = (imageResDataHandle? S_OK : E_FAIL); } ``` 3. Lock the resource and get the size. ```C++ // Lock the resource to retrieve memory pointer. if (SUCCEEDED(hr)){ pImageFile = LockResource(imageResDataHandle); hr = (pImageFile? S_OK : E_FAIL); } // Calculate the size. if (SUCCEEDED(hr)){ imageFileSize = SizeofResource(NULL, imageResHandle); hr = (imageFileSize? S_OK : E_FAIL); } ``` 4. Create an [**IWICImagingFactory**](/windows/desktop/api/Wincodec/nn-wincodec-iwicimagingfactory) to create Windows Imaging Component (WIC) objects. ```C++ // Create WIC factory hr = CoCreateInstance( CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&m_pIWICFactory) ); ``` 5. Use the [**CreateStream**](/windows/desktop/api/Wincodec/nf-wincodec-iwicimagingfactory-createstream) method to create an [**IWICStream**](/windows/desktop/api/Wincodec/nn-wincodec-iwicstream) object and initialize it by using the image memory pointer. ```C++ // Create a WIC stream to map onto the memory. if (SUCCEEDED(hr)){ hr = m_pIWICFactory->CreateStream(&pIWICStream); } // Initialize the stream with the memory pointer and size. if (SUCCEEDED(hr)){ hr = pIWICStream->InitializeFromMemory( reinterpret_cast<BYTE*>(pImageFile), imageFileSize); } ``` 6. Create an [**IWICBitmapDecoder**](/windows/desktop/api/Wincodec/nn-wincodec-iwicbitmapdecoder) from the new stream object using the [**CreateDecoderFromStream**](/windows/desktop/api/Wincodec/nf-wincodec-iwicimagingfactory-createdecoderfromstream) method. ```C++ // Create a decoder for the stream. if (SUCCEEDED(hr)){ hr = m_pIWICFactory->CreateDecoderFromStream( pIWICStream, // The stream to use to create the decoder NULL, // Do not prefer a particular vendor WICDecodeMetadataCacheOnLoad, // Cache metadata when needed &pIDecoder); // Pointer to the decoder } ``` 7. Get the first [**IWICBitmapFrameDecode**](/windows/desktop/api/Wincodec/nn-wincodec-iwicbitmapframedecode) of the image. ```C++ // Retrieve the first bitmap frame. if (SUCCEEDED(hr)) { hr = pIDecoder->GetFrame(0, &pIDecoderFrame); } ``` The JPEG file format only supports a single frame. Because the file in this example is a JPEG file, the first frame (`0`) is used. For image formats that have multiple frames, see [How to Retrieve the Frames of an Image](-wic-bitmapsources-howto-retrieveimageframes.md) for accessing each frame of the image. 8. Process the image frame. For additional information about [**IWICBitmapSource**](/windows/desktop/api/Wincodec/nn-wincodec-iwicbitmapsource) objects, see the [Bitmap Sources Overview](-wic-bitmapsources.md). ## See Also [Programming Guide](-wic-programming-guide.md) [Reference](-wic-codec-reference.md) [Samples](-wic-samples.md)     ======================= File: desktop-src/Multimedia/mim-close.md ======================= --- title: MIM_CLOSE message (Mmsystem.h) description: The MIM\_CLOSE message is sent to a MIDI input callback function when a MIDI input device is closed. ms.assetid: c19ecd3a-c3a5-4f17-9d44-d0d71eefcb15 keywords: - MIM_CLOSE message Windows Multimedia topic_type: - apiref api_name: - MIM_CLOSE api_location: - Mmsystem.h api_type: - HeaderDef ms.topic: reference ms.date: 05/31/2018 --- # MIM\_CLOSE message The **MIM\_CLOSE** message is sent to a MIDI input callback function when a MIDI input device is closed. ```C++ MIM_CLOSE dwParam1 = reserved dwParam2 = reserved ``` ## Parameters <dl> <dt> <span id="dwParam1"></span><span id="dwparam1"></span><span id="DWPARAM1"></span>*dwParam1* </dt> <dd> Reserved; do not use. </dd> <dt> <span id="dwParam2"></span><span id="dwparam2"></span><span id="DWPARAM2"></span>*dwParam2* </dt> <dd> Reserved; do not use. </dd> </dl> ## Return Value This message does not return a value. ## Remarks The device handle is no longer valid after this message has been sent. ## Requirements | Requirement | Value | |-------------------------------------|-----------------------------------------------------------------------------------------------------------| | Minimum supported client<br/> | Windows 2000 Professional \[desktop apps only\]<br/> | | Minimum supported server<br/> | Windows 2000 Server \[desktop apps only\]<br/> | | Header<br/> | <dl> <dt>Mmsystem.h (include Windows.h)</dt> </dl> | ## See also <dl> <dt> [Musical Instrument Digital Interface (MIDI)](musical-instrument-digital-interface--midi.md) </dt> <dt> [MIDI Messages](midi-messages.md) </dt> </dl> ======================= File: desktop-src/direct3d9/dx9-graphics-reference-x-file-return-values.md ======================= --- description: The methods used to work with DirectX.x files can return the following values in addition to the standard COM return values. Deprecated. ms.assetid: a91168bc-966a-47b5-ba83-fc480593228d title: Return Values (DXFile.h) ms.topic: reference ms.date: 05/31/2018 topic_type: - APIRef - kbSyntax api_name: - Return api_type: - HeaderDef api_location: - DXFile.h --- # Return Values (DXFile.h) The methods used to work with DirectX.x files can return the following values in addition to the standard COM return values. Deprecated. <dl> <dt> <span id="DXFILE_OK"></span><span id="dxfile_ok"></span>**DXFILE\_OK** </dt> <dd> Command completed successfully. </dd> <dt> <span id="DXFILEERR_BADALLOC"></span><span id="dxfileerr_badalloc"></span>**DXFILEERR\_BADALLOC** </dt> <dd> Memory allocation failed. </dd> <dt> <span id="DXFILEERR_BADARRAYSIZE"></span><span id="dxfileerr_badarraysize"></span>**DXFILEERR\_BADARRAYSIZE** </dt> <dd> Array size is invalid. </dd> <dt> <span id="DXFILEERR_BADCACHEFILE"></span><span id="dxfileerr_badcachefile"></span>**DXFILEERR\_BADCACHEFILE** </dt> <dd> The cache file containing the.x file date is invalid. A cache file contains data retrieved from the network, cached on the hard disk, and retrieved in subsequent requests. </dd> <dt> <span id="DXFILEERR_BADDataReference"></span><span id="dxfileerr_baddatareference"></span><span id="DXFILEERR_BADDATAREFERENCE"></span>**DXFILEERR\_BADDataReference** </dt> <dd> Data reference is invalid. </dd> <dt> <span id="DXFILEERR_BADFILE"></span><span id="dxfileerr_badfile"></span>**DXFILEERR\_BADFILE** </dt> <dd> File is invalid. </dd> <dt> <span id="DXFILEERR_BADFILECOMPRESSIONTYPE"></span><span id="dxfileerr_badfilecompressiontype"></span>**DXFILEERR\_BADFILECOMPRESSIONTYPE** </dt> <dd> File compression type is invalid. </dd> <dt> <span id="DXFILEERR_BADFILEFLOATSIZE"></span><span id="dxfileerr_badfilefloatsize"></span>**DXFILEERR\_BADFILEFLOATSIZE** </dt> <dd> Floating-point size is invalid. </dd> <dt> <span id="DXFILEERR_BADFILETYPE"></span><span id="dxfileerr_badfiletype"></span>**DXFILEERR\_BADFILETYPE** </dt> <dd> File is not a DirectX.x file. </dd> <dt> <span id="DXFILEERR_BADFILEVERSION"></span><span id="dxfileerr_badfileversion"></span>**DXFILEERR\_BADFILEVERSION** </dt> <dd> File version is not valid. </dd> <dt> <span id="DXFILEERR_BADINTRINSICS"></span><span id="dxfileerr_badintrinsics"></span>**DXFILEERR\_BADINTRINSICS** </dt> <dd> Intrinsics are invalid. </dd> <dt> <span id="DXFILEERR_BADOBJECT"></span><span id="dxfileerr_badobject"></span>**DXFILEERR\_BADOBJECT** </dt> <dd> Object is invalid. </dd> <dt> <span id="DXFILEERR_BADRESOURCE"></span><span id="dxfileerr_badresource"></span>**DXFILEERR\_BADRESOURCE** </dt> <dd> Resource is invalid. </dd> <dt> <span id="DXFILEERR_BADSTREAMHANDLE"></span><span id="dxfileerr_badstreamhandle"></span>**DXFILEERR\_BADSTREAMHANDLE** </dt> <dd> Stream handle is invalid. </dd> <dt> <span id="DXFILEERR_BADTYPE"></span><span id="dxfileerr_badtype"></span>**DXFILEERR\_BADTYPE** </dt> <dd> Object type is invalid. </dd> <dt> <span id="DXFILEERR_BADVALUE"></span><span id="dxfileerr_badvalue"></span>**DXFILEERR\_BADVALUE** </dt> <dd> Parameter is invalid. </dd> <dt> <span id="DXFILEERR_FILENOTFOUND"></span><span id="dxfileerr_filenotfound"></span>**DXFILEERR\_FILENOTFOUND** </dt> <dd> File could not be found. </dd> <dt> <span id="DXFILEERR_INTERNALERROR"></span><span id="dxfileerr_internalerror"></span>**DXFILEERR\_INTERNALERROR** </dt> <dd> Internal error occurred. </dd> <dt> <span id="DXFILEERR_NOINTERNET"></span><span id="dxfileerr_nointernet"></span>**DXFILEERR\_NOINTERNET** </dt> <dd> Internet connection not found. </dd> <dt> <span id="DXFILEERR_NOMOREDATA"></span><span id="dxfileerr_nomoredata"></span>**DXFILEERR\_NOMOREDATA** </dt> <dd> No further data is available. </dd> <dt> <span id="DXFILEERR_NOMOREOBJECTS"></span><span id="dxfileerr_nomoreobjects"></span>**DXFILEERR\_NOMOREOBJECTS** </dt> <dd> All objects have been enumerated. </dd> <dt> <span id="DXFILEERR_NOMORESTREAMHANDLES"></span><span id="dxfileerr_nomorestreamhandles"></span>**DXFILEERR\_NOMORESTREAMHANDLES** </dt> <dd> No stream handles are available. </dd> <dt> <span id="DXFILEERR_NOTDONEYET"></span><span id="dxfileerr_notdoneyet"></span>**DXFILEERR\_NOTDONEYET** </dt> <dd> Operation has not completed. </dd> <dt> <span id="DXFILEERR_NOTFOUND"></span><span id="dxfileerr_notfound"></span>**DXFILEERR\_NOTFOUND** </dt> <dd> Object could not be found. </dd> <dt> <span id="DXFILEERR_PARSEERROR"></span><span id="dxfileerr_parseerror"></span>**DXFILEERR\_PARSEERROR** </dt> <dd> File could not be parsed. </dd> <dt> <span id="DXFILEERR_RESOURCENOTFOUND"></span><span id="dxfileerr_resourcenotfound"></span>**DXFILEERR\_RESOURCENOTFOUND** </dt> <dd> Resource could not be found. </dd> <dt> <span id="DXFILEERR_NOTEMPLATE"></span><span id="dxfileerr_notemplate"></span>**DXFILEERR\_NOTEMPLATE** </dt> <dd> No template available. </dd> <dt> <span id="DXFILEERR_URLNOTFOUND"></span><span id="dxfileerr_urlnotfound"></span>**DXFILEERR\_URLNOTFOUND** </dt> <dd> URL could not be found. </dd> </dl> ## Requirements | Requirement | Value | |-------------------|-------------------------------------------------------------------------------------| | Header<br/> | <dl> <dt>DXFile.h</dt> </dl> | ## See also <dl> <dt> [X File Reference (Legacy)](dx9-graphics-reference-x-file.md) </dt> </dl>     ======================= File: desktop-src/NetMon2/generic-port.md ======================= <gh_stars>100-1000 --- description: Contains a port number used for IP or IPX protocols. ms.assetid: 730f6ee6-7b7d-4e10-91ee-a4ba87aae5aa title: GENERIC_PORT union (Netmon.h) ms.topic: reference ms.date: 05/31/2018 topic_type: - APIRef - kbSyntax api_name: - GENERIC_PORT api_type: - HeaderDef api_location: - Netmon.h --- # GENERIC\_PORT union The **GENERIC\_PORT** structure contains a port number used for IP or IPX protocols. ## Syntax ```C++ typedef union { BYTE IPPort; WORD ByteSwappedIPXPort; } GENERIC_PORT; ``` ## Members <dl> <dt> **IPPort** </dt> <dd> IP port number filled in. </dd> <dt> **ByteSwappedIPXPort** </dt> <dd> IPX port number filled in. </dd> </dl> ## Requirements | Requirement | Value | |-------------------------------------|-------------------------------------------------------------------------------------| | Minimum supported client<br/> | Windows 2000 Professional \[desktop apps only\]<br/> | | Minimum supported server<br/> | Windows 2000 Server \[desktop apps only\]<br/> | | Header<br/> | <dl> <dt>Netmon.h</dt> </dl> | ======================= File: desktop-src/extensible-storage-engine/jet-sesparam-enumeration.md ======================= --- description: "Learn more about: JET_sesparam enumeration" title: JET_sesparam enumeration (Microsoft.Isam.Esent.Interop.Windows8) TOCTitle: JET_sesparam enumeration ms:assetid: T:Microsoft.Isam.Esent.Interop.Windows8.JET_sesparam ms:mtpsurl: https://msdn.microsoft.com/library/microsoft.isam.esent.interop.windows8.jet_sesparam(v=EXCHG.10) ms:contentKeyID: 55104452 ms.date: 07/30/2014 ms.topic: reference f1_keywords: - Microsoft.Isam.Esent.Interop.Windows8.JET_sesparam - Microsoft.Isam.Esent.Interop.Windows8.JET_sesparam.Base - Microsoft.Isam.Esent.Interop.Windows8.JET_sesparam.CommitDefault - Microsoft.Isam.Esent.Interop.Windows8.JET_sesparam.CommitGenericContext dev_langs: - CSharp - JScript - VB - other api_name: - Microsoft.Isam.Esent.Interop.Windows8.JET_sesparam.Base - Microsoft.Isam.Esent.Interop.Windows8.JET_sesparam.CommitGenericContext - Microsoft.Isam.Esent.Interop.Windows8.JET_sesparam.CommitDefault - Microsoft.Isam.Esent.Interop.Windows8.JET_sesparam topic_type: - apiref - kbSyntax api_type: - Managed api_location: - Microsoft.Isam.Esent.Interop.dll ROBOTS: INDEX,FOLLOW --- # JET_sesparam enumeration ESENT session parameters. **Namespace:**  [Microsoft.Isam.Esent.Interop.Windows8](./microsoft.isam.esent.interop.windows8-namespace.md) **Assembly:**  Microsoft.Isam.Esent.Interop (in Microsoft.Isam.Esent.Interop.dll) ## Syntax ``` vb 'Declaration Public Enumeration JET_sesparam 'Usage Dim instance As JET_sesparam ``` ``` csharp public enum JET_sesparam ``` ## Members <table> <thead> <tr class="header"> <th></th> <th>Member name</th> <th>Description</th> </tr> </thead> <tbody> <tr class="odd"> <td></td> <td>Base</td> <td>This parameter is not meant to be used.</td> </tr> <tr class="even"> <td></td> <td>CommitDefault</td> <td>This parameter sets the grbits for commit. It is functionally the same as the system parameter JET_param.CommitDefault when used with an instance and a sesid.</td> </tr> <tr class="odd"> <td></td> <td>CommitGenericContext</td> <td>This parameter sets a user specific commit context that will be placed in the transaction log on commit to level 0.</td> </tr> </tbody> </table> ## See also #### Reference [Microsoft.Isam.Esent.Interop.Windows8 namespace](./microsoft.isam.esent.interop.windows8-namespace.md) ======================= File: desktop-src/printdocs/printer-info-3.md ======================= --- description: The PRINTER\_INFO\_3 structure specifies printer security information. ms.assetid: 527d635d-2d75-4b56-bab7-e95c9919a8fb title: PRINTER_INFO_3 structure (Winspool.h) ms.topic: reference ms.date: 05/31/2018 topic_type: - APIRef - kbSyntax api_name: - PRINTER_INFO_3 api_type: - HeaderDef api_location: - Winspool.h --- # PRINTER\_INFO\_3 structure The **PRINTER\_INFO\_3** structure specifies printer security information. ## Syntax ```C++ typedef struct _PRINTER_INFO_3 { PSECURITY_DESCRIPTOR pSecurityDescriptor; } PRINTER_INFO_3, *PPRINTER_INFO_3; ``` ## Members <dl> <dt> **pSecurityDescriptor** </dt> <dd> Pointer to a [**SECURITY\_DESCRIPTOR**](/windows/desktop/api/winnt/ns-winnt-security_descriptor) structure that specifies a printer's security information. </dd> </dl> ## Remarks The **PRINTER\_INFO\_3** structure lets an application get and set a printer's security descriptor. The caller may do so even if it lacks specific printer permissions, as long as it has the standard rights described in [**SetPrinter**](setprinter.md) and [**GetPrinter**](getprinter.md). Thus, an application may temporarily deny all access to a printer, while allowing the owner of the printer to have access to the printer's discretionary ACL. ## Requirements | Requirement | Value | |-------------------------------------|-----------------------------------------------------------------------------------------------------------| | Minimum supported client<br/> | Windows 2000 Professional \[desktop apps only\]<br/> | | Minimum supported server<br/> | Windows 2000 Server \[desktop apps only\]<br/> | | Header<br/> | <dl> <dt>Winspool.h (include Windows.h)</dt> </dl> | ## See also <dl> <dt> [Printing](printdocs-printing.md) </dt> <dt> [Print Spooler API Structures](printing-and-print-spooler-structures.md) </dt> <dt> [**SetPrinter**](setprinter.md) </dt> <dt> [**GetPrinter**](getprinter.md) </dt> <dt> [**PRINTER\_INFO\_1**](printer-info-1.md) </dt> <dt> [**PRINTER\_INFO\_2**](printer-info-2.md) </dt> <dt> [**PRINTER\_INFO\_4**](printer-info-4.md) </dt> <dt> [**SECURITY\_DESCRIPTOR**](/windows/desktop/api/winnt/ns-winnt-security_descriptor) </dt> </dl> ======================= File: desktop-src/WmiSdk/scripting-api-for-wmi.md ======================= --- description: The WMI scripting reference contains definitions for the WMI Scripting API. ms.assetid: 83fc78fc-929d-4d32-940e-9147543a6324 ms.tgt_platform: multiple title: Scripting API for WMI ms.topic: article ms.date: 05/31/2018 --- # Scripting API for WMI The WMI scripting reference contains definitions for the WMI Scripting API. Use this API if writing applications with Microsoft Visual Basic, Visual Basic for Applications, Visual Basic Scripting Edition (VBScript), or any other scripting language that supports active scripting technologies. > [!Note] > PowerShell is also available for scripting with WMI. The Get-WMI cmdlet and the three type accelerators (\[wmi\], \[wmiclass\], and \[wmisearcher\]) enable basic administrative access to WMI. For more information, see [Scripting with Windows PowerShell](https://TechNet.Microsoft.Com/library/bb978526.aspx).   WMI scripting objects, except for [**SWbemDateTime**](swbemdatetime.md) are not marked safe for scripting for scripts running on HTML pages in Internet Explorer. Therefore, unless the security level within Internet Explorer is lowered, the script will fail. **SWbemDateTime** is marked safe for initialization and scripting. However, use all WMI scripting objects in **GetObject** and **CreateObject** calls on server-side code in Active Server Pages (ASP). - [Scripting API Object Model](scripting-api-object-model.md) - [Document Conventions for the Scripting API](document-conventions-for-the-scripting-api.md) - [Scripting API Objects](scripting-api-objects.md) - [Scripting API Constants](scripting-api-constants.md) ## Related topics <dl> <dt> [WMI Reference](wmi-reference.md) </dt> <dt> [WMI Return Codes](wmi-return-codes.md) </dt> </dl>     ======================= File: desktop-src/shell/folderitems2-invokeverbex.md ======================= <reponame>velden/win32<gh_stars>100-1000 --- description: Executes a verb on a collection of FolderItem objects. This method is an extension of the InvokeVerb method, allowing additional control of the operation through a set of flags. ms.assetid: 2c02985d-8877-4a02-a232-6aeb1716928c title: FolderItems2.InvokeVerbEx method (Shldisp.h) ms.topic: reference ms.date: 05/31/2018 topic_type: - APIRef - kbSyntax api_name: - FolderItems2.InvokeVerbEx api_type: - COM api_location: - Shell32.dll --- # FolderItems2.InvokeVerbEx method Executes a verb on a collection of [**FolderItem**](folderitem.md) objects. This method is an extension of the [**InvokeVerb**](folderitem-invokeverb.md) method, allowing additional control of the operation through a set of flags. ## Syntax ```JScript iRetVal = FolderItems2.InvokeVerbEx( [ vVerb ], [ vArgs ] ) ``` ## Parameters <dl> <dt> *vVerb* \[in, optional\] </dt> <dd> Type: **Variant** A **Variant** with the verb string that corresponds to the command to be executed. If no verb is specified, the default verb is executed. </dd> <dt> *vArgs* \[in, optional\] </dt> <dd> Type: **Variant** A **Variant** that consists of a string with one or more arguments to the command specified by *vVerb*. The format of this string depends on the particular verb. </dd> </dl> ## Remarks A verb is a string used to specify a particular action associated with an item or collection of items. Typically, calling a verb launches a related application. For example, calling the **open** verb on a.txt file normally opens the file with a text editor, usually Microsoft Notepad. For further discussion of verbs, see [Launching Applications](launch.md). ## Examples The following example uses **InvokeVerbEx** to invoke the default verb ("open") on **My Computer**. Proper usage is shown for JScript, VBScript, and Visual Basic. JScript: ```JScript <script language="JScript"> function fnFolderItems2InvokeVerbExJ() { var objShell = new ActiveXObject("shell.application"); var objFolder; var ssfDRIVES = 17; objFolder = objShell.NameSpace(ssfDRIVES); if (objFolder!= null) { var objFolderItems2; objFolderItems2 = objFolder.Items(); if (objFolderItems2!= null) { objFolderItems2.InvokeVerbEx(); } } } </script> ``` VBScript: ```VB <script language="VBScript"> function fnFolderItems2InvokeVerbExVB() dim objShell set objShell = CreateObject("shell.application") if (not objShell is nothing) then dim objFolder dim ssfDRIVES ssfWINDOWS = 17 set objFolder = objShell.NameSpace(ssfWINDOWS) if (not objFolder is nothing) then dim objFolderItems2 set objFolderItems2 = objFolder.Items() if (not objFolderItems2 is nothing) then objFolderItems2.InvokeVerbEx end if set objFolderItems2 = nothing end if set objFolder = nothing end if set objShell = nothing end function </script> ``` Visual Basic: ```VB Private Sub fnFolderItems2InvokeVerbExVB() Dim objShell As Shell Dim objFolder As Folder2 Dim ssfDRIVES As Long ssfDRIVES = 17 Set objShell = New Shell Set objFolder = objShell.NameSpace(ssfDRIVES) If (Not objFolder Is Nothing) Then Dim objFolderItems2 As FolderItems Set objFolderItems2 = objFolder.Items If (Not objFolderItems2 Is Nothing) Then objFolderItems2.InvokeVerbEx End If Set objFolderItems2 = Nothing End If Set objFolder = Nothing Set objShell = Nothing End Sub ``` ## Requirements | Requirement | Value | |-------------------------------------|---------------------------------------------------------------------------------------------------------------| | Minimum supported client<br/> | Windows 2000 Professional, Windows XP \[desktop apps only\]<br/> | | Minimum supported server<br/> | Windows Server 2003 \[desktop apps only\]<br/> | | Header<br/> | <dl> <dt>Shldisp.h</dt> </dl> | | IDL<br/> | <dl> <dt>Shldisp.idl</dt> </dl> | | DLL<br/> | <dl> <dt>Shell32.dll (version 5.0 or later)</dt> </dl> | ## See also <dl> <dt> [**FolderItems2**](folderitems2-object.md) </dt> <dt> [**InvokeVerb**](folderitem-invokeverb.md) </dt> </dl>     ======================= File: desktop-src/direct3d9/id3dxeffect--endpass.md ======================= <filename>desktop-src/direct3d9/id3dxeffect--endpass.md<gh_stars>100-1000 --- description: End an active pass. ms.assetid: e20b3e0f-db9f-48e8-ab4e-761a5861f3ce title: ID3DXEffect::EndPass method (D3DX9Effect.h) ms.topic: reference ms.date: 05/31/2018 topic_type: - APIRef - kbSyntax api_name: - ID3DXEffect.EndPass api_type: - COM api_location: - D3dx9.lib - D3dx9.dll --- # ID3DXEffect::EndPass method End an active pass. ## Syntax ```C++ HRESULT EndPass(); ``` ## Parameters This method has no parameters. ## Return value Type: **[**HRESULT**](https://msdn.microsoft.com/library/Bb401631(v=MSDN.10).aspx)** This method always returns the value S\_OK. ## Remarks An application signals the end of rendering an active pass by calling **ID3DXEffect::EndPass**. Each **ID3DXEffect::EndPass** must be part of a matching pair of [**ID3DXEffect::BeginPass**](id3dxeffect--beginpass.md) and **ID3DXEffect::EndPass** calls. Each matching pair of [**ID3DXEffect::BeginPass**](id3dxeffect--beginpass.md) and **ID3DXEffect::EndPass** calls must be located within a matching pair of [**ID3DXEffect::Begin**](id3dxeffect--begin.md) and [**ID3DXEffect::End**](id3dxeffect--end.md) calls. If the application changes any effect state using any of the [**Effect::Setx**](id3dxeffect.md) methods inside of a [**ID3DXEffect::BeginPass**](id3dxeffect--beginpass.md)/**ID3DXEffect::EndPass** matching pair, the application must call [**ID3DXEffect::CommitChanges**](id3dxeffect--commitchanges.md) before any DrawxPrimitive call to propagate state changes to the device before rendering. ## Requirements | Requirement | Value | |--------------------|------------------------------------------------------------------------------------------| | Header<br/> | <dl> <dt>D3DX9Effect.h</dt> </dl> | | Library<br/> | <dl> <dt>D3dx9.lib</dt> </dl> | ## See also <dl> <dt> [ID3DXEffect](id3dxeffect.md) </dt> </dl>     ======================= File: desktop-src/DirectShow/recompressing-an-avi-file.md ======================= --- description: Recompressing an AVI File ms.assetid: 7c91e560-ac69-47e1-a921-c312b77ecadc title: Recompressing an AVI File ms.topic: article ms.date: 05/31/2018 --- # Recompressing an AVI File This article describes how to recompress an Audio-Video Interleaved (AVI) file using DirectShow. The article focuses on video compression, but the same principles apply for audio compression. This article contains the following sections: - [Choosing a Compression Filter](choosing-a-compression-filter.md) - [Setting Video Compression Properties](setting-video-compression-properties.md) - [Building the Recompression Graph](building-the-recompression-graph.md) - [Writing the File](writing-the-file.md)     ======================= File: desktop-src/medfound/mf-device-thermal-state-changed.md ======================= <reponame>velden/win32<filename>desktop-src/medfound/mf-device-thermal-state-changed.md --- description: Represents an event that signals a thermal state change in the device. ms.assetid: 7F656E64-CE72-4DF8-9094-1EBBAE3A81E5 title: MF_DEVICE_THERMAL_STATE_CHANGED attribute (Mfapi.h) ms.topic: reference ms.date: 05/31/2018 --- # MF\_DEVICE\_THERMAL\_STATE\_CHANGED attribute Represents an event that signals a thermal state change in the device. ## Data type **UINT32** ## Remarks The value of this attribute specifies the device thermal value in percentage. ## Requirements | Requirement | Value | |-------------------------------------|------------------------------------------------------------------------------------| | Minimum supported client<br/> | Windows 10, version 1709 \[desktop apps only\]<br/> | | Minimum supported server<br/> | None supported<br/> | | Header<br/> | <dl> <dt>Mfapi.h</dt> </dl> |     ======================= File: desktop-src/DMWmiBridgeProv/mdm-healthattestation.md ======================= <gh_stars>100-1000 --- title: MDM_HealthAttestation class description: The MDM\_HealthAttestation class enables enterprise IT managers to assess the health of managed devices and take enterprise policy actions. ms.assetid: 64f40ccc-98f6-48d6-bcd4-793375e3dbfb keywords: - MDM_HealthAttestation class - MDM_HealthAttestation class, described ms.topic: reference ms.date: 05/31/2018 topic_type: - kbSyntax api_name: api_type: api_location: --- # MDM\_HealthAttestation class \[Some information relates to pre-released product which may be substantially modified before it's commercially released. Microsoft makes no warranties, express or implied, with respect to the information provided here.\] The **MDM\_HealthAttestation** class enables enterprise IT managers to assess the health of managed devices and take enterprise policy actions. The following is a list of functions performed by the HealthAttestation CSP: - Collects data that is used in verifying a devices health states - Forwards the data to the Health Attestation Service (HAS) - Provisions the Health Attestation Certificate that it receives from HAS - Upon request, forwards the Health Attestation Certificate (received from HAS) and related runtime information to the MDM Server for verification The following syntax is simplified from MOF code and includes all inherited properties. ## Syntax ``` syntax [InPartition("local-system"), dynamic, provider("DMWmiBridgeProv")] class MDM_HealthAttestation { string InstanceID; string ParentID; sint32 Status; boolean ForceRetrieve; string Certificate; string Nonce; string CorrelationID; sint32 TpmReadyStatus; sint32 MaxSupportedProtocolVersion; sint32 PreferredMaxProtocolVersion; sint32 CurrentProtocolVersion; string HASEndpoint; }; ``` ## Members The **MDM\_HealthAttestation** class has these types of members: - [Methods](#methods) - [Properties](#properties) ### Methods The **MDM\_HealthAttestation** class has these methods. | Method | Description | |:-----------------------------------------------------------------------|:---------------------------------------------------------------------------------------------| | [**VerifyHealthMethod**](mdm-healthattestation-verifyhealthmethod.md) | Method to notify the device to prepare a health certificate verification request.<br/> | ### Properties The **MDM\_HealthAttestation** class has these properties. <dl> <dt> [Certificate](/windows/client-management/mdm/healthattestation-csp) </dt> <dd> <dl> <dt> Data type: **string** </dt> <dt> Access type: Read/write </dt> <dt> Qualifiers: **Octetstring** </dt> </dl> </dd> <dt> [CorrelationID](/windows/client-management/mdm/healthattestation-csp) </dt> <dd> <dl> <dt> Data type: **string** </dt> <dt> Access type: Read/write </dt> </dl> </dd> <dt> **CurrentProtocolVersion** </dt> <dd> <dl> <dt> Data type: **sint32** </dt> <dt> Access type: Read/write </dt> </dl> TBD </dd> <dt> [ForceRetrieve](/windows/client-management/mdm/healthattestation-csp) </dt> <dd> <dl> <dt> Data type: **boolean** </dt> <dt> Access type: Read/write </dt> </dl> </dd> <dt> [HASEndpoint](/windows/client-management/mdm/healthattestation-csp) </dt> <dd> <dl> <dt> Data type: **string** </dt> <dt> Access type: Read/write </dt> </dl> </dd> <dt> **InstanceID** </dt> <dd> <dl> <dt> Data type: **string** </dt> <dt> Access type: Read-only </dt> <dt> Qualifiers: [**key**](/windows/desktop/WmiSdk/key-qualifier) </dt> </dl> Identifies the name of the parent node. For this class, the string is "HealthAttestation". </dd> <dt> **MaxSupportedProtocolVersion** </dt> <dd> <dl> <dt> Data type: **sint32** </dt> <dt> Access type: Read/write </dt> </dl> TBD </dd> <dt> [Nonce](/windows/client-management/mdm/healthattestation-csp) </dt> <dd> <dl> <dt> Data type: **string** </dt> <dt> Access type: Read/write </dt> </dl> </dd> <dt> **ParentID** </dt> <dd> <dl> <dt> Data type: **string** </dt> <dt> Access type: Read-only </dt> <dt> Qualifiers: [**key**](/windows/desktop/WmiSdk/key-qualifier) </dt> </dl> Describes the full path to the parent node. For this class, the string is "./Vendor/MSFT/" </dd> <dt> **PreferredMaxProtocolVersion** </dt> <dd> <dl> <dt> Data type: **sint32** </dt> <dt> Access type: Read/write </dt> </dl> TBD </dd> <dt> [Status](/windows/client-management/mdm/healthattestation-csp) </dt> <dd> <dl> <dt> Data type: **sint32** </dt> <dt> Access type: Read/write </dt> </dl> </dd> <dt> [TpmReadyStatus](/windows/client-management/mdm/healthattestation-csp) </dt> <dd> <dl> <dt> Data type: **sint32** </dt> <dt> Access type: Read/write </dt> </dl> </dd> </dl> ## Requirements | Requirement | Value | |-------------------------------------|------------------------------------------------------------------------------------------------| | Minimum supported client<br/> | Windows 10 \[desktop apps only\]<br/> | | Minimum supported server<br/> | None supported<br/> | | Namespace<br/> | Root\\cimv2\\mdm\\dmmap<br/> | | MOF<br/> | <dl> <dt>DMWmiBridgeProv.mof</dt> </dl> | | DLL<br/> | <dl> <dt>DMWmiBridgeProv.dll</dt> </dl> | ## See also <dl> <dt> [Using PowerShell scripting with the WMI Bridge Provider](/windows/client-management/mdm/using-powershell-scripting-with-the-wmi-bridge-provider) </dt> </dl> ======================= File: desktop-src/medfound/mf-bytestream-content-type-attribute.md ======================= <filename>desktop-src/medfound/mf-bytestream-content-type-attribute.md --- description: Specifies the MIME type of a byte stream. ms.assetid: bcf86ece-2673-4ed8-98fd-cd0e2154b4a8 title: MF_BYTESTREAM_CONTENT_TYPE attribute (Mfobjects.h) ms.topic: reference ms.date: 05/31/2018 --- # MF\_BYTESTREAM\_CONTENT\_TYPE attribute Specifies the MIME type of a byte stream. ## Data type Wide-character string ## Remarks To get the attribute value, query the byte stream object for the [**IMFAttributes**](/windows/desktop/api/mfobjects/nn-mfobjects-imfattributes) interface. The GUID constant for this attribute is exported from mfuuid.lib. ## Requirements | Requirement | Value | |-------------------------------------|----------------------------------------------------------------------------------------------------------| | Minimum supported client<br/> | Windows Vista \[desktop apps \| UWP apps\]<br/> | | Minimum supported server<br/> | Windows Server 2008 \[desktop apps \| UWP apps\]<br/> | | Header<br/> | <dl> <dt>Mfobjects.h (include Mfidl.h)</dt> </dl> | ## See also <dl> <dt> [Alphabetical List of Media Foundation Attributes](alphabetical-list-of-media-foundation-attributes.md) </dt> <dt> [Byte Stream Attributes](byte-stream-attributes.md) </dt> <dt> [**IMFAttributes::GetString**](/windows/desktop/api/mfobjects/nf-mfobjects-imfattributes-getstring) </dt> <dt> [**IMFAttributes::SetString**](/windows/desktop/api/mfobjects/nf-mfobjects-imfattributes-setstring) </dt> <dt> [**IMFByteStream**](/windows/desktop/api/mfobjects/nn-mfobjects-imfbytestream) </dt> </dl>     ======================= File: desktop-src/ADSchema/r-reload-ssl-certificate.md ======================= <reponame>velden/win32 --- title: Reload-SSL-Certificate extended right description: Reload-SSL-Certificate extended right ms.assetid: 0546b2a7-3ce1-4649-af8b-44674f62d040 ms.tgt_platform: multiple keywords: - Reload-SSL-Certificate extended right AD Schema topic_type: - apiref api_name: - Reload-SSL-Certificate api_type: - Schema ms.topic: reference ms.date: 05/31/2018 --- # Reload-SSL-Certificate extended right | Entry | Value | |--------------|--------------------------------------| | CN | Reload-SSL-Certificate | | Display-Name | Reload SSL/TLS Certificate | | Rights-GUID | 1a60ea8d-58a6-4b20-bcdc-fb71eb8a9ff8 | ## Implementations - [**Windows Server 2008**](#windows-server-2008) - [**Windows Server 2008 R2**](#windows-server-2008-r2) - [**Windows Server 2012**](#windows-server-2012) ## Windows Server 2008 | Entry | Value | |-------------------------|------------------------------------------| | Applies-To | [**NTDS-DSA**](c-ntdsdsa.md)<br/> | | Localization-Display-ID | 76 | ## Windows Server 2008 R2 | Entry | Value | |-------------------------|------------------------------------------| | Applies-To | [**NTDS-DSA**](c-ntdsdsa.md)<br/> | | Localization-Display-ID | 76 | ## Windows Server 2012 | Entry | Value | |-------------------------|------------------------------------------| | Applies-To | [**NTDS-DSA**](c-ntdsdsa.md)<br/> | | Localization-Display-ID | 76 | ======================= File: desktop-src/gdiplus/-gdiplus-using-a-color-matrix-to-set-alpha-values-in-images-use.md ======================= --- description: The Bitmap class (which inherits from the Image class) and the ImageAttributes class provide functionality for getting and setting pixel values. ms.assetid: e3d67431-6098-4b2a-8910-5695a8473216 title: Using a Color Matrix to Set Alpha Values in Images ms.topic: article ms.date: 05/31/2018 --- # Using a Color Matrix to Set Alpha Values in Images The [**Bitmap**](/windows/win32/api/gdiplusheaders/nl-gdiplusheaders-bitmap) class (which inherits from the [**Image**](/windows/win32/api/gdiplusheaders/nl-gdiplusheaders-image) class) and the [**ImageAttributes**](/windows/win32/api/gdiplusimageattributes/nl-gdiplusimageattributes-imageattributes) class provide functionality for getting and setting pixel values. You can use the **ImageAttributes** class to modify the alpha values for an entire image, or you can call the [**Bitmap::SetPixel**](/windows/win32/api/Gdiplusheaders/nf-gdiplusheaders-bitmap-setpixel) method of the **Bitmap** class to modify individual pixel values. For more information on setting individual pixel values, see [Setting the Alpha Values of Individual Pixels](-gdiplus-setting-the-alpha-values-of-individual-pixels-use.md). The following example draws a wide black line and then displays an opaque image that covers part of that line. ``` Bitmap bitmap(L"Texture1.jpg"); Pen pen(Color(255, 0, 0, 0), 25); // First draw a wide black line. graphics.DrawLine(&pen, Point(10, 35), Point(200, 35)); // Now draw an image that covers part of the black line. graphics.DrawImage(&bitmap, Rect(30, 0, bitmap.GetWidth(), bitmap.GetHeight())); ``` The following illustration shows the resulting image, which is drawn at (30, 0). Note that the wide black line doesn't show through the image. ![illustration showing an opaque image overlapping a thin, wide, black rectangle](images/image1.png) The [**ImageAttributes**](/windows/win32/api/gdiplusimageattributes/nl-gdiplusimageattributes-imageattributes) class has many properties that you can use to modify images during rendering. In the following example, an **ImageAttributes** object is used to set all the alpha values to 80 percent of what they were. This is done by initializing a color matrix and setting the alpha scaling value in the matrix to 0.8. The address of the color matrix is passed to the [**ImageAttributes::SetColorMatrix**](/windows/win32/api/Gdiplusimageattributes/nf-gdiplusimageattributes-imageattributes-setcolormatrix) method of the **ImageAttributes** object, and the address of the **ImageAttributes** object is passed to the [DrawImage](/windows/win32/api/gdiplusgraphics/nf-gdiplusgraphics-graphics-drawimage(inimage_inconstrect_)) method of a [**Graphics**](/windows/win32/api/gdiplusgraphics/nl-gdiplusgraphics-graphics) object. ``` // Create a Bitmap object and load it with the texture image. Bitmap bitmap(L"Texture1.jpg"); Pen pen(Color(255, 0, 0, 0), 25); // Initialize the color matrix. // Notice the value 0.8 in row 4, column 4. ColorMatrix colorMatrix = {1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.8f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f}; // Create an ImageAttributes object and set its color matrix. ImageAttributes imageAtt; imageAtt.SetColorMatrix(&colorMatrix, ColorMatrixFlagsDefault, ColorAdjustTypeBitmap); // First draw a wide black line. graphics.DrawLine(&pen, Point(10, 35), Point(200, 35)); // Now draw the semitransparent bitmap image. INT iWidth = bitmap.GetWidth(); INT iHeight = bitmap.GetHeight(); graphics.DrawImage( &bitmap, Rect(30, 0, iWidth, iHeight), // Destination rectangle 0, // Source rectangle X 0, // Source rectangle Y iWidth, // Source rectangle width iHeight, // Source rectangle height UnitPixel, &imageAtt); ``` During rendering, the alpha values in the bitmap are converted to 80 percent of what they were. This results in an image that is blended with the background. As the following illustration shows, the bitmap image looks transparent; you can see the solid black line through it. ![illustration similar to the previous one, but the image is sem-transparent](images/image2.png) Where the image is over the white portion of the background, the image has been blended with the color white. Where the image crosses the black line, the image is blended with the color black.     ======================= File: desktop-src/NetMon2/configuring-experts.md ======================= <gh_stars>100-1000 --- description: To configure experts, use the custom dialog boxes and the Configure function. ms.assetid: 6298fa7b-ddc8-4924-9616-6eed67ec48db title: Configuring Experts ms.topic: article ms.date: 05/31/2018 --- # Configuring Experts To configure experts, use the custom dialog boxes and the [**Configure**](configure.md) function. When you write Network monitor experts, you have a choice. You can create a set of default configuration items that can be used when the expert initially runs, or you can allow Network Monitor users to configure the expert at run time. Configurations for each expert are stored by Network Monitor. As an option, users can reset the expert configuration back to original default settings. Be aware that you can bypass the use of **Configure** by developing an expert that passes a fixed configuration to Network Monitor. ![exper configuration dialog box](images/dialog.png)     ======================= File: desktop-src/P2PSdk/about-the-identity-manager-api.md ======================= <gh_stars>100-1000 --- description: The Peer Identity Manager API allows you to create, enumerate, and manipulate peer identities in a peer application. ms.assetid: c1b2a587-71c7-4623-a318-4624dad7feba title: About Identity Manager ms.topic: article ms.date: 05/31/2018 --- # About Identity Manager The Peer Identity Manager API allows you to create, enumerate, and manipulate peer identities in a peer application. You can use the peer identities created using this API as input for the Peer Grouping and Peer Name Resolution Protocol (PNRP) Namespace Provider APIs. ## Peer Identity Manager Best Practices Each user should have a few peer identities that they can use for the peer activities. For example, a user might have two peer identities for work and leisure. A well-designed peer application allows a user to select a peer identity to use. A user can create a new peer identity if none of the existing peer identities are appropriate to use with an application. A well-designed peer application also controls the number of identities that it creates. If an application creates a temporary peer identity, the application must delete the peer identity when the identity is not needed. If an application does not perform this maintenance, the Peer Identity Manager may not be able to create peer identities until some peer identities are removed.     ======================= File: desktop-src/wcs/device-dependent-color-spaces.md ======================= <reponame>velden/win32<filename>desktop-src/wcs/device-dependent-color-spaces.md --- title: Device-Dependent Color Spaces description: Most color spaces are device dependent. ms.assetid: 657ec64b-8605-4d05-a7d6-9f8bb71e6a71 keywords: - Windows Color System (WCS),device-dependent color spaces - WCS (Windows Color System),device-dependent color spaces - image color management,device-dependent color spaces - color management,device-dependent color spaces - colors,device-dependent color spaces - color spaces,device-dependent - device-dependent color spaces - white point - colorants ms.localizationpriority: high ms.topic: article ms.date: 05/31/2018 --- # Device-Dependent Color Spaces Most [color spaces](c.md) are device dependent. Even though a particular device, such as a printer, may use the CMYK color space, the colors it renders for specific CMYK values are often slightly different than all other types of printers.. It is precisely for this reason that the WCS 1.0 color management system is so useful. All color spaces have a*white point*, which is defined as the whitest white that can be produced in that color space. Since devices can differ from one another, their white points can also differ. All colors that a device can produce are relative to its white point. Therefore, a color management system must be able to map the white point of one color space into another and preserve the relative locations of all colors. It must also be able to map a color in one color space to its closest match in another color space regardless of the differences in the white points. WCS 1.0 is able to accomplish both of these tasks. The RGB color space is often used on computer monitors. As such, it is device dependent. Printers typically use CMYK [colorants](c.md). Each printer implements its own version of the CMYK color space. Digital images may not actually store colors in them. They may store index numbers into a palette of colors. The result is that it is very hard for individual application developers to use or provide a standardized method of moving color images from one device to another. Imaging professionals commonly experience the frustration of creating a graphic image on a computer screen and having it turn out very differently when it is printed. WCS 1.0 addresses these imaging needs.     ======================= File: desktop-src/SecAuthN/sspi-model.md ======================= <filename>desktop-src/SecAuthN/sspi-model.md --- description: Security Support Provider Interface (SSPI) allows an application to use various security models available on a computer or network without changing the interface to the security system. ms.assetid: 86ffc8c0-727d-437f-ac36-10df6563b0be title: SSPI Model ms.topic: article ms.date: 05/31/2018 --- # SSPI Model [*Security Support Provider Interface*](../secgloss/s-gly.md) (SSPI) allows an application to use various security models available on a computer or network without changing the interface to the security system. SSPI does not establish logon [*credentials*](../secgloss/c-gly.md) because that is generally a privileged operation handled by the operating system. A [*security support provider*](../secgloss/s-gly.md) (SSP) is contained in a [*dynamic-link library*](../secgloss/d-gly.md) (DLL) that implements SSPI by making one or more [*security packages*](../secgloss/s-gly.md) available to applications. Each security package provides mappings between the SSPI function calls of an application and the functions of an actual security model. Security packages support [*security protocols*](../secgloss/s-gly.md) such as [*Kerberos*](../secgloss/k-gly.md) authentication and LAN Manager. The SSPI interface is available in kernel mode as well as user mode. To use SSPI functionality in kernel mode, you must install the Windows Installable File System DDK. The calling model remains the same, but kernel mode considerations are noted on function reference pages. For more information, see [SSPI Functions](authentication-functions.md).     ======================= File: desktop-src/DirectShow/ctransformoutputpin-checkconnect.md ======================= --- description: CTransformOutputPin.CheckConnect method - The CheckConnect method determines whether a pin connection is suitable. ms.assetid: 3dae5c6d-720e-4445-b601-3bdfe32f4c21 title: CTransformOutputPin.CheckConnect method (Transfrm.h) ms.topic: reference ms.date: 05/31/2018 topic_type: - APIRef - kbSyntax api_name: - CTransformOutputPin.CheckConnect api_type: - COM api_location: - Strmbase.lib - Strmbase.dll - Strmbasd.lib - Strmbasd.dll --- # CTransformOutputPin.CheckConnect method The `CheckConnect` method determines whether a pin connection is suitable. ## Syntax ```C++ HRESULT CheckConnect( IPin *pPin ); ``` ## Parameters <dl> <dt> *pPin* </dt> <dd> Pointer to the output pin's [**IPin**](/windows/desktop/api/Strmif/nn-strmif-ipin) interface. </dd> </dl> ## Return value Returns an **HRESULT** value. Possible values include the following. | Return code | Description | |----------------------------------------------------------------------------------------------|-----------------------------------------------------| | <dl> <dt>**S\_OK**</dt> </dl> | Success.<br/> | | <dl> <dt>**E\_UNEXPECTED**</dt> </dl> | The filter's input pin is not connected.<br/> | ## Remarks This method overrides the [**CBaseOutputPin::CheckConnect**](cbaseoutputpin-checkconnect.md) method. It calls the filter's [**CTransformFilter::CheckConnect**](ctransformfilter-checkconnect.md) method, which returns S\_OK in the base class. The derived class can override the **CTransformFilter::CheckConnect** method to perform additional checks. ## Requirements | Requirement | Value | |--------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | Header<br/> | <dl> <dt>Transfrm.h (include Streams.h)</dt> </dl> | | Library<br/> | <dl> <dt>Strmbase.lib (retail builds); </dt> <dt>Strmbasd.lib (debug builds)</dt> </dl> | ======================= File: desktop-src/VSS/overview-of-restore-clean-up-and-termination.md ======================= <gh_stars>100-1000 --- description: Following a restore, writers check the status of the operation so that they can make use of the restored data and deal with errors. ms.assetid: f9def67a-c4ea-4014-929f-51fbd10d770a title: Overview of Restore Clean up and Termination ms.topic: article ms.date: 05/31/2018 --- # Overview of Restore Clean up and Termination Following a restore, writers check the status of the operation so that they can make use of the restored data and deal with errors. The requester must wait for the completion of this activity. For more information, see [Overview of Processing a Restore Under VSS](overview-of-processing-a-restore-under-vss.md). The following table shows the sequence of actions and events that are required after a restore operation has taken place. | Requester action | Event | Writer action | |-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | The requester indicates the end of the restore (see [**IVssBackupComponents::PostRestore**](/windows/desktop/api/VsBackup/nf-vsbackup-ivssbackupcomponents-postrestore)). | [*PostRestore*](vssgloss-p.md) | The writer conducts post-restore cleanup, and handles restoration failures and files that have been restored to nonstandard locations (see [**CVssWriter::OnPostRestore**](/windows/desktop/api/VsWriter/nf-vswriter-cvsswriter-onpostrestore), [**IVssComponent**](/windows/desktop/api/VsWriter/nl-vswriter-ivsscomponent)). | | The requester waits on writers to handle the [**PostRestore**](/windows/desktop/api/VsBackup/nf-vsbackup-ivssbackupcomponents-postrestore) event with [**IVssAsync**](/windows/desktop/api/Vss/nn-vss-ivssasync). It should also verify writer status (see [**IVssBackupComponents::GatherWriterStatus**](/windows/desktop/api/VsBackup/nf-vsbackup-ivssbackupcomponents-gatherwriterstatus), [**IVssBackupComponents::GetWriterStatus**](/windows/desktop/api/VsBackup/nf-vsbackup-ivssbackupcomponents-getwriterstatus)). | None | None | | The requester releases the [**IVssBackupComponents**](/windows/desktop/api/VsBackup/nl-vsbackup-ivssbackupcomponents) interface. | None | None |   ## Requester Actions during Cleanup and Termination At this point, a requester indicates the end of its file restoration activities by generating a [*PostRestore*](vssgloss-p.md) event by calling [**IVssBackupComponents::PostRestore**](/windows/desktop/api/VsBackup/nf-vsbackup-ivssbackupcomponents-postrestore). The requester's actions are limited to waiting on the writers, which may need to perform some final cleanup and handle restore errors, and releasing the [**IVssBackupComponents**](/windows/desktop/api/VsBackup/nl-vsbackup-ivssbackupcomponents) interface after all writers have returned from handling the [*PostRestore*](vssgloss-p.md) event. ## Writer Actions during Cleanup and Termination The [*PostRestore*](vssgloss-p.md) event is handled by the virtual method [**CVssWriter::OnPostRestore**](/windows/desktop/api/VsWriter/nf-vswriter-cvsswriter-onpostrestore). The default implementation simply returns **true** without taking any action. If a writer needs to exercise more control of the post-restore situation, it can override this method. In addition to any normal cleanup (such as removing temporary files) that a writer might perform in [**CVssWriter::OnPostRestore**](/windows/desktop/api/VsWriter/nf-vswriter-cvsswriter-onpostrestore), it can handle the success or failure of restore operations. How it handles restore errors, files restored to an alternate location, and the need for future restores are completely at the writer's discretion. Typical actions might include comparing files in alternate or new locations with files currently in use, merging data from multiple files, or starting new sessions connected to the new data files. VSS provides the following mechanisms for supporting this on a component-by-component basis: - Success or failure in restoring any component can be found with [**IVssComponent::GetFileRestoreStatus**](/windows/desktop/api/VsWriter/nf-vswriter-ivsscomponent-getfilerestorestatus). - The use of alternate location mappings in restoring files will be indicated by [**IVssComponent::GetAlternateLocationMapping**](/windows/desktop/api/VsWriter/nf-vswriter-ivsscomponent-getalternatelocationmapping). - Determining if a restore is incremental and will require further restores is done by calling [**IVssComponent::GetAdditionalRestores**](/windows/desktop/api/VsWriter/nf-vswriter-ivsscomponent-getadditionalrestores). Writers that need a complete restoration of their data should not restart until this method returns false. - Writers can determine if the requester has needed to restore files to a previously unspecified location using [**IVssComponent::GetNewTargetCount**](/windows/desktop/api/VsWriter/nf-vswriter-ivsscomponent-getnewtargetcount) and [**IVssComponent::GetNewTarget**](/windows/desktop/api/VsWriter/nf-vswriter-ivsscomponent-getnewtarget) (For more information on restoring files to non-default locations, see [Non-Default Backup and Restore Locations](non-default-backup-and-restore-locations.md).) As with any [**IVssComponent**](/windows/desktop/api/VsWriter/nl-vswriter-ivsscomponent) method, the information returned by a given instance applies to those components [*explicitly included*](vssgloss-e.md) for backup and any of its [*implicitly included*](vssgloss-i.md) for backup subcomponents, including those subcomponents explicitly included for restore by the requester using [**IVssBackupComponents::AddRestoreSubcomponent**](/windows/desktop/api/VsBackup/nf-vsbackup-ivssbackupcomponents-addrestoresubcomponent) (see [Working with Selectability For Restore and Subcomponents](working-with-selectability-for-restore-and-subcomponents.md) for details). Because the writers will require access to the Backup Components Document, it is important that the requester not release the [**IVssBackupComponents**](/windows/desktop/api/VsBackup/nl-vsbackup-ivssbackupcomponents) interface until writers have finished processing.     ======================= File: desktop-src/DirectShow/building-directshow-filters.md ======================= <gh_stars>100-1000 --- description: Building DirectShow Filters ms.assetid: fb907263-e7f3-42d6-80f9-a9f16fc21033 title: Building DirectShow Filters ms.topic: article ms.date: 05/31/2018 --- # Building DirectShow Filters The DirectShow base classes are recommended for implementing DirectShow filters. To build with the base classes, perform the following steps, in addition to the steps listed in [Setting Up the Build Environment](setting-up-the-build-environment.md): - Build the base class library, located in the directory Samples\\Multimedia\\DirectShow\\BaseClasses, under the SDK root directory. There are two versions of the library: a retail version (Strmbase.lib) and a debug version (Strmbasd.lib). - Include the header file Streams.h. - Use the \_\_stdcall calling convention. - Use the multithreaded C run-time library (debug or retail, as appropriate). - Include a definition (.def) file that exports the DLL functions. The following is an example of a definition file. It assumes that the output file is named MyFilter.dll. ```C++ LIBRARY MYFILTER.DLL EXPORTS DllMain PRIVATE DllGetClassObject PRIVATE DllCanUnloadNow PRIVATE DllRegisterServer PRIVATE DllUnregisterServer PRIVATE ``` - Link to the following lib files. | Label | Value | |--------------|--------------------------------------| | Debug Build | Strmbasd.lib, Msvcrtd.lib, Winmm.lib | | Retail Build | Strmbase.lib, Msvcrt.lib, Winmm.lib |   - Choose the "ignore default libraries" option in the linker settings. - Declare the DLL entry point in your source code, as follows: ```C++ extern "C" BOOL WINAPI DllEntryPoint(HINSTANCE, ULONG, LPVOID); BOOL APIENTRY DllMain(HANDLE hModule, DWORD dwReason, LPVOID lpReserved) { return DllEntryPoint((HINSTANCE)(hModule), dwReason, lpReserved); } ``` Previous Versions For versions of the base class library before DirectShow 9.0, you must also do the following: - For debug builds, define the preprocessor flag DEBUG. This step is not required for the version of the base class library that is available in DirectShow 9.0 and later. ## Related topics <dl> <dt> [DirectShow Base Classes](directshow-base-classes.md) </dt> <dt> [Writing DirectShow Filters](writing-directshow-filters.md) </dt> </dl>     ======================= File: desktop-src/WMP/video-maintainaspectratio.md ======================= <gh_stars>100-1000 --- title: VIDEO.maintainAspectRatio description: The maintainAspectRatio attribute specifies or retrieves a value indicating whether the video will maintain its aspect ratio when trying to fit within the width and height defined for the control. ms.assetid: 42ac2196-b747-48d5-868d-7f7e5eb8dabb keywords: - VIDEO.maintainAspectRatio Windows Media Player topic_type: - apiref api_name: - VIDEO.maintainAspectRatio api_type: - NA ms.topic: reference ms.date: 05/31/2018 --- # VIDEO.maintainAspectRatio The **maintainAspectRatio** attribute specifies or retrieves a value indicating whether the video will maintain its aspect ratio when trying to fit within the width and height defined for the control. ``` syntax elementID.maintainAspectRatio ``` ## Possible Values This attribute is a read/write **Boolean**. | Value | Description | |-------|----------------------------------------------------------| | true | Default. Video maintains its aspect ratio when resizing. | | false | Video does not maintain its aspect ratio when resizing. | ## Requirements | Requirement | Value | |--------------------|------------------------------------------------------| | Version<br/> | Windows Media Player version 7.0 or later<br/> | ## See also <dl> <dt> [**VIDEO Element**](video-element.md) </dt> </dl> ======================= File: desktop-src/DevNotes/octerminate.md ======================= --- description: Closes the OC manager. ms.assetid: feba9954-03b2-4b57-b7ba-933e171751ff title: OcTerminate function ms.topic: reference ms.date: 05/31/2018 topic_type: - APIRef - kbSyntax api_name: - OcTerminate api_type: - DllExport api_location: - OcManage.dll --- # OcTerminate function Closes the OC manager. ## Syntax ```C++ VOID OcTerminate( _Inout_ PVOID *OcManagerContext ); ``` ## Parameters <dl> <dt> *OcManagerContext* \[in, out\] </dt> <dd> On input, contains the OC manager context pointer returned by [**OcInitialize**](ocinitialize.md). On output, receives **NULL**. </dd> </dl> ## Return value This function does not return a value. ## Remarks This function has no associated import library or header file; you must call it using the [**LoadLibrary**](/windows/win32/api/libloaderapi/nf-libloaderapi-loadlibrarya) and [**GetProcAddress**](/windows/win32/api/libloaderapi/nf-libloaderapi-getprocaddress) functions. ## Requirements | Requirement | Value | |----------------|-----------------------------------------------------------------------------------------| | DLL<br/> | <dl> <dt>OcManage.dll</dt> </dl> | ## See also <dl> <dt> [**OcInitialize**](ocinitialize.md) </dt> </dl>     ======================= File: desktop-src/Msi/condition.md ======================= <filename>desktop-src/Msi/condition.md --- description: The Condition data type is a text string containing a valid conditional statement that can be evaluated as true or false. For information on the syntax of conditional statements, see Conditional Statement Syntax. ms.assetid: cdfda625-b1d7-4274-93e4-91af05d8b0f3 title: Condition ms.topic: article ms.date: 05/31/2018 --- # Condition The Condition data type is a text string containing a valid conditional statement that can be evaluated as true or false. For information on the syntax of conditional statements, see [Conditional Statement Syntax](conditional-statement-syntax.md).     ======================= File: desktop-src/Debug/initializing-the-symbol-handler.md ======================= --- description: The following code demonstrates how to initialize the symbol handler. ms.assetid: e8c8f648-c3b0-4595-ac07-f508dd576d9f title: Initializing the Symbol Handler ms.topic: article ms.date: 05/31/2018 --- # Initializing the Symbol Handler The following code demonstrates how to initialize the symbol handler. The [**SymSetOptions**](/windows/desktop/api/Dbghelp/nf-dbghelp-symsetoptions) function defers symbol loading until symbol information is requested. The code loads the symbols for each module in the specified process by passing a value of **TRUE** for the *bInvade* parameter of the [**SymInitialize**](/windows/desktop/api/Dbghelp/nf-dbghelp-syminitialize) function. (This function calls the [**SymLoadModule64**](/windows/desktop/api/Dbghelp/nf-dbghelp-symloadmodule) function for each module the process has mapped into its address space.) If the specified process is not the process that called [**SymInitialize**](/windows/desktop/api/Dbghelp/nf-dbghelp-syminitialize), the code passes a process identifier as the first parameter of **SymInitialize**. Specifying **NULL** as the second parameter of [**SymInitialize**](/windows/desktop/api/Dbghelp/nf-dbghelp-syminitialize) indicates that the symbol handler should use the default search path to locate symbol files. For detailed information on how the symbol handler locates symbol files or how an application can specify a symbol search path, see [Symbol Paths](symbol-paths.md). ```C++ DWORD error; HANDLE hProcess; SymSetOptions(SYMOPT_UNDNAME | SYMOPT_DEFERRED_LOADS); hProcess = GetCurrentProcess(); if (!SymInitialize(hProcess, NULL, TRUE)) { // SymInitialize failed error = GetLastError(); printf("SymInitialize returned error : %d\n", error); return FALSE; } ```     ======================= File: desktop-src/SecCertEnroll/ix509enrollmentwebclassfactory-methods.md ======================= --- description: The IX509EnrollmentWebClassFactory interface exposes the following methods. ms.assetid: F32995D4-E928-4CB8-9C44-C250D232F6A8 title: IX509EnrollmentWebClassFactory Methods ms.topic: reference ms.date: 05/31/2018 --- # IX509EnrollmentWebClassFactory Methods The [**IX509EnrollmentWebClassFactory**](/windows/desktop/api/CertEnroll/nn-certenroll-ix509enrollmentwebclassfactory) interface exposes the following methods. ## In this section - [**CreateObject Method**](/windows/desktop/api/CertEnroll/nf-certenroll-ix509enrollmentwebclassfactory-createobject)     ======================= File: desktop-src/Direct2D/d1112-device-must-be-dx10-1.md ======================= <reponame>velden/win32<gh_stars>100-1000 --- title: D1112 Device Must Be DX11 ms.assetid: 39dcccaf-db56-402d-b62f-704ad4daf151 description: The device associated with the DXGI surface must be a D3D11 device. keywords: - D1112 Device Must Be DX11 Direct2D topic_type: - apiref api_name: - D1112 Device Must Be DX11 api_type: - NA ms.topic: reference ms.date: 05/31/2018 ms.custom: "seodec18" --- # D1112: Device Must Be DX11 The device associated with the DXGI surface must be a D3D11 device. | &nbsp; | &nbsp; | |-------------|---------| | Error Level | Warning |   ## Possible Causes There was an attempt to use the [**CreateDxgiSurfaceRenderTarget**](/windows/win32/api/d2d1/nf-d2d1-id2d1factory-createdxgisurfacerendertarget(idxgisurface_constd2d1_render_target_properties__id2d1rendertarget)) with a DXGI surface created by a non-Direct3D11 device.     ======================= File: desktop-src/Tapi/tapi-3-terminal-manager.md ======================= --- description: The TAPI 3 Terminal Manager is created by Tapi3.dll at the request of an MSP, and is used by the MSP for tasks such as the creation and deletion of dynamic terminals. ms.assetid: 4fecbdc3-490d-44dc-bdbc-61a8e2b82d3d title: TAPI 3 Terminal Manager ms.topic: article ms.date: 05/31/2018 --- # TAPI 3 Terminal Manager The TAPI 3 Terminal Manager is created by Tapi3.dll at the request of an MSP, and is used by the MSP for tasks such as the creation and deletion of dynamic terminals. The precise implementation details for an MSP's dynamic terminals are beyond the scope of this documentation. However, many authors may choose to use some of the capabilities of the Media Streaming Terminal (MST). This terminal is based on DirectShow and filters specific to a given protocol may be written and used in conjunction with the MST.     ======================= File: desktop-src/WinSock/called-party-subaddress-2.md ======================= --- description: This section lists the type definition for the called party subaddress. ms.assetid: c6a1caf9-8bf8-41be-ae64-62d42eda550e title: Called Party Subaddress ms.topic: article ms.date: 05/31/2018 --- # Called Party Subaddress This section lists the type definition for the called party subaddress. ``` syntax typedef ATM_ADDRESS ATM_CALLED_PARTY_SUBADDRESS_IE; ```     ======================= File: desktop-src/Msi/findrelatedproducts-action.md ======================= --- description: The FindRelatedProducts action runs through each record of the Upgrade table in sequence and compares the upgrade code, product version, and language in each row to products installed on the system. ms.assetid: 7efcb767-9bdf-43a4-83b8-61b6fc84adf6 title: FindRelatedProducts Action ms.topic: article ms.date: 05/31/2018 --- # FindRelatedProducts Action The FindRelatedProducts action runs through each record of the [Upgrade table](upgrade-table.md) in sequence and compares the upgrade code, product version, and language in each row to products installed on the system. When FindRelatedProducts detects a correspondence between the upgrade information and an installed product, it appends the product code to the property specified in the ActionProperty column of the UpgradeTable. The FindRelatedProducts action only runs the first time the product is installed. The FindRelatedProducts action does not run during maintenance mode or uninstallation. ## Database Tables Queried This action queries the following table: [Upgrade Table](upgrade-table.md) ## Properties Used The FindRelatedProducts action uses the [**UpgradeCode**](upgradecode.md) property and the version and language information authored into the Upgrade table to detect installed products affected by the pending upgrade. It appends the product code of detected products to the property in the ActionProperty column of the UpgradeTable. FindRelatedProducts only recognizes existing products that have been installed using the Windows Installer with an.msi that defines an [**UpgradeCode**](upgradecode.md) property, a [**ProductVersion**](productversion.md) property, and a value for the [**ProductLanguage**](productlanguage.md) property that is one of the languages listed in the [**Template Summary**](template-summary.md) Property. Note that FindRelatedProducts uses the language returned by [**MsiGetProductInfo**](/windows/desktop/api/Msi/nf-msi-msigetproductinfoa). For FindRelatedProducts to work correctly, the package author must be sure that the [**ProductLanguage**](productlanguage.md) property in the [Property table](property-table.md) is set to a language that is also listed in the [**Template Summary**](template-summary.md) Property. See [Preparing an Application for Future Major Upgrades](preparing-an-application-for-future-major-upgrades.md). ## Sequence Restrictions FindRelatedProducts should be authored into the [InstallUISequence table](installuisequence-table.md) and [InstallExecuteSequence](installexecutesequence-table.md) tables. The installer prevents FindRelated Products from running in InstallExecuteSequence if the action has already run in InstallUISequence. The FindRelatedProducts action must come before the [MigrateFeatureStates action](migratefeaturestates-action.md) and the [RemoveExistingProducts action](removeexistingproducts-action.md). ## ActionData Messages FindRelatedProducts sends an action data message for each related product it detects on the system.     ======================= File: desktop-src/SecCrypto/icertview2-methods.md ======================= <reponame>velden/win32 --- description: The ICertView2 interface exposes the following methods. ms.assetid: 22496D16-27F2-45F6-A746-897D18A7D6E7 title: ICertView2 Methods ms.topic: reference ms.date: 05/31/2018 --- # ICertView2 Methods The [**ICertView2**](/windows/desktop/api/Certview/nn-certview-icertview2) interface exposes the following methods. ## In this section - [**EnumCertViewColumn Method**](/windows/desktop/api/Certview/nf-certview-icertview-enumcertviewcolumn) - [**GetColumnCount Method**](/windows/desktop/api/Certview/nf-certview-icertview-getcolumncount) - [**GetColumnIndex Method**](/windows/desktop/api/Certview/nf-certview-icertview-getcolumnindex) - [**OpenConnection Method**](/windows/desktop/api/Certview/nf-certview-icertview-openconnection) - [**OpenView Method**](/windows/desktop/api/Certview/nf-certview-icertview-openview) - [**SetRestriction Method**](/windows/desktop/api/Certview/nf-certview-icertview-setrestriction) - [**SetResultColumn Method**](/windows/desktop/api/Certview/nf-certview-icertview-setresultcolumn) - [**SetResultColumnCount Method**](/windows/desktop/api/Certview/nf-certview-icertview-setresultcolumncount) - [**SetTable Method**](/windows/desktop/api/Certview/nf-certview-icertview2-settable)     ======================= File: desktop-src/WinAuto/uiauto-annotation-type-identifiers.md ======================= <gh_stars>100-1000 --- title: Annotation Type Identifiers (UIAutomationClient.h) description: This topic describes the named constants that are used to identify types of annotations in a document. ms.assetid: 46948B7C-EC9F-4B55-B769-62EE8BE11D33 topic_type: - apiref api_name: - AnnotationType_AdvancedProofingIssue - AnnotationType_Author - AnnotationType_CircularReferenceError - AnnotationType_Comment - AnnotationType_ConflictingChange - AnnotationType_DataValidationError - AnnotationType_DeletionChange - AnnotationType_EditingLockedChange - AnnotationType_Endnote - AnnotationType_ExternalChange - AnnotationType_Footer - AnnotationType_Footnote - AnnotationType_FormatChange - AnnotationType_FormulaError - AnnotationType_GrammarError - AnnotationType_Header - AnnotationType_Highlighted - AnnotationType_InsertionChange - AnnotationType_Mathematics - AnnotationType_MoveChange - AnnotationType_SpellingError - AnnotationType_TrackChanges - AnnotationType_Unknown - AnnotationType_UnsyncedChange api_location: - UIAutomationClient.h api_type: - HeaderDef ms.topic: reference ms.date: 05/31/2018 --- # Annotation Type Identifiers This topic describes the named constants that are used to identify types of annotations in a document. | Constant/value | Description | |:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:---------------------------------------------------------------------------------------------------| | <span id="AnnotationType_AdvancedProofingIssue"></span><span id="annotationtype_advancedproofingissue"></span><span id="ANNOTATIONTYPE_ADVANCEDPROOFINGISSUE"></span><dl> <dt>**AnnotationType\_AdvancedProofingIssue**</dt> <dt>60020</dt> </dl> | An advanced proofing issue.<br/> | | <span id="AnnotationType_Author"></span><span id="annotationtype_author"></span><span id="ANNOTATIONTYPE_AUTHOR"></span><dl> <dt>**AnnotationType\_Author**</dt> <dt>60019</dt> </dl> | The author of the document.<br/> | | <span id="AnnotationType_CircularReferenceError"></span><span id="annotationtype_circularreferenceerror"></span><span id="ANNOTATIONTYPE_CIRCULARREFERENCEERROR"></span><dl> <dt>**AnnotationType\_CircularReferenceError**</dt> <dt>60022</dt> </dl> | A circular reference error that occurred.<br/> | | <span id="AnnotationType_Comment"></span><span id="annotationtype_comment"></span><span id="ANNOTATIONTYPE_COMMENT"></span><dl> <dt>**AnnotationType\_Comment**</dt> <dt>60003</dt> </dl> | A comment. Comments can take different forms depending on the application.<br/> | | <span id="AnnotationType_ConflictingChange"></span><span id="annotationtype_conflictingchange"></span><span id="ANNOTATIONTYPE_CONFLICTINGCHANGE"></span><dl> <dt>**AnnotationType\_ConflictingChange**</dt> <dt>60018</dt> </dl> | A conflicting change that was made to the document.<br/> | | <span id="AnnotationType_DataValidationError"></span><span id="annotationtype_datavalidationerror"></span><span id="ANNOTATIONTYPE_DATAVALIDATIONERROR"></span><dl> <dt>**AnnotationType\_DataValidationError**</dt> <dt>60021</dt> </dl> | A data validation error that occurred.<br/> | | <span id="AnnotationType_DeletionChange"></span><span id="annotationtype_deletionchange"></span><span id="ANNOTATIONTYPE_DELETIONCHANGE"></span><dl> <dt>**AnnotationType\_DeletionChange**</dt> <dt>60012</dt> </dl> | A deletion change that was made to the document.<br/> | | <span id="AnnotationType_EditingLockedChange"></span><span id="annotationtype_editinglockedchange"></span><span id="ANNOTATIONTYPE_EDITINGLOCKEDCHANGE"></span><dl> <dt>**AnnotationType\_EditingLockedChange**</dt> <dt>60016</dt> </dl> | An editing locked change that was made to the document.<br/> | | <span id="AnnotationType_Endnote"></span><span id="annotationtype_endnote"></span><span id="ANNOTATIONTYPE_ENDNOTE"></span><dl> <dt>**AnnotationType\_Endnote**</dt> <dt>60009</dt> </dl> | The endnote for a document.<br/> | | <span id="AnnotationType_ExternalChange"></span><span id="annotationtype_externalchange"></span><span id="ANNOTATIONTYPE_EXTERNALCHANGE"></span><dl> <dt>**AnnotationType\_ExternalChange**</dt> <dt>60017</dt> </dl> | An external change that was made to the document.<br/> | | <span id="AnnotationType_Footer"></span><span id="annotationtype_footer"></span><span id="ANNOTATIONTYPE_FOOTER"></span><dl> <dt>**AnnotationType\_Footer**</dt> <dt>60007</dt> </dl> | The footer for a page in a document.<br/> | | <span id="AnnotationType_Footnote"></span><span id="annotationtype_footnote"></span><span id="ANNOTATIONTYPE_FOOTNOTE"></span><dl> <dt>**AnnotationType\_Footnote**</dt> <dt>60010</dt> </dl> | The footnote for a page in a document.<br/> | | <span id="AnnotationType_FormatChange"></span><span id="annotationtype_formatchange"></span><span id="ANNOTATIONTYPE_FORMATCHANGE"></span><dl> <dt>**AnnotationType\_FormatChange**</dt> <dt>60014</dt> </dl> | A format change that was made.<br/> | | <span id="AnnotationType_FormulaError"></span><span id="annotationtype_formulaerror"></span><span id="ANNOTATIONTYPE_FORMULAERROR"></span><dl> <dt>**AnnotationType\_FormulaError**</dt> <dt>60004</dt> </dl> | An error in a formula. Formula errors typically include red text and exclamation marks.<br/> | | <span id="AnnotationType_GrammarError"></span><span id="annotationtype_grammarerror"></span><span id="ANNOTATIONTYPE_GRAMMARERROR"></span><dl> <dt>**AnnotationType\_GrammarError**</dt> <dt>60002</dt> </dl> | A grammatical error, often denoted by a green squiggly line. <br/> | | <span id="AnnotationType_Header"></span><span id="annotationtype_header"></span><span id="ANNOTATIONTYPE_HEADER"></span><dl> <dt>**AnnotationType\_Header**</dt> <dt>60006</dt> </dl> | The header for a page in a document.<br/> | | <span id="AnnotationType_Highlighted"></span><span id="annotationtype_highlighted"></span><span id="ANNOTATIONTYPE_HIGHLIGHTED"></span><dl> <dt>**AnnotationType\_Highlighted**</dt> <dt>60008</dt> </dl> | Highlighted content, typically denoted by a contrasting background color.<br/> | | <span id="AnnotationType_InsertionChange"></span><span id="annotationtype_insertionchange"></span><span id="ANNOTATIONTYPE_INSERTIONCHANGE"></span><dl> <dt>**AnnotationType\_InsertionChange**</dt> <dt>60011</dt> </dl> | An insertion change that was made to the document.<br/> | | <span id="AnnotationType_Mathematics"></span><span id="annotationtype_mathematics"></span><span id="ANNOTATIONTYPE_MATHEMATICS"></span><dl> <dt>**AnnotationType\_Mathematics**</dt> <dt>60023</dt> </dl> | A text range containing mathematics.<br/> | | <span id="AnnotationType_MoveChange"></span><span id="annotationtype_movechange"></span><span id="ANNOTATIONTYPE_MOVECHANGE"></span><dl> <dt>**AnnotationType\_MoveChange**</dt> <dt>60013</dt> </dl> | A move change that was made to the document.<br/> | | <span id="AnnotationType_SpellingError"></span><span id="annotationtype_spellingerror"></span><span id="ANNOTATIONTYPE_SPELLINGERROR"></span><dl> <dt>**AnnotationType\_SpellingError**</dt> <dt>60001</dt> </dl> | A spelling error, often denoted by a red squiggly line. <br/> | | <span id="AnnotationType_TrackChanges"></span><span id="annotationtype_trackchanges"></span><span id="ANNOTATIONTYPE_TRACKCHANGES"></span><dl> <dt>**AnnotationType\_TrackChanges**</dt> <dt>60005</dt> </dl> | A change that was made to the document.<br/> | | <span id="AnnotationType_Unknown"></span><span id="annotationtype_unknown"></span><span id="ANNOTATIONTYPE_UNKNOWN"></span><dl> <dt>**AnnotationType\_Unknown**</dt> <dt>60000</dt> </dl> | The annotation type is unknown.<br/> | | <span id="AnnotationType_UnsyncedChange"></span><span id="annotationtype_unsyncedchange"></span><span id="ANNOTATIONTYPE_UNSYNCEDCHANGE"></span><dl> <dt>**AnnotationType\_UnsyncedChange**</dt> <dt>60015</dt> </dl> | An unsynced change that was made to the document.<br/> | ## Requirements | Requirement | Value | |-------------------------------------|-------------------------------------------------------------------------------------------------| | Minimum supported client<br/> | Windows 8 \[desktop apps only\]<br/> | | Minimum supported server<br/> | Windows Server 2012 \[desktop apps only\]<br/> | | Header<br/> | <dl> <dt>UIAutomationClient.h</dt> </dl> | ## See also <dl> <dt> **Reference** </dt> <dt> [**IAnnotationProvider::AnnotationTypeId**](/windows/desktop/api/uiautomationcore/nf-uiautomationcore-iannotationprovider-get_annotationtypeid) </dt> <dt> [**ISpreadsheetItemProvider::GetAnnotationTypes**](/windows/desktop/api/uiautomationcore/nf-uiautomationcore-ispreadsheetitemprovider-getannotationtypes) </dt> <dt> [**IUIAutomationPattern::CachedAnnotationTypeId**](/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationannotationpattern-get_cachedannotationtypeid) </dt> <dt> [**IUIAutomationPattern::CurrentAnnotationTypeId**](/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationannotationpattern-get_currentannotationtypeid) </dt> <dt> [**IUIAutomationSpreadsheetItemPattern::GetCachedAnnotationType**](/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationspreadsheetitempattern-getcachedannotationtypes) </dt> <dt> [**IUIAutomationSpreadsheetItemPattern::GetCurrentAnnotationType**](/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationspreadsheetitempattern-getcurrentannotationtypes) </dt> <dt> **Conceptual** </dt> <dt> [UI Automation Support for Textual Content](uiauto-ui-automation-textpattern-overview.md) </dt> </dl> ======================= File: desktop-src/dxmath/xmmin-template.md ======================= <gh_stars>100-1000 --- description: Compares two numeric data type instances, or two instances of an object which supports an overload of <, and returns the smaller one of the two instances. The data type of the arguments and the return value is the same. ms.assetid:'m:microsoft.directx_sdk.reference.xmmin(t,t)' title: XMMin template (DirectXMath.h) ms.topic: reference ms.date: 05/31/2018 --- # XMMin template Compares two numeric data type instances, or two instances of an object which supports an overload of <, and returns the smaller one of the two instances. The data type of the arguments and the return value is the same. ## Syntax ``` syntax template<class T> T XMMin( [in] T a, [in] T b ); ``` ## Parameters <dl> <dt> <span id="a"></span><span id="A"></span>*a* </dt> <dd> \[in\] Specifies the first of two objects. </dd> <dt> <span id="b"></span><span id="B"></span>*b* </dt> <dd> \[in\] Specifies the two of two objects. </dd> </dl> ## Return Value Returns the smaller of the two input objects. ## Remarks `XMMin` is a template and the T type is specified when the template is instantiated. > [!Note] > The `XMMin` template is new for DirectXMath and is not available for XNAMath 2.x. `XMMin` is available as a macro in XNAMath 2.x.   > [!Note] > Ideally use std::min instead of `XMMin`. To avoid conflicts with Windows headers with std::min, you need to \#define NOMINMAX before you include Windows headers.   **Namespace**: Use DirectX ### Platform Requirements Microsoft Visual Studio 2010 or Microsoft Visual Studio 2012 with the Windows SDK for Windows 8. Supported for Win32 desktop apps, Windows Store apps, and Windows Phone 8 apps. ## Requirements | Requirement | Value | |-------------------|------------------------------------------------------------------------------------------| | Header<br/> | <dl> <dt>DirectXMath.h</dt> </dl> | ## See also <dl> <dt> [DirectXMath Library Template Functions](ovw-xnamath-templates.md) </dt> <dt> [**XMMax**](xmmax-template.md) </dt> </dl>     ======================= File: desktop-src/direct3d11/id3dx11dataprocessor-process.md ======================= --- title: ID3DX11DataProcessor Process method (D3DX11core.h) description: Note The D3DX (D3DX 9, D3DX 10, and D3DX 11) utility library is deprecated for Windows 8 and is not supported for Windows Store apps. Processes data. ms.assetid: be20b231-9c2e-4b4a-bdb1-cdc75552bf9d keywords: - Process method Direct3D 11 - Process method Direct3D 11, ID3DX11DataProcessor interface - ID3DX11DataProcessor interface Direct3D 11, Process method topic_type: - apiref api_name: - ID3DX11DataProcessor.Process api_location: - D3DX11.lib - D3DX11.dll api_type: - COM ms.topic: reference ms.date: 05/31/2018 --- # ID3DX11DataProcessor::Process method > [!Note] > The D3DX (D3DX 9, D3DX 10, and D3DX 11) utility library is deprecated for Windows 8 and is not supported for Windows Store apps. Processes data. ## Syntax ```C++ HRESULT Process( [in] void *pData, [in] SIZE_T cBytes ); ``` ## Parameters <dl> <dt> *pData* \[in\] </dt> <dd> Type: **void\*** Pointer to the data to be processed. </dd> <dt> *cBytes* \[in\] </dt> <dd> Type: **[**SIZE\_T**](/windows/desktop/WinProg/windows-data-types)** Size of the data to be processed. </dd> </dl> ## Return value Type: **[**HRESULT**](https://msdn.microsoft.com/library/Bb401631(v=MSDN.10).aspx)** The return value is one of the values listed in [Direct3D 11 Return Codes](d3d11-graphics-reference-returnvalues.md). ## Remarks This method is used by an [**ID3DX11ThreadPump Interface**](id3dx11threadpump.md). ## Requirements | Requirement | Value | |--------------------|-----------------------------------------------------------------------------------------| | Header<br/> | <dl> <dt>D3DX11core.h</dt> </dl> | | Library<br/> | <dl> <dt>D3DX11.lib</dt> </dl> | ## See also <dl> <dt> [ID3DX11DataProcessor](id3dx11dataprocessor.md) </dt> <dt> [D3DX Interfaces](d3d11-graphics-reference-d3dx11-interfaces.md) </dt> </dl> ======================= File: desktop-src/medfound/mf-toponode-markout-here-attribute.md ======================= --- description: Specifies whether the pipeline applies mark-out at this node. Mark-out is the point where a presentation ends. If pipeline components generate data past the mark-out point, the data is not rendered. ms.assetid: adf2361a-90c7-4650-a486-5c450a41ab54 title: MF_TOPONODE_MARKOUT_HERE attribute (Mfidl.h) ms.topic: reference ms.date: 05/31/2018 --- # MF\_TOPONODE\_MARKOUT\_HERE attribute Specifies whether the pipeline applies mark-out at this node. Mark-out is the point where a presentation ends. If pipeline components generate data past the mark-out point, the data is not rendered. ## Data type **UINT32** Treat as a Boolean value. ## Remarks This attribute applies to all node types. If this attribute is **TRUE**, the Media Foundation pipeline trims the output samples from this node to match the stop time for the presentation. The topology loader sets this attribute when it resolves a topology. Most applications do not need to set or retrieve this attribute. It is recommended that exactly one node in every branch of the topology should have this attribute set to **TRUE**. A topology branch is defined as the path from a source node to an output node. Within a branch, the MF\_TOPONODE\_MARKOUT\_HERE and [MF\_TOPONODE\_MARKIN\_HERE](mf-toponode-markin-here-attribute.md) attributes must be set on the same node in the branch. They cannot be set on different nodes within the same branch. The GUID constant for this attribute is exported from mfuuid.lib. ## Requirements | Requirement | Value | |-------------------------------------|------------------------------------------------------------------------------------| | Minimum supported client<br/> | Windows Vista \[desktop apps only\]<br/> | | Minimum supported server<br/> | Windows Server 2008 \[desktop apps only\]<br/> | | Header<br/> | <dl> <dt>Mfidl.h</dt> </dl> | ## See also <dl> <dt> [Alphabetical List of Media Foundation Attributes](alphabetical-list-of-media-foundation-attributes.md) </dt> <dt> [**IMFAttributes::GetUINT32**](/windows/desktop/api/mfobjects/nf-mfobjects-imfattributes-getuint32) </dt> <dt> [**IMFAttributes::SetUINT32**](/windows/desktop/api/mfobjects/nf-mfobjects-imfattributes-setuint32) </dt> <dt> [**IMFTopologyNode**](/windows/desktop/api/mfidl/nn-mfidl-imftopologynode) </dt> <dt> [**MF\_TOPONODE\_MARKIN\_HERE**](mf-toponode-markin-here-attribute.md) </dt> <dt> [Topology Node Attributes](topology-node-attributes.md) </dt> </dl>     ======================= File: desktop-src/ADSchema/a-msds-portldap.md ======================= <reponame>velden/win32 --- title: ms-DS-Port-LDAP attribute description: Specifies which port is used by the directory service to listen for LDAP requests. ms.assetid: bed80aeb-3fc2-4065-92df-1f387982848e ms.tgt_platform: multiple keywords: - ms-DS-Port-LDAP attribute AD Schema - msDS-PortLDAP attribute AD Schema topic_type: - apiref api_name: - ms-DS-Port-LDAP api_type: - Schema ms.topic: reference ms.date: 05/31/2018 --- # ms-DS-Port-LDAP attribute Specifies which port is used by the directory service to listen for LDAP requests. | Entry | Value | |-------------------|--------------------------------------| | CN | ms-DS-Port-LDAP | | Ldap-Display-Name | msDS-PortLDAP | | Size | \- | | Update Privilege | \- | | Update Frequency | \- | | Attribute-Id | 1.2.840.113556.1.4.1859 | | System-Id-Guid | 977225c1-5bdf-42b7-b6db-c3af077f558f | | Syntax | [**Enumeration**](s-enumeration.md) | ## Implementations - [**ADAM**](#adam) ## ADAM | Entry | Value | |------------------------|------------------------------------------| | Link-Id | \- | | MAPI-Id | \- | | System-Only | False | | Is-Single-Valued | True | | Is Indexed | False | | In Global Catalog | False | | NT-Security-Descriptor | O:BAG:BAD:S: | | Range-Lower | 0 | | Range-Upper | 65535 | | Search-Flags | 0x00000000 | | System-Flags | 0x00000010 | | Classes used in | [**NTDS-DSA**](c-ntdsdsa.md)<br/> | ======================= File: desktop-src/Direct2D/d1119.md ======================= --- title: D1119 Bitmap Bound As Target ms.assetid: 41cefcbd-e3e9-40e6-8525-d9d78f2fd1f9 description: An operation failed because the bitmap has the D2D1\_BITMAP\_OPTIONS\_CANNOT\_DRAW option. keywords: - D1119 Bitmap Bound As Target Direct2D topic_type: - apiref api_name: - D1119 Bitmap Bound As Target api_type: - NA ms.topic: reference ms.date: 05/31/2018 ms.custom: "seodec18" --- # D1119: Bitmap Bound As Target A drawing operation failed because the target bitmap and a source bitmap were the same.   ## Possible Causes A likely cause of this message is that the application attempted a drawing operation where the same bitmap was used for both the source and target. Semantically, this is possible for interoperated Direct3D textures with both BIND\_SHADER\_RESOURCE and BIND\_RENDER\_TARGET. ## Possible Fixes Ensure that the application does not attempt to use its target bitmap as the source of a drawing operation, including effects. In some cases, this message may indicate that the application set its device context’s target to a different bitmap than intended.     ======================= File: desktop-src/TermServ/imstscaxevents-gatewayencryptedotpcookiesize.md ======================= --- title: IMsRdpClientTransportSettings2 GatewayEncryptedOtpCookieSize property description: Specifies or retrieves the size of the encrypted one-time password (OTP) cookie. ms.assetid: a4fdcd06-59ae-407f-9ac6-dfe4b52fb5d7 ms.tgt_platform: multiple keywords: - GatewayEncryptedOtpCookieSize property Remote Desktop Services - GatewayEncryptedOtpCookieSize property Remote Desktop Services, IMsRdpClientTransportSettings2 interface - IMsRdpClientTransportSettings2 interface Remote Desktop Services, GatewayEncryptedOtpCookieSize property topic_type: - apiref api_name: - IMsRdpClientTransportSettings2.GatewayEncryptedOtpCookieSize - IMsRdpClientTransportSettings2.get_GatewayEncryptedOtpCookieSize - IMsRdpClientTransportSettings2.put_GatewayEncryptedOtpCookieSize api_location: - MsTscAx.dll api_type: - COM ms.topic: reference ms.date: 05/31/2018 --- # IMsRdpClientTransportSettings2::GatewayEncryptedOtpCookieSize property Specifies or retrieves the size of the encrypted one-time password (OTP) cookie. This property is read/write. ## Syntax ```C++ HRESULT put_GatewayEncryptedOtpCookieSize( [in] ULONG ulEncryptedOtpCookieSize ); HRESULT get_GatewayEncryptedOtpCookieSize( [out] ULONG *pulEncryptedOtpCookieSize ); ``` ## Property value Specifies or retrieves the size of the encrypted one-time password (OTP) cookie. ## Requirements | Requirement | Value | |-------------------------------------|---------------------------------------------------------------------------------------------------| | Minimum supported client<br/> | Windows Vista with SP1<br/> | | Minimum supported server<br/> | Windows Server 2008<br/> | | Type library<br/> | <dl> <dt>MsTscAx.dll</dt> </dl> | | DLL<br/> | <dl> <dt>MsTscAx.dll</dt> </dl> | | IID<br/> | IID\_IMsRdpClientTransportSettings2 is defined as 67341688-D606-4c73-A5D2-2E0489009319<br/> | ## See also <dl> <dt> [**IMsRdpClientTransportSettings**](imsrdpclienttransportsettings.md) </dt> <dt> [**IMsRdpClientTransportSettings2**](imsrdpclienttransportsettings2.md) </dt> </dl> ======================= File: desktop-src/DirectShow/cbaseinputpin-receive.md ======================= --- description: CBaseInputPin.Receive method - The Receive method receives the next media sample in the stream. This method implements the IMemInputPin::Receive method. ms.assetid: 30fefc7b-7c9c-44cd-b58b-2b275dfa2520 title: CBaseInputPin.Receive method (Amfilter.h) ms.topic: reference ms.date: 05/31/2018 topic_type: - APIRef - kbSyntax api_name: - CBaseInputPin.Receive api_type: - COM api_location: - Strmbase.lib - Strmbase.dll - Strmbasd.lib - Strmbasd.dll --- # CBaseInputPin.Receive method The `Receive` method receives the next media sample in the stream. This method implements the [**IMemInputPin::Receive**](/windows/desktop/api/Strmif/nf-strmif-imeminputpin-receive) method. ## Syntax ```C++ HRESULT Receive( IMediaSample *pSample ); ``` ## Parameters <dl> <dt> *pSample* </dt> <dd> Pointer to the sample's [**IMediaSample**](/windows/desktop/api/Strmif/nn-strmif-imediasample) interface. </dd> </dl> ## Return value Returns an **HRESULT** value. Possible values include those listed in the following table. | Return code | Description | |---------------------------------------------------------------------------------------------------------|------------------------------------------------------------| | <dl> <dt>**S\_OK**</dt> </dl> | Success.<br/> | | <dl> <dt>**S\_FALSE**</dt> </dl> | Pin is currently flushing; sample was rejected.<br/> | | <dl> <dt>**E\_POINTER**</dt> </dl> | **NULL** pointer argument.<br/> | | <dl> <dt>**VFW\_E\_INVALIDMEDIATYPE**</dt> </dl> | Invalid media type.<br/> | | <dl> <dt>**VFW\_E\_RUNTIME\_ERROR**</dt> </dl> | A run-time error occurred.<br/> | | <dl> <dt>**VFW\_E\_WRONG\_STATE**</dt> </dl> | The pin is stopped.<br/> | ## Remarks The upstream output pin calls this method to deliver a sample to the input pin. The input pin must do one of the following: - Process the sample before returning. - Return, and process the sample in a worker thread. - Reject the sample. If the pin uses a worker thread to process the sample, add a reference count to the sample inside this method. After the method returns, the upstream pin releases the sample. When the sample's reference count reaches zero, the sample returns to the allocator for re-use. This method is synchronous and can block. If the method might block, the pin's [**CBaseInputPin::ReceiveCanBlock**](cbaseinputpin-receivecanblock.md) method should return S\_OK. In the base class, this method performs the following steps: 1. Calls the [**CBaseInputPin::CheckStreaming**](cbaseinputpin-checkstreaming.md) method to verify that the pin can process samples now. If it cannot for example, if the pin is stopped the method fails. 2. Retrieves the sample properties and checks whether the format has changed (see below). 3. If the format has changed, the method calls the [**CBasePin::CheckMediaType**](cbasepin-checkmediatype.md) method to determine whether the new format is acceptable. 4. If the new format is not acceptable, the method calls the [**CBasePin::EndOfStream**](cbasepin-endofstream.md) method, posts an EC\_ERRORABORT event, and returns an error code. 5. Assuming there were no errors, the method returns S\_OK. Test for a format change as follows: - If the sample supports the [**IMediaSample2**](/windows/desktop/api/Strmif/nn-strmif-imediasample2) interface, check the **dwSampleFlags** member of the [**AM\_SAMPLE2\_PROPERTIES**](/windows/win32/api/strmif/ns-strmif-am_sample2_properties) structure. If the AM\_SAMPLE\_TYPECHANGED flag is present, the format has changed. - Otherwise, if the sample does not support **IMediaSample2**, call the [**IMediaSample::GetMediaType**](/windows/desktop/api/Strmif/nf-strmif-imediasample-getmediatype) method. If the method returns a non-**NULL** value, the format has changed. In the base class, this method does not process the sample. The derived class must override this method to perform the processing. (What this entails depends entirely on the filter.) The derived class should call the base-class method, to check for the errors described previously. ## Requirements | Requirement | Value | |--------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | Header<br/> | <dl> <dt>Amfilter.h (include Streams.h)</dt> </dl> | | Library<br/> | <dl> <dt>Strmbase.lib (retail builds); </dt> <dt>Strmbasd.lib (debug builds)</dt> </dl> | ## See also <dl> <dt> [**CBaseInputPin Class**](cbaseinputpin.md) </dt> </dl> ======================= File: desktop-src/VPC/ivmdvddrive-setbuslocation.md ======================= --- title: IVMDVDDrive SetBusLocation method (VPCCOMInterfaces.h) description: Attaches the DVD drive to the specified bus location in the virtual machine. ms.assetid: 765274b8-91bc-475a-ac4d-994b2425a421 keywords: - SetBusLocation method Virtual PC - SetBusLocation method Virtual PC, IVMDVDDrive interface - IVMDVDDrive interface Virtual PC, SetBusLocation method topic_type: - apiref api_name: - IVMDVDDrive.SetBusLocation api_location: - VPCCOMInterfaces.h api_type: - COM ms.topic: reference ms.date: 05/31/2018 --- # IVMDVDDrive::SetBusLocation method \[Windows Virtual PC is no longer available for use as of Windows 8. Instead, use the [Hyper-V WMI provider (V2)](/windows/desktop/HyperV_v2/windows-virtualization-portal).\] Attaches the DVD drive to the specified bus location in the virtual machine. ## Syntax ```C++ HRESULT SetBusLocation( [in] long busNumber, [in] long deviceNumber ); ``` ## Parameters <dl> <dt> *busNumber* \[in\] </dt> <dd> The bus number to which this drive is to be attached. For example, on an IDE bus, this number would represent whether to use the primary or secondary bus number. </dd> <dt> *deviceNumber* \[in\] </dt> <dd> The device number to which this drive is to be attached. For example, on an IDE bus, this number would represent whether to use the primary or secondary device location. </dd> </dl> ## Return value This method can return one of these values. | Return code/value | Description | |------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------| | <dl> <dt>**S\_OK**</dt> <dt>0</dt> </dl> | The operation was successful.<br/> | | <dl> <dt>**E\_INVALIDARG**</dt> <dt>0x80000003</dt> </dl> | The bus location specified is not valid.<br/> | | <dl> <dt>**E\_FAIL**</dt> <dt>0x80004005</dt> </dl> | An unexpected error has occurred.<br/> | | <dl> <dt>**VM\_E\_VM\_RUNNING\_OR\_SAVED**</dt> <dt>0xA004020B</dt> </dl> | The bus location cannot be set while the virtual machine is running or in a saved state.<br/> | | <dl> <dt>**VM\_E\_BUS\_LOC\_IN\_USE**</dt> </dl> | Another device is already attached to the specified bus location.<br/> | | <dl> <dt>**VM\_E\_DRIVE\_INVALID**</dt> <dt>0xA0040502</dt> </dl> | The current drive could not be initialized.<br/> | | <dl> <dt>**VM\_E\_VM\_UNKNOWN**</dt> <dt>0xA0040207</dt> </dl> | The changes could not be written to the preferences file because the virtual machine for this drive could not be determined.<br/> | | <dl> <dt>**DISP\_E\_EXCEPTION**</dt> <dt>0x80020009</dt> </dl> | An unexpected error has occurred.<br/> | ## Requirements | Requirement | Value | |-------------------------------------|-----------------------------------------------------------------------------------------------| | Minimum supported client<br/> | Windows 7 \[desktop apps only\]<br/> | | Minimum supported server<br/> | None supported<br/> | | End of client support<br/> | Windows 7<br/> | | Product<br/> | Windows Virtual PC<br/> | | Header<br/> | <dl> <dt>VPCCOMInterfaces.h</dt> </dl> | | IID<br/> | IID\_IVMDVDDrive is defined as b96328f6-6732-437d-a00d-ffa47e43971c<br/> | ## See also <dl> <dt> [**IVMDVDDrive**](ivmdvddrive.md) </dt> </dl> ======================= File: desktop-src/SecCertEnroll/icspalgorithm-methods.md ======================= <filename>desktop-src/SecCertEnroll/icspalgorithm-methods.md --- description: The ICspAlgorithm interface exposes the following methods. ms.assetid: BF8330A6-9494-4EA7-A6D5-E9DD4A5E178B title: ICspAlgorithm Methods ms.topic: reference ms.date: 05/31/2018 --- # ICspAlgorithm Methods The [**ICspAlgorithm**](/windows/desktop/api/CertEnroll/nn-certenroll-icspalgorithm) interface exposes the following methods. ## In this section - [**GetAlgorithmOid Method**](/windows/desktop/api/CertEnroll/nf-certenroll-icspalgorithm-getalgorithmoid)     ======================= File:
1,517
Repo: yuqj1990/deepano_train ======================= File: include/caffe/layers/faceEvaluateLayer.hpp ======================= <reponame>yuqj1990/deepano_train #ifndef CAFFE_DETECTION_EVALUATE_LAYER_HPP_ #define CAFFE_DETECTION_EVALUATE_LAYER_HPP_ #include <utility> #include <vector> #include "caffe/blob.hpp" #include "caffe/layer.hpp" #include "caffe/proto/caffe.pb.h" namespace caffe { /** * @brief Generate the detection evaluation based on DetectionOutputLayer and * ground truth bounding box labels. * * Intended for use with MultiBox detection method. * * NOTE: does not implement Backwards operation. */ template <typename Dtype> class FaceAttriEvaluateLayer : public Layer<Dtype> { public: explicit FaceAttriEvaluateLayer(const LayerParameter& param) : Layer<Dtype>(param) {} virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual inline const char* type() const { return "FaceEvaluate"; } virtual inline int ExactBottomBlobs() const { return 2; } virtual inline int ExactNumTopBlobs() const { return 1; } protected: virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); /// @brief Not implemented virtual void Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) { NOT_IMPLEMENTED; } int num_gender_; int num_glasses_; int num_headpose_; int num_facepoints_; FaceEvaluateParameter_FaceType facetype_; }; } // namespace caffe #endif // CAFFE_DETECTION_EVALUATE_LAYER_HPP_ ======================= File: include/caffe/layers/pairfaceEvaluate.hpp ======================= <gh_stars>10-100 #ifndef CAFFE_PAIRFACEVALUATE_LOSS_LAYER_HPP_ #define CAFFE_PAIRFACEVALUATE_LOSS_LAYER_HPP_ #include <vector> #include "caffe/blob.hpp" #include "caffe/layer.hpp" #include "caffe/proto/caffe.pb.h" namespace caffe { template <typename Dtype> class pairfaceEvaluateLayer : public Layer<Dtype> { public: explicit pairfaceEvaluateLayer(const LayerParameter& param) : Layer<Dtype>(param) {} virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual inline int ExactNumBottomBlobs() const { return 2; } virtual inline const char* type() const { return "pairfaceEvaluate"; } virtual inline int ExactNumTopBlobs() const { return 1; } protected: virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom){ NOT_IMPLEMENTED; } Blob<Dtype> diff_; // cached for backward pass Blob<Dtype> diff_sq_; // cached for backward pass Blob<Dtype> dist_left_; Blob<Dtype> dist_right_; Dtype eucildeanThresold_; Dtype cosThresold_; metricDistanceParameter_MetricType type_; }; } // namespace caffe #endif // CAFFE_CONTRASTIVE_LOSS_LAYER_HPP_ ======================= File: src/caffe/layers/Yolov3Loss.cpp ======================= #include <algorithm> #include <map> #include <utility> #include <vector> #include "caffe/layers/Yolov3Loss.hpp" #include "caffe/util/math_functions.hpp" namespace caffe { template <typename Dtype> void Yolov3LossLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { LossLayer<Dtype>::LayerSetUp(bottom, top); if (this->layer_param_.propagate_down_size() == 0) { this->layer_param_.add_propagate_down(true); this->layer_param_.add_propagate_down(false); } const CenterObjectLossParameter& center_object_loss_param = this->layer_param_.center_object_loss_param(); // bias_mask_ if(center_object_loss_param.has_bias_num()){ for(int i = 0; i < center_object_loss_param.bias_scale_size() / 2; i++){ bias_scale_.push_back(std::pair<Dtype, Dtype>(center_object_loss_param.bias_scale(i * 2), center_object_loss_param.bias_scale(i * 2 + 1))); } for(int i = 0; i < center_object_loss_param.bias_mask_size(); i++){ bias_mask_.push_back(center_object_loss_param.bias_mask(i)); } } net_height_ = center_object_loss_param.net_height(); net_width_ = center_object_loss_param.net_width(); bias_num_ = center_object_loss_param.bias_num(); ignore_thresh_ = center_object_loss_param.ignore_thresh(); CHECK_EQ(bias_num_, bias_scale_.size()); // anchor size num_classes_ = center_object_loss_param.num_class(); CHECK_GE(num_classes_, 1) << "num_classes should not be less than 1."; CHECK_EQ((4 + 1 + num_classes_) * bias_mask_.size(), bottom[0]->channels()) << "num_classes must be equal to prediction classes"; if (!this->layer_param_.loss_param().has_normalization() && this->layer_param_.loss_param().has_normalize()) { normalization_ = this->layer_param_.loss_param().normalize()? LossParameter_NormalizationMode_VALID : LossParameter_NormalizationMode_BATCH_SIZE; } else { normalization_ = this->layer_param_.loss_param().normalization(); } iterations_ = 0; } template <typename Dtype> void Yolov3LossLayer<Dtype>::Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { LossLayer<Dtype>::Reshape(bottom, top); } template <typename Dtype> void Yolov3LossLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { // gt_boxes const Dtype* gt_data = bottom[1]->cpu_data(); num_gt_ = bottom[1]->height(); bool use_difficult_gt_ = true; Dtype background_label_id_ = -1; num_ = bottom[0]->num(); all_gt_bboxes.clear(); GetYoloGroundTruth(gt_data, num_gt_, background_label_id_, use_difficult_gt_, false, &all_gt_bboxes, num_); num_groundtruth_ = 0; for(int i = 0; i < all_gt_bboxes.size(); i++){ vector<std::pair<NormalizedBBox, AnnoFaceLandmarks> > gt_boxes = all_gt_bboxes[i]; num_groundtruth_ += gt_boxes.size(); } // prediction data Dtype* channel_pred_data = bottom[0]->mutable_cpu_data(); const int output_height = bottom[0]->height(); const int output_width = bottom[0]->width(); const int num_channels = bottom[0]->channels(); Dtype * bottom_diff = bottom[0]->mutable_cpu_diff(); caffe_set(bottom[0]->count(), Dtype(0), bottom_diff); if (num_groundtruth_ >= 1) { EncodeYoloObject(num_, num_channels, num_classes_, output_width, output_height, net_width_, net_height_, channel_pred_data, all_gt_bboxes, bias_mask_, bias_scale_, bottom_diff, ignore_thresh_, &trainScore); const Dtype * diff = bottom[0]->cpu_diff(); Dtype sum_squre = Dtype(0.); for(int j = 0; j < bottom[0]->count(); j++){ sum_squre += diff[j] * diff[j]; } if(trainScore.count > 0) top[0]->mutable_cpu_data()[0] = sum_squre / trainScore.count; else top[0]->mutable_cpu_data()[0] = sum_squre / num_; } else { top[0]->mutable_cpu_data()[0] = 0; } #if 1 if(iterations_ % 100 == 0){ int dimScale = output_height * output_width; LOG(INFO); LOG(INFO)<<"all num_gt boxes: "<<num_gt_<<", Region "<<output_width<<": total loss: "<<top[0]->mutable_cpu_data()[0]<<", num_groundtruth: "<<num_groundtruth_<<" Avg IOU: " <<trainScore.avg_iou/trainScore.count<<", Class: "<<trainScore.avg_cat/trainScore.class_count <<", Obj: "<<trainScore.avg_obj/trainScore.count<<", No obj: "<<trainScore.avg_anyobj/(dimScale*bias_mask_.size()*num_) <<",.5R: "<<trainScore.recall/trainScore.count<<",.75R: "<<trainScore.recall75/trainScore.count <<", count: "<<trainScore.count; } iterations_++; #endif } template <typename Dtype> void Yolov3LossLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) { if (propagate_down[1]) { LOG(FATAL) << this->type() << " Layer cannot backpropagate to label inputs."; } if (propagate_down[0]) { Dtype loss_weight = Dtype(0.); if(trainScore.count) loss_weight = top[0]->cpu_diff()[0] / trainScore.count; else loss_weight = top[0]->cpu_diff()[0] / num_; const int output_height = bottom[0]->height(); const int output_width = bottom[0]->width(); const int num_channels = bottom[0]->channels(); Dtype* bottom_diff = bottom[0]->mutable_cpu_diff(); const Dtype* bottom_data = bottom[0]->cpu_data(); num_ = bottom[0]->num(); int channel_per_box = 4 + 1 + num_classes_; int mask_size_ = bias_mask_.size(); int dimScale = output_height * output_width; CHECK_EQ(channel_per_box * mask_size_, num_channels); for(int j = 0; j < num_; j++){ for(int mm = 0; mm < mask_size_; mm++){ for(int cc = 0; cc < channel_per_box; cc++){ int channal_index = j * num_channels * dimScale + (mm * channel_per_box + cc) * dimScale; if(cc!= 2 && cc!= 3){ for(int s = 0; s < dimScale; s++){ int index = channal_index + s; bottom_diff[index] = bottom_diff[index] * logistic_gradient(bottom_data[index]); } } } } } caffe_scal(bottom[0]->count(), loss_weight, bottom[0]->mutable_cpu_diff()); } } INSTANTIATE_CLASS(Yolov3LossLayer); REGISTER_LAYER_CLASS(Yolov3Loss); } // namespace caffe ======================= File: src/caffe/layers/pairfaceEvaluate.cpp ======================= #include <algorithm> #include <vector> #include "caffe/layers/pairfaceEvaluate.hpp" #include "caffe/util/math_functions.hpp" namespace caffe { template <typename Dtype> void pairfaceEvaluateLayer<Dtype>::LayerSetUp( const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { Layer<Dtype>::LayerSetUp(bottom, top); CHECK_EQ(bottom[0]->channels(), bottom[1]->channels()); CHECK_EQ(bottom[0]->height(), 1); CHECK_EQ(bottom[0]->width(), 1); CHECK_EQ(bottom[1]->height(), 1); CHECK_EQ(bottom[1]->width(), 1); diff_.Reshape(bottom[0]->num(), bottom[0]->channels(), 1, 1); diff_sq_.Reshape(bottom[0]->num(), bottom[0]->channels(), 1, 1); dist_left_.Reshape(bottom[0]->num(), bottom[0]->channels(), 1, 1); dist_right_.Reshape(bottom[0]->num(), bottom[0]->channels(), 1, 1); top[0]->Reshape(bottom[0]->num(), 1, 1, 1); eucildeanThresold_ = this->layer_param_.metric_param().eucil_threshold(); cosThresold_ = this->layer_param_.metric_param().cos_threshold(); type_ = this->layer_param_.metric_param().metric(); } template <typename Dtype> void pairfaceEvaluateLayer<Dtype>::Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { top[0]->Reshape(bottom[0]->num(), 1, 1, 1); } template <typename Dtype> void pairfaceEvaluateLayer<Dtype>::Forward_cpu( const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { int count = bottom[0]->count(); const int channels = bottom[0]->channels(); if(type_==metricDistanceParameter_MetricType_EUCILDISTANCE){ caffe_sub( count, bottom[0]->cpu_data(), // a bottom[1]->cpu_data(), // b diff_.mutable_cpu_data()); // a_i-b_i caffe_sqr<Dtype>(count, diff_.cpu_data(), diff_sq_.mutable_cpu_data()); Dtype squre_sum = Dtype(0.0); for (int i = 0; i < bottom[0]->num(); ++i) { squre_sum = caffe_cpu_asum<Dtype>(channels, diff_sq_.cpu_data() + (i*channels)); if(squre_sum >= eucildeanThresold_) top[0]->mutable_cpu_data()[i] = Dtype(0.0); else top[0]->mutable_cpu_data()[i] = Dtype(1.0); } }else if(type_==metricDistanceParameter_MetricType_COSDISTANCE){ caffe_mul(count, bottom[0]->cpu_data(), bottom[1]->cpu_data(), diff_.mutable_cpu_data()); caffe_sqr<Dtype>(count, bottom[0]->cpu_data(), dist_left_.mutable_cpu_data()); caffe_sqr<Dtype>(count, bottom[1]->cpu_data(), dist_right_.mutable_cpu_data()); Dtype top_sum = Dtype(0.0); Dtype bottom_left = Dtype(0.0); Dtype bottom_right = Dtype(0.0); Dtype cosvalue = Dtype(0.0); for (int i = 0; i < bottom[0]->num(); ++i) { top_sum = caffe_cpu_asum<Dtype>(channels, diff_.cpu_data() + (i*channels)); bottom_left = caffe_cpu_asum<Dtype>(channels, dist_left_.cpu_data() + (i*channels)); bottom_right = caffe_cpu_asum<Dtype>(channels, dist_right_.cpu_data() + (i*channels)); cosvalue = Dtype(top_sum *(std::pow(bottom_left, -0.5) * std::pow(bottom_right, -0.5) + 0.00000001)); if(cosvalue >= cosThresold_) top[0]->mutable_cpu_data()[i] = Dtype(1.0); else top[0]->mutable_cpu_data()[i] = Dtype(0.0); } } } #ifdef CPU_ONLY STUB_GPU(pairfaceEvaluateLayer); #endif INSTANTIATE_CLASS(pairfaceEvaluateLayer); REGISTER_LAYER_CLASS(pairfaceEvaluate); } // namespace caffe ======================= File: src/caffe/util/center_util.cpp ======================= <gh_stars>10-100 #include <algorithm> #include <csignal> #include <ctime> #include <functional> #include <map> #include <set> #include <string> #include <utility> #include <vector> #include "boost/iterator/counting_iterator.hpp" #include "caffe/util/bbox_util.hpp" #include "caffe/util/center_util.hpp" namespace caffe { float Yoloverlap(float x1, float w1, float x2, float w2) { float l1 = x1 - w1/2; float l2 = x2 - w2/2; float left = l1 > l2? l1 : l2; float r1 = x1 + w1/2; float r2 = x2 + w2/2; float right = r1 < r2? r1 : r2; return right - left; } float boxIntersection(NormalizedBBox a, NormalizedBBox b) { float a_center_x = (float)(a.xmin() + a.xmax()) / 2; float a_center_y = (float)(a.ymin() + a.ymax()) / 2; float a_w = (float)(a.xmax() - a.xmin()); float a_h = (float)(a.ymax() - a.ymin()); float b_center_x = (float)(b.xmin() + b.xmax()) / 2; float b_center_y = (float)(b.ymin() + b.ymax()) / 2; float b_w = (float)(b.xmax() - b.xmin()); float b_h = (float)(b.ymax() - b.ymin()); float w = Yoloverlap(a_center_x, a_w, b_center_x, b_w); float h = Yoloverlap(a_center_y, a_h, b_center_y, b_h); if(w < 0 || h < 0) return 0; float area = w*h; return area; } float boxUnion(NormalizedBBox a, NormalizedBBox b) { float i = boxIntersection(a, b); float a_w = (float)(a.xmax() - a.xmin()); float a_h = (float)(a.ymax() - a.ymin()); float b_w = (float)(b.xmax() - b.xmin()); float b_h = (float)(b.ymax() - b.ymin()); float u = a_h*a_w + b_w*b_h - i; return u; } float YoloBBoxIou(NormalizedBBox a, NormalizedBBox b){ return (float)boxIntersection(a, b)/boxUnion(a, b); } int int_index(std::vector<int>a, int val, int n) { int i; for(i = 0; i < n; ++i){ if(a[i] == val) return i; } return -1; } template <typename Dtype> Dtype CenterSigmoid(Dtype x){ return 1. / (1. + exp(-x)); } template double CenterSigmoid(double x); template float CenterSigmoid(float x); template <typename Dtype> Dtype SingleSoftmaxLoss(Dtype bg_score, Dtype face_score, Dtype lable_value){ Dtype Probability_value = Dtype(0.f); if(lable_value == 1.){ Probability_value = face_score; }else{ Probability_value = bg_score; } Dtype loss = (-1) * log(std::max(Probability_value, Dtype(FLT_MIN))); return loss; } template float SingleSoftmaxLoss(float bg_score, float face_score, float lable_value); template double SingleSoftmaxLoss(double bg_score, double face_score, double lable_value); template <typename T> bool SortScorePairDescendCenter(const pair<T, float>& pair1, const pair<T, float>& pair2) { return pair1.second > pair2.second; } template <typename Dtype> Dtype smoothL1_Loss(Dtype x, Dtype* x_diff){ Dtype loss = Dtype(0.); Dtype fabs_x_value = std::fabs(x); if(fabs_x_value < 1){ loss = 0.5 * x * x; *x_diff = x; }else{ loss = fabs_x_value - 0.5; *x_diff = (Dtype(0) < x) - (x < Dtype(0)); } return loss; } template float smoothL1_Loss(float x, float* x_diff); template double smoothL1_Loss(double x, double* x_diff); template <typename Dtype> Dtype L2_Loss(Dtype x, Dtype* x_diff){ Dtype loss = Dtype(0.); loss = x * x; *x_diff =2 * x; return loss; } template float L2_Loss(float x, float* x_diff); template double L2_Loss(double x, double* x_diff); template <typename Dtype> Dtype Object_L2_Loss(Dtype x, Dtype* x_diff){ Dtype loss = Dtype(0.); loss =0.5 * x * x; *x_diff =x; return loss; } template float Object_L2_Loss(float x, float* x_diff); template double Object_L2_Loss(double x, double* x_diff); template<typename Dtype> Dtype gaussian_radius(const Dtype heatmap_height, const Dtype heatmap_width, const Dtype min_overlap){ Dtype a1 = Dtype(1.0); Dtype b1 = (heatmap_width + heatmap_height); Dtype c1 = Dtype( heatmap_width * heatmap_height * (1 - min_overlap) / (1 + min_overlap)); Dtype sq1 = std::sqrt(b1 * b1 - 4 * a1 * c1); Dtype r1 = Dtype((b1 + sq1) / 2); Dtype a2 = Dtype(4.0); Dtype b2 = 2 * (heatmap_height + heatmap_width); Dtype c2 = (1 - min_overlap) * heatmap_width * heatmap_height; Dtype sq2 = std::sqrt(b2 * b2 - 4 * a2 * c2); Dtype r2 = Dtype((b2 + sq2) / 2); Dtype a3 = Dtype(4 * min_overlap); Dtype b3 = -2 * min_overlap * (heatmap_height + heatmap_width); Dtype c3 = (min_overlap - 1) * heatmap_width * heatmap_height; Dtype sq3 = std::sqrt(b3 * b3 - 4 * a3 * c3); Dtype r3 = Dtype((b3 + sq3) / 2); return std::min(std::min(r1, r2), r3); } template float gaussian_radius(const float heatmap_width, const float heatmap_height, const float min_overlap); template double gaussian_radius(const double heatmap_width, const double heatmap_height, const double min_overlap); template<typename Dtype> std::vector<Dtype> gaussian2D(const int height, const int width, Dtype sigma){ int half_width = (width - 1) / 2; int half_height = (height - 1) / 2; std::vector<Dtype> heatmap((width *height), Dtype(0.)); for(int i = 0; i < height; i++){ int x = i - half_height; for(int j = 0; j < width; j++){ int y = j - half_width; heatmap[i * width + j] = std::exp(float(-(x*x + y*y) / (2* sigma * sigma))); if(heatmap[i * width + j] < 0.00000000005) heatmap[i * width + j] = Dtype(0.); } } return heatmap; } template std::vector<float> gaussian2D(const int height, const int width, float sigma); template std::vector<double> gaussian2D(const int height, const int width, double sigma); template<typename Dtype> void draw_umich_gaussian(std::vector<Dtype>& heatmap, int center_x, int center_y, float radius , const int height, const int width){ float diameter = 2 * radius + 1; std::vector<Dtype> gaussian = gaussian2D(int(diameter), int(diameter), Dtype(diameter / 6)); int left = std::min(int(center_x), int(radius)), right = std::min(int(width - center_x), int(radius) + 1); int top = std::min(int(center_y), int(radius)), bottom = std::min(int(height - center_y), int(radius) + 1); if((left + right) > 0 && (top + bottom) > 0){ for(int row = 0; row < (top + bottom); row++){ for(int col = 0; col < (right + left); col++){ int heatmap_index = (int(center_y) -top + row) * width + int(center_x) -left + col; int gaussian_index = (int(radius) - top + row) * int(diameter) + int(radius) - left + col; heatmap[heatmap_index] = heatmap[heatmap_index] >= gaussian[gaussian_index] ? heatmap[heatmap_index]: gaussian[gaussian_index]; } } } } template void draw_umich_gaussian(std::vector<float>& heatmap, int center_x, int center_y, float radius, const int height, const int width); template void draw_umich_gaussian(std::vector<double>& heatmap, int center_x, int center_y, float radius, const int height, const int width); template <typename Dtype> void transferCVMatToBlobData(std::vector<Dtype> heatmap, Dtype* buffer_heat){ for(unsigned ii = 0; ii < heatmap.size(); ii++){ buffer_heat[ii] = buffer_heat[ii] > heatmap[ii]? buffer_heat[ii] : heatmap[ii]; } } template void transferCVMatToBlobData(std::vector<float> heatmap, float* buffer_heat); template void transferCVMatToBlobData(std::vector<double> heatmap, double* buffer_heat); template <typename Dtype> Dtype FocalLossSigmoid(Dtype* label_data, Dtype * pred_data, int dimScale, Dtype *bottom_diff){ Dtype alpha_ = 2.0f; Dtype gamma_ = 4.0f; Dtype loss = Dtype(0.); for(int i = 0; i < dimScale; i++){ if(label_data[i] == 0.5){ // gt_boxes之外的负样本 loss -= alpha_ * std::pow(pred_data[i], gamma_) * std::log(std::max(1 - pred_data[i], Dtype(FLT_MIN))); Dtype diff_elem_ = alpha_ * std::pow(pred_data[i], gamma_); Dtype diff_next_ = pred_data[i] - gamma_ * (1 - pred_data[i]) * std::log(std::max(1 - pred_data[i], Dtype(FLT_MIN))); bottom_diff[i] = diff_elem_ * diff_next_; }else if(label_data[i] == 1){ //gt_boxes包围的都认为是正样本 loss -= alpha_ * std::pow(1 - pred_data[i], gamma_) * std::log(std::max(pred_data[i], Dtype(FLT_MIN))); Dtype diff_elem_ = alpha_ * std::pow(1 - pred_data[i], gamma_); Dtype diff_next_ = gamma_ * pred_data[i] * std::log(std::max(pred_data[i], Dtype(FLT_MIN))) + pred_data[i] - 1; bottom_diff[i] = diff_elem_ * diff_next_; } } return loss; } template float FocalLossSigmoid(float* label_data, float *pred_data, int dimScale, float *bottom_diff); template double FocalLossSigmoid(double* label_data, double *pred_data, int dimScale, double *bottom_diff); // hard sampling mine postive : negative 1: 5 sigmoid // 按理来说是需要重新统计负样本的编号,以及获取到他的数值 // label_data : K x H x W // pred_data : K x H x W x N template <typename Dtype> void SelectHardSampleSigmoid(Dtype *label_data, Dtype *pred_data, const int negative_ratio, const int num_postive, const int output_height, const int output_width, const int num_channels){ CHECK_EQ(num_channels, 4 + 2) << "x, y, width, height + objectness + label class containing face"; std::vector<std::pair<int, float> > loss_value_indices; loss_value_indices.clear(); Dtype alpha_ = 0.25; Dtype gamma_ = 2.f; for(int h = 0; h < output_height; h ++){ for(int w = 0; w < output_width; w ++){ if(label_data[h * output_width +w] == 0.){ int bg_index = h * output_width + w; // Focal loss when sample belong to background Dtype loss = (-1) * alpha_ * std::pow(pred_data[bg_index], gamma_) * std::log(std::max(1 - pred_data[bg_index], Dtype(FLT_MIN))); loss_value_indices.push_back(std::make_pair(bg_index, loss)); } } } std::sort(loss_value_indices.begin(), loss_value_indices.end(), SortScorePairDescendCenter<int>); int num_negative = std::min(int(loss_value_indices.size()), num_postive * negative_ratio); for(int ii = 0; ii < num_negative; ii++){ int h = loss_value_indices[ii].first / output_width; int w = loss_value_indices[ii].first % output_width; label_data[h * output_width + w] = 0.5; } } template void SelectHardSampleSigmoid(float *label_data, float *pred_data, const int negative_ratio, const int num_postive, const int output_height, const int output_width, const int num_channels); template void SelectHardSampleSigmoid(double *label_data, double *pred_data, const int negative_ratio, const int num_postive, const int output_height, const int output_width, const int num_channels); template<typename Dtype> Dtype FocalLossSoftmax(Dtype* label_data, Dtype* pred_data, const int batch_size, const int output_height, const int output_width, Dtype *bottom_diff, const int num_channels, bool has_lm){ Dtype loss = Dtype(0.f); int dimScale = output_height * output_width; for(int b = 0; b < batch_size; b++){ for(int h = 0; h < output_height; h++){ for(int w = 0; w < output_width; w++){ Dtype label_value = Dtype(label_data[b * dimScale + h * output_width + w]); if(label_value < 0.f){ continue; }else{ int label_idx = 0; if(label_value == 0.5) label_idx = 0; else if(label_value == 1.) label_idx = 1; else{ LOG(FATAL)<<"no valid label value"; } int bg_index = b * num_channels * dimScale + 4 * dimScale + h * output_width + w; if(has_lm){ bg_index = b * num_channels * dimScale + 14 * dimScale + h * output_width + w; } Dtype p1 = pred_data[bg_index + label_idx * dimScale]; Dtype p0 = 1 - p1; #define USE_FOCAL_LOSS true #if USE_FOCAL_LOSS float alpha = 0.25f; float gamma = 2.f; Dtype log_value = Dtype(std::log(std::max(p1, Dtype(FLT_MIN)))); loss -= alpha * std::pow(p0, gamma) * log_value; bottom_diff[bg_index + label_idx * dimScale] = alpha * std::pow(p0, gamma) * (gamma * log_value * p1 - p0); bottom_diff[bg_index + (1 - label_idx) * dimScale] = alpha * std::pow(p0, gamma) * (p0 - gamma * log_value * p1 ); #else float transfer = 0.025f; float alpha = 0.25f; float gamma = 2.f; Dtype assist_value = Dtype((p0 + transfer) / (p1 + transfer)); Dtype p0_temp = Dtype(1. / (p0 + transfer)); Dtype p1_temp = Dtype(1. / (p1 + transfer)); Dtype log_value = Dtype(std::log(std::max(p1, Dtype(FLT_MIN)))); loss -= alpha * std::pow(assist_value * p0, gamma) * log_value; bottom_diff[bg_index + label_idx * dimScale] = alpha * std::pow(assist_value * p0, gamma) * (p0 - p1 * gamma * log_value * (p0 * p1_temp + (2 * p0 + transfer) * p0_temp)) * (-1); bottom_diff[bg_index + (1 - label_idx) * dimScale] = alpha * std::pow(assist_value * p0, gamma) * (p0 - p1 * gamma * log_value * (p0 * p1_temp + (2 * p0 + transfer) * p0_temp)); #endif } } } } return loss; } template float FocalLossSoftmax(float* label_data, float* pred_data, const int batch_size, const int output_height, const int output_width, float *bottom_diff, const int num_channels, bool has_lm); template double FocalLossSoftmax(double* label_data, double* pred_data, const int batch_size, const int output_height, const int output_width, double *bottom_diff, const int num_channels, bool has_lm); // label_data shape N : 1 // pred_data shape N : k (object classes) // dimScale is the number of what?? N * K?? template <typename Dtype> Dtype SoftmaxWithLoss(Dtype* label_data, Dtype* pred_data, const int batch_size, const int output_height, const int output_width, Dtype *bottom_diff, const int num_channels, bool has_lm){ Dtype loss = Dtype(0.f); int dimScale = output_height * output_width; for(int b = 0; b < batch_size; b++){ for(int h = 0; h < output_height; h++){ for(int w = 0; w < output_width; w++){ Dtype label_value = Dtype(label_data[b * dimScale + h * output_width + w]); if(label_value < 0.f){ continue; }else{ int label_idx = 0; if(label_value == 0.5) label_idx = 0; else if(label_value == 1.) label_idx = 1; else{ LOG(FATAL)<<"no valid label value"; } int bg_index = b * num_channels * dimScale + 4 * dimScale + h * output_width + w; if(has_lm){ bg_index = b * num_channels * dimScale + 14 * dimScale + h * output_width + w; } Dtype Probability_value = pred_data[bg_index + label_idx * dimScale]; Dtype pred_another_data_value = pred_data[bg_index + (1 - label_idx) * dimScale]; loss -= log(std::max(Probability_value, Dtype(FLT_MIN))); bottom_diff[bg_index + label_idx * dimScale] = Probability_value - 1; bottom_diff[bg_index + (1 - label_idx) * dimScale] = pred_another_data_value; } } } } return loss; } template float SoftmaxWithLoss(float* label_data, float* pred_data, const int batch_size, const int output_height, const int output_width, float *bottom_diff, const int num_channels, bool has_lm); template double SoftmaxWithLoss(double* label_data, double* pred_data, const int batch_size, const int output_height, const int output_width, double *bottom_diff, const int num_channels, bool has_lm); template <typename Dtype> void SoftmaxCenterGrid(Dtype * pred_data, const int batch_size, const int label_channel, const int num_channels, const int outheight, const int outwidth, bool has_lm){ int dimScale = outheight * outwidth; for(int b = 0; b < batch_size; b ++){ for(int h = 0; h < outheight; h++){ for(int w = 0; w < outwidth; w++){ int bg_index = b * num_channels * dimScale + 4 * dimScale + h * outwidth + w; if(has_lm) { bg_index = b * num_channels * dimScale + 14 * dimScale + h * outwidth + w; } Dtype MaxVaule = pred_data[bg_index + 0 * dimScale]; Dtype sumValue = Dtype(0.f); // 求出每组的最大值 for(int c = 0; c< label_channel; c++){ MaxVaule = std::max(MaxVaule, pred_data[bg_index + c * dimScale]); } // 每个样本组减去最大值, 计算exp,求和 for(int c = 0; c< label_channel; c++){ pred_data[bg_index + c * dimScale] = std::exp(pred_data[bg_index + c * dimScale] - MaxVaule); sumValue += pred_data[bg_index + c * dimScale]; } // 计算softMax for(int c = 0; c< label_channel; c++){ pred_data[bg_index + c * dimScale] = Dtype(pred_data[bg_index + c * dimScale] / sumValue); } } } } } template void SoftmaxCenterGrid(float * pred_data, const int batch_size, const int label_channel, const int num_channels, const int outheight, const int outwidth, bool has_lm); template void SoftmaxCenterGrid(double * pred_data, const int batch_size, const int label_channel, const int num_channels, const int outheight, const int outwidth, bool has_lm); // hard sampling mine postive : negative 1: 5 softmax // 按理来说是需要重新统计负样本的编号,以及获取到他的数值 // label_data : K x H x W template <typename Dtype> void SelectHardSampleSoftMax(Dtype *label_data, std::vector<Dtype> batch_sample_loss, const int negative_ratio, std::vector<int> postive, const int output_height, const int output_width, const int num_channels, const int batch_size, bool has_lm){ if(has_lm){ CHECK_EQ(num_channels, 14 + 2) << "x, y, width, height, landmarks + label classes containing background + face"; }else{ CHECK_EQ(num_channels, 4 + 2) << "x, y, width, height + label classes containing background + face"; } CHECK_EQ(postive.size(), batch_size); int num_postive = 0; int dimScale = output_height * output_width; std::vector<std::pair<int, float> > loss_value_indices; #define USE_Full_Batch false #if USE_Full_Batch loss_value_indices.clear(); for(int b = 0; b < batch_size; b ++){ num_postive += postive[b]; for(int h = 0; h < output_height; h ++){ for(int w = 0; w < output_width; w ++){ int select_index = b * dimScale + h * output_width + w; if(label_data[select_index] == -1.){ loss_value_indices.push_back(std::make_pair(select_index, batch_sample_loss[select_index])); } } } } std::sort(loss_value_indices.begin(), loss_value_indices.end(), SortScorePairDescendCenter<int>); int num_negative = std::min(int(loss_value_indices.size()), num_postive * negative_ratio); for(int ii = 0; ii < num_negative; ii++){ int select_index = loss_value_indices[ii].first; label_data[select_index] = 0.5; } #else for(int b = 0; b < batch_size; b ++){ num_postive = postive[b]; loss_value_indices.clear(); for(int h = 0; h < output_height; h ++){ for(int w = 0; w < output_width; w ++){ int select_index = b * dimScale + h * output_width + w; if(label_data[select_index] == -1.){ loss_value_indices.push_back(std::make_pair(select_index, batch_sample_loss[select_index])); } } } std::sort(loss_value_indices.begin(), loss_value_indices.end(), SortScorePairDescendCenter<int>); int num_negative = std::min(int(loss_value_indices.size()), num_postive * negative_ratio); for(int ii = 0; ii < num_negative; ii++){ int select_index = loss_value_indices[ii].first; label_data[select_index] = 0.5; } } #endif } template void SelectHardSampleSoftMax(float *label_data, std::vector<float> batch_sample_loss, const int negative_ratio, std::vector<int> postive, const int output_height, const int output_width, const int num_channels, const int batch_size, bool has_lm); template void SelectHardSampleSoftMax(double *label_data, std::vector<double> batch_sample_loss, const int negative_ratio, std::vector<int> postive, const int output_height, const int output_width, const int num_channels, const int batch_size, bool has_lm); template <typename Dtype> Dtype GIoULoss(NormalizedBBox predict_box, NormalizedBBox gt_bbox, Dtype* diff_x1, Dtype* diff_x2, Dtype* diff_y1, Dtype* diff_y2){ Dtype p_xmin = std::min(predict_box.xmin(), predict_box.xmax()); Dtype p_xmax = std::max(predict_box.xmin(), predict_box.xmax()); Dtype p_ymin = std::min(predict_box.ymin(), predict_box.ymax()); Dtype p_ymax = std::max(predict_box.ymin(), predict_box.ymax()); Dtype p_area = (p_xmax - p_xmin) *(p_ymax - p_ymin); Dtype gt_xmin = gt_bbox.xmin(); Dtype gt_xmax = gt_bbox.xmax(); Dtype gt_ymin = gt_bbox.ymin(); Dtype gt_ymax = gt_bbox.ymax(); Dtype gt_area = (gt_xmax - gt_xmin) *(gt_ymax - gt_ymin); Dtype iou_xmin = std::max(p_xmin, gt_xmin), iou_xmax = std::min(p_xmax, gt_xmax); Dtype iou_ymin = std::max(p_ymin, gt_ymin), iou_ymax = std::min(p_ymax, gt_ymax); Dtype iou_height = iou_ymax >= iou_ymin? (iou_ymax - iou_ymin) : 0; Dtype iou_width = iou_xmax >= iou_xmin? (iou_xmax - iou_xmin) : 0; Dtype iou_area = iou_height * iou_width; Dtype Union = p_area + gt_area - iou_area + 1e-7; Dtype Iou = Dtype(iou_area / Union); Dtype c_xmin = std::min(p_xmin, gt_xmin), c_xmax = std::max(p_xmax, gt_xmax); Dtype c_ymin = std::min(p_ymin, gt_ymin), c_ymax = std::max(p_ymax, gt_ymax); Dtype C = (c_xmax - c_xmin) * (c_ymax - c_ymin) + 1e-7; Dtype GIou = Iou - Dtype((C - Union) / C); // cal diff float IoU = I / U; // derivative of p_aera regard xmin,ymin,xmax,ymax Dtype dp_aera_wrt_xmin = -1 * (p_ymax - p_ymin); Dtype dp_aera_wrt_xmax = (p_ymax - p_ymin); Dtype dp_aera_wrt_ymin = -1 * (p_xmax - p_xmin); Dtype dp_aera_wrt_ymax = (p_xmax - p_xmin); // gradient of I min/max in IoU calc (prediction) Dtype dI_wrt_xmin = p_xmin > gt_xmin? (-1 * iou_height) : 0; Dtype dI_wrt_xmax = p_xmax < gt_xmax? iou_height : 0; Dtype dI_wrt_ymin = p_ymin > gt_ymin? (-1 * iou_width) : 0; Dtype dI_wrt_ymax = p_ymax < gt_ymax? iou_width : 0; // derivative of U with regard to xmin, ymin, xmax, ymax Dtype dU_wrt_ymin = dp_aera_wrt_ymin - dI_wrt_ymin; Dtype dU_wrt_ymax = dp_aera_wrt_ymax - dI_wrt_ymax; Dtype dU_wrt_xmin = dp_aera_wrt_xmin - dI_wrt_xmin; Dtype dU_wrt_xmax = dp_aera_wrt_xmax - dI_wrt_xmax; // gradient of C min/max in IoU calc (prediction) Dtype dC_wrt_ymin = p_ymin < gt_ymin? (-1 * (c_xmax - c_xmin)) : 0; Dtype dC_wrt_ymax = p_ymax > gt_ymax? (c_xmax - c_xmin) : 0; Dtype dC_wrt_xmin = p_xmin < gt_xmin? (-1 * (c_ymax - c_ymin)) : 0; Dtype dC_wrt_xmax = p_xmax > gt_ymax? (c_ymax - c_ymin) : 0; Dtype dp_ymin = Dtype(0.); Dtype dp_ymax = Dtype(0.); Dtype dp_xmin = Dtype(0.); Dtype dp_xmax = Dtype(0.); if (Union > 0) { // gradient of IOU regard to I / U dp_ymin = ((Union * dI_wrt_ymin) - (iou_area * dU_wrt_ymin)) / (Union * Union); dp_ymax = ((Union * dI_wrt_ymax) - (iou_area * dU_wrt_ymax)) / (Union * Union); dp_xmin = ((Union * dI_wrt_xmin) - (iou_area * dU_wrt_xmin)) / (Union * Union); dp_xmax = ((Union * dI_wrt_xmax) - (iou_area * dU_wrt_xmax)) / (Union * Union); } if (C > 0) { // gradient of GIou regard Iou, C dp_ymin += ((C * dU_wrt_ymin) - (Union * dC_wrt_ymin)) / (C * C); dp_ymax += ((C * dU_wrt_ymax) - (Union * dC_wrt_ymax)) / (C * C); dp_xmin += ((C * dU_wrt_xmin) - (Union * dC_wrt_xmin)) / (C * C); dp_xmax += ((C * dU_wrt_xmax) - (Union * dC_wrt_xmax)) / (C * C); } *diff_y1 = (predict_box.ymin() < predict_box.ymax())? dp_ymin : dp_ymax; *diff_y2 = (predict_box.ymin() < predict_box.ymax())? dp_ymax : dp_ymin; *diff_x1 = (predict_box.xmin() < predict_box.xmax())? dp_xmin : dp_xmax; *diff_x2 = (predict_box.xmin() < predict_box.xmax())? dp_xmax : dp_xmin; return (1 - GIou); } template float GIoULoss(NormalizedBBox predict_box, NormalizedBBox gt_bbox, float* diff_x1, float* diff_x2, float* diff_y1, float* diff_y2); template double GIoULoss(NormalizedBBox predict_box, NormalizedBBox gt_bbox, double* diff_x1, double* diff_x2, double* diff_y1, double* diff_y2); void correct_detector_bbox(int net_input_width, int net_input_height, int relative, std::map<int, std::vector<CenterNetInfo > > results, std::map<int, std::pair<int, int > > image_scale){ int i = 0, new_w = 0, new_h = 0; std::map<int, std::vector<CenterNetInfo > >::iterator iter; for(iter =results.begin(); iter!= results.end(); iter++){ int image_id = iter->first; std::pair<int, int> image_size = image_scale.find(image_id)->second; int image_width = image_size.first; int image_height = image_size.second; std::vector<CenterNetInfo > det_bboxes = iter->second; if(((float) net_input_width / image_width) < ((float) net_input_height / image_height)){ new_w = net_input_width; new_h = (image_height * net_input_width) / image_width; }else{ new_w = (image_width * net_input_height) / image_height; new_h = net_input_height; } for(i = 0; i < det_bboxes.size(); i++){ CenterNetInfo det_box = det_bboxes[i]; float center_x = float((det_box.xmin() + det_box.xmax()) / 2.); float center_y = float((det_box.ymin() + det_box.ymax()) / 2.); float box_width = det_box.xmax() - det_box.xmin(); float box_height = det_box.ymax() - det_box.ymin(); center_x = (center_x - (float)(net_input_width - new_w) / 2.) / ((float) new_w / net_input_width); center_y = (center_y - (float)(net_input_height - new_h) / 2.) / ((float) new_h / net_input_height); box_width *= (float)net_input_width / new_w; box_height *= (float) net_input_height / new_h; if(!relative){ center_x *= image_width; box_width *= image_width; center_y *= image_height; box_height *= image_height; } det_box.set_xmin(center_x - (float)box_width / 2); det_box.set_xmax(center_x + (float)box_width / 2); det_box.set_ymin(center_y - (float)box_height / 2); det_box.set_ymax(center_y + (float)box_height / 2); det_box.set_area(box_height * box_width); det_bboxes[i] = det_box; } } } template <typename Dtype> Dtype DIoULoss(NormalizedBBox predict_box, NormalizedBBox gt_bbox, Dtype* diff_x1, Dtype* diff_x2, Dtype* diff_y1, Dtype* diff_y2){ NOT_IMPLEMENTED; } } // namespace caffe ======================= File: src/caffe/layers/detection_ccpd_output_layer.cpp ======================= #include <algorithm> #include <fstream> // NOLINT(readability/streams) #include <map> #include <string> #include <utility> #include <vector> #include "boost/filesystem.hpp" #include "boost/foreach.hpp" #include "caffe/layers/detection_ccpd_output_layer.hpp" namespace caffe { template <typename Dtype> void DetectionCcpdOutputLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { const LpDetParameter& detection_output_param = this->layer_param_.lp_det_param(); CHECK(detection_output_param.has_num_chinese()) << "Must specify num_chinese"; CHECK(detection_output_param.has_num_english()) << "Must specify num_eng"; CHECK(detection_output_param.has_num_letter()) << "Must specify num_letter"; num_chinese_ = detection_output_param.num_chinese(); num_english_ = detection_output_param.num_english(); num_letter_ = detection_output_param.num_letter(); } template <typename Dtype> void DetectionCcpdOutputLayer<Dtype>::Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { CHECK_EQ(bottom[0]->num(), bottom[1]->num()); CHECK_EQ(bottom[1]->num(), bottom[2]->num()); CHECK_EQ(bottom[2]->num(), bottom[3]->num()); CHECK_EQ(bottom[3]->num(), bottom[4]->num()); CHECK_EQ(bottom[4]->num(), bottom[5]->num()); CHECK_EQ(bottom[5]->num(), bottom[6]->num()); // num() and channels() are 1. vector<int> top_shape(2, 1); // Since the number of bboxes to be kept is unknown before nms, we manually // set it to (fake) 1. top_shape.push_back(1); // Each row is a 9 dimension vector, which stores // [image_id, label, confidence, xmin, ymin, xmax, ymax] top_shape.push_back(7); top[0]->Reshape(top_shape); } template <typename Dtype> void DetectionCcpdOutputLayer<Dtype>::Forward_cpu( const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { const Dtype* chi_data = bottom[0]->cpu_data(); const Dtype* eng_data = bottom[1]->cpu_data(); const Dtype* let1_data = bottom[2]->cpu_data(); const Dtype* let2_data = bottom[3]->cpu_data(); const Dtype* let3_data = bottom[4]->cpu_data(); const Dtype* let4_data = bottom[5]->cpu_data(); const Dtype* let5_data = bottom[6]->cpu_data(); const int num = bottom[0]->num(); vector<int> top_shape(2, 1); top_shape.push_back(num); top_shape.push_back(7); top[0]->Reshape(top_shape); Dtype* top_data = top[0]->mutable_cpu_data(); caffe_set<Dtype>(top[0]->count(), -1, top_data); for (int i = 0; i < num; ++i) { const int chi_index = i*num_chinese_; const int eng_index = i*num_english_; const int letter_index = i*num_letter_; const Dtype* cur_chi_data= chi_data + chi_index; const Dtype* cur_eng_data= eng_data + eng_index; const Dtype* cur_let_1_data= let1_data + letter_index; const Dtype* cur_let_2_data= let2_data + letter_index; const Dtype* cur_let_3_data= let3_data + letter_index; const Dtype* cur_let_4_data= let4_data + letter_index; const Dtype* cur_let_5_data= let5_data + letter_index; int max_index = 0; Dtype temp = 0.f; for(int ii =0;ii<num_chinese_;ii++){ if(temp<cur_chi_data[ii]){ max_index = ii; temp = cur_chi_data[ii]; } } top_data[i * 7] = max_index; temp = 0.f; max_index = 0; for(int ii =0;ii<num_english_;ii++){ if(temp<cur_eng_data[ii]){ max_index = ii; temp = cur_eng_data[ii]; } } top_data[i * 7 + 1] = max_index; temp = 0.f; max_index = 0; for(int ii =0;ii<num_letter_;ii++){ if(temp<cur_let_1_data[ii]){ max_index = ii; temp = cur_let_1_data[ii]; } } top_data[i * 7 + 2] = max_index; temp = 0.f; max_index = 0; for(int ii =0;ii<num_letter_;ii++){ if(temp<cur_let_2_data[ii]){ max_index = ii; temp = cur_let_2_data[ii]; } } top_data[i * 7 + 3] = max_index; temp = 0.f; max_index = 0; for(int ii =0;ii<num_letter_;ii++){ if(temp<cur_let_3_data[ii]){ max_index = ii; temp = cur_let_3_data[ii]; } } top_data[i * 7 + 4] = max_index; temp = 0.f; max_index = 0; for(int ii =0;ii<num_letter_;ii++){ if(temp<cur_let_4_data[ii]){ max_index = ii; temp = cur_let_4_data[ii]; } } top_data[i * 7 + 5] = max_index; temp = 0.f; max_index = 0; for(int ii =0;ii<num_letter_;ii++){ if(temp<cur_let_5_data[ii]){ max_index = ii; temp = cur_let_5_data[ii]; } } top_data[i * 7 + 6] = max_index; } } #ifdef CPU_ONLY STUB_GPU_FORWARD(DetectionCcpdOutputLayer, Forward); #endif INSTANTIATE_CLASS(DetectionCcpdOutputLayer); REGISTER_LAYER_CLASS(DetectionCcpdOutput); } // namespace caffe ======================= File: src/caffe/layers/CenternetLossLayer.cpp ======================= #include <algorithm> #include <map> #include <utility> #include <vector> #include "caffe/layers/CenternetLossLayer.hpp" #include "caffe/util/math_functions.hpp" namespace caffe { template <typename Dtype> void CenterObjectLossLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { LossLayer<Dtype>::LayerSetUp(bottom, top); if (this->layer_param_.propagate_down_size() == 0) { this->layer_param_.add_propagate_down(true); this->layer_param_.add_propagate_down(true); this->layer_param_.add_propagate_down(false); } const CenterObjectLossParameter& center_object_loss_param = this->layer_param_.center_object_loss_param(); has_lm_ = center_object_loss_param.has_lm(); if(has_lm_){ CHECK_EQ(bottom[0]->channels(), 14); }else{ CHECK_EQ(bottom[0]->channels(), 4); } num_classes_ = center_object_loss_param.num_class(); CHECK_GE(num_classes_, 1) << "num_classes should not be less than 1."; CHECK_EQ(num_classes_, bottom[1]->channels()) << "num_classes must be equal to prediction classes"; num_ = bottom[0]->num(); num_gt_ = bottom[2]->height(); share_location_ = center_object_loss_param.share_location(); loc_classes_ = share_location_? 1 : num_classes_; if (!this->layer_param_.loss_param().has_normalization() && this->layer_param_.loss_param().has_normalize()) { normalization_ = this->layer_param_.loss_param().normalize()? LossParameter_NormalizationMode_VALID : LossParameter_NormalizationMode_BATCH_SIZE; } else { normalization_ = this->layer_param_.loss_param().normalization(); } vector<int> loss_shape(1, 1); // Set up loc offset & wh scale loss layer. loc_offset_weight_ = center_object_loss_param.loc_weight(); loc_offset_loss_type_ = center_object_loss_param.loc_loss_type(); // fake shape. vector<int> loc_offset_shape(1, 1); loc_offset_shape.push_back(2); loc_offset_pred_.Reshape(loc_offset_shape); loc_offset_gt_.Reshape(loc_offset_shape); //loc_channel_gt_.Reshape(loc_shape); loc_offset_bottom_vec_.push_back(&loc_offset_pred_); loc_offset_bottom_vec_.push_back(&loc_offset_gt_); //loc_bottom_vec_.push_back(&loc_channel_gt_); loc_offset_loss_.Reshape(loss_shape); loc_offset_top_vec_.push_back(&loc_offset_loss_); if (loc_offset_loss_type_ == CenterObjectLossParameter_LocLossType_L2) { LayerParameter layer_param; layer_param.set_name(this->layer_param_.name() + "_offset_l2_loc"); layer_param.set_type("EuclideanLoss"); layer_param.add_loss_weight(loc_offset_weight_); loc_offset_loss_layer_ = LayerRegistry<Dtype>::CreateLayer(layer_param); loc_offset_loss_layer_->SetUp(loc_offset_bottom_vec_, loc_offset_top_vec_); } else if (loc_offset_loss_type_ == CenterObjectLossParameter_LocLossType_SMOOTH_L1) { LayerParameter layer_param; layer_param.set_name(this->layer_param_.name() + "_offset_smooth_L1_loc"); layer_param.set_type("SmoothL1Loss"); layer_param.add_loss_weight(loc_offset_weight_); loc_offset_loss_layer_ = LayerRegistry<Dtype>::CreateLayer(layer_param); loc_offset_loss_layer_->SetUp(loc_offset_bottom_vec_, loc_offset_top_vec_); } else { LOG(FATAL) << "Unknown loc loss type."; } loc_wh_weight_ = center_object_loss_param.loc_weight(); loc_wh_loss_type_ = center_object_loss_param.loc_loss_type(); // fake shape. vector<int> loc_wh_shape(1, 1); loc_wh_shape.push_back(2); loc_wh_pred_.Reshape(loc_wh_shape); loc_wh_gt_.Reshape(loc_wh_shape); loc_wh_bottom_vec_.push_back(&loc_wh_pred_); loc_wh_bottom_vec_.push_back(&loc_wh_gt_); loc_wh_loss_.Reshape(loss_shape); loc_wh_top_vec_.push_back(&loc_wh_loss_); if (loc_wh_loss_type_ == CenterObjectLossParameter_LocLossType_L2) { LayerParameter layer_param; layer_param.set_name(this->layer_param_.name() + "_wh_l2_loc"); layer_param.set_type("EuclideanLoss"); layer_param.add_loss_weight(loc_wh_weight_); loc_wh_loss_layer_ = LayerRegistry<Dtype>::CreateLayer(layer_param); loc_wh_loss_layer_->SetUp(loc_wh_bottom_vec_, loc_wh_top_vec_); } else if (loc_wh_loss_type_ == CenterObjectLossParameter_LocLossType_SMOOTH_L1) { LayerParameter layer_param; layer_param.set_name(this->layer_param_.name() + "_wh_smooth_L1_loc"); layer_param.set_type("SmoothL1Loss"); layer_param.add_loss_weight(loc_wh_weight_); loc_wh_loss_layer_ = LayerRegistry<Dtype>::CreateLayer(layer_param); loc_wh_loss_layer_->SetUp(loc_wh_bottom_vec_, loc_wh_top_vec_); } else { LOG(FATAL) << "Unknown loc loss type."; } // Set up landmark loss layer. if(has_lm_){ lm_weight_ = center_object_loss_param.loc_weight(); lm_loss_type_ = center_object_loss_param.lm_loss_type(); // fake shape. vector<int> lm_shape(1, 1); lm_shape.push_back(10); lm_pred_.Reshape(lm_shape); lm_gt_.Reshape(lm_shape); lm_bottom_vec_.push_back(&lm_pred_); lm_bottom_vec_.push_back(&lm_gt_); lm_loss_.Reshape(loss_shape); lm_top_vec_.push_back(&lm_loss_); if (lm_loss_type_ == CenterObjectLossParameter_LocLossType_L2) { LayerParameter layer_param; layer_param.set_name(this->layer_param_.name() + "_l2_lm"); layer_param.set_type("EuclideanLoss"); layer_param.add_loss_weight(lm_weight_); lm_loss_layer_ = LayerRegistry<Dtype>::CreateLayer(layer_param); lm_loss_layer_->SetUp(lm_bottom_vec_, lm_top_vec_); } else if (lm_loss_type_ == CenterObjectLossParameter_LocLossType_SMOOTH_L1) { LayerParameter layer_param; layer_param.set_name(this->layer_param_.name() + "_smooth_L1_lm"); layer_param.set_type("SmoothL1Loss"); layer_param.add_loss_weight(lm_weight_); lm_loss_layer_ = LayerRegistry<Dtype>::CreateLayer(layer_param); lm_loss_layer_->SetUp(lm_bottom_vec_, lm_top_vec_); } else { LOG(FATAL) << "Unknown lm loss type."; } } // Set up confidence loss layer. conf_loss_type_ = center_object_loss_param.conf_loss_type(); conf_bottom_vec_.push_back(&conf_pred_); conf_bottom_vec_.push_back(&conf_gt_); conf_loss_.Reshape(loss_shape); conf_top_vec_.push_back(&conf_loss_); if (conf_loss_type_ == CenterObjectLossParameter_ConfLossType_FOCALSIGMOID) { LayerParameter layer_param; layer_param.set_name(this->layer_param_.name() + "_sigmoid_conf"); layer_param.set_type("CenterNetfocalSigmoidWithLoss"); layer_param.add_loss_weight(Dtype(1.)); layer_param.mutable_loss_param()->set_normalization(LossParameter_NormalizationMode_NONE); // Fake reshape. vector<int> conf_shape(1, 1); conf_gt_.Reshape(conf_shape); conf_shape.push_back(num_classes_); conf_pred_.Reshape(conf_shape); conf_loss_layer_ = LayerRegistry<Dtype>::CreateLayer(layer_param); conf_loss_layer_->SetUp(conf_bottom_vec_, conf_top_vec_); } else { LOG(FATAL) << "Unknown confidence loss type."; } iterations_ = 0; } template <typename Dtype> void CenterObjectLossLayer<Dtype>::Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { LossLayer<Dtype>::Reshape(bottom, top); CHECK_GE(num_classes_, 1) << "num_classes should not be less than 1."; CHECK_EQ(num_classes_, bottom[1]->channels()) << "num_classes must be equal to prediction classes"; } template <typename Dtype> void CenterObjectLossLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { const Dtype* loc_data = bottom[0]->cpu_data(); const int output_height = bottom[0]->height(); const int output_width = bottom[0]->width(); const int num_channels = bottom[0]->channels(); const Dtype* gt_data = bottom[2]->cpu_data(); num_gt_ = bottom[2]->height(); // Retrieve all ground truth. bool use_difficult_gt_ = true; Dtype background_label_id_ = -1; all_gt_bboxes.clear(); GetCenternetGroundTruth(gt_data, num_gt_, background_label_id_, use_difficult_gt_, &all_gt_bboxes, has_lm_); int num_groundtruth = 0; num_lm_ = 0; for(int i = 0; i < all_gt_bboxes.size(); i++){ vector<std::pair<NormalizedBBox, AnnoFaceLandmarks> > gt_boxes = all_gt_bboxes[i]; num_groundtruth += gt_boxes.size(); for(unsigned ii = 0; ii < gt_boxes.size(); ii++){ if(gt_boxes[ii].second.lefteye().x() > 0 && gt_boxes[ii].second.lefteye().y() > 0 && gt_boxes[ii].second.righteye().x() > 0 && gt_boxes[ii].second.righteye().y() > 0 && gt_boxes[ii].second.nose().x() > 0 && gt_boxes[ii].second.nose().y() > 0 && gt_boxes[ii].second.leftmouth().x() > 0 && gt_boxes[ii].second.leftmouth().y() > 0 && gt_boxes[ii].second.rightmouth().x() > 0 && gt_boxes[ii].second.rightmouth().y() > 0){ num_lm_++; } } } CHECK_EQ(num_gt_, num_groundtruth); if (num_gt_ >= 1) { // Form data to pass on to loc_loss_layer_. vector<int> loc_shape(2); loc_shape[0] = 1; loc_shape[1] = num_gt_ * 2; loc_offset_pred_.Reshape(loc_shape); loc_offset_gt_.Reshape(loc_shape); Dtype* loc_offset_pred_data = loc_offset_pred_.mutable_cpu_data(); Dtype* loc_offset_gt_data = loc_offset_gt_.mutable_cpu_data(); loc_wh_pred_.Reshape(loc_shape); loc_wh_gt_.Reshape(loc_shape); Dtype* loc_wh_pred_data = loc_wh_pred_.mutable_cpu_data(); Dtype* loc_wh_gt_data = loc_wh_gt_.mutable_cpu_data(); if(num_lm_ >0 && has_lm_){ loc_shape[0] = 1; loc_shape[1] = num_lm_ * 10; lm_pred_.Reshape(loc_shape); lm_gt_.Reshape(loc_shape); }else{ loc_shape[0] = 1; loc_shape[1] = 10; lm_pred_.Reshape(loc_shape); lm_gt_.Reshape(loc_shape); } Dtype* lm_pred_data = lm_pred_.mutable_cpu_data(); Dtype* lm_gt_data = lm_gt_.mutable_cpu_data(); EncodeTruthAndPredictions(loc_offset_gt_data, loc_offset_pred_data, loc_wh_gt_data, loc_wh_pred_data, lm_gt_data, lm_pred_data, output_width, output_height, share_location_, loc_data, num_channels, all_gt_bboxes, has_lm_); loc_offset_loss_layer_->Reshape(loc_offset_bottom_vec_, loc_offset_top_vec_); loc_offset_loss_layer_->Forward(loc_offset_bottom_vec_, loc_offset_top_vec_); loc_wh_loss_layer_->Reshape(loc_wh_bottom_vec_, loc_wh_top_vec_); loc_wh_loss_layer_->Forward(loc_wh_bottom_vec_, loc_wh_top_vec_); if(has_lm_ && num_lm_ >0){ lm_loss_layer_->Reshape(lm_bottom_vec_, lm_top_vec_); lm_loss_layer_->Forward(lm_bottom_vec_, lm_top_vec_); } } else { loc_offset_loss_.mutable_cpu_data()[0] = 0; loc_wh_loss_.mutable_cpu_data()[0] = 0; } if (num_gt_ >= 1) { if (conf_loss_type_ == CenterObjectLossParameter_ConfLossType_FOCALSIGMOID) { conf_gt_.ReshapeLike(*bottom[1]); conf_pred_.ReshapeLike(*bottom[1]); conf_pred_.CopyFrom(*bottom[1]); }else { LOG(FATAL) << "Unknown confidence loss type."; } Dtype* conf_gt_data = conf_gt_.mutable_cpu_data(); caffe_set(conf_gt_.count(), Dtype(0), conf_gt_data); GenerateBatchHeatmap(all_gt_bboxes, conf_gt_data, num_classes_, output_width, output_height); conf_loss_layer_->Reshape(conf_bottom_vec_, conf_top_vec_); conf_loss_layer_->Forward(conf_bottom_vec_, conf_top_vec_); } else { conf_loss_.mutable_cpu_data()[0] = 0; } top[0]->mutable_cpu_data()[0] = 0; Dtype loc_offset_loss = Dtype(0.), loc_wh_loss = Dtype(0.), cls_loss = Dtype(0.), lm_loss = Dtype(0.); Dtype normalizer = LossLayer<Dtype>::GetNormalizer( normalization_, num_, 1, num_gt_); Dtype lm_normalizer = LossLayer<Dtype>::GetNormalizer( normalization_, num_, 1, num_lm_); normalizer = normalizer > 0? normalizer : num_; lm_normalizer = lm_normalizer > 0? lm_normalizer : num_; if (this->layer_param_.propagate_down(0)) { loc_offset_loss = 1. * Dtype(loc_offset_loss_.cpu_data()[0] / normalizer); loc_wh_loss = 0.1 * Dtype(loc_wh_loss_.cpu_data()[0] / normalizer); if(has_lm_ && num_lm_ >0){ lm_loss = 0.1 * Dtype(lm_loss_.cpu_data()[0] / lm_normalizer); } } if (this->layer_param_.propagate_down(1)) { cls_loss = 1. * Dtype(conf_loss_.cpu_data()[0] / normalizer); } if(has_lm_ && num_lm_ >0){ top[0]->mutable_cpu_data()[0] = cls_loss + loc_offset_loss + loc_wh_loss + lm_loss; }else{ top[0]->mutable_cpu_data()[0] = cls_loss + loc_offset_loss + loc_wh_loss; } #if 1 if(iterations_ % 100 == 0){ LOG(INFO)<<"total loss: "<<top[0]->mutable_cpu_data()[0] <<", loc offset loss: "<<loc_offset_loss <<", loc wh loss: "<<loc_wh_loss <<", conf loss: "<< cls_loss <<", lm loss: "<< lm_loss; LOG(INFO)<<"normalizer: "<< normalizer <<", lm_normalizer: "<<lm_normalizer <<", num_lm_: "<<num_lm_ <<", num_gt_box_: "<<num_gt_ <<", num_class: "<<num_classes_ <<", output_width: "<<output_width <<", output_height: "<<output_height; } iterations_++; #endif } template <typename Dtype> void CenterObjectLossLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) { const int output_height = bottom[0]->height(); const int output_width = bottom[0]->width(); const int num_channels = bottom[0]->channels(); if (propagate_down[2]) { LOG(FATAL) << this->type() << " Layer cannot backpropagate to label inputs."; } // Back propagate on location offset prediction. Dtype normalizer = LossLayer<Dtype>::GetNormalizer( normalization_, num_, 1, num_gt_); Dtype lm_normalizer = LossLayer<Dtype>::GetNormalizer( normalization_, num_, 1, num_lm_); normalizer = normalizer > 0? normalizer : num_; lm_normalizer = lm_normalizer > 0? lm_normalizer : num_; if (propagate_down[0]) { Dtype* loc_bottom_diff = bottom[0]->mutable_cpu_diff(); caffe_set(bottom[0]->count(), Dtype(0), loc_bottom_diff); if (num_gt_ >= 1) { vector<bool> loc_propagate_down; loc_propagate_down.push_back(true); loc_propagate_down.push_back(false); // diff of offset loc_offset_loss_layer_->Backward(loc_offset_top_vec_, loc_propagate_down, loc_offset_bottom_vec_); Dtype loss_offset_weight = 1 * top[0]->cpu_diff()[0] / normalizer; caffe_scal(loc_offset_pred_.count(), loss_offset_weight, loc_offset_pred_.mutable_cpu_diff()); const Dtype* loc_offset_pred_diff = loc_offset_pred_.cpu_diff(); // diff of wh loc_wh_loss_layer_->Backward(loc_wh_top_vec_, loc_propagate_down, loc_wh_bottom_vec_); Dtype loss_wh_weight = 0.1 * top[0]->cpu_diff()[0] / normalizer; caffe_scal(loc_wh_pred_.count(), loss_wh_weight, loc_wh_pred_.mutable_cpu_diff()); const Dtype* loc_wh_pred_diff = loc_wh_pred_.cpu_diff(); // diff of landmarks if(has_lm_ && num_lm_ >0){ lm_loss_layer_->Backward(lm_top_vec_, loc_propagate_down, lm_bottom_vec_); Dtype lm_weight = 0.1 * top[0]->cpu_diff()[0] / lm_normalizer; caffe_scal(lm_pred_.count(), lm_weight, lm_pred_.mutable_cpu_diff()); } const Dtype* lm_pred_diff = lm_pred_.cpu_diff(); CopyDiffToBottom(loc_offset_pred_diff, loc_wh_pred_diff, output_width, output_height, has_lm_, lm_pred_diff, share_location_, loc_bottom_diff, num_channels, all_gt_bboxes); } } // Back propagate on confidence prediction. if (propagate_down[1]) { Dtype* conf_bottom_diff = bottom[1]->mutable_cpu_diff(); caffe_set(bottom[1]->count(), Dtype(0), conf_bottom_diff); if (num_gt_ >= 1) { vector<bool> conf_propagate_down; conf_propagate_down.push_back(true); conf_propagate_down.push_back(false); conf_loss_layer_->Backward(conf_top_vec_, conf_propagate_down, conf_bottom_vec_); Dtype loss_weight = top[0]->cpu_diff()[0] / normalizer; caffe_scal(conf_pred_.count(), loss_weight, conf_pred_.mutable_cpu_diff()); bottom[1]->ShareDiff(conf_pred_); } } } INSTANTIATE_CLASS(CenterObjectLossLayer); REGISTER_LAYER_CLASS(CenterObjectLoss); } // namespace caffe ======================= File: include/caffe/util/center_util.hpp ======================= #ifndef CAFFE_UTIL_H_CENTER_ #define CAFFE_UTIL_H_CENTER_ #include <stdint.h> #include <cmath> // for std::fabs and std::signbit #include <map> #include <string> #include <utility> #include <vector> #include "glog/logging.h" #include "caffe/caffe.hpp" namespace caffe { float YoloBBoxIou(NormalizedBBox a, NormalizedBBox b); int int_index(std::vector<int>a, int val, int n); template <typename Dtype> Dtype CenterSigmoid(Dtype x); template <typename Dtype> Dtype SingleSoftmaxLoss(Dtype bg_score, Dtype face_score, Dtype lable_value); template <typename T> bool SortScorePairDescendCenter(const pair<T, float>& pair1, const pair<T, float>& pair2); template <typename Dtype> Dtype smoothL1_Loss(Dtype x, Dtype* x_diff); template <typename Dtype> Dtype L2_Loss(Dtype x, Dtype* x_diff); template <typename Dtype> Dtype Object_L2_Loss(Dtype x, Dtype* x_diff); template<typename Dtype> Dtype gaussian_radius(const Dtype heatmap_height, const Dtype heatmap_width, const Dtype min_overlap); template <typename Dtype> void transferCVMatToBlobData(std::vector<Dtype> heatmap, Dtype* buffer_heat); template <typename Dtype> std::vector<Dtype> gaussian2D(const int height, const int width, Dtype sigma); template <typename Dtype> void draw_umich_gaussian(std::vector<Dtype>& heatmap, int center_x, int center_y, float radius,const int height, const int width); template <typename Dtype> void SelectHardSampleSoftMax(Dtype *label_data, std::vector<Dtype> batch_sample_loss, const int negative_ratio, std::vector<int> postive, const int output_height, const int output_width, const int num_channels, const int batch_size, bool has_lm); template <typename Dtype> void SoftmaxCenterGrid(Dtype * pred_data, const int batch_size, const int label_channel, const int num_channels, const int outheight, const int outwidth, bool has_lm); template<typename Dtype> Dtype FocalLossSoftmax(Dtype* label_data, Dtype* pred_data, const int batch_size, const int output_height, const int output_width, Dtype *bottom_diff, const int num_channels, bool has_lm); template <typename Dtype> Dtype SoftmaxWithLoss(Dtype* label_data, Dtype* pred_data, const int batch_size, const int output_height, const int output_width, Dtype *bottom_diff, const int num_channels, bool has_lm); template <typename Dtype> void SelectHardSampleSigmoid(Dtype *label_data, Dtype *pred_data, const int negative_ratio, const int num_postive, const int output_height, const int output_width, const int num_channels); template <typename Dtype> Dtype FocalLossSigmoid(Dtype* label_data, Dtype * pred_data, int dimScale, Dtype *bottom_diff); template <typename Dtype> Dtype GIoULoss(NormalizedBBox predict_box, NormalizedBBox gt_bbox, Dtype* diff_x1, Dtype* diff_x2, Dtype* diff_y1, Dtype* diff_y2); template <typename Dtype> Dtype DIoULoss(NormalizedBBox predict_box, NormalizedBBox gt_bbox, Dtype* diff_x1, Dtype* diff_x2, Dtype* diff_y1, Dtype* diff_y2); void correct_detector_bbox(int net_input_width, int net_input_height, int relative, std::map<int, std::vector<CenterNetInfo > > results, std::map<int, std::pair<int, int > > image_scale); } // namespace caffe #endif ======================= File: src/caffe/util/sampler.cpp ======================= <reponame>yuqj1990/deepano_train #include <algorithm> #include <vector> #include "caffe/util/bbox_util.hpp" #include "caffe/util/sampler.hpp" #include "caffe/util/im_transforms.hpp" #include "caffe/util/io.hpp" #include "google/protobuf/repeated_field.h" using google::protobuf::RepeatedPtrField; #define COMPAREMIN(a, b) (a >= b? b : a) #define COMPAREMAX(a, b) (a >= b? a : b) namespace caffe { void GenerateJitterSamples(const AnnotatedDatum& anno_datum, float jitter, vector<NormalizedBBox>* sampled_bboxes) { NormalizedBBox sampled_bbox; float img_w,img_h,off_x,off_y; vector<NormalizedBBox> object_bboxes; GroupObjectBBoxes(anno_datum, &object_bboxes); float pleft, pright, ptop, pbottom; caffe_rng_uniform(1, -jitter, jitter, &pleft); caffe_rng_uniform(1, -jitter, jitter, &pright); caffe_rng_uniform(1, -jitter, jitter, &ptop); caffe_rng_uniform(1, -jitter, jitter, &pbottom); off_x = pleft; off_y = ptop; img_w = 1.f - pleft - pright; img_h = 1.f - ptop - pbottom; sampled_bbox.set_xmin(off_x); sampled_bbox.set_ymin(off_y); sampled_bbox.set_xmax(off_x + img_w); sampled_bbox.set_ymax(off_y + img_h); SampleConstraint min_object_coverage_Constraint; min_object_coverage_Constraint.set_min_object_coverage(0.85); if(!SatisfySampleConstraint(sampled_bbox, object_bboxes, min_object_coverage_Constraint)){ sampled_bbox.set_xmin(0.f); sampled_bbox.set_ymin(0.f); sampled_bbox.set_xmax(1.f); sampled_bbox.set_ymax(1.f); } sampled_bboxes->push_back(sampled_bbox); } void GroupObjectBBoxes(const AnnotatedDatum& anno_datum, vector<NormalizedBBox>* object_bboxes) { object_bboxes->clear(); for (int i = 0; i < anno_datum.annotation_group_size(); ++i) { const AnnotationGroup& anno_group = anno_datum.annotation_group(i); for (int j = 0; j < anno_group.annotation_size(); ++j) { const Annotation& anno = anno_group.annotation(j); object_bboxes->push_back(anno.bbox()); } } } bool SatisfySampleConstraint(const NormalizedBBox& sampled_bbox, const vector<NormalizedBBox>& object_bboxes, const SampleConstraint& sample_constraint) { bool has_jaccard_overlap = sample_constraint.has_min_jaccard_overlap() || sample_constraint.has_max_jaccard_overlap(); bool has_sample_coverage = sample_constraint.has_min_sample_coverage() || sample_constraint.has_max_sample_coverage(); bool has_object_coverage = sample_constraint.has_min_object_coverage() || sample_constraint.has_max_object_coverage(); bool satisfy =!has_jaccard_overlap &&!has_sample_coverage && !has_object_coverage; if (satisfy) { // By default, the sampled_bbox is "positive" if no constraints are defined. return true; } // Check constraints. bool found = false; for (int i = 0; i < object_bboxes.size(); ++i) { const NormalizedBBox& object_bbox = object_bboxes[i]; // Test jaccard overlap. if (has_jaccard_overlap) { const float jaccard_overlap = JaccardOverlap(sampled_bbox, object_bbox); if (sample_constraint.has_min_jaccard_overlap() && jaccard_overlap < sample_constraint.min_jaccard_overlap()) { continue; } if (sample_constraint.has_max_jaccard_overlap() && jaccard_overlap > sample_constraint.max_jaccard_overlap()) { continue; } found = true; } // Test sample coverage. if (has_sample_coverage) { const float sample_coverage = BBoxCoverage(sampled_bbox, object_bbox); if (sample_constraint.has_min_sample_coverage() && sample_coverage < sample_constraint.min_sample_coverage()) { continue; } if (sample_constraint.has_max_sample_coverage() && sample_coverage > sample_constraint.max_sample_coverage()) { continue; } found = true; } // Test object coverage. if (has_object_coverage) { const float object_coverage = BBoxCoverage(object_bbox, sampled_bbox); if (sample_constraint.has_min_object_coverage() && object_coverage < sample_constraint.min_object_coverage()) { continue; } if (sample_constraint.has_max_object_coverage() && object_coverage > sample_constraint.max_object_coverage()) { continue; } found = true; } if (found) { return true; } } return found; } void SampleBBox(const Sampler& sampler, NormalizedBBox* sampled_bbox, float orl_ratio) { // Get random scale. CHECK_GE(sampler.max_scale(), sampler.min_scale()); CHECK_GT(sampler.min_scale(), 0.); CHECK_LE(sampler.max_scale(), 1.); float scale; caffe_rng_uniform(1, sampler.min_scale(), sampler.max_scale(), &scale); // Get random aspect ratio. CHECK_GE(sampler.max_aspect_ratio(), sampler.min_aspect_ratio()); CHECK_GT(sampler.min_aspect_ratio(), 0.); CHECK_LT(sampler.max_aspect_ratio(), FLT_MAX); float aspect_ratio; caffe_rng_uniform(1, sampler.min_aspect_ratio(), sampler.max_aspect_ratio(), &aspect_ratio); aspect_ratio = std::max<float>(aspect_ratio, std::pow(scale, 2.)); aspect_ratio = std::min<float>(aspect_ratio, 1 / std::pow(scale, 2.)); // Figure out bbox dimension. float bbox_width = scale * sqrt(aspect_ratio); float bbox_height = scale / sqrt(aspect_ratio); // Figure out top left coordinates. float w_off, h_off; caffe_rng_uniform(1, 0.f, 1 - bbox_width, &w_off); caffe_rng_uniform(1, 0.f, 1 - bbox_height, &h_off); sampled_bbox->set_xmin(w_off); sampled_bbox->set_ymin(h_off); sampled_bbox->set_xmax(w_off + bbox_width); sampled_bbox->set_ymax(h_off + bbox_height); } void SampleBBox_Square(const AnnotatedDatum& anno_datum, const Sampler& sampler, NormalizedBBox* sampled_bbox) { // Get random scale. CHECK_GE(sampler.max_scale(), sampler.min_scale()); CHECK_GT(sampler.min_scale(), 0.); CHECK_LE(sampler.max_scale(), 1.); const Datum datum = anno_datum.datum(); int datum_height = datum.height(); int datum_width = datum.width(); int min_side = datum_height; float min_side_scale = 0.0; min_side = datum_height > datum_width? datum_width : datum_height; // printf("height=%d, width=%d, min_side=%d\n", datum_height, datum_width, min_side); float scale; caffe_rng_uniform(1, sampler.min_scale(), sampler.max_scale(), &scale); min_side_scale = min_side * scale; // printf("scale=%f, min_side_scale = %f\n", scale, min_side_scale); float bbox_width = min_side_scale/datum_width; float bbox_height = min_side_scale/datum_height; // printf("bbox_width=%f, bbox_height=%f\n", bbox_width, bbox_height); // Figure out top left coordinates. float w_off, h_off; caffe_rng_uniform(1, 0.f, 1 - bbox_width, &w_off); caffe_rng_uniform(1, 0.f, 1 - bbox_height, &h_off); sampled_bbox->set_xmin(w_off); sampled_bbox->set_ymin(h_off); sampled_bbox->set_xmax(w_off + bbox_width); sampled_bbox->set_ymax(h_off + bbox_height); } void GenerateSamples(const NormalizedBBox& source_bbox, const vector<NormalizedBBox>& object_bboxes, const BatchSampler& batch_sampler, vector<NormalizedBBox>* sampled_bboxes, float orl_ratio) { int found = 0; for (int i = 0; i < batch_sampler.max_trials(); ++i) { if (batch_sampler.has_max_sample() && found >= batch_sampler.max_sample()) { break; } // Generate sampled_bbox in the normalized space [0, 1]. NormalizedBBox sampled_bbox; SampleBBox(batch_sampler.sampler(), &sampled_bbox, orl_ratio); // Transform the sampled_bbox w.r.t. source_bbox. LocateBBox(source_bbox, sampled_bbox, &sampled_bbox); // Determine if the sampled bbox is positive or negative by the constraint. if (SatisfySampleConstraint(sampled_bbox, object_bboxes, batch_sampler.sample_constraint())) { ++found; sampled_bboxes->push_back(sampled_bbox); } } } void GenerateSamples_Square(const AnnotatedDatum& anno_datum, const NormalizedBBox& source_bbox, const vector<NormalizedBBox>& object_bboxes, const BatchSampler& batch_sampler, vector<NormalizedBBox>* sampled_bboxes) { int found = 0; for (int i = 0; i < batch_sampler.max_trials(); ++i) { if (batch_sampler.has_max_sample() && found >= batch_sampler.max_sample()) { break; } // Generate sampled_bbox in the normalized space [0, 1]. NormalizedBBox sampled_bbox; SampleBBox_Square(anno_datum, batch_sampler.sampler(), &sampled_bbox); // Transform the sampled_bbox w.r.t. source_bbox. LocateBBox(source_bbox, sampled_bbox, &sampled_bbox); // Determine if the sampled bbox is positive or negative by the constraint. if (SatisfySampleConstraint(sampled_bbox, object_bboxes, batch_sampler.sample_constraint())) { ++found; sampled_bboxes->push_back(sampled_bbox); } } } void GenerateBatchSamples(const AnnotatedDatum& anno_datum, const vector<BatchSampler>& batch_samplers, vector<NormalizedBBox>* sampled_bboxes) { sampled_bboxes->clear(); vector<NormalizedBBox> object_bboxes; GroupObjectBBoxes(anno_datum, &object_bboxes); const int img_height = anno_datum.datum().height(); const int img_width = anno_datum.datum().width(); float ratio = (float)img_height / img_width; for (int i = 0; i < batch_samplers.size(); ++i) { if (batch_samplers[i].use_original_image()) { NormalizedBBox unit_bbox; unit_bbox.set_xmin(0); unit_bbox.set_ymin(0); unit_bbox.set_xmax(1); unit_bbox.set_ymax(1); GenerateSamples(unit_bbox, object_bboxes, batch_samplers[i], sampled_bboxes, ratio); } } } void GenerateBatchSamples_Square(const AnnotatedDatum& anno_datum, const vector<BatchSampler>& batch_samplers, vector<NormalizedBBox>* sampled_bboxes) { sampled_bboxes->clear(); vector<NormalizedBBox> object_bboxes; GroupObjectBBoxes(anno_datum, &object_bboxes); for (int i = 0; i < batch_samplers.size(); ++i) { if (batch_samplers[i].use_original_image()) { NormalizedBBox unit_bbox; unit_bbox.set_xmin(0); unit_bbox.set_ymin(0); unit_bbox.set_xmax(1); unit_bbox.set_ymax(1); GenerateSamples_Square(anno_datum, unit_bbox, object_bboxes, batch_samplers[i], sampled_bboxes); } } } void GenerateDataAnchorSample(const AnnotatedDatum& anno_datum, const DataAnchorSampler& data_anchor_sampler, const vector<NormalizedBBox>& object_bboxes, NormalizedBBox* sampled_bbox, const int & resized_scale){ vector<int>anchorScale; int img_height = anno_datum.datum().height(); int img_width = anno_datum.datum().width(); anchorScale.clear(); for(int s = 0 ; s < data_anchor_sampler.scale_size(); s++){ anchorScale.push_back(data_anchor_sampler.scale(s)); } CHECK_GT(object_bboxes.size(), 0); int object_bbox_index = caffe_rng_rand() % object_bboxes.size(); const float xmin = object_bboxes[object_bbox_index].xmin()*img_width; const float xmax = object_bboxes[object_bbox_index].xmax()*img_width; const float ymin = object_bboxes[object_bbox_index].ymin()*img_height; const float ymax = object_bboxes[object_bbox_index].ymax()*img_height; float bbox_width = xmax - xmin; float bbox_height = ymax - ymin; int range_size = 0, rand_idx_size = 0, rng_rand_size = 0; float bbox_aera = bbox_height * bbox_width; float scaleChoose = 0.0f; float min_resize_val = 0.f, max_resize_val = 0.f; for(int j = 0; j < anchorScale.size() - 1; ++j){ if(bbox_aera >= std::pow(anchorScale[j], 2) && bbox_aera < std::pow(anchorScale[j+1], 2)){ range_size = j + 1; break; } } if(bbox_aera > std::pow(anchorScale[anchorScale.size() - 2], 2)) range_size = anchorScale.size() - 2; if(range_size == 0){ rand_idx_size = 0; }else{ rng_rand_size = caffe_rng_rand() % range_size; rand_idx_size = rng_rand_size % range_size; } if(rand_idx_size == range_size){ min_resize_val = anchorScale[rand_idx_size] / 2; max_resize_val = COMPAREMIN((float)anchorScale[rand_idx_size] * 2, 2*std::sqrt(bbox_aera)); if(min_resize_val <= max_resize_val) caffe_rng_uniform(1, min_resize_val, max_resize_val, &scaleChoose); else caffe_rng_uniform(1, max_resize_val, min_resize_val, &scaleChoose); }else{ min_resize_val = anchorScale[rand_idx_size] / 2; max_resize_val = (float)anchorScale[rand_idx_size] * 2; caffe_rng_uniform(1, min_resize_val, max_resize_val, &scaleChoose); } float w_off = 0.0f, h_off = 0.0f; int image_long_side = COMPAREMAX(img_height, img_width); float sample_bbox_size = std::sqrt(bbox_aera) * float(resized_scale / scaleChoose); if(sample_bbox_size > 10000) sample_bbox_size = 10000; if(sample_bbox_size >= image_long_side){ caffe_rng_uniform(1, img_width - sample_bbox_size, 0.f, &w_off); caffe_rng_uniform(1, img_height - sample_bbox_size, 0.f, &h_off); }else{ /* if(image_long_side == img_height){ if(bbox_height <= sample_bbox_size){ caffe_rng_uniform(1, ymin + bbox_height - sample_bbox_size, ymin, &h_off); }else{ caffe_rng_uniform(1, ymin, ymin + bbox_height - sample_bbox_size, &h_off); } if(sample_bbox_size >= img_width){ caffe_rng_uniform(1, img_width - sample_bbox_size, 0.f, &w_off); }else{ if(bbox_width <= sample_bbox_size){ caffe_rng_uniform(1, xmin + bbox_width - sample_bbox_size, xmin, &w_off); }else{ caffe_rng_uniform(1, xmin, xmin + bbox_width - sample_bbox_size, &w_off); } } }else if(image_long_side == img_width){ if(bbox_width <= sample_bbox_size){ caffe_rng_uniform(1, xmin + bbox_width - sample_bbox_size, xmin, &w_off); }else{ caffe_rng_uniform(1, xmin, xmin + bbox_width - sample_bbox_size, &w_off); } if(sample_bbox_size >= img_height){ caffe_rng_uniform(1, img_height - sample_bbox_size, 0.f, &h_off); }else{ if(bbox_height <= sample_bbox_size){ caffe_rng_uniform(1, ymin + bbox_height - sample_bbox_size, ymin, &h_off); }else{ caffe_rng_uniform(1, ymin, ymin + bbox_height - sample_bbox_size, &h_off); } } } */ if(bbox_height <= sample_bbox_size){ caffe_rng_uniform(1, ymin + bbox_height - sample_bbox_size, ymin, &h_off); }else{ caffe_rng_uniform(1, ymin, ymin + bbox_height - sample_bbox_size, &h_off); } if(bbox_width <= sample_bbox_size){ caffe_rng_uniform(1, xmin + bbox_width - sample_bbox_size, xmin, &w_off); }else{ caffe_rng_uniform(1, xmin, xmin + bbox_width - sample_bbox_size, &w_off); } } sampled_bbox->set_xmin((float)w_off / img_width); sampled_bbox->set_ymin((float)h_off / img_height); sampled_bbox->set_xmax((float)(w_off + sample_bbox_size) / img_width); sampled_bbox->set_ymax((float)(h_off + sample_bbox_size) / img_height); } void GenerateBatchDataAnchorSamples(const AnnotatedDatum& anno_datum, const vector<DataAnchorSampler>& data_anchor_samplers, vector<NormalizedBBox>* sampled_bboxes, const int & resized_scale) { CHECK_EQ(data_anchor_samplers.size(), 1); vector<NormalizedBBox> object_bboxes; GroupObjectBBoxes(anno_datum, &object_bboxes); for (int i = 0; i < data_anchor_samplers.size(); ++i) { if (data_anchor_samplers[i].use_original_image()) { int found = 0; NormalizedBBox sampled_bbox; for (int j = 0; j < data_anchor_samplers[i].max_trials(); ++j) { if (data_anchor_samplers[i].has_max_sample() && found >= data_anchor_samplers[i].max_sample()) { break; } GenerateDataAnchorSample(anno_datum, data_anchor_samplers[i], object_bboxes, &sampled_bbox, resized_scale); if (SatisfySampleConstraint(sampled_bbox, object_bboxes, data_anchor_samplers[i].sample_constraint())){ found++; sampled_bboxes->push_back(sampled_bbox); } } if(found == 0){ sampled_bbox.set_xmin(0.f); sampled_bbox.set_ymin(0.f); sampled_bbox.set_xmax(1.f); sampled_bbox.set_ymax(1.f); sampled_bboxes->push_back(sampled_bbox); } }else{ LOG(FATAL)<<"must use original_image"; } } } void GenerateLFFDSample(const AnnotatedDatum& anno_datum, vector<NormalizedBBox>* sampled_bboxes, std::vector<int> bbox_small_size_list, std::vector<int> bbox_large_size_list, std::vector<int> anchorStride, AnnotatedDatum* resized_anno_datum, const TransformationParameter& trans_param, bool do_resize){ CHECK_EQ(bbox_large_size_list.size(), bbox_small_size_list.size()); int resized_height = trans_param.resize_param().height(); int resized_width = trans_param.resize_param().width(); vector<NormalizedBBox> object_bboxes; GroupObjectBBoxes(anno_datum, &object_bboxes); int num_output_scale = bbox_small_size_list.size(); int img_height = anno_datum.datum().height(); int img_width = anno_datum.datum().width(); CHECK_GT(object_bboxes.size(), 0); int object_bbox_index = caffe_rng_rand() % object_bboxes.size(); const float xmin = object_bboxes[object_bbox_index].xmin()*img_width; const float xmax = object_bboxes[object_bbox_index].xmax()*img_width; const float ymin = object_bboxes[object_bbox_index].ymin()*img_height; const float ymax = object_bboxes[object_bbox_index].ymax()*img_height; float bbox_width = xmax - xmin; float bbox_height = ymax - ymin; float longer_side = COMPAREMAX(bbox_height, bbox_width); int scaled_idx = 0, side_length = 0; if(longer_side <= bbox_small_size_list[0]){ scaled_idx = 0; }else if(longer_side <= bbox_small_size_list[1]){ scaled_idx = caffe_rng_rand() % 2; }else if(longer_side <= bbox_small_size_list[2]){ scaled_idx = caffe_rng_rand() % 3; }else if(longer_side >= bbox_small_size_list[num_output_scale - 1]){ scaled_idx = num_output_scale - 1; }else{ for(int ii = 3; ii < num_output_scale - 1; ii++){ if(longer_side >= bbox_small_size_list[ii] && longer_side < bbox_small_size_list[ii + 1]) scaled_idx = ii; } } if(scaled_idx == (num_output_scale - 1)){ side_length = bbox_large_size_list[num_output_scale - 1] + caffe_rng_rand() % (static_cast<int>(bbox_large_size_list[num_output_scale - 1] * 0.5)); }else{ side_length = bbox_small_size_list[scaled_idx] + caffe_rng_rand() % (bbox_large_size_list[scaled_idx] - bbox_small_size_list[scaled_idx]); } NormalizedBBox sampled_bbox; if(do_resize){ float scale = (float) side_length / longer_side; ResizedCropSample(anno_datum, resized_anno_datum, scale, trans_param); int Resized_ori_Height = int(scale * img_height); int Resized_ori_Width = int(scale * img_width); NormalizedBBox target_bbox = object_bboxes[object_bbox_index]; float resized_xmin = target_bbox.xmin() * Resized_ori_Width; float resized_xmax = target_bbox.xmax() * Resized_ori_Width; float resized_ymin = target_bbox.ymin() * Resized_ori_Height; float resized_ymax = target_bbox.ymax() * Resized_ori_Height; float vibration_length = float(anchorStride[scaled_idx]); float offset_x = 0.f, offset_y = 0.f; caffe_rng_uniform(1, -vibration_length, vibration_length, &offset_x); caffe_rng_uniform(1, -vibration_length, vibration_length, &offset_y); float width_offset_ = (resized_xmin + resized_xmax) / 2 + offset_x - resized_width / 2; float height_offset_ = (resized_ymin + resized_ymax) / 2 + offset_y - resized_height / 2; float width_end_ = (resized_xmin + resized_xmax) / 2 + offset_x + resized_width / 2; float height_end_ = (resized_ymin + resized_ymax) / 2 + offset_y + resized_height / 2; float w_off = (float) width_offset_ / Resized_ori_Width; float h_off = (float) height_offset_ / Resized_ori_Height; float w_end = (float) width_end_ / Resized_ori_Width; float h_end = (float) height_end_ / Resized_ori_Height; sampled_bbox.set_xmin(w_off); sampled_bbox.set_ymin(h_off); sampled_bbox.set_xmax(w_end); sampled_bbox.set_ymax(h_end); SampleConstraint min_object_coverage_Constraint; min_object_coverage_Constraint.set_min_object_coverage(0.85); if(!SatisfySampleConstraint(sampled_bbox, object_bboxes, min_object_coverage_Constraint)){ resized_anno_datum->CopyFrom(anno_datum); sampled_bbox.set_xmin(0.f); sampled_bbox.set_ymin(0.f); sampled_bbox.set_xmax(1.f); sampled_bbox.set_ymax(1.f); } sampled_bboxes->push_back(sampled_bbox); }else{ LOG(FATAL)<<"must be resized"; } } void ResizedCropSample(const AnnotatedDatum& anno_datum, AnnotatedDatum* resized_anno_datum, float scale, const TransformationParameter& trans_param){ const Datum datum = anno_datum.datum(); const int img_width = datum.width(); const int img_height = datum.height(); int Resized_img_Height = int(img_height * scale); int Resized_img_Width = int(img_width * scale); // image data if (datum.encoded()) { #ifdef USE_OPENCV CHECK(!(trans_param.force_color() && trans_param.force_gray())) << "cannot set both force_color and force_gray"; cv::Mat cv_img; if (trans_param.force_color() || trans_param.force_gray()) { // If force_color then decode in color otherwise decode in gray. cv_img = DecodeDatumToCVMat(datum, trans_param.force_color()); } else { cv_img = DecodeDatumToCVMatNative(datum); } // Expand the image. cv::Mat resized_img; cv::resize(cv_img, resized_img, cv::Size(Resized_img_Width, Resized_img_Height), 0, 0, cv::INTER_CUBIC); EncodeCVMatToDatum(resized_img, "jpg", resized_anno_datum->mutable_datum()); resized_anno_datum->mutable_datum()->set_label(datum.label()); #else LOG(FATAL) << "Encoded datum requires OpenCV; compile with USE_OPENCV."; #endif } else { if (trans_param.force_color() || trans_param.force_gray()) { LOG(ERROR) << "force_color and force_gray only for encoded datum"; } } resized_anno_datum->set_type(anno_datum.type()); RepeatedPtrField<AnnotationGroup>* Resized_anno_group = resized_anno_datum->mutable_annotation_group(); // labels trans if (anno_datum.type() == AnnotatedDatum_AnnotationType_BBOX) { // Go through each AnnotationGroup. for (int g = 0; g < anno_datum.annotation_group_size(); ++g) { const AnnotationGroup& anno_group = anno_datum.annotation_group(g); AnnotationGroup transformed_anno_group ; for (int a = 0; a < anno_group.annotation_size(); ++a) { const Annotation& anno = anno_group.annotation(a); const NormalizedBBox& bbox = anno.bbox(); // Adjust bounding box annotation. NormalizedBBox resize_bbox = bbox; float x_min = bbox.xmin() * img_width; float y_min = bbox.ymin() * img_height; float x_max = bbox.xmax() * img_width; float y_max = bbox.ymax() * img_height; x_min = std::max(0.f, x_min * Resized_img_Width / img_width); x_max = std::min(float(Resized_img_Width), x_max * Resized_img_Width / img_width); y_min = std::max(0.f, y_min * Resized_img_Height / img_height); y_max = std::min(float(Resized_img_Height), y_max * Resized_img_Height / img_height); resize_bbox.set_xmin(x_min / Resized_img_Width); resize_bbox.set_xmax(x_max / Resized_img_Width); resize_bbox.set_ymin(y_min / Resized_img_Height); resize_bbox.set_ymax(y_max / Resized_img_Height); Annotation* transformed_anno = transformed_anno_group.add_annotation(); NormalizedBBox* transformed_bbox = transformed_anno->mutable_bbox(); transformed_bbox->CopyFrom(resize_bbox); } transformed_anno_group.set_group_label(anno_group.group_label()); Resized_anno_group->Add()->CopyFrom(transformed_anno_group); } } else { LOG(FATAL) << "Unknown annotation type."; } CHECK_GT(resized_anno_datum->datum().channels(), 0); } } // namespace caffe ======================= File: src/caffe/layers/detection_centernet_output_layer.cpp ======================= #include <algorithm> #include <fstream> // NOLINT(readability/streams) #include <map> #include <string> #include <utility> #include <vector> #include "boost/filesystem.hpp" #include "boost/foreach.hpp" #include "caffe/layers/detection_centernet_output_layer.hpp" namespace caffe { bool compare_score(CenterNetInfo a, CenterNetInfo b){ return a.score() > b.score(); } template <typename Dtype> void CenternetDetectionOutputLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { const DetectionOutputParameter& detection_output_param = this->layer_param_.detection_output_param(); CHECK(detection_output_param.has_num_classes()) << "Must specify num_classes"; num_classes_ = detection_output_param.num_classes(); share_location_ = detection_output_param.share_location(); num_loc_classes_ = share_location_? 1 : num_classes_; keep_top_k_ = detection_output_param.keep_top_k(); confidence_threshold_ = detection_output_param.has_confidence_threshold()? detection_output_param.confidence_threshold() : -FLT_MAX; nms_thresh_ = detection_output_param.nms_thresh(); has_lm_ = detection_output_param.has_lm(); } template <typename Dtype> void CenternetDetectionOutputLayer<Dtype>::Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { //CHECK_EQ(bottom[0]->num(), bottom[1]->num()); //CHECK_EQ(bottom[0]->channels(), bottom[1]->channels()); CHECK_EQ(bottom[1]->channels(), num_classes_ - 1); // add background to classes if(has_lm_){ CHECK_EQ(bottom[0]->channels(), 14); vector<int> top_shape(2, 1); top_shape.push_back(1); top_shape.push_back(17); top[0]->Reshape(top_shape); }else{ CHECK_EQ(bottom[0]->channels(), 4); vector<int> top_shape(2, 1); top_shape.push_back(1); top_shape.push_back(7); top[0]->Reshape(top_shape); } } template <typename Dtype> void CenternetDetectionOutputLayer<Dtype>::Forward_cpu( const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { const Dtype* loc_data = bottom[0]->cpu_data(); const int output_height = bottom[0]->height(); const int output_width = bottom[0]->width(); num_ = bottom[0]->num(); int loc_channels = bottom[0]->channels(); const Dtype* conf_data = bottom[1]->cpu_data(); const int classes = bottom[1]->channels(); results_.clear(); get_topK(conf_data, loc_data, output_height, output_width, classes, num_, &results_, loc_channels, has_lm_, confidence_threshold_, nms_thresh_); int num_kept = 0; std::map<int, vector<CenterNetInfo > > ::iterator iter; int count = 0; #if 1 for(iter = results_.begin(); iter!= results_.end(); iter++){ int num_det = iter->second.size(); if(keep_top_k_ > 0 && num_det > keep_top_k_){ std::sort(iter->second.begin(), iter->second.end(), compare_score); iter->second.resize(keep_top_k_); num_kept += keep_top_k_; }else{ num_kept += num_det; } } #else for(iter = results_.begin(); iter!= results_.end(); iter++){ int num_det = iter->second.size(); num_kept += num_det; } #endif vector<int> top_shape(2, 1); top_shape.push_back(num_kept); if(has_lm_) top_shape.push_back(17); else top_shape.push_back(7); Dtype* top_data; if (num_kept == 0) { top_shape[2] = num_; top[0]->Reshape(top_shape); top_data = top[0]->mutable_cpu_data(); caffe_set<Dtype>(top[0]->count(), -1, top_data); for (int i = 0; i < num_; ++i) { top_data[0] = i; if(has_lm_) top_data += 17; else top_data += 7; } } else { top[0]->Reshape(top_shape); top_data = top[0]->mutable_cpu_data(); } for(int i = 0; i < num_; i++){ if(results_.find(i)!= results_.end()){ std::vector<CenterNetInfo > result_temp = results_.find(i)->second; for(unsigned j = 0; j < result_temp.size(); ++j){ if(has_lm_){ top_data[count * 17] = i; top_data[count * 17 + 1] = result_temp[j].class_id() + 1; top_data[count * 17 + 2] = result_temp[j].score(); top_data[count * 17 + 3] = result_temp[j].xmin(); top_data[count * 17 + 4] = result_temp[j].ymin(); top_data[count * 17 + 5] = result_temp[j].xmax(); top_data[count * 17 + 6] = result_temp[j].ymax(); top_data[count * 17 + 7] = result_temp[j].marks().lefteye().x(); top_data[count * 17 + 8] = result_temp[j].marks().lefteye().y(); top_data[count * 17 + 9] = result_temp[j].marks().righteye().x(); top_data[count * 17 + 10] = result_temp[j].marks().righteye().y(); top_data[count * 17 + 11] = result_temp[j].marks().nose().x(); top_data[count * 17 + 12] = result_temp[j].marks().nose().y(); top_data[count * 17 + 13] = result_temp[j].marks().leftmouth().x(); top_data[count * 17 + 14] = result_temp[j].marks().leftmouth().y(); top_data[count * 17 + 15] = result_temp[j].marks().rightmouth().x(); top_data[count * 17 + 16] = result_temp[j].marks().rightmouth().y(); }else{ top_data[count * 7] = i; top_data[count * 7 + 1] = result_temp[j].class_id() + 1; top_data[count * 7 + 2] = result_temp[j].score(); top_data[count * 7 + 3] = result_temp[j].xmin(); top_data[count * 7 + 4] = result_temp[j].ymin(); top_data[count * 7 + 5] = result_temp[j].xmax(); top_data[count * 7 + 6] = result_temp[j].ymax(); } ++count; } } } } #ifdef CPU_ONLY STUB_GPU_FORWARD(CenternetDetectionOutputLayer, Forward); #endif INSTANTIATE_CLASS(CenternetDetectionOutputLayer); REGISTER_LAYER_CLASS(CenternetDetectionOutput); } // namespace caffe ======================= File: src/caffe/layers/triplet_loss_layer.cpp ======================= <reponame>yuqj1990/deepano_train #include "caffe/layers/triplet_loss_layer.hpp" #include "math.h" namespace caffe { template <typename Dtype> void TripletLossLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { batch_size_ = bottom[0]->num(); feature_dim_ = bottom[0]->count(1); triplet_num_ = bottom[1]->num(); diff_na_.Reshape(feature_dim_, 1, 1, 1); diff_pa_.Reshape(feature_dim_, 1, 1, 1); diff_np_.Reshape(feature_dim_, 1, 1, 1); bottom_diff_.Reshape(batch_size_, feature_dim_, 1, 1); } template <typename Dtype> void TripletLossLayer<Dtype>::Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { vector<int> loss_shape(1); loss_shape[0]=1; top[0]->Reshape(loss_shape); } template <typename Dtype> void TripletLossLayer<Dtype>::ComputeDiff_cpu(const Dtype *x_1, const Dtype *x_2, const Dtype x_1_norm, const Dtype x_2_norm, const Dtype inner_val, Dtype *x_1_diff) { caffe_cpu_scale(feature_dim_, Dtype(1) / (x_1_norm * x_2_norm), x_2, x_1_diff); Dtype x_1_norm_cubic = x_1_norm * x_1_norm * x_1_norm; caffe_cpu_axpby(feature_dim_, -inner_val / (x_1_norm_cubic * x_2_norm), x_1, Dtype(1), x_1_diff); } template <typename Dtype> void TripletLossLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { caffe_set(bottom[0]->count(), Dtype(0), bottom_diff_.mutable_cpu_data()); Dtype loss = 0; Dtype margin = this->layer_param_.triplet_loss_param().margin(); for (int i = 0; i < triplet_num_; ++i) { int a_idx = bottom[1]->cpu_data()[i * 3 ]; int p_idx = bottom[1]->cpu_data()[i * 3 + 1]; int n_idx = bottom[1]->cpu_data()[i * 3 + 2]; const Dtype *a_pointer = bottom[0]->cpu_data() + a_idx * feature_dim_; const Dtype *p_pointer = bottom[0]->cpu_data() + p_idx * feature_dim_; const Dtype *n_pointer = bottom[0]->cpu_data() + n_idx * feature_dim_; /*************以下为自己添加的*********************/ Dtype dist_ap = 0.f, dist_an = 0.f; for(int i = 0; i< feature_dim_; i++){ float diff_apos = std::pow(float(a_pointer[i])- float(p_pointer[i]), 2); float diff_aneg = std::pow(float(a_pointer[i] )- float(n_pointer[i]), 2); dist_ap += diff_apos; dist_an +=diff_aneg; } //LOG(INFO)<<"dist_ap: "<<dist_ap<<" dist_an: "<<dist_an; /***********************************************/ if (dist_ap - dist_an + margin > 0) { loss += dist_ap + margin - dist_an; } /*********************以下是我自己做的**********************/ // backword a caffe_sub( feature_dim_, n_pointer, // n p_pointer, // p diff_np_.mutable_cpu_data()); // n_i - p_i; caffe_cpu_axpby( feature_dim_, Dtype(2.0), diff_np_.mutable_cpu_data(), Dtype(0.0), bottom_diff_.mutable_cpu_data() + (a_idx * feature_dim_)); // backward p caffe_sub( feature_dim_, p_pointer, // p a_pointer, // a diff_pa_.mutable_cpu_data()); // p_i - a_i; caffe_cpu_axpby( feature_dim_, Dtype(2.0), diff_pa_.mutable_cpu_data(), Dtype(0.0), bottom_diff_.mutable_cpu_data() + (p_idx * feature_dim_)); // backward n caffe_sub( feature_dim_, a_pointer, // a p_pointer, // n diff_na_.mutable_cpu_data()); // a_i - n_i; caffe_cpu_axpby( feature_dim_, Dtype(2.0), diff_na_.mutable_cpu_data(), Dtype(0.0), bottom_diff_.mutable_cpu_data() + (n_idx * feature_dim_)); /*********************以上是我自己做的**********************/ } Dtype scalar = Dtype(1) / triplet_num_; top[0]->mutable_cpu_data()[0] = loss * scalar; } template <typename Dtype> void TripletLossLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) { if (propagate_down[0]) { Dtype scalar = top[0]->cpu_diff()[0] / triplet_num_; caffe_cpu_scale(bottom_diff_.count(), scalar, bottom_diff_.cpu_data(), bottom[0]->mutable_cpu_diff()); } } INSTANTIATE_CLASS(TripletLossLayer); REGISTER_LAYER_CLASS(TripletLoss); } ======================= File: src/caffe/layers/CenterGridLossLayer.cpp ======================= <filename>src/caffe/layers/CenterGridLossLayer.cpp #include <algorithm> #include <map> #include <utility> #include <vector> #include "caffe/layers/CenterGridLossLayer.hpp" #include "caffe/util/math_functions.hpp" namespace caffe { template <typename Dtype> void CenterGridLossLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { LossLayer<Dtype>::LayerSetUp(bottom, top); if (this->layer_param_.propagate_down_size() == 0) { this->layer_param_.add_propagate_down(true); this->layer_param_.add_propagate_down(false); } const CenterObjectLossParameter& center_object_loss_param = this->layer_param_.center_object_loss_param(); // bias_mask_ CHECK_EQ(center_object_loss_param.has_bias_num(), 1); if(center_object_loss_param.has_bias_num()){ CHECK_EQ(center_object_loss_param.bias_scale_size(), 1); CHECK_EQ(center_object_loss_param.bias_num(), 1); anchor_scale_ = center_object_loss_param.bias_scale(0); int low_bbox = center_object_loss_param.low_bbox_scale(); int up_bbox = center_object_loss_param.up_bbox_scale(); bbox_range_scale_ = std::make_pair(low_bbox, up_bbox); } net_height_ = center_object_loss_param.net_height(); net_width_ = center_object_loss_param.net_width(); ignore_thresh_ = center_object_loss_param.ignore_thresh(); has_lm_ = center_object_loss_param.has_lm(); if (!this->layer_param_.loss_param().has_normalization() && this->layer_param_.loss_param().has_normalize()) { normalization_ = this->layer_param_.loss_param().normalize()? LossParameter_NormalizationMode_VALID : LossParameter_NormalizationMode_BATCH_SIZE; } else { normalization_ = this->layer_param_.loss_param().normalization(); } iterations_ = 0; vector<int> label_shape(1, 1); label_shape.push_back(1); label_data_.Reshape(label_shape); class_type_ = center_object_loss_param.class_type(); num_classes_ = center_object_loss_param.num_class(); CHECK_GE(num_classes_, 1) << "num_classes should not be less than 1."; if(class_type_ == CenterObjectLossParameter_CLASS_TYPE_SIGMOID){ CHECK_GE(num_classes_, 1) << "num_classes must be more than equal to prediction classes"; }else if(class_type_ == CenterObjectLossParameter_CLASS_TYPE_SOFTMAX){ CHECK_GT(num_classes_, 1) << "softmax num_classes must be equal to contain background"; }else{ LOG(FATAL)<<"unknown class type"; } CHECK_EQ(center_object_loss_param.share_location(), true); normalized_changed_ = false; } template <typename Dtype> void CenterGridLossLayer<Dtype>::Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { LossLayer<Dtype>::Reshape(bottom, top); } template <typename Dtype> void CenterGridLossLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { // gt_boxes const Dtype* gt_data = bottom[1]->cpu_data(); num_gt_ = bottom[1]->height(); bool use_difficult_gt_ = true; Dtype background_label_id_ = -1; num_ = bottom[0]->num(); all_gt_bboxes.clear(); GetYoloGroundTruth(gt_data, num_gt_, background_label_id_, use_difficult_gt_, has_lm_, &all_gt_bboxes, num_); num_groundtruth_ = 0; num_lm_ = 0; for(int i = 0; i < all_gt_bboxes.size(); i++){ vector<std::pair<NormalizedBBox, AnnoFaceLandmarks> > gt_boxes = all_gt_bboxes[i]; num_groundtruth_ += gt_boxes.size(); for(unsigned ii = 0; ii < gt_boxes.size(); ii++){ if(gt_boxes[ii].second.lefteye().x() > 0 && gt_boxes[ii].second.lefteye().y() > 0 && gt_boxes[ii].second.righteye().x() > 0 && gt_boxes[ii].second.righteye().y() > 0 && gt_boxes[ii].second.nose().x() > 0 && gt_boxes[ii].second.nose().y() > 0 && gt_boxes[ii].second.leftmouth().x() > 0 && gt_boxes[ii].second.leftmouth().y() > 0 && gt_boxes[ii].second.rightmouth().x() > 0 && gt_boxes[ii].second.rightmouth().y() > 0){ num_lm_++; } } } // prediction data Dtype* channel_pred_data = bottom[0]->mutable_cpu_data(); const int output_height = bottom[0]->height(); const int output_width = bottom[0]->width(); const int num_channels = bottom[0]->channels(); Dtype * bottom_diff = bottom[0]->mutable_cpu_diff(); std::vector<int> postive_batch_(num_, 0); //计算每个样本的总损失(loc loss + softmax loss) std::vector<Dtype> batch_sample_loss_(num_ * output_height * output_width, Dtype(-1.)); vector<int> label_shape(2, 1); label_shape.push_back(num_); label_shape.push_back(output_height*output_width); label_data_.Reshape(label_shape); Dtype *label_muti_data = label_data_.mutable_cpu_data(); Dtype class_score = Dtype(0.); Dtype sum_squre = Dtype(0.); Dtype lm_loss_origin = Dtype(0.); caffe_set(bottom[0]->count(), Dtype(0), bottom_diff); Dtype loc_loss = Dtype(0.), score_loss = Dtype(0.), normalizer = Dtype(0.), lm_loss = Dtype(0.), lm_normalizer = Dtype(0.); int num_gt_match = 0; if (num_groundtruth_ >= 1) { const float downRatio = (float)net_height_ / output_height; if(class_type_ == CenterObjectLossParameter_CLASS_TYPE_SIGMOID){ class_score = EncodeCenterGridObjectSigmoidLoss(num_, num_channels, num_classes_, output_width, output_height, downRatio, channel_pred_data, anchor_scale_, bbox_range_scale_, all_gt_bboxes, label_muti_data, bottom_diff, ignore_thresh_, &count_postive_, &sum_squre); }else if(class_type_ == CenterObjectLossParameter_CLASS_TYPE_SOFTMAX){ class_score = EncodeCenterGridObjectSoftMaxLoss(num_, num_channels, num_classes_, output_width, output_height, downRatio, postive_batch_, batch_sample_loss_, channel_pred_data, anchor_scale_, bbox_range_scale_, all_gt_bboxes, label_muti_data, bottom_diff, &count_postive_lm_, &count_postive_, &sum_squre, &num_gt_match, has_lm_, &lm_loss_origin); } normalizer = LossLayer<Dtype>::GetNormalizer( normalization_, num_, 1, count_postive_); lm_normalizer = LossLayer<Dtype>::GetNormalizer( normalization_, num_, 1, count_postive_lm_); loc_loss = sum_squre / normalizer; score_loss = class_score / normalizer; top[0]->mutable_cpu_data()[0] = loc_loss + score_loss; if(has_lm_ && num_lm_ > 0){ lm_loss = 0.1 * lm_loss_origin / lm_normalizer; top[0]->mutable_cpu_data()[0] += lm_loss; } } else { top[0]->mutable_cpu_data()[0] = 0; } #if 1 if(iterations_ % 100 == 0){ LOG(INFO)<<"Region "<<output_width <<": anchor scale: "<<anchor_scale_ <<", total loss: "<<top[0]->mutable_cpu_data()[0] <<", loc loss: "<< loc_loss <<", class loss: "<< score_loss <<", lm_loss: "<<lm_loss; LOG(INFO)<<"all_gt_boxes: "<<num_groundtruth_ <<", normalizer: "<<normalizer <<", lm_normalizer: "<<lm_normalizer <<", count_postive: "<< count_postive_ <<", count_postive_lm: "<< count_postive_lm_ <<", num_match: "<<num_gt_match <<", num_landmarks: "<<num_lm_; LOG(INFO)<<"*****************"; } iterations_++; #endif } template <typename Dtype> void CenterGridLossLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) { if (propagate_down[1]) { LOG(FATAL) << this->type() << " Layer cannot backpropagate to label inputs."; } if (propagate_down[0]) { Dtype loss_weight = Dtype(0.); Dtype normalizer = LossLayer<Dtype>::GetNormalizer( normalization_, num_, 1, count_postive_); Dtype lm_normalizer = LossLayer<Dtype>::GetNormalizer( normalization_, num_, 1, count_postive_lm_); const int output_height = bottom[0]->height(); const int output_width = bottom[0]->width(); const int num_channels = bottom[0]->channels(); int spatial_dim = output_height * output_width; loss_weight = top[0]->cpu_diff()[0] / normalizer; Dtype* bottom_diff = bottom[0]->mutable_cpu_diff(); caffe_cpu_scale(bottom[0]->count(), loss_weight, bottom_diff, bottom_diff); loss_weight = 0.1 * top[0]->cpu_diff()[0] * normalizer/ lm_normalizer; if(has_lm_ && num_lm_ >0){ for(int i = 0; i < num_; i++) caffe_cpu_scale(10 * spatial_dim, loss_weight, bottom_diff + i * num_channels * spatial_dim + 4 * spatial_dim, bottom_diff + i * num_channels * spatial_dim + 4 * spatial_dim); } } } INSTANTIATE_CLASS(CenterGridLossLayer); REGISTER_LAYER_CLASS(CenterGridLoss); } // namespace caffe ======================= File: include/caffe/layers/ccpdlp_evaluate_layer.hpp ======================= <filename>include/caffe/layers/ccpdlp_evaluate_layer.hpp<gh_stars>10-100 #ifndef CAFFE_DETECTION_EVALUATE_LAYER_HPP_ #define CAFFE_DETECTION_EVALUATE_LAYER_HPP_ #include <utility> #include <vector> #include "caffe/blob.hpp" #include "caffe/layer.hpp" #include "caffe/proto/caffe.pb.h" namespace caffe { /** * @brief Generate the detection evaluation based on DetectionOutputLayer and * ground truth bounding box labels. * * Intended for use with MultiBox detection method. * * NOTE: does not implement Backwards operation. */ template <typename Dtype> class LpEvaluateLayer : public Layer<Dtype> { public: explicit LpEvaluateLayer(const LayerParameter& param) : Layer<Dtype>(param) {} virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual inline const char* type() const { return "LpEvaluate"; } virtual inline int ExactBottomBlobs() const { return 2; } virtual inline int ExactNumTopBlobs() const { return 1; } protected: virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); /// @brief Not implemented virtual void Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) { NOT_IMPLEMENTED; } int num_chinese_; int num_english_; int num_letter_; }; } // namespace caffe #endif // CAFFE_DETECTION_EVALUATE_LAYER_HPP_ ======================= File: src/caffe/layers/CenterGridDetectionLayer.cpp ======================= <reponame>yuqj1990/deepano_train #include <algorithm> #include <fstream> // NOLINT(readability/streams) #include <map> #include <string> #include <utility> #include <vector> #include "boost/filesystem.hpp" #include "boost/foreach.hpp" #include "caffe/layers/CenterGridDetectionLayer.hpp" namespace caffe { bool GridCompareScore(CenterNetInfo a, CenterNetInfo b){ return a.score() > b.score(); } template <typename Dtype> void CenterGridOutputLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { bottom_size_ = bottom.size(); const DetectionOutputParameter& detection_output_param = this->layer_param_.detection_output_param(); CHECK(detection_output_param.has_num_classes()) << "Must specify num_classes"; num_classes_ = detection_output_param.num_classes(); if(detection_output_param.bias_scale_size() > 0){ CHECK_EQ(bottom_size_, detection_output_param.bias_scale_size()); for(int i = 0; i < detection_output_param.bias_scale_size(); i++){ anchor_scale_.push_back(detection_output_param.bias_scale(i)); } } keep_top_k_ = detection_output_param.keep_top_k(); confidence_threshold_ = detection_output_param.has_confidence_threshold()? detection_output_param.confidence_threshold() : -FLT_MAX; nms_thresh_ = detection_output_param.nms_thresh(); class_type_ = detection_output_param.class_type(); has_lm_ = detection_output_param.has_lm(); net_height_ = detection_output_param.net_height(); net_width_ = detection_output_param.net_width(); } template <typename Dtype> void CenterGridOutputLayer<Dtype>::Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { CHECK_EQ(bottom[0]->num(), bottom[1]->num()); CHECK_EQ(bottom[0]->channels(), bottom[1]->channels()); CHECK_EQ(bottom[0]->channels(), bottom[2]->channels()); // num() and channels() are 1. vector<int> top_shape(2, 1); // Since the number of bboxes to be kept is unknown before nms, we manually // set it to (fake) 1. top_shape.push_back(1); if(has_lm_){ CHECK_GE(bottom[0]->channels(), 14 + num_classes_); top_shape.push_back(17); top[0]->Reshape(top_shape); }else{ CHECK_GE(bottom[0]->channels(), 4 + num_classes_); top_shape.push_back(7); top[0]->Reshape(top_shape); } } template <typename Dtype> void CenterGridOutputLayer<Dtype>::Forward_cpu( const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { bottom_size_ = bottom.size(); results_.clear(); for(int t = 0; t < bottom_size_; t++){ Dtype *channel_pred_data = bottom[t]->mutable_cpu_data(); const int output_height = bottom[t]->height(); const int output_width = bottom[t]->width(); assert(output_height == output_width); const float downRatio = (float)net_width_ / output_width; num_ = bottom[t]->num(); int num_channels = bottom[t]->channels(); if(class_type_ == DetectionOutputParameter_CLASS_TYPE_SIGMOID){ GetCenterGridObjectResultSigmoid(num_, num_channels, num_classes_, output_width, output_height, downRatio, channel_pred_data, anchor_scale_[t], confidence_threshold_, &results_); }else if(class_type_ == DetectionOutputParameter_CLASS_TYPE_SOFTMAX){ GetCenterGridObjectResultSoftMax(num_, num_channels, num_classes_, output_width, output_height, downRatio, channel_pred_data, anchor_scale_[t], confidence_threshold_, &results_, has_lm_); }else { LOG(FATAL)<<"unknown class type"; } } int num_kept = 0; // nms 去除多余的框 std::map<int, vector<CenterNetInfo > > ::iterator iter; for(iter = results_.begin(); iter!= results_.end(); iter++){ std::sort(iter->second.begin(), iter->second.end(), GridCompareScore); std::vector<CenterNetInfo> temp_result = iter->second; std::vector<CenterNetInfo> nms_result; hard_nms(temp_result, &nms_result, nms_thresh_); int num_det = nms_result.size(); #if 1 if(keep_top_k_ > 0 && num_det > keep_top_k_){ std::sort(nms_result.begin(), nms_result.end(), GridCompareScore); nms_result.resize(keep_top_k_); num_kept += keep_top_k_; }else{ num_kept += num_det; } #else num_kept += num_det; #endif iter->second.clear(); for(unsigned ii = 0; ii < nms_result.size(); ii++){ iter->second.push_back(nms_result[ii]); } } vector<int> top_shape(2, 1); top_shape.push_back(num_kept); if(has_lm_) top_shape.push_back(17); else top_shape.push_back(7); Dtype* top_data; if (num_kept == 0) { top_shape[2] = num_; top[0]->Reshape(top_shape); top_data = top[0]->mutable_cpu_data(); caffe_set<Dtype>(top[0]->count(), -1, top_data); // Generate fake results per image. for (int i = 0; i < num_; ++i) { top_data[0] = i; if(has_lm_) top_data += 17; else top_data += 7; } } else { top[0]->Reshape(top_shape); top_data = top[0]->mutable_cpu_data(); } // 保存生成新的结果 int count = 0; for(int i = 0; i < num_; i++){ if(results_.find(i)!= results_.end()){ std::vector<CenterNetInfo > result_temp = results_.find(i)->second; for(unsigned j = 0; j < result_temp.size(); ++j){ if(has_lm_){ top_data[count * 17] = i; top_data[count * 17 + 1] = result_temp[j].class_id() + 1; top_data[count * 17 + 2] = result_temp[j].score(); top_data[count * 17 + 3] = result_temp[j].xmin() / net_width_; top_data[count * 17 + 4] = result_temp[j].ymin() / net_height_; top_data[count * 17 + 5] = result_temp[j].xmax() / net_width_; top_data[count * 17 + 6] = result_temp[j].ymax() / net_height_; top_data[count * 17 + 7] = result_temp[j].marks().lefteye().x() / net_width_; top_data[count * 17 + 8] = result_temp[j].marks().lefteye().y() / net_height_; top_data[count * 17 + 9] = result_temp[j].marks().righteye().x() / net_width_; top_data[count * 17 + 10] = result_temp[j].marks().righteye().y() / net_height_; top_data[count * 17 + 11] = result_temp[j].marks().nose().x() / net_width_; top_data[count * 17 + 12] = result_temp[j].marks().nose().y() / net_height_; top_data[count * 17 + 13] = result_temp[j].marks().leftmouth().x() / net_width_; top_data[count * 17 + 14] = result_temp[j].marks().leftmouth().y() / net_height_; top_data[count * 17 + 15] = result_temp[j].marks().rightmouth().x() / net_width_; top_data[count * 17 + 16] = result_temp[j].marks().rightmouth().y() / net_height_; }else{ top_data[count * 7] = i; top_data[count * 7 + 1] = result_temp[j].class_id() + 1; top_data[count * 7 + 2] = result_temp[j].score(); top_data[count * 7 + 3] = result_temp[j].xmin() / net_width_; top_data[count * 7 + 4] = result_temp[j].ymin() / net_height_; top_data[count * 7 + 5] = result_temp[j].xmax() / net_width_; top_data[count * 7 + 6] = result_temp[j].ymax() / net_height_; } ++count; } } } } #ifdef CPU_ONLY STUB_GPU_FORWARD(CenterGridOutputLayer, Forward); #endif INSTANTIATE_CLASS(CenterGridOutputLayer); REGISTER_LAYER_CLASS(CenterGridOutput); } // namespace caffe ======================= File: src/caffe/layers/ccpd_data_layer.cpp ======================= <reponame>yuqj1990/deepano_train<gh_stars>10-100 #ifdef USE_OPENCV #include <opencv2/core/core.hpp> #endif // USE_OPENCV #include <stdint.h> #include <algorithm> #include <map> #include <vector> #include "caffe/data_transformer.hpp" #include "caffe/layers/ccpd_data_layer.hpp" #include "caffe/util/benchmark.hpp" namespace caffe{ template <typename Dtype> ccpdDataLayer<Dtype>::ccpdDataLayer(const LayerParameter & param) : BasePrefetchingDataLayer<Dtype>(param), reader_(param){ } template <typename Dtype> ccpdDataLayer<Dtype>::~ccpdDataLayer(){ this->StopInternalThread(); } template <typename Dtype> void ccpdDataLayer<Dtype>::DataLayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top){ const int batch_size = this->layer_param_.data_param().batch_size(); // Make sure dimension is consistent within batch. const TransformationParameter& transform_param = this->layer_param_.transform_param(); if (transform_param.has_resize_param()) { if (transform_param.resize_param().resize_mode() == ResizeParameter_Resize_mode_FIT_SMALL_SIZE) { CHECK_EQ(batch_size, 1) << "Only support batch size of 1 for FIT_SMALL_SIZE."; } } // Read a data point, and use it to initialize the top blob. AnnotatedCCpdDatum& anno_datum = *(reader_.full().peek()); // Use data_transformer to infer the expected blob shape from anno_datum. vector<int> top_shape = this->data_transformer_->InferBlobShape(anno_datum.datum()); this->transformed_data_.Reshape(top_shape); // Reshape top[0] and prefetch_data according to the batch_size. top_shape[0] = batch_size; top[0]->Reshape(top_shape); for (int i = 0; i < this->PREFETCH_COUNT; ++i) { this->prefetch_[i].data_.Reshape(top_shape); } LOG(INFO) << "output data size: " << top[0]->num() << "," << top[0]->channels() << "," << top[0]->height() << "," << top[0]->width(); // label if (this->output_labels_) { has_anno_type_ = anno_datum.has_type(); vector<int> label_shape(2, 1); if (has_anno_type_) { anno_type_ = anno_datum.type(); if (anno_type_ == AnnotatedCCpdDatum_AnnotationType_CCPD) { // Since the number of lanmarks of one person can be constant for each image, // and another point is each image only have one person face, so we store the lable // in a specific formate. In specific: label_shape[0] = batch_size; label_shape[1] = 7; } else { LOG(FATAL) << "Unknown annotation type."; } } else { label_shape[0] = batch_size; } top[1]->Reshape(label_shape); for (int i = 0; i < this->PREFETCH_COUNT; ++i) { this->prefetch_[i].label_.Reshape(label_shape); } } } // This function is called on prefetch thread template<typename Dtype> void ccpdDataLayer<Dtype>::load_batch(Batch<Dtype>* batch) { CPUTimer batch_timer; batch_timer.Start(); double read_time = 0; double trans_time = 0; CPUTimer timer; CHECK(batch->data_.count()); CHECK(this->transformed_data_.count()); // Reshape according to the first datum of each batch // on single input batches allows for inputs of varying dimension. const int batch_size = this->layer_param_.data_param().batch_size(); const TransformationParameter& transform_param = this->layer_param_.transform_param(); AnnotatedCCpdDatum& anno_datum = *(reader_.full().peek()); // Use data_transformer to infer the expected blob shape from datum. vector<int> top_shape = this->data_transformer_->InferBlobShape(anno_datum.datum()); this->transformed_data_.Reshape(top_shape); // Reshape batch according to the batch_size. top_shape[0] = batch_size; batch->data_.Reshape(top_shape); Dtype* top_data = batch->data_.mutable_cpu_data(); Dtype* top_label = NULL; // suppress warnings about uninitialized variables // Store transformed annotation. map<int, LicensePlate > all_anno; if (this->output_labels_ &&!has_anno_type_) { top_label = batch->label_.mutable_cpu_data(); } for (int item_id = 0; item_id < batch_size; ++item_id) { timer.Start(); // get a anno_datum AnnotatedCCpdDatum& anno_datum = *(reader_.full().pop("Waiting for data")); #if 0 LOG(INFO)<<" START READ RAW ANNODATUM================================================="; LOG(INFO) <<" chi: "<<anno_datum.lpnumber().chichracter()<<" eng: "<<anno_datum.lpnumber().engchracter() <<" let1: "<<anno_datum.lpnumber().letternum_1()<<" let2: "<<anno_datum.lpnumber().letternum_2() <<" let3: "<<anno_datum.lpnumber().letternum_3()<<" let4: "<<anno_datum.lpnumber().letternum_4(); LOG(INFO)<<" END READ RAW ANNODATUM+++++++++++++++++++++++++++++++++++++++++++++++++++"; #endif AnnotatedCCpdDatum distort_datum; AnnotatedCCpdDatum* expand_datum = NULL; if (transform_param.has_distort_param()) { distort_datum.CopyFrom(anno_datum); this->data_transformer_->DistortImage(anno_datum.datum(), distort_datum.mutable_datum()); if (transform_param.has_expand_param()) { expand_datum = new AnnotatedCCpdDatum(); this->data_transformer_->ExpandImage(distort_datum, expand_datum); } else { expand_datum = &distort_datum; } } else { if (transform_param.has_expand_param()) { expand_datum = new AnnotatedCCpdDatum(); this->data_transformer_->ExpandImage(anno_datum, expand_datum); } else { expand_datum = &anno_datum; } } timer.Start(); vector<int> shape = this->data_transformer_->InferBlobShape(expand_datum->datum()); if (transform_param.has_resize_param()) { if (transform_param.resize_param().resize_mode() == ResizeParameter_Resize_mode_FIT_SMALL_SIZE) { this->transformed_data_.Reshape(shape); batch->data_.Reshape(shape); top_data = batch->data_.mutable_cpu_data(); } else { CHECK(std::equal(top_shape.begin() + 1, top_shape.begin() + 4, shape.begin() + 1)); } } else { CHECK(std::equal(top_shape.begin() + 1, top_shape.begin() + 4, shape.begin() + 1)); } read_time += timer.MicroSeconds(); // Apply data transformations (mirror, scale, crop...) int offset = batch->data_.offset(item_id); this->transformed_data_.set_cpu_data(top_data + offset); LicensePlate transformed_anno_vec; if (this->output_labels_) { if (has_anno_type_) { // Transform datum and annotation_group at the same time this->data_transformer_->Transform(*expand_datum, &(this->transformed_data_), &transformed_anno_vec); all_anno[item_id] = transformed_anno_vec; } else { this->data_transformer_->Transform(expand_datum->datum(), &(this->transformed_data_)); // Otherwise, store the label from datum. // CHECK(expand_datum->datum().has_label()) << "Cannot find any label."; // top_label[item_id] = expand_datum->datum().label(); } } else { this->data_transformer_->Transform(expand_datum->datum(), &(this->transformed_data_)); } // clear memory if (transform_param.has_expand_param()) { delete expand_datum; } trans_time += timer.MicroSeconds(); reader_.free().push(const_cast<AnnotatedCCpdDatum*>(&anno_datum)); } // store "rich " landmark, face attributes if (this->output_labels_ && has_anno_type_) { vector<int> label_shape(2); if (anno_type_ == AnnotatedCCpdDatum_AnnotationType_CCPD) { // Reshape the label and store the annotation. label_shape[0] = batch_size; label_shape[1] = 7; batch->label_.Reshape(label_shape); top_label = batch->label_.mutable_cpu_data(); int idx = 0; for (int item_id = 0; item_id < batch_size; ++item_id) { LicensePlate lp = all_anno[item_id]; top_label[idx++] = lp.chichracter(); top_label[idx++] = lp.engchracter(); top_label[idx++] = lp.letternum_1(); top_label[idx++] = lp.letternum_2(); top_label[idx++] = lp.letternum_3(); top_label[idx++] = lp.letternum_4(); top_label[idx++] = lp.letternum_5(); } } else { LOG(FATAL) << "Unknown annotation type."; } } #if 0 const Dtype* top_label_data = batch->label_.cpu_data(); for(int ii=0; ii < batch_size; ii++) { int id = ii*7; LOG(INFO) <<" chi: "<<top_label_data[id+0] <<" eng: "<<top_label_data[id+1]<<" let1: "<<top_label_data[id+2]<<" let2: "<<top_label_data[id+3] <<" let3: "<<top_label_data[id+4]<<" let4: "<<top_label_data[id+5] <<" let5: "<<top_label_data[id+6]; } LOG(INFO)<< "finished **************************************************** end "; #endif timer.Stop(); batch_timer.Stop(); DLOG(INFO) << "Prefetch batch: " << batch_timer.MilliSeconds() << " ms."; DLOG(INFO) << " Read time: " << read_time / 1000 << " ms."; DLOG(INFO) << "Transform time: " << trans_time / 1000 << " ms."; } INSTANTIATE_CLASS(ccpdDataLayer); REGISTER_LAYER_CLASS(ccpdData); } //namespace caffe ======================= File: src/caffe/util/center_bbox_util.cpp ======================= #include <algorithm> #include <csignal> #include <ctime> #include <functional> #include <map> #include <set> #include <string> #include <utility> #include <vector> #include "boost/iterator/counting_iterator.hpp" #include "caffe/util/bbox_util.hpp" #include "caffe/util/center_util.hpp" #include "caffe/util/center_bbox_util.hpp" #define GET_VALID_VALUE(value, min, max) ((((value) >= (min)? (value) : (min)) < (max)? ((value) >= (min)? (value) : (min)): (max))) int count_gt = 0; int count_one = 0; namespace caffe { template <typename Dtype> void _nms_heatmap(const Dtype* conf_data, Dtype* keep_max_data, const int output_height , const int output_width, const int channels, const int num_batch){ int dim = num_batch * channels * output_height * output_width; for(int ii = 0; ii < dim; ii++){ keep_max_data[ii] = (keep_max_data[ii] == conf_data[ii])? keep_max_data[ii] : Dtype(0.); } } template void _nms_heatmap(const float* conf_data, float* keep_max_data, const int output_height , const int output_width, const int channels, const int num_batch); template void _nms_heatmap(const double* conf_data, double* keep_max_data, const int output_height , const int output_width, const int channels, const int num_batch); void hard_nms(std::vector<CenterNetInfo>& input, std::vector<CenterNetInfo>* output, float nmsthreshold,int type){ if (input.empty()) { return; } std::sort(input.begin(), input.end(), [](const CenterNetInfo& a, const CenterNetInfo& b) { return a.score() > b.score(); }); float IOU = 0.f; float maxX = 0.f; float maxY = 0.f; float minX = 0.f; float minY = 0.f; std::vector<int> vPick; std::vector<pair<float, int> > vScores; const int num_boxes = input.size(); for (int i = 0; i < num_boxes; ++i) { vScores.push_back(std::pair<float, int>(input[i].score(), i)); } while (vScores.size()!= 0) { const int idx = vScores.front().second; bool keep = true; for (int k = 0; k < vPick.size(); ++k) { if (keep) { const int kept_idx = vPick[k]; maxX = std::max(input[idx].xmin(), input[kept_idx].xmin()); maxY = std::max(input[idx].ymin(), input[kept_idx].ymin()); minX = std::min(input[idx].xmax(), input[kept_idx].xmax()); minY = std::min(input[idx].ymax(), input[kept_idx].ymax()); //maxX1 and maxY1 reuse maxX = ((minX - maxX + 1) > 0)? (minX - maxX + 1) : 0; maxY = ((minY - maxY + 1) > 0)? (minY - maxY + 1) : 0; //IOU reuse for the area of two bbox IOU = maxX * maxY; if (type==NMS_UNION) IOU = IOU / (input[idx].area() + input[kept_idx].area() - IOU); else if (type == NMS_MIN) { IOU = IOU / ((input[idx].area() < input[kept_idx].area())? input[idx].area() : input[kept_idx].area()); } keep = IOU <= nmsthreshold; } else { break; } } if (keep) { vPick.push_back(idx); } vScores.erase(vScores.begin()); } for (unsigned i = 0; i < vPick.size(); i++) { output->push_back(input[vPick[i]]); } } void soft_nms(std::vector<CenterNetInfo>& input, std::vector<CenterNetInfo>* output, float sigma, float Nt, float threshold, unsigned int type){ unsigned int numBoxes = input.size(); float iw, ih; float ua; int pos = 0; float maxscore = 0; int maxpos = 0; float x1,x2,y1,y2,tx1,tx2,ty1,ty2,ts,area,weight,ov; for(int ii = 0; ii < numBoxes; ii++){ maxscore = input[ii].score(); maxpos = ii; tx1 = input[ii].xmin(); ty1 = input[ii].ymin(); tx2 = input[ii].xmax(); ty2 = input[ii].ymax(); ts = input[ii].score(); pos = ii + 1; while(pos < numBoxes){ if(maxscore < input[pos].score()){ maxscore = input[pos].score(); maxpos = pos; } pos = pos + 1; } // add max box as a detection input[ii].set_xmin(input[maxpos].xmin()); input[ii].set_xmax(input[maxpos].xmax()); input[ii].set_ymin(input[maxpos].ymin()); input[ii].set_ymax(input[maxpos].ymax()); input[ii].set_score(input[maxpos].score()); input[maxpos].set_xmin(tx1); input[maxpos].set_xmax(tx2); input[maxpos].set_ymin(ty1); input[maxpos].set_ymax(ty2); input[maxpos].set_score(ts); tx1 = input[ii].xmin(); ty1 = input[ii].ymin(); tx2 = input[ii].xmax(); ty2 = input[ii].ymax(); ts = input[ii].score(); pos = ii + 1; // NMS iterations, note that N changes if detection boxes fall below threshold while(pos < numBoxes){ x1 = input[pos].xmin(); y1 = input[pos].ymin(); x2 = input[pos].xmax(); y2 = input[pos].ymax(); //s = input[pos].score(); area = (x2 - x1 + 1) * (y2 - y1 + 1); iw = (std::min(tx2, x2) - std::max(tx1, x1) + 1); if(iw > 0){ ih = (std::min(ty2, y2) - std::max(ty1, y1) + 1); if(ih > 0){ ua = float((tx2 - tx1 + 1) * (ty2 - ty1 + 1) + area - iw * ih); ov = (float) iw * ih / ua ;// iou between max box and detection box if(type == 1) {// linear if(ov > Nt) weight = 1 - ov; else weight = 1; } else if(type == 2) // gaussian weight = std::exp( -1 * (float)(ov * ov)/sigma); else{ if(ov > Nt) weight = 0; else weight = 1; } input[pos].set_score(weight * input[pos].score()); //if box score falls below threshold, discard the box by swapping with last box //update numBoxes if(input[pos].score() < threshold){ input[pos].set_xmin(input[numBoxes - 1].xmin()); input[pos].set_xmax(input[numBoxes - 1].xmax()); input[pos].set_ymin(input[numBoxes - 1].ymin()); input[pos].set_ymax(input[numBoxes - 1].ymax()); input[pos].set_score(input[numBoxes - 1].score()); numBoxes = numBoxes - 1; pos = pos - 1; } } } pos = pos + 1; } } for(int ii = 0; ii < numBoxes; ii++){ output->push_back(input[ii]); } } void check_box_value(NormalizedBBox box){ CHECK_LE(box.xmin(), 1.); CHECK_LE(box.xmax(), 1.); CHECK_LE(box.ymin(), 1.); CHECK_LE(box.ymax(), 1.); CHECK_GE(box.xmin(), 0.); CHECK_GE(box.xmax(), 0.); CHECK_GE(box.ymin(), 0.); CHECK_GE(box.ymax(), 0.); } void check_landmarks_value(AnnoFaceLandmarks lmarks){ CHECK_LE(lmarks.lefteye().x(), 1.); CHECK_LE(lmarks.lefteye().y(), 1.); CHECK_LE(lmarks.righteye().x(), 1.); CHECK_LE(lmarks.righteye().y(), 1.); CHECK_LE(lmarks.nose().x(), 1.); CHECK_LE(lmarks.nose().y(), 1.); CHECK_LE(lmarks.leftmouth().x(), 1.); CHECK_LE(lmarks.leftmouth().y(), 1.); CHECK_LE(lmarks.rightmouth().x(), 1.); CHECK_LE(lmarks.rightmouth().y(), 1.); CHECK_GE(lmarks.lefteye().x(), 0.); CHECK_GE(lmarks.lefteye().y(), 0.); CHECK_GE(lmarks.righteye().x(), 0.); CHECK_GE(lmarks.righteye().y(), 0.); CHECK_GE(lmarks.nose().x(), 0.); CHECK_GE(lmarks.nose().y(), 0.); CHECK_GE(lmarks.leftmouth().x(), 0.); CHECK_GE(lmarks.leftmouth().y(), 0.); CHECK_GE(lmarks.rightmouth().x(), 0.); CHECK_GE(lmarks.rightmouth().y(), 0.); } template <typename Dtype> void EncodeTruthAndPredictions(Dtype* gt_loc_offest_data, Dtype* pred_loc_offest_data, Dtype* gt_loc_wh_data, Dtype* pred_loc_wh_data, Dtype* gt_lm_data, Dtype* pred_lm_data, const int output_width, const int output_height, bool share_location, const Dtype* channel_loc_data, const int num_channels, const std::map<int, vector<std::pair<NormalizedBBox, AnnoFaceLandmarks> > >& all_gt_bboxes, bool has_lm){ CHECK_EQ(share_location, true); int dimScale = output_height * output_width; int count = 0; int lm_count = 0; if(has_lm){ CHECK_EQ(num_channels, 14); }else{ CHECK_EQ(num_channels, 4); } for(auto iter = all_gt_bboxes.begin(); iter!= all_gt_bboxes.end(); iter++){ int batch_id = iter->first; vector<std::pair<NormalizedBBox, AnnoFaceLandmarks> > gt_bboxes = iter->second; for(unsigned ii = 0; ii < gt_bboxes.size(); ii++){ check_box_value(gt_bboxes[ii].first); const Dtype xmin = gt_bboxes[ii].first.xmin() * output_width; const Dtype ymin = gt_bboxes[ii].first.ymin() * output_height; const Dtype xmax = gt_bboxes[ii].first.xmax() * output_width; const Dtype ymax = gt_bboxes[ii].first.ymax() * output_height; Dtype center_x = Dtype((xmin + xmax) / 2); Dtype center_y = Dtype((ymin + ymax) / 2); int inter_center_x = static_cast<int> (center_x); int inter_center_y = static_cast<int> (center_y); Dtype diff_x = center_x - inter_center_x; Dtype diff_y = center_y - inter_center_y; Dtype width = xmax - xmin; Dtype height = ymax - ymin; if(width * height * 4 * 4 <= 8 * 8) continue; int x_index = batch_id * num_channels * dimScale + 0 * dimScale + inter_center_y * output_width + inter_center_x; int y_index = batch_id * num_channels * dimScale + 1 * dimScale + inter_center_y * output_width + inter_center_x; int width_index = batch_id * num_channels * dimScale + 2 * dimScale + inter_center_y * output_width + inter_center_x; int height_index = batch_id * num_channels * dimScale + 3 * dimScale + inter_center_y * output_width + inter_center_x; gt_loc_offest_data[count * 2 + 0] = diff_x; gt_loc_offest_data[count * 2 + 1] = diff_y; gt_loc_wh_data[count * 2 + 0] = std::log(width); gt_loc_wh_data[count * 2 + 1] = std::log(height); pred_loc_offest_data[count * 2 + 0] = channel_loc_data[x_index]; pred_loc_offest_data[count * 2 + 1] = channel_loc_data[y_index]; pred_loc_wh_data[count * 2 + 0] = channel_loc_data[width_index]; pred_loc_wh_data[count * 2 + 1] = channel_loc_data[height_index]; ++count; if(has_lm){ //lm_gt_datas, & lm_pred_datas if(gt_bboxes[ii].second.lefteye().x() > 0 && gt_bboxes[ii].second.lefteye().y() > 0 && gt_bboxes[ii].second.righteye().x() > 0 && gt_bboxes[ii].second.righteye().y() > 0 && gt_bboxes[ii].second.nose().x() > 0 && gt_bboxes[ii].second.nose().y() > 0 && gt_bboxes[ii].second.leftmouth().x() > 0 && gt_bboxes[ii].second.leftmouth().y() > 0 && gt_bboxes[ii].second.rightmouth().x() > 0 && gt_bboxes[ii].second.rightmouth().y() > 0){ check_landmarks_value(gt_bboxes[ii].second); gt_lm_data[lm_count * 10 + 0] = Dtype((gt_bboxes[ii].second.lefteye().x() * output_width - inter_center_x) / width); gt_lm_data[lm_count * 10 + 1] = Dtype((gt_bboxes[ii].second.lefteye().y() * output_height - inter_center_y) / height); gt_lm_data[lm_count * 10 + 2] = Dtype((gt_bboxes[ii].second.righteye().x() * output_width - inter_center_x) / width); gt_lm_data[lm_count * 10 + 3] = Dtype((gt_bboxes[ii].second.righteye().y() * output_height - inter_center_y) / height); gt_lm_data[lm_count * 10 + 4] = Dtype((gt_bboxes[ii].second.nose().x() * output_width - inter_center_x) / width); gt_lm_data[lm_count * 10 + 5] = Dtype((gt_bboxes[ii].second.nose().y() * output_height - inter_center_y) / height); gt_lm_data[lm_count * 10 + 6] = Dtype((gt_bboxes[ii].second.leftmouth().x() * output_width - inter_center_x) / width); gt_lm_data[lm_count * 10 + 7] = Dtype((gt_bboxes[ii].second.leftmouth().y() * output_height - inter_center_y) / height); gt_lm_data[lm_count * 10 + 8] = Dtype((gt_bboxes[ii].second.rightmouth().x() * output_width - inter_center_x) / width); gt_lm_data[lm_count * 10 + 9] = Dtype((gt_bboxes[ii].second.rightmouth().y() * output_height - inter_center_y) / height); int le_x_index = batch_id * num_channels * dimScale + 4 * dimScale + inter_center_y * output_width + inter_center_x; int le_y_index = batch_id * num_channels * dimScale + 5 * dimScale + inter_center_y * output_width + inter_center_x; int re_x_index = batch_id * num_channels * dimScale + 6 * dimScale + inter_center_y * output_width + inter_center_x; int re_y_index = batch_id * num_channels * dimScale + 7 * dimScale + inter_center_y * output_width + inter_center_x; int no_x_index = batch_id * num_channels * dimScale + 8 * dimScale + inter_center_y * output_width + inter_center_x; int no_y_index = batch_id * num_channels * dimScale + 9 * dimScale + inter_center_y * output_width + inter_center_x; int lm_x_index = batch_id * num_channels * dimScale + 10 * dimScale + inter_center_y * output_width + inter_center_x; int lm_y_index = batch_id * num_channels * dimScale + 11 * dimScale + inter_center_y * output_width + inter_center_x; int rm_x_index = batch_id * num_channels * dimScale + 12 * dimScale + inter_center_y * output_width + inter_center_x; int rm_y_index = batch_id * num_channels * dimScale + 13 * dimScale + inter_center_y * output_width + inter_center_x; pred_lm_data[lm_count * 10 + 0] = channel_loc_data[le_x_index]; pred_lm_data[lm_count * 10 + 1] = channel_loc_data[le_y_index]; pred_lm_data[lm_count * 10 + 2] = channel_loc_data[re_x_index]; pred_lm_data[lm_count * 10 + 3] = channel_loc_data[re_y_index]; pred_lm_data[lm_count * 10 + 4] = channel_loc_data[no_x_index]; pred_lm_data[lm_count * 10 + 5] = channel_loc_data[no_y_index]; pred_lm_data[lm_count * 10 + 6] = channel_loc_data[lm_x_index]; pred_lm_data[lm_count * 10 + 7] = channel_loc_data[lm_y_index]; pred_lm_data[lm_count * 10 + 8] = channel_loc_data[rm_x_index]; pred_lm_data[lm_count * 10 + 9] = channel_loc_data[rm_y_index]; ++lm_count; } } } } } template void EncodeTruthAndPredictions(float* gt_loc_offest_data, float* pred_loc_offest_data, float* gt_loc_wh_data, float* pred_loc_wh_data, float* gt_lm_data, float* pred_lm_data, const int output_width, const int output_height, bool share_location, const float* channel_loc_data, const int num_channels, const std::map<int, vector<std::pair<NormalizedBBox, AnnoFaceLandmarks> > >& all_gt_bboxes, bool has_lm); template void EncodeTruthAndPredictions(double* gt_loc_offest_data, double* pred_loc_offest_data, double* gt_loc_wh_data, double* pred_loc_wh_data, double* gt_lm_data, double* pred_lm_data, const int output_width, const int output_height, bool share_location, const double* channel_loc_data, const int num_channels, const std::map<int, vector<std::pair<NormalizedBBox, AnnoFaceLandmarks> > >& all_gt_bboxes, bool has_lm); template <typename Dtype> void CopyDiffToBottom(const Dtype* pre_offset_diff, const Dtype* pre_wh_diff, const int output_width, const int output_height, bool has_lm, const Dtype* lm_pre_diff, bool share_location, Dtype* bottom_diff, const int num_channels, const std::map<int, vector<std::pair<NormalizedBBox, AnnoFaceLandmarks> > >& all_gt_bboxes){ int count = 0; int lm_count = 0; CHECK_EQ(share_location, true); int dimScale = output_height * output_width; if(has_lm){ CHECK_EQ(num_channels, 14); }else{ CHECK_EQ(num_channels, 4); } for(auto iter = all_gt_bboxes.begin(); iter!= all_gt_bboxes.end(); iter++){ int batch_id = iter->first; vector<std::pair<NormalizedBBox, AnnoFaceLandmarks> > gt_bboxes = iter->second; for(unsigned ii = 0; ii < gt_bboxes.size(); ii++){ const Dtype xmin = gt_bboxes[ii].first.xmin() * output_width; const Dtype ymin = gt_bboxes[ii].first.ymin() * output_height; const Dtype xmax = gt_bboxes[ii].first.xmax() * output_width; const Dtype ymax = gt_bboxes[ii].first.ymax() * output_height; Dtype center_x = Dtype((xmin + xmax) / 2); Dtype center_y = Dtype((ymin + ymax) / 2); Dtype width = xmax - xmin; Dtype height = ymax - ymin; if(width * height * 4 * 4 <= 8 * 8) continue; int inter_center_x = static_cast<int> (center_x); int inter_center_y = static_cast<int> (center_y); int x_index = batch_id * num_channels * dimScale + 0 * dimScale + inter_center_y * output_width + inter_center_x; int y_index = batch_id * num_channels * dimScale + 1 * dimScale + inter_center_y * output_width + inter_center_x; int width_index = batch_id * num_channels * dimScale + 2 * dimScale + inter_center_y * output_width + inter_center_x; int height_index = batch_id * num_channels * dimScale + 3 * dimScale + inter_center_y * output_width + inter_center_x; bottom_diff[x_index] = pre_offset_diff[count * 2 + 0]; bottom_diff[y_index] = pre_offset_diff[count * 2 + 1]; bottom_diff[width_index] = pre_wh_diff[count * 2 + 0]; bottom_diff[height_index] = pre_wh_diff[count * 2 + 1]; ++count; if(has_lm){ //lm_gt_datas, & lm_pred_datas if(gt_bboxes[ii].second.lefteye().x() > 0 && gt_bboxes[ii].second.lefteye().y() > 0 && gt_bboxes[ii].second.righteye().x() > 0 && gt_bboxes[ii].second.righteye().y() > 0 && gt_bboxes[ii].second.nose().x() > 0 && gt_bboxes[ii].second.nose().y() > 0 && gt_bboxes[ii].second.leftmouth().x() > 0 && gt_bboxes[ii].second.leftmouth().y() > 0 && gt_bboxes[ii].second.rightmouth().x() > 0 && gt_bboxes[ii].second.rightmouth().y() > 0){ int le_x_index = batch_id * num_channels * dimScale + 4 * dimScale + inter_center_y * output_width + inter_center_x; int le_y_index = batch_id * num_channels * dimScale + 5 * dimScale + inter_center_y * output_width + inter_center_x; int re_x_index = batch_id * num_channels * dimScale + 6 * dimScale + inter_center_y * output_width + inter_center_x; int re_y_index = batch_id * num_channels * dimScale + 7 * dimScale + inter_center_y * output_width + inter_center_x; int no_x_index = batch_id * num_channels * dimScale + 8 * dimScale + inter_center_y * output_width + inter_center_x; int no_y_index = batch_id * num_channels * dimScale + 9 * dimScale + inter_center_y * output_width + inter_center_x; int lm_x_index = batch_id * num_channels * dimScale + 10 * dimScale + inter_center_y * output_width + inter_center_x; int lm_y_index = batch_id * num_channels * dimScale + 11 * dimScale + inter_center_y * output_width + inter_center_x; int rm_x_index = batch_id * num_channels * dimScale + 12 * dimScale + inter_center_y * output_width + inter_center_x; int rm_y_index = batch_id * num_channels * dimScale + 13 * dimScale + inter_center_y * output_width + inter_center_x; bottom_diff[le_x_index] = lm_pre_diff[lm_count * 10 + 0]; bottom_diff[le_y_index] = lm_pre_diff[lm_count * 10 + 1]; bottom_diff[re_x_index] = lm_pre_diff[lm_count * 10 + 2]; bottom_diff[re_y_index] = lm_pre_diff[lm_count * 10 + 3]; bottom_diff[no_x_index] = lm_pre_diff[lm_count * 10 + 4]; bottom_diff[no_y_index] = lm_pre_diff[lm_count * 10 + 5]; bottom_diff[lm_x_index] = lm_pre_diff[lm_count * 10 + 6]; bottom_diff[lm_y_index] = lm_pre_diff[lm_count * 10 + 7]; bottom_diff[rm_x_index] = lm_pre_diff[lm_count * 10 + 8]; bottom_diff[rm_y_index] = lm_pre_diff[lm_count * 10 + 9]; ++lm_count; } } } } } template void CopyDiffToBottom(const float* pre_offset_diff, const float* pre_wh_diff, const int output_width, const int output_height, bool has_lm, const float* lm_pre_diff, bool share_location, float* bottom_diff, const int num_channels, const std::map<int, vector<std::pair<NormalizedBBox, AnnoFaceLandmarks> > >& all_gt_bboxes); template void CopyDiffToBottom(const double* pre_offset_diff, const double* pre_wh_diff,const int output_width, const int output_height, bool has_lm, const double* lm_pre_diff, bool share_location, double* bottom_diff, const int num_channels, const std::map<int, vector<std::pair<NormalizedBBox, AnnoFaceLandmarks> > >& all_gt_bboxes); template <typename Dtype> void get_topK(const Dtype* keep_max_data, const Dtype* loc_data, const int output_height , const int output_width, const int classes, const int num_batch , std::map<int, std::vector<CenterNetInfo > >* results , const int loc_channels, bool has_lm, Dtype conf_thresh, Dtype nms_thresh){ std::vector<CenterNetInfo > batch_result; int dim = classes * output_width * output_height; int dimScale = output_width * output_height; if(has_lm){ CHECK_EQ(loc_channels, 14); }else{ CHECK_EQ(loc_channels, 4); } for(int i = 0; i < num_batch; i++){ std::vector<CenterNetInfo > batch_temp; batch_result.clear(); for(int c = 0 ; c < classes; c++){ for(int h = 0; h < output_height; h++){ for(int w = 0; w < output_width; w++){ int index = i * dim + c * dimScale + h * output_width + w; if(keep_max_data[index] > conf_thresh && keep_max_data[index] < 1){ int x_index = i * loc_channels * dimScale + 0 * dimScale + h * output_width + w; int y_index = i * loc_channels * dimScale + 1 * dimScale + h * output_width + w; int w_index = i * loc_channels * dimScale + 2 * dimScale + h * output_width + w; int h_index = i * loc_channels * dimScale + 3 * dimScale + h * output_width + w; Dtype center_x = (w + loc_data[x_index]) * 4; Dtype center_y = (h + loc_data[y_index]) * 4; Dtype width = std::exp(loc_data[w_index]) * 4 ; Dtype height = std::exp(loc_data[h_index]) * 4 ; Dtype xmin = GET_VALID_VALUE((center_x - Dtype(width / 2)), Dtype(0.f), Dtype(4 * output_width)); Dtype xmax = GET_VALID_VALUE((center_x + Dtype(width / 2)), Dtype(0.f), Dtype(4 * output_width)); Dtype ymin = GET_VALID_VALUE((center_y - Dtype(height / 2)), Dtype(0.f), Dtype(4 * output_height)); Dtype ymax = GET_VALID_VALUE((center_y + Dtype(height / 2)), Dtype(0.f), Dtype(4 * output_height)); CenterNetInfo temp_result; temp_result.set_class_id(c); temp_result.set_score(keep_max_data[index]); temp_result.set_xmin(xmin); temp_result.set_xmax(xmax); temp_result.set_ymin(ymin); temp_result.set_ymax(ymax); temp_result.set_area(width * height); if(has_lm){ int le_x_index = i * loc_channels * dimScale + 4 * dimScale + h * output_width + w; int le_y_index = i * loc_channels * dimScale + 5 * dimScale + h * output_width + w; int re_x_index = i * loc_channels * dimScale + 6 * dimScale + h * output_width + w; int re_y_index = i * loc_channels * dimScale + 7 * dimScale + h * output_width + w; int no_x_index = i * loc_channels * dimScale + 8 * dimScale + h * output_width + w; int no_y_index = i * loc_channels * dimScale + 9 * dimScale + h * output_width + w; int lm_x_index = i * loc_channels * dimScale + 10 * dimScale + h * output_width + w; int lm_y_index = i * loc_channels * dimScale + 11 * dimScale + h * output_width + w; int rm_x_index = i * loc_channels * dimScale + 12 * dimScale + h * output_width + w; int rm_y_index = i * loc_channels * dimScale + 13 * dimScale + h * output_width + w; Dtype bbox_width = xmax - xmin; Dtype bbox_height = ymax - ymin; Dtype le_x = GET_VALID_VALUE((center_x + loc_data[le_x_index] * bbox_width) * 4, Dtype(0.f), Dtype(4 * output_width)); Dtype le_y = GET_VALID_VALUE((center_y + loc_data[le_y_index] * bbox_height) * 4, Dtype(0.f),Dtype(4 * output_height)); Dtype re_x = GET_VALID_VALUE((center_x + loc_data[re_x_index] * bbox_width) * 4, Dtype(0.f), Dtype(4 * output_width)); Dtype re_y = GET_VALID_VALUE((center_y + loc_data[re_y_index] * bbox_height) * 4, Dtype(0.f),Dtype(4 * output_height)); Dtype no_x = GET_VALID_VALUE((center_x + loc_data[no_x_index] * bbox_width) * 4, Dtype(0.f), Dtype(4 * output_width)); Dtype no_y = GET_VALID_VALUE((center_y + loc_data[no_y_index] * bbox_height) * 4, Dtype(0.f),Dtype(4 * output_height)); Dtype lm_x = GET_VALID_VALUE((center_x + loc_data[lm_x_index] * bbox_width) * 4, Dtype(0.f), Dtype(4 * output_width)); Dtype lm_y = GET_VALID_VALUE((center_y + loc_data[lm_y_index] * bbox_height) * 4, Dtype(0.f),Dtype(4 * output_height)); Dtype rm_x = GET_VALID_VALUE((center_x + loc_data[rm_x_index] * bbox_width) * 4, Dtype(0.f), Dtype(4 * output_width)); Dtype rm_y = GET_VALID_VALUE((center_y + loc_data[rm_y_index] * bbox_height) * 4, Dtype(0.f),Dtype(4 * output_height)); temp_result.mutable_marks()->mutable_lefteye()->set_x(le_x); temp_result.mutable_marks()->mutable_lefteye()->set_y(le_y); temp_result.mutable_marks()->mutable_righteye()->set_x(re_x); temp_result.mutable_marks()->mutable_righteye()->set_y(re_y); temp_result.mutable_marks()->mutable_nose()->set_x(no_x); temp_result.mutable_marks()->mutable_nose()->set_y(no_y); temp_result.mutable_marks()->mutable_leftmouth()->set_x(lm_x); temp_result.mutable_marks()->mutable_leftmouth()->set_y(lm_y); temp_result.mutable_marks()->mutable_rightmouth()->set_x(rm_x); temp_result.mutable_marks()->mutable_rightmouth()->set_y(rm_y); } batch_temp.push_back(temp_result); } } } } hard_nms(batch_temp, &batch_result, nms_thresh); for(unsigned j = 0 ; j < batch_result.size(); j++){ batch_result[j].set_xmin(batch_result[j].xmin() / (4 * output_width)); batch_result[j].set_xmax(batch_result[j].xmax() / (4 * output_width)); batch_result[j].set_ymin(batch_result[j].ymin() / (4 * output_height)); batch_result[j].set_ymax(batch_result[j].ymax() / (4 * output_height)); } if(batch_result.size() > 0){ if(results->find(i) == results->end()){ results->insert(std::make_pair(i, batch_result)); }else{ } } } } template void get_topK(const float* keep_max_data, const float* loc_data, const int output_height , const int output_width, const int classes, const int num_batch , std::map<int, std::vector<CenterNetInfo > >* results , const int loc_channels, bool has_lm, float conf_thresh, float nms_thresh); template void get_topK(const double* keep_max_data, const double* loc_data, const int output_height , const int output_width, const int classes, const int num_batch , std::map<int, std::vector<CenterNetInfo > >* results , const int loc_channels, bool has_lm, double conf_thresh, double nms_thresh); template <typename Dtype> void GenerateBatchHeatmap(const std::map<int, vector<std::pair<NormalizedBBox, AnnoFaceLandmarks> > >& all_gt_bboxes, Dtype* gt_heatmap, const int num_classes_, const int output_width, const int output_height){ count_gt = 0; for(auto iter = all_gt_bboxes.begin(); iter!= all_gt_bboxes.end(); iter++){ int batch_id = iter->first; vector<std::pair<NormalizedBBox, AnnoFaceLandmarks> > gt_bboxes = iter->second; for(unsigned ii = 0; ii < gt_bboxes.size(); ii++){ std::vector<Dtype> heatmap((output_width *output_height), Dtype(0.)); const int class_id = gt_bboxes[ii].first.label(); Dtype *classid_heap = gt_heatmap + (batch_id * num_classes_ + (class_id - 1)) * output_width * output_height; const Dtype xmin = gt_bboxes[ii].first.xmin() * output_width; const Dtype ymin = gt_bboxes[ii].first.ymin() * output_height; const Dtype xmax = gt_bboxes[ii].first.xmax() * output_width; const Dtype ymax = gt_bboxes[ii].first.ymax() * output_height; const Dtype width = Dtype(xmax - xmin); const Dtype height = Dtype(ymax - ymin); if(width * height * 4 * 4 <= 8 * 8) continue; Dtype radius = gaussian_radius(height, width, Dtype(0.7)); radius = std::max(0, int(radius)); int center_x = static_cast<int>(Dtype((xmin + xmax) / 2)); int center_y = static_cast<int>(Dtype((ymin + ymax) / 2)); draw_umich_gaussian( heatmap, center_x, center_y, radius, output_height, output_width ); transferCVMatToBlobData(heatmap, classid_heap); count_gt++; } } } template void GenerateBatchHeatmap(const std::map<int, vector<std::pair<NormalizedBBox, AnnoFaceLandmarks> > >& all_gt_bboxes, float* gt_heatmap, const int num_classes_, const int output_width, const int output_height); template void GenerateBatchHeatmap(const std::map<int, vector<std::pair<NormalizedBBox, AnnoFaceLandmarks> > >& all_gt_bboxes, double* gt_heatmap, const int num_classes_, const int output_width, const int output_height); // 置信度得分,用逻辑回归来做,loss_delta梯度值,既前向又后向 template <typename Dtype> void EncodeYoloObject(const int batch_size, const int num_channels, const int num_classes, const int output_width, const int output_height, const int net_width, const int net_height, Dtype* channel_pred_data, const std::map<int, vector<std::pair<NormalizedBBox, AnnoFaceLandmarks> > >& all_gt_bboxes, const std::vector<int> mask_bias, std::vector<std::pair<Dtype, Dtype> >& bias_scale, Dtype* bottom_diff, Dtype ignore_thresh, YoloScoreShow *Score){ CHECK_EQ(net_height, net_width); int stride_channel = 4 + 1 + num_classes; int dimScale = output_height * output_width; float avg_iou = 0; float recall = 0; float recall75 = 0; float avg_cat = 0; float avg_obj = 0; float avg_anyobj = 0; int count = 0; int class_count = 0; CHECK_EQ(num_channels, (5 + num_classes) * mask_bias.size()) << "num_channels shoule be set to including bias_x, bias_y, width, height, object_confidence and classes"; for(int b = 0; b < batch_size; b++){ for(unsigned m = 0; m < mask_bias.size(); m++){ int x_index = b * num_channels * dimScale + (m * stride_channel + 0)* dimScale; for(int i = 0; i < 2 * dimScale; i++) channel_pred_data[x_index + i] = CenterSigmoid(channel_pred_data[x_index + i]); int object_index = b * num_channels * dimScale + (m * stride_channel + 4)* dimScale; for(int i = 0; i < (num_classes + 1) * dimScale; i++){ channel_pred_data[object_index + i] = CenterSigmoid(channel_pred_data[object_index + i]); } } } for(int b = 0; b < batch_size; b++){ vector<std::pair<NormalizedBBox, AnnoFaceLandmarks> > gt_bboxes = all_gt_bboxes.find(b)->second; for(int h = 0; h < output_height; h++){ for(int w = 0; w < output_width; w++){ for(unsigned m = 0; m < mask_bias.size(); m++){ int x_index = b * num_channels * dimScale + (m * stride_channel + 0)* dimScale + h * output_width + w; int y_index = b * num_channels * dimScale + (m * stride_channel + 1)* dimScale + h * output_width + w; int width_index = b * num_channels * dimScale + (m * stride_channel + 2)* dimScale + h * output_width + w; int height_index = b * num_channels * dimScale + (m * stride_channel + 3)* dimScale + h * output_width + w; int object_index = b * num_channels * dimScale + (m * stride_channel + 4)* dimScale + h * output_width + w; NormalizedBBox predBox; float bb_center_x = (channel_pred_data[x_index] + w) / output_width; float bb_center_y = (channel_pred_data[y_index] + h) / output_height; float bb_width = (float)std::exp(channel_pred_data[width_index]) * bias_scale[mask_bias[m]].first / net_width; float bb_height = (float)std::exp(channel_pred_data[height_index]) * bias_scale[mask_bias[m]].second / net_height; predBox.set_xmin(bb_center_x - bb_width / 2); predBox.set_xmax(bb_center_x + bb_width / 2); predBox.set_ymin(bb_center_y - bb_height / 2); predBox.set_ymax(bb_center_y + bb_height / 2); float best_iou = 0; for(unsigned ii = 0; ii < gt_bboxes.size(); ii++){ float iou = YoloBBoxIou(predBox, gt_bboxes[ii].first); if (iou > best_iou) { best_iou = iou; } } avg_anyobj += channel_pred_data[object_index]; bottom_diff[object_index] = (-1) * (0 - channel_pred_data[object_index]); if(best_iou > ignore_thresh){ bottom_diff[object_index] = 0; } } } } for(unsigned ii = 0; ii < gt_bboxes.size(); ii++){ const Dtype xmin = gt_bboxes[ii].first.xmin(); const Dtype ymin = gt_bboxes[ii].first.ymin(); const Dtype xmax = gt_bboxes[ii].first.xmax(); const Dtype ymax = gt_bboxes[ii].first.ymax(); float best_iou = 0.f; int best_mask_scale = 0; for(unsigned m = 0; m < bias_scale.size(); m++){ NormalizedBBox anchor_bbox ; NormalizedBBox shfit_gt_bbox; Dtype shift_x_min = 0 - Dtype((xmax - xmin) / 2); Dtype shift_x_max = 0 + Dtype((xmax - xmin) / 2); Dtype shift_y_min = 0 - Dtype((ymax - ymin) / 2); Dtype shift_y_max = 0 + Dtype((ymax - ymin) / 2); shfit_gt_bbox.set_xmin(shift_x_min); shfit_gt_bbox.set_xmax(shift_x_max); shfit_gt_bbox.set_ymin(shift_y_min); shfit_gt_bbox.set_ymax(shift_y_max); Dtype bias_width = bias_scale[m].first; Dtype bias_height = bias_scale[m].second; float bias_xmin = 0 - (float)bias_width / (2 * net_width); float bias_ymin = 0 - (float)bias_height / (2 * net_height); float bias_xmax = 0 + (float)bias_width / (2 * net_width); float bias_ymax = 0 + (float)bias_height / (2 * net_height); anchor_bbox.set_xmin(bias_xmin); anchor_bbox.set_xmax(bias_xmax); anchor_bbox.set_ymin(bias_ymin); anchor_bbox.set_ymax(bias_ymax); float iou = YoloBBoxIou(shfit_gt_bbox, anchor_bbox); if (iou > best_iou){ best_iou = iou; best_mask_scale = m; } } int mask_n = int_index(mask_bias, best_mask_scale, mask_bias.size()); if(mask_n >= 0){ Dtype center_x = Dtype((xmin + xmax) / 2) * output_width; Dtype center_y = Dtype((ymin + ymax) / 2) * output_height; int inter_center_x = static_cast<int> (center_x); int inter_center_y = static_cast<int> (center_y); Dtype diff_x = center_x - inter_center_x; Dtype diff_y = center_y - inter_center_y; Dtype width = std::log((xmax - xmin) * net_width / bias_scale[best_mask_scale].first); Dtype height = std::log((ymax - ymin) * net_height / bias_scale[best_mask_scale].second); int x_index = b * num_channels * dimScale + (mask_n * stride_channel + 0)* dimScale + inter_center_y * output_width + inter_center_x; int y_index = b * num_channels * dimScale + (mask_n * stride_channel + 1)* dimScale + inter_center_y * output_width + inter_center_x; int width_index = b * num_channels * dimScale + (mask_n * stride_channel + 2)* dimScale + inter_center_y * output_width + inter_center_x; int height_index = b * num_channels * dimScale + (mask_n * stride_channel + 3)* dimScale + inter_center_y * output_width + inter_center_x; int object_index = b * num_channels * dimScale + (mask_n * stride_channel + 4)* dimScale + inter_center_y * output_width + inter_center_x; float delta_scale = 2 - (float)(xmax - xmin) * (ymax - ymin); bottom_diff[x_index] = (-1) * delta_scale * (diff_x - channel_pred_data[x_index]); bottom_diff[y_index] = (-1) *delta_scale * (diff_y - channel_pred_data[y_index]); bottom_diff[width_index] = (-1) *delta_scale * (width - channel_pred_data[width_index]); bottom_diff[height_index] = (-1) *delta_scale * (height - channel_pred_data[height_index]); bottom_diff[object_index] = (-1) * (1 - channel_pred_data[object_index]); avg_obj += channel_pred_data[object_index]; // class score // 特殊情况,face数据集,包含了背景目标,而实际上不需要背景目标,所以减一 int class_lable = gt_bboxes[ii].first.label() - 1; int class_index = b * num_channels * dimScale + (mask_n * stride_channel + 5)* dimScale + inter_center_y * output_width + inter_center_x; if ( bottom_diff[class_index]){ bottom_diff[class_index + class_lable * dimScale] = 1 - channel_pred_data[class_index + class_lable * dimScale]; avg_cat += channel_pred_data[class_index + class_lable * dimScale]; }else{ for(int c = 0; c < num_classes; c++){ bottom_diff[class_index + c * dimScale] =(-1) * (((c == class_lable)?1 : 0) - channel_pred_data[class_index + c * dimScale]); if(c == class_lable) avg_cat += channel_pred_data[class_index + c * dimScale]; } } count++; class_count++; NormalizedBBox predBox; float bb_center_x = (channel_pred_data[x_index] + inter_center_x) / output_width; float bb_center_y = (channel_pred_data[y_index] + inter_center_y) / output_height; float bb_width = (float)std::exp(channel_pred_data[width_index]) * bias_scale[best_mask_scale].first / net_width; float bb_height = (float)std::exp(channel_pred_data[height_index]) * bias_scale[best_mask_scale].second / net_height; predBox.set_xmin(bb_center_x - bb_width / 2); predBox.set_xmax(bb_center_x + bb_width / 2); predBox.set_ymin(bb_center_y - bb_height / 2); predBox.set_ymax(bb_center_y + bb_height / 2); float iou = YoloBBoxIou(predBox, gt_bboxes[ii].first); if(iou >.5) recall += 1; if(iou >.75) recall75 += 1; avg_iou += iou; } } } Score->avg_anyobj = avg_anyobj; Score->avg_cat = avg_cat; Score->avg_iou = avg_iou; Score->avg_obj = avg_obj; Score->class_count = class_count; Score->count = count; Score->recall75 =recall75; Score->recall = recall; } template void EncodeYoloObject(const int batch_size, const int num_channels, const int num_classes, const int output_width, const int output_height, const int net_width, const int net_height, float* channel_pred_data, const std::map<int, vector<std::pair<NormalizedBBox, AnnoFaceLandmarks> > >& all_gt_bboxes, const std::vector<int> mask_bias, std::vector<std::pair<float, float> >& bias_scale, float* bottom_diff, float ignore_thresh, YoloScoreShow *Score); template void EncodeYoloObject(const int batch_size, const int num_channels, const int num_classes, const int output_width, const int output_height, const int net_width, const int net_height, double* channel_pred_data, const std::map<int, vector<std::pair<NormalizedBBox, AnnoFaceLandmarks> > >& all_gt_bboxes, const std::vector<int> mask_bias, std::vector<std::pair<double, double> >& bias_scale, double* bottom_diff, double ignore_thresh, YoloScoreShow *Score); template <typename Dtype> void GetYoloGroundTruth(const Dtype* gt_data, int num_gt, const int background_label_id, const bool use_difficult_gt, bool has_lm, std::map<int, vector<std::pair<NormalizedBBox, AnnoFaceLandmarks> > >* all_gt_bboxes, int batch_size){ all_gt_bboxes->clear(); for(int b = 0; b < batch_size; b++){ for (int i = 0; i < num_gt; ++i) { int start_idx = b * num_gt * 8 + i * 8; if(has_lm){ start_idx = b * num_gt * 19 + i * 19; } int item_id = gt_data[start_idx]; if (item_id == -1) { continue; } CHECK_EQ(b,item_id); int label = gt_data[start_idx + 1]; CHECK_NE(background_label_id, label) << "Found background label in the dataset."; bool difficult = static_cast<bool>(gt_data[start_idx + 7]); if (!use_difficult_gt && difficult) { continue; } NormalizedBBox bbox; bbox.set_label(label); bbox.set_xmin(gt_data[start_idx + 3]); bbox.set_ymin(gt_data[start_idx + 4]); bbox.set_xmax(gt_data[start_idx + 5]); bbox.set_ymax(gt_data[start_idx + 6]); bbox.set_difficult(difficult); float bbox_size = BBoxSize(bbox); bbox.set_size(bbox_size); AnnoFaceLandmarks lmarks; if(has_lm){ Dtype bbox_has_lm = gt_data[start_idx + 8]; if(bbox_has_lm > 0){ lmarks.mutable_lefteye()->set_x(gt_data[start_idx + 9]); lmarks.mutable_lefteye()->set_y(gt_data[start_idx + 10]); lmarks.mutable_righteye()->set_x(gt_data[start_idx + 11]); lmarks.mutable_righteye()->set_y(gt_data[start_idx + 12]); lmarks.mutable_nose()->set_x(gt_data[start_idx + 13]); lmarks.mutable_nose()->set_y(gt_data[start_idx + 14]); lmarks.mutable_leftmouth()->set_x(gt_data[start_idx + 15]); lmarks.mutable_leftmouth()->set_y(gt_data[start_idx + 16]); lmarks.mutable_rightmouth()->set_x(gt_data[start_idx + 17]); lmarks.mutable_rightmouth()->set_y(gt_data[start_idx + 18]); }else{ lmarks.mutable_lefteye()->set_x(-1.); lmarks.mutable_lefteye()->set_y(-1.); lmarks.mutable_righteye()->set_x(-1.); lmarks.mutable_righteye()->set_y(-1.); lmarks.mutable_nose()->set_x(-1.); lmarks.mutable_nose()->set_y(-1.); lmarks.mutable_leftmouth()->set_x(-1.); lmarks.mutable_leftmouth()->set_y(-1.); lmarks.mutable_rightmouth()->set_x(-1.); lmarks.mutable_rightmouth()->set_y(-1.); } } (*all_gt_bboxes)[item_id].push_back(std::make_pair(bbox, lmarks)); } } } template void GetYoloGroundTruth(const float* gt_data, int num_gt, const int background_label_id, const bool use_difficult_gt, bool has_lm, std::map<int, vector<std::pair<NormalizedBBox, AnnoFaceLandmarks> > >* all_gt_bboxes, int batch_size); template void GetYoloGroundTruth(const double* gt_data, const int num_gt, const int background_label_id, const bool use_difficult_gt, bool has_lm, std::map<int, vector<std::pair<NormalizedBBox, AnnoFaceLandmarks> > >* all_gt_bboxes, int batch_size); // 每一层使用感受野作为anchor,此anchor只匹配相对应大小范围的gt_boxes, // anchor 生成的方式是按照感受野的大小来生成的,所以每层只有一个感受野大小的anchor, 用于匹配相应的gt_boxes; // anchor 的匹配方式是按照每个anchor中心落在真实框之内匹配呢?,还是直接基于每个格子中心来进行预测呢? // loss -01: loc loss // loss -02: class loss 分类概率, 使用focalloss,对所有负样本进行计算 // 只针对单类物体,二分类物体检测 template <typename Dtype> Dtype EncodeCenterGridObjectSigmoidLoss(const int batch_size, const int num_channels, const int num_classes, const int output_width, const int output_height, const float downRatio, Dtype* channel_pred_data, const int anchor_scale, std::pair<int, int> loc_truth_scale, const std::map<int, vector<std::pair<NormalizedBBox, AnnoFaceLandmarks> > >& all_gt_bboxes, Dtype* class_label, Dtype* bottom_diff, Dtype ignore_thresh, int *count_postive, Dtype *loc_loss_value){ CHECK_EQ(num_classes, 1); int dimScale = output_height * output_width; Dtype score_loss = Dtype(0.), loc_loss = Dtype(0.); CHECK_EQ(num_channels, (4 + num_classes)) << "num_channels shoule be set to including bias_x, bias_y, width, height, classes"; for(int b = 0; b < batch_size; b++){ int object_index = b * num_channels * dimScale + 4 * dimScale; for(int i = 0; i < 1 * dimScale; i++){ channel_pred_data[object_index + i] = CenterSigmoid(channel_pred_data[object_index + i]); } } int postive = 0; caffe_set(batch_size * dimScale, Dtype(0.5f), class_label); for(auto iter =all_gt_bboxes.begin(); iter!= all_gt_bboxes.end(); iter++){ int b = iter->first; std::vector<std::pair<NormalizedBBox, AnnoFaceLandmarks> > gt_bboxes = iter->second; std::vector<int> mask_Rf_anchor(dimScale, 0); int count = 0; for(unsigned ii = 0; ii < gt_bboxes.size(); ii++){ const Dtype xmin = gt_bboxes[ii].first.xmin() * output_width; const Dtype ymin = gt_bboxes[ii].first.ymin() * output_height; const Dtype xmax = gt_bboxes[ii].first.xmax() * output_width; const Dtype ymax = gt_bboxes[ii].first.ymax() * output_height; const int gt_bbox_width = static_cast<int>((xmax - xmin) * downRatio); const int gt_bbox_height = static_cast<int>((ymax - ymin) * downRatio); for(int h = static_cast<int>(ymin); h < static_cast<int>(ymax); h++){ for(int w = static_cast<int>(xmin); w < static_cast<int>(xmax); w++){ int class_index = b * dimScale + h * output_width + w; class_label[class_index] = -10; } } int large_side = std::max(gt_bbox_height, gt_bbox_width); if(large_side >= loc_truth_scale.first && large_side < loc_truth_scale.second){ for(int h = static_cast<int>(ymin); h < static_cast<int>(ymax); h++){ for(int w = static_cast<int>(xmin); w < static_cast<int>(xmax); w++){ if(mask_Rf_anchor[h * output_width + w] == 1) // 避免同一个anchor的中心落在多个gt里面 continue; Dtype xmin_bias = (w + 0.5 - xmin) * downRatio * 2 / anchor_scale; Dtype ymin_bias = (h + 0.5 - ymin) * downRatio * 2 / anchor_scale; Dtype xmax_bias = (w + 0.5 - xmax) * downRatio * 2 / anchor_scale; Dtype ymax_bias = (h + 0.5 - ymax) * downRatio * 2 / anchor_scale; int xmin_index = b * num_channels * dimScale + 0 * dimScale + h * output_width + w; int ymin_index = b * num_channels * dimScale + 1 * dimScale + h * output_width + w; int xmax_index = b * num_channels * dimScale + 2 * dimScale + h * output_width + w; int ymax_index = b * num_channels * dimScale + 3 * dimScale + h * output_width + w; Dtype xmin_diff, ymin_diff, xmax_diff, ymax_diff; loc_loss += smoothL1_Loss(Dtype(channel_pred_data[xmin_index] - xmin_bias), &xmin_diff); loc_loss += smoothL1_Loss(Dtype(channel_pred_data[ymin_index] - ymin_bias), &ymin_diff); loc_loss += smoothL1_Loss(Dtype(channel_pred_data[xmax_index] - xmax_bias), &xmax_diff); loc_loss += smoothL1_Loss(Dtype(channel_pred_data[ymax_index] - ymax_bias), &ymax_diff); bottom_diff[xmin_index] = xmin_diff; bottom_diff[ymin_index] = ymin_diff; bottom_diff[xmax_index] = xmax_diff; bottom_diff[ymax_index] = ymax_diff; // class score // 特殊情况,face数据集,包含了背景目标,而实际上不需要背景目标 int class_index = b * dimScale + h * output_width + w; class_label[class_index] = 1; mask_Rf_anchor[h * output_width + w] = 1; count++; } } } } int gt_class_index = b * dimScale; int pred_class_index = b * num_channels * dimScale + 4* dimScale; score_loss += FocalLossSigmoid(class_label + gt_class_index, channel_pred_data + pred_class_index, dimScale, bottom_diff + pred_class_index); postive += count; } *count_postive = postive; *loc_loss_value = loc_loss; return score_loss; } template float EncodeCenterGridObjectSigmoidLoss(const int batch_size, const int num_channels, const int num_classes, const int output_width, const int output_height, const float downRatio, float* channel_pred_data, const int anchor_scale, std::pair<int, int> loc_truth_scale, const std::map<int, vector<std::pair<NormalizedBBox, AnnoFaceLandmarks> > >& all_gt_bboxes, float* class_label, float* bottom_diff, float ignore_thresh, int *count_postive, float *loc_loss_value); template double EncodeCenterGridObjectSigmoidLoss(const int batch_size, const int num_channels, const int num_classes, const int output_width, const int output_height, const float downRatio, double* channel_pred_data, const int anchor_scale, std::pair<int, int> loc_truth_scale, const std::map<int, vector<std::pair<NormalizedBBox, AnnoFaceLandmarks> > >& all_gt_bboxes, double* class_label, double* bottom_diff, double ignore_thresh, int *count_postive, double *loc_loss_value); template <typename Dtype> void GetCenterGridObjectResultSigmoid(const int batch_size, const int num_channels, const int num_classes, const int output_width, const int output_height, const float downRatio, Dtype* channel_pred_data, const int anchor_scale, Dtype conf_thresh, std::map<int, std::vector<CenterNetInfo > >* results){ // face class 人脸类型 CHECK_EQ(num_classes, 1); CHECK_EQ(num_channels, 4 + num_classes); int dimScale = output_height * output_width; for(int b = 0; b < batch_size; b++){ int object_index = b * num_channels * dimScale + 4 * dimScale; for(int i = 0; i < num_classes * dimScale; i++){ channel_pred_data[object_index + i] = CenterSigmoid(channel_pred_data[object_index + i]); } } for(int b = 0; b < batch_size; b++){ for(int h = 0; h < output_height; h++){ for(int w = 0; w < output_width; w++){ int x_index = b * num_channels * dimScale + 0* dimScale + h * output_width + w; int y_index = b * num_channels * dimScale + 1* dimScale + h * output_width + w; int width_index = b * num_channels * dimScale + 2* dimScale + h * output_width + w; int height_index = b * num_channels * dimScale + 3* dimScale + h * output_width + w; int class_index = b * num_channels * dimScale + 4* dimScale + h * output_width + w; float xmin = 0.f, ymin = 0.f, xmax = 0.f, ymax = 0.f; float bb_xmin = (w + 0.5 - channel_pred_data[x_index] * anchor_scale /(2*downRatio)) *downRatio; float bb_ymin = (h + 0.5 - channel_pred_data[y_index] * anchor_scale /(2*downRatio)) *downRatio; float bb_xmax = (w + 0.5 - channel_pred_data[width_index] * anchor_scale /(2*downRatio)) *downRatio; float bb_ymax = (h + 0.5 - channel_pred_data[height_index] * anchor_scale /(2*downRatio)) *downRatio; xmin = GET_VALID_VALUE(bb_xmin, (0.f), float(downRatio * output_width)); ymin = GET_VALID_VALUE(bb_ymin, (0.f), float(downRatio * output_height)); xmax = GET_VALID_VALUE(bb_xmax, (0.f), float(downRatio * output_width)); ymax = GET_VALID_VALUE(bb_ymax, (0.f), float(downRatio * output_height)); if((xmax - xmin) <= 0 || (ymax - ymin) <= 0) continue; Dtype label_score = channel_pred_data[class_index]; if(label_score >= conf_thresh){ CenterNetInfo temp_result; temp_result.set_class_id(0); temp_result.set_score(label_score); temp_result.set_xmin(xmin); temp_result.set_xmax(xmax); temp_result.set_ymin(ymin); temp_result.set_ymax(ymax); temp_result.set_area((xmax - xmin) * (ymax - ymin)); (*results)[b].push_back(temp_result); } } } } } template void GetCenterGridObjectResultSigmoid(const int batch_size, const int num_channels, const int num_classes, const int output_width, const int output_height, const float downRatio, float* channel_pred_data, const int anchor_scale, float conf_thresh, std::map<int, std::vector<CenterNetInfo > >* results); template void GetCenterGridObjectResultSigmoid(const int batch_size, const int num_channels, const int num_classes, const int output_width, const int output_height, const float downRatio, double* channel_pred_data, const int anchor_scale, double conf_thresh, std::map<int, std::vector<CenterNetInfo > >* results); bool bboxSatisfyEllipise(const int &x, const int &y, const NormalizedBBox & box){ int center_x = static_cast<int>((box.xmin() + box.xmax())/2); int center_y = static_cast<int>((box.ymin() + box.ymax())/2); int box_width = static_cast<int>(box.xmax() - box.xmin()); int box_height = static_cast<int>(box.ymax() - box.ymin()); float judgeValue= std::pow(float((x - center_x) / (box_width + 0.00000001)), 2.) + std::pow(float((y - center_y) / (box_height + 0.00000001)), 2.) - 1; if(judgeValue <= 0) return true; else return false; } template <typename Dtype> Dtype EncodeCenterGridObjectSoftMaxLoss(const int batch_size, const int num_channels, const int num_classes, const int output_width, const int output_height, const float downRatio, std::vector<int>postive_batch, std::vector<Dtype> batch_sample_loss, Dtype* channel_pred_data, const int anchor_scale, std::pair<int, int> loc_truth_scale, const std::map<int, vector<std::pair<NormalizedBBox, AnnoFaceLandmarks> > >& all_gt_bboxes, Dtype* class_label, Dtype* bottom_diff, int *count_postive_lm, int *count_postive, Dtype *loc_loss_value, int *match_num_gt_box, bool has_lm, Dtype* lm_loss_value){ CHECK_EQ(num_classes, 2) << "the current version is just classfly bg_0 and face_1, two class"; int dimScale = output_height * output_width; Dtype score_loss = Dtype(0.), loc_loss = Dtype(0.), lm_loss = Dtype(0.); if(has_lm) CHECK_EQ(num_channels, (14 + num_classes)) << "num_channels shoule be set to including bias_x, bias_y, width, height, classes"; else CHECK_EQ(num_channels, (4 + num_classes)) << "num_channels shoule be set to including 4 points landmarks, &classes"; int postive = 0; int lm_postive = 0; int gt_match_box = 0; SoftmaxCenterGrid(channel_pred_data, batch_size, num_classes, num_channels, output_height, output_width, has_lm); // 将所有值设置为 -2 的原因为,排除掉iou>0.35的一些样本, // 也就是说只采集那些iou<0.35的负样本. // 20200611,舍弃之 #define FOCAL_LOSS_SOFTMAX true #if FOCAL_LOSS_SOFTMAX caffe_set(batch_size * dimScale, Dtype(0.5f), class_label); #else caffe_set(batch_size * dimScale, Dtype(-1.), class_label); #endif int previous_id = -1; for(auto iter =all_gt_bboxes.begin(); iter!= all_gt_bboxes.end(); iter++){ int b = iter->first; if(previous_id == b) LOG(FATAL)<<"preivous_id: "<<previous_id<<", batch_id: "<<b; previous_id = b; std::vector<std::pair<NormalizedBBox, AnnoFaceLandmarks> > gt_bboxes = iter->second; int count = 0; int lm_count = 0; std::vector<int> mask_Rf_anchor_already(dimScale, 0); for(int h = 0; h < output_height; h++){ for(int w = 0; w < output_width; w++){ int bg_index = b * num_channels * dimScale + 4* dimScale + h * output_width + w; int face_index = b * num_channels * dimScale + 5* dimScale + h * output_width + w; if(has_lm){ bg_index = b * num_channels * dimScale + 14* dimScale + h * output_width + w; face_index = b * num_channels * dimScale + 15* dimScale + h * output_width + w; } Dtype class_loss = SingleSoftmaxLoss(channel_pred_data[bg_index], channel_pred_data[face_index], Dtype(-1.)); batch_sample_loss[b * dimScale + h * output_width + w] = class_loss; } } for(unsigned ii = 0; ii < gt_bboxes.size(); ii++){ Dtype xmin = gt_bboxes[ii].first.xmin() * output_width; Dtype ymin = gt_bboxes[ii].first.ymin() * output_height; Dtype xmax = gt_bboxes[ii].first.xmax() * output_width; Dtype ymax = gt_bboxes[ii].first.ymax() * output_height; if ((xmax - xmin) <= 0 || (ymax - ymin) <=0){ LOG(INFO) << "xmin: " << xmin << ", xmax: " << xmax << ", ymin: " << ymin << ", ymax: " << ymax; continue; } for(int h = static_cast<int>(ymin); h < static_cast<int>(ymax); h++){ for(int w = static_cast<int>(xmin); w < static_cast<int>(xmax); w++){ int class_index = b * dimScale + h * output_width + w; class_label[class_index] = -10; } } int gt_bbox_width = static_cast<int>((xmax - xmin) * downRatio); int gt_bbox_height = static_cast<int>((ymax - ymin) * downRatio); NormalizedBBox temp_bbox; temp_bbox.set_xmax(xmax); temp_bbox.set_xmin(xmin); temp_bbox.set_ymax(ymax); temp_bbox.set_ymin(ymin); int large_side = std::max(gt_bbox_height, gt_bbox_width); if(large_side >= loc_truth_scale.first && large_side < loc_truth_scale.second){ for(int h = static_cast<int>(ymin); h < static_cast<int>(ymax); h++){ for(int w = static_cast<int>(xmin); w < static_cast<int>(xmax); w++){ if(mask_Rf_anchor_already[h * output_width + w] == 1) // 避免同一个anchor的中心落在多个gt里面 continue; #define USE_GIOU_LOSS false #if USE_GIOU_LOSS int x_index = b * num_channels * dimScale + 0* dimScale + h * output_width + w; int y_index = b * num_channels * dimScale + 1* dimScale + h * output_width + w; int width_index = b * num_channels * dimScale + 2* dimScale + h * output_width + w; int height_index = b * num_channels * dimScale + 3* dimScale + h * output_width + w; int class_index = b * dimScale + h * output_width + w; Dtype center_x_diff, center_y_diff, width_diff, height_diff; Dtype bb_xmin = (w + 0.5 - channel_pred_data[x_index] * anchor_scale / (downRatio)) *downRatio; Dtype bb_ymin = (h + 0.5 - channel_pred_data[y_index] * anchor_scale / (downRatio)) *downRatio; Dtype bb_xmax = (w + 0.5 - channel_pred_data[width_index] * anchor_scale / (downRatio)) *downRatio; Dtype bb_ymax = (h + 0.5 - channel_pred_data[height_index] * anchor_scale / (downRatio)) *downRatio; NormalizedBBox pred_bbox; pred_bbox.set_xmin(bb_xmin); pred_bbox.set_xmax(bb_xmax); pred_bbox.set_ymin(bb_ymin); pred_bbox.set_ymax(bb_ymax); NormalizedBBox gt_bbox; gt_bbox.set_xmin(xmin * downRatio); gt_bbox.set_xmax(xmax * downRatio); gt_bbox.set_ymin(ymin * downRatio); gt_bbox.set_ymax(ymax * downRatio); loc_loss += GIoULoss(pred_bbox, gt_bbox, &center_x_diff, &center_y_diff, &width_diff, &height_diff); bottom_diff[x_index] = center_x_diff * (-1) * Dtype(anchor_scale); bottom_diff[y_index] = center_y_diff * (-1) * Dtype(anchor_scale); bottom_diff[width_index] = width_diff * (-1) * Dtype(anchor_scale); bottom_diff[height_index] = height_diff * (-1) * Dtype(anchor_scale); #else Dtype xmin_bias = (w + 0.5 - xmin) * downRatio / anchor_scale; Dtype ymin_bias = (h + 0.5 - ymin) * downRatio / anchor_scale; Dtype xmax_bias = (w + 0.5 - xmax) * downRatio / anchor_scale; Dtype ymax_bias = (h + 0.5 - ymax) * downRatio / anchor_scale; int xmin_index = b * num_channels * dimScale + 0* dimScale + h * output_width + w; int ymin_index = b * num_channels * dimScale + 1* dimScale + h * output_width + w; int xmax_index = b * num_channels * dimScale + 2* dimScale + h * output_width + w; int ymax_index = b * num_channels * dimScale + 3* dimScale + h * output_width + w; int class_index = b * dimScale + h * output_width + w; Dtype xmin_diff, ymin_diff, xmax_diff, ymax_diff; loc_loss += smoothL1_Loss(Dtype(channel_pred_data[xmin_index] - xmin_bias), &xmin_diff); loc_loss += smoothL1_Loss(Dtype(channel_pred_data[ymin_index] - ymin_bias), &ymin_diff); loc_loss += smoothL1_Loss(Dtype(channel_pred_data[xmax_index] - xmax_bias), &xmax_diff); loc_loss += smoothL1_Loss(Dtype(channel_pred_data[ymax_index] - ymax_bias), &ymax_diff); bottom_diff[xmin_index] = xmin_diff; bottom_diff[ymin_index] = ymin_diff; bottom_diff[xmax_index] = xmax_diff; bottom_diff[ymax_index] = ymax_diff; #endif if(has_lm){ if(gt_bboxes[ii].second.lefteye().x() > 0 && gt_bboxes[ii].second.lefteye().y() > 0 && gt_bboxes[ii].second.righteye().x() > 0 && gt_bboxes[ii].second.righteye().y() > 0 && gt_bboxes[ii].second.nose().x() > 0 && gt_bboxes[ii].second.nose().y() > 0 && gt_bboxes[ii].second.leftmouth().x() > 0 && gt_bboxes[ii].second.leftmouth().y() > 0 && gt_bboxes[ii].second.rightmouth().x() > 0 && gt_bboxes[ii].second.rightmouth().y() > 0){ check_landmarks_value(gt_bboxes[ii].second); int le_x_index = b * num_channels * dimScale + 4* dimScale + h * output_width + w; int le_y_index = b * num_channels * dimScale + 5* dimScale + h * output_width + w; int re_x_index = b * num_channels * dimScale + 6* dimScale + h * output_width + w; int re_y_index = b * num_channels * dimScale + 7* dimScale + h * output_width + w; int no_x_index = b * num_channels * dimScale + 8* dimScale + h * output_width + w; int no_y_index = b * num_channels * dimScale + 9* dimScale + h * output_width + w; int lm_x_index = b * num_channels * dimScale + 10* dimScale + h * output_width + w; int lm_y_index = b * num_channels * dimScale + 11* dimScale + h * output_width + w; int rm_x_index = b * num_channels * dimScale + 12* dimScale + h * output_width + w; int rm_y_index = b * num_channels * dimScale + 13* dimScale + h * output_width + w; Dtype le_x_bias = (w + 0.5 - gt_bboxes[ii].second.lefteye().x() * output_width) * downRatio / anchor_scale; Dtype le_y_bias = (h + 0.5 - gt_bboxes[ii].second.lefteye().y() * output_height) * downRatio / anchor_scale; Dtype re_x_bias = (w + 0.5 - gt_bboxes[ii].second.righteye().x() * output_width) * downRatio / anchor_scale; Dtype re_y_bias = (h + 0.5 - gt_bboxes[ii].second.righteye().y() * output_height) * downRatio / anchor_scale; Dtype no_x_bias = (w + 0.5 - gt_bboxes[ii].second.nose().x() * output_width) * downRatio / anchor_scale; Dtype no_y_bias = (h + 0.5 - gt_bboxes[ii].second.nose().y() * output_height) * downRatio / anchor_scale; Dtype lm_x_bias = (w + 0.5 - gt_bboxes[ii].second.leftmouth().x() * output_width) * downRatio / anchor_scale; Dtype lm_y_bias = (h + 0.5 - gt_bboxes[ii].second.leftmouth().y() * output_height) * downRatio / anchor_scale; Dtype rm_x_bias = (w + 0.5 - gt_bboxes[ii].second.rightmouth().x() * output_width) * downRatio / anchor_scale; Dtype rm_y_bias = (h + 0.5 - gt_bboxes[ii].second.rightmouth().y() * output_height) * downRatio / anchor_scale; Dtype le_x_diff, le_y_diff, re_x_diff, re_y_diff, no_x_diff, no_y_diff, lm_x_diff, lm_y_diff, rm_x_diff, rm_y_diff; lm_loss += smoothL1_Loss(Dtype(channel_pred_data[le_x_index] - le_x_bias), &le_x_diff); lm_loss += smoothL1_Loss(Dtype(channel_pred_data[le_y_index] - le_y_bias), &le_y_diff); lm_loss += smoothL1_Loss(Dtype(channel_pred_data[re_x_index] - re_x_bias), &re_x_diff); lm_loss += smoothL1_Loss(Dtype(channel_pred_data[re_y_index] - re_y_bias), &re_y_diff); lm_loss += smoothL1_Loss(Dtype(channel_pred_data[no_x_index] - no_x_bias), &no_x_diff); lm_loss += smoothL1_Loss(Dtype(channel_pred_data[no_y_index] - no_y_bias), &no_y_diff); lm_loss += smoothL1_Loss(Dtype(channel_pred_data[lm_x_index] - lm_x_bias), &lm_x_diff); lm_loss += smoothL1_Loss(Dtype(channel_pred_data[lm_y_index] - lm_y_bias), &lm_y_diff); lm_loss += smoothL1_Loss(Dtype(channel_pred_data[rm_x_index] - rm_x_bias), &rm_x_diff); lm_loss += smoothL1_Loss(Dtype(channel_pred_data[rm_y_index] - rm_y_bias), &rm_y_diff); bottom_diff[le_x_index] = le_x_diff; bottom_diff[le_y_index] = le_y_diff; bottom_diff[re_x_index] = re_x_diff; bottom_diff[re_y_index] = re_y_diff; bottom_diff[no_x_index] = no_x_diff; bottom_diff[no_y_index] = no_y_diff; bottom_diff[lm_x_index] = lm_x_diff; bottom_diff[lm_y_index] = lm_y_diff; bottom_diff[rm_x_index] = rm_x_diff; bottom_diff[rm_y_index] = rm_y_diff; lm_count++; } } class_label[class_index] = 1; mask_Rf_anchor_already[h * output_width + w] = 1; count++; int bg_index = b * num_channels * dimScale + 4* dimScale + h * output_width + w; int face_index = b * num_channels * dimScale + 5* dimScale + h * output_width + w; if(has_lm){ bg_index = b * num_channels * dimScale + 14* dimScale + h * output_width + w; face_index = b * num_channels * dimScale + 15* dimScale + h * output_width + w; } Dtype class_loss = SingleSoftmaxLoss(channel_pred_data[bg_index], channel_pred_data[face_index], Dtype(1.0)); batch_sample_loss[b * dimScale + h * output_width + w] = class_loss; } } gt_match_box ++; } } mask_Rf_anchor_already.clear(); postive_batch[b] = count; postive += count; lm_postive += lm_count; } #if FOCAL_LOSS_SOFTMAX score_loss = FocalLossSoftmax(class_label, channel_pred_data, batch_size, output_height, output_width, bottom_diff, num_channels, has_lm); #else // 计算softMax loss value SelectHardSampleSoftMax(class_label, batch_sample_loss, 2, postive_batch, output_height, output_width, num_channels, batch_size, has_lm); score_loss = SoftmaxWithLoss(class_label, channel_pred_data, batch_size, output_height, output_width, bottom_diff, num_channels, has_lm); #endif *count_postive = postive; *count_postive_lm = lm_postive; *loc_loss_value = loc_loss; *lm_loss_value = lm_loss; *match_num_gt_box = gt_match_box; return score_loss; } template float EncodeCenterGridObjectSoftMaxLoss(const int batch_size, const int num_channels, const int num_classes, const int output_width, const int output_height, const float downRatio, std::vector<int>postive_batch, std::vector<float> batch_sample_loss, float* channel_pred_data, const int anchor_scale, std::pair<int, int> loc_truth_scale, const std::map<int, vector<std::pair<NormalizedBBox, AnnoFaceLandmarks> > >& all_gt_bboxes, float* class_label, float* bottom_diff, int *count_postive_lm, int *count_postive, float *loc_loss_value, int *match_num_gt_box, bool has_lm, float * lm_loss_value); template double EncodeCenterGridObjectSoftMaxLoss(const int batch_size, const int num_channels, const int num_classes, const int output_width, const int output_height, const float downRatio, std::vector<int>postive_batch, std::vector<double> batch_sample_loss, double* channel_pred_data, const int anchor_scale, std::pair<int, int> loc_truth_scale, const std::map<int, vector<std::pair<NormalizedBBox, AnnoFaceLandmarks> > >& all_gt_bboxes, double* class_label, double* bottom_diff, int *count_postive_lm, int *count_postive, double *loc_loss_value, int *match_num_gt_box, bool has_lm, double * lm_loss_value); template <typename Dtype> void GetCenterGridObjectResultSoftMax(const int batch_size, const int num_channels, const int num_classes, const int output_width, const int output_height, const float downRatio, Dtype* channel_pred_data, const int anchor_scale, Dtype conf_thresh, std::map<int, std::vector<CenterNetInfo > >* results, bool has_lm){ // face class 人脸类型 包括背景 + face人脸,两类 CHECK_EQ(num_classes, 2); if(has_lm){ CHECK_EQ(num_channels, 14 + num_classes); }else{ CHECK_EQ(num_channels, 4 + num_classes); } int dimScale = output_height * output_width; SoftmaxCenterGrid(channel_pred_data, batch_size, num_classes, num_channels, output_height, output_width, has_lm); for(int b = 0; b < batch_size; b++){ for(int h = 0; h < output_height; h++){ for(int w = 0; w < output_width; w++){ int x_index = b * num_channels * dimScale + 0* dimScale + h * output_width + w; int y_index = b * num_channels * dimScale + 1* dimScale + h * output_width + w; int width_index = b * num_channels * dimScale + 2* dimScale + h * output_width + w; int height_index = b * num_channels * dimScale + 3* dimScale + h * output_width + w; float xmin = 0.f, ymin = 0.f, xmax = 0.f, ymax = 0.f; float bb_xmin = (w + 0.5 - channel_pred_data[x_index] * anchor_scale / (downRatio)) *downRatio; float bb_ymin = (h + 0.5 - channel_pred_data[y_index] * anchor_scale / (downRatio)) *downRatio; float bb_xmax = (w + 0.5 - channel_pred_data[width_index] * anchor_scale / (downRatio)) *downRatio; float bb_ymax = (h + 0.5 - channel_pred_data[height_index] * anchor_scale / (downRatio)) *downRatio; xmin = GET_VALID_VALUE(bb_xmin, (0.f), float(downRatio * output_width)); ymin = GET_VALID_VALUE(bb_ymin, (0.f), float(downRatio * output_height)); xmax = GET_VALID_VALUE(bb_xmax, (0.f), float(downRatio * output_width)); ymax = GET_VALID_VALUE(bb_ymax, (0.f), float(downRatio * output_height)); float le_x = 0.f, le_y = 0.f, re_x = 0.f, re_y = 0.f, no_x = 0.f, no_y = 0.f, lm_x = 0.f, lm_y = 0.f, rm_x = 0.f, rm_y = 0.f; if(has_lm){ int le_x_index = b * num_channels * dimScale + 4* dimScale + h * output_width + w; int le_y_index = b * num_channels * dimScale + 5* dimScale + h * output_width + w; int re_x_index = b * num_channels * dimScale + 6* dimScale + h * output_width + w; int re_y_index = b * num_channels * dimScale + 7* dimScale + h * output_width + w; int no_x_index = b * num_channels * dimScale + 8* dimScale + h * output_width + w; int no_y_index = b * num_channels * dimScale + 9* dimScale + h * output_width + w; int lm_x_index = b * num_channels * dimScale + 10* dimScale + h * output_width + w; int lm_y_index = b * num_channels * dimScale + 11* dimScale + h * output_width + w; int rm_x_index = b * num_channels * dimScale + 12* dimScale + h * output_width + w; int rm_y_index = b * num_channels * dimScale + 13* dimScale + h * output_width + w; le_x = (w + 0.5 - channel_pred_data[le_x_index] * anchor_scale /(downRatio)) *downRatio; le_y = (w + 0.5 - channel_pred_data[le_y_index] * anchor_scale /(downRatio)) *downRatio; le_x = GET_VALID_VALUE(le_x, (0.f), float(downRatio * output_width)); le_y = GET_VALID_VALUE(le_y, (0.f), float(downRatio * output_height)); re_x = (w + 0.5 - channel_pred_data[re_x_index] * anchor_scale /(downRatio)) *downRatio; re_y = (w + 0.5 - channel_pred_data[re_y_index] * anchor_scale /(downRatio)) *downRatio; re_x = GET_VALID_VALUE(re_x, (0.f), float(downRatio * output_width)); re_y = GET_VALID_VALUE(re_y, (0.f), float(downRatio * output_height)); no_x = (w + 0.5 - channel_pred_data[no_x_index] * anchor_scale /(downRatio)) *downRatio; no_y = (w + 0.5 - channel_pred_data[no_y_index] * anchor_scale /(downRatio)) *downRatio; no_x = GET_VALID_VALUE(no_x, (0.f), float(downRatio * output_width)); no_y = GET_VALID_VALUE(no_y, (0.f), float(downRatio * output_height)); lm_x = (w + 0.5 - channel_pred_data[lm_x_index] * anchor_scale /(downRatio)) *downRatio; lm_y = (w + 0.5 - channel_pred_data[lm_y_index] * anchor_scale /(downRatio)) *downRatio; lm_x = GET_VALID_VALUE(lm_x, (0.f), float(downRatio * output_width)); lm_y = GET_VALID_VALUE(lm_y, (0.f), float(downRatio * output_height)); rm_x = (w + 0.5 - channel_pred_data[rm_x_index] * anchor_scale /(downRatio)) *downRatio; rm_y = (w + 0.5 - channel_pred_data[rm_y_index] * anchor_scale /(downRatio)) *downRatio; rm_x = GET_VALID_VALUE(rm_x, (0.f), float(downRatio * output_width)); rm_y = GET_VALID_VALUE(rm_y, (0.f), float(downRatio * output_height)); } if((xmax - xmin) <= 0 || (ymax - ymin) <= 0) continue; int class_index = b * num_channels * dimScale + 5* dimScale + h * output_width + w; if(has_lm){ class_index = b * num_channels * dimScale + 15* dimScale + h * output_width + w; } Dtype label_score = channel_pred_data[class_index]; if(label_score >= conf_thresh){ CenterNetInfo temp_result; temp_result.set_class_id(0); temp_result.set_score(label_score); temp_result.set_xmin(xmin); temp_result.set_xmax(xmax); temp_result.set_ymin(ymin); temp_result.set_ymax(ymax); temp_result.set_area((xmax - xmin) * (ymax - ymin)); if(has_lm){ temp_result.mutable_marks()->mutable_lefteye()->set_x(le_x); temp_result.mutable_marks()->mutable_lefteye()->set_y(le_y); temp_result.mutable_marks()->mutable_righteye()->set_x(re_x); temp_result.mutable_marks()->mutable_righteye()->set_y(re_y); temp_result.mutable_marks()->mutable_nose()->set_x(no_x); temp_result.mutable_marks()->mutable_nose()->set_y(no_y); temp_result.mutable_marks()->mutable_leftmouth()->set_x(lm_x); temp_result.mutable_marks()->mutable_leftmouth()->set_y(lm_y); temp_result.mutable_marks()->mutable_rightmouth()->set_x(rm_x); temp_result.mutable_marks()->mutable_rightmouth()->set_y(rm_y); } (*results)[b].push_back(temp_result); } } } } } template void GetCenterGridObjectResultSoftMax(const int batch_size, const int num_channels, const int num_classes, const int output_width, const int output_height, const float downRatio, float* channel_pred_data, const int anchor_scale, float conf_thresh, std::map<int, std::vector<CenterNetInfo > >* results, bool has_lm); template void GetCenterGridObjectResultSoftMax(const int batch_size, const int num_channels, const int num_classes, const int output_width, const int output_height, const float downRatio, double* channel_pred_data, const int anchor_scale, double conf_thresh, std::map<int, std::vector<CenterNetInfo > >* results, bool has_lm); // OHEM 样本难例挖掘, 只记录具体思路 // 1. 通过IOU 或者中心点的方式,确定正样本,也就是说,对于位置回归来说,确定回归的损失函数(loc loss), 通过样本框真实值确定样本分类 // 2. 这样会得到一张图像里面所有样本的正样本数量,以及全部的负样本数量 // 3. 正常计算正样本 + 所有负样本的loss和(位置回归损失 + 置信度损失)是一个集合(所有样本的集合) // 针对上面的解释,假设对于160x160的featureMap,一共有25600个样本,其中有600个正样本,其余都是负样本(20000), // 那么,这样来计算每个样本的loss集合, // 1).对于一个正样本,计算这个样本的loc_loss + cls_loss。 // 2).对于一个负样本,计算cls_loss(背景类的置信度得分损失),SSD中,在计算负样本的时候 // 4. 使用NMS 去除重复的框, 针对NMS, 该如何去实现呢?ohem的作者是这样做的, // 1).首先第一步box从哪里来,所有计算出来的预测box(160x160) // 2).置信得分,以loss为准,具体的每个box的结构为[x1, y1, x2, y2, loss] // 3).这样再进行nms,排除多余的框,以框IOU_Thresh > 0.7 为临界阈值 // 5. 再对剩余Loss的集合进行从大到小排列,选取一定数量的负样本 // 6. 只回归计算这样正样本和一部分负样本的总损失,以及回归相应的梯度值 template <typename Dtype> void SelectHardSampleSoftMaxWithOHEM(){ NOT_IMPLEMENTED; } // anchor匹配方式采用IOU匹配,但是还是分层的概念,每一层匹配不同大小的gt_bboxes // 采用overlap > 0.45的为正样本,其他的均为负样本 // loss = smoothL1loss + focal loss + objectness_loss确定这一层有无目标物体 // 对于没有匹配到的某一层,则这一层loss值为0 template <typename Dtype> Dtype EncodeOverlapObjectSigmoidLoss(const int batch_size, const int num_channels, const int num_classes, const int output_width, const int output_height, const int downRatio, Dtype* channel_pred_data, const int anchor_scale, std::pair<int, int> loc_truth_scale, const std::map<int, vector<NormalizedBBox> >& all_gt_bboxes, Dtype* class_label, Dtype* bottom_diff, Dtype ignore_thresh, int *count_postive, Dtype *loc_loss_value){ CHECK_EQ(num_classes, 1); int dimScale = output_height * output_width; Dtype score_loss = Dtype(0.), loc_loss = Dtype(0.); CHECK_EQ(num_channels, (4 + 1 + num_classes)) << "num_channels shoule be set to including bias_x, bias_y, width, height, object_confidence and classes"; for(int b = 0; b < batch_size; b++){ int object_index = b * num_channels * dimScale + 4 * dimScale; for(int i = 0; i < (num_classes + 1) * dimScale; i++){ channel_pred_data[object_index + i] = CenterSigmoid(channel_pred_data[object_index + i]); } } int postive = 0; // 采用focal loss 使用所有的负样本,作为训练 caffe_set(batch_size * dimScale, Dtype(0.5f), class_label); for(int b = 0; b < batch_size; b++){ auto it = all_gt_bboxes.find(b); if(it == all_gt_bboxes.end()){ continue; } std::vector<NormalizedBBox> gt_bboxes = it->second; std::vector<int> mask_Rf_anchor(dimScale, 0); std::vector<Dtype> object_loss_temp(dimScale, Dtype(0.)); int count = 0; for(int h = 0; h < output_height; h++){ for(int w = 0; w < output_width; w++){ int xmin_index = b * num_channels * dimScale + 0* dimScale + h * output_width + w; int ymin_index = b * num_channels * dimScale + 1* dimScale + h * output_width + w; int xmax_index = b * num_channels * dimScale + 2* dimScale + h * output_width + w; int ymax_index = b * num_channels * dimScale + 3* dimScale + h * output_width + w; int object_index = b * num_channels * dimScale + 4* dimScale + h * output_width + w; NormalizedBBox predBox; Dtype center_x = (w + 0.5 - channel_pred_data[xmin_index] * anchor_scale /(2*downRatio)) / output_width; Dtype center_y = (h + 0.5 - channel_pred_data[ymin_index] * anchor_scale /(2*downRatio)) / output_height; Dtype pred_width = (std::exp(channel_pred_data[xmax_index]) * anchor_scale / downRatio) / output_width; Dtype pred_height = (std::exp(channel_pred_data[ymax_index]) * anchor_scale / downRatio) /output_height; predBox.set_xmin(center_x - pred_width / 2); predBox.set_xmax(center_x + pred_width / 2); predBox.set_ymin(center_y - pred_height / 2); predBox.set_ymax(center_y + pred_height / 2); float best_iou = 0; for(unsigned ii = 0; ii < gt_bboxes.size(); ii++){ const Dtype xmin = gt_bboxes[ii].xmin() * output_width; const Dtype ymin = gt_bboxes[ii].ymin() * output_height; const Dtype xmax = gt_bboxes[ii].xmax() * output_width; const Dtype ymax = gt_bboxes[ii].ymax() * output_height; const int gt_bbox_width = static_cast<int>((xmax - xmin) * downRatio); const int gt_bbox_height = static_cast<int>((ymax - ymin) * downRatio); int large_side = std::max(gt_bbox_height, gt_bbox_width); if(large_side >= loc_truth_scale.first && large_side < loc_truth_scale.second){ float iou = YoloBBoxIou(predBox, gt_bboxes[ii]); if (iou > best_iou) { best_iou = iou; } } } Dtype object_value = (channel_pred_data[object_index] - 0.); if(best_iou > ignore_thresh){ object_value = 0.; } object_loss_temp[h * output_width + w] = Object_L2_Loss(object_value, &(bottom_diff[object_index])); } } for(unsigned ii = 0; ii < gt_bboxes.size(); ii++){ const Dtype xmin = gt_bboxes[ii].xmin() * output_width; const Dtype ymin = gt_bboxes[ii].ymin() * output_height; const Dtype xmax = gt_bboxes[ii].xmax() * output_width; const Dtype ymax = gt_bboxes[ii].ymax() * output_height; const Dtype gt_center_x = (xmin + xmax) / 2; const Dtype gt_center_y = (ymin + ymax) / 2; const int gt_bbox_width = static_cast<int>((xmax - xmin) * downRatio); const int gt_bbox_height = static_cast<int>((ymax - ymin) * downRatio); int large_side = std::max(gt_bbox_height, gt_bbox_width); if(large_side >= loc_truth_scale.first && large_side < loc_truth_scale.second){ for(int h = 0; h < output_height; h++){ for(int w = 0; w < output_width; w++){ if(mask_Rf_anchor[h * output_width + w] == 1) // 避免同一个anchor的中心落在多个gt里面 continue; NormalizedBBox anchorBox; float bb_xmin = (w - anchor_scale /(2*downRatio)) / output_width; float bb_ymin = (h - anchor_scale /(2*downRatio)) / output_height; float bb_xmax = (w + anchor_scale /(2*downRatio)) / output_width; float bb_ymax = (h + anchor_scale /(2*downRatio)) /output_height; anchorBox.set_xmin(bb_xmin); anchorBox.set_xmax(bb_xmax); anchorBox.set_ymin(bb_ymin); anchorBox.set_ymax(bb_ymax); float best_iou = YoloBBoxIou(anchorBox, gt_bboxes[ii]); if(best_iou > (ignore_thresh + 0.15)){ int x_center_index = b * num_channels * dimScale + 0* dimScale + h * output_width + w; int y_center_index = b * num_channels * dimScale + 1* dimScale + h * output_width + w; int width_index = b * num_channels * dimScale + 2* dimScale + h * output_width + w; int height_index = b * num_channels * dimScale + 3* dimScale + h * output_width + w; int object_index = b * num_channels * dimScale + 4* dimScale + h * output_width + w; Dtype x_center_bias = (w + 0.5 - gt_center_x) * downRatio *2 / anchor_scale; Dtype y_center_bias = (h + 0.5 - gt_center_y) * downRatio *2 / anchor_scale; Dtype width_bias = std::log((xmax - xmin) * downRatio / anchor_scale); Dtype height_bias = std::log((ymax - ymin) * downRatio / anchor_scale); loc_loss += smoothL1_Loss(Dtype(channel_pred_data[x_center_index] - x_center_bias), &(bottom_diff[x_center_index])); loc_loss += smoothL1_Loss(Dtype(channel_pred_data[y_center_index] - y_center_bias), &(bottom_diff[y_center_index])); loc_loss += smoothL1_Loss(Dtype(channel_pred_data[width_index] - width_bias), &(bottom_diff[width_index])); loc_loss += smoothL1_Loss(Dtype(channel_pred_data[height_index] - height_bias), &(bottom_diff[height_index])); object_loss_temp[h * output_width + w] = Object_L2_Loss(Dtype(channel_pred_data[object_index] - 1.), &(bottom_diff[object_index])); int class_index = b * dimScale + h * output_width + w; class_label[class_index] = 1; mask_Rf_anchor[h * output_width + w] = 1; count++; } } } } } for(unsigned ii = 0; ii < dimScale; ii++){ loc_loss += object_loss_temp[ii]; } if(count > 0){ int gt_class_index = b * dimScale; int pred_class_index = b * num_channels * dimScale + 5* dimScale; score_loss += FocalLossSigmoid(class_label + gt_class_index, channel_pred_data + pred_class_index, dimScale, bottom_diff + pred_class_index); }else{ score_loss += 0; } postive += count; } *count_postive = postive; *loc_loss_value = loc_loss; return score_loss; } template float EncodeOverlapObjectSigmoidLoss(const int batch_size, const int num_channels, const int num_classes, const int output_width, const int output_height, const int downRatio, float* channel_pred_data, const int anchor_scale, std::pair<int, int> loc_truth_scale, const std::map<int, vector<NormalizedBBox> >& all_gt_bboxes, float* class_label, float* bottom_diff, float ignore_thresh, int *count_postive, float *loc_loss_value); template double EncodeOverlapObjectSigmoidLoss(const int batch_size, const int num_channels, const int num_classes, const int output_width, const int output_height, const int downRatio, double* channel_pred_data, const int anchor_scale, std::pair<int, int> loc_truth_scale, const std::map<int, vector<NormalizedBBox> >& all_gt_bboxes, double* class_label, double* bottom_diff, double ignore_thresh, int *count_postive, double *loc_loss_value); template <typename Dtype> void GetCenterOverlapResultSigmoid(const int batch_size, const int num_channels, const int num_classes, const int output_width, const int output_height, const int downRatio, Dtype* channel_pred_data, const int anchor_scale, Dtype conf_thresh, std::map<int, std::vector<CenterNetInfo > >* results){ // face class 人脸类型 CHECK_EQ(num_classes, 1); CHECK_EQ(num_channels, 4 + 1 + num_classes); int dimScale = output_height * output_width; for(int b = 0; b < batch_size; b++){ int object_index = b * num_channels * dimScale + 4 * dimScale; for(int i = 0; i < (num_classes + 1) * dimScale; i++){ channel_pred_data[object_index + i] = CenterSigmoid(channel_pred_data[object_index + i]); } } for(int b = 0; b < batch_size; b++){ for(int h = 0; h < output_height; h++){ for(int w = 0; w < output_width; w++){ int x_index = b * num_channels * dimScale + 0* dimScale + h * output_width + w; int y_index = b * num_channels * dimScale + 1* dimScale + h * output_width + w; int width_index = b * num_channels * dimScale + 2* dimScale + h * output_width + w; int height_index = b * num_channels * dimScale + 3* dimScale + h * output_width + w; int object_index = b * num_channels * dimScale + 4* dimScale + h * output_width + w; int class_index = b * num_channels * dimScale + 5* dimScale + h * output_width + w; Dtype center_x = (w + 0.5 - channel_pred_data[x_index] * anchor_scale /(2*downRatio)) * downRatio; Dtype center_y = (h + 0.5 - channel_pred_data[y_index] * anchor_scale /(2*downRatio)) * downRatio; Dtype pred_width = (std::exp(channel_pred_data[width_index]) * anchor_scale / downRatio) * downRatio; Dtype pred_height = (std::exp(channel_pred_data[height_index]) * anchor_scale / downRatio) * downRatio; Dtype xmin = GET_VALID_VALUE(center_x - pred_width / 2, Dtype(0.f), Dtype(downRatio * output_width)); Dtype ymin = GET_VALID_VALUE(center_y - pred_height / 2, Dtype(0.f), Dtype(downRatio * output_height)); Dtype xmax = GET_VALID_VALUE(center_x + pred_width / 2, Dtype(0.f), Dtype(downRatio * output_width)); Dtype ymax = GET_VALID_VALUE(center_y + pred_height / 2, Dtype(0.f), Dtype(downRatio * output_height)); if((xmax - xmin) <= 0 || (ymax - ymin) <= 0) continue; Dtype label_score = channel_pred_data[class_index] * channel_pred_data[object_index]; if(label_score >= conf_thresh){ CenterNetInfo temp_result; temp_result.set_class_id(0); temp_result.set_score(label_score); temp_result.set_xmin(xmin); temp_result.set_xmax(xmax); temp_result.set_ymin(ymin); temp_result.set_ymax(ymax); temp_result.set_area((xmax - xmin) * (ymax - ymin)); (*results)[b].push_back(temp_result); } } } } } template void GetCenterOverlapResultSigmoid(const int batch_size, const int num_channels, const int num_classes, const int output_width, const int output_height, const int downRatio, float* channel_pred_data, const int anchor_scale, float conf_thresh, std::map<int, std::vector<CenterNetInfo > >* results); template void GetCenterOverlapResultSigmoid(const int batch_size, const int num_channels, const int num_classes, const int output_width, const int output_height, const int downRatio, double* channel_pred_data, const int anchor_scale, double conf_thresh, std::map<int, std::vector<CenterNetInfo > >* results); } // namespace caffe ======================= File: scripts/mtfl/main.cpp ======================= #include<ostream> #include <iostream> #include <stdlib.h> #include<vector> #include <string> #include<fstream> #include<algorithm> #include <opencv2/opencv.hpp> #include <opencv2/highgui/highgui.hpp> using namespace std; using namespace cv; #define Random(low, up) (rand()%(up-low+1)) + low - 1 vector<cv::Point2f> getRotatePoint(int row, vector<cv::Point2f> Points, const cv::Point rotate_center, const double angle) { vector<cv::Point2f> dstPoints; float x1 = 0.f, y1 = 0.f; for (size_t i = 0; i < Points.size(); i++){ x1 = Points.at(i).x; y1 = row - Points.at(i).y; float x2 = rotate_center.x; float y2 = row - rotate_center.y; float x = (x1 - x2)*cos(M_PI / 180.0 * angle) - (y1 - y2)*sin(M_PI / 180.0 * angle) + x2; float y = (x1 - x2)*sin(M_PI / 180.0 * angle) + (y1 - y2)*cos(M_PI / 180.0 * angle) + y2; y = row - y; dstPoints.push_back(Point2i(x, y)); } return dstPoints; } Mat rotateImg(Mat src, int angle){ Mat dst; //填充图像 int maxBorder =(int) (max(src.cols, src.rows)* 1.414 ); //即为sqrt(2)*max int dx = (maxBorder - src.cols)/2; int dy = (maxBorder - src.rows)/2; copyMakeBorder(src, dst, dy, dy, dx, dx, BORDER_CONSTANT); //旋转 Point2f center( (float)(dst.cols/2), (float) (dst.rows/2)); Mat affine_matrix = getRotationMatrix2D( center, angle, 1.0 );//求得旋转矩阵 warpAffine(dst, dst, affine_matrix, dst.size()); return dst; } Mat rotateSameImg(Mat src, int angle){ Mat dst; //旋转 Point2f center( (float)(src.cols/2), (float) (src.rows/2)); Mat affine_matrix = getRotationMatrix2D( center, angle, 1.0 );//求得旋转矩阵 warpAffine(src, dst, affine_matrix, dst.size()); return dst; } vector<cv::Point2f> CropImg(Mat src, Mat& dst, int angle, vector<cv::Point2f> Points){ float radian = (float) (angle /180.0 * M_PI); vector<cv::Point2f> dstPoints; //计算图像旋转之后包含图像的最大的矩形 float sinVal = fabs(sin(radian)); float cosVal = fabs(cos(radian)); Size targetSize( (int)(src.cols * cosVal +src.rows * sinVal), (int)(src.cols * sinVal + src.rows * cosVal) ); //剪掉多余边框 int x = (dst.cols - targetSize.width) / 2; int y = (dst.rows - targetSize.height) / 2; Rect rect(x, y, targetSize.width, targetSize.height); dst = Mat(dst,rect); for(int i=0; i<Points.size(); i++){ float point_x = Points.at(i).x - x; float point_y = Points.at(i).y - y; dstPoints.push_back(Point2f(point_x, point_y)); } return dstPoints; } string& replace_all(string& str,const string& old_value,const string& new_value) { while(true) { string::size_type pos(0); if( (pos=str.find(old_value))!=string::npos ) str.replace(pos,old_value.length(),new_value); else break; } return str; } void RotateBatchImage(string& srcfilePath, string &labelPath, string &newTrainingSetFile){ ofstream setFile(newTrainingSetFile, ios::out|ios::app); if(!setFile.is_open()){ std::cout<< "cannot open lablefile, the file" << newTrainingSetFile << "does not exit!"<<std::endl; return; } Mat src = imread(srcfilePath); vector<cv::Point2f> Points; int maxBorder =(int) (max(src.cols, src.rows)* 1.414 ); int dx = (maxBorder - src.cols)/2; int dy = (maxBorder - src.rows)/2; std::ifstream infile(labelPath.c_str()); std::string lineStr ; std::stringstream sstr ; if (!infile.good()) { std::cout << "Cannot open " << labelPath<<std::endl; return; } float x[5]; float y[5]; int gender; int glass; while (std::getline(infile, lineStr )) { sstr << lineStr; sstr >> x[0] >> x[1] >> x[2] >> x[3] >> x[4] >> y[0] >> y[1] >> y[2] >> y[3] >> y[4] >> gender >> glass; for(size_t ii=0; ii<5; ii++){ x[ii] += dx; y[ii] += dy; Points.push_back(cv::Point2f(x[ii], y[ii])); } lineStr.clear(); } double angle ; srand((int)time(0)); size_t iPos = srcfilePath.find(".jpg"); string s2 = srcfilePath.substr(0, iPos); for(int iter = 0; iter < 15; iter++){ string newImgFilepath = s2 + "_"+std::to_string(iter)+".jpg"; string newImgFilepath_rotete = s2 + "_"+std::to_string(iter)+"_rotate.jpg"; string newLablePath = labelPath + "_"+std::to_string(iter); angle = Random(-120, 120); std::cout<<"angle: "<<angle<<std::endl; Mat dst = rotateImg(src, angle); cv::Point2f center(dst.cols / 2., dst.rows / 2.); vector<cv::Point2f> dstPoints = getRotatePoint(dst.rows, Points, center, angle); vector<cv::Point2f> cropPoints = CropImg(src, dst, angle, dstPoints); ofstream file(newLablePath, ios::out); if(!file.is_open()){ std::cout<< "cannot open lablefile, the file" << newLablePath << "does not exit!"<<std::endl; return; } file << cropPoints.at(0).x << " " << cropPoints.at(1).x << " " << cropPoints.at(2).x << " " << cropPoints.at(3).x << " " << cropPoints.at(4).x << " " << cropPoints.at(0).y << " " << cropPoints.at(1).y << " " << cropPoints.at(2).y << " " << cropPoints.at(3).y << " " << cropPoints.at(4).y << " "<<gender<<" "<<glass<< std::endl; cv::imwrite(newImgFilepath, dst); for(size_t ii=0; ii<cropPoints.size(); ii++){ cv::circle(dst, cropPoints.at(ii), 5, cv::Scalar(0, 0, 255), 2); } cv::imwrite(newImgFilepath_rotete, dst); file.close(); setFile << newImgFilepath <<std::endl; } setFile.close(); } void RotateSameBatchImage(string& srcfilePath, string &labelPath, string &newTrainingSetFile){ ofstream setFile(newTrainingSetFile, ios::out|ios::app); if(!setFile.is_open()){ std::cout<< "cannot open lablefile, the file" << newTrainingSetFile << "does not exit!"<<std::endl; return; } Mat src = imread(srcfilePath); vector<cv::Point2f> Points; std::ifstream infile(labelPath.c_str()); std::string lineStr ; std::stringstream sstr ; if (!infile.good()) { std::cout << "Cannot open " << labelPath<<std::endl; return; } float x[5]; float y[5]; int gender; int glass; while (std::getline(infile, lineStr )) { sstr << lineStr; sstr >> x[0] >> x[1] >> x[2] >> x[3] >> x[4] >> y[0] >> y[1] >> y[2] >> y[3] >> y[4] >> gender >> glass; for(size_t ii=0; ii<5; ii++){ Points.push_back(cv::Point2f(x[ii], y[ii])); } lineStr.clear(); } double angle ; srand((int)time(0)); size_t iPos = srcfilePath.find(".jpg"); string s2 = srcfilePath.substr(0, iPos); for(int iter = 0; iter < 5; iter++){ string newImgFilepath = s2 + "_"+std::to_string(iter)+".jpg"; //string newImgFilepath_rotete = replace_all(s2, "annoImage", "cropImg") + "_"+std::to_string(iter)+"_rotate.jpg"; string newLablePath = labelPath + "_"+std::to_string(iter); angle = Random(-120, 120); std::cout<<"angle: "<<angle<<std::endl; Mat dst = rotateSameImg(src, angle); cv::Point2f center(dst.cols / 2., dst.rows / 2.); vector<cv::Point2f> dstPoints = getRotatePoint(dst.rows, Points, center, angle); ofstream file(newLablePath, ios::out); if(!file.is_open()){ std::cout<< "cannot open lablefile, the file" << newLablePath << "does not exit!"<<std::endl; return; } file << dstPoints.at(0).x << " " << dstPoints.at(1).x << " " << dstPoints.at(2).x << " " << dstPoints.at(3).x << " " << dstPoints.at(4).x << " " << dstPoints.at(0).y << " " << dstPoints.at(1).y << " " << dstPoints.at(2).y << " " << dstPoints.at(3).y << " " << dstPoints.at(4).y << " "<<gender<<" "<<glass<< std::endl; cv::imwrite(newImgFilepath, dst); /*for(size_t ii=0; ii<dstPoints.size(); ii++){ cv::circle(dst, dstPoints.at(ii), 5, cv::Scalar(0, 0, 255), 2); } cv::imwrite(newImgFilepath_rotete, dst);*/ file.close(); setFile << newImgFilepath <<std::endl; } setFile.close(); } int main() { string srcTrainsetFile = "/home/stive/workspace/dataset/facedata/mtfl/ImageSets/training.txt"; string srcTestsetFile = "/home/stive/workspace/dataset/facedata/mtfl/ImageSets/testing.txt"; string newTrainsetFile = "/home/stive/workspace/dataset/facedata/mtfl/ImageSets/newtraining.txt"; string newTestsetFile = "/home/stive/workspace/dataset/facedata/mtfl/ImageSets/newtesting.txt"; std::ifstream infile(srcTrainsetFile.c_str()); std::string lineStr ; if (!infile.good()) { std::cout << "Cannot open " << srcTrainsetFile; return 0; } string imgPath; string labelPath; while (!infile.eof()) { std::getline(infile, lineStr ); std::stringstream sstr ; sstr << lineStr; sstr >> imgPath >> labelPath; std:: cout << "imgPath: "<<imgPath<<" labelPath: "<<labelPath<<std::endl; RotateBatchImage(imgPath, labelPath, newTrainsetFile); lineStr.clear(); while(std::getline(infile, lineStr )){ std::stringstream newsster(lineStr) ; newsster >> imgPath >> labelPath; std:: cout << "imgPath: "<<imgPath<<" labelPath: "<<labelPath<<std::endl; //RotateBatchImage(imgPath, labelPath, newTrainsetFile); RotateSameBatchImage(imgPath, labelPath, newTrainsetFile); } } infile.close(); return 0; } ======================= File: src/caffe/layers/batch_norm_scale_layer.cpp ======================= <gh_stars>10-100 #include <algorithm> #include <vector> #include "caffe/filler.hpp" #include "caffe/layers/batch_norm_scale_layer.hpp" #include "caffe/util/math_functions.hpp" namespace caffe { template <typename Dtype> void BatchNormScaleLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { BatchNormParameter param = this->layer_param_.batch_norm_param(); moving_average_fraction_ = param.moving_average_fraction(); use_global_stats_ = this->phase_ == TEST; if (param.has_use_global_stats()) use_global_stats_ = param.use_global_stats(); if (bottom[0]->num_axes() == 1) channels_ = 1; else channels_ = bottom[0]->shape(1); eps_ = param.eps(); if (this->blobs_.size() > 0) { LOG(INFO) << "Skipping parameter initialization"; } else { this->blobs_.resize(5); vector<int> sz; sz.push_back(channels_); this->blobs_[0].reset(new Blob<Dtype>(sz)); this->blobs_[1].reset(new Blob<Dtype>(sz)); this->blobs_[3].reset(new Blob<Dtype>(sz)); this->blobs_[4].reset(new Blob<Dtype>(sz)); sz[0] = 1; this->blobs_[2].reset(new Blob<Dtype>(sz)); for (int i = 0; i < this->blobs_.size(); ++i) { if(i == 3){ caffe_set(this->blobs_[i]->count(), Dtype(1), this->blobs_[i]->mutable_cpu_data()); }else{ caffe_set(this->blobs_[i]->count(), Dtype(0), this->blobs_[i]->mutable_cpu_data()); } } } // the mean, variance, bias_correction can not be learned,but the scale-parameter shoule be set true this->param_propagate_down_.resize(this->blobs_.size(), false); this->param_propagate_down_[3] = true; this->param_propagate_down_[4] = true; // Mask statistics from optimization by setting local learning rates // for mean, variance, and the bias correction(i.a.moving) to zero. // and to set the scale-parameter the lr-policy(1., 2.) for (int i = 0; i < this->blobs_.size(); ++i) { if(i < 3){ if (this->layer_param_.param_size() == i) { ParamSpec* fixed_param_spec = this->layer_param_.add_param(); fixed_param_spec->set_lr_mult(0.f); } else { CHECK_EQ(this->layer_param_.param(i).lr_mult(), 0.f) << "Cannot configure batch normalization statistics as layer " << "parameters."; } } } } template <typename Dtype> void BatchNormScaleLayer<Dtype>::Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { if (bottom[0]->num_axes() >= 1) CHECK_EQ(bottom[0]->shape(1), channels_); top[0]->ReshapeLike(*bottom[0]); vector<int> sz; sz.push_back(channels_); mean_.Reshape(sz); variance_.Reshape(sz); x_norm_.ReshapeLike(*bottom[0]); sz[0] = bottom[0]->shape(0); batch_sum_multiplier_.Reshape(sz); int spatial_dim = bottom[0]->count()/(channels_*bottom[0]->shape(0)); if (spatial_sum_multiplier_.num_axes() == 0 || spatial_sum_multiplier_.shape(0)!= spatial_dim) { sz[0] = spatial_dim; spatial_sum_multiplier_.Reshape(sz); Dtype* multiplier_data = spatial_sum_multiplier_.mutable_cpu_data(); caffe_set(spatial_sum_multiplier_.count(), Dtype(1), multiplier_data); } int numbychans = channels_*bottom[0]->shape(0); if (num_by_chans_.num_axes() == 0 || num_by_chans_.shape(0)!= numbychans) { sz[0] = numbychans; num_by_chans_.Reshape(sz); caffe_set(batch_sum_multiplier_.count(), Dtype(1), batch_sum_multiplier_.mutable_cpu_data()); } } template <typename Dtype> void BatchNormScaleLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { const Dtype* bottom_data = bottom[0]->cpu_data(); Dtype* top_data = top[0]->mutable_cpu_data(); int num = bottom[0]->shape(0); int spatial_dim = bottom[0]->count()/(bottom[0]->shape(0)*channels_); if (bottom[0]!= top[0]) { caffe_copy(bottom[0]->count(), bottom_data, top_data); } if (use_global_stats_) { // use the stored mean/variance estimates. // 如果使用已经计算好的mean和variance // mean保存在blobs_[0]中,variance保存在blobs_[1]中 // 滑动平均系数保存在blobs_[2]中 const Dtype scale_factor = this->blobs_[2]->cpu_data()[0] == 0? 0 : 1 / this->blobs_[2]->cpu_data()[0]; caffe_cpu_scale(variance_.count(), scale_factor, this->blobs_[0]->cpu_data(), mean_.mutable_cpu_data()); caffe_cpu_scale(variance_.count(), scale_factor, this->blobs_[1]->cpu_data(), variance_.mutable_cpu_data()); } else { // 训练阶段 compute mean // 1.计算均值,先计算HW的,每个通道的均值,在包含N // caffe_cpu_gemv 实现 y = alpha*A*x+beta*y; // 输出的是channels_*num, // 每次处理的列是spatial_dim,由于spatial_sum_multiplier_初始为1,即NCHW中的 // H*W各自相加,得到N*C*average,此处多除以了num,下一步可以不除以。 // compute mean //这个矩阵与向量相乘,目的是计算每个feature map的数值和,然后在除以1./(num*spatial_dim) //bottom_data: (channels_*num) x (spatial_dim) //spatial_sum_multiplier: spatial_dim x 1 //alpha : 1./(num*spatial_dim); beta : 0 //num_by_chans = alpha * (bottom_data x spatial_sum_multiplier) + beta * num_by_chans //其中spatial_sum_multiplier的值都为1 //注意关键字是CblasTrans!! //num_by_chans_ : channels_ x num; //batch_sum_multiplier_ : num x 1; //mean_ = 1. x (num_by_chans_ x batch_sum_multiplier_) //mean_ : channels_ x 1 //计算得到对应channels的平均值,这也解释了为什么之前要除以1./(num*spatial_dim) //而不是仅除以1./spatial_dim,这样减少了计算量 caffe_cpu_gemv<Dtype>(CblasNoTrans, channels_ * num, spatial_dim, 1. / (num * spatial_dim), bottom_data, spatial_sum_multiplier_.cpu_data(), 0., num_by_chans_.mutable_cpu_data()); // 2.计算均值,计算N各的平均值. // 由于输出的是channels上的均值,因此需要转置 // 上一步得到的N*C的均值,再按照num求均值,因为batch_sum全部为1, caffe_cpu_gemv<Dtype>(CblasTrans, num, channels_, 1., num_by_chans_.cpu_data(), batch_sum_multiplier_.cpu_data(), 0., mean_.mutable_cpu_data()); } // subtract mean // 进行 x - mean_x 操作,需要注意按照通道,即先确定x属于哪个通道. // caffe_cpu_gemm 实现alpha * A*B + beta* C // 输入是num*1 * 1* channels_,输出是num*channels_ caffe_cpu_gemm<Dtype>(CblasNoTrans, CblasNoTrans, num, channels_, 1, 1, batch_sum_multiplier_.cpu_data(), mean_.cpu_data(), 0., num_by_chans_.mutable_cpu_data()); caffe_cpu_gemm<Dtype>(CblasNoTrans, CblasNoTrans, channels_ * num, spatial_dim, 1, -1, num_by_chans_.cpu_data(), spatial_sum_multiplier_.cpu_data(), 1., top_data); if (!use_global_stats_) { // compute variance using var(X) = E((X-EX)^2) 训练时,计算方差, 此处的top已经为x-mean_x了 Dtype* var_data = variance_.mutable_cpu_data(); for(int c = 0; c < channels_; c++){ Dtype sum_value = Dtype(0.); for(int b = 0; b < num; b++){ for(int i = 0; i < spatial_dim; i++){ Dtype squre_value = Dtype(0.); caffe_powx(1, top_data + b * channels_ * spatial_dim + c * spatial_dim + i, Dtype(2.0), &squre_value); sum_value += squre_value; } } var_data[c] = sum_value / (num * spatial_dim); } // compute and save moving average // 均值和方差计算完成后,需要更新batch的滑动系数 // y = alpha * x + beta * y // this->blobs_[2] 存放的是平均滑动系数 this->blobs_[2]->mutable_cpu_data()[0] *= moving_average_fraction_; this->blobs_[2]->mutable_cpu_data()[0] += 1; caffe_cpu_axpby(mean_.count(), Dtype(1), mean_.cpu_data(), moving_average_fraction_, this->blobs_[0]->mutable_cpu_data()); int m = bottom[0]->count()/channels_; Dtype bias_correction_factor = m > 1? Dtype(m)/(m-1) : 1; caffe_cpu_axpby(variance_.count(), bias_correction_factor, variance_.cpu_data(), moving_average_fraction_, this->blobs_[1]->mutable_cpu_data()); } // normalize variance, 方差求个根号,加上eps为防止分母为0 caffe_add_scalar(variance_.count(), eps_, variance_.mutable_cpu_data()); caffe_powx(variance_.count(), variance_.cpu_data(), Dtype(0.5), variance_.mutable_cpu_data()); // top_data = x-mean_x/sqrt(variance_),此处的top_data已经之前转化为x-mean_x了 const Dtype* var_data = variance_.cpu_data(); for(int b = 0; b < num; b ++){ for(int c = 0; c < channels_; c++){ caffe_cpu_scale(spatial_dim, Dtype(1 / var_data[c]), top_data + b * channels_ * spatial_dim + c * spatial_dim, top_data + b * channels_ * spatial_dim + c * spatial_dim); } } caffe_copy(x_norm_.count(), top_data, x_norm_.mutable_cpu_data());// x_norm_.cpu_data stored normolized_top_data /********************scale-forward**************/ const Dtype* scale_data = this->blobs_[3]->cpu_data(); const Dtype* bias_data = this->blobs_[4]->cpu_data(); for (int n = 0; n < num; ++n) { for (int d = 0; d < channels_; ++d) { const Dtype factor = scale_data[d]; const Dtype bias = bias_data[d]; caffe_cpu_scale(spatial_dim, factor, bottom_data, top_data); caffe_add_scalar(spatial_dim, bias, top_data); bottom_data += spatial_dim; top_data += spatial_dim; } } /* caffe_copy(x_norm_.count(), top_data, x_norm_.mutable_cpu_diff()); // x_norm_.cpu_diff stored scaled_top_data */ /********************scale-forward**************/ } template <typename Dtype> void BatchNormScaleLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) { const Dtype* top_diff; if (bottom[0]!= top[0]) { top_diff = top[0]->cpu_diff(); } else { caffe_copy(x_norm_.count(), top[0]->cpu_diff(), x_norm_.mutable_cpu_diff()); top_diff = top[0]->cpu_diff(); } int num = bottom[0]->shape()[0]; int spatial_dim = bottom[0]->count()/(bottom[0]->shape(0)*channels_); if(this->param_propagate_down_[4]){ Dtype* bias_diff = this->blobs_[4]->mutable_cpu_diff(); caffe_cpu_gemv<Dtype>(CblasNoTrans, channels_ * num, spatial_dim, Dtype(1), top_diff, spatial_sum_multiplier_.cpu_data(), Dtype(0), num_by_chans_.mutable_gpu_data()); caffe_cpu_gemv<Dtype>(CblasTrans, num, channels_, 1., num_by_chans_.cpu_data(), batch_sum_multiplier_.cpu_data(), 0., bias_diff); } Dtype* bottom_diff = bottom[0]->mutable_cpu_diff(); const Dtype* norm_data = x_norm_.cpu_data(); //const Dtype* top_data = x_norm_.cpu_diff(); const Dtype* var_data = variance_.cpu_data(); if (use_global_stats_) { for(int b = 0; b < num; b ++){ for(int c = 0; c < channels_; c++){ caffe_cpu_scale(spatial_dim, Dtype(1 / var_data[c]), top_diff + b * channels_ * spatial_dim + c * spatial_dim, bottom_diff + b * channels_ * spatial_dim + c * spatial_dim); } } return; } // if S = alpha * (X-mean(X))/(sqrt(var(X)+eps)) + bias, then // // dE(S)/dX = // alpha * (dE/dS - mean(dE/dS) - mean(dE/dS \cdot Y) \cdot Y) // ./ sqrt(var(X) + eps) // // where \cdot and./ are hadamard product and elementwise division, // respectively, dE/dS is the top diff, and mean/var/sum are all computed // along all dimensions except the channels dimension. In the above // equation, the operations allow for expansion (i.e. broadcast) along all // dimensions except the channels dimension where required. // sum(dE/dS \cdot Y) caffe_mul(top[0]->count(), norm_data, top_diff, bottom_diff); //new_added /*****************scale-diff*************/ if(this->param_propagate_down_[3]){ Dtype* scale_diff = this->blobs_[3]->mutable_cpu_diff(); caffe_cpu_gemv<Dtype>(CblasNoTrans, channels_ * num,
1,518
OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package io.airbyte.integrations.destination.kafka; import com.fasterxml.jackson.databind.JsonNode; import com.google.common.collect.ImmutableMap; import io.airbyte.commons.json.Jsons; import io.airbyte.integrations.BaseConnector; import io.airbyte.integrations.base.AirbyteMessageConsumer; import io.airbyte.integrations.base.Destination; import io.airbyte.integrations.base.IntegrationRunner; import io.airbyte.integrations.base.JavaBaseConstants; import io.airbyte.integrations.destination.StandardNameTransformer; import io.airbyte.protocol.models.AirbyteConnectionStatus; import io.airbyte.protocol.models.AirbyteConnectionStatus.Status; import io.airbyte.protocol.models.AirbyteMessage; import io.airbyte.protocol.models.ConfiguredAirbyteCatalog; import java.util.UUID; import java.util.function.Consumer; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.kafka.clients.producer.RecordMetadata; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class KafkaDestination extends BaseConnector implements Destination { private static final Logger LOGGER = LoggerFactory.getLogger(KafkaDestination.class); public static final String COLUMN_NAME_AB_ID = JavaBaseConstants.COLUMN_NAME_AB_ID; public static final String COLUMN_NAME_EMITTED_AT = JavaBaseConstants.COLUMN_NAME_EMITTED_AT; public static final String COLUMN_NAME_DATA = JavaBaseConstants.COLUMN_NAME_DATA; public static final String COLUMN_NAME_STREAM = "_airbyte_stream"; private final StandardNameTransformer namingResolver; public KafkaDestination() { this.namingResolver = new StandardNameTransformer(); } @Override public AirbyteConnectionStatus check(JsonNode config) { try { final String testTopic = config.has("test_topic")? config.get("test_topic").asText() : ""; if (!testTopic.isBlank()) { final KafkaDestinationConfig kafkaDestinationConfig = KafkaDestinationConfig.getKafkaDestinationConfig(config); final KafkaProducer<String, JsonNode> producer = kafkaDestinationConfig.getProducer(); final String key = UUID.randomUUID().toString(); final JsonNode value = Jsons.jsonNode(ImmutableMap.of( COLUMN_NAME_AB_ID, key, COLUMN_NAME_STREAM, "test-topic-stream", COLUMN_NAME_EMITTED_AT, System.currentTimeMillis(), COLUMN_NAME_DATA, Jsons.jsonNode(ImmutableMap.of("test-key", "test-value")))); final RecordMetadata metadata = producer.send(new ProducerRecord<>( namingResolver.getIdentifier(testTopic), key, value)).get(); producer.flush(); LOGGER.info("Successfully connected to Kafka brokers for topic '{}'.", metadata.topic()); } return new AirbyteConnectionStatus().withStatus(Status.SUCCEEDED); } catch (Exception e) { LOGGER.error("Exception attempting to connect to the Kafka brokers: ", e); return new AirbyteConnectionStatus() .withStatus(Status.FAILED) .withMessage("Could not connect to the Kafka brokers with provided configuration. \n" + e.getMessage()); } } @Override public AirbyteMessageConsumer getConsumer(JsonNode config, ConfiguredAirbyteCatalog catalog, Consumer<AirbyteMessage> outputRecordCollector) { return new KafkaRecordConsumer(KafkaDestinationConfig.getKafkaDestinationConfig(config), catalog, outputRecordCollector, namingResolver); } public static void main(String[] args) throws Exception { final Destination destination = new KafkaDestination(); LOGGER.info("Starting destination: {}", KafkaDestination.class); new IntegrationRunner(destination).run(args); LOGGER.info("Completed destination: {}", KafkaDestination.class); } } ======================= File: airbyte-integrations/connectors/destination-jdbc/src/main/java/io/airbyte/integrations/destination/jdbc/copy/gcs/GcsConfig.java ======================= /* * MIT License * * Copyright (c) 2020 Airbyte * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package io.airbyte.integrations.destination.jdbc.copy.gcs; import com.fasterxml.jackson.databind.JsonNode; public class GcsConfig { private final String projectId; private final String bucketName; private final String credentialsJson; public GcsConfig(String projectId, String bucketName, String credentialsJson) { this.projectId = projectId; this.bucketName = bucketName; this.credentialsJson = credentialsJson; } public String getProjectId() { return projectId; } public String getBucketName() { return bucketName; } public String getCredentialsJson() { return credentialsJson; } public static GcsConfig getGcsConfig(JsonNode config) { return new GcsConfig( config.get("loading_method").get("project_id").asText(), config.get("loading_method").get("bucket_name").asText(), config.get("loading_method").get("credentials_json").asText()); } } ======================= File: airbyte-integrations/connectors/source-postgres/src/test-integration/java/io/airbyte/integrations/io/airbyte/integration_tests/sources/PostresSourceDatatypeTest.java ======================= /* * MIT License * * Copyright (c) 2020 Airbyte * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package io.airbyte.integrations.io.airbyte.integration_tests.sources; import com.fasterxml.jackson.databind.JsonNode; import com.google.common.collect.ImmutableMap; import io.airbyte.commons.json.Jsons; import io.airbyte.db.Database; import io.airbyte.db.Databases; import io.airbyte.integrations.standardtest.source.AbstractSourceDatabaseTypeTest; import io.airbyte.integrations.standardtest.source.TestDataHolder; import io.airbyte.integrations.standardtest.source.TestDestinationEnv; import io.airbyte.protocol.models.JsonSchemaPrimitive; import java.sql.SQLException; import org.jooq.SQLDialect; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testcontainers.containers.PostgreSQLContainer; public class PostresSourceDatatypeTest extends AbstractSourceDatabaseTypeTest { private PostgreSQLContainer<?> container; private JsonNode config; private static final Logger LOGGER = LoggerFactory .getLogger(PostresSourceDatatypeTest.class); @Override protected Database setupDatabase() throws SQLException { container = new PostgreSQLContainer<>("postgres:13-alpine"); container.start(); final JsonNode replicationMethod = Jsons.jsonNode(ImmutableMap.builder() .put("method", "Standard") .build()); config = Jsons.jsonNode(ImmutableMap.builder() .put("host", container.getHost()) .put("port", container.getFirstMappedPort()) .put("database", container.getDatabaseName()) .put("username", container.getUsername()) .put("password", container.getPassword()) .put("ssl", false) .put("replication_method", replicationMethod) .build()); LOGGER.warn("PPP:config:" + config); final Database database = Databases.createDatabase( config.get("username").asText(), config.get("password").asText(), String.format("jdbc:postgresql://%s:%s/%s", config.get("host").asText(), config.get("port").asText(), config.get("database").asText()), "org.postgresql.Driver", SQLDialect.POSTGRES); database.query(ctx -> ctx.fetch("CREATE SCHEMA TEST;")); database.query(ctx -> ctx.fetch("CREATE TYPE mood AS ENUM ('sad', 'ok', 'happy');")); database.query(ctx -> ctx.fetch("CREATE TYPE inventory_item AS (\n" + " name text,\n" + " supplier_id integer,\n" + " price numeric\n" + ");")); return database; } @Override protected String getNameSpace() { return "test"; } @Override protected String getImageName() { return "airbyte/source-postgres:dev"; } @Override protected JsonNode getConfig() { return config; } @Override protected void tearDown(TestDestinationEnv testEnv) { container.close(); } @Override protected void initTests() { addDataTypeTestData( TestDataHolder.builder() .sourceType("bigint") .airbyteType(JsonSchemaPrimitive.NUMBER) .addInsertValues("-9223372036854775808", "9223372036854775807", "0", "null") .addExpectedValues("-9223372036854775808", "9223372036854775807", "0", null) .build()); addDataTypeTestData( TestDataHolder.builder() .sourceType("bigserial") .airbyteType(JsonSchemaPrimitive.NUMBER) .addInsertValues("1", "9223372036854775807", "0", "-9223372036854775808") .addExpectedValues("1", "9223372036854775807", "0", "-9223372036854775808") .build()); addDataTypeTestData( TestDataHolder.builder() .sourceType("serial") .airbyteType(JsonSchemaPrimitive.NUMBER) .addInsertValues("1", "2147483647", "0", "-2147483647") .addExpectedValues("1", "2147483647", "0", "-2147483647") .build()); addDataTypeTestData( TestDataHolder.builder() .sourceType("smallserial") .airbyteType(JsonSchemaPrimitive.NUMBER) .addInsertValues("1", "32767", "0", "-32767") .addExpectedValues("1", "32767", "0", "-32767") .build()); // BUG https://github.com/airbytehq/airbyte/issues/3932 // BIT type is currently parsed as a Boolean which is incorrect // addDataTypeTestData( // TestDataHolder.builder() //.sourceType("bit") //.fullSourceDataType("BIT(3)") //.airbyteType(JsonSchemaPrimitive.NUMBER) //.addInsertValues("B'101'") // //.addExpectedValues("101") // -.build()); addDataTypeTestData( TestDataHolder.builder() .sourceType("bit_varying") .fullSourceDataType("BIT VARYING(5)") .airbyteType(JsonSchemaPrimitive.NUMBER) .addInsertValues("B'101'", "null") .addExpectedValues("101", null) .build()); addDataTypeTestData( TestDataHolder.builder() .sourceType("boolean") .airbyteType(JsonSchemaPrimitive.BOOLEAN) .addInsertValues("true", "'yes'", "'1'", "false", "'no'", "'0'", "null") .addExpectedValues("true", "true", "true", "false", "false", "false", null) .build()); addDataTypeTestData( TestDataHolder.builder() .sourceType("bytea") .airbyteType(JsonSchemaPrimitive.OBJECT) .addInsertValues("decode('1234', 'hex')") .addExpectedValues("EjQ=") .build()); addDataTypeTestData( TestDataHolder.builder() .sourceType("character") .airbyteType(JsonSchemaPrimitive.STRING) .addInsertValues("'a'", "'*'", "null") .addExpectedValues("a", "*", null) .build()); addDataTypeTestData( TestDataHolder.builder() .sourceType("character") .fullSourceDataType("character(8)") .airbyteType(JsonSchemaPrimitive.STRING) .addInsertValues("'{asb123}'", "'{asb12}'") .addExpectedValues("{asb123}", "{asb12} ") .build()); addDataTypeTestData( TestDataHolder.builder() .sourceType("varchar") .airbyteType(JsonSchemaPrimitive.STRING) .addInsertValues("'a'", "'abc'", "'Миші йдуть на південь, не питай чому;'", "'櫻花分店'", "''", "null", "'\\xF0\\x9F\\x9A\\x80'") .addExpectedValues("a", "abc", "Миші йдуть на південь, не питай чому;", "櫻花分店", "", null, "\\xF0\\x9F\\x9A\\x80") .build()); addDataTypeTestData( TestDataHolder.builder() .sourceType("varchar") .fullSourceDataType("character(12)") .airbyteType(JsonSchemaPrimitive.STRING) .addInsertValues("'a'", "'abc'", "'Миші йдуть;'", "'櫻花分店'", "''", "null") .addExpectedValues("a ", "abc ", "Миші йдуть; ", "櫻花分店 ", " ", null) .build()); addDataTypeTestData( TestDataHolder.builder() .sourceType("cidr") .airbyteType(JsonSchemaPrimitive.STRING) .addInsertValues("null", "'192.168.100.128/25'", "'192.168/24'", "'192.168.1'", "'128.1'", "'2001:4f8:3:ba::/64'") .addExpectedValues(null, "192.168.100.128/25", "192.168.0.0/24", "192.168.1.0/24", "192.168.3.11/16", "2001:4f8:3:ba::/64") .build()); // JdbcUtils-> DATE_FORMAT is set as ""yyyy-MM-dd'T'HH:mm:ss'Z'"" so it doesnt suppose to handle BC // dates addDataTypeTestData( TestDataHolder.builder() .sourceType("date") .airbyteType(JsonSchemaPrimitive.STRING) .addInsertValues("'1999-01-08'", "null") // "'199-10-10 BC'" .addExpectedValues("1999-01-08T00:00:00Z", null) //, "199-10-10 BC") .build()); // Values "'-Infinity'", "'Infinity'", "'Nan'" will not be parsed due to: // JdbcUtils -> setJsonField contains: // case FLOAT, DOUBLE -> o.put(columnName, nullIfInvalid(() -> r.getDouble(i), Double::isFinite)); addDataTypeTestData( TestDataHolder.builder() .sourceType("float8") .airbyteType(JsonSchemaPrimitive.NUMBER) .addInsertValues("'123'", "'1234567890.1234567'", "null") .addExpectedValues("123.0", "1.2345678901234567E9", null) .build()); // Values "'-Infinity'", "'Infinity'", "'Nan'" will not be parsed due to: // JdbcUtils -> setJsonField contains: // case FLOAT, DOUBLE -> o.put(columnName, nullIfInvalid(() -> r.getDouble(i), Double::isFinite)); addDataTypeTestData( TestDataHolder.builder() .sourceType("float") .airbyteType(JsonSchemaPrimitive.NUMBER) .addInsertValues("'123'", "'1234567890.1234567'", "null") .addExpectedValues("123.0", "1.2345678901234567E9", null) .build()); addDataTypeTestData( TestDataHolder.builder() .sourceType("inet") .airbyteType(JsonSchemaPrimitive.STRING) .addInsertValues("'172.16.31.10/24'", "'172.16.31.10'", "'198.10/8'", "null") .addExpectedValues("172.16.31.10/24", "172.16.31.10", "172.16.31.10/8", null) .build()); addDataTypeTestData( TestDataHolder.builder() .sourceType("int") .airbyteType(JsonSchemaPrimitive.NUMBER) .addInsertValues("null", "-2147483648", "2147483647") .addExpectedValues(null, "-2147483648", "2147483647") .build()); addDataTypeTestData( TestDataHolder.builder() .sourceType("interval") .airbyteType(JsonSchemaPrimitive.STRING) .addInsertValues("null", "'P1Y2M3DT4H5M6S'", "'-178000000'", "'178000000'") .addExpectedValues(null, "1 year 2 mons 3 days 04:05:06", "-49444:26:40", "49444:26:40") .build()); addDataTypeTestData( TestDataHolder.builder() .sourceType("json") .airbyteType(JsonSchemaPrimitive.STRING) .addInsertValues("null", "'{\"a\": 10, \"b\": 15}'") .addExpectedValues(null, "{\"a\": 10, \"b\": 15}") .build()); addDataTypeTestData( TestDataHolder.builder() .sourceType("jsonb") .airbyteType(JsonSchemaPrimitive.STRING) .addInsertValues("null", "'[1, 2, 3]'::jsonb") .addExpectedValues(null, "[1, 2, 3]") .build()); addDataTypeTestData( TestDataHolder.builder() .sourceType("macaddr") .airbyteType(JsonSchemaPrimitive.STRING) .addInsertValues("null", "'08:00:2b:01:02:03'", "'08-00-2b-01-02-04'", "'08002b:010205'") .addExpectedValues(null, "08:00:2b:01:02:03", "08:00:2b:01:02:04", "08:00:2b:01:02:05") .build()); addDataTypeTestData( TestDataHolder.builder() .sourceType("macaddr8") .airbyteType(JsonSchemaPrimitive.STRING) .addInsertValues("null", "'fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b'", "'08-00-2b-01-02-03-04-06'", "'08002b:0102030407'") .addExpectedValues(null, "fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b", "fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b", "fc00:db20:35b:7399::5") .build()); // The Money type fails when amount is > 1,000. in JdbcUtils-> rowToJson as r.getObject(i); // Bad value for type double : 1,000.01 // The reason is that in jdbc implementation money type is tried to get as Double (jdbc // implementation) // Max values for Money type: "-92233720368547758.08", "92233720368547758.07" addDataTypeTestData( TestDataHolder.builder() .sourceType("money") .airbyteType(JsonSchemaPrimitive.STRING) .addInsertValues("null", "'999.99'") .addExpectedValues(null, "999.99") .build()); // The numeric type in Postres may contain 'Nan' type, but in JdbcUtils-> rowToJson // we try to map it like this, so it fails // case NUMERIC, DECIMAL -> o.put(columnName, nullIfInvalid(() -> r.getBigDecimal(i))); addDataTypeTestData( TestDataHolder.builder() .sourceType("numeric") .airbyteType(JsonSchemaPrimitive.NUMBER) .addInsertValues("'99999'", "null") .addExpectedValues("99999", null) .build()); // The numeric type in Postres may contain 'Nan' type, but in JdbcUtils-> rowToJson // we try to map it like this, so it fails // case NUMERIC, DECIMAL -> o.put(columnName, nullIfInvalid(() -> r.getBigDecimal(i))); addDataTypeTestData( TestDataHolder.builder() .sourceType("decimal") .airbyteType(JsonSchemaPrimitive.NUMBER) .addInsertValues("99999", "5.1", "0", "null") .addExpectedValues("99999", "5.1", "0", null) .build()); addDataTypeTestData( TestDataHolder.builder() .sourceType("smallint") .airbyteType(JsonSchemaPrimitive.NUMBER) .addInsertValues("null", "-32768", "32767") .addExpectedValues(null, "-32768", "32767") .build()); addDataTypeTestData( TestDataHolder.builder() .sourceType("text") .airbyteType(JsonSchemaPrimitive.STRING) .addInsertValues("'a'", "'abc'", "'Миші йдуть;'", "'櫻花分店'", "''", "null", "'\\xF0\\x9F\\x9A\\x80'") .addExpectedValues("a", "abc", "Миші йдуть;", "櫻花分店", "", null, "\\xF0\\x9F\\x9A\\x80") .build()); // JdbcUtils-> DATE_FORMAT is set as ""yyyy-MM-dd'T'HH:mm:ss'Z'"" for both Date and Time types. // So Time only (04:05:06) would be represented like "1970-01-01T04:05:06Z" which is incorrect addDataTypeTestData( TestDataHolder.builder() .sourceType("time") .airbyteType(JsonSchemaPrimitive.STRING) .addInsertValues("null") .addNullExpectedValue() .build()); // JdbcUtils-> DATE_FORMAT is set as ""yyyy-MM-dd'T'HH:mm:ss'Z'"" for both Date and Time types. // So Time only (04:05:06) would be represented like "1970-01-01T04:05:06Z" which is incorrect addDataTypeTestData( TestDataHolder.builder() .sourceType("timetz") .airbyteType(JsonSchemaPrimitive.STRING) .addInsertValues("null") .addNullExpectedValue() .build()); addDataTypeTestData( TestDataHolder.builder() .sourceType("timestamp") .airbyteType(JsonSchemaPrimitive.STRING) .addInsertValues("TIMESTAMP '2004-10-19 10:23:54'", "null") .addExpectedValues("2004-10-19T10:23:54Z", null) .build()); // May be run locally, but correct the timezone aacording to your location // addDataTypeTestData( // TestDataHolder.builder() //.sourceType("timestamptz") //.airbyteType(JsonSchemaPrimitive.STRING) //.addInsertValues("TIMESTAMP '2004-10-19 10:23:54+02'", "null") //.addExpectedValues("2004-10-19T07:23:54Z", null) //.build()); addDataTypeTestData( TestDataHolder.builder() .sourceType("tsvector") .airbyteType(JsonSchemaPrimitive.STRING) .addInsertValues("to_tsvector('The quick brown fox jumped over the lazy dog.')") .addExpectedValues("'brown':3 'dog':9 'fox':4 'jump':5 'lazi':8 'quick':2") .build()); addDataTypeTestData( TestDataHolder.builder() .sourceType("uuid") .airbyteType(JsonSchemaPrimitive.STRING) .addInsertValues("'a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11'", "null") .addExpectedValues("a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11", null) .build()); addDataTypeTestData( TestDataHolder.builder() .sourceType("xml") .airbyteType(JsonSchemaPrimitive.STRING) .addInsertValues( "XMLPARSE (DOCUMENT '<?xml version=\"1.0\"?><book><title>Manual</title><chapter>...</chapter></book>')", "null", "''") .addExpectedValues("<book><title>Manual</title><chapter>...</chapter></book>", null, "") .build()); // preconditions for this test are set at the time of database creation (setupDatabase method) addDataTypeTestData( TestDataHolder.builder() .sourceType("mood") .airbyteType(JsonSchemaPrimitive.STRING) .addInsertValues("'happy'", "null") .addExpectedValues("happy", null) .build()); addDataTypeTestData( TestDataHolder.builder() .sourceType("text") .fullSourceDataType("text[]") .airbyteType(JsonSchemaPrimitive.STRING) .addInsertValues("'{10000, 10000, 10000, 10000}'", "null") .addExpectedValues("{10000,10000,10000,10000}", null) .build()); addDataTypeTestData( TestDataHolder.builder() .sourceType("inventory_item") .airbyteType(JsonSchemaPrimitive.STRING) .addInsertValues("ROW('fuzzy dice', 42, 1.99)", "null") .addExpectedValues("(\"fuzzy dice\",42,1.99)", null) .build()); addDataTypeTestData( TestDataHolder.builder() .sourceType("tsrange") .airbyteType(JsonSchemaPrimitive.STRING) .addInsertValues("'(2010-01-01 14:30, 2010-01-01 15:30)'", "null") .addExpectedValues("(\"2010-01-01 14:30:00\",\"2010-01-01 15:30:00\")", null) .build()); addDataTypeTestData( TestDataHolder.builder() .sourceType("box") .airbyteType(JsonSchemaPrimitive.STRING) .addInsertValues("'((3,7),(15,18))'", "'((0,0),(0,0))'", "null") .addExpectedValues("(15,18),(3,7)", "(0,0),(0,0)", null) .build()); addDataTypeTestData( TestDataHolder.builder() .sourceType("circle") .airbyteType(JsonSchemaPrimitive.STRING) .addInsertValues("'(5,7),10'", "'(0,0),0'", "'(-10,-4),10'", "null") .addExpectedValues("<(5,7),10>", "<(0,0),0>", "<(-10,-4),10>", null) .build()); addDataTypeTestData( TestDataHolder.builder() .sourceType("line") .airbyteType(JsonSchemaPrimitive.STRING) .addInsertValues("'{4,5,6}'", "'{0,1,0}'", "null") .addExpectedValues("{4,5,6}", "{0,1,0}", null) .build()); addDataTypeTestData( TestDataHolder.builder() .sourceType("lseg") .airbyteType(JsonSchemaPrimitive.STRING) .addInsertValues("'((3,7),(15,18))'", "'((0,0),(0,0))'", "null") .addExpectedValues("[(3,7),(15,18)]", "[(0,0),(0,0)]", null) .build()); addDataTypeTestData( TestDataHolder.builder() .sourceType("path") .airbyteType(JsonSchemaPrimitive.STRING) .addInsertValues("'((3,7),(15,18))'", "'((0,0),(0,0))'", "null") .addExpectedValues("((3,7),(15,18))", "((0,0),(0,0))", null) .build()); addDataTypeTestData( TestDataHolder.builder() .sourceType("point") .airbyteType(JsonSchemaPrimitive.NUMBER) .addInsertValues("'(3,7)'", "'(0,0)'", "'(999999999999999999999999,0)'", "null") .addExpectedValues("(3,7)", "(0,0)", "(1e+24,0)", null) .build()); addDataTypeTestData( TestDataHolder.builder() .sourceType("polygon") .airbyteType(JsonSchemaPrimitive.STRING) .addInsertValues("'((3,7),(15,18))'", "'((0,0),(0,0))'", "'((0,0),(999999999999999999999999,0))'", "null") .addExpectedValues("((3,7),(15,18))", "((0,0),(0,0))", "((0,0),(1e+24,0))", null) .build()); } } ======================= File: airbyte-integrations/bases/debezium/src/main/java/io/airbyte/integrations/debezium/AirbyteDebeziumHandler.java ======================= /* * MIT License * * Copyright (c) 2020 Airbyte * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package io.airbyte.integrations.debezium; import com.fasterxml.jackson.databind.JsonNode; import io.airbyte.commons.util.AutoCloseableIterator; import io.airbyte.commons.util.AutoCloseableIterators; import io.airbyte.commons.util.CompositeIterator; import io.airbyte.commons.util.MoreIterators; import io.airbyte.integrations.debezium.internals.AirbyteFileOffsetBackingStore; import io.airbyte.integrations.debezium.internals.AirbyteSchemaHistoryStorage; import io.airbyte.integrations.debezium.internals.DebeziumEventUtils; import io.airbyte.integrations.debezium.internals.DebeziumRecordIterator; import io.airbyte.integrations.debezium.internals.DebeziumRecordPublisher; import io.airbyte.integrations.debezium.internals.FilteredFileDatabaseHistory; import io.airbyte.protocol.models.AirbyteMessage; import io.airbyte.protocol.models.ConfiguredAirbyteCatalog; import io.debezium.engine.ChangeEvent; import java.time.Instant; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Properties; import java.util.concurrent.LinkedBlockingQueue; import java.util.function.Supplier; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class acts as the bridge between Airbyte DB connectors and debezium. If a DB connector wants * to use debezium for CDC, it should use this class */ public class AirbyteDebeziumHandler { private static final Logger LOGGER = LoggerFactory.getLogger(AirbyteDebeziumHandler.class); /** * We use 10000 as capacity cause the default queue size and batch size of debezium is : * {@link io.debezium.config.CommonConnectorConfig#DEFAULT_MAX_BATCH_SIZE}is 2048 * {@link io.debezium.config.CommonConnectorConfig#DEFAULT_MAX_QUEUE_SIZE} is 8192 */ private static final int QUEUE_CAPACITY = 10000; private final Properties connectorProperties; private final JsonNode config; private final CdcTargetPosition targetPosition; private final ConfiguredAirbyteCatalog catalog; private final boolean trackSchemaHistory; private final LinkedBlockingQueue<ChangeEvent<String, String>> queue; public AirbyteDebeziumHandler(JsonNode config, CdcTargetPosition targetPosition, Properties connectorProperties, ConfiguredAirbyteCatalog catalog, boolean trackSchemaHistory) { this.config = config; this.targetPosition = targetPosition; this.connectorProperties = connectorProperties; this.catalog = catalog; this.trackSchemaHistory = trackSchemaHistory; this.queue = new LinkedBlockingQueue<>(QUEUE_CAPACITY); } public List<AutoCloseableIterator<AirbyteMessage>> getIncrementalIterators(CdcSavedInfoFetcher cdcSavedInfoFetcher, CdcStateHandler cdcStateHandler, CdcMetadataInjector cdcMetadataInjector, Instant emittedAt) { LOGGER.info("using CDC: {}", true); final AirbyteFileOffsetBackingStore offsetManager = AirbyteFileOffsetBackingStore.initializeState(cdcSavedInfoFetcher.getSavedOffset()); final Optional<AirbyteSchemaHistoryStorage> schemaHistoryManager = schemaHistoryManager(cdcSavedInfoFetcher); final DebeziumRecordPublisher publisher = new DebeziumRecordPublisher(connectorProperties, config, catalog, offsetManager, schemaHistoryManager); publisher.start(queue); // handle state machine around pub/sub logic. final AutoCloseableIterator<ChangeEvent<String, String>> eventIterator = new DebeziumRecordIterator( queue, targetPosition, publisher::hasClosed, publisher::close); // convert to airbyte message. final AutoCloseableIterator<AirbyteMessage> messageIterator = AutoCloseableIterators .transform( eventIterator, (event) -> DebeziumEventUtils.toAirbyteMessage(event, cdcMetadataInjector, emittedAt)); // our goal is to get the state at the time this supplier is called (i.e. after all message records // have been produced) final Supplier<AirbyteMessage> stateMessageSupplier = () -> { Map<String, String> offset = offsetManager.read(); String dbHistory = trackSchemaHistory? schemaHistoryManager .orElseThrow(() -> new RuntimeException("Schema History Tracking is true but manager is not initialised")).read() : null; return cdcStateHandler.saveState(offset, dbHistory); }; // wrap the supplier in an iterator so that we can concat it to the message iterator. final Iterator<AirbyteMessage> stateMessageIterator = MoreIterators.singletonIteratorFromSupplier(stateMessageSupplier); // this structure guarantees that the debezium engine will be closed, before we attempt to emit the // state file. we want this so that we have a guarantee that the debezium offset file (which we use // to produce the state file) is up-to-date. final CompositeIterator<AirbyteMessage> messageIteratorWithStateDecorator = AutoCloseableIterators.concatWithEagerClose(messageIterator, AutoCloseableIterators.fromIterator(stateMessageIterator)); return Collections.singletonList(messageIteratorWithStateDecorator); } private Optional<AirbyteSchemaHistoryStorage> schemaHistoryManager(CdcSavedInfoFetcher cdcSavedInfoFetcher) { if (trackSchemaHistory) { FilteredFileDatabaseHistory.setDatabaseName(config.get("database").asText()); return Optional.of(AirbyteSchemaHistoryStorage.initializeDBHistory(cdcSavedInfoFetcher.getSavedSchemaHistory())); } return Optional.empty(); } } ======================= File: airbyte-db/lib/src/main/java/io/airbyte/db/instance/development/DevDatabaseMigrator.java ======================= <gh_stars>1-10 /* * MIT License * * Copyright (c) 2020 Airbyte * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package io.airbyte.db.instance.development; import io.airbyte.db.instance.DatabaseMigrator; import io.airbyte.db.instance.FlywayDatabaseMigrator; import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.Optional; import org.flywaydb.core.Flyway; import org.flywaydb.core.api.MigrationInfo; import org.flywaydb.core.api.MigrationVersion; import org.flywaydb.core.api.configuration.Configuration; import org.flywaydb.core.api.configuration.FluentConfiguration; import org.flywaydb.core.api.output.BaselineResult; import org.flywaydb.core.api.output.MigrateResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This migrator can prepare the database with previous migrations, and only run the latest * migration for testing. It is used in {@link MigrationDevHelper#runLastMigration}. */ public class DevDatabaseMigrator implements DatabaseMigrator { private static final Logger LOGGER = LoggerFactory.getLogger(DevDatabaseMigrator.class); // A migrator that can run all migrations. private final DatabaseMigrator fullMigrator; // A migrator that will not run the last migration. It prepares the database to the state right // before the last migration. private final DatabaseMigrator baselineMigrator; public DevDatabaseMigrator(FlywayDatabaseMigrator fullMigrator) { this.fullMigrator = fullMigrator; this.baselineMigrator = getBaselineMigrator(fullMigrator); } private static class NoOpDatabaseMigrator implements DatabaseMigrator { @Override public MigrateResult migrate() { return null; } @Override public List<MigrationInfo> list() { return Collections.emptyList(); } @Override public BaselineResult createBaseline() { return null; } @Override public String dumpSchema() { return ""; } } /** * Create a baseline migration from a full migrator. The baseline migrator does not run the last * migration, which will be usually the migration to be tested. */ private static DatabaseMigrator getBaselineMigrator(FlywayDatabaseMigrator fullMigrator) { Configuration fullConfig = fullMigrator.getFlyway().getConfiguration(); FluentConfiguration baselineConfig = Flyway.configure() .dataSource(fullConfig.getDataSource()) .baselineVersion(fullConfig.getBaselineVersion()) .baselineDescription(fullConfig.getBaselineDescription()) .baselineOnMigrate(fullConfig.isBaselineOnMigrate()) .installedBy(fullConfig.getInstalledBy()) .table(fullConfig.getTable()) .locations(fullConfig.getLocations()); Optional<MigrationVersion> secondToLastMigrationVersion = MigrationDevHelper.getSecondToLastMigrationVersion(fullMigrator); if (secondToLastMigrationVersion.isEmpty()) { LOGGER.info("There is zero or one migration. No extra baseline setup is needed."); return new NoOpDatabaseMigrator(); } // Set the baseline flyway config to not run the last migration by setting the target migration // version. LOGGER.info("Baseline migrator target version: {}", secondToLastMigrationVersion.get()); baselineConfig.target(secondToLastMigrationVersion.get()); return new FlywayDatabaseMigrator(fullMigrator.getDatabase(), baselineConfig.load()); } @Override public MigrateResult migrate() { return fullMigrator.migrate(); } @Override public List<MigrationInfo> list() { return fullMigrator.list(); } @Override public BaselineResult createBaseline() { fullMigrator.createBaseline(); // Run all previous migration except for the last one to establish the baseline database state. baselineMigrator.migrate(); return fullMigrator.createBaseline(); } @Override public String dumpSchema() throws IOException { return fullMigrator.dumpSchema(); } } ======================= File: airbyte-integrations/connectors/destination-dynamodb/src/test/java/io/airbyte/integrations/destination/dynamodb/DynamodbDestinationTest.java ======================= /* * MIT License * * Copyright (c) 2020 Airbyte * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package io.airbyte.integrations.destination.dynamodb; import static org.junit.jupiter.api.Assertions.assertEquals; import com.fasterxml.jackson.databind.JsonNode; import io.airbyte.commons.json.Jsons; import io.airbyte.protocol.models.*; import org.junit.jupiter.api.Test; class DynamodbDestinationTest { @Test void testGetOutputTableNameWithString() throws Exception { var actual = DynamodbOutputTableHelper.getOutputTableName("test_table", "test_namespace", "test_stream"); assertEquals("test_table_test_namespace_test_stream", actual); } @Test void testGetOutputTableNameWithStream() throws Exception { var stream = new AirbyteStream(); stream.setName("test_stream"); stream.setNamespace("test_namespace"); var actual = DynamodbOutputTableHelper.getOutputTableName("test_table", stream); assertEquals("test_table_test_namespace_test_stream", actual); } @Test void testGetDynamodbDestinationdbConfig() throws Exception { JsonNode json = Jsons.deserialize("{\n" + " \"dynamodb_table_name\": \"test_table\",\n" + " \"dynamodb_region\": \"test_region\",\n" + " \"access_key_id\": \"test_key_id\",\n" + " \"secret_access_key\": \"test_access_key\"\n" + "}"); var config = DynamodbDestinationConfig.getDynamodbDestinationConfig(json); assertEquals(config.getTableName(), "test_table"); assertEquals(config.getRegion(), "test_region"); assertEquals(config.getAccessKeyId(), "test_key_id"); assertEquals(config.getSecretAccessKey(), "test_access_key"); } } ======================= File: airbyte-workers/src/main/java/io/airbyte/workers/process/WorkerHeartbeatServer.java ======================= /* * MIT License * * Copyright (c) 2020 Airbyte * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package io.airbyte.workers.process; import com.google.common.collect.ImmutableMap; import com.google.common.net.HttpHeaders; import io.airbyte.commons.json.Jsons; import java.io.IOException; import java.util.Map; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.servlet.ServletContextHandler; /** * Creates a server on a single port that returns a 200 JSON response on any path requested. This is * intended to stay up as long as the Kube worker exists so pods spun up can check if the spawning * Kube worker still exists. */ public class WorkerHeartbeatServer { private final int port; private Server server; public WorkerHeartbeatServer(int port) { this.port = port; } public void start() throws Exception { server = getServer(); server.start(); server.join(); } public void startBackground() throws Exception { server = getServer(); server.start(); } public void stop() throws Exception { server.stop(); } protected Server getServer() { Server server = new Server(port); ServletContextHandler handler = new ServletContextHandler(); handler.addServlet(WorkerHeartbeatServlet.class, "/*"); server.setHandler(handler); return server; } public static class WorkerHeartbeatServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { this.serveDefaultRequest(response); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { this.serveDefaultRequest(response); } public void doOptions(HttpServletRequest request, HttpServletResponse response) throws IOException { this.addCorsHeaders(response); } private void serveDefaultRequest(HttpServletResponse response) throws IOException { var outputMap = ImmutableMap.of("up", true); this.addCorsHeaders(response); response.setContentType("application/json"); response.setStatus(HttpServletResponse.SC_OK); response.getWriter().println(Jsons.serialize(outputMap)); } private void addCorsHeaders(HttpServletResponse response) { for (Map.Entry<String, String> entry : CORS_FILTER_MAP.entrySet()) { response.setHeader(entry.getKey(), entry.getValue()); } } } private static final ImmutableMap<String, String> CORS_FILTER_MAP = ImmutableMap.of( HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "*", HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "Origin, Content-Type, Accept, Content-Encoding", HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET, POST, PUT, DELETE, OPTIONS, HEAD"); } ======================= File: airbyte-workers/src/test/java/io/airbyte/workers/protocols/airbyte/HeartbeatMonitorTest.java ======================= <gh_stars>1-10 /* * MIT License * * Copyright (c) 2020 Airbyte * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package io.airbyte.workers.protocols.airbyte; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.time.Duration; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.function.Supplier; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class HeartbeatMonitorTest { private static final Duration HEART_BEAT_FRESH_DURATION = Duration.of(30, ChronoUnit.SECONDS); private static final Instant NOW = Instant.now(); private static final Instant FIVE_SECONDS_BEFORE = NOW.minus(5, ChronoUnit.SECONDS); private static final Instant THIRTY_SECONDS_BEFORE = NOW.minus(30, ChronoUnit.SECONDS); private Supplier<Instant> nowSupplier; private HeartbeatMonitor heartbeatMonitor; @SuppressWarnings("unchecked") @BeforeEach void setup() { nowSupplier = mock(Supplier.class); heartbeatMonitor = new HeartbeatMonitor(HEART_BEAT_FRESH_DURATION, nowSupplier); } @Test void testNeverBeat() { assertFalse(heartbeatMonitor.isBeating()); } @Test void testFreshBeat() { when(nowSupplier.get()).thenReturn(FIVE_SECONDS_BEFORE).thenReturn(NOW); heartbeatMonitor.beat(); assertTrue(heartbeatMonitor.isBeating()); } @Test void testStaleBeat() { when(nowSupplier.get()).thenReturn(THIRTY_SECONDS_BEFORE).thenReturn(NOW); heartbeatMonitor.beat(); assertFalse(heartbeatMonitor.isBeating()); } } ======================= File: airbyte-integrations/connectors/source-mssql/src/test/java/io/airbyte/integrations/source/mssql/MssqlSourceTest.java ======================= <reponame>luizgribeiro/airbyte<filename>airbyte-integrations/connectors/source-mssql/src/test/java/io/airbyte/integrations/source/mssql/MssqlSourceTest.java /* * MIT License * * Copyright (c) 2020 Airbyte * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package io.airbyte.integrations.source.mssql; import static org.junit.jupiter.api.Assertions.assertEquals; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import io.airbyte.commons.json.Jsons; import io.airbyte.commons.string.Strings; import io.airbyte.db.Database; import io.airbyte.db.Databases; import io.airbyte.protocol.models.AirbyteCatalog; import io.airbyte.protocol.models.CatalogHelpers; import io.airbyte.protocol.models.Field; import io.airbyte.protocol.models.JsonSchemaPrimitive; import io.airbyte.protocol.models.SyncMode; import java.sql.SQLException; import java.util.List; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.testcontainers.containers.MSSQLServerContainer; class MssqlSourceTest { private static final String DB_NAME = "dbo"; private static final String STREAM_NAME = "id_and_name"; private static final AirbyteCatalog CATALOG = new AirbyteCatalog().withStreams(Lists.newArrayList(CatalogHelpers.createAirbyteStream( STREAM_NAME, DB_NAME, Field.of("id", JsonSchemaPrimitive.NUMBER), Field.of("name", JsonSchemaPrimitive.STRING), Field.of("born", JsonSchemaPrimitive.STRING)) .withSupportedSyncModes(Lists.newArrayList(SyncMode.FULL_REFRESH, SyncMode.INCREMENTAL)) .withSourceDefinedPrimaryKey(List.of(List.of("id"))))); private JsonNode configWithoutDbName; private JsonNode config; private static MSSQLServerContainer<?> db; @BeforeAll static void init() { db = new MSSQLServerContainer<>("mcr.microsoft.com/mssql/server:2019-latest").acceptLicense(); db.start(); } // how to interact with the mssql test container manaully. // 1. exec into mssql container (not the test container container) // 2. /opt/mssql-tools/bin/sqlcmd -S localhost -U SA -P "A_Str0ng_Required_Password" @BeforeEach void setup() throws SQLException { configWithoutDbName = getConfig(db); final String dbName = Strings.addRandomSuffix("db", "_", 10).toLowerCase(); final Database database = getDatabase(configWithoutDbName); database.query(ctx -> { ctx.fetch(String.format("CREATE DATABASE %s;", dbName)); ctx.fetch(String.format("USE %s;", dbName)); ctx.fetch("CREATE TABLE id_and_name(id INTEGER NOT NULL, name VARCHAR(200), born DATETIMEOFFSET(7));"); ctx.fetch( "INSERT INTO id_and_name (id, name, born) VALUES (1,'picard', '2124-03-04T01:01:01Z'), (2, 'crusher', '2124-03-04T01:01:01Z'), (3, 'vash', '2124-03-04T01:01:01Z');"); return null; }); config = Jsons.clone(configWithoutDbName); ((ObjectNode) config).put("database", dbName); } @AfterAll static void cleanUp() { db.stop(); db.close(); } // if a column in mssql is used as a primary key and in a separate index the discover query returns // the column twice. we now de-duplicate it (pr: https://github.com/airbytehq/airbyte/pull/983). // this tests that this de-duplication is successful. @Test void testDiscoverWithPk() throws Exception { final Database database = getDatabase(configWithoutDbName); database.query(ctx -> { ctx.fetch(String.format("USE %s;", config.get("database"))); ctx.execute("ALTER TABLE id_and_name ADD CONSTRAINT i3pk PRIMARY KEY CLUSTERED (id);"); ctx.execute("CREATE INDEX i1 ON id_and_name (id);"); return null; }); final AirbyteCatalog actual = new MssqlSource().discover(config); assertEquals(CATALOG, actual); } private JsonNode getConfig(MSSQLServerContainer<?> db) { return Jsons.jsonNode(ImmutableMap.builder() .put("host", db.getHost()) .put("port", db.getFirstMappedPort()) .put("username", db.getUsername()) .put("password", <PASSWORD>()) .build()); } public static Database getDatabase(JsonNode config) { // todo (cgardens) - rework this abstraction so that we do not have to pass a null into the // constructor. at least explicitly handle it, even if the impl doesn't change. return Databases.createDatabase( config.get("username").asText(), config.get("password").asText(), String.format("jdbc:sqlserver://%s:%s", config.get("host").asText(), config.get("port").asInt()), "com.microsoft.sqlserver.jdbc.SQLServerDriver", null); } } ======================= File: airbyte-integrations/connectors/destination-e2e-test/src/main/java/io/airbyte/integrations/destination/e2e_test/LoggingDestination.java ======================= /* * MIT License * * Copyright (c) 2020 Airbyte * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package io.airbyte.integrations.destination.e2e_test; import com.fasterxml.jackson.databind.JsonNode; import io.airbyte.integrations.BaseConnector; import io.airbyte.integrations.base.AirbyteMessageConsumer; import io.airbyte.integrations.base.Destination; import io.airbyte.protocol.models.AirbyteConnectionStatus; import io.airbyte.protocol.models.AirbyteConnectionStatus.Status; import io.airbyte.protocol.models.AirbyteMessage; import io.airbyte.protocol.models.AirbyteMessage.Type; import io.airbyte.protocol.models.ConfiguredAirbyteCatalog; import java.util.function.Consumer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This destination logs each record it receives. */ public class LoggingDestination extends BaseConnector implements Destination { private static final Logger LOGGER = LoggerFactory.getLogger(LoggingDestination.class); @Override public AirbyteConnectionStatus check(final JsonNode config) { return new AirbyteConnectionStatus().withStatus(Status.SUCCEEDED); } @Override public AirbyteMessageConsumer getConsumer(final JsonNode config, final ConfiguredAirbyteCatalog catalog, final Consumer<AirbyteMessage> outputRecordCollector) { return new RecordConsumer(outputRecordCollector); } public static class RecordConsumer implements AirbyteMessageConsumer { private final Consumer<AirbyteMessage> outputRecordCollector; public RecordConsumer(Consumer<AirbyteMessage> outputRecordCollector) { this.outputRecordCollector = outputRecordCollector; } @Override public void start() {} @Override public void accept(final AirbyteMessage message) { LOGGER.info("record: {}", message); if (message.getType() == Type.STATE) { LOGGER.info("emitting state: {}", message); outputRecordCollector.accept(message); } } @Override public void close() {} } } ======================= File: airbyte-integrations/connectors/source-relational-db/src/main/java/io/airbyte/integrations/source/relationaldb/CursorInfo.java ======================= <reponame>luizgribeiro/airbyte<gh_stars>1-10 /* * MIT License * * Copyright (c) 2020 Airbyte * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package io.airbyte.integrations.source.relationaldb; import java.util.Objects; public class CursorInfo { private final String originalCursorField; private final String originalCursor; private final String cursorField; private String cursor; public CursorInfo(String originalCursorField, String originalCursor, String cursorField, String cursor) { this.originalCursorField = originalCursorField; this.originalCursor = originalCursor; this.cursorField = cursorField; this.cursor = cursor; } public String getOriginalCursorField() { return originalCursorField; } public String getOriginalCursor() { return originalCursor; } public String getCursorField() { return cursorField; } public String getCursor() { return cursor; } @SuppressWarnings("UnusedReturnValue") public CursorInfo setCursor(String cursor) { this.cursor = cursor; return this; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass()!= o.getClass()) { return false; } CursorInfo that = (CursorInfo) o; return Objects.equals(originalCursorField, that.originalCursorField) && Objects .equals(originalCursor, that.originalCursor) && Objects.equals(cursorField, that.cursorField) && Objects.equals(cursor, that.cursor); } @Override public int hashCode() { return Objects.hash(originalCursorField, originalCursor, cursorField, cursor); } @Override public String toString() { return "CursorInfo{" + "originalCursorField='" + originalCursorField + '\'' + ", originalCursor='" + originalCursor + '\'' + ", cursorField='" + cursorField + '\'' + ", cursor='" + cursor + '\'' + '}'; } } ======================= File: airbyte-migration/src/main/java/io/airbyte/migrate/migrations/MigrationV0_25_0.java ======================= <gh_stars>1-10 /* * MIT License * * Copyright (c) 2020 Airbyte * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package io.airbyte.migrate.migrations; import com.fasterxml.jackson.databind.JsonNode; import io.airbyte.migrate.Migration; import io.airbyte.migrate.MigrationUtils; import io.airbyte.migrate.ResourceId; import io.airbyte.migrate.ResourceType; import java.nio.file.Path; import java.util.HashMap; import java.util.Map; import java.util.function.Consumer; import java.util.stream.Stream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; // This migration does the following: // 1. Add fields to StandardSync. public class MigrationV0_25_0 extends BaseMigration implements Migration { private static final Logger LOGGER = LoggerFactory.getLogger(MigrationV0_25_0.class); protected static final ResourceId STANDARD_SYNC_RESOURCE_ID = ResourceId .fromConstantCase(ResourceType.CONFIG, "STANDARD_SYNC"); private static final String MIGRATION_VERSION = "0.25.0-alpha"; private static final Path CONFIG_PATH = Path.of("migrations/migrationV0_25_0"); private final Migration previousMigration; public MigrationV0_25_0(Migration previousMigration) { super(previousMigration); this.previousMigration = previousMigration; } @Override public String getVersion() { return MIGRATION_VERSION; } @Override public Map<ResourceId, JsonNode> getOutputSchema() { final Map<ResourceId, JsonNode> outputSchema = new HashMap<>(previousMigration.getOutputSchema()); outputSchema.put( STANDARD_SYNC_RESOURCE_ID, MigrationUtils.getSchemaFromResourcePath(CONFIG_PATH, STANDARD_SYNC_RESOURCE_ID)); return outputSchema; } @Override public void migrate(Map<ResourceId, Stream<JsonNode>> inputData, Map<ResourceId, Consumer<JsonNode>> outputData) { for (final Map.Entry<ResourceId, Stream<JsonNode>> entry : inputData.entrySet()) { final Consumer<JsonNode> recordConsumer = outputData.get(entry.getKey()); entry.getValue().forEach(r -> { // empty migration recordConsumer.accept(r); }); } } } ======================= File: airbyte-integrations/connectors/destination-keen/src/test-integration/java/io/airbyte/integrations/destination/keen/KeenDestinationTest.java ======================= /* * MIT License * * Copyright (c) 2020 Airbyte * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package io.airbyte.integrations.destination.keen; import static io.airbyte.integrations.destination.keen.KeenDestination.CONFIG_API_KEY; import static io.airbyte.integrations.destination.keen.KeenDestination.CONFIG_PROJECT_ID; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.api.client.util.Lists; import io.airbyte.commons.io.IOs; import io.airbyte.commons.json.Jsons; import io.airbyte.integrations.standardtest.destination.DestinationAcceptanceTest; import io.airbyte.protocol.models.AirbyteMessage; import io.airbyte.protocol.models.ConfiguredAirbyteCatalog; import java.nio.file.Files; import java.nio.file.Path; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; public class KeenDestinationTest extends DestinationAcceptanceTest { private static final String SECRET_FILE_PATH = "secrets/config.json"; private final KeenHttpClient keenHttpClient = new KeenHttpClient(); private String projectId; private String apiKey; private JsonNode configJson; @Override protected String getImageName() { return "airbyte/destination-keen:dev"; } @Override protected JsonNode getConfig() throws Exception { return configJson; } @Override protected JsonNode getFailCheckConfig() throws Exception { ((ObjectNode) configJson).put(CONFIG_PROJECT_ID, "fake"); ((ObjectNode) configJson).put(CONFIG_API_KEY, "fake"); return configJson; } protected JsonNode getBaseConfigJson() { return Jsons.deserialize(IOs.readFile(Path.of(SECRET_FILE_PATH))); } @Override protected List<JsonNode> retrieveRecords(TestDestinationEnv testEnv, String streamName, String namespace, JsonNode streamSchema) throws Exception { String accentStrippedStreamName = KeenCharactersStripper.stripSpecialCharactersFromStreamName(streamName); ArrayNode array = keenHttpClient.extract(accentStrippedStreamName, projectId, apiKey); return Lists.newArrayList(array.elements()).stream() .sorted(Comparator.comparing(o -> o.get("keen").get("timestamp").textValue())) .map(node -> (JsonNode) ((ObjectNode) node).without("keen")) .collect(Collectors.toList()); } @Override protected void setup(TestDestinationEnv testEnv) throws Exception { if (!Files.exists(Path.of(SECRET_FILE_PATH))) { throw new IllegalStateException( "Must provide path to a file containing Keen account credentials: Project ID and Master API Key. " + "By default {module-root}/" + SECRET_FILE_PATH); } configJson = getBaseConfigJson(); projectId = configJson.get(CONFIG_PROJECT_ID).asText(); apiKey = configJson.get(CONFIG_API_KEY).asText(); } @Override protected void tearDown(TestDestinationEnv testEnv) throws Exception { // Changes for this particular operation - get all collections - can take a couple more time to // propagate // than standard queries for the newly created collection Thread.sleep(5000); List<String> keenCollections = keenHttpClient.getAllCollectionsForProject(projectId, apiKey); for (String keenCollection : keenCollections) { keenHttpClient.eraseStream(keenCollection, projectId, apiKey); } } @Override protected void runSyncAndVerifyStateOutput(JsonNode config, List<AirbyteMessage> messages, ConfiguredAirbyteCatalog catalog, boolean runNormalization) throws Exception { super.runSyncAndVerifyStateOutput(config, messages, catalog, runNormalization); Thread.sleep(10000); } } ======================= File: airbyte-integrations/connectors/destination-azure-blob-storage/src/main/java/io/airbyte/integrations/destination/azure_blob_storage/csv/AzureBlobStorageCsvWriter.java ======================= /* * MIT License * * Copyright (c) 2020 Airbyte * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package io.airbyte.integrations.destination.azure_blob_storage.csv; import com.azure.storage.blob.specialized.AppendBlobClient; import com.azure.storage.blob.specialized.BlobOutputStream; import io.airbyte.integrations.destination.azure_blob_storage.AzureBlobStorageDestinationConfig; import io.airbyte.integrations.destination.azure_blob_storage.writer.AzureBlobStorageWriter; import io.airbyte.integrations.destination.azure_blob_storage.writer.BaseAzureBlobStorageWriter; import io.airbyte.protocol.models.AirbyteRecordMessage; import io.airbyte.protocol.models.ConfiguredAirbyteStream; import java.io.IOException; import java.io.PrintWriter; import java.nio.charset.StandardCharsets; import java.util.UUID; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVPrinter; import org.apache.commons.csv.QuoteMode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class AzureBlobStorageCsvWriter extends BaseAzureBlobStorageWriter implements AzureBlobStorageWriter { private static final Logger LOGGER = LoggerFactory.getLogger(AzureBlobStorageCsvWriter.class); private final CsvSheetGenerator csvSheetGenerator; private final CSVPrinter csvPrinter; private final BlobOutputStream blobOutputStream; public AzureBlobStorageCsvWriter(AzureBlobStorageDestinationConfig config, AppendBlobClient appendBlobClient, ConfiguredAirbyteStream configuredStream, boolean isNewlyCreatedBlob) throws IOException { super(config, appendBlobClient, configuredStream); AzureBlobStorageCsvFormatConfig formatConfig = (AzureBlobStorageCsvFormatConfig) config .getFormatConfig(); this.csvSheetGenerator = CsvSheetGenerator.Factory .create(configuredStream.getStream().getJsonSchema(), formatConfig); this.blobOutputStream = appendBlobClient.getBlobOutputStream(); if (isNewlyCreatedBlob) { this.csvPrinter = new CSVPrinter( new PrintWriter(blobOutputStream, true, StandardCharsets.UTF_8), CSVFormat.DEFAULT.withQuoteMode(QuoteMode.ALL) .withHeader(csvSheetGenerator.getHeaderRow().toArray(new String[0]))); } else { // no header required for append this.csvPrinter = new CSVPrinter( new PrintWriter(blobOutputStream, true, StandardCharsets.UTF_8), CSVFormat.DEFAULT.withQuoteMode(QuoteMode.ALL)); } } @Override public void write(UUID id, AirbyteRecordMessage recordMessage) throws IOException { csvPrinter.printRecord(csvSheetGenerator.getDataRow(id, recordMessage)); } @Override protected void closeWhenSucceed() throws IOException { LOGGER.info("Closing csvPrinter when succeed"); csvPrinter.close(); } @Override protected void closeWhenFail() throws IOException { LOGGER.info("Closing csvPrinter when failed"); csvPrinter.close(); } } ======================= File: airbyte-server/src/main/java/io/airbyte/server/handlers/ArchiveHandler.java ======================= <gh_stars>1-10 /* * MIT License * * Copyright (c) 2020 Airbyte * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package io.airbyte.server.handlers; import io.airbyte.api.model.ImportRead; import io.airbyte.api.model.ImportRead.StatusEnum; import io.airbyte.api.model.ImportRequestBody; import io.airbyte.api.model.UploadRead; import io.airbyte.api.model.WorkspaceIdRequestBody; import io.airbyte.commons.io.FileTtlManager; import io.airbyte.config.persistence.ConfigNotFoundException; import io.airbyte.config.persistence.ConfigRepository; import io.airbyte.config.persistence.YamlSeedConfigPersistence; import io.airbyte.scheduler.persistence.JobPersistence; import io.airbyte.scheduler.persistence.WorkspaceHelper; import io.airbyte.server.ConfigDumpExporter; import io.airbyte.server.ConfigDumpImporter; import io.airbyte.server.errors.InternalServerKnownException; import io.airbyte.validation.json.JsonValidationException; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ArchiveHandler { private static final Logger LOGGER = LoggerFactory.getLogger(ArchiveHandler.class); private final String version; private final ConfigDumpExporter configDumpExporter; private final ConfigDumpImporter configDumpImporter; private final FileTtlManager fileTtlManager; public ArchiveHandler(final String version, final ConfigRepository configRepository, final JobPersistence jobPersistence, final WorkspaceHelper workspaceHelper, final FileTtlManager fileTtlManager) { this( version, fileTtlManager, new ConfigDumpExporter(configRepository, jobPersistence, workspaceHelper), new ConfigDumpImporter(configRepository, jobPersistence, workspaceHelper)); } public ArchiveHandler(final String version, final FileTtlManager fileTtlManager, final ConfigDumpExporter configDumpExporter, final ConfigDumpImporter configDumpImporter) { this.version = version; this.configDumpExporter = configDumpExporter; this.configDumpImporter = configDumpImporter; this.fileTtlManager = fileTtlManager; } /** * Creates an archive tarball file using Gzip compression of internal Airbyte Data * * @return that tarball File. */ public File exportData() { final File archive = configDumpExporter.dump(); fileTtlManager.register(archive.toPath()); return archive; } /** * Creates an archive tarball file using Gzip compression of only configurations tied to * * @param workspaceIdRequestBody which is the target workspace to export * @return that lightweight tarball file */ public File exportWorkspace(WorkspaceIdRequestBody workspaceIdRequestBody) { final File archive; try { archive = configDumpExporter.exportWorkspace(workspaceIdRequestBody.getWorkspaceId()); fileTtlManager.register(archive.toPath()); return archive; } catch (JsonValidationException | IOException | ConfigNotFoundException e) { throw new InternalServerKnownException(String.format("Failed to export Workspace configuration due to: %s", e.getMessage())); } } /** * Extract internal Airbyte data from the @param archive tarball file (using Gzip compression) as * produced by {@link #exportData()}. Note that the provided archived file will be deleted. * * @return a status object describing if import was successful or not. */ public ImportRead importData(File archive) { try { return importInternal(() -> configDumpImporter.importDataWithSeed(version, archive, YamlSeedConfigPersistence.get())); } finally { FileUtils.deleteQuietly(archive); } } public UploadRead uploadArchiveResource(File archive) { return configDumpImporter.uploadArchiveResource(archive); } /** * Extract Airbyte configuration data from the archive tarball file (using Gzip compression) as * produced by {@link #exportWorkspace(WorkspaceIdRequestBody)}. The configurations from the tarball * may get mutated to be safely included into the current workspace. (the exact same tarball could * be imported into 2 different workspaces) Note that the provided archived file will be deleted. * * @return a status object describing if import was successful or not. */ public ImportRead importIntoWorkspace(ImportRequestBody importRequestBody) { final File archive = configDumpImporter.getArchiveResource(importRequestBody.getResourceId()); try { return importInternal( () -> configDumpImporter.importIntoWorkspace(version, importRequestBody.getWorkspaceId(), archive)); } finally { configDumpImporter.deleteArchiveResource(importRequestBody.getResourceId()); } } private ImportRead importInternal(importCall importCall) { ImportRead result; try { importCall.importData(); result = new ImportRead().status(StatusEnum.SUCCEEDED); } catch (Exception e) { LOGGER.error("Import failed", e); result = new ImportRead().status(StatusEnum.FAILED).reason(e.getMessage()); } return result; } public interface importCall { void importData() throws IOException, JsonValidationException, ConfigNotFoundException; } } ======================= File: airbyte-db/lib/src/test/java/io/airbyte/db/instance/configs/ConfigsDatabaseInstanceTest.java ======================= /* * MIT License * * Copyright (c) 2020 Airbyte * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package io.airbyte.db.instance.configs; import static org.jooq.impl.DSL.select; import static org.junit.jupiter.api.Assertions.assertThrows; import java.time.OffsetDateTime; import org.jooq.JSONB; import org.jooq.exception.DataAccessException; import org.junit.jupiter.api.Test; class ConfigsDatabaseInstanceTest extends AbstractConfigsDatabaseTest { @Test public void testGet() throws Exception { // when the database has been initialized and loaded with data (in setup method), the get method // should return the database database = new ConfigsDatabaseInstance(container.getUsername(), container.getPassword(), container.getJdbcUrl()).getInitialized(); // check table database.query(ctx -> ctx.fetchExists(select().from(AIRBYTE_CONFIGS))); } @Test public void testGetAndInitialize() throws Exception { // check table database.query(ctx -> ctx.fetchExists(select().from(AIRBYTE_CONFIGS))); // check columns (if any of the column does not exist, the query will throw exception) database.query(ctx -> ctx.fetchExists(select().from(AIRBYTE_CONFIGS).where(CONFIG_ID.eq("ID")))); database.query(ctx -> ctx.fetchExists(select().from(AIRBYTE_CONFIGS).where(CONFIG_TYPE.eq("TYPE")))); database.query(ctx -> ctx.fetchExists(select().from(AIRBYTE_CONFIGS).where(CONFIG_BLOB.eq(JSONB.valueOf("{}"))))); OffsetDateTime timestamp = OffsetDateTime.now(); database.query(ctx -> ctx.fetchExists(select().from(AIRBYTE_CONFIGS).where(CREATED_AT.eq(timestamp)))); database.query(ctx -> ctx.fetchExists(select().from(AIRBYTE_CONFIGS).where(UPDATED_AT.eq(timestamp)))); // when the configs database has been initialized, calling getAndInitialize again will not change // anything String testSchema = "CREATE TABLE IF NOT EXISTS airbyte_test_configs(id BIGINT PRIMARY KEY);"; database = new ConfigsDatabaseInstance(container.getUsername(), container.getPassword(), container.getJdbcUrl(), testSchema).getAndInitialize(); // the airbyte_test_configs table does not exist assertThrows(DataAccessException.class, () -> database.query(ctx -> ctx.fetchExists(select().from("airbyte_test_configs")))); } } ======================= File: airbyte-integrations/connectors/destination-s3/src/main/java/io/airbyte/integrations/destination/s3/csv/RootLevelFlatteningSheetGenerator.java ======================= /* * MIT License * * Copyright (c) 2020 Airbyte * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package io.airbyte.integrations.destination.s3.csv; import com.fasterxml.jackson.databind.JsonNode; import com.google.common.collect.Lists; import io.airbyte.commons.json.Jsons; import io.airbyte.commons.util.MoreIterators; import io.airbyte.integrations.base.JavaBaseConstants; import java.util.LinkedList; import java.util.List; import java.util.stream.Collectors; public class RootLevelFlatteningSheetGenerator extends BaseSheetGenerator implements CsvSheetGenerator { /** * Keep a header list to iterate the input json object with a defined order. */ private final List<String> recordHeaders; public RootLevelFlatteningSheetGenerator(JsonNode jsonSchema) { this.recordHeaders = MoreIterators.toList(jsonSchema.get("properties").fieldNames()) .stream().sorted().collect(Collectors.toList());; } @Override public List<String> getHeaderRow() { List<String> headers = Lists.newArrayList(JavaBaseConstants.COLUMN_NAME_AB_ID, JavaBaseConstants.COLUMN_NAME_EMITTED_AT); headers.addAll(recordHeaders); return headers; } /** * With root level flattening, the record columns are the first level fields of the json. */ @Override List<String> getRecordColumns(JsonNode json) { List<String> values = new LinkedList<>(); for (String field : recordHeaders) { JsonNode value = json.get(field); if (value == null) { values.add(""); } else if (value.isValueNode()) { // Call asText method on value nodes so that proper string // representation of json values can be returned by Jackson. // Otherwise, CSV printer will just call the toString method, // which can be problematic (e.g. text node will have extra // double quotation marks around its text value). values.add(value.asText()); } else { values.add(Jsons.serialize(value)); } } return values; } } ======================= File: airbyte-integrations/connectors/source-shopify/source_shopify/spec.json ======================= <gh_stars>1-10 { "documentationUrl": "https://docs.airbyte.io/integrations/sources/shopify", "connectionSpecification": { "$schema": "http://json-schema.org/draft-07/schema#", "title": "Shopify Source CDK Specifications", "type": "object", "required": ["shop", "start_date", "api_password"], "additionalProperties": false, "properties": { "shop": { "type": "string", "description": "The name of the shopify store. For https://EXAMPLE.myshopify.com, the shop name is 'EXAMPLE'." }, "start_date": { "type": "string", "description": "The date you would like to replicate data. Format: YYYY-MM-DD.", "examples": ["2021-01-01"], "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$" }, "api_password": { "type": "string", "description": "The API PASSWORD for a private application in Shopify shop.", "airbyte_secret": true } } } } ======================= File: airbyte-integrations/connectors/source-facebook-pages/source_facebook_pages/spec.json ======================= { "documentationUrl": "https://docs.airbyte.io/integrations/sources/facebook-pages", "connectionSpecification": { "$schema": "http://json-schema.org/draft-07/schema#", "title": "Facebook Pages Spec", "type": "object", "required": ["access_token", "page_id"], "additionalProperties": false, "properties": { "access_token": { "type": "string", "description": "Facebook Page Access Token", "airbyte_secret": true }, "page_id": { "type": "string", "description": "Page ID" } } } } ======================= File: airbyte-integrations/connectors/source-github/source_github/spec.json ======================= { "documentationUrl": "https://docs.airbyte.io/integrations/sources/github", "connectionSpecification": { "$schema": "http://json-schema.org/draft-07/schema#", "title": "Github Source Spec", "type": "object", "required": ["access_token", "start_date", "repository"], "additionalProperties": false, "properties": { "access_token": { "type": "string", "title": "Access Tokens", "description": "Log into Github and then generate a <a href=\"https://github.com/settings/tokens\"> personal access token</a>. To load balance your API quota consumption across multiple API tokens, input multiple tokens separated with \",\"", "airbyte_secret": true }, "repository": { "type": "string", "examples": ["airbytehq/airbyte", "airbytehq/*"], "description": "Space-delimited list of GitHub repositories/organizations, e.g. `airbytehq/airbyte` for single repository and `airbytehq/*` for get all repositories from organization" }, "start_date": { "type": "string", "description": "The date from which you'd like to replicate data for GitHub in the format YYYY-MM-DDT00:00:00Z. All data generated after this date will be replicated. Note that it will be used only in the following incremental streams: comments, commits and issues.", "examples": ["2021-03-01T00:00:00Z"], "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z$" } } } } ======================= File: airbyte-config/init/src/main/resources/config/STANDARD_DESTINATION_DEFINITION/81740ce8-d764-4ea7-94df-16bb41de36ae.json ======================= <filename>airbyte-config/init/src/main/resources/config/STANDARD_DESTINATION_DEFINITION/81740ce8-d764-4ea7-94df-16bb41de36ae.json { "destinationDefinitionId": "81740ce8-d764-4ea7-94df-16bb41de36ae", "name": "Chargify (Keen)", "dockerRepository": "airbyte/destination-keen", "dockerImgeTag": "0.1.0", "documentationUrl": "https://docs.airbyte.io/integrations/destinations/keen" } ======================= File: airbyte-config/init/src/main/resources/config/STANDARD_SOURCE_DEFINITION/9e0556f4-69df-4522-a3fb-03264d36b348.json ======================= <reponame>luizgribeiro/airbyte { "sourceDefinitionId": "9e0556f4-69df-4522-a3fb-03264d36b348", "name": "Marketo", "dockerRepository": "airbyte/source-marketo-singer", "dockerImageTag": "0.2.3", "documentationUrl": "https://docs.airbyte.io/integrations/sources/marketo", "icon": "marketo.svg" } ======================= File: airbyte-integrations/connectors/source-looker/source_looker/spec.json ======================= { "documentationUrl": "https://docs.airbyte.io/integrations/sources/looker", "connectionSpecification": { "$schema": "http://json-schema.org/draft-07/schema#", "title": "Looker Spec", "type": "object", "required": ["domain", "client_id", "client_secret"], "additionalProperties": false, "properties": { "domain": { "type": "string", "examples": [ "domainname.looker.com", "looker.clientname.com", "172.16.17.32:8000" ], "description": "Domain for your Looker account, e.g. airbyte.cloud.looker.com,looker.[clientname].com,IP address" }, "client_id": { "title": "Client ID", "type": "string", "description": "The Client ID is first part of an API3 key that is specific to each Looker user. See the <a href=\"https://docs.airbyte.io/integrations/sources/looker\">docs</a> for more information on how to generate this key." }, "client_secret": { "title": "Client Secret", "type": "string", "description": "The Client Secret is second part of an API3 key." }, "run_look_ids": { "title": "Look IDs to Run", "type": "array", "items": { "type": "string", "pattern": ["^[0-9]*$"] }, "description": "The IDs of any Looks to run (optional)" } } } } ======================= File: airbyte-integrations/connectors/source-google-search-console-singer/integration_tests/configured_catalog.json ======================= <gh_stars>1-10 { "streams": [ { "stream": { "name": "sites", "json_schema": {}, "supported_sync_modes": ["full_refresh"], "source_defined_cursor": false }, "sync_mode": "full_refresh", "destination_sync_mode": "overwrite" }, { "stream": { "name": "sitemaps", "json_schema": {}, "supported_sync_modes": ["full_refresh"], "source_defined_cursor": false }, "sync_mode": "full_refresh", "destination_sync_mode": "overwrite" }, { "stream": { "name": "performance_report_custom", "json_schema": {}, "supported_sync_modes": ["incremental"], "source_defined_cursor": true, "default_cursor_field": ["date"] }, "sync_mode": "incremental", "cursor_field": ["date"], "destination_sync_mode": "append" }, { "stream": { "name": "performance_report_country", "json_schema": {}, "supported_sync_modes": ["incremental"], "source_defined_cursor": true, "default_cursor_field": ["date"] }, "sync_mode": "incremental", "cursor_field": ["date"], "destination_sync_mode": "append" }, { "stream": { "name": "performance_report_device", "json_schema": {}, "supported_sync_modes": ["incremental"], "source_defined_cursor": true, "default_cursor_field": ["date"] }, "sync_mode": "incremental", "cursor_field": ["date"], "destination_sync_mode": "append" }, { "stream": { "name": "performance_report_page", "json_schema": {}, "supported_sync_modes": ["incremental"], "source_defined_cursor": true, "default_cursor_field": ["date"] }, "sync_mode": "incremental", "cursor_field": ["date"], "destination_sync_mode": "append" }, { "stream": { "name": "performance_report_query", "json_schema": {}, "supported_sync_modes": ["incremental"], "source_defined_cursor": true, "default_cursor_field": ["date"] }, "sync_mode": "incremental", "cursor_field": ["date"], "destination_sync_mode": "append" } ] } ======================= File: airbyte-integrations/connectors/source-square/integration_tests/invalid_config.json ======================= { "api_key": "API_KEY", "is_sandbox": true, "start_date": "START_DATE", "include_deleted_objects": false } ======================= File: airbyte-server/src/test/resources/migration/dummy_data/config/STANDARD_SOURCE_DEFINITION/4eb22946-2a79-4d20-a3e6-effd234613c3.json ======================= <reponame>luizgribeiro/airbyte { "sourceDefinitionId": "4eb22946-2a79-4d20-a3e6-effd234613c3", "name": "Old connector still being used", "dockerRepository": "airbyte/source-mysql", "dockerImageTag": "0.2.0", "documentationUrl": "https://docs.airbyte.io/integrations/sources/mysql" } ======================= File: airbyte-integrations/connectors/source-jira/integration_tests/invalid_config.json ======================= { "api_token": "<PASSWORD>", "domain": "invaliddomain.atlassian.net", "email": "<EMAIL>" } ======================= File: airbyte-integrations/connectors/source-shortio/source_shortio/spec.json ======================= <filename>airbyte-integrations/connectors/source-shortio/source_shortio/spec.json<gh_stars>1000+ { "documentationUrl": "https://developers.short.io/reference", "connectionSpecification": { "$schema": "http://json-schema.org/draft-07/schema#", "title": "Shortio Spec", "type": "object", "required": ["domain_id", "secret_key", "start_date"], "additionalProperties": false, "properties": { "domain_id": { "type": "string", "description": "Domain ID", "airbyte_secret": false }, "secret_key": { "type": "string", "description": "Short.io Secret key", "airbyte_secret": true }, "start_date": { "type": "string", "description": "Start Date, YYYY-MM-DD", "airbyte_secret": false } } } } ======================= File: airbyte-integrations/connectors/source-typeform/source_typeform/spec.json ======================= { "documentationUrl": "https://docs.airbyte.io/integrations/sources/typeform", "connectionSpecification": { "$schema": "http://json-schema.org/draft-07/schema#", "title": "Typeform Spec", "type": "object", "required": ["token", "start_date"], "additionalProperties": true, "properties": { "start_date": { "type": "string", "description": "The date you would like to replicate data. Format: YYYY-MM-DDTHH:mm:ss[Z].", "examples": ["2020-01-01T00:00:00Z"], "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z$" }, "token": { "type": "string", "description": "The API Token for a Typeform account.", "airbyte_secret": true } } } } ======================= File: airbyte-config/init/src/main/resources/config/STANDARD_DESTINATION_DEFINITION/079d5540-f236-4294-ba7c-ade8fd918496.json ======================= { "destinationDefinitionId": "079d5540-f236-4294-ba7c-ade8fd918496", "name": "BigQuery (denormalized typed struct)", "dockerRepository": "airbyte/destination-bigquery-denormalized", "dockerImageTag": "0.1.2", "documentationUrl": "https://docs.airbyte.io/integrations/destinations/bigquery" } ======================= File: airbyte-integrations/connectors/source-asana/source_asana/spec.json ======================= <reponame>luizgribeiro/airbyte<filename>airbyte-integrations/connectors/source-asana/source_asana/spec.json { "documentationUrl": "https://docsurl.com", "connectionSpecification": { "$schema": "http://json-schema.org/draft-07/schema#", "title": "Asana Spec", "type": "object", "required": ["access_token"], "additionalProperties": false, "properties": { "access_token": { "type": "string", "title": "Personal Access Token", "description": "Asana Personal Access Token (generate yours <a href=\"https://app.asana.com/0/developer-console\">here</a>).", "airbyte_secret": true } } } } ======================= File: airbyte-config/init/src/main/resources/config/STANDARD_SOURCE_DEFINITION/e2b40e36-aa0e-4bed-b41b-bcea6fa348b1.json ======================= { "sourceDefinitionId": "e2b40e36-aa0e-4bed-b41b-bcea6fa348b1", "name": "Exchange Rates Api", "dockerRepository": "airbyte/source-exchange-rates", "dockerImageTag": "0.2.3", "documentationUrl": "https://docs.airbyte.io/integrations/sources/exchangeratesapi", "icon": "exchangeratesapi.svg" } ======================= File: airbyte-config/init/src/main/resources/config/STANDARD_SOURCE_DEFINITION/63cea06f-1c75-458d-88fe-ad48c7cb27fd.json ======================= { "sourceDefinitionId": "63cea06f-1c75-458d-88fe-ad48c7cb27fd", "name": "Braintree", "dockerRepository": "airbyte/source-braintree", "dockerImageTag": "0.1.0", "documentationUrl": "https://docs.airbyte.io/integrations/sources/braintree", "icon": "braintree.svg" } ======================= File: airbyte-config/init/src/main/resources/config/STANDARD_DESTINATION_DEFINITION/4816b78f-1489-44c1-9060-4b19d5fa9362.json ======================= <gh_stars>1-10 { "destinationDefinitionId": "4816b78f-1489-44c1-9060-4b19d5fa9362", "name": "S3", "dockerRepository": "airbyte/destination-s3", "dockerImageTag": "0.1.10", "documentationUrl": "https://docs.airbyte.io/integrations/destinations/s3" } ======================= File: airbyte-integrations/connectors/source-pipedrive/source_pipedrive/spec.json ======================= <gh_stars>1-10 { "documentationUrl": "https://docs.airbyte.io/integrations/sources/pipedrive", "connectionSpecification": { "$schema": "http://json-schema.org/draft-07/schema#", "title": "Pipedrive Spec", "type": "object", "required": ["api_token", "replication_start_date"], "additionalProperties": false, "properties": { "api_token": { "title": "API Token", "description": "Pipedrive API Token", "airbyte_secret": true, "type": "string" }, "replication_start_date": { "title": "Replication Start Date", "description": "UTC date and time in the format 2017-01-25T00:00:00Z. Any data before this date will not be replicated. When specified and not None, then stream will behave as incremental", "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z$", "examples": ["2017-01-25T00:00:00Z"], "type": "string" } } }, "supportsIncremental": true, "supported_destination_sync_modes": ["append"] } ======================= File: airbyte-integrations/connectors/source-github/integration_tests/invalid_config.json ======================= { "access_token": "<PASSWORD> KEY", "repository": "airbytehq/integration-test", "start_date": "2021-06-30T11:30:03Z" } ======================= File: airbyte-integrations/connectors/source-googleanalytics-singer/integration_tests/invalid_config.json ======================= { "credentials_json": "{\n \"type\": \"service_account\",\n \"project_id\": \"dataline-integration-testing\",\n \"private_key_id\": \"8e24553ba1c810d663a74dc5e0b4463911ae3dbb\",\n \"private_key\": \"-----<KEY>\\n\",\n \"client_email\": \"<EMAIL>\",\n \"client_id\": \"103293192021796062643\",\n \"auth_uri\": \"https://accounts.google.com/o/oauth2/auth\",\n \"token_uri\": \"https://oauth2.googleapis.com/token\",\n \"auth_provider_x509_cert_url\": \"https://www.googleapis.com/oauth2/v1/certs\",\n \"client_x509_cert_url\": \"https://www.googleapis.com/robot/v1/metadata/x509/google-analytics-access%40dataline-integration-testing.iam.gserviceaccount.com\"\n}\n", "view_id": "222222222", "start_date": "2020-02-13T00:00:00Z", "custom_reports": "[{\"name\": \"users_per_day\", \"dimensions\": [\"ga:date\"], \"metrics\": [\"ga:users\", \"ga:newUsers\"]}, {\"name\": \"sessions_per_country_day\", \"dimensions\": [\"ga:date\", \"ga:country\"], \"metrics\": [\"ga:sessions\", \"ga:sessionsPerUser\", \"ga:avgSessionDuration\"]}]" } ======================= File: airbyte-integrations/connectors/source-bing-ads/integration_tests/invalid_config.json ======================= <gh_stars>1-10 { "accounts": { "type": "all" }, "user_id": "2222", "customer_id": "1111", "developer_token": "<PASSWORD>", "refresh_token": "<PASSWORD>", "client_secret": "1234", "client_id": "123" } ======================= File: airbyte-integrations/connectors/source-zuora/integration_tests/invalid_config.json ======================= { "start_date": "2020-01-01", "window_in_days": 0, "client_id": "some_client_id", "client_secret": "some_client_secret", "is_sandbox": true } ======================= File: airbyte-integrations/connectors/source-google-search-console-singer/source_google_search_console_singer/spec.json ======================= <filename>airbyte-integrations/connectors/source-google-search-console-singer/source_google_search_console_singer/spec.json { "documentationUrl": "https://docs.airbyte.io/integrations/sources/google-search-console", "connectionSpecification": { "$schema": "http://json-schema.org/draft-07/schema#", "title": "Source Google Search Console Singer Spec", "type": "object", "required": [ "credentials_json", "email", "site_urls", "start_date", "user_agent" ], "additionalProperties": true, "properties": { "credentials_json": { "type": "string", "description": "The contents of the JSON service account key. See the <a href=\"https://developers.google.com/identity/protocols/oauth2/service-account#delegatingauthority\">docs</a> for more information on how to generate this key.", "airbyte_secret": true }, "email": { "type": "string", "description": "The email of the user, which has permissions to access the Google Workspace Admin APIs." }, "site_urls": { "type": "string", "description": "Website URL properties in a comma delimited list; do not include the domain-level property in the list", "examples": "https://example.com, https://www.example.com, http://example.com, http://www.example.com, sc-domain:example.com" }, "start_date": { "type": "string", "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z$", "description": "UTC date and time in the format 2017-01-25T00:00:00Z. Any data before this date will not be replicated.", "examples": ["2021-03-01T00:00:00Z"] }, "user_agent": { "type": "string", "description": "Tap name with the api user email address" } } } } ======================= File: airbyte-config/init/src/main/resources/config/STANDARD_SOURCE_DEFINITION/2470e835-feaf-4db6-96f3-70fd645acc77.json ======================= <reponame>luizgribeiro/airbyte { "sourceDefinitionId": "2470e835-feaf-4db6-96f3-70fd645acc77", "name": "Salesforce", "dockerRepository": "airbyte/source-salesforce-singer", "dockerImageTag": "0.2.5", "documentationUrl": "https://docs.airbyte.io/integrations/sources/salesforce", "icon": "salesforce.svg" } ======================= File: airbyte-config/init/src/main/resources/config/STANDARD_SOURCE_DEFINITION/bfd1ddf8-ae8a-4620-b1d7-55597d2ba08c.json ======================= { "sourceDefinitionId": "bfd1ddf8-ae8a-4620-b1d7-55597d2ba08c", "name": "BigQuery", "dockerRepository": "airbyte/source-bigquery", "dockerImageTag": "0.1.1", "documentationUrl": "https://docs.airbyte.io/integrations/sources/bigquery" } ======================= File: airbyte-integrations/connectors/source-google-analytics-v4/source_google_analytics_v4/spec.json ======================= { "documentationUrl": "https://docs.airbyte.io/integrations/sources/google-analytics-v4", "connectionSpecification": { "$schema": "http://json-schema.org/draft-07/schema#", "title": "Google Analytics V4 Spec", "type": "object", "required": ["credentials_json", "view_id", "start_date"], "additionalProperties": false, "properties": { "credentials_json": { "type": "string", "title": "Credentials JSON", "description": "The contents of the JSON service account key. Check out the <a href=\"https://docs.airbyte.io/integrations/sources/googleanalytics\">docs</a> if you need help generating this key.", "airbyte_secret": true }, "view_id": { "type": "string", "title": "View ID", "description": "The ID for the Google Analytics View you want to fetch data from. This can be found from the <a href=\"https://ga-dev-tools.appspot.com/account-explorer/\">Google Analytics Account Explorer</a>.", "airbyte_secret": true }, "start_date": { "type": "string", "title": "Start Date", "description": "A date in the format YYYY-MM-DD.", "examples": ["2020-06-01"] }, "window_in_days": { "type": "integer", "description": "The amount of days for each data-chunk begining from start_date. Bigger the value - faster the fetch. (Min=1, as for a Day; Max=364, as for a Year).", "examples": [30, 60, 90, 120, 200, 364], "default": 90 }, "custom_reports": { "title": "Custom Reports", "type": "string", "description": "A JSON array describing the custom reports you want to sync from GA. Check out the <a href=\"https://docs.airbyte.io/integrations/sources/google-analytics-v4\">docs</a> to get more information about this field." } } } } ======================= File: airbyte-config/init/src/main/resources/config/STANDARD_SOURCE_DEFINITION/d1aa448b-7c54-498e-ad95-263cbebcd2db.json ======================= <filename>airbyte-config/init/src/main/resources/config/STANDARD_SOURCE_DEFINITION/d1aa448b-7c54-498e-ad95-263cbebcd2db.json { "sourceDefinitionId": "d1aa448b-7c54-498e-ad95-263cbebcd2db", "name": "Tempo", "dockerRepository": "airbyte/source-tempo", "dockerImageTag": "0.2.3", "documentationUrl": "https://docs.airbyte.io/integrations/sources/tempo" } ======================= File: airbyte-config/init/src/main/resources/config/STANDARD_SOURCE_DEFINITION/47f17145-fe20-4ef5-a548-e29b048adf84.json ======================= <reponame>luizgribeiro/airbyte<filename>airbyte-config/init/src/main/resources/config/STANDARD_SOURCE_DEFINITION/47f17145-fe20-4ef5-a548-e29b048adf84.json { "sourceDefinitionId": "47f17145-fe20-4ef5-a548-e29b048adf84", "name": "Apify Dataset", "dockerRepository": "airbyte/source-apify-dataset", "dockerImageTag": "0.1.1", "documentationUrl": "https://docs.airbyte.io/integrations/sources/apify-dataset" } ======================= File: airbyte-integrations/connectors/source-us-census/integration_tests/invalid_config.json ======================= { "query_params": "get=NAME&for=us:*&NAICS2017=72&LFO=001&EMPSZES=001", "api_key": "MY_API_KEY" } ======================= File: airbyte-integrations/connectors/source-slack/integration_tests/invalid_config.json ======================= <filename>airbyte-integrations/connectors/source-slack/integration_tests/invalid_config.json { "api_token": "<PASSWORD>", "start_date": "2022-07-22T20:00:00Z", "lookback_window": 2, "join_channels": true } ======================= File: airbyte-integrations/connectors/source-google-adwords-singer/integration_tests/invalid_config.json ======================= { "developer_token": "<PASSWORD>", "oauth_client_id": "notvalid.apps.googleusercontent.com", "oauth_client_secret": "<PASSWORD>", "refresh_token": "<PASSWORD>", "customer_ids": ["0000000000"], "start_date": "2020-06-01T00:00:00Z", "user_agent": "unknown" } ======================= File: airbyte-integrations/connectors/source-zuora/source_zuora/spec.json ======================= { "documentationUrl": "https://docs.airbyte.io/integrations/sources/zuora", "connectionSpecification": { "$schema": "http://json-schema.org/draft-07/schema#", "title": "Zuora Connector Configuration", "type": "object", "required": ["start_date", "client_id", "client_secret"], "additionalProperties": false, "properties": { "start_date": { "type": "string", "description": "Start Date in format: YYYY-MM-DD", "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$" }, "window_in_days": { "type": "integer", "description": "The amount of days for each data-chunk begining from start_date. Bigger the value - faster the fetch. (Min=1, as for a Day; Max=364, as for a Year).", "examples": [30, 60, 90, 120, 200, 364], "default": 90 }, "client_id": { "type": "string", "description": "Client ID", "airbyte_secret": true }, "client_secret": { "type": "string", "description": "Client Secret", "airbyte_secret": true }, "is_sandbox": { "type": "boolean", "description": "Defines whether use the SANDBOX or PRODUCTION environment.", "default": false } } } } ======================= File: airbyte-config/init/src/main/resources/config/STANDARD_SOURCE_DEFINITION/badc5925-0485-42be-8caa-b34096cb71b5.json ======================= <filename>airbyte-config/init/src/main/resources/config/STANDARD_SOURCE_DEFINITION/badc5925-0485-42be-8caa-b34096cb71b5.json<gh_stars>1000+ { "sourceDefinitionId": "badc5925-0485-42be-8caa-b34096cb71b5", "name": "Survey Monkey", "dockerRepository": "airbyte/source-surveymonkey", "dockerImageTag": "0.1.0", "documentationUrl": "https://docs.airbyte.io/integrations/sources/surveymonkey" } ======================= File: airbyte-integrations/connectors/source-amplitude/source_amplitude/spec.json ======================= { "documentationUrl": "https://docs.airbyte.io/integrations/sources/amplitude", "connectionSpecification": { "$schema": "http://json-schema.org/draft-07/schema#", "title": "Amplitude Spec", "type": "object", "required": ["api_key", "secret_key", "start_date"], "additionalProperties": false, "properties": { "api_key": { "type": "string", "description": "This is the project’s API key, used for calling Amplitude’s APIs", "airbyte_secret": true }, "secret_key": { "type": "string", "description": "This is the project's secret key, which is also used for calling Amplitude’s APIs", "airbyte_secret": true }, "start_date": { "type": "string", "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z$", "description": "UTC date and time in the format 2021-01-25T00:00:00Z. Any data before this date will not be replicated.", "examples": ["2021-01-25T00:00:00Z"] } } } } ======================= File: airbyte-integrations/connectors/source-bigquery/src/main/resources/spec.json ======================= { "documentationUrl": "https://docs.airbyte.io/integrations/source/bigquery", "supportsIncremental": true, "supportsNormalization": true, "supportsDBT": true, "supported_sync_modes": ["overwrite", "append", "append_dedup"], "connectionSpecification": { "$schema": "http://json-schema.org/draft-07/schema#", "title": "BigQuery Source Spec", "type": "object", "required": ["project_id", "credentials_json"], "additionalProperties": false, "properties": { "project_id": { "type": "string", "description": "The GCP project ID for the project containing the target BigQuery dataset.", "title": "Project ID" }, "dataset_id": { "type": "string", "description": "The BigQuery Dataset ID to look for tables to replicate from.", "title": "Default Dataset ID" }, "credentials_json": { "type": "string", "description": "The contents of the JSON service account key. Check out the <a href=\"https://docs.airbyte.io/integrations/source/bigquery\">docs</a> if you need help generating this key.", "title": "Credentials JSON", "airbyte_secret": true } } } } ======================= File: airbyte-config/init/src/main/resources/config/STANDARD_SOURCE_DEFINITION/9fa5862c-da7c-11eb-8d19-0242ac130003.json ======================= <filename>airbyte-config/init/src/main/resources/config/STANDARD_SOURCE_DEFINITION/9fa5862c-da7c-11eb-8d19-0242ac130003.json { "sourceDefinitionId": "9fa5862c-da7c-11eb-8d19-0242ac130003", "name": "Cockroachdb", "dockerRepository": "airbyte/source-cockroachdb", "dockerImageTag": "0.1.2", "documentationUrl": "https://docs.airbyte.io/integrations/sources/cockroachdb" } ======================= File: airbyte-integrations/connectors/source-gitlab/integration_tests/sample_config.json ======================= { "api_url": "gitlab.com", "private_token": "<<PASSWORD>`s_private_token>", "groups": "new-group", "projects": "new-ci-test", "start_date": "2021-01-01T00:00:00Z", "ultimate_license": false, "fetch_merge_request_commits": true, "fetch_pipelines_extended": true } ======================= File: airbyte-config/init/src/main/resources/config/STANDARD_SOURCE_DEFINITION/8da67652-004c-11ec-9a03-0242ac130003.json ======================= <reponame>luizgribeiro/airbyte<gh_stars>1-10 { "sourceDefinitionId": "8da67652-004c-11ec-9a03-0242ac130003", "name": "Trello", "dockerRepository": "airbyte/source-trello", "dockerImageTag": "0.1.0", "documentationUrl": "https://docs.airbyte.io/integrations/sources/trello" } ======================= File: airbyte-integrations/connectors/source-slack/source_slack/spec.json ======================= <filename>airbyte-integrations/connectors/source-slack/source_slack/spec.json { "documentationUrl": "https://docs.airbyte.io/integrations/sources/slack", "connectionSpecification": { "$schema": "http://json-schema.org/draft-07/schema#", "title": "Slack Spec", "type": "object", "required": ["api_token", "start_date", "lookback_window", "join_channels"], "additionalProperties": false, "properties": { "api_token": { "type": "string", "title": "API Token", "description": "A slack bot token. See the <a href=\"https://docs.airbyte.io/integrations/sources/slack\">docs</a> for instructions on how to generate it.", "airbyte_secret": true }, "start_date": { "type": "string", "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z$", "description": "UTC date and time in the format 2017-01-25T00:00:00Z. Any data before this date will not be replicated.", "examples": ["2017-01-25T00:00:00Z"], "title": "Start date" }, "lookback_window": { "type": "integer", "title": "Threads Lookback window (Days)", "description": "How far into the past to look for messages in threads.", "examples": [7, 14] }, "join_channels": { "type": "boolean", "default": true, "title": "Join all channels", "description": "Whether to join all channels or to sync data only from channels the bot is already in. If false, you'll need to manually add the bot to all the channels from which you'd like to sync messages. " } } } } ======================= File: airbyte-integrations/connectors/source-amazon-ads/integration_tests/sample_config.json ======================= { "client_id": "<user's_client_id>", "client_secret": "<user's_client_secret>", "refresh_token": "<user's_ refresh_token>", "scope": "<user's_scopes>" } ======================= File: airbyte-config/init/src/main/resources/config/STANDARD_SOURCE_DEFINITION/d0243522-dccf-4978-8ba0-37ed47a0bdbf.json ======================= <filename>airbyte-config/init/src/main/resources/config/STANDARD_SOURCE_DEFINITION/d0243522-dccf-4978-8ba0-37ed47a0bdbf.json { "sourceDefinitionId": "d0243522-dccf-4978-8ba0-37ed47a0bdbf", "name": "Asana", "dockerRepository": "airbyte/source-asana", "dockerImageTag": "0.1.1", "documentationUrl": "https://docs.airbyte.io/integrations/sources/asana" } ======================= File: airbyte-integrations/connectors/source-braintree/integration_tests/spec.json ======================= <reponame>luizgribeiro/airbyte<gh_stars>1000+ { "documentationUrl": "https://docs.airbyte.io/integrations/sources/braintree", "connectionSpecification": { "title": "Braintree Spec", "type": "object", "properties": { "merchant_id": { "title": "Merchant Id", "description": "<a href=\"https://docs.airbyte.io/integrations/sources/braintree\">Merchant ID</a> is the unique identifier for entire gateway account.", "name": "Merchant ID", "type": "string" }, "public_key": { "title": "Public Key", "description": "This is your user-specific public identifier for Braintree.", "name": "Public key", "type": "string" }, "private_key": { "title": "Private Key", "description": "This is your user-specific private identifier.", "name": "Private Key", "airbyte_secret": true, "type": "string" }, "start_date": { "title": "Start Date", "description": "The date from which you'd like to replicate data for Braintree API for UTC timezone, All data generated after this date will be replicated.", "name": "Start date", "examples": ["2020", "2020-12-30", "2020-11-22 20:20:05"], "type": "string", "format": "date-time" }, "environment": { "description": "Environment specifies where the data will come from.", "name": "Environment", "examples": ["sandbox", "production", "qa", "development"], "allOf": [ { "$ref": "#/definitions/Environment" } ] } }, "required": ["merchant_id", "public_key", "private_key", "environment"], "definitions": { "Environment": { "title": "Environment", "description": "An enumeration.", "enum": ["Development", "Sandbox", "Qa", "Production"], "type": "string" } } } } ======================= File: airbyte-integrations/connectors/source-jira/source_jira/schemas/permissions.json ======================= { "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "properties": { "permissions": { "type": "object", "description": "List of permissions.", "readOnly": true } }, "additionalProperties": false, "description": "Details about permissions." } ======================= File: airbyte-config/init/src/main/resources/config/STANDARD_SOURCE_DEFINITION/253487c0-2246-43ba-a21f-5116b20a2c50.json ======================= { "sourceDefinitionId": "253487c0-2246-43ba-a21f-5116b20a2c50", "name": "Google Ads", "dockerRepository": "airbyte/source-google-ads", "dockerImageTag": "0.1.8", "documentationUrl": "https://docs.airbyte.io/integrations/sources/google-ads" } ======================= File: airbyte-config/init/src/main/resources/config/STANDARD_DESTINATION_DEFINITION/8aaf41d0-f6d2-46de-9e79-c9540f828142.json ======================= <gh_stars>1-10 { "destinationDefinitionId": "8aaf41d0-f6d2-46de-9e79-c9540f828142", "name": "Keen", "dockerRepository": "airbyte/destination-keen", "dockerImgeTag": "0.1.0", "documentationUrl": "https://docs.airbyte.io/integrations/destinations/keen" } ======================= File: airbyte-integrations/connectors/source-google-search-console-singer/integration_tests/invalid_config.json ======================= { "credentials_json": "{\n \"type\": \"service_account\",\n \"project_id\": \"some_id\",\n \"private_key_id\": \"key_id\",\n \"private_key\": \"key\",\n \"client_email\": \"email\",\n \"client_id\": \"id\",\n \"auth_uri\": \"https://accounts.google.com/o/oauth2/auth\",\n \"token_uri\": \"https://oauth2.googleapis.com/token\",\n \"auth_provider_x509_cert_url\": \"https://www.googleapis.com/oauth2/v1/certs\",\n \"client_x509_cert_url\": \"\"\n}", "email": "<EMAIL>", "site_urls": "https://airbyte.io/", "start_date": "2021-04-01T00:00:00Z", "user_agent": "test <EMAIL>>" } ======================= File:.github/pull_request_template.md ======================= ## What *Describe what the change is solving* *It helps to add screenshots if it affects the frontend.* ## How *Describe the solution* ## Recommended reading order 1. `x.java` 2. `y.python` ## Pre-merge Checklist Expand the relevant checklist and delete the others. <details><summary> <strong> New Connector </strong></summary> <p> #### Community member or Airbyter - [ ] **Community member?** Grant edit access to maintainers ([instructions](https://docs.github.com/en/github/collaborating-with-pull-requests/working-with-forks/allowing-changes-to-a-pull-request-branch-created-from-a-fork#enabling-repository-maintainer-permissions-on-existing-pull-requests)) - [ ] Secrets in the connector's spec are annotated with `airbyte_secret` - [ ] Unit & integration tests added and passing. Community members, please provide proof of success locally e.g: screenshot or copy-paste unit, integration, and acceptance test output. To run acceptance tests for a Python connector, follow instructions in the README. For java connectors run `./gradlew :airbyte-integrations:connectors:<name>:integrationTest`. - [ ] Code reviews completed - [ ] Documentation updated - [ ] Connector's `README.md` - [ ] Connector's `bootstrap.md`. See [description and examples](https://docs.google.com/document/d/1ypdgmwmEHWv-TrO4_YOQ7pAJGVrMp5BOkEVh831N260/edit?usp=sharing) - [ ] `docs/SUMMARY.md` - [ ] `docs/integrations/<source or destination>/<name>.md` including changelog. See changelog [example](https://docs.airbyte.io/integrations/sources/stripe#changelog) - [ ] `docs/integrations/README.md` - [ ] `airbyte-integrations/builds.md` - [ ] PR name follows [PR naming conventions](https://docs.airbyte.io/contributing-to-airbyte/updating-documentation#issues-and-pull-requests) - [ ] Connector added to connector index like described [here](https://docs.airbyte.io/connector-development#publishing-a-connector) #### Airbyter If this is a community PR, the Airbyte engineer reviewing this PR is responsible for the below items. - [ ] Create a non-forked branch based on this PR and test the below items on it - [ ] Build is successful - [ ] Credentials added to Github CI. [Instructions](https://docs.airbyte.io/connector-development#using-credentials-in-ci). - [ ] [`/test connector=connectors/<name>` command](https://docs.airbyte.io/connector-development#updating-an-existing-connector) is passing. - [ ] New Connector version released on Dockerhub by running the `/publish` command described [here](https://docs.airbyte.io/connector-development#updating-an-existing-connector) </p> </details> <details><summary> <strong> Updating a connector </strong></summary> <p> #### Community member or Airbyter - [ ] Grant edit access to maintainers ([instructions](https://docs.github.com/en/github/collaborating-with-pull-requests/working-with-forks/allowing-changes-to-a-pull-request-branch-created-from-a-fork#enabling-repository-maintainer-permissions-on-existing-pull-requests)) - [ ] Secrets in the connector's spec are annotated with `airbyte_secret` - [ ] Unit & integration tests added and passing. Community members, please provide proof of success locally e.g: screenshot or copy-paste unit, integration, and acceptance test output. To run acceptance tests for a Python connector, follow instructions in the README. For java connectors run `./gradlew :airbyte-integrations:connectors:<name>:integrationTest`. - [ ] Code reviews completed - [ ] Documentation updated - [ ] Connector's `README.md` - [ ] Connector's `bootstrap.md`. See [description and examples](https://docs.google.com/document/d/1ypdgmwmEHWv-TrO4_YOQ7pAJGVrMp5BOkEVh831N260/edit?usp=sharing) - [ ] Changelog updated in `docs/integrations/<source or destination>/<name>.md` including changelog. See changelog [example](https://docs.airbyte.io/integrations/sources/stripe#changelog) - [ ] PR name follows [PR naming conventions](https://docs.airbyte.io/contributing-to-airbyte/updating-documentation#issues-and-pull-requests) - [ ] Connector version bumped like described [here](https://docs.airbyte.io/connector-development#publishing-a-connector) #### Airbyter If this is a community PR, the Airbyte engineer reviewing this PR is responsible for the below items. - [ ] Create a non-forked branch based on this PR and test the below items on it - [ ] Build is successful - [ ] Credentials added to Github CI. [Instructions](https://docs.airbyte.io/connector-development#using-credentials-in-ci). - [ ] [`/test connector=connectors/<name>` command](https://docs.airbyte.io/connector-development#updating-an-existing-connector) is passing. - [ ] New Connector version released on Dockerhub by running the `/publish` command described [here](https://docs.airbyte.io/connector-development#updating-an-existing-connector) </p> </details> <details><summary> <strong> Connector Generator </strong> </summary> <p> - [ ] Issue acceptance criteria met - [ ] PR name follows [PR naming conventions](https://docs.airbyte.io/contributing-to-airbyte/updating-documentation#issues-and-pull-requests) - [ ] If adding a new generator, add it to the [list of scaffold modules being tested](https://github.com/airbytehq/airbyte/blob/master/airbyte-integrations/connector-templates/generator/build.gradle#L41) - [ ] The generator test modules (all connectors with `-scaffold` in their name) have been updated with the latest scaffold by running `./gradlew :airbyte-integrations:connector-templates:generator:testScaffoldTemplates` then checking in your changes - [ ] Documentation which references the generator is updated as needed. </p> </details> ======================= File: docs/integrations/sources/bamboo-hr.md ======================= <reponame>luizgribeiro/airbyte<filename>docs/integrations/sources/bamboo-hr.md # Bamboo HR ## Overview The BambooHr source supports Full Refresh sync. You can choose if this connector will overwrite the old records or duplicate old ones. ### Output schema This connector outputs the following streams: * [Employees](https://documentation.bamboohr.com/reference#get-employees-directory-1) ### Features | Feature | Supported? | | :--- | :--- | | Full Refresh Sync | Yes | | Incremental - Append Sync | No | | SSL connection | Yes | | Namespaces | No | ### Performance considerations BambooHR has the [rate limits](https://documentation.bamboohr.com/docs/api-details), but the connector should not run into API limitations under normal usage. Please [create an issue](https://github.com/airbytehq/airbyte/issues) if you see any rate limit issues that are not automatically retried successfully. ## Getting started ### Requirements * BambooHr Account * BambooHr [Api key](https://documentation.bamboohr.com/docs) ## Changelog | Version | Date | Pull Request | Subject | | :------ | :-------- | :----- | :------ | | 0.1.0 | 2021-08-27 | [5054](https://github.com/airbytehq/airbyte/pull/5054) | Initial release with Employees API | ======================= File: docs/understanding-airbyte/operations.md ======================= <filename>docs/understanding-airbyte/operations.md<gh_stars>1-10 # Sync Operations Airbyte [connections](connections/README.md) support configuring additional transformations that execute after the sync. Useful applications could be: - Customized normalization to better fit the requirements of your own business context. - Business transformations from a technical data representation into a more logical and business oriented data structure. This can facilitate usage by end-users, non-technical operators, and executives looking to generate Business Intelligence dashboards and reports. - Data Quality, performance optimization, alerting and monitoring, etc. - Integration with other tools from your data stack (orchestration, data visualization, etc.) ## Supported Operations ### dbt transformations #### - git repository url: A url to a git repository to (shallow) clone the latest dbt project code from. The project versioned in the repository is expected to: - be a valid dbt package with a `dbt_project.yml` file at its root. - have a `dbt_project.yml` with a "profile" name declared as described [here](https://docs.getdbt.com/dbt-cli/configure-your-profile). When using the dbt CLI, dbt checks your `profiles.yml` file for a profile with the same name. A profile contains all the details required to connect to your data warehouse. This file generally lives outside of your dbt project to avoid sensitive credentials being checked in to version control. Therefore, a `profiles.yml` will be generated according to the configured destination from the Airbyte UI. Note that if you prefer to use your own `profiles.yml` stored in the git repository or in the Docker image, then you can specify an override with `--profiles-dir=<path-to-my-profiles-yml>` in the dbt CLI arguments. #### - git repository branch (optional): The name of the branch to use when cloning the git repository. If left empty, git will use the default branch of your repository. #### - docker image: A Docker image and tag to run dbt commands from. The Docker image should have `/bin/bash` and `dbt` installed for this operation type to work. A typical value for this field would be for example: `fishtownanalytics/dbt:0.19.1` from [dbt dockerhub](https://hub.docker.com/r/fishtownanalytics/dbt/tags?page=1&ordering=last_updated). This field lets you configure the version of dbt that your custom dbt project requires and the loading of additional software and packages necessary for your transformations (other than your dbt `packages.yml` file). #### - dbt cli arguments This operation type is aimed at running the dbt cli. A typical value for this field would be "run" and the actual command invoked would as a result be: `dbt run` in the docker container. One thing to consider is that dbt allows for vast configuration of the run command, for example, allowing you to select a subset of models. You can find the [dbt reference docs](https://docs.getdbt.com/reference/dbt-commands) which describes this set of available commands and options. ## Future Operations * Docker/Script operations: Execute a generic script in a custom Docker container. * Webhook operations: Trigger API or hooks from other providers. * Airflow operations: To use a specialized orchestration tool that lets you schedule and manage more advanced/complex sequences of operations in your sync workflow. ## Going Further In the meantime, please feel free to react, comment, and share your thoughts/use cases with us. We would be glad to hear your feedback and ideas as they will help shape the next set of features and our roadmap for the future. You can head to our GitHub and participate in the corresponding issue or discussions. Thank you! ======================= File: docs/understanding-airbyte/connections/full-refresh-overwrite.md ======================= # Full Refresh - Overwrite ## Overview The **Full Refresh** modes are the simplest methods that Airbyte uses to sync data, as they always retrieve all available information requested from the source, regardless of whether it has been synced before. This contrasts with [**Incremental sync**](./incremental-append.md), which does not sync data that has already been synced before. In the **Overwrite** variant, new syncs will destroy all data in the existing destination table and then pull the new data in. Therefore, data that has been removed from the source after an old sync will be deleted in the destination table. ## Example Behavior On the nth sync of a full refresh connection: ## _Replace_ existing data with new data. The connection does not create any new tables. data in the destination _before_ the sync: | Languages | | :--- | | Python | | Java | new data: | Languages | | :--- | | Python | | Java | | Ruby | data in the destination _after_ the sync: | Languages | | :--- | | Python | | Java | | Ruby | Note: This is how Singer target-bigquery does it. ## In the future We will consider making other flavors of full refresh configurable as first-class citizens in Airbyte. e.g. On new data, copy old data to a new table with a timestamp, and then replace the original table with the new data. As always, we will focus on adding these options in such a way that the behavior of each connector is both well documented and predictable. ======================= File: docs/integrations/destinations/pubsub.md ======================= --- description: 'Pub/Sub is an asynchronous messaging service provided by Google Cloud Provider.' --- # Google PubSub ## Overview The Airbyte Google PubSub destination allows you to send/stream data into PubSub. Pub/Sub is an asynchronous messaging service provided by Google Cloud Provider. ### Sync overview #### Output schema Each stream will be output a PubSubMessage with attributes. The message attributes will be * `_stream`: the name of stream where the data is coming from * `_namespace`: namespace if available from the stream The data will be a serialized JSON, containing the following fields * `_airbyte_ab_id`: a uuid string assigned by Airbyte to each event that is processed. * `_airbyte_emitted_at`: a long timestamp(ms) representing when the event was pulled from the data source. * `_airbyte_data`: a json string representing source data. #### Features | Feature | Supported?\(Yes/No\) | Notes | | :--- | :--- | :--- | | Full Refresh Sync | Yes | | | Incremental - Append Sync | Yes | | | Namespaces | Yes | | ## Getting started ### Requirements To use the PubSub destination, you'll need: * A Google Cloud Project with PubSub enabled * A PubSub Topic to which Airbyte can stream/sync your data * A Google Cloud Service Account with the `Pub/Sub Editor` role in your GCP project * A Service Account Key to authenticate into your Service Account See the setup guide for more information about how to create the required resources. ### Setup guide #### Google cloud project If you have a Google Cloud Project with PubSub enabled, skip to the "Create a Topic" section. First, follow along the Google Cloud instructions to [Create a Project](https://cloud.google.com/resource-manager/docs/creating-managing-projects#before_you_begin). PubSub is enabled automatically in new projects. If this is not the case for your project, find it in [Marketplace](https://console.cloud.google.com/marketplace/product/google/pubsub.googleapis.com) and enable. #### PubSub topic for Airbyte syncs Airbyte needs a topic in PubSub to write the data being streamed/synced from your data sources. If you already have a Topic into which Airbyte should stream/sync data, skip this section. Otherwise, follow the Google Cloud guide for [Creating a PubSub Topic](https://cloud.google.com/pubsub/docs/admin#creating_a_topic) to achieve this. #### Service account In order for Airbyte to stream/sync data into PubSub, it needs credentials for a [Service Account](https://cloud.google.com/iam/docs/service-accounts) with the `Pub/Sub Editor` role, which grants permissions to publish messages into PubSub topics. We highly recommend that this Service Account is exclusive to Airbyte for ease of permissioning and auditing. However, you can use a pre-existing Service Account if you already have one with the correct permissions. The easiest way to create a Service Account is to follow GCP's guide for [Creating a Service Account](https://cloud.google.com/iam/docs/creating-managing-service-accounts). Once you've created the Service Account, make sure to keep its ID handy as you will need to reference it when granting roles. Service Account IDs typically take the form `<account-name>@<project-name>.iam.gserviceaccount.com` Then, add the service account as a Member in your Google Cloud Project with the `Pub/Sub Editor` role. To do this, follow the instructions for [Granting Access](https://cloud.google.com/iam/docs/granting-changing-revoking-access#granting-console) in the Google documentation. The email address of the member you are adding is the same as the Service Account ID you just created. At this point you should have a service account with the `Pub/Sub Editor` project-level permission. #### Service account key Service Account Keys are used to authenticate as Google Service Accounts. For Airbyte to leverage the permissions you granted to the Service Account in the previous step, you'll need to provide its Service Account Keys. See the [Google documentation](https://cloud.google.com/iam/docs/service-accounts#service_account_keys) for more information about Keys. Follow the [Creating and Managing Service Account Keys](https://cloud.google.com/iam/docs/creating-managing-service-account-keys) guide to create a key. Airbyte currently supports JSON Keys only, so make sure you create your key in that format. As soon as you created the key, make sure to download it, as that is the only time Google will allow you to see its contents. Once you've successfully configured BigQuery as a destination in Airbyte, delete this key from your computer. ### Setup the PubSub destination in Airbyte You should now have all the requirements needed to configure BigQuery as a destination in the UI. You'll need the following information to configure the BigQuery destination: * **Project ID**: GCP project id * **Topic ID**: name of pubsub topic under the project * **Service Account Key**: the contents of your Service Account Key JSON file Once you've configured PubSub as a destination, delete the Service Account Key from your computer. ## CHANGELOG | Version | Date | Pull Request | Subject | | :--- | :--- | :--- | :--- | | 0.1.1 | August 13, 2021 | [#4699](https://github.com/airbytehq/airbyte/pull/4699)| Added json config validator | | 0.1.0 | June 24, 2021 | [#4339](https://github.com/airbytehq/airbyte/pull/4339)| Initial release | ======================= File: airbyte-integrations/connectors/source-jira/CHANGELOG.md ======================= <reponame>luizgribeiro/airbyte # Changelog Moved to the JIRA connector documentation [here](https://docs.airbyte.io/integrations/sources/jira#changelog). ======================= File: docs/understanding-airbyte/cdc.md ======================= # Change Data Capture \(CDC\) ## What is log-based incremental replication? Many common databases support writing all record changes to log files for the purpose of replication. A consumer of these log files \(such as Airbyte\) can read these logs while keeping track of the current position within the logs in order to read all record changes coming from `DELETE`/`INSERT`/`UPDATE` statements. ## Syncing The orchestration for syncing is similar to non-CDC database sources. After selecting a sync interval, syncs are launched regularly. We read data from the log up to the time that the sync was started. We do not treat CDC sources as infinite streaming sources. You should ensure that your schedule for running these syncs is frequent enough to consume the logs that are generated. The first time the sync is run, a snapshot of the current state of the data will be taken. This is done using `SELECT` statements and is effectively a Full Refresh. Subsequent syncs will use the logs to determine which changes took place since the last sync and update those. Airbyte keeps track of the current log position between syncs. A single sync might have some tables configured for Full Refresh replication and others for Incremental. If CDC is configured at the source level, all tables with Incremental selected will use CDC. All Full Refresh tables will replicate using the same process as non-CDC sources. However, these tables will still include CDC metadata columns by default. The Airbyte Protocol outputs records from sources. Records from `UPDATE` statements appear the same way as records from `INSERT` statements. We support different options for how to sync this data into destinations using primary keys, so you can choose to append this data, delete in place, etc. We add some metadata columns for CDC sources: * `ab_cdc_lsn` (postgres and sql server sources) is the point in the log where the record was retrieved * `ab_cdc_log_file` & `ab_cdc_log_pos` (specific to mysql source) is the file name and position in the file where the record was retrieved * `ab_cdc_updated_at` is the timestamp for the database transaction that resulted in this record change and is present for records from `DELETE`/`INSERT`/`UPDATE` statements * `ab_cdc_deleted_at` is the timestamp for the database transaction that resulted in this record change and is only present for records from `DELETE` statements ## Limitations * CDC incremental is only supported for tables with primary keys. A CDC source can still choose to replicate tables without primary keys as Full Refresh or a non-CDC source can be configured for the same database to replicate the tables without primary keys using standard incremental replication. * Data must be in tables, not views. * The modifications you are trying to capture must be made using `DELETE`/`INSERT`/`UPDATE`. For example, changes made from `TRUNCATE`/`ALTER` won't appear in logs and therefore in your destination. * We do not support schema changes automatically for CDC sources. We recommend resetting and resyncing data if you make a schema change. * There are database-specific limitations. See the documentation pages for individual connectors for more information. * The records produced by `DELETE` statements only contain primary keys. All other data fields are unset. ## Current Support * [Postgres](../integrations/sources/postgres.md) (For a quick video overview of CDC on Postgres, click [here](https://www.youtube.com/watch?v=NMODvLgZvuE&ab_channel=Airbyte)) * [MySQL](../integrations/sources/mysql.md) * [Microsoft SQL Server / MSSQL](../integrations/sources/mssql.md) ## Coming Soon * Oracle DB * Please [create a ticket](https://github.com/airbytehq/airbyte/issues/new/choose) if you need CDC support on another database! ======================= File: docs/contributing-to-airbyte/code-style.md ======================= # Code Style ## Configure Java Style for IntelliJ First, download the style configuration. ```text curl https://raw.githubusercontent.com/google/styleguide/gh-pages/intellij-java-google-style.xml -o ~/Downloads/intellij-java-google-style.xml ``` Install it in IntelliJ:‌ 1. Go to `Preferences > Editor > Code Style` 2. Press the little cog: 1. `Import Scheme > IntelliJ IDEA code style XML` 2. Select the file we just downloaded 3. Select `GoogleStyle` in the drop down 4. Change default `Hard wrap at` in `Wrapping and Braces` tab to **150**. 5. We prefer `import foo.bar.ClassName` over `import foo.bar.*`. Even in cases where we import multiple classes from the same package. This can be set by going to `Preferences > Code Style > Java > Imports` and changing `Class count to use import with '*'` to 9999 and `Names count to use static import with '*' to 9999. 6. You're done! ======================= File: docs/integrations/sources/posthog.md ======================= <filename>docs/integrations/sources/posthog.md # PostHog ## Sync overview This source can sync data for the [PostHog API](https://posthog.com/docs/api/overview). It supports both Full Refresh and Incremental syncs. You can choose if this connector will copy only the new or updated data, or all rows in the tables and columns you set up for replication, every time a sync is run. ### Output schema This Source is capable of syncing the following core Streams: * [Annotations](https://posthog.com/docs/api/annotations) (Incremental) * [Cohorts](https://posthog.com/docs/api/cohorts) * [Events](https://posthog.com/docs/api/events) (Incremental) * [FeatureFlags](https://posthog.com/docs/api/feature-flags) * [Insights](https://posthog.com/docs/api/insights) * [InsightsPath](https://posthog.com/docs/api/insights) * [InsightsSessions](https://posthog.com/docs/api/insights) * [Persons](https://posthog.com/docs/api/people) * [Trends](https://posthog.com/docs/api/insights) ### Data type mapping | Integration Type | Airbyte Type | Notes | | :--- | :--- | :--- | | `string` | `string` | | | `number` | `number` | | | `array` | `array` | | | `object` | `object` | | ### Features | Feature | Supported?\(Yes/No\) | Notes | | :--- | :--- | :--- | | Full Refresh Sync | Yes | | | Incremental Sync | Yes | | | Namespaces | No | | ### Performance considerations The PostHog API doesn't have any known request limitation. Please [create an issue](https://github.com/airbytehq/airbyte/issues) if you see any rate limit issues that are not automatically retried successfully. ## Getting started ### Requirements * PostHog Personal API Key ### Setup guide Please follow these [steps](https://posthog.com/docs/api/overview#how-to-obtain-a-personal-api-key) to obtain Private API Key for your account. ## Changelog | Version | Date | Pull Request | Subject | | :------ | :-------- | :----- | :------ | | 0.1.3 | 2021-07-20 | [4001](https://github.com/airbytehq/airbyte/pull/4001) | Incremental streams read only relevant pages| | 0.1.2 | 2021-07-15 | [4692](https://github.com/airbytehq/airbyte/pull/4692) | Use account information for checking the connection| | 0.1.1 | 2021-07-05 | [4539](https://github.com/airbytehq/airbyte/pull/4539) | Add `AIRBYTE_ENTRYPOINT` env variable for kubernetes support| | 0.1.0 | 2021-06-08 | [3768](https://github.com/airbytehq/airbyte/pull/3768) | Initial Release| ======================= File: docs/connector-development/cdk-python/basic-concepts.md ======================= <reponame>luizgribeiro/airbyte<gh_stars>1-10 # Basic Concepts ## The Airbyte Specification As a quick recap, the Airbyte Specification requires an Airbyte Source to support 4 distinct operations: 1. `Spec` - The required configuration in order to interact with the underlying technical system e.g. database information, authentication information etc. 2. `Check` - Validate that the provided configuration is valid with sufficient permissions for one to perform all required operations on the Source. 3. `Discover` - Discover the Source's schema. This let users select what a subset of the data to sync. Useful if users require only a subset of the data. 4. `Read` - Perform the actual syncing process. Data is read from the Source, parsed into `AirbyteRecordMessage`s and sent to the Airbyte Destination. Depending on how the Source is implemented, this sync can be incremental or a full-refresh. A core concept discussed here is the **Source**. The Source contains one or more **Streams** \(or **Airbyte Streams**\). A **Stream** is the other concept key to understanding how Airbyte models the data syncing process. A **Stream** models the logical data groups that make up the larger **Source**. If the **Source** is a RDMS, each **Stream** is a table. In a REST API setting, each **Stream** corresponds to one resource within the API. e.g. a **Stripe Source** would have have one **Stream** for `Transactions`, one for `Charges` and so on. ## The `Source` class Airbyte provides abstract base classes which make it much easier to perform certain categories of tasks e.g: `HttpStream` makes it easy to create HTTP API-based streams. However, if those do not satisfy your use case \(for example, if you're pulling data from a relational database\), you can always directly implement the Airbyte Protocol by subclassing the CDK's `Source` class. Note that while this is the most flexible way to implement a source connector, it is also the most toilsome as you will be required to manually manage state, input validation, correctly conforming to the Airbyte Protocol message formats, and more. We recommend using a subclass of `Source` unless you cannot fulfill your use case otherwise. ## The `AbstractSource` Object `AbstractSource` is a more opinionated implementation of `Source`. It implements `Source`'s 4 methods as follows: `Spec` and `Check` are the `AbstractSource`'s simplest operations. `Spec` returns a checked in json schema file specifying the required configuration. The `AbstractSource` looks for a file named `spec.json` in the module's root by default. Here is an [example](https://github.com/airbytehq/airbyte/blob/master/airbyte-integrations/connectors/source-exchange-rates/source_exchange_rates/spec.json). `Check` delegates to the `AbstractSource`'s `check_connection` function. The function's `config` parameter contains the user-provided configuration, specified in the `spec.json` returned by `Spec`. `check_connection` uses this configuration to validate access and permissioning. Here is an [example](https://github.com/airbytehq/airbyte/blob/master/airbyte-integrations/connectors/source-exchange-rates/source_exchange_rates/source.py#L90) from the same Exchange Rates API. ### The `Stream` Abstract Base Class An `AbstractSource` also owns a set of `Stream`s. This is populated via the `AbstractSource`'s `streams` [function](https://github.com/airbytehq/airbyte/blob/master/airbyte-cdk/python/airbyte_cdk/sources/abstract_source.py#L63). `Discover` and `Read` rely on this populated set. `Discover` returns an `AirbyteCatalog` representing all the distinct resources the underlying API supports. Here is the [entrypoint](https://github.com/airbytehq/airbyte/blob/master/airbyte-cdk/python/airbyte_cdk/sources/abstract_source.py#L74) for those interested in reading the code. See [schemas](schemas.md) for more information on how to declare the schema of a stream. `Read` creates an in-memory stream reading from each of the `AbstractSource`'s streams. Here is the [entrypoint](https://github.com/airbytehq/airbyte/blob/master/airbyte-cdk/python/airbyte_cdk/sources/abstract_source.py#L90) for those interested. As the code examples show, the `AbstractSource` delegates to the set of `Stream`s it owns to fulfill both `Discover` and `Read`. Thus, implementing `AbstractSource`'s `streams` function is required when using the CDK. A summary of what we've covered so far on how to use the Airbyte CDK: * A concrete implementation of the `AbstractSource` object is required. * This involves, 1. implementing the `check_connection`function. 2. Creating the appropriate `Stream` classes and returning them in the `streams` function. 3. placing the above mentioned `spec.json` file in the right place. ## HTTP Streams We've covered how the `AbstractSource` works with the `Stream` interface in order to fulfill the Airbyte Specification. Although developers are welcome to implement their own object, the CDK saves developers the hassle of doing so in the case of HTTP APIs with the [`HTTPStream`](http-streams.md) object. ======================= File: docs/connector-development/tutorials/cdk-tutorial-python-http/1-creating-the-source.md ======================= # Step 1: Creating the Source Airbyte provides a code generator which bootstraps the scaffolding for our connector. ```bash $ cd airbyte-integrations/connector-templates/generator # assumes you are starting from the root of the Airbyte project. # Install NPM from https://www.npmjs.com/get-npm if you don't have it $./generate.sh ``` This will bring up an interactive helper application. Use the arrow keys to pick a template from the list. Select the `Python HTTP API Source` template and then input the name of your connector. The application will create a new directory in airbyte/airbyte-integrations/connectors/ with the name of your new connector. For this walk-through we will refer to our source as `python-http-example`. The finalized source code for this tutorial can be found [here](https://github.com/airbytehq/airbyte/tree/master/airbyte-integrations/connectors/source-python-http-tutorial). The source we will build in this tutorial will pull data from the [Rates API](https://exchangeratesapi.io/), a free and open API which documents historical exchange rates for fiat currencies. ======================= File: docs/examples/build-a-slack-activity-dashboard.md ======================= --- description: Using Airbyte and Apache Superset --- # Build a Slack Activity Dashboard ![](../.gitbook/assets/46.png) This article will show how to use [Airbyte](http://airbyte.io) - an open-source data integration platform - and [Apache Superset](https://superset.apache.org/) - an open-source data exploration platform - in order to build a Slack activity dashboard showing: * Total number of members of a Slack workspace * The evolution of the number of Slack workspace members * Evolution of weekly messages * Evolution of messages per channel * Members per time zone Before we get started, let’s take a high-level look at how we are going to achieve creating a Slack dashboard using Airbyte and Apache Superset. 1. We will use the Airbyte’s Slack connector to get the data off a Slack workspace \(we will be using Airbyte’s own Slack workspace for this tutorial\). 2. We will save the data onto a PostgreSQL database. 3. Finally, using Apache Superset, we will implement the various metrics we care about. Got it? Now let’s get started. ## 1. Replicating Data from Slack to Postgres with Airbyte ### a. Deploying Airbyte There are several easy ways to deploy Airbyte, as listed [here](https://docs.airbyte.io/). For this tutorial, I will just use the [Docker Compose method](https://docs.airbyte.io/deploying-airbyte/local-deployment) from my workstation: ```text # In your workstation terminal git clone https://github.com/airbytehq/airbyte.git cd airbyte docker-compose up ``` The above command will make the Airbyte app available on `localhost:8000`. Visit the URL on your favorite browser, and you should see Airbyte’s dashboard \(if this is your first time, you will be prompted to enter your email to get started\). If you haven’t set Docker up, follow the [instructions here](https://docs.docker.com/desktop/) to set it up on your machine. ### b. Setting Up Airbyte’s Slack Source Connector Airbyte’s Slack connector will give us access to the data. So, we are going to kick things off by setting this connector to be our data source in Airbyte’s web app. I am assuming you already have Airbyte and Docker set up on your local machine. We will be using Docker to create our PostgreSQL database container later on. Now, let’s proceed. If you already went through the onboarding, click on the “new source” button at the top right of the Sources section. If you're going through the onboarding, then follow the instructions. You will be requested to enter a name for the source you are about to create. You can call it “slack-source”. Then, in the Source Type combo box, look for “Slack,” and then select it. Airbyte will then present the configuration fields needed for the Slack connector. So you should be seeing something like this on the Airbyte App: ![](../.gitbook/assets/1.png) The first thing you will notice is that this connector requires a Slack token. So, we have to obtain one. If you are not a workspace admin, you will need to ask for permission. Let’s walk through how we would get the Slack token we need. Assuming you are a workspace admin, open the Slack workspace and navigate to \[Workspace Name\] &gt; Administration &gt; Customize \[Workspace Name\]. In our case, it will be Airbyte &gt; Administration &gt; Customize Airbyte \(as shown below\): ![](../.gitbook/assets/2.png) In the new page that opens up in your browser, you will then need to navigate to **Configure apps**. ![](../.gitbook/assets/3.png) In the new window that opens up, click on **Build** in the top right corner. ![](../.gitbook/assets/4.png) Click on the **Create an App** button. ![](../.gitbook/assets/5.png) In the modal form that follows, give your app a name - you can name it `airbyte_superset`, then select your workspace from the Development Slack Workspace. ![](../.gitbook/assets/6.png) Next, click on the **Create App** button. You will then be presented with a screen where we are going to set permissions for our `airbyte_superset` app, by clicking on the **Permissions** button on this page. ![](../.gitbook/assets/7.png) In the next screen, navigate to the scope section. Then, click on the **Add an OAuth Scope** button. This will allow you to add permission scopes for your app. At a minimum, your app should have the following permission scopes: ![](../.gitbook/assets/8.png) Then, we are going to add our created app to the workspace by clicking the **Install to Workspace** button. ![](../.gitbook/assets/9.png) Slack will prompt you that your app is requesting permission to access your workspace of choice. Click Allow. ![](../.gitbook/assets/10.png) After the app has been successfully installed, you will be navigated to Slack’s dashboard, where you will see the Bot User OAuth Access Token. This is the token you will provide back on the Airbyte page, where we dropped off to obtain this token. So make sure to copy it and keep it in a safe place. Now that we are done with obtaining a Slack token, let’s go back to the Airbyte page we dropped off and add the token in there. We will also need to provide Airbyte with `start_date`. This is the date from which we want Airbyte to start replicating data from the Slack API, and we define that in the format: `YYYY-MM-DDT00:00:00Z`. We will specify ours as `2020-09-01T00:00:00Z`. We will also tell Airbyte to exclude archived channels and not include private channels, and also to join public channels, so the latter part of the form should look like this: ![](../.gitbook/assets/11.png) Finally, click on the **Set up source** button for Airbyte to set the Slack source up. If the source was set up correctly, you will be taken to the destination section of Airbyte’s dashboard, where you will tell Airbyte where to store the replicated data. ### c. Setting Up Airbyte’s Postgres Destination Connector For our use case, we will be using PostgreSQL as the destination. Click the **add destination** button in the top right corner, then click on **add a new destination**. ![](../.gitbook/assets/12.png) In the next screen, Airbyte will validate the source, and then present you with a form to give your destination a name. We’ll call this destination slack-destination. Then, we will select the Postgres destination type. Your screen should look like this now: ![](../.gitbook/assets/13.png) Great! We have a form to enter Postgres connection credentials, but we haven’t set up a Postgres database. Let’s do that! Since we already have Docker installed, we can spin off a Postgres container with the following command in our terminal: ```text docker run --rm --name slack-db -e POSTGRES_PASSWORD=password -p 2000:5432 -d postgres ``` \(Note that the Docker compose file for Superset ships with a Postgres database, as you can see [here](https://github.com/apache/superset/blob/master/docker-compose.yml#L40)\). The above command will do the following: * create a Postgres container with the name slack-db, * set the password to password, * expose the container’s port 5432, as our machine’s port 2000. * create a database and a user, both called postgres. With this, we can go back to the Airbyte screen and supply the information needed. Your form should look like this: ![](../.gitbook/assets/14.png) Then click on the **Set up destination** button. ### d. Setting Up the Replication You should now see the following screen: ![](../.gitbook/assets/15.png) Airbyte will then fetch the schema for the data coming from the Slack API for your workspace. You should leave all boxes checked and then choose the sync frequency - this is the interval in which Airbyte will sync the data coming from your workspace. Let’s set the sync interval to every 24 hours. Then click on the **Set up connection** button. Airbyte will now take you to the destination dashboard, where you will see the destination you just set up. Click on it to see more details about this destination. ![](../.gitbook/assets/16.png) You will see Airbyte running the very first sync. Depending on the size of the data Airbyte is replicating, it might take a while before syncing is complete. ![](../.gitbook/assets/17.png) When it’s done, you will see the **Running status** change to **Succeeded**, and the size of the data Airbyte replicated as well as the number of records being stored on the Postgres database. ![](../.gitbook/assets/18.png) To test if the sync worked, run the following in your terminal: ```text docker exec slack-source psql -U postgres -c "SELECT * FROM public.users;" ``` This should output the rows in the users’ table. To get the count of the users’ table as well, you can also run: ```text docker exec slack-db psql -U postgres -c "SELECT count(*) FROM public.users;" ``` Now that we have the data from the Slack workspace in our Postgres destination, we will head on to creating the Slack dashboard with Apache Superset. ## 2. Setting Up Apache Superset for the Dashboards ### a. Installing Apache Superset Apache Superset, or simply Superset, is a modern data exploration and visualization platform. To get started using it, we will be cloning the Superset repo. Navigate to a destination in your terminal where you want to clone the Superset repo to and run: ```text git clone https://github.com/apache/superset.git ``` It’s recommended to check out the latest branch of Superset, so run: ```text cd superset ``` And then run: ```text git checkout latest ``` Superset needs you to install and build its frontend dependencies and assets. So, we will start by installing the frontend dependencies: ```text npm install ``` Note: The above command assumes you have both Node and NPM installed on your machine. Finally, for the frontend, we will build the assets by running: ```text npm run build ``` After that, go back up one directory into the Superset directory by running: ```text cd.. ``` Then run: ```text docker-compose up ``` This will download the Docker images Superset needs and build containers and start services Superset needs to run locally on your machine. Once that’s done, you should be able to access Superset on your browser by visiting [`http://localhost:8088`](http://localhost:8088), and you should be presented with the Superset login screen. Enter username: **admin** and Password: **<PASSWORD>** to be taken to your Superset dashboard. Great! You’ve got Superset set up. Now let’s tell Superset about our Postgres Database holding the Slack data from Airbyte. ### b. Setting Up a Postgres Database in Superset To do this, on the top menu in your Superset dashboard, hover on the Data dropdown and click on **Databases**. ![](../.gitbook/assets/19.png) In the page that opens up, click on the **+ Database** button in the top right corner. ![](../.gitbook/assets/20.png) Then, you will be presented with a modal to add your Database Name and the connection URI. ![](../.gitbook/assets/21.png) Let’s call our Database `slack_db`, and then add the following URI as the connection URI: ```text postgresql://postgres:[email protected]:2000/postgres ``` If you are on a Windows Machine, yours will be: ```text postgresql://postgres:[email protected]:2000/postgres ``` Note: We are using `docker.for.[mac|win].localhost` in order to access the localhost of your machine, because using just localhost will point to the Docker container network and not your machine’s network. Your Superset UI should look like this: ![](../.gitbook/assets/22.png) We will need to enable some settings on this connection. Click on the **SQL LAB SETTINGS** and check the following boxes: ![](../.gitbook/assets/23.png) Afterwards, click on the **ADD** button, and you will see your database on the data page of Superset. ![](../.gitbook/assets/24.png) ### c. Importing our dataset Now that you’ve added the database, you will need to hover over the data menu again; now click on **Datasets**. ![](../.gitbook/assets/25.png) Then, you will be taken to the datasets page: ![](../.gitbook/assets/26.png) We want to only see the datasets that are in our `slack_db` database, so in the Database that is currently showing All, select `slack_db` and you will see that we don’t have any datasets at the moment. ![](../.gitbook/assets/27.png) ![](../.gitbook/assets/28.png) You can fix this by clicking on the **+ DATASET** button and adding the following datasets. Note: Make sure you select the public schema under the Schema dropdown. ![](../.gitbook/assets/29.png) Now that we have set up Superset and given it our Slack data, let’s proceed to creating the visualizations we need. Still remember them? Here they are again: * Total number of members of a Slack workspace * The evolution of the number of Slack workspace members * Evolution of weekly messages * Evolution of weekly threads created * Evolution of messages per channel * Members per time zone ## 3. Creating Our Dashboards with Superset ### a. Total number of members of a Slack workspace To get this, we will first click on the users’ dataset of our `slack_db` on the Superset dashboard. ![](../.gitbook/assets/30.png) Next, change **untitled** at the top to **Number of Members**. ![](../.gitbook/assets/31.png) Now change the **Visualization Type** to **Big Number,** remove the **Time Range** filter, and add a Subheader named “Slack Members.” So your UI should look like this: ![](../.gitbook/assets/32.png) Then, click on the **RUN QUERY** button, and you should now see the total number of members. Pretty cool, right? Now let’s save this chart by clicking on the **SAVE** button. ![](../.gitbook/assets/33.png) Then, in the **ADD TO DASHBOARD** section, type in “Slack Dashboard”, click on the “Create Slack Dashboard” button, and then click the **Save** button. Great! We have successfully created our first Chart, and we also created the Dashboard. Subsequently, we will be following this flow to add the other charts to the created Slack Dashboard. ### b. Casting the ts column Before we proceed with the rest of the charts for our dashboard, if you inspect the **ts** column on either the **messages** table or the **threads** table, you will see it’s of the type `VARCHAR`. We can’t really use this for our charts, so we have to cast both the **messages** and **threads**’ **ts** column as `TIMESTAMP`. Then, we can create our charts from the results of those queries. Let’s do this. First, navigate to the **Data** menu, and click on the **Datasets** link. In the list of datasets, click the **Edit** button for the **messages** table. ![](../.gitbook/assets/34.png) You’re now in the Edit Dataset view. Click the **Lock** button to enable editing of the dataset. Then, navigate to the **Columns** tab, expand the **ts** dropdown, and then tick the **Is Temporal** box. ![](../.gitbook/assets/35.png) Persist the changes by clicking the Save button. ### c. The evolution of the number of Slack workspace members In the exploration page, let’s first get the chart showing the evolution of the number of Slack members. To do this, make your settings on this page match the screenshot below: ![](../.gitbook/assets/36.png) Save this chart onto the Slack Dashboard. ### d. Evolution of weekly messages posted Now, we will look at the evolution of weekly messages posted. Let’s configure the chart settings on the same page as the previous one. ![](../.gitbook/assets/37.png) Remember, your visualization will differ based on the data you have. ### e. Evolution of weekly threads created Now, we are finished with creating the message chart. Let's go over to the thread chart. You will recall that we will need to cast the **ts** column as stated earlier. So, do that and get to the exploration page, and make it match the screenshot below to achieve the required visualization: ![](../.gitbook/assets/38.png) ### f. Evolution of messages per channel For this visualization, we will need a more complex SQL query. Here’s the query we used \(as you can see in the screenshot below\): ```text SELECT CAST(m.ts as TIMESTAMP), c.name, m.text FROM public.messages m INNER JOIN public.channels c ON m.channel_id = c_id ``` ![](../.gitbook/assets/39.png) Next, click on **EXPLORE** to be taken to the exploration page; make it match the screenshot below: ![](../.gitbook/assets/40.png) Save this chart to the dashboard. ### g. Members per time zone Finally, we will be visualizing members per time zone. To do this, instead of casting in the SQL lab as we’ve previously done, we will explore another method to achieve casting by using Superset’s Virtual calculated column feature. This feature allows us to write SQL queries that customize the appearance and behavior of a specific column. For our use case, we will need the updated column of the users table to be a `TIMESTAMP`, in order to perform the visualization we need for Members per time zone. Let’s start on clicking the edit icon on the users table in Superset. ![](../.gitbook/assets/41.png) You will be presented with a modal like so: ![](../.gitbook/assets/42.png) Click on the **CALCULATED COLUMNS** tab: ![](../.gitbook/assets/43.png) Then, click on the **+ ADD ITEM** button, and make your settings match the screenshot below. ![](../.gitbook/assets/44.png) Then, go to the **exploration** page and make it match the settings below: ![](../.gitbook/assets/45.png) Now save this last chart, and head over to your Slack Dashboard. It should look like this: ![](../.gitbook/assets/46.png) Of course, you can edit how the dashboard looks to fit what you want on it. ## Conclusion In this article, we looked at using Airbyte’s Slack connector to get the data from a Slack workspace into a Postgres database, and then used Apache Superset to craft a dashboard of visualizations.If you have any questions about Airbyte, don’t hesitate to ask questions on our [Slack](https://slack.airbyte.io)! If you have questions about Superset, you can join the [Superset Community Slack](https://superset.apache.org/community/)! ======================= File: docs/integrations/sources/harvest.md ======================= # Harvest ## Overview The Harvest connector can be used to sync your Harvest data. It supports full refresh sync for all streams and incremental sync for all streams except of Expense Reports streams which are: Clients Report, Projects Report, Categories Report, Team Report. Incremental sync is also now available for Company stream, but it always has only one record. ### Output schema Several output streams are available from this source: * [Client Contacts](https://help.getharvest.com/api-v2/clients-api/clients/contacts/) \(Incremental\) * [Clients](https://help.getharvest.com/api-v2/clients-api/clients/clients/) \(Incremental\) * [Company](https://help.getharvest.com/api-v2/company-api/company/company/) * [Invoice Messages](https://help.getharvest.com/api-v2/invoices-api/invoices/invoice-messages/) \(Incremental\) * [Invoice Payments](https://help.getharvest.com/api-v2/invoices-api/invoices/invoice-payments/) \(Incremental\) * [Invoices](https://help.getharvest.com/api-v2/invoices-api/invoices/invoices/) \(Incremental\) * [Invoice Item Categories](https://help.getharvest.com/api-v2/invoices-api/invoices/invoice-item-categories/) \(Incremental\) * [Estimate Messages](https://help.getharvest.com/api-v2/estimates-api/estimates/estimate-messages/) \(Incremental\) * [Estimates](https://help.getharvest.com/api-v2/estimates-api/estimates/estimates/) \(Incremental\) * [Estimate Item Categories](https://help.getharvest.com/api-v2/estimates-api/estimates/estimate-item-categories/) \(Incremental\) * [Expenses](https://help.getharvest.com/api-v2/expenses-api/expenses/expenses/) \(Incremental\) * [Expense Categories](https://help.getharvest.com/api-v2/expenses-api/expenses/expense-categories/) \(Incremental\) * [Tasks](https://help.getharvest.com/api-v2/tasks-api/tasks/tasks/) \(Incremental\) * [Time Entries](https://help.getharvest.com/api-v2/timesheets-api/timesheets/time-entries/) \(Incremental\) * [Project User Assignments](https://help.getharvest.com/api-v2/projects-api/projects/user-assignments/) \(Incremental\) * [Project Task Assignments](https://help.getharvest.com/api-v2/projects-api/projects/task-assignments/) \(Incremental\) * [Projects](https://help.getharvest.com/api-v2/projects-api/projects/projects/) \(Incremental\) * [Roles](https://help.getharvest.com/api-v2/roles-api/roles/roles/) \(Incremental\) * [User Billable Rates](https://help.getharvest.com/api-v2/users-api/users/billable-rates/) * [User Cost Rates](https://help.getharvest.com/api-v2/users-api/users/cost-rates/) * [User Project Assignments](https://help.getharvest.com/api-v2/users-api/users/project-assignments/) \(Incremental\) * [Expense Reports](https://help.getharvest.com/api-v2/reports-api/reports/expense-reports/) * [Uninvoiced Report](https://help.getharvest.com/api-v2/reports-api/reports/uninvoiced-report/) * [Time Reports](https://help.getharvest.com/api-v2/reports-api/reports/time-reports/) * [Project Budget Report](https://help.getharvest.com/api-v2/reports-api/reports/project-budget-report/) ### Features | Feature | Supported? | | :--- | :--- | | Full Refresh Sync | Yes | | Incremental Sync | Yes | | Replicate Incremental Deletes | No | | SSL connection | Yes | | Namespaces | No | ### Performance considerations The Harvest connector will gracefully handle rate limits. For more information, see [the Harvest docs for rate limitations](https://help.getharvest.com/api-v2/introduction/overview/general/#rate-limiting). ## Getting started ### Requirements * Harvest Account * Harvest Authorized OAuth2 API Client to create Access Token and get account ID ### Setup guide This connector supports only authentication with API Key. To obtain API key follow the instructions below: 1. Go to Account Settings page; 1. Under Integrations section press Authorized OAuth2 API Clients button; 1. New page will be opened on which you need to click on Create New Personal Access Token button and follow instructions. See [docs](https://help.getharvest.com/api-v2/authentication-api/authentication/authentication/) for more details. ## Changelog | Version | Date | Pull Request | Subject | | :------ | :-------- | :----- | :------ | | 0.1.4 | 2021-06-22 | [5701](https://github.com/airbytehq/airbyte/pull/5071) | Harvest normalization failure: fixing the schemas | | 0.1.3 | 2021-06-22 | [4274](https://github.com/airbytehq/airbyte/pull/4274) | Fix wrong data type on `statement_key` in `clients` stream | | 0.1.2 | 2021-06-07 | [4222](https://github.com/airbytehq/airbyte/pull/4222) | Correct specification parameter name | | 0.1.1 | 2021-06-09 | [3973](https://github.com/airbytehq/airbyte/pull/3973) | Add `AIRBYTE_ENTRYPOINT` for Kubernetes support | | 0.1.0 | 2021-06-07 | [3709](https://github.com/airbytehq/airbyte/pull/3709) | Release Harvest connector! | ======================= File: airbyte-integrations/connectors/source-amplitude/CHANGELOG.md ======================= # Changelog ## 0.1.0 Source implementation. ======================= File: docs/integrations/sources/facebook-pages.md ======================= <gh_stars>1-10 # Facebook Pages ## Changelog | Version | Date | Pull Request | Subject | | :------ | :-------- | :----- | :------ | | 0.1.0 | 2021-09-01 | [5158](https://github.com/airbytehq/airbyte/pull/5158) | Initial release. | ======================= File: docs/integrations/destinations/kafka.md ======================= <gh_stars>1-10 # Kafka ## Overview The Airbyte Kafka destination allows you to sync data to Kafka. Each stream is written to the corresponding Kafka topic. ### Sync overview #### Output schema Each stream will be output into a Kafka topic. Currently, this connector only writes data with JSON format. More formats (e.g. Apache Avro) will be supported in the future. Each record will contain in its key the uuid assigned by Airbyte, and in the value these 3 fields: * `_airbyte_ab_id`: a uuid assigned by Airbyte to each event that is processed. * `_airbyte_emitted_at`: a timestamp representing when the event was pulled from the data source. * `_airbyte_data`: a json blob representing with the event data. * `_airbyte_stream`: the name of each record's stream. #### Features | Feature | Supported?\(Yes/No\) | Notes | | :--- | :--- | :--- | | Full Refresh Sync | No | | | Incremental - Append Sync | Yes | | | Namespaces | Yes | | ## Getting started ### Requirements To use the Kafka destination, you'll need: * A Kafka cluster 1.0 or above. ### Setup guide #### Network Access Make sure your Kafka brokers can be accessed by Airbyte. #### **Permissions** Airbyte should be allowed to write messages into topics, and these topics should be created before writing into Kafka or, at least, enable the configuration in the brokers `auto.create.topics.enable` (which is not recommended for production environments). Note that if you choose to use dynamic topic names, you will probably need to enable `auto.create.topics.enable` to avoid your connection failing if there was an update to the source connector's schema. Otherwise a hardcoded topic name may be best. #### Target topics You can determine the topics to which messages are written via the `topic_pattern` configuration parameter. Messages can be written to either a hardcoded, pre-defined topic, or dynamically written to different topics based on the [namespace](https://docs.airbyte.io/understanding-airbyte/namespaces) or stream they came from. To write all messages to a single hardcoded topic, enter its name in the `topic_pattern` field e.g: setting `topic_pattern` to `my-topic-name` will write all messages from all streams and namespaces to that topic. To define the output topics dynamically, you can leverage the `{namespace}` and `{stream}` pattern variables, which cause messages to be written to different topics based on the values present when producing the records. For example, setting the `topic_pattern` parameter to `airbyte_syncs/{namespace}/{stream}` means that messages from namespace `n1` and stream `s1` will get written to the topic `airbyte_syncs/n1/s1`, and messages from `s2` to `airbyte_syncs/n1/s2` etc. If you define output topic dynamically, you might want to enable `auto.create.topics.enable` to avoid your connection failing if there was an update to the source connector's schema. Otherwise, you'll need to manually create topics in Kafka as they are added/updated in the source, which is the recommended option for production environments. **NOTICE**: a naming convention transformation will be applied to the target topic name using the `StandardNameTransformer` so that some special characters will be replaced. ### Setup the Kafka destination in Airbyte You should now have all the requirements needed to configure Kafka as a destination in the UI. You can configure the following parameters on the Kafka destination (though many of these are optional or have default values): * **Bootstrap servers** * **Topic pattern** * **Test topic** * **Sync producer** * **Security protocol** * **SASL JAAS config** * **SASL mechanism** * **Client ID** * **ACKs** * **Enable idempotence** * **Compression type** * **Batch size** * **Linger ms** * **Max in flight requests per connection** * **Client DNS lookup** * **Buffer memory** * **Max request size** * **Retries** * **Socket connection setup timeout** * **Socket connection setup max timeout** * **Max block ms** * **Request timeout** * **Delivery timeout** * **Send buffer bytes** * **Receive buffer bytes** More info about this can be found in the [Kafka producer configs documentation site](https://kafka.apache.org/documentation/#producerconfigs). *NOTE*: Some configurations for SSL are not available yet. ## Changelog | Version | Date | Pull Request | Subject | | :------ | :-------- | :----- | :------ | | 0.1.1 | 2021-07-30 | [#5125](https://github.com/airbytehq/airbyte/pull/5125) | Enable `additionalPropertities` in spec.json | | 0.1.0 | 2021-07-21 | [3746](https://github.com/airbytehq/airbyte/pull/3746) | Initial Release | ======================= File: docs/integrations/sources/oracle-siebel-crm.md ======================= # Oracle Siebel CRM [Oracle Siebel CRM](https://www.oracle.com/cx/siebel/) is a Customer Relationship Management platform. ## Sync overview Oracle Siebel CRM can run on the [Oracle, MSSQL, or IBM DB2](https://docs.oracle.com/cd/E88140_01/books/DevDep/installing-and-configuring-siebel-crm.html#PrerequisiteSoftware) databases. You can use Airbyte to sync your Oracle Siebel CRM instance by connecting to the underlying database using the appropriate Airbyte connector: * [DB2](db2.md) * [MSSQL](./mssql.md) * [Oracle](oracle.md) {% hint style="info" %} Reach out to your service representative or system admin to find the parameters required to connect to the underlying database {% endhint %} ### Output schema To understand your Oracle Siebel CRM database schema, see the [Organization Setup Overview docs](https://docs.oracle.com/cd/E88140_01/books/DevDep/basic-organization-setup-overview.html#basic-organization-setup-overview) documentation. Otherwise, the schema will be loaded according to the rules of the underlying database's connector. ======================= File: docs/integrations/sources/wordpress.md ======================= <gh_stars>1-10 # Wordpress [Wordpress](https://wordpress.org/) is the most popular tool for creating websites worldwide. ## Sync overview Wordpress runs on a MySQL database. You can use Airbyte to sync your Wordpress instance by connecting to the underlying MySQL database and leveraging the [MySQL](./mysql.md) connector. {% hint style="info" %} Reach out to your service representative or system admin to find the parameters required to connect to the underlying database {% endhint %} ### Output schema The output schema is the same as that of the [Wordpress Database](https://codex.wordpress.org/Database_Description) described here. ======================= File: docs/integrations/destinations/redshift.md ======================= <reponame>luizgribeiro/airbyte # Redshift ## Overview The Airbyte Redshift destination allows you to sync data to Redshift. This Redshift destination connector has two replication strategies: 1\) INSERT: Replicates data via SQL INSERT queries. This is built on top of the destination-jdbc code base and is configured to rely on JDBC 4.2 standard drivers provided by Amazon via Mulesoft [here](https://mvnrepository.com/artifact/com.amazon.redshift/redshift-jdbc42) as described in Redshift documentation [here](https://docs.aws.amazon.com/redshift/latest/mgmt/jdbc20-install.html). Not recommended for production workloads as this does not scale well. 2\) COPY: Replicates data by first uploading data to an S3 bucket and issuing a COPY command. This is the recommended loading approach described by Redshift [best practices](https://docs.aws.amazon.com/redshift/latest/dg/c_loading-data-best-practices.html). Requires an S3 bucket and credentials. Airbyte automatically picks an approach depending on the given configuration - if S3 configuration is present, Airbyte will use the COPY strategy and vice versa. We recommend users use INSERT for testing, to avoid any additional setup, and switch to COPY for production workloads. ### Sync overview #### Output schema Each stream will be output into its own raw table in Redshift. Each table will contain 3 columns: * `_airbyte_ab_id`: a uuid assigned by Airbyte to each event that is processed. The column type in Redshift is `VARCHAR`. * `_airbyte_emitted_at`: a timestamp representing when the event was pulled from the data source. The column type in Redshift is `TIMESTAMP WITH TIME ZONE`. * `_airbyte_data`: a json blob representing with the event data. The column type in Redshift is `VARCHAR` but can be be parsed with JSON functions. #### Features | Feature | Supported?\(Yes/No\) | Notes | | :--- | :--- | :--- | | Full Refresh Sync | Yes | | | Incremental - Append Sync | Yes | | | Namespaces | Yes | | #### Target Database You will need to choose an existing database or create a new database that will be used to store synced data from Airbyte. ## Getting started ### Requirements 1. Active Redshift cluster 2. Allow connections from Airbyte to your Redshift cluster \(if they exist in separate VPCs\) 3. A staging S3 bucket with credentials \(for the COPY strategy\). {% hint style="info" %} Even if your Airbyte instance is running on a server in the same VPC as your Redshift cluster, you may need to place them in the **same security group** to allow connections between the two. {% endhint %} ### Setup guide #### 1. Make sure your cluster is active and accessible from the machine running Airbyte This is dependent on your networking setup. The easiest way to verify if Airbyte is able to connect to your Redshift cluster is via the check connection tool in the UI. You can check AWS Redshift documentation with a tutorial on how to properly configure your cluster's access [here](https://docs.aws.amazon.com/redshift/latest/gsg/rs-gsg-authorize-cluster-access.html) #### 2. Fill up connection info Next is to provide the necessary information on how to connect to your cluster such as the `host` whcih is part of the connection string or Endpoint accessible [here](https://docs.aws.amazon.com/redshift/latest/gsg/rs-gsg-connect-to-cluster.html#rs-gsg-how-to-get-connection-string) without the `port` and `database` name \(it typically includes the cluster-id, region and end with `.redshift.amazonaws.com`\). You should have all the requirements needed to configure Redshift as a destination in the UI. You'll need the following information to configure the destination: * **Host** * **Port** * **Username** * **Password** * **Schema** * **Database** * This database needs to exist within the cluster provided. #### 2a. Fill up S3 info \(for COPY strategy\) Provide the required S3 info. * **S3 Bucket Name** * See [this](https://docs.aws.amazon.com/AmazonS3/latest/userguide/create-bucket-overview.html) to create an S3 bucket. * **S3 Bucket Region** * Place the S3 bucket and the Redshift cluster in the same region to save on networking costs. * **Access Key Id** * See [this](https://docs.aws.amazon.com/general/latest/gr/aws-sec-cred-types.html#access-keys-and-secret-access-keys) on how to generate an access key. * We recommend creating an Airbyte-specific user. This user will require [read and write permissions](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_examples_s3_rw-bucket.html) to objects in the staging bucket. * **Secret Access Key** * Corresponding key to the above key id. * **Part Size** * Affects the size limit of an individual Redshift table. Optional. Increase this if syncing tables larger than 100GB. Files are streamed to S3 in parts. This determines the size of each part, in MBs. As S3 has a limit of 10,000 parts per file, part size affects the table size. This is 10MB by default, resulting in a default table limit of 100GB. Note, a larger part size will result in larger memory requirements. A rule of thumb is to multiply the part size by 10 to get the memory requirement. Modify this with care. ## Notes about Redshift Naming Conventions From [Redshift Names & Identifiers](https://docs.aws.amazon.com/redshift/latest/dg/r_names.html): ### Standard Identifiers * Begin with an ASCII single-byte alphabetic character or underscore character, or a UTF-8 multibyte character two to four bytes long. * Subsequent characters can be ASCII single-byte alphanumeric characters, underscores, or dollar signs, or UTF-8 multibyte characters two to four bytes long. * Be between 1 and 127 bytes in length, not including quotation marks for delimited identifiers. * Contain no quotation marks and no spaces. ### Delimited Identifiers Delimited identifiers \(also known as quoted identifiers\) begin and end with double quotation marks \("\). If you use a delimited identifier, you must use the double quotation marks for every reference to that object. The identifier can contain any standard UTF-8 printable characters other than the double quotation mark itself. Therefore, you can create column or table names that include otherwise illegal characters, such as spaces or the percent symbol. ASCII letters in delimited identifiers are case-insensitive and are folded to lowercase. To use a double quotation mark in a string, you must precede it with another double quotation mark character. Therefore, Airbyte Redshift destination will create tables and schemas using the Unquoted identifiers when possible or fallback to Quoted Identifiers if the names are containing special characters. ## Data Size Limitations Redshift specifies a maximum limit of 65535 bytes to store the raw JSON record data. Thus, when a row is too big to fit, the Redshift destination fails to load such data and currently ignores that record. See [docs](https://docs.aws.amazon.com/redshift/latest/dg/r_Character_types.html) ## Changelog | Version | Date | Pull Request | Subject | | :------ | :-------- | :----- | :------ | | 0.3.13 | 2021-09-02 | [5745](https://github.com/airbytehq/airbyte/pull/5745) | Disable STATUPDATE flag when using S3 staging to speed up performance | | 0.3.12 | 2021-07-21 | [3555](https://github.com/airbytehq/airbyte/pull/3555) | Enable partial checkpointing for halfway syncs | | 0.3.11 | 2021-07-20 | [4874](https://github.com/airbytehq/airbyte/pull/4874) | allow `additionalProperties` in connector spec | ======================= File: docs/understanding-airbyte/connections/full-refresh-append.md ======================= # Full Refresh - Append ## Overview The **Full Refresh** modes are the simplest methods that Airbyte uses to sync data, as they always retrieve all available data requested from the source, regardless of whether it has been synced before. This contrasts with [**Incremental sync**](./incremental-append.md), which does not sync data that has already been synced before. In the **Append** variant, new syncs will take all data from the sync and append it to the destination table. Therefore, if syncing similar information multiple times, every sync will create duplicates of already existing data. ## Example Behavior On the nth sync of a full refresh connection: ## Add new data to the same table. Do not touch existing data. data in the destination _before_ the nth sync: | Languages | | :--- | | Python | | Java | new data: | Languages | | :--- | | Python | | Java | | Ruby | data in the destination _after_ the nth sync: | Languages | | :--- | | Python | | Java | | Python | | Java | | Ruby | This could be useful when we are interested to know about deletion of data in the source. This is possible if we also consider the date, or the batch id from which the data was written to the destination: new data at the n+1th sync: | Languages | | :--- | | Python | | Ruby | data in the destination _after_ the n+1th sync: | Languages | batch id | | :--- | :--- | | Python | 1 | | Java | 1 | | Python | 2 | | Java | 2 | | Ruby | 2 | | Python | 3 | | Ruby | 3 | ## In the future We will consider making a better detection of deletions in the source, especially with `Incremental`, and `Change Data Capture` based sync modes for example. ======================= File: docs/connector-development/airbyte101.md ======================= # Airbyte 101 for Connector Development ## The Airbyte Catalog The Airbyte catalog defines the relationship between your incoming data's schema and the schema of your output stream. This is an incredibly important concept to understand as a connector dev, so check out the AirbyteCatalog [here](../understanding-airbyte/beginners-guide-to-catalog.md). ======================= File: airbyte-integrations/connectors/source-aws-cloudtrail/CHANGELOG.md ======================= <reponame>luizgribeiro/airbyte # Changelog ## 0.1.0 Initial Release. Added Management Events incremental stream: https://docs.aws.amazon.com/awscloudtrail/latest/APIReference/API_LookupEvents.html ======================= File: docs/contributing-to-airbyte/updating-documentation.md ======================= <filename>docs/contributing-to-airbyte/updating-documentation.md # Updating Documentation Our documentation uses [GitBook](https://gitbook.com), and all the [Markdown](https://guides.github.com/features/mastering-markdown/) files are stored in our Github repository. ## Workflow for updating docs 1. Modify docs using Git or the Github UI (All docs live in the `docs/` folder in the [Airbyte repository](https://github.com/airbytehq/airbyte)) 2. If you're adding new files, update `docs/SUMMARY.md`. 3. If you're moving existing pages, add redirects in the [`.gitbook.yaml` file](https://github.com/airbytehq/airbyte/blob/master/.gitbook.yaml) in the Airbyte repository root directory 4. Create a Pull Request ### Modify in the Github UI 1. Directly edit the docs you want to edit [in the Github UI](https://docs.github.com/en/github/managing-files-in-a-repository/managing-files-on-github/editing-files-in-your-repository) 2. Create a Pull Request ### Modify using Git 1. [Fork](https://docs.github.com/en/github/getting-started-with-github/fork-a-repo) the repository. 2. Clone the fork on your workstation: ```bash git clone [email protected]:{YOUR_USERNAME}/airbyte.git cd airbyte ``` Or ```bash git clone https://github.com/{YOUR_USERNAME}/airbyte.git cd airbyte ``` {% hint style="info" %} While cloning on Windows, you might encounter errors about long filenames. Refer to the instructions [here](../deploying-airbyte/local-deployment.md#handling-long-filename-error) to correct it. {% endhint %} 3. Modify the documentation. 4. Create a pull request ## Documentation Best Practices Connectors typically have the following documentation elements: * READMEs * Changelogs * Github Issues & Pull Requests * Source code comments * How-to guides Below are some best practices related to each of these. ### READMEs Every module should have a README containing: * A brief description of the module * development pre-requisites (like which language or binaries are required for development) * how to install dependencies * how to build and run the code locally & via Docker * any other information needed for local iteration ### Changelogs ##### Core Core changelogs should be updated in the `docs/project-overview/platform.md` file. #### Connectors Each connector should have a CHANGELOG.md section in its public facing docs in the `docs/integrations/<sources OR destinations>/<name>` at the bottom of the page. Inside, each new connector version should have a section whose title is the connector's version number. The body of this section should describe the changes added in the new version. For example: ``` | Version | Date | Pull Request | Subject | | :------ | :-------- | :----- | :------ | | 0.2.0 | 20XX-05-XX | [PR2#](https://github.com/airbytehq/airbyte/pull/PR2#) | Fixed bug with schema generation <br><br> Added a better description for the `password` input parameter | | 0.1.0 | 20XX-04-XX | [PR#](https://github.com/airbytehq/airbyte/pull/PR#) | Added incremental sync | ``` ### Source code comments It's hard to pin down exactly what to do around source code comments, but there are two (very subjective) and rough guidelines: **If something is not obvious, write it down**. Examples include: * non-trivial class definitions should have docstrings * magic variables should have comments explaining why those values are used (e.g: if using a page size of 10 in a connector, describe why if possible. If there is no reason, that's also fine, just mention in a comment). * Complicated subroutines/logic which cannot be refactored should have comments explaining what they are doing and why **If something is obvious, don't write it down** since it's probably more likely to go out of date. For example, a comment like `x = 42; // sets x to 42` is not adding any new information and is therefore better omitted. ### Issues & Pull Requests #### Titles **Describe outputs, not implementation**: An issue or PR title should describe the desired end result, not the implementation. The exception is child issues/subissues of an epic. **Be specific about the domain**. Airbyte operates a monorepo, so being specific about what is being changed in the PR or issue title is important. Some examples: _subpar issue title_: `Remove airbyteCdk.dependsOn("unrelatedPackage")`. This describes a solution not a problem. _good issue title_: `Building the Airbyte Python CDK should not build unrelated packages`. Describes desired end state and the intent is understandable without reading the full issue. _subpar PR title_: `Update tests`. Which tests? What was the update? _good PR title_: `Source MySQL: update acceptance tests to connect to SSL-enabled database`. Specific about the domain and change that was made. **PR title conventions** When creating a PR, follow the naming conventions depending on the change being made: * Notable updates to Airbyte Core: "🎉<description of feature>" * e.g: `🎉 enable configuring un-nesting in normalization` * New connectors: “🎉 New source or destination: <name>” e.g: `🎉 New Source: Okta` * New connector features: “🎉<Source or Destination> <name>: <feature description> E.g: * `🎉 Destination Redshift: write JSONs as SUPER type instead of VARCHAR` * `🎉 Source MySQL: enable logical replication` * Bugfixes should start with the 🐛 emoji * `🐛 Source Facebook Marketing: fix incorrect parsing of lookback window` * Documentation improvements should start with any of the book/paper emojis: 📚 📝 etc… * Any refactors, cleanups, etc.. that are not visible improvements to the user should not have emojis The emojis help us identify which commits should be included in the product release notes. #### Descriptions **Context**: Provide enough information (or a link to enough information) in the description so team members with no context can understand what the issue or PR is trying to accomplish. This usually means you should include two things: 1. Some background information motivating the problem 2. A description of the problem itself 3. Good places to start reading and file changes that can be skipped Some examples: _insufficient context_: `Create an OpenAPI to JSON schema generator`. Unclear what the value or problem being solved here is. _good context_: ``` When creating or updating connectors, we spend a lot of time manually transcribing JSON Schema files based on OpenAPI docs. This is ncessary because OpenAPI and JSON schema are very similar but not perfectly compatible. This process is automatable. Therefore we should create a program which converts from OpenAPI to JSONSchema format. ``` ======================= File: docs/integrations/sources/microsoft-dynamics-ax.md ======================= <reponame>luizgribeiro/airbyte # MS Dynamics AX [MS Dynamics AX](https://dynamics.microsoft.com/en-us/ax) is a powerful enterprise resource planning (ERP) software package for finance and operations. ## Sync overview MS Dynamics AX runs on the MSSQL database. You can use the [MSSQL connector](mssql.md) to sync your MS Dynamics AX instance by connecting to the underlying database. ### Output schema To understand your MS Dynamics AX database schema, see the [Microsoft docs](https://docs.microsoft.com/en-us/dynamicsax-2012/developer/database-erds-on-the-axerd-website). Otherwise, the schema will be loaded according to the rules of MSSQL connector. ======================= File: docs/deploying-airbyte/local-deployment.md ======================= <filename>docs/deploying-airbyte/local-deployment.md # Local Deployment {% hint style="info" %} These instructions have been tested on MacOS, Windows 10 and Ubuntu 20.04. {% endhint %} ## Setup & launch Airbyte * Install Docker on your workstation \(see [instructions](https://www.docker.com/products/docker-desktop)\). Note: There is a known issue with docker-compose 1.27.3. If you are using that version, please upgrade to 1.27.4. * After Docker is installed, you can immediately get started locally by running: ```bash git clone https://github.com/airbytehq/airbyte.git cd airbyte docker-compose up ``` * In your browser, just visit [http://localhost:8000](http://localhost:8000) * Start moving some data! ## Deploy on Windows We recommend following [this guide](https://docs.docker.com/docker-for-windows/install/) to install Docker on Windows. After installing the WSL 2 backend and Docker you should be able to run containers using Windows PowerShell. Additionally, as we note frequently, you will need `docker-compose` to build Airbyte from source. The suggested guide already installs `docker-compose` on Windows. ### Handling long filename error If you are cloning the repo, you might run into a problem where git indicates that certain filenames are too long and it therefore can't create the local file. So if you received this error after cloning the repo, run the following commands in *git bash*: ```bash cd airbyte git config core.longpaths true git reset --hard HEAD ``` However it's worth pointing out that the `core.longpaths` option is defaulted to false for a reason, so use with caution. This git configuration is only changed within the cloned Airbyte repo, so you won't need to worry about changing this setting for other repositories. Find more details about this issue in [this stack overflow question](https://stackoverflow.com/questions/22575662/filename-too-long-in-git-for-windows). Instead of cloning the repo, you can alternatively download the latest Airbyte release [here](https://github.com/airbytehq/airbyte/releases). Unzip the downloaded file, access the unzipped file using PowerShell terminal, and run `docker-compose up`. After this, you should see the Airbyte containers in the Docker application as in the image below. ![](../.gitbook/assets/airbyte_deploy_windows_docker.png) ## Troubleshooting **I have a Mac with the M1 chip. Is it possible to run Airbyte?** Some users using Macs with an M1 chip are facing some problems running Airbyte. The problem is related with the chip and Docker. [Issue #2017](https://github.com/airbytehq/airbyte/issues/2017) was created to follow up the problem, you can subscribe to it and get updates about the resolution. If you can successfully run Airbyte using a MacBook with the M1 chip, let us know so that we can share the process with the community! **Other issues** If you encounter any issues, just connect to our [Slack](https://slack.airbyte.io). Our community will help! We also have a [troubleshooting](../troubleshooting/on-deploying.md) section in our docs for common problems. ======================= File: docs/troubleshooting/README.md ======================= <reponame>luizgribeiro/airbyte # Troubleshooting This section is aimed at collecting common issues users have to provide quick solutions. There are some sections you can find: - [On Deploying](on-deploying.md): - [On Setting up a New Connection](new-connection.md) - [On Running a Sync](running-sync.md) - [On Upgrading](on-upgrading.md) If you don't see your issue listed in those sections, you can send a message in our #issues Slack channel. Using the template bellow will allow us to address your issue quickly and will give us full understanding of your situation. ## Slack Issue Template **Is this your first time deploying Airbyte**: No / Yes <br> **OS Version / Instance**: Ubuntu 18.04, Mac OS, Windows, GCP, EC2 micro.a4 <br> **Memory / Disk**: 16Gb / 1Tb SSD <br> **Deployment**: Docker / Kubernetes <br> **Airbyte Version**: 0.26.2-alpha <br> **Source name/version**: File 0.24 <br> **Destination name/version**: Postgres 0.3.0 <br> **Step**: Setting new connection, source / On sync <br> **Description**: I'm trying to sync for the first time and the process doesn't finish. I had enabled CDC and other cool features. <br> Add the logs and other relevant information in the message thread. Below is an example: ![](../.gitbook/assets/issue-example.png) ======================= File: airbyte-integrations/connectors/source-exchange-rates/CHANGELOG.md ======================= # Changelog ## 0.2.2 Adding clearer error message when a currency isn't supported. access_key field in spec.json was marked as sensitive ======================= File: docs/integrations/sources/presta-shop.md ======================= <reponame>luizgribeiro/airbyte # PrestaShop ## Overview The PrestaShop source supports both Full Refresh and Incremental syncs. You can choose if this connector will copy only the new or updated data, or all rows in the tables and columns you set up for replication, every time a sync is run. ### Output schema This Source is capable of syncing the following core Streams: * [Addresses](https://devdocs.prestashop.com/1.7/webservice/resources/addresses/) * [Carriers](https://devdocs.prestashop.com/1.7/webservice/resources/carriers/) * [Cart Rules](https://devdocs.prestashop.com/1.7/webservice/resources/cart_rules/) * [Carts](https://devdocs.prestashop.com/1.7/webservice/resources/carts/) * [Categories](https://devdocs.prestashop.com/1.7/webservice/resources/categories/) * [Combinations](https://devdocs.prestashop.com/1.7/webservice/resources/combinations/) * [Configurations](https://devdocs.prestashop.com/1.7/webservice/resources/configurations/) * [Contacts](https://devdocs.prestashop.com/1.7/webservice/resources/contacts/) * [Content Management System](https://devdocs.prestashop.com/1.7/webservice/resources/content_management_system/) * [Countries](https://devdocs.prestashop.com/1.7/webservice/resources/countries/) * [Currencies](https://devdocs.prestashop.com/1.7/webservice/resources/currencies/) * [Customer Messages](https://devdocs.prestashop.com/1.7/webservice/resources/customer_messages/) * [Customer Threads](https://devdocs.prestashop.com/1.7/webservice/resources/customer_threads/) * [Customers](https://devdocs.prestashop.com/1.7/webservice/resources/customers/) * [Deliveries](https://devdocs.prestashop.com/1.7/webservice/resources/deliveries/) * [Employees](https://devdocs.prestashop.com/1.7/webservice/resources/employees/) * [Groups](https://devdocs.prestashop.com/1.7/webservice/resources/groups/) * [Guests](https://devdocs.prestashop.com/1.7/webservice/resources/guests/) * [Image Types](https://devdocs.prestashop.com/1.7/webservice/resources/image_types/) * [Languages](https://devdocs.prestashop.com/1.7/webservice/resources/languages/) * [Manufacturers](https://devdocs.prestashop.com/1.7/webservice/resources/manufacturers/) * [Messages](https://devdocs.prestashop.com/1.7/webservice/resources/messages/) * [Order Carriers](https://devdocs.prestashop.com/1.7/webservice/resources/order_carriers/) * [Order Details](https://devdocs.prestashop.com/1.7/webservice/resources/order_details/) * [Order Histories](https://devdocs.prestashop.com/1.7/webservice/resources/order_histories/) * [Order Invoices](https://devdocs.prestashop.com/1.7/webservice/resources/order_invoices/) * [Order Payments](https://devdocs.prestashop.com/1.7/webservice/resources/order_payments/) * [Order Slip](https://devdocs.prestashop.com/1.7/webservice/resources/order_slip/) * [Order States](https://devdocs.prestashop.com/1.7/webservice/resources/order_states/) * [Orders](https://devdocs.prestashop.com/1.7/webservice/resources/orders/) * [Price Ranges](https://devdocs.prestashop.com/1.7/webservice/resources/price_ranges/) * [Product Customization Fields](https://devdocs.prestashop.com/1.7/webservice/resources/product_customization_fields/) * [Product Feature Values](https://devdocs.prestashop.com/1.7/webservice/resources/product_feature_values/) * [Product Features](https://devdocs.prestashop.com/1.7/webservice/resources/product_features/) * [Product Option Values](https://devdocs.prestashop.com/1.7/webservice/resources/product_option_values/) * [Product Suppliers](https://devdocs.prestashop.com/1.7/webservice/resources/product_suppliers/) * [Products](https://devdocs.prestashop.com/1.7/webservice/resources/products/) * [ShopGroups](https://devdocs.prestashop.com/1.7/webservice/resources/shop_groups/) * [ShopUrls](https://devdocs.prestashop.com/1.7/webservice/resources/shop_urls/) * [Shops](https://devdocs.prestashop.com/1.7/webservice/resources/shops/) * [Specific Price Rules](https://devdocs.prestashop.com/1.7/webservice/resources/specific_price_rules/) * [Specific Prices](https://devdocs.prestashop.com/1.7/webservice/resources/specific_prices/) * [States](https://devdocs.prestashop.com/1.7/webservice/resources/states/) * [Stock Availables](https://devdocs.prestashop.com/1.7/webservice/resources/stock_availables/) * [Stock Movement Reasons](https://devdocs.prestashop.com/1.7/webservice/resources/stock_movement_reasons/) * [Stock Movements](https://devdocs.prestashop.com/1.7/webservice/resources/stock_movements/) * [Stores](https://devdocs.prestashop.com/1.7/webservice/resources/stores/) * [Suppliers](https://devdocs.prestashop.com/1.7/webservice/resources/suppliers/) * [Tags](https://devdocs.prestashop.com/1.7/webservice/resources/tags/) * [Tax Rule Groups](https://devdocs.prestashop.com/1.7/webservice/resources/tax_rule_groups/) * [Tax Rules](https://devdocs.prestashop.com/1.7/webservice/resources/tax_rules/) * [Taxes](https://devdocs.prestashop.com/1.7/webservice/resources/taxes/) * [Translated Configurations](https://devdocs.prestashop.com/1.7/webservice/resources/translated_configurations/) * [Weight Ranges](https://devdocs.prestashop.com/1.7/webservice/resources/weight_ranges/) * [Zones](https://devdocs.prestashop.com/1.7/webservice/resources/zones/) If there are more endpoints you'd like Airbyte to support, please [create an issue.](https://github.com/airbytehq/airbyte/issues/new/choose) ### Features | Feature | Supported? | | | :--- | :--- | :--- | Full Refresh Sync | Yes | | | Incremental Sync | Yes | Addresses, Cart Rules, Carts, Categories, Customer Messages, Customer Threads, Customers, Manufacturers, Messages, Order Carriers, Order Histories, Order Invoices, Order Payments, Order Slip, Orders, Products, Stock Movement Reasons, Stock Movements, Stores, Suppliers, Tax Rule Groups | | Replicate Incremental Deletes | Coming soon | | | SSL connection | Yes | | | Namespaces | No | | ## Getting started PrestaShop enables merchants to give third-party tools access to their shop’s database through a CRUD API, otherwise called a [web service](https://devdocs.prestashop.com/1.7/webservice/). By default, the webservice feature is disabled on PrestaShop and needs to be [switched on](https://devdocs.prestashop.com/1.7/webservice/tutorials/creating-access/#enable-the-webservice) before the first use. ### Requirements * PrestaShop [access key](https://devdocs.prestashop.com/1.7/webservice/tutorials/creating-access/#create-an-access-key) * PrestaShop url ## CHANGELOG | Version | Date | Pull Request | Subject | | :--- | :--- | :--- | :--- | | 0.1.0 | 2021-07-02 | [#4465](https://github.com/airbytehq/airbyte/pull/4465) | Initial implementation | ======================= File: docs/integrations/sources/quickbooks.md ======================= # Quickbooks ## Overview The Quickbooks source supports both Full Refresh and Incremental syncs. You can choose if this connector will copy only the new or updated data, or all rows in the tables and columns you set up for replication, every time a sync is run. This source wraps the [Singer Quickbooks Tap](https://github.com/singer-io/tap-quickbooks). ### Output schema This Source is capable of syncing the following [Streams](https://developer.intuit.com/app/developer/qbo/docs/api/accounting/most-commonly-used/account): * [Accounts](https://developer.intuit.com/app/developer/qbo/docs/api/accounting/all-entities/account) * [BillPayments](https://developer.intuit.com/app/developer/qbo/docs/api/accounting/all-entities/billpayment) * [Budgets](https://developer.intuit.com/app/developer/qbo/docs/api/accounting/all-entities/budget) * [Bills](https://developer.intuit.com/app/developer/qbo/docs/api/accounting/all-entities/bill) * [Classes](https://developer.intuit.com/app/developer/qbo/docs/api/accounting/all-entities/class) * [CreditMemos](https://developer.intuit.com/app/developer/qbo/docs/api/accounting/all-entities/creditmemo) * [Customers](https://developer.intuit.com/app/developer/qbo/docs/api/accounting/all-entities/customer) * [Departments](https://developer.intuit.com/app/developer/qbo/docs/api/accounting/all-entities/department) * [Deposits](https://developer.intuit.com/app/developer/qbo/docs/api/accounting/all-entities/deposit) * [Employees](https://developer.intuit.com/app/developer/qbo/docs/api/accounting/all-entities/employee) * [Estimates](https://developer.intuit.com/app/developer/qbo/docs/api/accounting/all-entities/estimate) * [Invoices](https://developer.intuit.com/app/developer/qbo/docs/api/accounting/all-entities/invoice) * [Items](https://developer.intuit.com/app/developer/qbo/docs/api/accounting/all-entities/item) * [JournalEntries](https://developer.intuit.com/app/developer/qbo/docs/api/accounting/all-entities/journalentry) * [Payments](https://developer.intuit.com/app/developer/qbo/docs/api/accounting/all-entities/payment) * [PaymentMethods](https://developer.intuit.com/app/developer/qbo/docs/api/accounting/all-entities/paymentmethod) * [Purchases](https://developer.intuit.com/app/developer/qbo/docs/api/accounting/all-entities/purchase) * [PurchaseOrders](https://developer.intuit.com/app/developer/qbo/docs/api/accounting/all-entities/purchaseorder) * [RefundReceipts](https://developer.intuit.com/app/developer/qbo/docs/api/accounting/all-entities/refundreceipt) * [SalesReceipts](https://developer.intuit.com/app/developer/qbo/docs/api/accounting/all-entities/salesreceipt) * [TaxAgencies](https://developer.intuit.com/app/developer/qbo/docs/api/accounting/all-entities/taxagency) * [TaxCodes](https://developer.intuit.com/app/developer/qbo/docs/api/accounting/all-entities/taxcode) * [TaxRates](https://developer.intuit.com/app/developer/qbo/docs/api/accounting/all-entities/taxrate) * [Terms](https://developer.intuit.com/app/developer/qbo/docs/api/accounting/all-entities/term) * [TimeActivities](https://developer.intuit.com/app/developer/qbo/docs/api/accounting/all-entities/timeactivity) * [Transfers](https://developer.intuit.com/app/developer/qbo/docs/api/accounting/all-entities/transfer) * [VendorCredits](https://developer.intuit.com/app/developer/qbo/docs/api/accounting/all-entities/vendorcredit) * [Vendors](https://developer.intuit.com/app/developer/qbo/docs/api/accounting/all-entities/vendor) ### Data type mapping | Integration Type | Airbyte Type | Notes | | :--- | :--- | :--- | | `string` | `string` | | | `number` | `number` | | | `array` | `array` | | | `object` | `object` | | ### Features | Feature | Supported?\(Yes/No\) | Notes | | :--- | :--- | :--- | | Full Refresh Sync | Yes | | | Incremental Sync | Yes | | | SSL connection | Yes | | | Namespaces | No | | ## Getting started 1. Create an [Intuit Developer account](https://developer.intuit.com/app/developer/qbo/docs/get-started) 2. Create an app 3. Obtain credentials ### Requirements * Client ID * Client Secret * Realm ID * Refresh token The easiest way to get these credentials is by using Quickbook's [OAuth 2.0 playground](https://developer.intuit.com/app/developer/qbo/docs/develop/authentication-and-authorization/oauth-2.0-playground) **Important note:** The refresh token expires every 100 days. You will need to manually revisit the Oauth playground to obtain a refresh token every 100 days, or your syncs will expire. We plan on offering full Oauth support soon so you don't need to redo this process manually. ## CHANGELOG | Version | Date | Pull Request | Subject | | :------ | :-------- | :----- | :------ | | `0.1.3` | 2021-08-10 | [4986](https://github.com/airbytehq/airbyte/pull/4986) | Using number data type for decimal fields instead string | | `0.1.2` | 2021-07-06 | [4539](https://github.com/airbytehq/airbyte/pull/4539) | Add `AIRBYTE_ENTRYPOINT` for Kubernetes support | ======================= File: docs/integrations/sources/spree-commerce.md ======================= # Spree Commerce [Spree Commerce](https://spreecommerce.org/) is an open source eCommerce platform for global brands. ## Sync overview Spree Commerce can run on the MySQL or Postgres databases. You can use Airbyte to sync your Spree Commerce instance by connecting to the underlying database using the appropriate Airbyte connector: * [MySQL](mysql.md) * [Postgres](postgres.md) {% hint style="info" %} Reach out to your service representative or system admin to find the parameters required to connect to the underlying database {% endhint %} ### Output schema The Spree Commerce schema is described in the [Spree Internals](https://dev-docs.spreecommerce.org/internals/) section of the Spree docs. Otherwise, the schema will follow the rules of the MySQL or Postgres connectors. ======================= File: airbyte-integrations/bases/base-normalization/integration_tests/resources/test_primary_key_streams/README.md ======================= # test_primary_key_streams This test suite is focusing on testing a stream of data similar to `source-exchangerates` using two different `destination_sync_modes`: - `incremental` + `overwrite` with stream `exchange_rate` - `incremental` + `append_dedup` with stream `dedup_exchange_rate` To do so, we've setup two streams in the catalog.json and are using the exact same record messages data in both. Note that we are also making sure that one of the column used as primary key is of type `float` as this could be an edge case using it as partition key on certain destinations. # Nested streams The stream `nested_stream_with_complex_columns_resulting_into_long_names` is testing primary key definition on a stream with nested fields with different complex types: - nested object - nested array - nested array of array # Stream names collisions The following three streams are purposely named with very long descriptions to break postgres 64 characters limits: (even if they are set in different schemas) - `test_normalization_nested_stream_with_complex_columns_resulting_into_long_names` - `test_normalization_non_nested_stream_without_namespace_resulting_into_long_names` - `test_normalization_namespace_simple_stream_with_namespace_resulting_into_long_names` which could all be truncated into: - `test_normalization_n__lting_into_long_names` Resulting into collisions... ======================= File: docs/contributing-to-airbyte/developing-on-kubernetes.md ======================= # Developing On Kubernetes Make sure to read [our docs for developing locally](./developing-locally.md) first. ## Architecture ![Airbyte on Kubernetes](../.gitbook/assets/contributing-to-airbyte-k8s-architecture.png) ## Iteration Cycle (Locally) If you're developing locally using Minikube/Docker Desktop/Kind, you can iterate with the following series of commands: ```bash ./gradlew composeBuild # build dev images kubectl delete -k kube/overlays/dev # optional (allows you to recreate resources from scratch) kubectl apply -k kube/overlays/dev # applies manifests kubectl port-forward svc/airbyte-webapp-svc 8000:80 # port forward the api/ui ``` ## Iteration Cycle \(on GKE\) The process is similar to developing on a local cluster, except you will need to build the local version and push it to your own container registry with names such as `your-registry/scheduler`. Then you will need to configure an overlay to override the name of images and apply your overlay with `kubectl apply -k <path to your overlay>`. We are [working to improve this process](https://github.com/airbytehq/airbyte/issues/4225). ## Completely resetting a local cluster In most cases, running `kubectl delete -k kube/overlays/dev` is sufficient to remove the core Airbyte-related components. However, if you are in a dev environment on a local cluster only running Airbyte and want to start **completely from scratch** (removing all PVCs, pods, completed pods, etc.), you can use the following command to destroy everything on the cluster: ```bash # BE CAREFUL, THIS COMMAND DELETES ALL RESOURCES, EVEN NON-AIRBYTE ONES! kubectl delete "$(kubectl api-resources --namespaced=true --verbs=delete -o name | tr "\n" "," | sed -e's/,$//')" --all ``` ======================= File: docs/connector-development/tutorials/cdk-tutorial-python-http/README.md ======================= # Creating an HTTP API Source with the Python CDK ======================= File: docs/integrations/sources/amazon-seller-partner.md ======================= # Amazon Seller Partner ## Sync overview This source can sync data for the [Amazon Seller Partner API](https://github.com/amzn/selling-partner-api-docs/blob/main/guides/en-US/developer-guide/SellingPartnerApiDeveloperGuide.md). ### Output schema This source is capable of syncing the following streams: * [Orders](https://github.com/amzn/selling-partner-api-docs/blob/main/references/orders-api/ordersV0.md) (incremental) * [GET_FLAT_FILE_ALL_ORDERS_DATA_BY_ORDER_DATE_GENERAL](https://github.com/amzn/selling-partner-api-docs/blob/main/references/reports-api/reporttype-values.md#order-tracking-reports) (incremental) * [GET_MERCHANT_LISTINGS_ALL_DATA](https://github.com/amzn/selling-partner-api-docs/blob/main/references/reports-api/reporttype-values.md#inventory-reports) (incremental) * [GET_FBA_INVENTORY_AGED_DATA](https://github.com/amzn/selling-partner-api-docs/blob/main/references/reports-api/reporttype-values.md#fulfillment-by-amazon-fba-reports) (incremental) ### Data type mapping | Integration Type | Airbyte Type | Notes | | :--- | :--- | :--- | | `string` | `string` | | | `int`, `float`, `number` | `number` | | | `date` | `date` | | | `datetime` | `datetime` | | | `array` | `array` | | | `object` | `object` | | ### Features | Feature | Supported?\(Yes/No\) | Notes | | :--- | :--- | :--- | | Full Refresh Sync | yes | | | Incremental Sync | yes | | | Namespaces | No | | ### Performance considerations Information about rate limits you may find [here](https://github.com/amzn/selling-partner-api-docs/blob/main/guides/en-US/usage-plans-rate-limits/Usage-Plans-and-Rate-Limits.md). ## Getting started ### Requirements * replication_start_date * refresh_token * lwa_app_id * lwa_client_secret * aws_access_key * aws_secret_key * role_arn * aws_environment * region ### Setup guide Information about how to get credentials you may find [here](https://github.com/amzn/selling-partner-api-docs/blob/main/guides/en-US/developer-guide/SellingPartnerApiDeveloperGuide.md). ## CHANGELOG | Version | Date | Pull Request | Subject | | :------ | :-------- | :----- | :------ | | `0.2.0` | 2021-08-06 | [#4863](https://github.com/airbytehq/airbyte/pull/4863) | `Rebuild source with airbyte-cdk` | | `0.1.3` | 2021-06-23 | [#4288](https://github.com/airbytehq/airbyte/pull/4288) | `Bugfix failing connection check` | | `0.1.2` | 2021-06-15 | [#4108](https://github.com/airbytehq/airbyte/pull/4108) | `Fixed: Sync fails with timeout when create report is CANCELLED` | ======================= File: docs/integrations/destinations/keen.md ======================= <reponame>luizgribeiro/airbyte --- description: Keen is a fully managed event streaming and analytic platform. --- # Keen ## Overview The Airbyte Keen destination allows you to send/stream data into Keen. Keen is a flexible, fully managed event streaming and analytic platform. ### Sync overview #### Output schema Each stream will output an event in Keen. Each collection will inherit the name from the stream with all non-alphanumeric characters removed, except for `.-_ ` and whitespace characters. When possible, the connector will try to guess the timestamp value for the record and override the special field `keen.timestamp` with it. #### Features | Feature | Supported?\(Yes/No\) | Notes | | :--- | :--- | :--- | | Full Refresh Sync | Yes | | | Incremental - Append Sync | Yes | | | Namespaces | No | | ## Getting started ### Requirements To use the Keen destination, you'll need: * A Keen Project ID * A Keen Master API key associated with the project See the setup guide for more information about how to acquire the required resources. ### Setup guide #### Keen Project If you already have the project set up, jump to the "Access" section. Login to your [Keen](https://keen.io/) account, then click the Add New link next to the Projects label on the left-hand side tab. Then give project a name. #### API Key and Project ID Keen connector uses Keen Kafka Inbound Cluster to stream the data. It requires `Project ID` and `Master Key` for the authentication. To get them, navigate to the `Access` tab from the left-hand side panel and check the `Project Details` section. **Important**: This destination requires the Project's **Master** Key. #### Timestamp Inference `Infer Timestamp` field lets you specify if you want the connector to guess the special `keen.timestamp` field based on the streamed data. It might be useful for historical data synchronization to fully leverage Keen's analytics power. If not selected, `keen.timestamp` will be set to date when data was streamed. By default, set to `true`. ### Setup the Keen destination in Airbyte Now you should have all the parameters needed to configure Keen destination. * **Project ID** * **Master API Key** * **Infer Timestamp** ## CHANGELOG ======================= File: docs/project-overview/slack-code-of-conduct.md ======================= <reponame>luizgribeiro/airbyte --- description: 'Be nice to one another.' --- # Slack Code of Conduct Airbyte's Slack community is growing incredibly fast. We're home to over 1500 data professionals and are growing at an awesome pace. We are proud of our community, and have provided these guidelines to support new members in maintaining the wholesome spirit we have developed here. We appreciate your continued commitment to making this a community we are all excited to be a part of. ## Rule 1: Be respectful. ## Rule 2: Check off your resolved questions. If you asked for help and received a useful reply, please place a ✅ reaction by your original post to mark it as resolved. ## Rule 3: Don’t double-post. If you ask a question and don’t get a response, review your question for clarity and revise it instead of reposting it. If you still feel that you haven’t received an adequate response, feel free to ping @support. ## Rule 4: Keep it public. This is a public forum; do not contact individual members of this community without their explicit permission, independent of reason. ## Rule 5: No soliciting! If you’re a vendor, you may advertise your product in #shameless-plugs. Advertising your product anywhere else, especially in direct messages (DMs), is strictly against the rules. We are appreciative when recruiters and vendors identify themselves through their Slack username. ## Rule 6: Don't spam tags. For support and questions, generally avoid tagging community members. You will find that our community of volunteers is generally very responsive and amazingly helpful! As mentioned above, if you don’t receive an answer to your question, feel free to ping @support. ## Rule 7: Use threads for discussion. Using threads allows us to scope conversations without burying messages before it! They allow us to be organized in responding to questions and help keep our time to first response and resolution very low. --- *If you see a message or receive a direct message that violates any of these rules, please contact an Airbyte team member and we will take the appropriate moderation action immediately. We have zero tolerance for intentional rule-breaking and hate speech.* ======================= File: docs/integrations/sources/woo-commerce.md ======================= # WooCommerce [WooCommerce](https://woocommerce.com/) is an open source eCommerce platform built on Wordpress. ## Sync overview WooCommerce runs on a MySQL database. You can use Airbyte to sync your WooCommerce instance by connecting to the underlying MySQL database and leveraging the [MySQL](./mysql.md) connector. {% hint style="info" %} Reach out to your service representative or system admin to find the parameters required to connect to the underlying database {% endhint %} ### Output schema The output schema is the same as that of the [WooCommerce Database](https://github.com/woocommerce/woocommerce/wiki/Database-Description) described here. ======================= File: docs/understanding-airbyte/high-level-view.md ======================= <reponame>luizgribeiro/airbyte --- description: A high level view of Airbyte's components. --- # High-level View ![3.048-Kilometer view](../.gitbook/assets/understanding_airbyte_high_level_architecture.png) * `UI`: An easy-to-use graphical interface for interacting with the Airbyte API. * `WebApp Server`: Handles connection between UI and API. * `Config Store`: Stores all the connections information \(credentials, frequency...\). * `Scheduler Store`: Stores statuses and job information for the scheduler bookkeeping. * `Config API`: Airbyte's main control plane. All operations in Airbyte such as creating sources, destinations, connections, managing configurations, etc.. are configured and invoked from the API. * `Scheduler`: The scheduler takes work requests from the API and sends them to the Temporal service to parallelize. It is responsible for tracking success/failure and for triggering syncs based on the configured frequency. * `Temporal Service`: Manages the task queue and workflows for the Scheduler. * `Worker`: The worker connects to a source, pulls the data and writes it to a destination. * `Temporary Storage`: A storage that workers can use whenever they need to spill data on a disk. ======================= File: airbyte-migration/README.md ======================= <filename>airbyte-migration/README.md # Airbyte Config Migration This module migrates configs specified in `airbyte-config` to new versions. ## Change Airbyte Configs - Update the config json schema in [`airbyte-config/models`](../airbyte-config/models). - Add the changed json schema to the [main resources](./src/main/resources/migrations). - If a migration is needed, create a migration file under [`io.airbyte.migrate.migrations`](./src/main/java/io/airbyte/migrate/migrations). - Register the migration in [`Migrations.java`](./src/main/java/io/airbyte/migrate/Migrations.java). - If needed, write a migration unit test under [`io.airbyte.migrate.migrations`](./src/test/java/io/airbyte/migrate/migrations). - Test the migration locally in IDE or commandline (see below). ## Test Migration Locally ### IDE Run `MigrationRunner.java` with arguments (`--input`, `--output`, `--target-version`). ### Command line Run the following command in project root: ```sh # Get the current version BUILD_VERSION=$(cat.env | grep VERSION | awk -F"=" '{print $2}') # Build the migration bundle file SUB_BUILD=PLATFORM./gradlew airbyte-migration:build # Extract the bundle file tar xf./airbyte-migration/build/distributions/airbyte-migration-${BUILD_VERSION}.tar --strip-components=1 # Run the migration bin/airbyte-migration \ --input <input_config_archive.tar.gz> \ --output <output_config_archive.tar.gz> ``` See [MigrationRunner](./src/main/java/io/airbyte/migrate/MigrationRunner.java) for details. ## Run migration in production ```sh BUILD_VERSION=$(cat.env | grep VERSION | awk -F"=" '{print $2}') INPUT_PATH=<path to directory containing downloaded airbyte_archive.tar.gz> OUTPUT_PATH=<path to where migrated archive will be written (should end in.tar.gz)> TARGET_VERSION=<version you are migrating to or empty for latest> docker run --rm -v ${INPUT_PATH}:/config airbyte/migration:${BUILD_VERSION} -- \ --input /config/airbyte_archive.tar.gz \ --output ${OUTPUT_PATH} \ [ --target-version ${TARGET_VERSION} ] ``` See [Upgrading Airbyte](https://docs.airbyte.io/tutorials/upgrading-airbyte) for details. ======================= File: airbyte-integrations/connectors/source-looker/CHANGELOG.md ======================= # Changelog Moved to the looker [documentation](https://docs.airbyte.io/integrations/sources/looker#changelog). ======================= File: docs/deploying-airbyte/on-oci-vm.md ======================= <reponame>luizgribeiro/airbyte # Install Airbyte on Oracle Cloud Infrastructure (OCI) VM Install Airbyte on Oracle Cloud Infrastructure VM running Oracle Linux 7 ## Create OCI Instance Go to OCI Console > Compute > Instances > Create Instance ![](../.gitbook/assets/OCIScreen1.png) ![](../.gitbook/assets/OCIScreen2.png) ## Whitelist Port 8000 for a CIDR range in Security List of OCI VM Subnet Go to OCI Console > Networking > Virtual Cloud Network Select the Subnet > Security List > Add Ingress Rules ![](../.gitbook/assets/OCIScreen3.png) ## Login to the Instance/VM with the SSH key and 'opc' user ``` chmod 600 private-key-file ssh -i private-key-file opc@oci-private-instance-ip -p 2200 ``` ## Install Airbyte Prerequisites on OCI VM ### Install Docker sudo yum update -y sudo yum install -y docker sudo service docker start sudo usermod -a -G docker $USER ### Install Docker Compose sudo wget https://github.com/docker/compose/releases/download/1.26.2/docker-compose-$(uname -s)-$(uname -m) -O /usr/local/bin/docker-compose sudo chmod +x /usr/local/bin/docker-compose docker-compose --version ### Install Airbyte mkdir airbyte && cd airbyte wget https://raw.githubusercontent.com/airbytehq/airbyte/master/{.env,docker-compose.yaml} which docker-compose sudo /usr/local/bin/docker-compose up -d ## Create SSH Tunnel to Login to the Instance it is highly recommended to not have a Public IP for the Instance where you are running Airbyte). ### SSH Local Port Forward to Airbyte VM From your local workstation ``` ssh opc@bastion-host-public-ip -i <private-key-file.key> -L 2200:oci-private-instance-ip:22 ssh opc@localhost -i <private-key-file.key> -p 2200 ``` ### Airbyte GUI Local Port Forward to Airbyte VM ``` ssh opc@bastion-host-public-ip -i <private-key-file.key> -L 8000:oci-private-instance-ip:8000 ``` ## Access Airbyte Open URL in Browser : http://localhost:8000/ ![](../.gitbook/assets/OCIScreen4.png) /* Please note Airbyte currently does not support SSL/TLS certificates */ ======================= File: docs/quickstart/add-a-source.md ======================= <reponame>luizgribeiro/airbyte # Add a Source You can either follow this tutorial from the onboarding or through the UI, where you can first navigate to the `Sources` tab on the left bar. Our demo source will pull data from an external API, which will pull down the information on one specified Pokémon. To set it up, just follow the instructions on the screenshot below. {% hint style="info" %} You might have to wait ~30 seconds before the fields show up because it is the first time you're using Airbyte. {% endhint %} ![](../.gitbook/assets/getting-started-source.png) Can't find the connectors that you want? Try your hand at easily building one yourself using our [Python CDK for HTTP API sources!](../connector-development/cdk-python) ======================= File: docs/understanding-airbyte/tech-stack.md ======================= # Technical Stack ## Airbyte Core Backend * Java 14 * Framework: [Jersey](https://eclipse-ee4j.github.io/jersey/) * API: [OAS3](https://www.openapis.org/) * Databases: [PostgreSQL](https://www.postgresql.org/) * Unit & E2E testing: [JUnit 5](https://junit.org/junit5) * Orchestration: [Temporal](https://temporal.io) ## Connectors Connectors can be written in any language. However the most common languages are: * Python 3.7.0 * Java 14 ## **Frontend** * [Node.js 14](https://nodejs.org/en/) * [TypeScript](https://www.typescriptlang.org/) * Web Framework/Library: [React](https://reactjs.org/) ## Additional Tools * CI/CD: [GitHub Actions](https://github.com/features/actions) * Containerization: [Docker](https://www.docker.com/) and [Docker Compose](https://docs.docker.com/compose/) * Linter \(Frontend\): [Prettier](https://prettier.io/) * Formatter \(Backend\): [Spotless](https://github.com/diffplug/spotless) ## FAQ #### *Why do we write most destination/database connectors in Java?* JDBC makes writing reusable database connector frameworks fairly easy, saving us a lot of development time. #### *Why are most REST API connectors written in Python?* Most contributors felt comfortable writing in Python, so we created a [Python CDK](../connector-development/cdk-python) to accelerate this development. You can write a connector from scratch in any language as long as it follows the [Airbyte Specification](./airbyte-specification.md). #### *Why did we choose to build the server with Java?* Simply put, the team has more experience writing production Java code. #### *Why do we use [Temporal](https://temporal.io) for orchestration?* Temporal solves the two major hurdles that exist in orchestrating hundreds to thousands of jobs simultaneously: scaling state management and proper queue management. Temporal solves this by offering primitives that allow serialising the jobs' current runtime memory into a DB. Since a job's entire state is stored, it's trivial to recover from failures, and it's easy to determine if a job was assigned correctly. ======================= File: docs/understanding-airbyte/catalog.md ======================= <reponame>luizgribeiro/airbyte # AirbyteCatalog & ConfiguredAirbyteCatalog Reference ## Overview An `AirbyteCatalog` is a struct that is produced by the `discover` action of a source. It is a list of `AirbyteStream`s. Each `AirbyteStream` describes the data available to be synced from the source. After a source produces an `AirbyteCatalog` or `AirbyteStream`, they should be treated as read only. A `ConfiguredAirbyteCatalog` is a list of `ConfiguredAirbyteStream`s. Each `ConfiguredAirbyteStream` describes how to sync an `AirbyteStream`. ## Cursor * The cursor is how sources track which records are new or updated since the last sync. * A "cursor field" is the field that is used as a comparable for making this determinations. * If a configuration requires a cursor field, it requires an array of strings that serves as a path to the desired field. e.g. if the structure of a stream is `{ value: 2, metadata: { updated_at: 2020-11-01 } }` the `default_cursor_field` might be `["metadata", "updated_at"]`. ## AirbyteStream This section will document the meaning of each field in an `AirbyteStream` * `json_schema` - This field contains a [JsonSchema](https://json-schema.org/understanding-json-schema) representation of the schema of the stream. * `supported_sync_modes` - The sync modes that the stream supports. By default, all sources support `FULL_REFRESH`. Even if this array is empty, it can be assumed that a source supports `FULL_REFRESH`. The allowed sync modes are `FULL_REFRESH` and `INCREMENTAL`. * `source_defined_cursor` - If a source supports the `INCREMENTAL` sync mode, and it sets this field to true, it is responsible for determining internally how it tracks which records in a source are new or updated since the last sync It is an array of keys to a field in the schema. * `default_cursor_field` - If a source supports the `INCREMENTAL` sync mode, it may, optionally, set this field. If this field is set, and the user does not override it with the `cursor_field` attribute in the `ConfiguredAirbyteStream` \(described below\), this field will be used as the cursor. ## ConfiguredAirbyteStream This section will document the meaning of each field in an `ConfiguredAirbyteStream` * `stream` - This field contains the `AirbyteStream` that it is configured. * `sync_mode` - The sync mode that will be used to sync that stream. The value in this field MUST be present in the `supported_sync_modes` array for the discovered `AirbyteStream` of this stream. * `cursor_field` - This field is an array of keys to a field in the schema that in the `INCREMENTAL` sync mode will be used to determine if a record is new or updated since the last sync. * If an `AirbyteStream` defines a `cursor_field`, then the `cursor_field` attribute in `ConfiguredAirbyteStream` will be ignored. * If an `AirbyteStream` defines a `default_cursor_field`, then the `cursor_field` attribute in `ConfiguredAirbyteStream` is not required, but if it is set, it will override the default value. * If an `AirbyteStream` does not define a `cursor_field` or a `default_cursor_field`, then `ConfiguredAirbyteStream` must define a `cursor_field`. ## Logic for resolving the Cursor Field This section lays out how a cursor field is determined in the case of a Stream that is doing an `incremental` sync. * If `source_defined_cursor` in `AirbyteStream` is true, then the source determines the cursor field internally. It cannot be overriden. If it is false, continue... * If `cursor_field` in `ConfiguredAirbyteStream` is set, then the source uses that field as the cursor. If it is not set, continue... * If `default_cursor_field` in `AirbyteStream` is set, then the sources use that field as the cursor. If it is not set, continue... * Illegal - If `source_defined_cursor`, `cursor_field`, and `default_cursor_field` are all falsey, this is an invalid configuration. ======================= File: airbyte-integrations/connectors/destination-s3/README.md ======================= # S3 Test Configuration In order to test the S3 destination, you need an AWS account (or alternative S3 account). ## Community Contributor As a community contributor, you will need access to AWS to run the integration tests. - Create an S3 bucket for testing. - Get your `access_key_id` and `secret_access_key` that can read and write to the above bucket. - Paste the bucket and key information into the config files under [`./sample_secrets`](./sample_secrets). - Rename the directory from `sample_secrets` to `secrets`. - Feel free to modify the config files with different settings in the acceptance test file (e.g. `S3CsvDestinationAcceptanceTest.java`, method `getFormatConfig`), as long as they follow the schema defined in [spec.json](src/main/resources/spec.json). ## Airbyte Employee - Access the `destination s3 creds` secrets on Last Pass, and put it in `sample_secrets/config.json`. - Rename the directory from `sample_secrets` to `secrets`. ## Add New Output Format - Add a new enum in `S3Format`. - Modify `spec.json` to specify the configuration of this new format. - Update `S3FormatConfigs` to be able to construct a config for this new format. - Create a new package under `io.airbyte.integrations.destination.s3`. - Implement a new `S3Writer`. The implementation can extend `BaseS3Writer`. - Write an acceptance test for the new output format. The test can extend `S3DestinationAcceptanceTest`. ======================= File: tools/openapi2jsonschema/README.md ======================= # openapi2jsonschema Util for generating catalog schema from OpenAPI definition file. Froked from [openapi2jsonschema](https://github.com/instrumenta/openapi2jsonschema) util with fixes for generating standlone schemas e.g. ones that don't contain reference to another files/resources. ## Usage ```bash $ tools/openapi2jsonschema/run.sh <path to OpenAPI definition file> ``` It would generate set of jsonschema files based on components described on OpenAPI definition and place it on "**schemas**" fodler in current working directory. Support OpenAPI v2.0, v3.0 and v3.1. Works with both json and yaml OpenAPI formats. ### Examples You can try to run this tool on sample OpenApi definition files located in [exmaples](./examples) directory. That is some OpenAPI files taken from APIs-guru repo [from github](https://github.com/APIs-guru). ======================= File: docs/integrations/custom-connectors.md ======================= <gh_stars>1-10 --- description: Missing a connector? --- # Custom or New Connector If you'd like to **ask for a new connector,** you can request it directly [here](https://github.com/airbytehq/airbyte/issues/new?assignees=&labels=area%2Fintegration%2C+new-integration&template=new-integration-request.md&title=). If you'd like to build new connectors and **make them part of the pool of pre-built connectors on Airbyte,** first a big thank you. We invite you to check our [contributing guide on building connectors](../contributing-to-airbyte/README.md). If you'd like to build new connectors, or update existing ones, **for your own usage,** without contributing to the Airbyte codebase, read along. ## Developing your own connector It's easy to code your own connectors on Airbyte. Here is a link to instruct on how to code new sources and destinations: [building new connectors](../contributing-to-airbyte/README.md) While the guides in the link above are specific to the languages used most frequently to write integrations, **Airbyte connectors can be written in any language**. Please reach out to us if you'd like help developing connectors in other languages. ## Adding your connectors in the UI There are only 3 easy steps to do that: 1.Get the `Docker` coordinate of a custom connector from `Dockerhub` \(or any image repository that Airbyte can access\). 2.In the UI, go to the Admin section, and click on `[+ New connector]` on the top right ![](https://lh4.googleusercontent.com/8lW_KRkw8w8q96JUJ7Snxj9MRC8toOyd7avLEj9anID53Q7Vj1bkPRSp8skV1VcIJPWsjWugX0pj0jCZ2jdaBwqhZED9E7DN5SRX_FWyRMdQu1eRojCTGm3xW2R8xYC9JE_kQtwn) 3.We will ask you for the display name, the Docker repository name, tag and documentation URL for that connector. ![](https://lh6.googleusercontent.<KEY>) Once this is filled, you will see your connector in the UI and your team will be able to use it, **from the UI and Airbyte's API too.** Note that this new connector could just be an updated version of an existing connector that you adapted to your specific edge case. Anything is possible! ## Upgrading a connector To upgrade your connector version, go to the admin panel in the left hand side of the UI, find this connector in the list, and input the latest connector version. ![](../.gitbook/assets/upgrading_connector_admin_panel.png) To browse the available connector versions, simply click on the relevant link in the `Image` column to navigate to the connector's DockerHub page. From there, simply click on the `Tags` section in the top bar. ======================= File:.github/ISSUE_TEMPLATE/bug-report.md ======================= --- name: Bug report about: Report a bug to help us improve title: '' labels: type/bug assignees: '' --- <!-- Welcome to Airbyte! We're really appreciate your report and know that this will help us build an amazing tool. If you want to contribute yourself, you can find a good place to start by searching for the good-first-issues label or maybe... by trying to solve this one? (we can help debug this with you!) Right now we are in alpha, so we're releasing versions a lot more frequently than normal. You can help us get to the root of the problem faster by filling out the questionnaire below! It's really important having all information and context. You can remove the examples bellow and fill out with your information. --> ## Enviroment - **Airbyte version**: example is 0.22.0-alpha - **OS Version / Instance**: example macOS, Windows 7/10, Ubuntu 18.04, GCP n2., AWS EC2 - **Deployment**: example are Docker or Kubernetes deploy env - **Source Connector and version**: (if applicable example Salesforce 0.2.3) <!-- Found in the admin page in the UI in the Source tab. --> - **Destination Connector and version**: (if applicable example Postgres 0.3.3) <!-- Found in the admin page in the UI in the Destination tab. --> - **Severity**: Very Low / Low / Medium / High / Critical - **Step where error happened**: Deploy / Sync job / Setup new connection / Update connector / Upgrade Airbyte ## Current Behavior *Tell us what happens.* ## Expected Behavior *Tell us what should happen.* ## Logs *If applicable, please upload the logs from the failing operation. For sync jobs, you can download the full logs from the UI by going to the sync attempt page and clicking the download logs button at the top right of the logs display window.* <details> <summary>LOG</summary> ``` replace this with your long log output here ``` </details> ## Steps to Reproduce 1. 2. 3. ## Are you willing to submit a PR? <!--- We accept contributions! Don't feel pressured, but if you want to contribute we can help you by giving some tips, highlighting the necessary code change or explaining any relevant point your feature will impact. You can also send questions on #dev Slack channel. We understand if you can't submit a PR and we're tremendously grateful that you've already contributed by suggesting a new feature. --> Remove this with your answer. ======================= File: airbyte-integrations/connectors/source-s3/integration_tests/integration_test.py ======================= # # MIT License # # Copyright (c) 2020 Airbyte # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # import json import time from typing import Iterator, List, Mapping import boto3 from airbyte_cdk.logger import AirbyteLogger from botocore.errorfactory import ClientError from source_s3.stream import IncrementalFileStreamS3 from.integration_test_abstract import HERE, SAMPLE_DIR, AbstractTestIncrementalFileStream LOGGER = AirbyteLogger() class TestIncrementalFileStreamS3(AbstractTestIncrementalFileStream): @property def stream_class(self) -> type: return IncrementalFileStreamS3 @property def credentials(self) -> Mapping: filename = HERE.parent / "secrets/config.json" with open(filename) as json_file: config = json.load(json_file) return { "aws_access_key_id": config["provider"]["aws_access_key_id"], "aws_secret_access_key": config["provider"]["aws_secret_access_key"], } def provider(self, bucket_name: str) -> Mapping: return {"storage": "S3", "bucket": bucket_name} def _s3_connect(self, credentials: Mapping): region = "eu-west-3" self.s3_client = boto3.client( "s3", aws_access_key_id=credentials["aws_access_key_id"], aws_secret_access_key=credentials["aws_secret_access_key"], region_name=region, ) self.s3_resource = boto3.resource( "s3", aws_access_key_id=credentials["aws_access_key_id"], aws_secret_access_key=credentials["aws_secret_access_key"] ) def cloud_files(self, cloud_bucket_name: str, credentials: Mapping, files_to_upload: List, private: bool = True) -> Iterator[str]: self._s3_connect(credentials) region = "eu-west-3" location = {"LocationConstraint": region} bucket_name = cloud_bucket_name print("\n") LOGGER.info(f"Uploading {len(files_to_upload)} file(s) to {'private' if private else 'public'} aws bucket '{bucket_name}'") try: self.s3_client.head_bucket(Bucket=bucket_name) except ClientError: acl = "private" if private else "public-read" self.s3_client.create_bucket(ACL=acl, Bucket=bucket_name, CreateBucketConfiguration=location) # wait here until the bucket is ready ready = False attempts, max_attempts = 0, 30 while not ready: time.sleep(1) try: self.s3_client.head_bucket(Bucket=bucket_name) except ClientError: attempts += 1 if attempts >= max_attempts: raise RuntimeError(f"Couldn't get a successful ping on bucket after ~{max_attempts} seconds") else: ready = True LOGGER.info(f"bucket {bucket_name} initialised") extra_args = {} if not private: extra_args = {"ACL": "public-read"} for filepath in files_to_upload: upload_path = str(filepath).replace(str(SAMPLE_DIR), "") upload_path = upload_path[1:] if upload_path[0] == "/" else upload_path self.s3_client.upload_file(str(filepath), bucket_name, upload_path, ExtraArgs=extra_args) yield f"{bucket_name}/{upload_path}" def teardown_infra(self, cloud_bucket_name: str, credentials: Mapping): self._s3_connect(credentials) bucket = self.s3_resource.Bucket(cloud_bucket_name) bucket.objects.all().delete() bucket.delete() LOGGER.info(f"S3 Bucket {cloud_bucket_name} is now deleted") ======================= File: airbyte-integrations/connectors/source-prestashop/integration_tests/acceptance.py ======================= <reponame>luizgribeiro/airbyte<gh_stars>1-10 # # MIT License # # Copyright (c) 2020 Airbyte # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # import json import subprocess import sys from pathlib import Path import pytest HERE = Path(__file__).parent.absolute() pytest_plugins = ("source_acceptance_test.plugin",) @pytest.fixture(name="create_config", scope="session") def create_config_fixture(): secrets_path = HERE.parent / "secrets" secrets_path.mkdir(exist_ok=True) config_filename = str(secrets_path / "config.json") config = {"url": "http://localhost:8080", "access_key": "<KEY>"} with open(config_filename, "w+") as fp: json.dump(obj=config, fp=fp) @pytest.fixture(scope="session", autouse=True) def connector_setup(create_config): """This fixture is a placeholder for external resources that acceptance test might require.""" filename = str(HERE / "docker-compose.yaml") subprocess.check_call([sys.executable, "-m", "pip", "install", "docker-compose"], stdout=subprocess.DEVNULL) subprocess.check_call(["docker-compose", "-f", filename, "up", "-d"]) yield subprocess.check_call(["docker-compose", "-f", filename, "down", "-v"]) ======================= File: airbyte-cdk/python/airbyte_cdk/sources/streams/http/exceptions.py ======================= # # MIT License # # Copyright (c) 2020 Airbyte # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # from typing import Union import requests class BaseBackoffException(requests.exceptions.HTTPError): pass class RequestBodyException(Exception): """ Raised when there are issues in configuring a request body """ class UserDefinedBackoffException(BaseBackoffException): """ An exception that exposes how long it attempted to backoff """ def __init__(self, backoff: Union[int, float], request: requests.PreparedRequest, response: requests.Response): """ :param backoff: how long to backoff in seconds :param request: the request that triggered this backoff exception :param response: the response that triggered the backoff exception """ self.backoff = backoff super().__init__(request=request, response=response) class DefaultBackoffException(BaseBackoffException): pass ======================= File: airbyte-integrations/connectors/source-instagram/integration_tests/test_streams.py ======================= <reponame>luizgribeiro/airbyte # # MIT License # # Copyright (c) 2020 Airbyte # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # from typing import Any, Callable, List, MutableMapping, Tuple import pendulum import pytest from airbyte_cdk import AirbyteLogger from airbyte_cdk.models import AirbyteMessage, ConfiguredAirbyteCatalog, Type from source_instagram.source import SourceInstagram @pytest.fixture(name="state") def state_fixture() -> MutableMapping[str, Any]: today = pendulum.today() return { "user_insights": { "17841408147298757": {"date": (today - pendulum.duration(days=10)).to_datetime_string()}, "17841403112736866": {"date": (today - pendulum.duration(days=5)).to_datetime_string()}, } } class TestInstagramSource: """Custom integration tests should test incremental with nested state""" def test_incremental_streams(self, configured_catalog, config, state): catalog = self.slice_catalog(configured_catalog, lambda name: name == "user_insights") records, states = self._read_records(config, catalog) assert len(records) == 60, "UserInsights for two accounts over last 30 day should return 60 records when empty STATE provided" records, states = self._read_records(config, catalog, state) assert len(records) <= 60 - 10 - 5, "UserInsights should have less records returned when non empty STATE provided" assert states, "insights should produce states" for state in states: assert "user_insights" in state.state.data assert isinstance(state.state.data["user_insights"], dict) assert len(state.state.data["user_insights"].keys()) == 2 @staticmethod def slice_catalog(catalog: ConfiguredAirbyteCatalog, predicate: Callable[[str], bool]) -> ConfiguredAirbyteCatalog: sliced_catalog = ConfiguredAirbyteCatalog(streams=[]) for stream in catalog.streams: if predicate(stream.stream.name): sliced_catalog.streams.append(stream) return sliced_catalog @staticmethod def _read_records(conf, catalog, state=None) -> Tuple[List[AirbyteMessage], List[AirbyteMessage]]: records = [] states = [] for message in SourceInstagram().read(AirbyteLogger(), conf, catalog, state=state): if message.type == Type.RECORD: records.append(message) elif message.type == Type.STATE: states.append(message) return records, states ======================= File: airbyte-integrations/connectors/source-looker/source_looker/client.py ======================= # # MIT License # # Copyright (c) 2020 Airbyte # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # from typing import Generator, List, Tuple import backoff import requests from airbyte_protocol import AirbyteStream from base_python import BaseClient from requests.exceptions import ConnectionError from requests.structures import CaseInsensitiveDict class Client(BaseClient): API_VERSION = "3.1" def __init__(self, domain: str, client_id: str, client_secret: str, run_look_ids: list = []): """ Note that we dynamically generate schemas for the stream__run_looks function because the fields returned depend on the user's look(s) (entered during configuration). See get_run_look_json_schema(). """ self.BASE_URL = f"https://{domain}/api/{self.API_VERSION}" self._client_id = client_id self._client_secret = client_secret self._token, self._connect_error = self.get_token() self._headers = { "Authorization": f"token {self._token}", "Content-Type": "application/json", "Accept": "application/json", } # Maps Looker types to JSON Schema types for run_look JSON schema self._field_type_mapping = { "string": "string", "date_date": "datetime", "date_raw": "datetime", "date": "datetime", "date_week": "datetime", "date_day_of_week": "string", "date_day_of_week_index": "integer", "date_month": "string", "date_month_num": "integer", "date_month_name": "string", "date_day_of_month": "integer", "date_fiscal_month_num": "integer", "date_quarter": "string", "date_quarter_of_year": "string", "date_fiscal_quarter": "string", "date_fiscal_quarter_of_year": "string", "date_year": "integer", "date_day_of_year": "integer", "date_week_of_year": "integer", "date_fiscal_year": "integer", "date_time_of_day": "string", "date_hour": "string", "date_hour_of_day": "integer", "date_minute": "datetime", "date_second": "datetime", "date_millisecond": "datetime", "date_microsecond": "datetime", "number": "number", "int": "integer", "list": "array", "yesno": "boolean", } # Helpers for the self.stream__run_looks function self._run_look_explore_fields = {} self._run_looks, self._run_looks_connect_error = self.get_run_look_info(run_look_ids) self._dashboard_ids = [] self._project_ids = [] self._role_ids = [] self._user_attribute_ids = [] self._user_ids = [] self._context_metadata_mapping = {"dashboards": [], "folders": [], "homepages": [], "looks": [], "spaces": []} super().__init__() @property def streams(self) -> Generator[AirbyteStream, None, None]: """ Uses the default streams except for the run_look endpoint, where we have to generate its JSON Schema on the fly for the given look """ streams = super().streams for stream in streams: if len(self._run_looks) > 0 and stream.name == "run_looks": stream.json_schema = self._get_run_look_json_schema() yield stream def get_token(self): headers = CaseInsensitiveDict() headers["Content-Type"] = "application/x-www-form-urlencoded" try: resp = requests.post( url=f"{self.BASE_URL}/login", headers=headers, data=f"client_id={self._client_id}&client_secret={self._client_secret}" ) if resp.status_code!= 200: return None, "Unable to connect to the Looker API. Please check your credentials." return resp.json()["access_token"], None except ConnectionError as error: return None, str(error) def get_run_look_info(self, run_look_ids): """ Checks that the look IDs entered exist and can be queried and returns the LookML model for each (needed for JSON Schema creation) """ looks = [] for look_id in run_look_ids: resp = self._request(f"{self.BASE_URL}/looks/{look_id}?fields=model(id),title") if resp == []: return ( [], f"Unable to find look {look_id}. Verify that you have entered a valid look ID and that you have permission to run it.", ) looks.append((resp[0]["model"]["id"], look_id, resp[0]["title"])) return looks, None def health_check(self) -> Tuple[bool, str]: if self._connect_error: return False, self._connect_error elif self._run_looks_connect_error: return False, self._run_looks_connect_error return True, "" @backoff.on_exception(backoff.expo, requests.exceptions.ConnectionError, max_tries=7) def _request(self, url: str, method: str = "GET", data: dict = None) -> List[dict]: response = requests.request(method, url, headers=self._headers, json=data) if response.status_code == 200: response_data = response.json() if isinstance(response_data, list): return response_data else: return [response_data] return [] def _get_run_look_json_schema(self): """ Generates a JSON Schema for the run_look endpoint based on the Look IDs entered in configuration """ json_schema = { "$schema": "http://json-schema.org/draft-07/schema#", "additionalProperties": True, "type": "object", "properties": { self._get_run_look_key(look_id, look_name): { "title": look_name, "properties": {field: self._get_look_field_schema(model, field) for field in self._get_look_fields(look_id)}, "type": ["null", "object"], "additionalProperties": False, } for (model, look_id, look_name) in self._run_looks }, } return json_schema def _get_run_look_key(self, look_id, look_name): return f"{look_id} - {look_name}" def _get_look_field_schema(self, model, field): """ For a given LookML model and field, looks up its type and generates its properties for the run_look endpoint JSON Schema """ explore = field.split(".")[0] fields = self._get_explore_fields(model, explore) field_type = "string" # default to string for dimension in fields["dimensions"]: if field == dimension["name"] and dimension["type"] in self._field_type_mapping: field_type = self._field_type_mapping[dimension["type"]] for measure in fields["measures"]: if field == measure["name"]: # Default to number except for list, date, and yesno field_type = "number" if measure["type"] in self._field_type_mapping: field_type = self._field_type_mapping[measure["type"]] if field_type == "datetime": # no datetime type for JSON Schema return {"type": ["null", "string"], "format": "date-time"} return {"type": ["null", field_type]} def _get_explore_fields(self, model, explore): """ For a given LookML model and explore, looks up its dimensions/measures and their types for run_look endpoint JSON Schema generation """ if (model, explore) not in self._run_look_explore_fields: self._run_look_explore_fields[(model, explore)] = self._request( f"{self.BASE_URL}/lookml_models/{model}/explores/{explore}?fields=fields(dimensions(name,type),measures(name,type))" )[0]["fields"] return self._run_look_explore_fields[(model, explore)] def _get_look_fields(self, look_id) -> List[str]: return self._request(f"{self.BASE_URL}/looks/{look_id}?fields=query(fields)")[0]["query"]["fields"] def _get_dashboard_ids(self) -> List[int]: if not self._dashboard_ids: self._dashboard_ids = [obj["id"] for obj in self._request(f"{self.BASE_URL}/dashboards") if isinstance(obj["id"], int)] return self._dashboard_ids def _get_project_ids(self) -> List[int]: if not self._project_ids: self._project_ids = [obj["id"] for obj in self._request(f"{self.BASE_URL}/projects")] return self._project_ids def _get_user_ids(self) -> List[int]: if not self._user_ids: self._user_ids = [obj["id"] for obj in self._request(f"{self.BASE_URL}/users")] return self._user_ids def stream__color_collections(self, fields): yield from self._request(f"{self.BASE_URL}/color_collections") def stream__connections(self, fields): yield from self._request(f"{self.BASE_URL}/connections") def stream__dashboards(self, fields): dashboards_list = [obj for obj in self._request(f"{self.BASE_URL}/dashboards") if isinstance(obj["id"], int)] self._dashboard_ids = [obj["id"] for obj in dashboards_list] self._context_metadata_mapping["dashboards"] = [ obj["content_metadata_id"] for obj in dashboards_list if isinstance(obj["content_metadata_id"], int) ] yield from dashboards_list def stream__dashboard_elements(self, fields): for dashboard_id in self._get_dashboard_ids(): yield from self._request(f"{self.BASE_URL}/dashboards/{dashboard_id}/dashboard_elements") def stream__dashboard_filters(self, fields): for dashboard_id in self._get_dashboard_ids(): yield from self._request(f"{self.BASE_URL}/dashboards/{dashboard_id}/dashboard_filters") def stream__dashboard_layouts(self, fields): for dashboard_id in self._get_dashboard_ids(): yield from self._request(f"{self.BASE_URL}/dashboards/{dashboard_id}/dashboard_layouts") def stream__datagroups(self, fields): yield from self._request(f"{self.BASE_URL}/datagroups") def stream__folders(self, fields): folders_list = self._request(f"{self.BASE_URL}/folders") self._context_metadata_mapping["folders"] = [ obj["content_metadata_id"] for obj in folders_list if isinstance(obj["content_metadata_id"], int) ] yield from folders_list def stream
1,519
Repo: sasaju/NormalSchedule ======================= File: app/src/main/java/com/liflymark/normalschedule/logic/model/GraduateWeb.kt ======================= package com.liflymark.normalschedule.logic.model import androidx.annotation.Keep @Keep data class GraduateWeb( val cookies: String, val result: String ) ======================= File: app/src/main/java/com/liflymark/normalschedule/ui/tool_box/ToolBoxElement.kt ======================= <gh_stars>1-10 package com.liflymark.normalschedule.ui.tool_box import androidx.compose.foundation.* import androidx.compose.foundation.layout.* import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.* import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Shape import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.google.accompanist.flowlayout.FlowMainAxisAlignment import com.google.accompanist.flowlayout.FlowRow @Composable fun SinglePart(titleIcon:ImageVector, titleName:String, content: @Composable () -> Unit){ val mainColor = Color.Gray Card(elevation = 2.dp, modifier = Modifier .fillMaxWidth() .padding(3.dp)) { Column( modifier = Modifier.fillMaxWidth() ) { Spacer(modifier = Modifier.height(5.dp)) Row { Spacer(modifier = Modifier.width(16.dp)) Icon( titleIcon, contentDescription = null, modifier = Modifier.size(20.dp), tint = mainColor ) Spacer(modifier = Modifier.width(10.dp)) Text(text = titleName, fontSize = 12.sp, color = mainColor) Spacer(modifier = Modifier.height(10.dp)) } Spacer(modifier = Modifier.height(10.dp)) FlowRow( modifier = Modifier.fillMaxWidth(), mainAxisAlignment = FlowMainAxisAlignment.Center, lastLineMainAxisAlignment = FlowMainAxisAlignment.SpaceAround, mainAxisSpacing = 2.dp, crossAxisSpacing = 2.dp ) { content() } } } } @Composable fun SingleButton(icon:ImageVector,description: String,onClick:()->Unit){ Surface(shape = RoundedCornerShape(4.dp)) { Column( verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier .size(85.dp) .padding(2.dp) .clickable { onClick() } ) { Icon( icon, contentDescription = null, modifier = Modifier.size(50.dp), tint = MaterialTheme.colors.primary ) Spacer(modifier = Modifier.height(2.dp)) Text(text = description) } } } @Composable fun CenterCard( modifier: Modifier = Modifier, shape: Shape = MaterialTheme.shapes.medium, backgroundColor: Color = MaterialTheme.colors.surface, contentColor: Color = contentColorFor(backgroundColor), border: BorderStroke? = null, elevation: Dp = 1.dp, content: @Composable () -> Unit ){ Box(modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.Center){ Surface( modifier = modifier, shape = shape, color = backgroundColor, contentColor = contentColor, elevation = elevation, border = border, content = content ) } } //@Preview(showBackground = true) //@Composable //fun DefaultPreview9() { // NorScTheme { // Column(modifier = Modifier // .fillMaxSize() // .verticalScroll(rememberScrollState())) { // SinglePart( // titleIcon = Icons.Default.Message, // titleName = "开发者公告" // ) { // SingleButton(Icons.Filled.StickyNote2, "公告栏"){ // // } // } // // SinglePart( // titleIcon = Icons.Default.EmojiSymbols, // titleName = "校内生活" // ) { // SingleButton(Icons.Filled.CalendarToday, "校历") { // // } // SingleButton(Icons.Filled.DirectionsBus, "校车时刻表") { // // } // SingleButton(Icons.Filled.LunchDining, "作息时刻表") { // // } // } // // SinglePart( // titleIcon = Icons.Default.Fastfood, // titleName = "吃喝玩乐" // ) { // SingleButton(Icons.Filled.ShoppingBag, "购物指南") { // // } // SingleButton(Icons.Filled.FoodBank, "美食指南") { // // } // } // } // } //} ======================= File: app/src/main/java/com/liflymark/normalschedule/ui/sign_in_compose/TopBar.kt ======================= package com.liflymark.normalschedule.ui.sign_in_compose import android.app.Activity import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material.icons.filled.Close import androidx.compose.runtime.* import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.tooling.preview.Preview @Composable fun NormalTopBar(label: String){ val activity = LocalContext.current as Activity TopAppBar( title = { Text(label) }, navigationIcon = { IconButton(onClick = { activity.finish() }) { Icon(Icons.Filled.ArrowBack, null) } }, backgroundColor = Color(0xFF2196F3) ) } @Composable fun NormalTopBar(label: String,nav: () -> Unit){ TopAppBar( title = { Text(label) }, navigationIcon = { IconButton(onClick = { nav() }) { Icon(Icons.Filled.Close, null) } }, backgroundColor = Color(0xFF2196F3) ) } @Preview(showBackground = true) @Composable fun MyPreView() { } ======================= File: app/src/main/java/com/liflymark/normalschedule/ui/work_book/WorkBookActivity.kt ======================= package com.liflymark.normalschedule.ui.work_book import android.os.Bundle import android.util.Log import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.material.Scaffold import androidx.lifecycle.ViewModelProvider import androidx.navigation.compose.rememberNavController import com.google.accompanist.pager.ExperimentalPagerApi import com.liflymark.normalschedule.ui.login_space_room.ShowSpaceViewModel import com.liflymark.normalschedule.ui.score_detail.UiControl import com.liflymark.normalschedule.ui.sign_in_compose.NormalTopBar import com.liflymark.normalschedule.ui.theme.NorScTheme class WorkBookActivity : ComponentActivity() { private val viewModel by lazy { ViewModelProvider(this).get(WorkBookViewModel::class.java) } @OptIn(ExperimentalPagerApi::class, ExperimentalMaterialApi::class) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val courseName = intent.getStringExtra("courseName")?.replace("?", "")?.replace("/", "") setContent { val nav = rememberNavController() if (courseName == null) { WorkBookNavGraph( navController = nav, startDestination = "allWork" ) } else { Log.d("WOrkbookAc", courseName) ACourseWorkList(courseName = courseName) } } } } //@ExperimentalMaterialApi //@Preview(showBackground = true) //@Composable //fun DefaultPreview2() { // NorScTheme { // SingleBookButton() // } //} ======================= File: app/src/main/java/com/liflymark/normalschedule/logic/Repository.kt ======================= package com.liflymark.normalschedule.logic import android.content.ContentResolver import android.content.Context import android.content.Intent import android.graphics.Bitmap import android.graphics.BitmapFactory import android.net.Uri import android.util.Log import androidx.compose.runtime.snapshotFlow import androidx.lifecycle.liveData import com.liflymark.normalschedule.NormalScheduleApplication import com.liflymark.normalschedule.R import com.liflymark.normalschedule.logic.bean.* import com.liflymark.normalschedule.logic.dao.AccountDao import com.liflymark.normalschedule.logic.dao.AccountDataDao import com.liflymark.normalschedule.logic.dao.AppDatabase import com.liflymark.normalschedule.logic.dao.SentenceDao import com.liflymark.normalschedule.logic.model.* import com.liflymark.normalschedule.logic.network.NormalScheduleNetwork import com.liflymark.normalschedule.logic.utils.Convert import com.liflymark.normalschedule.logic.utils.GetDataUtil import com.liflymark.normalschedule.ui.show_timetable.getNeededClassList import com.liflymark.schedule.data.Settings import com.liflymark.schedule.data.twoColorItem import es.dmoral.toasty.Toasty import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.* import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import kotlin.coroutines.CoroutineContext object Repository { private val dataBase = AppDatabase.getDatabase(NormalScheduleApplication.context) private val courseDao = dataBase.courseDao() private val backgroundDao = dataBase.backgroundDao() private val homeworkDao = dataBase.homeworkDao() private val startBulletinBean = dataBase.StartBulletinDao() fun getDefaultString() = listOf( listOf("#12c2e9", "#FFFC354C", "#FF0ABFBC"), listOf("#376B78", "#FFC04848", "#FF480048"), listOf("#f64f59", "#ff5f2c82", "#ff49a09d"), listOf("#CBA689", "#FFDC2424", "#DF5B69BE"), listOf("#ffffbb33", "#ff24C6DC", "#ff514A9D"), listOf("#8202F2", "#ffE55D87", "#ff5FC3E4"), listOf("#F77CC2", "#ff5C258D", "#ff4389A2"), listOf("#4b5cc4", "#ff134E5E", "#ff71B280"), listOf("#426666", "#ff085078", "#ff85D8CE"), listOf("#40de5a", "#ff4776E6", "#ff8E54E9"), listOf("#f0c239", "#5B59FF", "#D2934B"), listOf("#725e82", "#A91A2980", "#ff26D0CE"), listOf("#c32136", "#ffAA076B", "#E692088F"), listOf("#b35c44", "#FFFFA8C3", "#FFDCE083"), ) private fun getDefaultStringTwo() = listOf( listOf("#6E3CBC","#30cfd0", "#330867"), listOf("#7267CB","#667eea", "#764ba2"), listOf("#98BAE7","#9890e3", "#b1f4cf"), listOf("#B8E4F0","#2af598", "#009efd"), listOf("#009DAE","#00c6fb", "#005bea"), listOf("#009DAE","#00c6fb", "#005bea"), listOf("#38A3A5","#b721ff", "#21d4fd"), listOf("#57CC99","#0acffe", "#495aff"), listOf("#80ED99","#007adf", "#00ecbc"), listOf("#7FC8A9","#7DE2FC", "#B9B6E5"), listOf("#D5EEBB","#6C44EC", "#3AC1FC"), listOf("#3EDBF0","#5A49F5", "##2C9CA6"), listOf("#93e37d","#7164F5", "#21BEF1"), listOf("#7868E6","#511DDC", "#5AA2FC"), ) fun getId() = fire(Dispatchers.IO) { val id = NormalScheduleNetwork.getId() if (id.id!= "") { Result.success(id) } else { Result.failure(RuntimeException("Can't get id!")) } } fun getId2() = liveData { try { val result = NormalScheduleNetwork.getId() emit(result) } catch (e: Exception) { emit(IdResponse("")) } } fun getId3() = fireFlow(Dispatchers.IO) { Result.success(NormalScheduleNetwork.getId()) } fun getId4() = liveData { try { val result = NormalScheduleNetwork.getId() emit(result) } catch (e: Exception) { emit(IdResponse("love")) } } fun getId5() = flow { val result = NormalScheduleNetwork.getId() emit(result) }.catch { emit(IdResponse("love")) } suspend fun getId6():IdResponse{ Log.d("Repo", "GetID6") return try { NormalScheduleNetwork.getId() } catch (e:Exception){ IdResponse("love") } } fun cancelAll() = NormalScheduleNetwork.cancelAll() fun getCaptcha(sessionId: String) = liveData(Dispatchers.IO) { try { val img = NormalScheduleNetwork.getCaptcha(sessionId).bytes() val imgStream = BitmapFactory.decodeByteArray(img, 0, img.size) emit(imgStream) } catch (e: Exception) { emit(null) } } // fun getCourse(user:String, password:String, yzm:String, headers:String) = fire(Dispatchers.IO) { // val courseResponse = NormalScheduleNetwork.getCourse(user, password, yzm, headers) // Result.success(courseResponse) // } // // fun getCourse(user: String, password: String) = fire(Dispatchers.IO){ // val courseResponse = NormalScheduleNetwork.getCourse(user, password) // Result.success(courseResponse) // } fun getCourse2(user: String, password: String, yzm: String, headers: String) = liveData(Dispatchers.IO) { try { when { user == "123456" -> { val courseResponse = courseSampleData() emit(courseResponse) } headers!= "" -> { val courseResponse = NormalScheduleNetwork.getCourse(user, password, yzm, headers) Log.d("Repon", "getCourse发生错误") emit(courseResponse) } else -> { val courseResponse = NormalScheduleNetwork.getCourse(user, password) emit(courseResponse) } } } catch (e: Exception) { Log.d("Repon", e.toString()) emit(null) } } fun getCourse2(user: String, password: String) = liveData(Dispatchers.IO) { try { if (user == "123456") { val courseResponse = courseSampleData() emit(courseResponse) } else { val courseResponse = NormalScheduleNetwork.getCourse(user, password) emit(courseResponse) } } catch (e: Exception) { emit(null) } } fun getVisitCourse() = fire(Dispatchers.IO) { // val courseResponse = NormalScheduleNetwork.getVisitCourse() val courseResponse = CourseResponse( listOf( AllCourse( "五四路", 4, 1, "11111111111111111111111", 1, "点击右上角重新导入课程", "", "" ) ), status = "ok" ) Result.success(courseResponse) } suspend fun loadCourseUnTeacher( className: String, classDay: Int, classSessions: Int, continuingSession: Int, buildingName: String ): List<CourseBean> { return courseDao.loadCourseUnTeacher( className, classDay, classSessions, continuingSession, buildingName ) } suspend fun loadCourseUnTeacher( className: String, classDay: Int, classSessions: Int, continuingSession: Int ): List<CourseBean> { return courseDao.loadCourseUnTeacher( className, classDay, classSessions, continuingSession ) } fun loadAllCourse2(colorList: List<List<String>> = getDefaultString()) = liveData(Dispatchers.IO) { emit(Convert.courseBeanToOneByOne2(courseDao.loadAllUnRemoveCourse(), colorList)) } fun getDepartmentList() = flow { Log.d("Repo", "getDeprat执行") val result = NormalScheduleNetwork.getDepartmentList() emit(result) }.catch { emit(DepartmentList("异常", listOf())) }.flowOn(Dispatchers.IO) fun loadCourseByMajorToAll(department: String, major: String) = flow { val result = NormalScheduleNetwork.getCourseByMajor(department, major) emit(result) }.catch { emit(CourseResponse(listOf(), "异常")) } fun loadCourseByMajor2(department: String, major: String) = flow { val result = NormalScheduleNetwork.getCourseByMajor(department, major) val allCourseList = mutableListOf<CourseBean>() if (result.status == "读取正常") { for (i in result.allCourse) { val a = Convert.courseResponseToBean(i) allCourseList.add(a) } } emit(Convert.courseBeanToOneByOne2(allCourseList, getDefaultString())) }.catch { emit(getNeededClassList(getData())) } fun deleteCourseByName(courseName: String) = liveData(Dispatchers.IO) { try { courseDao.deleteCourseByName(courseName) emit(true) } catch (e: Exception) { emit(false) } } fun loadCourseByName2(courseName: String) = flow { val courseBeanList = courseDao.loadCourseByName(courseName) emit(courseBeanList.toList()) }.catch { emit( listOf( CourseBean( campusName = "五四路校区", classDay = 3, classSessions = 9, classWeek = "111111111111110000000000", continuingSession = 3, courseName = courseName, teacher = "发生错误 ", teachingBuildName = "发生错误 ", color = "#f0c239" ) ) ) }.flowOn(Dispatchers.IO) suspend fun loadCourseByName(courseName: String) = try { courseDao.loadCourseByName(courseName) } catch (e: Exception) { listOf( CourseBean( campusName = "五四路校区", classDay = 3, classSessions = 9, classWeek = "111111111111110000000000", continuingSession = 3, courseName = "发生错误", teacher = "发生错误 ", teachingBuildName = "发生错误 ", color = "#f0c239" ) ) } suspend fun deleteCourseByList(courseBeanList: List<CourseBean>) { try { courseBeanList.forEach { courseDao.deleteCourse(it) Log.d("Repo", it.toString()) } } catch (e: java.lang.Exception) { Log.d("Repos", e.toString()) } } fun loadCourseByNameAndStart2(courseName: String, courseStart: Int, whichColumn: Int) = flow { val result = courseDao.loadCourseByNameAndStart(courseName, courseStart, whichColumn) emit(result[0]) } .catch { emit(CourseBean("", 0, 0, "011110", 0, "异常查询", "", "", "")) } .flowOn(Dispatchers.IO) fun getScore(user: String, password: String, id: String) = liveData(Dispatchers.IO) { try { if (user!= "123456") { val scoreResponse = NormalScheduleNetwork.getScore(user, password, id) emit(scoreResponse) } else { val scoreResponse = ScoreResponse( listOf( Grade( "培养方案", listOf( listOf( ThisProjectGrade("实例", "示例课程", 90.0, "2021"), ThisProjectGrade("实例", "示例课程2", 95.0, "2021") ) ) ), ), "登陆成功" ) emit(scoreResponse) } } catch (e: Exception) { emit(null) } } fun getScoreDetail2(user: String, password: String, id: String) = fireFlow(Dispatchers.IO) { if (user!= "123456") { val scoreDetailResponse = NormalScheduleNetwork.getScoreDetail(user, password, id) Result.success(scoreDetailResponse) } else { val a = ScoreDetail( listOf( Grades("90", "示例课程", "培养方案", "90.0", "5.0", "90", "99", "20", "5", "88"), Grades("92", "示例课程2", "培养方案", "90.0", "4.0", "92.2", "95", "10", "10", "95") ), result = "登陆成功" ) Result.success(a) } } fun getScoreDetail(user: String, password: String, id: String) = flow { if (user!= "123456") { val scoreDetailResponse = NormalScheduleNetwork.getScoreDetail(user, password, id) emit(scoreDetailResponse) } else { val a = ScoreDetail( listOf( Grades("90", "示例课程", "培养方案", "90.0", "5.0", "90", "99", "20", "5", "88"), Grades("92", "示例课程2", "培养方案", "90.0", "4.0", "92.2", "95", "10", "10", "95") ), result = "登陆成功" ) emit(a) } }.catch { val a = ScoreDetail( listOf( Grades("90", "示例课程", "培养方案", "90.0", "5.0", "90", "99", "20", "5", "88"), Grades("92", "示例课程2", "培养方案", "90.0", "4.0", "92.2", "95", "10", "10", "95") ), result = "登陆异常" ) emit(a) } fun loadAllCourse3(): List<List<OneByOneCourseBean>>? { return try { Convert.courseBeanToOneByOne2(courseDao.loadAllCourseAs(), getDefaultString()) } catch (e: Exception) { null } } suspend fun insertCourse2(courseList: List<AllCourse>) { for (singleCourse in courseList) { try { courseDao.insertCourse(Convert.courseResponseToBean(singleCourse)) } catch (e: Exception) { } } } suspend fun insertCourse(courseBean: CourseBean) { try { courseDao.insertCourse(courseBean) } catch (e: Exception) { } } suspend fun insertCourse(courseBean: List<CourseBean>) { courseBean.forEach { try { Log.d("Repo", courseBean.toString()) courseDao.insertCourse(it) } catch (e: Exception) { courseDao.updateCourse(it) } } } suspend fun deleteAllCourseBean2() { try { courseDao.deleteAllCourseBean() } catch (e: Exception) { // Result.failure<Exception>(e) } } suspend fun updateBackground(background: UserBackgroundBean) { return try { backgroundDao.insertBackground(background) } catch (e: Exception) { backgroundDao.updateBackground(background) } } fun loadBackground() = liveData(Dispatchers.IO) { val resources = NormalScheduleApplication.context.resources val resourceId = R.drawable.main_background_4 // r.mipmap.yourmipmap; R.drawable.yourdrawable val uriBeepSound = Uri.Builder() .scheme(ContentResolver.SCHEME_ANDROID_RESOURCE) .authority(resources.getResourcePackageName(resourceId)) .appendPath(resources.getResourceTypeName(resourceId)) .appendPath(resources.getResourceEntryName(resourceId)) .build() try { val a = backgroundDao.loadLastBackground() if (a.userBackground!= "0") { emit(Uri.parse(a.userBackground)) } else { Log.d("ShowBackgroudRE", uriBeepSound.toString()) emit(uriBeepSound) } } catch (e: Exception) { emit(uriBeepSound) } } suspend fun loadBackground2():Uri { val resources = NormalScheduleApplication.context.resources val resourceId = R.drawable.main_background_4 // r.mipmap.yourmipmap; R.drawable.yourdrawable val uriBeepSound = Uri.Builder() .scheme(ContentResolver.SCHEME_ANDROID_RESOURCE) .authority(resources.getResourcePackageName(resourceId)) .appendPath(resources.getResourceTypeName(resourceId)) .appendPath(resources.getResourceEntryName(resourceId)) .build() try { val a = backgroundDao.loadLastBackground() if (a.userBackground!= "0") { return Uri.parse(a.userBackground) } else { Log.d("ShowBackgroudRE", uriBeepSound.toString()) return uriBeepSound } } catch (e: Exception) { return uriBeepSound } } suspend fun loadBackgroundFileName(): String? { return try { val a = backgroundDao.loadLastBackground() if (a.userBackground!= "0") { a.userBackground.split('/').last() } else { null } } catch (e: java.lang.Exception) { null } } fun getSentences(force: Boolean = false) = flow { try { if (SentenceDao.isSentenceSaved() &&!force) { val resultList = SentenceDao.getSentences() emit(OneSentencesResponse(resultList, "local")) } else { val result = NormalScheduleNetwork.getSentences() SentenceDao.saveSentence(result.result) emit(result) } } catch (e: Exception) { emit(null) } } fun loginToSpace(user: String, password: String, id: String) = flow { try { val result = NormalScheduleNetwork.loginToSpace(user, password, id) emit(result) } catch (e: Exception) { emit(SpaceLoginResponse("登陆异常")) } }.flowOn(Dispatchers.IO) .catch { emit(SpaceLoginResponse("登陆异常")) } fun getBulletin() = flow { val result = NormalScheduleNetwork.getBulletin() emit(result) } .flowOn(Dispatchers.IO) .catch { val error = Bulletin("admin", "作者服务器炸了,有事烧纸", "????", "作者服务器炸了") emit(DevBoardResponse(listOf(error), status = "error")) } fun getSpaceRooms(id: String, roomName: String, searchDate: String) = flow { val result = NormalScheduleNetwork.getSpaceRooms(id, roomName, searchDate) emit(result) }.catch { val errorRoom = Room("查询失败", "0", "00000000000", "无") emit(SpaceResponse(roomList = listOf(errorRoom), roomName = roomName)) }.flowOn(Dispatchers.IO) fun getSchoolBusTime(searchType: String) = flow { val result = NormalScheduleNetwork.getSchoolBusTime(searchType = searchType) emit(result) }.catch { val error = SchoolBusResponse( nowDay = "error", timeList = TimeList( fiveToSeven = listOf(), sevenToFive = listOf() ) ) emit(error) } suspend fun addHomework(homeworkBean: HomeworkBean): Long { return homeworkDao.insertHomeWork(homeworkBean) } fun loadHomeworkByName(courseName: String) = flow { val result = homeworkDao.loadHomeworkByName(courseName) Log.d("Repo", "加载一次") emit(result) } .flowOn(Dispatchers.IO) .catch { val init = HomeworkBean( id = 999, "未查询到", "无", deadLine = 0, finished = false, createDate = 0 ) emit(listOf(init)) } fun getNewBeanInit(courseName: String) = flow { val lastId = homeworkDao.getLastId() Log.d("Repo", "NewBean加载一次") val newId = lastId + 1 emit( HomeworkBean( id = newId, courseName = courseName, workContent = "", createDate = GetDataUtil.getDayMillis(0), deadLine = GetDataUtil.getDayMillis(7), finished = false ) ) } .catch { emit( HomeworkBean( id = 0, courseName = courseName, workContent = "", createDate = GetDataUtil.getDayMillis(0), deadLine = GetDataUtil.getDayMillis(7), finished = false ) ) } .flowOn(Dispatchers.IO) fun loadWorkCourseName() = flow { Log.d("Repo", "leadName加载一次") val result = homeworkDao.loadHasWorkCourse() emit(result) } .catch { emit(listOf()) } .flowOn(Dispatchers.IO) fun loadUnFinishCourseName() = flow { Log.d("Repo", "leadName加载一次") val result = homeworkDao.loadHasWorkCourse() val result_ = mutableListOf<String>() for (singleName in result) { val homeworkList = homeworkDao.loadHomeworkByName(singleName) homeworkList.forEach { if (!it.finished) { result_.add(it.courseName) } } } emit(result_.toList()) } .catch { emit(listOf()) } .flowOn(Dispatchers.IO) suspend fun deleteHomeworkByName(courseName: String): String { return try { homeworkDao.deleteHomeworkByName(courseName = courseName) "success" } catch (e: Exception) { "error" } } suspend fun deleteHomeworkById(id: Int): String { return try { homeworkDao.deleteHomeworkById(id) "success" } catch (e: Exception) { "error" } } fun getScheduleSettings(): Flow<Settings> { val defaultString = getDefaultString() return AccountDataDao.scheduleSettings.map { val new = it.toBuilder() if (new.coursePerHeight == 0) { new.coursePerHeight = 70 } if (new.courseNameFontSize == 0F) { new.courseNameFontSize = 13F } if (new.courseTeacherFontSize == 0F) { new.courseTeacherFontSize = 10F } if (new.courseCardAlpha == 0F) { new.courseCardAlpha = 0.75F } if (new.courseBorderAlpha == 0) { new.courseBorderAlpha = 50 } if (new.colorsList.isEmpty()) { new.addAllColors(colorListSetting(defaultString)) } if (new.courseCardRadius==0F){ new.courseCardRadius=4F } if(new.timetableIconColor==0){ new.timetableIconColor= 0xFF000000.toInt() } new.build() } } fun getScheduleSettingsColorList():Flow<List<twoColorItem>>{ return AccountDataDao.scheduleSettings.map { val new = it.toBuilder() if (new.colorsList.isEmpty()) { new.addAllColors(colorListSetting(getDefaultString())) } new.colorsList } } fun getColorListAsync(): List<twoColorItem> { val settingsList = AccountDataDao.getColorListAsyc() return if (settingsList.isEmpty()) { colorListSetting(getDefaultString()) } else { AccountDataDao.getColorListAsyc() } } private fun colorListSetting(colorList: List<List<String>>): List<twoColorItem> { val res = mutableListOf<twoColorItem>() colorList.forEach { twoColor -> val two = twoColorItem.newBuilder().apply { addAllColorItem(twoColor) }.build() res.add(two) } return res.toList() } fun colorListSettingToStringList(colorList: List<twoColorItem>):List<List<String>>{ val res = mutableListOf<List<String>>() colorList.forEach { items -> res.add(items.colorItemList) } return res.toList() } fun colorStringListToTwoItems( colorStringList: List<List<String>> = getDefaultString() ): List<twoColorItem> { return colorListSetting(colorStringList) } suspend fun updateMode(mode: Int): Int { return try { AccountDataDao.updateColorMode(mode = mode) 0 } catch (e: Exception) { 1 } } fun getShowDarkBack() = AccountDataDao.getDarkShowBack() suspend fun updateShowDarkBack(show: Boolean): Int { return try { AccountDataDao.updateDarkShowBack(show) 0 } catch (e: Exception) { 1 } } suspend fun updateSettings(setSettings: (settings: Settings) -> Settings) { AccountDataDao.updateSettings { Log.d("Repo", "SaveSettings 1") setSettings(it) } } suspend fun updateSettings(settings: Settings) { AccountDataDao.updateSettings { Log.d("Repo", "SaveSettings 1") settings } } fun loadAllCourseName() = flow { val res = courseDao.loadAllCourseName() emit(res) }.flowOn(Dispatchers.IO) suspend fun loadAllCourseNameNoFlow() = courseDao.loadAllCourseName() suspend fun unRemovedCourseToRemoved( courseList: List<String> ) { courseList.forEach { courseName -> val courseBeanList = courseDao.loadCourseByName(courseName) courseBeanList.forEach { Log.d("rep", it.toString()) it.removed = true Log.d("rep", it.toString()) } courseDao.updateCourse(courseBeanList) } } suspend fun removedCourseToUnRemoved() { val removedCourseBeanList = courseDao.loadRemovedCourse() val removedName = removedCourseBeanList.map { it.courseName }.toSet() removedCourseBeanList.forEach { it.removed = false } removedName.forEach { courseDao.deleteCourseByName(it) } courseDao.updateCourse(removedCourseBeanList) } fun getExamArrange(user: String, password: String, id: String) = flow { val res = NormalScheduleNetwork.getExamArrange(user, password, id) Log.d("RepoExam", res.toString()) emit(res) } .catch { val fail = ExamArrangeResponse( result = "查询异常", arrange_list = listOf() ) emit(fail) } .flowOn(Dispatchers.IO) fun getNewVersion(versionCode: String) = flow { val res = NormalScheduleNetwork.getNewVersion(versionCode) emit(res) }.catch { CheckUpdateResponse( status = "404", result = "链接服务器失败", force = null, newUrl = null ) } suspend fun getNewVerison2(versionCode: String) = NormalScheduleNetwork.getNewVersion(versionCode) // 只要本地没有存储公告每次打开都会请求,存储公告以后每天访问一遍公告 suspend fun getNewStartBulletin2(versionCode: Int): Bulletin2? { try{ val lastBulletin2 = startBulletinBean.getLastBulletin2() val lastId = (lastBulletin2?.id)?: 0 val lastUpdate = AccountDataDao.getLastUpdate() return if (lastBulletin2 == null ||!GetDataUtil.thisStringIsToday(lastUpdate)) { val res = NormalScheduleNetwork.getStartBulletin(lastId,versionCode) AccountDataDao.setLastUpdate(GetDataUtil.getTodayDateString()) Log.d("getNewStart", "访问一次") if (res.bulletin_list.isEmpty()) { // 如果今天没有公告就更新一次每日一句 getSentences(true).last() null } else { startBulletinBean.insertStartBulletin(res.bulletin_list) res.bulletin_list.last() } } else { Log.d("getNewStart", "today have visited") null } }catch (e:Exception){ return null } } // 研究生导入 fun loginWebVPN(user: String,password: String) = flow { val res = NormalScheduleNetwork.loginWebVPN(user, password) emit(res) } .flowOn(Dispatchers.IO) .catch { emit( GraduateWeb( cookies = "", result = "访问异常" ) ) } fun loginURP( user: String, password: String, yzm: String, cookies:String ) = flow { val res = NormalScheduleNetwork.loginURP(user, password, yzm, cookies) emit(res) } .flowOn(Dispatchers.IO) .catch { GraduateResponse( allCourse = listOf(), result = "访问异常", status = "no" ) } fun getGraduateCaptcha(cookies: String) = flow { val img = NormalScheduleNetwork.getGraduateCaptcha(cookies = cookies).bytes() val imgStream = BitmapFactory.decodeByteArray(img, 0, img.size) emit(imgStream) }.catch { emit(null) } .flowOn(Dispatchers.IO) // suspend fun getGraduateCaptcha2(cookies: String):Bitmap = withContext(Dispatchers.IO) { // val img = NormalScheduleNetwork.getGraduateCaptcha(cookies = cookies).bytes() // val imgStream = BitmapFactory.decodeByteArray(img, 0, img.size) // imgStream // } fun getScoreDetail() = AccountDataDao.getScoreDetail() fun setScoreDetail(detail: String) = AccountDataDao.updateScoreDetail(detail) private fun <T> fire(context: CoroutineContext, block: suspend () -> Result<T>) = liveData<Result<T>>(context) { val result = try { block() } catch (e: Exception) { Result.failure<T>(e) } emit(result) } private fun <T> fireFlow(context: CoroutineContext, block: suspend () -> Result<T>) = flow { val result = try { block() } catch (e: Exception) { Result.failure<T>(e) } emit(result) }.flowOn(context) fun saveAccount(user: String, password: String) = AccountDao.saveAccount(user, password) fun getSavedAccount() = AccountDao.getSavedAccount() fun isAccountSaved() = AccountDao.isAccountSaved() fun importAgain() = AccountDao.importedAgain() fun saveLogin() = AccountDao.saveLogin() // 0-未读取,1-已经显示快速跳转,3-已经显示过快速跳转,已完成重大Bug检测, 4-已完成新的新手引导 suspend fun saveUserVersion(version: Int = 1) = AccountDataDao.saveUserVersion(version) fun getNewUserOrNot() = AccountDataDao.getNewUserOrNot() fun getUserVersion() = AccountDataDao.getUserVersion() suspend fun getUserVersionS() = AccountDataDao.getUserVersionS() fun joinQQGroup(context:Context){ val key = "<KEY>" val intent = Intent() intent.data = Uri.parse("mqqopensdkapi://bizAgent/qm/qr?url=http%3A%2F%2Fqm.qq.com%2Fcgi-bin%2Fqm%2Fqr%3Ffrom%3Dapp%26p%3Dandroid%26jump_from%3Dwebapi%26k%3D$key") // 此Flag可根据具体产品需要自定义,如设置,则在加群界面按返回,返回手Q主界面,不设置,按返回会返回到呼起产品界面 // intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) try { context.startActivity(intent) } catch (e: Exception){ Toasty.error(context, "未安装QQ").show() } } private fun courseSampleData() = CourseResponse( listOf( AllCourse( "五四路", 4, 2, "11111111111111111111111", 4, "物理化学", "王老师", "第九教学楼808" ), AllCourse( "五四路", 6, 3, "11111111111111111111111", 2, "这是一个示例课程", "张老师", "九教999" ), AllCourse( "五四路", 5, 2, "11111111111111111111111", 2, "点击右上角重新导入课程", "王老师", "第九教学楼808" ), AllCourse( "五四路", 3, 3, "11111111111111111111111", 3, "这是一个示例课程", "张老师", "九教999" ), AllCourse( "五四路", 2, 2, "11111111111111111111111", 5, "点击右上角重新导入课程", "王老师", "第九教学楼808" ), AllCourse( "五四路", 2, 9, "11111111111111111111111", 2, "这是一个示例课程", "张老师", "九教999" ), AllCourse( "五四路", 1, 2, "11111111111111111111111", 1, "点击右上角重新导入课程", "王老师", "第九教学楼808" ), AllCourse( "五四路", 3, 9, "11111111111111111111111", 2, "这是一个示例课程", "张老师", "九教999" ), ), status = "yes" ) } ======================= File: app/src/main/java/com/liflymark/normalschedule/logic/model/GraduateResponse.kt ======================= <gh_stars>1-10 package com.liflymark.normalschedule.logic.model import androidx.annotation.Keep @Keep data class GraduateResponse( val allCourse: List<AllCourse>, val result: String, val status: String ) ======================= File: app/src/main/java/com/liflymark/normalschedule/logic/model/OneSentencesResponse.kt ======================= package com.liflymark.normalschedule.logic.model import androidx.annotation.Keep @Keep data class OneSentencesResponse( val result: List<Sentence>, val status: String ) @Keep data class Sentence( val author: String, val sentence: String ) ======================= File: app/src/main/java/com/liflymark/normalschedule/ui/tool_box/ToolBoxNav.kt ======================= package com.liflymark.normalschedule.ui.tool_box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.* import androidx.compose.runtime.Composable import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Modifier import androidx.navigation.NavController import androidx.navigation.NavHostController import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController import com.liflymark.normalschedule.logic.utils.RomUtil import com.liflymark.normalschedule.ui.sign_in_compose.NormalTopBar import com.liflymark.normalschedule.ui.theme.NorScTheme import kotlinx.coroutines.launch @ExperimentalMaterialApi @Composable fun ToolBoxNavGraph( modifier: Modifier = Modifier, navController: NavHostController = rememberNavController(), startDestination: String = "functionList", ){ NavHost( navController = navController, startDestination = startDestination, modifier = modifier ) { composable("functionList"){ FunctionList(navController = navController) } composable("devBoard"){ DevBoard(navController = navController) } composable("busTime"){ SchoolBusAll(navController = navController) } composable("schoolCalendar"){ HbuCalendar(navController = navController) } composable("question"){ QuestionAllPage(navController = navController) } composable("wait"){ WaitTime(navController = navController) } } } @Composable fun FunctionList(navController: NavController){ NorScTheme { val scope = rememberCoroutineScope() Column(modifier = Modifier .fillMaxSize() .verticalScroll(rememberScrollState())) { NormalTopBar(label = "工具箱") SinglePart( titleIcon = Icons.Default.Message, titleName = "开发者公告" ) { SingleButton(Icons.Filled.StickyNote2, "公告栏"){ navController.navigate("devBoard") } SingleButton(Icons.Filled.HelpCenter, "常见问题"){ navController.navigate("question") } } SinglePart( titleIcon = Icons.Default.EmojiSymbols, titleName = "校内生活" ) { if(!RomUtil.isVivo) { SingleButton(Icons.Filled.CalendarToday, "校历") { navController.navigate("schoolCalendar") } } SingleButton(Icons.Filled.DirectionsBus, "校车时刻表") { navController.navigate("busTime") } // SingleButton(Icons.Filled.LunchDining, "作息时刻表") { // navController.navigate("wait") // } } // SinglePart( // titleIcon = Icons.Default.Fastfood, // titleName = "吃喝玩乐" // ) { // SingleButton(Icons.Filled.ShoppingBag, "购物指南") { // navController.navigate("wait") // } // SingleButton(Icons.Filled.FoodBank, "美食指南") { // navController.navigate("wait") // } // } } } } ======================= File: app/src/main/java/com/liflymark/normalschedule/ui/app_widget_day/DayRemoteViewsService.kt ======================= package com.liflymark.normalschedule.ui.app_widget_day import android.content.Context import android.content.Intent import android.widget.RemoteViewsService class DayRemoteViewsService: RemoteViewsService() { override fun onGetViewFactory(intent: Intent): RemoteViewsFactory { return DayRemoteViewsFactory(this.applicationContext, intent) } } ======================= File: app/src/main/java/com/liflymark/normalschedule/ui/import_again/ImportCourseAgain.kt ======================= package com.liflymark.normalschedule.ui.import_again import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import com.liflymark.normalschedule.R import com.liflymark.normalschedule.logic.Repository import kotlinx.coroutines.CoroutineScope class ImportCourseAgain : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } override fun finish() { Repository.saveLogin() super.finish() } } ======================= File: app/src/main/java/com/liflymark/normalschedule/logic/network/ServiceCreator.kt ======================= package com.liflymark.normalschedule.logic.network import android.util.Log import okhttp3.OkHttpClient import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.TimeUnit object ServiceCreator { private const val BASE_URL = "https://liflymark.top/" private val okHttpClient: OkHttpClient = OkHttpClient.Builder() .connectTimeout(10, TimeUnit.SECONDS) .readTimeout(10, TimeUnit.SECONDS) .writeTimeout(10, TimeUnit.SECONDS) .build() fun cancelAll(){ okHttpClient.dispatcher.cancelAll() Log.d("Service", okHttpClient.dispatcher.maxRequests.toString()) Log.d("Service", okHttpClient.dispatcher.maxRequestsPerHost.toString()) } private val retrofit = Retrofit.Builder() .baseUrl(BASE_URL) //.addConverterFactory(ScalarsConverterFactory.create()) .client(okHttpClient) .addConverterFactory(GsonConverterFactory.create()) //.addCallAdapterFactory() .build() fun <T>create(serviceClass: Class<T>) : T = retrofit.create(serviceClass) inline fun <reified T> create(): T = create(T::class.java) } ======================= File: app/src/main/java/com/liflymark/normalschedule/ui/add_course/AddCourseComposeActivity.kt ======================= <reponame>sasaju/NormalSchedule package com.liflymark.normalschedule.ui.add_course import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.material.Scaffold import com.google.accompanist.pager.ExperimentalPagerApi import com.liflymark.normalschedule.ui.score_detail.UiControl import com.liflymark.normalschedule.ui.sign_in_compose.NormalTopBar import com.liflymark.normalschedule.ui.theme.NorScTheme class AddCourseComposeActivity : ComponentActivity() { @OptIn(ExperimentalPagerApi::class, ExperimentalMaterialApi::class) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { NorScTheme { // A surface container using the 'background' color from the theme UiControl() Scaffold( topBar = { NormalTopBar(label = "添加课程") }, content = { ShowAllCourseToEdit(courseName = "") } ) } } } } //@Preview(showBackground = true) //@Composable //fun DefaultPreview3() { // NormalScheduleTheme { // Greeting("Android") // } //} ======================= File: app/src/main/java/com/liflymark/normalschedule/ui/show_timetable/DrawerSideUI.kt ======================= package com.liflymark.normalschedule.ui.show_timetable import android.content.Intent import androidx.activity.ComponentActivity import androidx.appcompat.app.AppCompatActivity import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.ExperimentalAnimationApi import androidx.compose.foundation.* import androidx.compose.foundation.layout.* import androidx.compose.material.DrawerState import androidx.compose.material.Icon import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.* import androidx.compose.runtime.* import androidx.compose.runtime.livedata.observeAsState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.lifecycle.viewmodel.compose.viewModel import com.google.accompanist.insets.statusBarsHeight import com.liflymark.normalschedule.logic.utils.RomUtil import com.liflymark.normalschedule.ui.about.ComposeAboutActivity import com.liflymark.normalschedule.ui.class_course.ClassCourseActivity import com.liflymark.normalschedule.ui.exam_arrange.ExamActivity import com.liflymark.normalschedule.ui.import_show_score.ImportScoreActivity import com.liflymark.normalschedule.ui.login_space_room.LoginSpaceActivity import com.liflymark.normalschedule.ui.score_detail.LoginToScoreActivity import com.liflymark.normalschedule.ui.set_background.SetBackground import com.liflymark.normalschedule.ui.settings.SettingsActivity import com.liflymark.normalschedule.ui.theme.NorScTheme import com.liflymark.normalschedule.ui.tool_box.ToolBoxActivity import com.liflymark.normalschedule.ui.work_book.WorkBookActivity import es.dmoral.toasty.Toasty import kotlinx.coroutines.launch @ExperimentalAnimationApi @Composable fun DrawerNavHost(drawerState: DrawerState){ Column(modifier = Modifier.verticalScroll(rememberScrollState())) { OneSentence() NavButton(SetBackground(), drawerState, Icons.Filled.Wallpaper, "更换背景") NavButton(WorkBookActivity(), drawerState, Icons.Filled.MenuBook, "作业本") Spacer(modifier = Modifier .fillMaxWidth() .height(5.dp) .padding(2.dp) .background(Color.Gray)) NavButton(activity = ImportScoreActivity(), drawerState = drawerState, icon = Icons.Filled.Stairs, text = "成绩查询") NavButton(activity = LoginToScoreActivity(), drawerState = drawerState, icon = Icons.Filled.TrendingUp, text = "本学期成绩明细") NavButton(activity = LoginSpaceActivity(), drawerState = drawerState, icon = Icons.Filled.EventSeat, text = "空教室查询") // NavButton( // activity = UpdateCourseActivity(), drawerState = drawerState, // icon = Icons.Filled.Rule, text = "公共调课" // ) NavButton( activity = ExamActivity(), drawerState = drawerState, icon = Icons.Filled.Rule, text = "考试安排" ) Spacer(modifier = Modifier .fillMaxWidth() .height(5.dp) .padding(2.dp) .background(Color.Gray)) NavButton(activity = ClassCourseActivity(), drawerState = drawerState, icon = Icons.Filled.Margin, text = "班级课程查询") NavButton( activity = ToolBoxActivity(), drawerState = drawerState, icon = Icons.Filled.WorkOutline, text = if(RomUtil.isVivo){"工具箱"}else{"河大工具箱"} ) Spacer(modifier = Modifier .fillMaxWidth() .height(5.dp) .padding(2.dp) .background(Color.Gray)) NavButton( activity = SettingsActivity(), drawerState = drawerState, icon = Icons.Filled.Settings, text = "设置" ) NavButton(activity = ComposeAboutActivity(), drawerState = drawerState, icon = Icons.Filled.Info, text = "关于软件") } } @ExperimentalAnimationApi @Composable fun OneSentence(viewModel:ShowTimetableViewModel = viewModel()){ val sentencesList= viewModel.sentenceLiveData.observeAsState() val context = LocalContext.current val status = sentencesList.value?.status val result = sentencesList.value?.result var expand by remember { mutableStateOf(false) } var clickTimes by remember { mutableStateOf(0) } Box( Modifier .clickable { expand =!expand clickTimes += 1 if (clickTimes > 3) { viewModel.fetchSentence(force = true) Toasty .success(context, "已从网络端重新加载") .show() clickTimes = 0 } } .wrapContentHeight(), contentAlignment = Alignment.Center ) { Spacer(modifier = Modifier .fillMaxWidth() .statusBarsHeight(200.dp) .background( brush = Brush.verticalGradient( listOf(Color(0xff2196f3), MaterialTheme.colors.background) ) ) ) Column( modifier = Modifier.fillMaxWidth(0.9f), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally) { Text(text = "『",fontSize = 14.sp, modifier = Modifier .fillMaxWidth() .padding(5.dp), textAlign = TextAlign.Start) Text( text = "${result?.get(0)?.sentence}", maxLines = 4, fontSize = 17.5.sp, modifier = Modifier .fillMaxWidth() .padding(10.dp) ) Text(text = "』", fontSize = 14.sp, modifier = Modifier .fillMaxWidth() .padding(5.dp), textAlign = TextAlign.End) AnimatedVisibility(visible = expand) { Text(text = "————${result?.get(0)?.author}", fontSize = 15.sp, textAlign = TextAlign.End, modifier = Modifier .fillMaxWidth() .padding(10.dp)) } } } } @Composable fun NavButton( activity: AppCompatActivity, drawerState: DrawerState, icon:ImageVector, text: String ){ val context = LocalContext.current val scope = rememberCoroutineScope() Row(modifier = Modifier .fillMaxWidth() .horizontalScroll(rememberScrollState()) .padding(2.dp) .clickable { val intent = Intent(context, activity::class.java) context.startActivity(intent) scope.launch { drawerState.close() } },verticalAlignment = Alignment.CenterVertically ) { Spacer(modifier = Modifier.width(10.dp)) Icon(icon, null,modifier = Modifier.height(50.dp)) Text(text = " $text", fontSize = 18.sp,) } } @Composable fun NavButton( activity: ComponentActivity, drawerState: DrawerState, icon:ImageVector, text: String, ){ val context = LocalContext.current val scope = rememberCoroutineScope() Row(modifier = Modifier .fillMaxWidth() .horizontalScroll(rememberScrollState()) .padding(2.dp) .clickable { val intent = Intent(context, activity::class.java) context.startActivity(intent) scope.launch { drawerState.close() } },verticalAlignment = Alignment.CenterVertically ) { Spacer(modifier = Modifier.width(10.dp)) Icon(icon, null,modifier = Modifier.height(50.dp)) Text(text = " $text", fontSize = 18.sp,) } } @Preview(showBackground = true) @Composable fun Test(){ NorScTheme { Spacer( modifier = Modifier .fillMaxWidth() .height(200.dp) .background(Color.DarkGray) ) Text(text = "adfasdfasdf") } } ======================= File: app/src/main/java/com/liflymark/normalschedule/logic/model/DepartmentList.kt ======================= <gh_stars>1-10 package com.liflymark.normalschedule.logic.model import androidx.annotation.Keep @Keep data class DepartmentList( val status: String, val structure: List<Structure> ) @Keep data class Structure( val department: String, val majorList: List<String> ) ======================= File: app/src/main/java/com/liflymark/normalschedule/ui/settings/CourseCardSetting.kt ======================= <reponame>sasaju/NormalSchedule<filename>app/src/main/java/com/liflymark/normalschedule/ui/settings/CourseCardSetting.kt<gh_stars>1-10 package com.liflymark.normalschedule.ui.settings import android.util.Log import androidx.activity.OnBackPressedCallback import androidx.activity.compose.LocalOnBackPressedDispatcherOwner import androidx.compose.foundation.* import androidx.compose.foundation.layout.* import androidx.compose.material.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.* import androidx.compose.runtime.* import androidx.compose.runtime.livedata.observeAsState import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.* import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.compose.ui.window.DialogProperties import androidx.compose.ui.zIndex import androidx.navigation.NavController import coil.annotation.ExperimentalCoilApi import coil.compose.LocalImageLoader import coil.compose.rememberAsyncImagePainter import coil.compose.rememberImagePainter import coil.request.ImageRequest import com.godaddy.android.colorpicker.ClassicColorPicker import com.godaddy.android.colorpicker.HsvColor import com.godaddy.android.colorpicker.toColorInt import com.liflymark.normalschedule.R import com.liflymark.normalschedule.logic.Repository import com.liflymark.normalschedule.logic.bean.CourseBean import com.liflymark.normalschedule.logic.bean.OneByOneCourseBean import com.liflymark.normalschedule.logic.utils.Convert.color import com.liflymark.normalschedule.logic.utils.CornerDialog import com.liflymark.normalschedule.logic.utils.GifLoader import com.liflymark.normalschedule.ui.show_timetable.SingleClass2 import com.liflymark.normalschedule.ui.show_timetable.getEndTime import com.liflymark.normalschedule.ui.show_timetable.getStartTime import com.liflymark.normalschedule.ui.sign_in_compose.NormalTopBar import com.liflymark.normalschedule.ui.theme.NorScTheme import com.liflymark.schedule.data.Settings import es.dmoral.toasty.Toasty import kotlinx.coroutines.launch import kotlin.math.roundToInt import kotlin.math.roundToLong import kotlin.reflect.KMutableProperty1 @Composable fun SettingsCardPage( navController: NavController ){ var newSettings by remember{ mutableStateOf<Settings?>(null) } val scope = rememberCoroutineScope() val context = LocalContext.current var showCloseDialog by rememberSaveable { mutableStateOf(false) } // 拦截返回键 val backDispatcher = LocalOnBackPressedDispatcherOwner.current!!.onBackPressedDispatcher val backCallback = remember { object : OnBackPressedCallback(!showCloseDialog) { override fun handleOnBackPressed() { showCloseDialog =!showCloseDialog } } } // LaunchedEffect(showCloseDialog){ // backCallback.isEnabled =!showCloseDialog // } DisposableEffect(backDispatcher) { // Add callback to the backDispatcher backDispatcher.addCallback(backCallback) // When the effect leaves the Composition, remove the callback onDispose { backCallback.remove() } } if (showCloseDialog){ AlertDialog( onDismissRequest = { showCloseDialog=false }, title = { Text(text = "您还没有保存您的修改")}, text = { Text(text = "是否保存您的修改")}, confirmButton = { TextButton(onClick = { if (newSettings!=null){ scope.launch { Repository.updateSettings(newSettings!!) Toasty.success(context, "保存成功").show() showCloseDialog = false navController.navigateUp() } } }) { Text(text = "保存并退出") } }, dismissButton = { TextButton(onClick = { showCloseDialog = false navController.navigateUp() }) { Text(text = " 直接退出") } } ) } Scaffold( topBar = { NormalTopBar(label = "配置课程格子") { showCloseDialog = true } }, floatingActionButton = { ExtendedFloatingActionButton( text = { Text(text = "保存修改") }, onClick = { if (newSettings!=null){ scope.launch { Repository.updateSettings(newSettings!!) Toasty.success(context, "保存成功").show() navController.navigateUp() } } }, icon = {Icon(Icons.Default.Save,"Save")} ) }, content = { SettingsPreviewAndControl(onValueChange = { newSettings = it }) } ) } @Composable fun SettingsPreviewAndControl( onValueChange: (settings: Settings) -> Unit ){ val settings = Repository.getScheduleSettings().collectAsState(initial = null) BackgroundImage() settings.value?.let { nowSetting -> var newSettings by remember { mutableStateOf(nowSetting) } LaunchedEffect(newSettings){ onValueChange(newSettings) } Row( modifier = Modifier .fillMaxSize() .background(Color.Transparent) ) { ShowPreView( settings =newSettings, modifier = Modifier .weight(1.6f) .background(Color.Transparent) ) Box( modifier = Modifier .weight(6f) .fillMaxHeight() .background(MaterialTheme.colors.background) ){ SetCardControl( settings = newSettings, onValueChange ={ newSettings = it }, onValueChangeFinish = { newSettings = it } ) } } } } @Composable fun SetCardControl( modifier: Modifier = Modifier, settings: Settings, onValueChange: (settings: Settings) -> Unit, onValueChangeFinish: (settings: Settings) -> Unit ) { var settingsState by remember { mutableStateOf(settings) } var showColorPicker by rememberSaveable { mutableStateOf(false) } Column( modifier = modifier.verticalScroll(rememberScrollState()), horizontalAlignment = Alignment.CenterHorizontally ) { Spacer(modifier = Modifier.height(5.dp)) OutlinedButton(onClick = { val newSettingsBuilder = settingsState.toBuilder() newSettingsBuilder.apply { coursePerHeight = 70 courseNameFontSize = 13F courseCardAlpha = 0.75F courseBorderSize = 0F courseBorderAlpha = 50 courseCardRadius = 4F timetableIconColor = 0xFF000000.toInt() } settingsState = newSettingsBuilder.build() onValueChange(newSettingsBuilder.build()) onValueChangeFinish(newSettingsBuilder.build()) }) { Text(text = "全部恢复默认") } // 课程格子高度 SettingSliderItem( value = settingsState.coursePerHeight.toFloat(), startClick = { val newSettings = settingsState .toBuilder() .setCoursePerHeight(settingsState.coursePerHeight - 1) .build() settingsState = newSettings onValueChange(newSettings) }, endClick = { val newSettings = settingsState .toBuilder() .setCoursePerHeight(settingsState.coursePerHeight + 1) .build() settingsState = newSettings onValueChange(newSettings) }, onValueChange = { val newSettings = settingsState .toBuilder() .setCoursePerHeight(it.toInt()) .build() settingsState = newSettings onValueChange(newSettings) }, onValueChangeFinish = { onValueChangeFinish(settingsState) }, contentTitle = "课程格子高度", contentDescription = "当前${settingsState.coursePerHeight}dp, 默认:70dp", valueRange = 50F..150F ) // 课程格子字体大小 SettingSliderItem( value = settingsState.courseNameFontSize, startClick = { val newSettings = settingsState .toBuilder() .setCourseNameFontSize(settingsState.courseNameFontSize.roundToInt() - 1F) .build() settingsState = newSettings onValueChange(newSettings) }, endClick = { val newSettings = settingsState .toBuilder() .setCourseNameFontSize(settingsState.courseNameFontSize.roundToInt() + 1F) .build() settingsState = newSettings onValueChange(newSettings) }, onValueChange = { val newSettings = settingsState .toBuilder() .setCourseNameFontSize(it) .build() settingsState = newSettings onValueChange(newSettings) }, onValueChangeFinish = { onValueChangeFinish(settingsState) }, contentTitle = "课程名称大小", contentDescription = "当前${(settingsState.courseNameFontSize * 100).roundToInt()/100.0}sp, 默认:13sp", valueRange = 10F..30F ) // 课程格子透明度 SettingSliderItem( valueRange = 0F..1F, value = settingsState.courseCardAlpha, startClick = { val newSettings = settingsState .toBuilder() .setCourseCardAlpha(settingsState.courseCardAlpha - 0.01F) .build() settingsState = newSettings onValueChange(newSettings) }, endClick = { val newSettings = settingsState .toBuilder() .setCourseCardAlpha(settingsState.courseCardAlpha + 0.01F) .build() settingsState = newSettings onValueChange(newSettings) }, onValueChange = { val newSettings = settingsState .toBuilder() .setCourseCardAlpha(it) .build() settingsState = newSettings onValueChange(newSettings) }, onValueChangeFinish = { onValueChangeFinish(settingsState) }, contentTitle = "课程格子透明度", contentDescription = "当前${(settingsState.courseCardAlpha * 100).roundToInt()/100.0}, 默认:0.75", ) // 课程格子边框宽度 SettingSliderItem( valueRange = 0F..5F, value = settingsState.courseBorderSize, startClick = { val newSettings = settingsState .toBuilder() .setCourseBorderSize(settingsState.courseBorderSize - 0.01F) .build() settingsState = newSettings onValueChange(newSettings) }, endClick = { val newSettings = settingsState .toBuilder() .setCourseBorderSize(settingsState.courseBorderSize + 0.01F) .build() settingsState = newSettings onValueChange(newSettings) }, onValueChange = { val newSettings = settingsState .toBuilder() .setCourseBorderSize(it) .build() settingsState = newSettings onValueChange(newSettings) }, onValueChangeFinish = { onValueChangeFinish(settingsState) }, contentTitle = "边框宽度", contentDescription = "当前${(settingsState.courseBorderSize * 100).roundToInt()/100.0}dp, 默认:0dp", ) // 课程边框透明度 SettingSliderItem( valueRange = 0F..100F, value = settingsState.courseBorderAlpha.toFloat(), startClick = { val newSettings = settingsState .toBuilder() .setCourseBorderAlpha(settingsState.courseBorderAlpha - 1) .build() settingsState = newSettings onValueChange(newSettings) }, endClick = { val newSettings = settingsState .toBuilder() .setCourseBorderAlpha(settingsState.courseBorderAlpha + 1) .build() settingsState = newSettings onValueChange(newSettings) }, onValueChange = { val newSettings = settingsState .toBuilder() .setCourseBorderAlpha(it.toInt()) .build() settingsState = newSettings onValueChange(newSettings) }, onValueChangeFinish = { onValueChangeFinish(settingsState) }, contentTitle = "边框透明度", contentDescription = "当前${settingsState.courseBorderAlpha}%, 默认:50%", ) // 课程边框圆角 SettingSliderItem( valueRange = 0F..20F, value = settingsState.courseCardRadius, startClick = { val newSettings = settingsState .toBuilder() .setCourseCardRadius(settingsState.courseCardRadius - 0.1F) .build() settingsState = newSettings onValueChange(newSettings) }, endClick = { val newSettings = settingsState .toBuilder() .setCourseCardRadius(settingsState.courseCardRadius + 0.1F) .build() settingsState = newSettings onValueChange(newSettings) }, onValueChange = { val newSettings = settingsState .toBuilder() .setCourseCardRadius(it) .build() settingsState = newSettings onValueChange(newSettings) }, onValueChangeFinish = { onValueChangeFinish(settingsState) }, contentTitle = "课程格子圆角大小", contentDescription = "当前${(settingsState.courseCardRadius*100).roundToInt()/100.0}dp, 默认:4dp", ) Column( modifier = Modifier .fillMaxWidth() .height(90.dp) .clickable { showColorPicker = true } .padding(horizontal = 10.dp, vertical = 5.dp) , verticalArrangement = Arrangement.SpaceAround, ) { Text(text = "配置时间表文字颜色",style = MaterialTheme.typography.subtitle2) Spacer(modifier = Modifier.height(10.dp)) Spacer( modifier = Modifier .width(40.dp) .height(20.dp) .background(Color(settingsState.timetableIconColor)) ) } Spacer( modifier = Modifier .height(1.dp) .background(MaterialTheme.colors.secondary) .fillMaxWidth() ) } if(showColorPicker){ ColorPickerDialog( initColor = Color(settings.timetableIconColor), onDismissRequest = { showColorPicker = false }, onRes = { val newSettings = settingsState .toBuilder() .setTimetableIconColor(it.toColorInt()) .build() settingsState = newSettings onValueChange(newSettings) showColorPicker = false } ) Color.Black } } /** * 颜色选择Dialog */ @Composable fun ColorPickerDialog( initColor: Color=Color.Black, onDismissRequest: () -> Unit, onRes:(hsv:HsvColor) -> Unit ){ val hsv = rememberSaveable(stateSaver = HsvColor.Saver) { mutableStateOf(HsvColor.from(initColor)) } CornerDialog( onDismissRequest = { onDismissRequest() }, properties = DialogProperties(dismissOnClickOutside = false, dismissOnBackPress = true) ) { Column( horizontalAlignment = Alignment.CenterHorizontally ){ ClassicColorPicker( color = initColor, onColorChanged = { hsv.value = it }, modifier = Modifier .fillMaxWidth() .height(240.dp) .padding(10.dp) ) Spacer( modifier = Modifier .width(40.dp) .height(20.dp) .background(hsv.value.toColor()) ) Spacer(modifier = Modifier.height(10.dp)) Row( modifier = Modifier.fillMaxWidth() ) { TextButton( onClick = { onDismissRequest() }, modifier = Modifier.weight(1F) ) { Text("取消") } TextButton( onClick = { onRes(hsv.value) }, modifier = Modifier.weight(1F) ) { Text("确定") } } } } } /** * 单个配置项 */ @Composable fun SettingSliderItem( value: Float, valueRange: ClosedFloatingPointRange<Float> = 0f..1f, enabled: Boolean = true, steps: Int = 0, startIcon: ImageVector = Icons.Default.Remove, endIcon: ImageVector = Icons.Default.Add, startClick: () -> Unit, endClick: () -> Unit, onValueChange: (value: Float) -> Unit, onValueChangeFinish: () -> Unit, contentTitle: String, contentDescription: String, ) { Column { TextSlider( modifier = Modifier, value = value, startIcon = startIcon, endIcon = endIcon, startClick = { startClick() }, endClick = { endClick() }, onValueChange = { onValueChange(it) }, onValueChangeFinish = { onValueChangeFinish() }, valueRange = valueRange, enabled = enabled, steps = steps, contentTitle = contentTitle, contentDescription = contentDescription ) Spacer( modifier = Modifier .height(1.dp) .background(MaterialTheme.colors.secondary) .fillMaxWidth() ) } } /** * 一个带有文字说明的Slider */ @Composable fun TextSlider( modifier: Modifier, value: Float, valueRange: ClosedFloatingPointRange<Float> = 0f..1f, enabled: Boolean = true, steps: Int = 0, startIcon: ImageVector = Icons.Default.Remove, endIcon: ImageVector = Icons.Default.Add, startClick: () -> Unit, endClick: () -> Unit, onValueChange: (value: Float) -> Unit, onValueChangeFinish: () -> Unit, contentTitle: String, contentDescription: String, ) { Column( modifier = Modifier.padding(5.dp) ) { Row(verticalAlignment = Alignment.Bottom) { Spacer(modifier = Modifier.width(10.dp)) Text(text = contentTitle, style = MaterialTheme.typography.subtitle2) Spacer(modifier = Modifier.width(10.dp)) Text( text = contentDescription, style = MaterialTheme.typography.body2, color = MaterialTheme.colors.onSecondary ) } IconSlider( modifier = modifier, value = value, startIcon = startIcon, endIcon = endIcon, startClick = { startClick() }, endClick = { endClick() }, onValueChange = { onValueChange(it) }, onValueChangeFinish = { onValueChangeFinish() }, valueRange = valueRange, enabled = enabled, steps = steps ) } } /** * 一个带有左右图标的Slider封装 */ @Composable fun IconSlider( modifier: Modifier, value: Float, valueRange: ClosedFloatingPointRange<Float> = 0f..1f, enabled: Boolean = true, steps: Int = 0, startIcon: ImageVector = Icons.Default.Remove, endIcon: ImageVector = Icons.Default.Add, startClick: () -> Unit, endClick: () -> Unit, onValueChange: (value: Float) -> Unit, onValueChangeFinish: () -> Unit ) { Row( modifier = modifier, ) { IconButton(onClick = { startClick() }) { Icon(startIcon, "减少") } Spacer(modifier = Modifier.width(10.dp)) Slider( value = value, onValueChange = { onValueChange(it) }, onValueChangeFinished = { onValueChangeFinish() }, steps = steps, valueRange = valueRange, enabled = enabled, modifier = Modifier.weight(1f) ) Spacer(modifier = Modifier.width(10.dp)) IconButton(onClick = { endClick() }) { Icon(endIcon, "增加") } } } @OptIn(ExperimentalCoilApi::class) @Composable fun ShowPreView( modifier: Modifier = Modifier, settings: Settings ) { val iconColor = Color(settings.timetableIconColor) Row( modifier = modifier.verticalScroll(rememberScrollState()) ) { Column(modifier = Modifier.weight(0.6f)) { Spacer(modifier = Modifier.height(40.dp)) // 时间列 repeat(11) { Text( buildAnnotatedString { withStyle(style = ParagraphStyle(lineHeight = 6.sp)) { withStyle( style = SpanStyle( fontSize = 18.sp, fontWeight = FontWeight.Bold, color = iconColor ) ) { append("\n\n${it + 1}") } } withStyle(style = SpanStyle(fontSize = 10.sp, color = iconColor)) { append("${getStartTime(it + 1)}\n") append(getEndTime(it + 1)) } }, modifier = Modifier .fillMaxWidth() .height(settings.coursePerHeight.dp), textAlign = TextAlign.Center, ) } } Column( Modifier.weight(1f) ) { Spacer(modifier = Modifier.height(40.dp)) SingleClass2( singleClass = OneByOneCourseBean("药物化学\n第九教学楼888\n张三", 1, 2, 1, Color(0xff12c2e9)), courseClick = {}, settings = settings, loadWork = false, ) Spacer(modifier = Modifier.height((settings.coursePerHeight * 2).dp)) SingleClass2( singleClass = OneByOneCourseBean( "大学生职业规划\n第八教学楼666\n张三", 1, 2, 1, Color(0xfff64f59), listOf("#ffffbb33", "#ff24C6DC", "#ff514A9D").map{ it.color } ), courseClick = {}, settings = settings, loadWork = false, ) } } } @OptIn(ExperimentalCoilApi::class) @Composable fun BackgroundImage() { val showDarkBack = Repository.getShowDarkBack().collectAsState(initial = false) val path = Repository.loadBackground().observeAsState() val context = LocalContext.current if (!isSystemInDarkTheme() || showDarkBack.value) { CompositionLocalProvider(LocalImageLoader provides GifLoader(context)) { Image( painter = rememberAsyncImagePainter( ImageRequest.Builder(LocalContext.current) .data(data = path.value?:R.drawable.main_background_4) .apply( block = fun ImageRequest.Builder.() { error(R.drawable.main_background_4) } ).build() ), contentDescription = null, modifier = Modifier.fillMaxSize(), contentScale = ContentScale.Crop ) } } else { Image( painter = rememberAsyncImagePainter(model = ""), contentDescription = null, modifier = Modifier .background(Color(1, 86, 127)) .fillMaxSize() ) } } @Composable @Preview(showBackground = true, showSystemUi = true) fun CardSetPreview() { NorScTheme { // BackgroundImage() // Row( // modifier = Modifier // .fillMaxSize() // .background(Color.Transparent) // ) { // ShowPreView(settings = Settings.getDefaultInstance(), modifier = Modifier // .weight(1.6f) // .background(Color.Transparent)) // Box(modifier = Modifier // .weight(6f) // .fillMaxHeight() // .background(Color.DarkGray)) // } SettingsPreviewAndControl({}) } } ======================= File: app/src/main/java/com/liflymark/normalschedule/logic/utils/NumberPicker.kt ======================= package com.liflymark.normalschedule.logic.utils import android.content.Intent import android.graphics.Bitmap import android.net.Uri import android.webkit.* import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.width import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.snapshotFlow import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.compose.ui.viewinterop.AndroidView import com.google.accompanist.pager.ExperimentalPagerApi import com.google.accompanist.pager.PagerState import com.google.accompanist.pager.VerticalPager import kotlinx.coroutines.flow.collect import android.util.Log import androidx.compose.animation.* import androidx.compose.animation.core.* import androidx.compose.foundation.background import androidx.compose.foundation.gestures.Orientation import androidx.compose.foundation.gestures.detectTapGestures import androidx.compose.foundation.gestures.draggable import androidx.compose.foundation.gestures.rememberDraggableState import androidx.compose.foundation.layout.* import androidx.compose.material.* import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.draw.alpha import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.layout.Layout import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.IntOffset import com.liflymark.normalschedule.ui.theme.NorScTheme import kotlinx.coroutines.launch import kotlin.math.abs import kotlin.math.roundToInt @Composable fun StringPicker2( modifier: Modifier = Modifier, strList: List<String>, label: (Int) -> String = { strList.getOrNull(it)?:"" }, value: Int, onValueChange: (Int) -> Unit, dividersColor: Color = MaterialTheme.colors.primary, textStyle: TextStyle = LocalTextStyle.current, ){ NumberPicker( modifier = modifier, label = label, value = value, onValueChange = { onValueChange(it) }, dividersColor = dividersColor, range = strList.indices, textStyle = textStyle ) } fun getIndexForOffset(range: Iterable<Int>, value: Int, offset: Float, halfNumbersColumnHeightPx: Float): Int { val indexOf = range.indexOf(value) + range.first() - (offset / halfNumbersColumnHeightPx).toInt() return when (val indexInRange = range.indexOf(indexOf)) { -1 -> indexOf else -> indexInRange }.let { minOf(it, range.count() - 1) }.let { maxOf(0, it) } } @Composable fun NumberPicker( modifier: Modifier = Modifier, label: (Int) -> String = { it.toString() }, value: Int, onValueChange: (Int) -> Unit, dividersColor: Color = MaterialTheme.colors.primary, range: Iterable<Int>, textStyle: TextStyle = LocalTextStyle.current, ) { val minimumAlpha = 0.3f val verticalMargin = 8.dp val numbersColumnHeight = 80.dp val halfNumbersColumnHeight = numbersColumnHeight / 2 val halfNumbersColumnHeightPx = with(LocalDensity.current) { halfNumbersColumnHeight.toPx() } val coroutineScope = rememberCoroutineScope() val animatedOffset = remember { Animatable(0f) } .apply { val offsetRange = remember(value, range) { -((range.count() - 1) - range.indexOf(value)) * halfNumbersColumnHeightPx to value * halfNumbersColumnHeightPx } updateBounds(offsetRange.first, offsetRange.second) } val coercedAnimatedOffset = animatedOffset.value % halfNumbersColumnHeightPx val indexOfElement = getIndexForOffset(range, value, animatedOffset.value, halfNumbersColumnHeightPx) var dividersWidth by remember { mutableStateOf(0.dp) } Layout( modifier = modifier .draggable( orientation = Orientation.Vertical, state = rememberDraggableState { deltaY -> coroutineScope.launch { animatedOffset.snapTo(animatedOffset.value + deltaY) } }, onDragStopped = { velocity -> coroutineScope.launch { val endValue = animatedOffset.fling( initialVelocity = velocity, animationSpec = exponentialDecay(frictionMultiplier = 20f), adjustTarget = { target -> val coercedTarget = target % halfNumbersColumnHeightPx val coercedAnchors = listOf( -halfNumbersColumnHeightPx, 0f, halfNumbersColumnHeightPx ) val coercedPoint = coercedAnchors.minByOrNull { kotlin.math.abs(it - coercedTarget) }!! val base = halfNumbersColumnHeightPx * (target / halfNumbersColumnHeightPx).toInt() coercedPoint + base } ).endState.value val result = range.elementAt( getIndexForOffset( range, value, endValue, halfNumbersColumnHeightPx ) ) onValueChange(result) // animatedOffset.snapTo(0f) } } ) .padding(vertical = numbersColumnHeight / 3 + verticalMargin * 2), content = { Box( Modifier .width(dividersWidth) .height(2.dp) .background(color = dividersColor) ) Box( modifier = Modifier .padding(vertical = verticalMargin, horizontal = 20.dp) .offset { IntOffset(x = 0, y = coercedAnimatedOffset.roundToInt()) } ) { val baseLabelModifier = Modifier.align(Alignment.Center) ProvideTextStyle(textStyle) { if (indexOfElement > 0) Label( text = label(range.elementAt(indexOfElement - 1)), modifier = baseLabelModifier .offset(y = -halfNumbersColumnHeight) .alpha( maxOf( minimumAlpha, coercedAnimatedOffset / halfNumbersColumnHeightPx ) ) ) Label( text = label(range.elementAt(indexOfElement)), modifier = baseLabelModifier .alpha((maxOf(minimumAlpha, 1 - kotlin.math.abs(coercedAnimatedOffset) / halfNumbersColumnHeightPx))) ) if (indexOfElement < range.count() - 1) Label( text = label(range.elementAt(indexOfElement + 1)), modifier = baseLabelModifier .offset(y = halfNumbersColumnHeight) .alpha( maxOf( minimumAlpha, -coercedAnimatedOffset / halfNumbersColumnHeightPx ) ) ) } } Box( Modifier .width(dividersWidth) .height(2.dp) .background(color = dividersColor) ) } ) { measurables, constraints -> // Don't constrain child views further, measure them with given constraints // List of measured children val placeables = measurables.map { measurable -> // Measure each children measurable.measure(constraints) } dividersWidth = placeables .drop(1) .first() .width .toDp() // Set the size of the layout as big as it can layout(dividersWidth.toPx().toInt(), placeables .sumOf { it.height } ) { // Track the y co-ord we have placed children up to var yPosition = 0 // Place children in the parent layout placeables.forEach { placeable -> // Position item on the screen placeable.placeRelative(x = 0, y = yPosition) // Record the y co-ord placed up to yPosition += placeable.height } } } } @Composable private fun Label(text: String, modifier: Modifier) { Text( modifier = modifier.pointerInput(Unit) { detectTapGestures(onLongPress = { // FIXME: Empty to disable text selection }) }, text = text, textAlign = TextAlign.Center, ) } private suspend fun Animatable<Float, AnimationVector1D>.fling( initialVelocity: Float, animationSpec: DecayAnimationSpec<Float>, adjustTarget: ((Float) -> Float)?, block: (Animatable<Float, AnimationVector1D>.() -> Unit)? = null, ): AnimationResult<Float, AnimationVector1D> { val targetValue = animationSpec.calculateTargetValue(value, initialVelocity) val adjustedTarget = adjustTarget?.invoke(targetValue) return if (adjustedTarget!= null) { animateTo( targetValue = adjustedTarget, initialVelocity = initialVelocity, block = block ) } else { animateDecay( initialVelocity = initialVelocity, animationSpec = animationSpec, block = block, ) } } @Composable @ExperimentalPagerApi @ExperimentalMaterialApi fun StringPicker( modifier: Modifier = Modifier, strList: List<String>, pagerState: PagerState, reverseLayout: Boolean = false, itemSpacing: Dp = 5.dp, pageChange: (it: Int) -> Unit, ) { VerticalPager( state = pagerState, count = strList.size, reverseLayout = reverseLayout, contentPadding = PaddingValues(vertical = 80.dp), itemSpacing = itemSpacing, modifier = modifier ) { page -> Text( strList[page], fontSize = 19.sp, modifier = Modifier .wrapContentHeight() .wrapContentWidth() ) } LaunchedEffect(pagerState) { snapshotFlow { pagerState.currentPage }.collect { page -> pageChange(page) } } } @Composable fun CustomWebView( modifier: Modifier = Modifier, url: String, onProgressChange: (progress: Int) -> Unit = {}, initSettings: (webSettings: WebSettings?) -> Unit = {}, onReceivedError: (error: WebResourceError?) -> Unit = {} ) { val webViewChromeClient = object : WebChromeClient() { override fun onProgressChanged(view: WebView?, newProgress: Int) { //回调网页内容加载进度 onProgressChange(newProgress) super.onProgressChanged(view, newProgress) } } val webViewClient = object : WebViewClient() { override fun onPageStarted( view: WebView?, url: String?, favicon: Bitmap? ) { super.onPageStarted(view, url, favicon) onProgressChange(-1) } override fun onPageFinished(view: WebView?, url: String?) { super.onPageFinished(view, url) onProgressChange(100) } override fun shouldOverrideUrlLoading( view: WebView?, request: WebResourceRequest? ): Boolean { if (null == request?.url) return false val showOverrideUrl = request.url.toString() try { if (!showOverrideUrl.startsWith("http://") &&!showOverrideUrl.startsWith("https://") ) { //处理非http和https开头的链接地址 Intent(Intent.ACTION_VIEW, Uri.parse(showOverrideUrl)).apply { addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) view?.context?.applicationContext?.startActivity(this) } return true } } catch (e: Exception) { //没有安装和找到能打开(「xxxx://openlink.cc....」、「weixin://xxxxx」等)协议的应用 return true } return super.shouldOverrideUrlLoading(view, request) } override fun onReceivedError( view: WebView?, request: WebResourceRequest?, error: WebResourceError? ) { super.onReceivedError(view, request, error) //自行处理.... onReceivedError(error) } } // var webView: WebView? = null // val coroutineScope = rememberCoroutineScope() AndroidView(modifier = modifier, factory = { ctx -> WebView(ctx).apply { this.webViewClient = webViewClient this.webChromeClient = webViewChromeClient //回调webSettings供调用方设置webSettings的相关配置 initSettings(this.settings) // webView = this loadUrl(url) } }) // BackHandler { // coroutineScope.launch { // //自行控制点击了返回按键之后,关闭页面还是返回上一级网页 // onBack(webView) // } // } } //@ExperimentalAnimationApi //@Preview(showBackground = true) //@Composable //fun PreviewNumberPicker() { // NorScTheme { // StringPicker2( // strList = listOf("1","嫩爹", "hhhh"), // value = 1, // onValueChange = { // // } // ) // } //} ======================= File: app/src/main/java/com/liflymark/normalschedule/ui/class_course/ClassCourseActivity.kt ======================= <filename>app/src/main/java/com/liflymark/normalschedule/ui/class_course/ClassCourseActivity.kt package com.liflymark.normalschedule.ui.class_course import android.content.Intent import android.os.Bundle import android.util.Log import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.animation.core.spring import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.* import androidx.compose.runtime.* import androidx.compose.runtime.livedata.observeAsState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.ParagraphStyle import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.withStyle import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.viewmodel.compose.viewModel import com.google.accompanist.pager.ExperimentalPagerApi import com.google.accompanist.pager.HorizontalPager import com.google.accompanist.pager.PagerDefaults import com.google.accompanist.pager.rememberPagerState import com.liflymark.normalschedule.logic.bean.OneByOneCourseBean import com.liflymark.normalschedule.logic.bean.getData import com.liflymark.normalschedule.logic.model.DepartmentList import com.liflymark.normalschedule.logic.utils.Convert import com.liflymark.normalschedule.logic.utils.GetDataUtil import com.liflymark.normalschedule.ui.score_detail.UiControl import com.liflymark.normalschedule.ui.show_timetable.* import com.liflymark.normalschedule.ui.sign_in_compose.NormalTopBar import com.liflymark.normalschedule.ui.theme.NorScTheme import kotlinx.coroutines.flow.collectLatest class ClassCourseActivity : ComponentActivity() { private val viewModel by lazy { ViewModelProvider(this).get(ClassCourseViewModel::class.java) } @OptIn(ExperimentalPagerApi::class) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val allowImport = intent.getBooleanExtra("allowImport", false) setContent { NorScTheme { UiControl() Column { NormalTopBar(label = "班级课程") SelectMajor(allowImport = allowImport) ShowCourse(courseViewModel = viewModel) } } } } } @Composable fun SelectMajor(allowImport:Boolean = false,courseViewModel: ClassCourseViewModel = viewModel()){ val departmentList = courseViewModel.departmentListFlow.collectAsState(initial =DepartmentList("正在加载", listOf())) var department by remember { mutableStateOf("点击选择学院") } var majorList by remember { mutableStateOf(listOf("点击选择专业")) } var major by remember { mutableStateOf("点击选择专业") } val context = LocalContext.current val activity = LocalContext.current as ClassCourseActivity LaunchedEffect(true){ if (allowImport) { courseViewModel.classBeanLiveData.observe(activity) { val intent = Intent(context, ShowTimetableActivity2::class.java).apply { putExtra("isSaved", false) putExtra("courseList", Convert.allCourseToJson(it.allCourse)) putExtra("user", "") putExtra("password", "") } activity.startActivity(intent) activity.finish() } } } LaunchedEffect(department) { for (i in departmentList.value.structure){ if (i.department == department) { majorList = i.majorList } else { major = "专业" } } } WaitingDepartList(departState = departmentList) Row(horizontalArrangement = Arrangement.Center, modifier = Modifier.fillMaxWidth()) { val expanded = remember { mutableStateOf(false) } val expandedMajorList = remember { mutableStateOf(false) } Box(contentAlignment = Alignment.TopCenter){ TextButton(onClick = { expanded.value = true }) { Text(text = department, fontSize = 15.sp) } //学院列表 DropdownMenu( expanded = expanded.value, onDismissRequest = { expanded.value = false }, modifier = Modifier.height(280.dp) ) { for (i in departmentList.value.structure){ Item(itemName = i.department){ department = it expanded.value =false } } } } Box(contentAlignment = Alignment.Center){ TextButton(onClick = { expandedMajorList.value = true }) { Text(text = major, fontSize = 15.sp) } /*专业列表*/ DropdownMenu( expanded = expandedMajorList.value, onDismissRequest = { expandedMajorList.value = false }, modifier = Modifier.height(280.dp) ) { for (i in majorList){ Item(itemName = i){ major = it expandedMajorList.value =false courseViewModel.putDepartmentAndMajor(department, major) } } } } if (allowImport) { TextButton(onClick = { courseViewModel.saveAccount() courseViewModel.putDepartmentAndMajorBean(department, major) }) { Text(text = "导入当前课表",fontSize = 15.sp) } } } } @Composable fun Item(itemName:String, selectedString: (String) -> Unit){ DropdownMenuItem(onClick = { selectedString(itemName) }) { Text(itemName) } } @ExperimentalPagerApi @Composable fun ShowCourse(courseViewModel: ClassCourseViewModel) { val courseList = courseViewModel.classCourseListLiveData.observeAsState(getNeededClassList(getData())) Column(modifier = Modifier.background(Color.Transparent)) { var userNowWeek by remember { mutableStateOf(getNowWeek()) } val pagerState = rememberPagerState( // pageCount = 19, // initialOffscreenLimit = 2, initialPage = 0, // infiniteLoop = true ) HorizontalPager( state = pagerState, count = 19 ) { page -> SingleLineClass2(oneWeekClass = courseList, page = page) } LaunchedEffect(pagerState) { snapshotFlow { pagerState.currentPage }.collectLatest { page -> userNowWeek = page } } } } @Composable fun SingleLineClass2(oneWeekClass: State<List<List<OneByOneCourseBean>>>, page:Int){ Column() { //星期行 Row() { Column( Modifier .weight(0.6F) .height(40.dp)) { Spacer(modifier = Modifier.height(5.dp)) Text(text = "${getDayOfDate(0, page)}\n月",modifier = Modifier.fillMaxWidth(), fontSize = 10.sp, textAlign = TextAlign.Center) } repeat(7){ Text(text = "${getDayOfWeek(it+1)}\n\n${getDayOfDate(it+1, page)}", Modifier .weight(1F, true) .height(40.dp),fontSize = 11.sp, lineHeight = 10.sp, textAlign = TextAlign.Center) } } Row(modifier = Modifier.verticalScroll(rememberScrollState())) { Column(Modifier.weight(0.6F, true)) { // 时间列 repeat(11) { Text( buildAnnotatedString { withStyle(style = ParagraphStyle(lineHeight = 6.sp)) { withStyle( style = SpanStyle( fontSize = 18.sp, fontWeight = FontWeight.Bold ) ) { append("\n\n${it + 1}") } } withStyle(style = SpanStyle(fontSize = 10.sp)) { append("${getStartTime(it + 1)}\n") append(getEndTime(it + 1)) } }, modifier = Modifier .fillMaxWidth() .height(70.dp), textAlign = TextAlign.Center, ) } } // 课程 val realOneWeekClass = getNeededClassList(oneWeekClass.value.getOrElse(page){ getData() }) for (oneDayClass in realOneWeekClass) { val nowJieShu = IntArray(12) { it + 1 }.toMutableList() Column(Modifier.weight(1F, true)) { for (oneClass in oneDayClass) { val spacerHeight = (oneClass.start - nowJieShu[0]) * 70 if (spacerHeight < 0) { Log.d("TestActivity", "当前有冲突课程") } Spacer( modifier = Modifier .fillMaxWidth() .height(spacerHeight.dp) ) SingleClass3(singleClass = oneClass) // Log.d("classcourseActiv", oneClass.toString()) nowJieShu -= IntArray(oneClass.end) { it + 1 }.toMutableList() } } } } } } @Composable fun SingleClass3(singleClass: OneByOneCourseBean){ // val context = LocalContext.current // val activity = (LocalContext.current as? Activity) // val interactionSource = remember { MutableInteractionSource() } val height = 70*(singleClass.end- singleClass.start + 1) Log.d("aa", "${singleClass.end}-${singleClass.start+1}") Card( modifier = Modifier .fillMaxWidth() .height(height.dp) .padding(2.dp) // 外边距 .alpha(0.75F), elevation = 1.dp, // 设置阴影 ) { val nameList = singleClass.courseName.split("\n") val showDetailDialog = remember { mutableStateOf(false) } // ClassDetailDialog(openDialog = showDetailDialog, singleClass = singleClass) Text( buildAnnotatedString { withStyle(style = SpanStyle(fontWeight = FontWeight.W600, color = Color.White, fontSize = 13.sp) ) { append(nameList[0]+"\n"+nameList[1]+"\n\n") } withStyle(style = SpanStyle(fontWeight = FontWeight.W600, color = Color.White, fontSize = 10.sp) ) { append(nameList[2]) } }, modifier = Modifier .background(singleClass.color) .clickable { showDetailDialog.value = true }, textAlign = TextAlign.Center ) } } fun getNowWeek(): Int { return GetDataUtil.whichWeekNow() } //@Preview(showBackground = true) //@Composable //fun DefaultPreview2() { // NormalScheduleTheme { // // } //} ======================= File: app/src/main/java/com/liflymark/normalschedule/ui/about/ComposeAboutActivity.kt ======================= package com.liflymark.normalschedule.ui.about import android.R.attr.path import android.content.Intent import android.net.Uri import android.os.Build import android.os.Bundle import android.text.TextUtils import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.* import androidx.compose.foundation.layout.* import androidx.compose.material.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.* import androidx.compose.runtime.* import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.core.content.pm.PackageInfoCompat import coil.annotation.ExperimentalCoilApi import coil.compose.rememberImagePainter import com.afollestad.materialdialogs.MaterialDialog import com.liflymark.normalschedule.R import com.liflymark.normalschedule.logic.Repository import com.liflymark.normalschedule.logic.utils.Dialog import com.liflymark.normalschedule.logic.utils.RomUtil import com.liflymark.normalschedule.ui.score_detail.UiControl import com.liflymark.normalschedule.ui.sign_in_compose.NormalTopBar import com.liflymark.normalschedule.ui.theme.NorScTheme import es.dmoral.toasty.Toasty class ComposeAboutActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { UiControl() NorScTheme { Scaffold( topBar = { NormalTopBar(label = "关于") }, content = { AboutPage() } ) } } } fun openBrowser(url: String){ try { val intent = Intent(Intent.ACTION_VIEW) intent.addCategory(Intent.CATEGORY_BROWSABLE) intent.data = Uri.parse(url) startActivity(intent) } catch (e: Exception) { Toasty.error(this,"当前手机未安装浏览器").show() } } } @OptIn(ExperimentalCoilApi::class) @Composable fun AboutPage(){ val context = LocalContext.current val dialog = remember { Dialog.getContractDialog( context, yes = { Toasty.success(context, "您已同意隐私政策及用户协议").show() }, no = { Toasty.info(context,"如果您拒绝该隐私政策或用户协议请立即关闭应用程序").show() } ) } val userDialog = remember { Dialog.getUerContract( context, yes = { Toasty.info(context, "请点击登陆按钮上方的复选框以再次确认").show() }, no = { Toasty.info(context,"如果您拒绝该隐私政策或用户协议请立即关闭应用程序").show() } ) } Column( modifier = Modifier .fillMaxWidth() , horizontalAlignment = Alignment.CenterHorizontally ) { Spacer(modifier = Modifier.height(15.dp)) Image( painter = rememberImagePainter( data = R.mipmap.ic_launcher ), contentDescription = null ) Spacer(modifier = Modifier.height(20.dp)) Text("河大课表", style = MaterialTheme.typography.h5, color = Color.DarkGray) Spacer(modifier = Modifier.height(25.dp)) Text(text = "一款针对河北大学教务系统的课表APP", color = Color.Gray) Spacer(modifier = Modifier.height(30.dp)) Introduce() Row( modifier = Modifier.fillMaxSize(), horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.Bottom ) { Row( modifier = Modifier.fillMaxWidth().wrapContentWidth(), verticalAlignment = Alignment.CenterVertically ) { TextButton(onClick = { dialog.show() }) { Text("隐私政策") } Spacer( modifier = Modifier .width(10.dp) .padding(horizontal = 4.25.dp, vertical = 8.dp) .background(Color.Gray) .height(15.dp) ) TextButton(onClick = { userDialog.show() }) { Text(text = "用户协议") } } } } } @Composable fun Introduce(){ val context = LocalContext.current val activity = LocalContext.current as ComposeAboutActivity val pm = context.packageManager val versionCode2 = PackageInfoCompat.getLongVersionCode(pm.getPackageInfo(context.packageName,0)).toInt() val versionName = pm.getPackageInfo(context.packageName, 0).versionName val versionCode = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { pm.getPackageInfo(context.packageName,0).longVersionCode.toInt() } else { //noinspection deprecation pm.getPackageInfo(context.packageName, 0).versionCode } val checkNewOrNot = rememberSaveable { mutableStateOf(false) } // var checkRes by remember { // mutableStateOf( // CheckUpdateResponse( // result = "正在查询", // status = "301", // force = null, // newUrl = null // ) // ) // } LaunchedEffect(checkNewOrNot.value){ if (checkNewOrNot.value){ Toasty.info(context, "正在查询新版本", Toasty.LENGTH_SHORT).show() val res = Repository.getNewVerison2(versionCode = versionCode2.toString()) if (res.status == "200"){ Toasty.success(context, res.result).show() val uri = Uri.parse(res.newUrl) val intent = Intent(Intent.ACTION_VIEW, uri) context.startActivity(intent) }else{ Toasty.success(context,res.result).show() } } } Column( modifier = Modifier.verticalScroll(rememberScrollState()) ) { SingleIconButton( icon =Icons.Default.BubbleChart, text = "当前版本:$versionName" ) { checkNewOrNot.value = true } SingleIconButton( icon = Icons.Default.Groups, text = "加入反馈群" ) { val key = "<KEY>" val intent = Intent() intent.data = Uri.parse("mqqopensdkapi://bizAgent/qm/qr?url=http%3A%2F%2Fqm.qq.com%2Fcgi-bin%2Fqm%2Fqr%3Ffrom%3Dapp%26p%3Dandroid%26jump_from%3Dwebapi%26k%3D$key") // 此Flag可根据具体产品需要自定义,如设置,则在加群界面按返回,返回手Q主界面,不设置,按返回会返回到呼起产品界面 // intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) try { context.startActivity(intent) } catch (e: Exception){ Toasty.error(context, "未安装QQ").show() } } SingleIconButton( icon = Icons.Default.Adb, text = "开源许可" ) { val intent = Intent(context, GitListActivity::class.java) context.startActivity(intent) } SingleIconButton( icon = Icons.Default.Star, text = "用户协议及隐私政策" ) { val url = if(RomUtil.isVivo){"https://liflymark.top/privacy2/"}else{"https://liflymark.top/privacy/"} activity.openBrowser(url) } // SingleIconButton( // icon = Icons.Default.Star, // text = "隐私政策(内置)" // ) { // dialog.show() // } // SingleIconButton( // icon = Icons.Default.Star, // text = "用户协议(内置)" // ) { // userDialog.show() // } // SingleIconButton( // icon = Icons.Default.Share, // text = "分享APP给同学" // ) { // val it = Intent(Intent.ACTION_SEND) // it.putExtra(Intent.EXTRA_TEXT, "河大课表APP下载:\nhttp://app.lifly.cn\n非官方开发,仅为个人开发") // it.type = "text/plain" // context.startActivity(Intent.createChooser(it, "分享APP")) // Toasty.success(context, "感谢你的分享和认可").show() // } SingleIconButton( icon = Icons.Default.EmojiNature, text = "项目开源" ) { activity.openBrowser("https://github.com/sasaju/NormalSchedule") } SingleIconButton( icon = Icons.Default.Category, text = "关于开发组" ) { MaterialDialog(context) .title(text = "关于开发组") .message(text = "开发者:\n 河北大学 | 大三药物制剂在读@符号 \n (QQ:1289142675) \nLOGO、背景图绘制:\n 河北大学 | 大三药学在读@Mr.") .positiveButton(text = "知道了") .show() } } } @Composable fun SingleIconButton( icon:ImageVector, text:String, onClick:() -> Unit ){ Box(modifier = Modifier.clickable { onClick() }) { Row( modifier = Modifier .fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, ) { Spacer(modifier = Modifier.width(10.dp)) Icon(imageVector = icon, contentDescription = null, modifier = Modifier.padding(10.dp)) Spacer(modifier = Modifier.width(19.dp)) Text(text = text) } } } @Preview(showBackground = true) @Composable fun PreViewAbout(){ Row( horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically ) { TextButton(onClick = { }) { Text("隐私政策") } Text(text = " | ") TextButton(onClick = { }) { Text(text = "用户协议") } } } ======================= File: app/src/main/java/com/liflymark/normalschedule/ui/edit_course/EditCourseActivity.kt ======================= package com.liflymark.normalschedule.ui.edit_course import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.material.* import com.google.accompanist.pager.ExperimentalPagerApi import com.liflymark.normalschedule.ui.add_course.ShowAllCourseToEdit import com.liflymark.normalschedule.ui.score_detail.UiControl import com.liflymark.normalschedule.ui.sign_in_compose.NormalTopBar import com.liflymark.normalschedule.ui.theme.NorScTheme class EditCourseActivity : ComponentActivity() { @OptIn(ExperimentalPagerApi::class, ExperimentalMaterialApi::class) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val courseName = intent.getStringExtra("courseName")?: "" setContent { NorScTheme { UiControl() Scaffold( topBar = { NormalTopBar(label = "添加课程") }, content = { ShowAllCourseToEdit(courseName = courseName) } ) } } } } ======================= File: app/src/main/java/com/liflymark/normalschedule/logic/model/SpaceResponse.kt ======================= <reponame>sasaju/NormalSchedule<gh_stars>1-10 package com.liflymark.normalschedule.logic.model import androidx.annotation.Keep @Keep data class SpaceResponse( val roomList: List<Room>, val roomName: String ) @Keep data class Room( val classroomName: String, val placeNum: String, val spaceNow: String, val type: String ) ======================= File: app/src/main/java/com/liflymark/normalschedule/ui/score_detail/LoginToScoreViewModel.kt ======================= <reponame>sasaju/NormalSchedule<gh_stars>1-10 package com.liflymark.normalschedule.ui.score_detail import android.util.Log import androidx.lifecycle.* import com.liflymark.normalschedule.logic.Repository class LoginToScoreViewModel:ViewModel() { var ids = "" private var user = "" private var password = "" private var nums = 0 private var getIdOrNotLiveData = MutableLiveData(0) private var formMapLiveData = MutableLiveData<Map<String, String>>() val scoreDetailState = Transformations.switchMap(formMapLiveData){ map -> Repository.getScoreDetail(map["user"]!!, map["password"]!!, map["id"]!!).asLiveData().map { if (it.result!="登陆成功"){it.result += nums} it } } val idLiveData = Transformations.switchMap(getIdOrNotLiveData) { Repository.getId3().asLiveData() } // val scoreLiveData = Transformations.switchMap(formMapLiveData) { _ -> // Repository.getScore(user, password, id) // } fun getId() { getIdOrNotLiveData.value = getIdOrNotLiveData.value?.plus(1) Log.d("LoginViewModel", "getID") } fun putValue(user: String, password: String,id: String) { this.user = user this.password = password this.ids = id Log.d("LoginViewModel", "putValue运行") formMapLiveData.value = mapOf("user" to user, "password" to password, "id" to id) } fun putValue(user: String, password: String) { this.user = user this.password = password nums += 1 formMapLiveData.value = mapOf("user" to user, "password" to password, "id" to ids) } fun saveAccount(user: String, password: String) = Repository.saveAccount(user, password) fun getSavedAccount() = Repository.getSavedAccount() fun isAccountSaved() = Repository.isAccountSaved() } ======================= File: app/src/main/java/com/liflymark/normalschedule/ui/abase/BaseActivity.kt ======================= <filename>app/src/main/java/com/liflymark/normalschedule/ui/abase/BaseActivity.kt package com.liflymark.normalschedule.ui.abase import android.content.res.Configuration import android.content.res.Resources import androidx.activity.ComponentActivity import androidx.appcompat.app.AppCompatActivity open class BaseActivity:AppCompatActivity() { override fun getResources(): Resources { val res = super.getResources() if (res.configuration.fontScale!= 1f) { //非默认值 val newConfig = Configuration() newConfig.setToDefaults() //设置默认 res.updateConfiguration(newConfig, res.displayMetrics) } return res } } open class BaseComment:ComponentActivity() { override fun getResources(): Resources { val res = super.getResources() if (res.configuration.fontScale!= 1f) { //非默认值 val newConfig = Configuration() newConfig.setToDefaults() //设置默认 res.updateConfiguration(newConfig, res.displayMetrics) } return res } } ======================= File: app/src/main/java/com/liflymark/normalschedule/logic/model/ScoreDetail.kt ======================= package com.liflymark.normalschedule.logic.model import androidx.annotation.Keep @Keep data class ScoreDetail( val grade_list: List<Grades>, var result: String ) @Keep data class Grades( val allcj: String, val courseName: String, val coursePropertyName: String, val courseScore: String, val credit: String, val lastcj: String, val maxcj: String, val mincj: String, val rank: String, val usualcj: String ) ======================= File: app/src/main/java/com/liflymark/normalschedule/logic/bean/CourseBean.kt ======================= package com.liflymark.normalschedule.logic.bean import androidx.annotation.Keep import androidx.room.ColumnInfo import androidx.room.ColumnInfo.INTEGER import androidx.room.Entity import androidx.room.PrimaryKey import com.liflymark.normalschedule.logic.utils.Convert /** 课程data类 * APP中极为关键的一个类 * @param campusName 校区 * @param color 颜色配置,实例:#ff51555 * @param colorIndex 为适配主题色,配置一个数字,数字代表一个colorList中的index * @param removed 代表是否移除主题色的限制,如果为false-0,则使用colorIndex作为颜色依据,如果为true-1,则使用color作为颜色依据 * * 不过无论是开发难度和用户操作难度,实现脱离主题配置都十分的不容易,所以暂时放弃。 */ @Keep @Entity(primaryKeys = ["courseName", "teacher", "classWeek", "classDay", "classSessions", "continuingSession", "removed"]) data class CourseBean( var campusName: String, var classDay: Int, var classSessions: Int, var classWeek: String, var continuingSession: Int, var courseName: String, var teacher: String, var teachingBuildName: String, var color: String, @ColumnInfo(defaultValue = "-1") var colorIndex: Int = -1, @ColumnInfo(defaultValue = "0") var removed: Boolean = false ) fun getInitial(): List<CourseBean> { return listOf(CourseBean( campusName="五四路校区", classDay=3, classSessions=9, classWeek="111111111111110000000000", continuingSession=3, courseName="毛泽东思想与中国特色社会主义理论概论", teacher="刘卫萍* 耿金龙 ", teachingBuildName="第九教学楼402", color="#f0c239")) } ======================= File: app/src/main/java/com/liflymark/normalschedule/ui/import_show_score/ShowScoreViewModel.kt ======================= package com.liflymark.normalschedule.ui.import_show_score import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider class ShowScoreViewModel():ViewModel() { var gradeString = "" } ======================= File: app/src/main/java/com/liflymark/normalschedule/logic/network/SentenceService.kt ======================= package com.liflymark.normalschedule.logic.network import com.liflymark.normalschedule.logic.model.OneSentencesResponse import retrofit2.Call import retrofit2.http.GET interface SentenceService { @GET("/sentence/") fun getSentencesList():Call<OneSentencesResponse> } ======================= File: app/src/main/java/com/liflymark/normalschedule/ui/GetViewToPng.kt ======================= <reponame>sasaju/NormalSchedule package com.liflymark.normalschedule.ui import android.content.ContentValues import android.content.Context import android.graphics.Bitmap import android.net.Uri import android.os.Bundle import android.os.Environment import android.provider.MediaStore import android.view.View import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import com.liflymark.normalschedule.ui.score_detail.UiControl import com.liflymark.normalschedule.ui.theme.NorScTheme import kotlinx.coroutines.launch import java.io.File import java.io.File.separator import java.io.FileOutputStream import java.io.OutputStream import androidx.compose.material.* import androidx.compose.runtime.* import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.ui.window.DialogProperties import com.google.accompanist.permissions.ExperimentalPermissionsApi import com.google.accompanist.permissions.MultiplePermissionsState import com.google.accompanist.permissions.PermissionState import com.liflymark.normalschedule.ui.sign_in_compose.NormalTopBar import com.liflymark.normalschedule.ui.sign_in_compose.SignUIAll class GetViewToPng : ComponentActivity() { @OptIn(ExperimentalPermissionsApi::class) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // val view = LayoutInflater.from(this).inflate(R.layout.activity_test, null, false) // val drawingCacheEnabled = true // setContentView(view) // view.setDrawingCacheEnabled(drawingCacheEnabled) // view.buildDrawingCache(drawingCacheEnabled) // view.measure( // View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), // View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED) // ); // view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight()); // val drawingCache: Bitmap = view.getDrawingCache() // val bitmap: Bitmap? // bitmap = Bitmap.createBitmap(drawingCache) // view.setDrawingCacheEnabled(false) //// MediaStore.Images.Media.insertImage(contentResolver, bitmap!!, "title", "") // saveImage(bitmap,this, "test") // lifecycle.coroutineScope.launch { // // } // WindowCompat.setDecorFitsSystemWindows(window, false) setContent { NorScTheme { UiControl() val state = rememberScaffoldState() Scaffold( scaffoldState = state, content = { SignUIAll(state){_,_ ->} }, topBar = { NormalTopBar(label = "登录") } ) } } } @OptIn(ExperimentalPermissionsApi::class) @Composable private fun RequestGrant( multiplePermissionsState: MultiplePermissionsState, navigateToSettingsScreen: () -> Unit, scaffoldState: ScaffoldState, hadShowedGrant:@Composable () -> Unit ) { var doNotShowRationale by rememberSaveable { mutableStateOf(false) } val scope = rememberCoroutineScope() when { multiplePermissionsState.allPermissionsGranted -> { hadShowedGrant() } multiplePermissionsState.shouldShowRationale || !multiplePermissionsState.permissionRequested -> { if (doNotShowRationale) { LaunchedEffect(key1 = Unit, block = { scaffoldState.snackbarHostState.showSnackbar(message = "您已拒绝授予,如需授予请重新打开该页面") }) } else { var show by rememberSaveable{ mutableStateOf(true)} if (show) { AlertDialog( onDismissRequest = { multiplePermissionsState.launchMultiplePermissionRequest() show = false }, confirmButton = { TextButton(onClick = { multiplePermissionsState.launchMultiplePermissionRequest() }) { Text(text = "授予权限") } }, dismissButton = { TextButton(onClick = { scope.launch { scaffoldState.snackbarHostState.showSnackbar("拒绝将无法使用该功能") } show = false doNotShowRationale = true }) { Text(text = "拒绝并不再提示") } }, title = { Text(text = "应用需要您授予权限,用以导入日历事件") }, properties = DialogProperties( dismissOnBackPress = true, dismissOnClickOutside = false ) ) } } } else -> { var show by rememberSaveable{ mutableStateOf(true)} if (show){ AlertDialog( onDismissRequest = { show = false }, confirmButton = { TextButton(onClick = navigateToSettingsScreen ) { Text(text = "去设置授予") } }, title = { Text(text = "应用需要您授予权限,用以导入日历事件") }, properties = DialogProperties(dismissOnBackPress = true, dismissOnClickOutside = true) ) } } } } @OptIn(ExperimentalPermissionsApi::class) private fun getPermissionsText(permissions: List<PermissionState>): String { val revokedPermissionsSize = permissions.size if (revokedPermissionsSize == 0) return "" val textToShow = StringBuilder().apply { append("The ") } for (i in permissions.indices) { textToShow.append(permissions[i].permission) when { revokedPermissionsSize > 1 && i == revokedPermissionsSize - 2 -> { textToShow.append(", and ") } i == revokedPermissionsSize - 1 -> { textToShow.append(" ") } else -> { textToShow.append(", ") } } } textToShow.append(if (revokedPermissionsSize == 1) "permission is" else "permissions are") return textToShow.toString() } private fun saveImage(bitmap: Bitmap, context: Context, folderName: String) { if (android.os.Build.VERSION.SDK_INT >= 29) { val values = contentValues() values.put(MediaStore.Images.Media.RELATIVE_PATH, "Pictures/" + folderName) values.put(MediaStore.Images.Media.IS_PENDING, true) // RELATIVE_PATH and IS_PENDING are introduced in API 29. val uri: Uri? = context.contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values) if (uri!= null) { saveImageToStream(bitmap, context.contentResolver.openOutputStream(uri)) values.put(MediaStore.Images.Media.IS_PENDING, false) context.contentResolver.update(uri, values, null, null) } } else { val directory = File(Environment.getExternalStorageDirectory().toString() + separator + folderName) // getExternalStorageDirectory is deprecated in API 29 if (!directory.exists()) { directory.mkdirs() } val fileName = System.currentTimeMillis().toString() + ".png" val file = File(directory, fileName) saveImageToStream(bitmap, FileOutputStream(file)) if (file.absolutePath!= null) { val values = contentValues() values.put(MediaStore.Images.Media.DATA, file.absolutePath) //.DATA is deprecated in API 29 context.contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values) } } } private fun contentValues() : ContentValues { val values = ContentValues() values.put(MediaStore.Images.Media.MIME_TYPE, "image/png") values.put(MediaStore.Images.Media.DATE_ADDED, System.currentTimeMillis() / 1000); values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis()); return values } private fun saveImageToStream(bitmap: Bitmap, outputStream: OutputStream?) { if (outputStream!= null) { try { bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream) outputStream.close() } catch (e: Exception) { e.printStackTrace() } } } /** * 获取一个 View 的缓存视图 * (前提是这个View已经渲染完成显示在页面上) * @param view * @return */ fun getCacheBitmapFromView(view: View): Bitmap? { return null } } ======================= File: app/src/main/java/com/liflymark/normalschedule/ui/app_widget_day/DayAppWidgetProvider.kt ======================= package com.liflymark.normalschedule.ui.app_widget_day import android.annotation.SuppressLint import android.app.PendingIntent import android.appwidget.AppWidgetManager import android.appwidget.AppWidgetProvider import android.content.ComponentName import android.content.Context import android.content.Intent import android.net.Uri import android.util.Log import android.widget.RemoteViews import com.liflymark.normalschedule.MainActivity import com.liflymark.normalschedule.R import com.liflymark.normalschedule.logic.utils.GetDataUtil class DayAppWidgetProvider: AppWidgetProvider() { private val clickAction = "com.liflymark.DayAppWidgetProvider.onclick" @SuppressLint("ResourceType") override fun onUpdate( context: Context?, appWidgetManager: AppWidgetManager?, appWidgetIds: IntArray? ) { // Perform this loop procedure for each App Widget that belongs to this provider appWidgetIds?.forEach { appWidgetId -> // Create an Intent to launch ExampleActivity val randomNumber=(Math.random()*100).toInt() val pendingIntent: PendingIntent = Intent(context, MainActivity::class.java) .let { intent -> PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT) } // Get the layout for the App Widget and attach an on-click listener // to the button val views: RemoteViews = RemoteViews( context?.packageName, R.layout.app_widget_day ).apply { setOnClickPendingIntent(R.id.start_text, pendingIntent) } val nowWeekNum = GetDataUtil.whichWeekNow() val nowDayNum = GetDataUtil.getNowWeekNum() val intent = Intent(context, DayRemoteViewsService::class.java) intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId) intent.putExtra("random", randomNumber) intent.data = Uri.fromParts("content", (appWidgetId+randomNumber).toString(),null) views.setTextViewText( R.id.start_text, GetDataUtil.getNowMonth(whichColumn = nowDayNum, whichWeek = nowWeekNum) ) views.setRemoteAdapter(R.id.course_day_list, intent) views.setEmptyView(R.id.course_day_list, R.layout.app_widget_none_data) val miuiIntent = Intent(context, MainActivity::class.java) val pendingIntent1 = PendingIntent.getActivity(context, 0, miuiIntent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT) views.setPendingIntentTemplate(R.id.course_day_list, pendingIntent1) // val intentSync = Intent(context, DayAppWidgetProvider::class.java) // intentSync.action = // AppWidgetManager.ACTION_APPWIDGET_UPDATE //You need to specify the action for the intent. Right now that intent is doing nothing for there is no action to be broadcasted. // // val pendingSync = PendingIntent.getBroadcast( // context, // 0, // intentSync, // PendingIntent.FLAG_UPDATE_CURRENT // ) //You need to specify a proper flag for the intent. Or else the intent will become deleted. // // remoteV.setOnClickPendingIntent(R.id.imageButtonSync, pendingSync) Log.d("Appwidget", "小部件Update") // appWidgetManager?.notifyAppWidgetViewDataChanged() // Tell the AppWidgetManager to perform an update on the current app widget appWidgetManager?.updateAppWidget(appWidgetId, views) } } override fun onReceive(context: Context, intent: Intent) { super.onReceive(context, intent) val action = clickAction if (action == "refresh"){ val mgr =AppWidgetManager.getInstance(context) val cn = ComponentName(context, DayAppWidgetProvider::class.java) } } } ======================= File: app/src/main/java/com/liflymark/normalschedule/ui/login_space_room/ShowSpaceActivity.kt ======================= <filename>app/src/main/java/com/liflymark/normalschedule/ui/login_space_room/ShowSpaceActivity.kt package com.liflymark.normalschedule.ui.login_space_room import android.os.Bundle import android.util.Log import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.* import androidx.compose.runtime.* import androidx.compose.runtime.livedata.observeAsState import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.TextStyle import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.viewmodel.compose.viewModel import com.liflymark.normalschedule.ui.class_course.Item import com.liflymark.normalschedule.ui.score_detail.UiControl import com.liflymark.normalschedule.ui.sign_in_compose.NormalTopBar import com.liflymark.normalschedule.ui.theme.NorScTheme import es.dmoral.toasty.Toasty class ShowSpaceActivity : ComponentActivity() { private val viewModel by lazy { ViewModelProvider(this).get(ShowSpaceViewModel::class.java) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val ids = intent.getStringExtra("ids") setContent { NorScTheme { UiControl() Column { NormalTopBar(label = "查询空教室") SelectAndShow(ids = ids, viewModel) } } } } } @Composable fun SelectAndShow(ids:String?, ssViewModel: ShowSpaceViewModel = viewModel()){ Column { SayHowToUse() SelectRoom(ids, ssViewModel) ShowSpaceResult() } } @Composable fun SayHowToUse(){ Column { Spacer(modifier = Modifier.height(10.dp)) CenterText(text = "有颜色代表未占用(空教室),无颜色代表已占用",modifier = Modifier.fillMaxWidth()) Spacer(modifier = Modifier.height(3.dp)) CenterText( text = "目前仅支持新区、本部、医学部的部分教室", modifier = Modifier.fillMaxWidth(), textStyle = TextStyle(fontSize = 12.sp, color = Color(0xFF28B1FA)) ) } } @Composable fun SelectRoom(ids:String?, ssViewModel: ShowSpaceViewModel = viewModel()){ val activity = LocalContext.current as ShowSpaceActivity val roomListOf = listOf("六教", "七教","八教", "九教", "A1", "A2","A3", "A4","A6","综合楼", "新楼") if (ids == null){ Toasty.error(activity, "缺少参数").show() activity.finish() } val expandClassRoom = remember { mutableStateOf(false) } val roomName = rememberSaveable { mutableStateOf("六教") } val expandSchool = remember { mutableStateOf(false) } val schoolName = rememberSaveable { mutableStateOf("五四路校区") } val expandDate = remember { mutableStateOf(false) } val threeDate = remember { mutableStateOf(ssViewModel.getThreeDay()) } val dateName = rememberSaveable { mutableStateOf(ssViewModel.getThreeDay()[1]) } val roomList = remember { mutableStateListOf("六教", "七教","八教", "九教", "A1", "A2","A3", "A4") } val schoolList = remember { mutableStateListOf("五四路校区","七一路校区","裕华路校区") } LaunchedEffect(roomName.value){ if (roomName.value in roomListOf){ if (ids!= null) { ssViewModel.getSpaceRoom(ids, roomName.value, dateName.value) } } } LaunchedEffect(dateName.value){ if (roomName.value in roomListOf){ if (ids!= null) { ssViewModel.getSpaceRoom(ids, roomName.value, dateName.value) } } } LaunchedEffect(schoolName.value){ roomList.clear() when(schoolName.value){ "五四路校区" -> roomList.addAll(listOf("六教", "七教","八教", "九教")) "七一路校区" -> roomList.addAll(listOf("A1", "A2","A3", "A4","A6")) "裕华路校区" -> roomList.addAll(listOf("综合楼", "新楼")) } } Row(horizontalArrangement = Arrangement.Center, modifier = Modifier.fillMaxWidth()) { // 选择校区 Box{ TextButton(onClick = { expandSchool.value = true }) { Text(text = schoolName.value, fontSize = 18.sp) } DropdownMenu( expanded = expandSchool.value, onDismissRequest = { expandSchool.value = false }, modifier = Modifier.heightIn(20.dp,280.dp) ) { for (i in schoolList){ Item(itemName = i){ schoolName.value = it expandSchool.value = false } } } } // 选择教室 Box{ TextButton(onClick = { expandDate.value = true }) { Text(text = roomName.value, fontSize = 18.sp) } DropdownMenu( expanded = expandDate.value, onDismissRequest = { expandDate.value = false }, modifier = Modifier.heightIn(20.dp,280.dp) ) { for (i in roomList){ Item(itemName = i){ roomName.value = it expandDate.value = false } } } } // 选择日期 Box{ TextButton(onClick = { expandClassRoom.value = true }) { Text(text = dateName.value, fontSize = 18.sp) } DropdownMenu( expanded = expandClassRoom.value, onDismissRequest = { expandClassRoom.value = false }, modifier = Modifier.heightIn(20.dp,280.dp) ) { for (i in threeDate.value){ Item(itemName = i){ dateName.value = it expandClassRoom.value = false } } } } } } @Composable fun ShowSpaceResult(ssViewModel: ShowSpaceViewModel = viewModel()){ val spaceResult = ssViewModel.spaceResult .observeAsState(initial = ssViewModel.initialSpace) Column(modifier = Modifier.verticalScroll(rememberScrollState())) { for (space in spaceResult.value.roomList){ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth(0.98f)) { CenterText( text = space.classroomName, modifier = Modifier .weight(0.7f) .height(30.dp), textStyle = TextStyle(fontSize = 18.sp), maxLines = 1 ) // Text(text = space.placeNum, modifier = Modifier.weight(0.5f)) // Text(text = space.type, modifier = Modifier.weight(0.5f),maxLines = 1) for (i in space.spaceNow.indices){ if (space.spaceNow[i] == '1'){ ClassIntBox(text = "${i+1}", modifier = Modifier.weight(0.3f)) }else{ ClassIntBox(text = "${i+1}", modifier = Modifier.weight(0.3f), color = Color( 0xAE28B1FA) ) } } } } } } @Composable fun SingleRowSpace(){ Row { repeat(11){ Spacer(modifier = Modifier .size(10.dp) .background(Color.Green)) Spacer(modifier = Modifier.size(10.dp)) } } } @Composable fun CenterText( modifier: Modifier = Modifier, text:String, textStyle: TextStyle = TextStyle(), maxLines: Int = Int.MAX_VALUE, ){ Box(contentAlignment = Alignment.Center, modifier = modifier){ Text(text = text, style = textStyle, maxLines = maxLines) } } @Composable fun ClassIntBox( modifier: Modifier = Modifier, text:String, color: Color = Color.White ){ Box(modifier = modifier.background(color = color), contentAlignment = Alignment.Center){ Text( text = text, color = contentColorFor(backgroundColor = color) ) } } //@Preview(showBackground = true) //@Composable //fun DefaultPreview7() { // NormalScheduleTheme { // SingleRowSpace() // } //} ======================= File: app/src/main/java/com/liflymark/normalschedule/ui/score_detail/ShowDetailScoreActivity.kt ======================= package com.liflymark.normalschedule.ui.score_detail import android.os.Bundle import android.util.Log import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.ExperimentalAnimationApi import androidx.compose.foundation.layout.* import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ExpandLess import androidx.compose.material.icons.filled.ExpandMore import androidx.compose.runtime.* import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.liflymark.normalschedule.logic.Repository import com.liflymark.normalschedule.logic.model.Grades import com.liflymark.normalschedule.logic.utils.Convert import com.liflymark.normalschedule.ui.sign_in_compose.NormalTopBar import com.liflymark.normalschedule.ui.theme.NorScTheme import es.dmoral.toasty.Toasty class ShowDetailScoreActivity : ComponentActivity() { @OptIn( ExperimentalAnimationApi::class, ExperimentalMaterialApi::class ) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val allGradeListString = intent.getStringExtra("detail_list")?:"" setContent { UiControl() NorScTheme { Scaffold( topBar = { NormalTopBar(label = "成绩明细") }, content = { AllGrades(allGradeListString = allGradeListString) } ) } } } } @ExperimentalAnimationApi @ExperimentalMaterialApi @Composable fun AllGrades(allGradeListString: String){ val allGradeList by rememberSaveable { mutableStateOf(Convert.jsonToGradesList(allGradeListString)) } val context = LocalContext.current Column( modifier = Modifier .verticalScroll(rememberScrollState()) .fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally ) { Text(text = "结果仅供参考,一切请以教务系统数据为准!!!") OutlinedButton(onClick = { Repository.setScoreDetail(allGradeListString) Toasty.success(context, "缓存完成").show() }) { Text(text = "缓存至本地") } if (allGradeList.isEmpty()){ Spacer(modifier = Modifier.height(20.dp)) Text(text = "当前教务系统“本学期成绩”为空") } for (i in allGradeList){ SingleGrade(grades = i) Spacer(modifier = Modifier.height(20.dp)) } } } @ExperimentalAnimationApi @ExperimentalMaterialApi @Composable fun SingleGrade(grades: Grades) { var expand by remember { mutableStateOf(false) } var expandIcon by remember { mutableStateOf(Icons.Filled.ExpandLess) } Card(onClick = { expand =!expand expandIcon = if (expand){ Icons.Filled.ExpandMore } else { Icons.Filled.ExpandLess}}, modifier = Modifier.padding(2.dp) ) { Column(modifier = Modifier .fillMaxWidth(0.9f) .padding(8.dp)) { Row(modifier = Modifier.fillMaxWidth()) { Text( text = "${grades.courseName}: ${grades.courseScore}", fontSize = 20.sp, modifier = Modifier.fillMaxWidth(0.8F) ) Icon(imageVector = expandIcon, contentDescription = null, modifier = Modifier .height(30.dp) .fillMaxWidth()) } AnimatedVisibility(visible = expand) { Column { Row(modifier = Modifier.fillMaxWidth()) { Text(text = "平时成绩:${grades.usualcj}",modifier = Modifier.weight(1F)) Text(text = "期末成绩:${grades.lastcj}",modifier = Modifier.weight(1F)) Text(text = "总成绩:${grades.allcj}",modifier = Modifier.weight(1F)) } Row(modifier = Modifier.fillMaxWidth()) { Text(text = "排名:${grades.rank}", modifier = Modifier.weight(1F) ) Text(text = "最高成绩:${grades.maxcj}", modifier = Modifier.weight(1F)) Text(text = "最低成绩:${grades.mincj}", modifier = Modifier.weight(1F)) } Row(modifier = Modifier.fillMaxWidth()) { Text(text = "课程学分:${grades.credit}", modifier = Modifier.weight(1F)) Text(text = "课程类型:${grades.coursePropertyName}", modifier = Modifier.weight(1F)) } } } } } } ======================= File: app/src/main/java/com/liflymark/normalschedule/ui/import_show_score/ImportScoreActivity.kt ======================= <filename>app/src/main/java/com/liflymark/normalschedule/ui/import_show_score/ImportScoreActivity.kt package com.liflymark.normalschedule.ui.import_show_score import android.content.Intent import android.os.Bundle import android.text.SpannableStringBuilder import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import com.gyf.immersionbar.ImmersionBar import com.liflymark.normalschedule.R import com.liflymark.normalschedule.databinding.ActivityImportScoreBinding import com.liflymark.normalschedule.logic.utils.Convert import com.liflymark.normalschedule.logic.utils.Dialog import com.liflymark.normalschedule.logic.utils.RomUtil import es.dmoral.toasty.Toasty class ImportScoreActivity : AppCompatActivity() { private val viewModel by lazy { ViewModelProvider(this).get(ImportScoreViewModel::class.java) } private lateinit var binding: ActivityImportScoreBinding var userName = "" var userPassword = "" private var id = "" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityImportScoreBinding.inflate(layoutInflater) setContentView(binding.root) binding.btnSign.text = "登陆以导入成绩" binding.inputId.hint = "请输入统一认证密码" Toasty.Config.getInstance().setTextSize(15).apply() setSupportActionBar(binding.importToolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true);//添加默认的返回图标 supportActionBar?.setHomeButtonEnabled(true); //设置返回键可用 ImmersionBar.with(this) .statusBarDarkFont(true) .init() if (!RomUtil.isVivo){ binding.tvTitle.text = "登陆HBU教务系统" } val saved = viewModel.isAccountSaved() if (saved) { binding.user0.text = SpannableStringBuilder(viewModel.getSavedAccount()["user"]) binding.password0.text = SpannableStringBuilder(viewModel.getSavedAccount()["password"]) } val progressDialog = Dialog.getProgressDialog(this, "正在加载内容") progressDialog.show() viewModel.getId()// 获取cookie viewModel.idLiveData.observe(this) { val idResponse = it?.id if (idResponse == null || idResponse == ""){ Toasty.error(this, "服务异常,去工具箱-公告栏看看吧", Toasty.LENGTH_SHORT).show() progressDialog.dismiss() } else { this.id = idResponse Toasty.success(this, "服务正常,可以登陆", Toasty.LENGTH_SHORT).show() progressDialog.dismiss() } } viewModel.scoreLiveData.observe(this, Observer { result -> if (result == null) { Toasty.error(this, "登陆异常,重启app试试", Toasty.LENGTH_SHORT).show() progressDialog.dismiss() } else { val allGradeList = result.grade_list when (result.result) { // 此处服务信息传输易造成错误 后期需修改 "登陆成功" -> { // saveAccount() if (binding.saveOrNot.isChecked) { viewModel.saveAccount(userName, userPassword) } else { viewModel.saveAccount(userName, "") } val intent = Intent(this, ShowScoreActivity::class.java).apply { putExtra("grade_list_string", Convert.allGradeToJson(allGradeList)) } startActivity(intent) this.finish() } else -> { result.result.let { Toasty.error(this, it, Toasty.LENGTH_SHORT).show() } } } } }) binding.btnSign.setOnClickListener { // 判断是否输入学号密码并提交数据至ViewModel层以更新数据 userName = binding.user0.text.toString() userPassword = binding.password0.text.toString() progressDialog.show() when { userName == "" -> { Toasty.info(this, "请输入学号", Toasty.LENGTH_SHORT).show() progressDialog.dismiss() } userPassword == "" -> { Toasty.info(this, "请输入密码", Toasty.LENGTH_SHORT).show() progressDialog.dismiss() } else -> viewModel.putValue(userName, userPassword, id) } } } } ======================= File: app/src/main/java/com/liflymark/normalschedule/ui/tool_box/ToolBoxViewModel.kt ======================= package com.liflymark.normalschedule.ui.tool_box import androidx.lifecycle.MutableLiveData import androidx.lifecycle.Transformations import androidx.lifecycle.ViewModel import androidx.lifecycle.asLiveData import com.liflymark.normalschedule.logic.Repository import com.liflymark.normalschedule.logic.model.Bulletin import com.liflymark.normalschedule.logic.model.DevBoardResponse import com.liflymark.normalschedule.logic.model.SchoolBusResponse import com.liflymark.normalschedule.logic.model.TimeList class ToolBoxViewModel:ViewModel() { private val getBulletinValue = MutableLiveData<Int>(0) private val getBusTimeValue = MutableLiveData("now") val initialBulletin = DevBoardResponse( bulletin_list = listOf(Bulletin("admin", "正在链接作者的服务器", "????", "请等待")), status = "no" ) val initialSchoolBus = SchoolBusResponse( nowDay = "error", timeList = TimeList( fiveToSeven = listOf(), sevenToFive = listOf() ) ) val bulletinsLiveData = Transformations.switchMap(getBulletinValue){ Repository.getBulletin().asLiveData() } val busTimeLiveData = Transformations.switchMap(getBusTimeValue){ Repository.getSchoolBusTime(it).asLiveData() } fun getBulletin(){ getBulletinValue.value = getBulletinValue.value?.plus(1) } fun getBusTime(nowType:String){ getBusTimeValue.value = nowType } fun getTypeToString(type:String):String{ return when(type){ "workday" -> "工作日" "weekday" -> "双休日" "holiday" -> "法定假日或寒暑假" else -> "未知" } } } ======================= File: app/src/main/java/com/liflymark/normalschedule/logic/utils/CoilEngine.kt ======================= <filename>app/src/main/java/com/liflymark/normalschedule/logic/utils/CoilEngine.kt package com.liflymark.normalschedule.logic.utils import android.content.Context import android.graphics.PointF import android.graphics.drawable.BitmapDrawable import android.os.Build import android.os.Build.VERSION.SDK_INT import android.view.View import android.widget.ImageView import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory import coil.ComponentRegistry import coil.ImageLoader import coil.decode.GifDecoder import coil.decode.ImageDecoderDecoder import coil.imageLoader import coil.load import coil.request.ImageRequest import com.luck.picture.lib.engine.ImageEngine import com.luck.picture.lib.listener.OnImageCompleteCallback import com.luck.picture.lib.tools.MediaUtils import com.luck.picture.lib.widget.longimage.ImageSource import com.luck.picture.lib.widget.longimage.ImageViewState import com.luck.picture.lib.widget.longimage.SubsamplingScaleImageView import java.io.File class CoilEngine private constructor() : ImageEngine { companion object { private var INSTANCE: CoilEngine? = null @JvmStatic fun create(): CoilEngine { return INSTANCE?: synchronized(this) { INSTANCE?: CoilEngine().also { INSTANCE = it } } } } /** * 加载图片 * * @param context * @param url * @param imageView */ override fun loadImage(context: Context, url: String, imageView: ImageView) { imageView.loadImage(url) } /** * 加载网络图片适配长图方案 * # 注意:此方法只有加载网络图片才会回调 * * @param context * @param url * @param imageView * @param longImageView * @param callback 网络图片加载回调监听 {link after version 2.5.1 Please use the #OnImageCompleteCallback#} */ override fun loadImage( context: Context, url: String, imageView: ImageView, longImageView: SubsamplingScaleImageView, callback: OnImageCompleteCallback? ) { imageView.loadImage(url) { target({ // onStart callback?.onShowLoading() }, { // onError callback?.onHideLoading() }) { // onSuccess callback?.onHideLoading() val eqLongImage = MediaUtils.isLongImg( it.intrinsicWidth, it.intrinsicHeight ) longImageView.visibility = if (eqLongImage) View.VISIBLE else View.GONE imageView.visibility = if (eqLongImage) View.GONE else View.VISIBLE if (eqLongImage) { // 加载长图 longImageView.isQuickScaleEnabled = true longImageView.isZoomEnabled = true longImageView.setDoubleTapZoomDuration(100) longImageView.setMinimumScaleType(SubsamplingScaleImageView.SCALE_TYPE_CENTER_CROP) longImageView.setDoubleTapZoomDpi(SubsamplingScaleImageView.ZOOM_FOCUS_CENTER) longImageView.setImage( ImageSource.bitmap((it as BitmapDrawable).bitmap), ImageViewState(0f, PointF(0f, 0f), 0) ) } else { // 普通图片 imageView.load(it) } } } } /** * 加载网络图片适配长图方案 * # 注意:此方法只有加载网络图片才会回调 * * @param context * @param url * @param imageView * @param longImageView * @ 已废弃 */ override fun loadImage( context: Context, url: String, imageView: ImageView, longImageView: SubsamplingScaleImageView ) { } /** * 加载相册目录 * * @param context 上下文 * @param url 图片路径 * @param imageView 承载图片ImageView */ override fun loadFolderImage(context: Context, url: String, imageView: ImageView) { imageView.scaleType = ImageView.ScaleType.FIT_CENTER imageView.loadImage(url) { size(180, 180) transformations() // placeholder(R.drawable.picture_image_placeholder) target { val circularBitmapDrawable = RoundedBitmapDrawableFactory.create( context.resources, (it as BitmapDrawable).bitmap ) circularBitmapDrawable.cornerRadius = 8f imageView.setImageDrawable(circularBitmapDrawable) } } } /** * 加载gif * * @param context 上下文 * @param url 图片路径 * @param imageView 承载图片ImageView */ override fun loadAsGifImage( context: Context, url: String, imageView: ImageView ) { val imageLoader = ImageLoader.Builder(context).components(fun ComponentRegistry.Builder.() { if (SDK_INT >= 28) { this.add(ImageDecoderDecoder.Factory()) } else { this.add(GifDecoder.Factory()) } }).build() imageView.loadImage(url, imageLoader) } /** * 加载图片列表图片 * * @param context 上下文 * @param url 图片路径 * @param imageView 承载图片ImageView */ override fun loadGridImage(context: Context, url: String, imageView: ImageView) { imageView.scaleType = ImageView.ScaleType.CENTER_CROP imageView.loadImage(url) { size(200, 200) // placeholder(R.drawable.picture_image_placeholder) } } private fun ImageView.loadImage( url: String, imageLoader: ImageLoader = context.imageLoader, builder: ImageRequest.Builder.() -> Unit = {} ) { if (url.startsWith("http") || url.startsWith("https") || Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { load(url, imageLoader, builder) } else { load(File(url), imageLoader, builder) } } } ======================= File: app/src/main/java/com/liflymark/normalschedule/logic/dao/AccountDataDao.kt ======================= <gh_stars>1-10 package com.liflymark.normalschedule.logic.dao import android.content.Context import androidx.datastore.core.DataStore import androidx.datastore.dataStore import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.edit import androidx.datastore.preferences.core.intPreferencesKey import androidx.datastore.preferences.preferencesDataStore import com.liflymark.normalschedule.NormalScheduleApplication import com.liflymark.normalschedule.NormalScheduleApplication.Companion.context import com.liflymark.schedule.data.Settings import com.liflymark.schedule.data.twoColorItem import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.last import kotlinx.coroutines.flow.map import kotlinx.coroutines.runBlocking object AccountDataDao { fun getNewUserOrNot() = run { val context = NormalScheduleApplication.context context.dataStore.data .map { preferences -> preferences[intPreferencesKey("userVersion")]?:0 < 1 } } fun getUserVersion()= run { val context = NormalScheduleApplication.context context.dataStore.data .map { preferences -> preferences[intPreferencesKey("userVersion")] } } suspend fun getUserVersionS(): Int { val context = NormalScheduleApplication.context return context.dataStore.data .map { it[intPreferencesKey("userVersion")] }.first()?:0 } suspend fun saveUserVersion(version:Int = 1){ val context = NormalScheduleApplication.context context.dataStore.edit { it[intPreferencesKey("userVersion")] = version } } // Proto内容 private val Context.settingsStore: DataStore<Settings> by dataStore( fileName = "settings.pb", serializer = SettingsSerializer ) val scheduleSettings = context.settingsStore.data fun getDarkShowBack() = context.settingsStore.data.map { it.darkShowBack } /** * 0-非渐变 默认 * 1-渐变色 */ suspend fun updateColorMode(mode: Int){ context.settingsStore.updateData { it.toBuilder() .setColorMode(mode) .build() } } suspend fun updateDarkShowBack(show:Boolean){ context.settingsStore.updateData { it.toBuilder() .setDarkShowBack(show) .build() } } // 同步写入成绩详情的缓存 fun updateScoreDetail(scoreDetail:String) = runBlocking { context.settingsStore.updateData { it.toBuilder() .setScoreDetail(scoreDetail).build() } } // 同步读取成绩详情缓存 fun getScoreDetail(): String = runBlocking { scheduleSettings.map { settings -> settings.scoreDetail }.first() } fun getColorListAsyc(): MutableList<twoColorItem> = runBlocking { scheduleSettings.map { value: Settings -> value.colorsList }.first() } suspend fun getLastUpdate():String { val res = scheduleSettings.map { it.lastUpdate }.first() return if (res==""){ "2000-01-01" }else{ res } } suspend fun setLastUpdate(last:String) { context.settingsStore.updateData { it.toBuilder() .setLastUpdate(last) .build() } } suspend fun updateSettings(setSettings:(settings:Settings)->Settings){ context.settingsStore.updateData { setSettings(it) } } suspend fun updateSettings(settings: Settings){ context.settingsStore.updateData { settings } } private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "accountInfo") } ======================= File: app/src/main/java/com/liflymark/normalschedule/ui/abase/Button.kt ======================= package com.liflymark.normalschedule.ui.abase import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Button import androidx.compose.material.MaterialTheme import androidx.compose.material.OutlinedButton import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp @Composable fun ConorButton( enable:Boolean = true, onClick:() -> Unit, text:String, ){ Button( enabled = enable, onClick = onClick, shape = RoundedCornerShape(20.dp), modifier = Modifier.fillMaxWidth(0.8f) ) { Row( modifier = Modifier.fillMaxWidth(0.9f), horizontalArrangement = Arrangement.SpaceBetween ) { text.split("").forEach { Text(text = it, style = MaterialTheme.typography.h6, maxLines = 1) } } } } @Composable fun ConorOutlineButton( enable:Boolean = true, onClick:() -> Unit, text:String, ){ OutlinedButton( enabled = enable, onClick = onClick, shape = RoundedCornerShape(20.dp), modifier = Modifier.fillMaxWidth(0.8f) ) { Row( modifier = Modifier.fillMaxWidth(0.9f), horizontalArrangement = Arrangement.SpaceBetween ) { text.split("").forEach { Text(text = it, style = MaterialTheme.typography.h6, maxLines = 1) } } } } ======================= File: app/src/main/java/com/liflymark/normalschedule/logic/network/CheckUpdateService.kt ======================= <gh_stars>1-10 package com.liflymark.normalschedule.logic.network import com.liflymark.normalschedule.logic.model.CheckUpdateResponse import retrofit2.Call import retrofit2.http.Field import retrofit2.http.FormUrlEncoded import retrofit2.http.POST interface CheckUpdateService { @FormUrlEncoded @POST("checkveriosn/") fun getNewVersion( @Field("version")versionCode:String ):Call<CheckUpdateResponse> } ======================= File: app/src/main/java/com/liflymark/normalschedule/ui/tool_box/BusTime.kt ======================= package com.liflymark.normalschedule.ui.tool_box import android.util.Log import androidx.compose.foundation.layout.* import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.DirectionsBus import androidx.compose.runtime.* import androidx.compose.runtime.livedata.observeAsState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.withStyle import androidx.compose.ui.unit.dp import androidx.lifecycle.viewmodel.compose.viewModel import androidx.navigation.NavController import com.liflymark.normalschedule.ui.class_course.Item import com.liflymark.normalschedule.ui.sign_in_compose.NormalTopBar import com.liflymark.normalschedule.ui.theme.NorScTheme /** * 校车总界面 */ @Composable fun SchoolBusAll(navController: NavController){ NorScTheme { Scaffold( topBar = { NormalTopBar(label = "校车时刻表") { navController.navigateUp() } }, content = { SchoolBusCard() } ) } } /** * 校车Content界面 */ @Composable fun SchoolBusCard(tbViewModel: ToolBoxViewModel = viewModel()){ val schoolBusResponse = tbViewModel.busTimeLiveData.observeAsState(initial = tbViewModel.initialSchoolBus) Column(modifier = Modifier.fillMaxWidth() ) { FullCard(modifier = Modifier .fillMaxWidth() .padding(top = 2.dp)) { Log.d("BusTime", schoolBusResponse.value.nowDay) ShowHowToUse(tbViewModel.getTypeToString(schoolBusResponse.value.nowDay)) } RoundedHeader(title = "五四路<-->七一路") Column( modifier= Modifier .fillMaxWidth() .verticalScroll(rememberScrollState()), horizontalAlignment = Alignment.CenterHorizontally ) { Text("五四路 >>> 七一路", style = MaterialTheme.typography.body1) Spacer(modifier = Modifier.height(3.dp)) SingleRowTime(firstCo = "班次", secondCo = "发车时间", thirdCo = "发车数量", isFirst = true) // SingleRowTime(firstCo = "1", secondCo = "7:30", thirdCo = "1") // SingleRowTime(firstCo = "1", secondCo = "7:30", thirdCo = "1") // SingleRowTime(firstCo = "1", secondCo = "7:30", thirdCo = "1") // SingleRowTime(firstCo = "1", secondCo = "7:30", thirdCo = "1") for (singleFive in schoolBusResponse.value.timeList.fiveToSeven){ key(singleFive.runTime+singleFive.runNumber) { SingleRowTime( firstCo = singleFive.runNumber, secondCo = singleFive.runTime, thirdCo = singleFive.runHowMany ) } } Spacer(modifier = Modifier.height(20.dp)) Text("七一路 >>> 五四路", style = MaterialTheme.typography.body1) SingleRowTime(firstCo = "班次", secondCo = "发车时间", thirdCo = "发车数量", isFirst = true) for (singleFive in schoolBusResponse.value.timeList.sevenToFive){ key(singleFive.runTime+singleFive.runNumber) { SingleRowTime( firstCo = singleFive.runNumber, secondCo = singleFive.runTime, thirdCo = singleFive.runHowMany ) } } } } } /** * 单行校车时刻 */ @Composable fun SingleRowTime(firstCo:String, secondCo:String, thirdCo:String,isFirst:Boolean = false){ Row(Modifier.padding(2.dp)){ if (isFirst){ Spacer(modifier = Modifier.size(23.dp)) }else{ Icon(Icons.Default.DirectionsBus, null) } Spacer(modifier = Modifier.width(10.dp)) Text(text = firstCo, modifier = Modifier.weight(1f), textAlign = TextAlign.Center) Text(text = secondCo, modifier = Modifier.weight(1f), textAlign = TextAlign.Center) Text(text = thirdCo, modifier = Modifier.weight(1f), textAlign = TextAlign.Center) } } /** * 说明如何使用校车时刻表 */ @Composable fun ShowHowToUse(type:String, tbViewModel: ToolBoxViewModel = viewModel()){ var userType by remember { mutableStateOf(type) } var expand by remember { mutableStateOf(false) } val typeMap = mapOf("节假日或寒暑假" to "holiday", "工作日" to "workday", "双休日" to "weekday") Column( horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier .padding(3.dp) .fillMaxWidth() ) { Text( buildAnnotatedString { withStyle(SpanStyle()){ append("系统判断当前处于:") } withStyle(SpanStyle(color = Color.Green)){ append("$type\n") } withStyle(SpanStyle()){ append("如有错误,请点击下方文字修改") } } ) Box { TextButton(onClick = { expand = true }) { Text(text = "当前显示日期类型:${userType}", color = Color.White) } DropdownMenu( expanded = expand, onDismissRequest = { expand = false }, modifier = Modifier.height(200.dp) ){ for (i in typeMap.keys){ Item(itemName = i) { userType = it expand =false typeMap[it]?.let { it1 -> tbViewModel.getBusTime(it1) } } } } } } } ======================= File: app/src/main/java/com/liflymark/normalschedule/ui/tool_box/AnwserQuestion.kt ======================= <reponame>sasaju/NormalSchedule package com.liflymark.normalschedule.ui.tool_box import android.content.Intent import android.net.Uri import androidx.compose.foundation.layout.* import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.* import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.font.FontStyle import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.navigation.NavController import com.liflymark.normalschedule.ui.sign_in_compose.NormalTopBar import com.liflymark.normalschedule.ui.theme.NorScTheme import es.dmoral.toasty.Toasty @ExperimentalMaterialApi @Composable fun QuestionAllPage( navController: NavController ){ NorScTheme { Scaffold( topBar = { NormalTopBar(label = "常见问题") { navController.navigateUp() } }, content = { QuestionContent() } ) } } @ExperimentalMaterialApi @Composable fun QuestionContent(){ val context = LocalContext.current Column( modifier = Modifier .fillMaxSize() .verticalScroll(rememberScrollState()) ) { QuestionCard( onClick = { }, question = "1.为什么有时候成绩无法查询?", answer = "成绩数据目前全部来源于教务系统,如果教务系统无法通过EasyConnect访问,那么也就无法查询," + "开发者未来可能会加入本地缓存,用来显示查询历史,但时间未确定,请持续关注。" ) QuestionCard( onClick = { }, question = "2.如何调整桌面小部件大小?", answer = "请自行百度:”你的手机品牌+调整小部件大小“" ) QuestionCard( onClick = { val key = "<KEY>" val intent = Intent() intent.data = Uri.parse("mqqopensdkapi://bizAgent/qm/qr?url=http%3A%2F%2Fqm.qq.com%2Fcgi-bin%2Fqm%2Fqr%3Ffrom%3Dapp%26p%3Dandroid%26jump_from%3Dwebapi%26k%3D$key") // 此Flag可根据具体产品需要自定义,如设置,则在加群界面按返回,返回手Q主界面,不设置,按返回会返回到呼起产品界面 // intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) try { context.startActivity(intent) } catch (e: Exception){ Toasty.error(context, "未安装QQ").show() } }, question = "3.能否加入xxx功能?", answer = "社交功能不加,广告功能不加,笔记功能不加,其他功能建议欢迎加入反馈群或发邮件反馈。(直接点击可跳转至QQ反馈群)" ) QuestionCard( onClick = { }, question = "4.为什么开发速度这么慢,质量也不高?", answer = "开发者只有一个人,UI、逻辑处理、后台搭建全部为一个人,平时还需上课、做实验,精力和能力实在有限。如果有愿意一起开发、帮我设计UI的小伙伴欢迎联系我。" ) } } @ExperimentalMaterialApi @Composable fun QuestionCard( onClick:() -> Unit, question:String, answer:String ){ Card( onClick = { onClick() }, elevation = 1.dp, modifier = Modifier .padding(vertical = 2.dp, horizontal = 3.dp) .fillMaxWidth() ) { Column( modifier = Modifier .padding(6.dp) .fillMaxWidth() ) { Text(text = question, style = MaterialTheme.typography.h6,fontStyle = FontStyle.Italic) Spacer(modifier = Modifier.height(10.dp)) Text(text = answer, style = MaterialTheme.typography.body1, fontStyle = FontStyle.Normal, color = Color.Gray) } } } @ExperimentalMaterialApi @Composable @Preview(showBackground = true) fun AnswerPreView(){ NorScTheme { QuestionContent() } } ======================= File: app/src/main/java/com/liflymark/normalschedule/logic/network/NormalScheduleNetwork.kt ======================= <filename>app/src/main/java/com/liflymark/normalschedule/logic/network/NormalScheduleNetwork.kt package com.liflymark.normalschedule.logic.network import android.util.Log import retrofit2.Call import retrofit2.Callback import retrofit2.Response import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException import kotlin.coroutines.suspendCoroutine object NormalScheduleNetwork { private val CourseService = ServiceCreator.create(CourseService::class.java) private val ScoreService = ServiceCreator.create(ScoreService::class.java) private val SentenceService = ServiceCreator.create(SentenceService::class.java) private val SpacesService = ServiceCreator.create(SpaceService::class.java) private val DevService = ServiceCreator.create(DevBoardService::class.java) private val ExamArrangeService = ServiceCreator.create(ExamArrangeService::class.java) private val CheckUpdateService = ServiceCreator.create(CheckUpdateService::class.java) suspend fun getId() = CourseService.getId().await() fun cancelAll() = ServiceCreator.cancelAll() suspend fun getCaptcha(sessionID: String) = CourseService.getCaptcha(sessionID).await() suspend fun getCourse(user:String,password:String, yzm:String, headers:String) = CourseService.getCourse(user, password, yzm, headers).await() suspend fun getCourse(user: String, password: String) = CourseService.getCourseByNew(user, password).await() suspend fun getDepartmentList() = CourseService.getDepartmentList().await() suspend fun getCourseByMajor(department: String, major:String) = CourseService.getCourseByClass(department, major).await() suspend fun getScore(user:String, password:String, id:String) = ScoreService.getScore(user, password, id).await() suspend fun getVisitCourse() = CourseService.getVisit().await() suspend fun getSentences() = SentenceService.getSentencesList().await() suspend fun getScoreDetail(user:String, password:String, id:String) = ScoreService.getScoreDetail(user, password, id).await() suspend fun loginToSpace(user: String, password: String, id: String) = SpacesService.loginToSpace(user, password, id).await() suspend fun getSpaceRooms(id: String, roomName:String, searchDate: String) = SpacesService.getSpaceRooms(id, roomName, searchDate).await() suspend fun getBulletin() = DevService.getBulletin().await() suspend fun getSchoolBusTime(searchType: String) = DevService.getSchoolBusTime(searchType).await() suspend fun getExamArrange(userNumber: String, password: String, id: String) = ExamArrangeService.getExamArrange(userNumber, password, id).await() suspend fun getNewVersion(versionCode:String) = CheckUpdateService.getNewVersion(versionCode).await() suspend fun loginWebVPN(user: String,password: String) = CourseService.loginWebVPN(user, password).await() suspend fun loginURP( user: String, password: <PASSWORD>, yzm: String, cookies:String ) = CourseService.loginURP(user, password, yzm, cookies).await() suspend fun getGraduateCaptcha(cookies: String) = CourseService.getGraduateCaptcha(cookies).await() suspend fun getStartBulletin(id:Int, versionCode: Int) = DevService.getStartBulletin(id, versionCode).await() private suspend fun <T> Call<T>.await(): T { return suspendCoroutine { continuation -> enqueue(object : Callback<T> { override fun onResponse(call: Call<T>, response: Response<T>) { val body = response.body() if (body!= null) continuation.resume(body) else continuation.resumeWithException( RuntimeException("Response body is null") ) } override fun onFailure(call: Call<T>, t: Throwable) { if (call.isCanceled){ call.cancel() } continuation.resumeWithException(t) } }) } } } ======================= File: app/src/main/java/com/liflymark/normalschedule/logic/model/SchoolBusResponse.kt ======================= <reponame>sasaju/NormalSchedule package com.liflymark.normalschedule.logic.model import androidx.annotation.Keep @Keep data class SchoolBusResponse( val nowDay: String, val timeList: TimeList ) @Keep data class TimeList( val fiveToSeven: List<FiveToSeven>, val sevenToFive: List<SevenToFive> ) @Keep data class FiveToSeven( val runHowMany: String, val runNumber: String, val runTime: String ) @Keep data class SevenToFive( val runHowMany: String, val runNumber: String, val runTime: String ) ======================= File: app/src/main/java/com/liflymark/normalschedule/ui/about/GitListActivity.kt ======================= <filename>app/src/main/java/com/liflymark/normalschedule/ui/about/GitListActivity.kt package com.liflymark.normalschedule.ui.about import android.content.Intent import android.net.Uri import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.LinearLayout import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.recyclerview.widget.LinearLayoutManager import com.gyf.immersionbar.ImmersionBar import com.liflymark.normalschedule.R import com.liflymark.normalschedule.logic.model.GitProject import com.liflymark.normalschedule.ui.score_detail.UiControl import com.liflymark.normalschedule.ui.sign_in_compose.NormalTopBar import com.liflymark.normalschedule.ui.theme.NorScTheme class GitListActivity : ComponentActivity() { private val gitProjectList = ArrayList<GitProject>() // private lateinit var binding: ActivityGitListBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { NorScTheme { ProjectListAll() } } // binding = ActivityGitListBinding.inflate(layoutInflater) // ImmersionBar.with(this).init() // initList() // val layoutManager = LinearLayoutManager(this) // binding.gitList.layoutManager = layoutManager // val adapter = GitListAdapter(this,gitProjectList) // binding.gitList.adapter = adapter // setContentView(binding.root) } private fun initList(){ gitProjectList.add(GitProject("NiceSpinner:下拉组件", "https://github.com/arcadefire/nice-spinner")) gitProjectList.add(GitProject("ImmersionBar:沉浸式状态栏实现", "https://github.com/gyf-dev/ImmersionBar")) gitProjectList.add(GitProject("Toasty", "https://github.com/GrenderG/Toasty")) gitProjectList.add(GitProject("Wakeup课程表", "https://github.com/YZune/WakeupSchedule_Kotlin")) gitProjectList.add(GitProject("docker-easyconnect:服务器使用easyconnect", "https://github.com/Hagb/docker-easyconnect")) gitProjectList.add(GitProject("Androidx", "https://github.com/google")) gitProjectList.add(GitProject("Material Dialogs","https://github.com/afollestad/material-dialogs")) gitProjectList.add(GitProject("Retrofit2","https://github.com/square/retrofit")) gitProjectList.add(GitProject("Coil", "https://github.com/coil-kt/coil")) gitProjectList.add(GitProject("Gson", "https://github.com/google/gson")) gitProjectList.add(GitProject("Accompanist", "https://github.com/google/accompanist")) gitProjectList.add(GitProject("PictureSelector","https://github.com/LuckSiege/PictureSelector")) } fun openBrowser(url: String){ try { val intent = Intent(Intent.ACTION_VIEW) intent.addCategory(Intent.CATEGORY_BROWSABLE); intent.setData(Uri.parse(url)) startActivity(intent) } catch (e: Exception) { println("当前手机未安装浏览器") } } } ======================= File: app/src/main/java/com/liflymark/normalschedule/ui/work_book/AddHomework.kt ======================= package com.liflymark.normalschedule.ui.work_book import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.material.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.paint import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.painter.Painter import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.window.Dialog import androidx.compose.ui.window.DialogProperties import androidx.lifecycle.viewmodel.compose.viewModel import com.google.accompanist.pager.ExperimentalPagerApi import com.google.accompanist.pager.rememberPagerState import com.liflymark.normalschedule.logic.bean.HomeworkBean import com.liflymark.normalschedule.logic.utils.* import com.liflymark.normalschedule.logic.utils.GetDataUtil import java.util.* @ExperimentalPagerApi @ExperimentalMaterialApi @Composable fun EditNewOrEditDialog( show: MutableState<Boolean>, homeworkBean: HomeworkBean, deleteId: (beanId: Int) -> Unit, newBean: (newHomeworkBean: HomeworkBean) -> Unit ) { val valueInit = homeworkBean.workContent val showSelectDialog = remember { mutableStateOf(false) } var dateStr by remember { mutableStateOf(GetDataUtil.getDateStrByMillis(homeworkBean.deadLine)) } val beanCalendar = GetDataUtil.getCalendarByMillis(homeworkBean.deadLine) SelectDateDialog( showDialog = showSelectDialog, initialYear = beanCalendar.get(Calendar.YEAR)-2021, initialMonth = beanCalendar.get(Calendar.MONTH), initialDay = beanCalendar.get(Calendar.DATE)-1, selectMillis = { homeworkBean.deadLine = it dateStr = GetDataUtil.getDateStrByMillis(it) } ) if (show.value) { Dialog( onDismissRequest = { show.value = false }, DialogProperties(dismissOnBackPress = false, dismissOnClickOutside = true), ) { Column( modifier = Modifier .fillMaxWidth() .wrapContentHeight() .background(Color.White) .padding(10.dp) ) { EditTextFiled( valueInit = valueInit, onValueChange = { homeworkBean.workContent = it } ) Row( modifier = Modifier .fillMaxWidth() .height(100.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center ) { Text(text = "截止日期:") TextButton(onClick = { showSelectDialog.value = true }) { Text(text = dateStr) } } Spacer(modifier = Modifier.height(10.dp)) Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween ) { TextButton(onClick = { show.value = false }) { Text(text = "取消") } TextButton(onClick = { deleteId(homeworkBean.id) show.value = false }) { Text(text = "删除") } TextButton(onClick = { newBean(homeworkBean) show.value = false }) { Text(text = "保存") } } } } } } @ExperimentalPagerApi @ExperimentalMaterialApi @Composable fun AddNewOrEditDialog( show: MutableState<Boolean>, homeworkBean: HomeworkBean, deleteId: (beanId: Int) -> Unit, newBean: (newHomeworkBean: HomeworkBean) -> Unit ) { val valueInit = homeworkBean.workContent if (show.value) { Dialog( onDismissRequest = { show.value = false }, DialogProperties(dismissOnBackPress = false, dismissOnClickOutside = true), ) { Column( modifier = Modifier .fillMaxWidth() .wrapContentHeight() .background(Color.White) .padding(10.dp) ) { EditTextFiled( valueInit = valueInit, onValueChange = { homeworkBean.workContent = it } ) Spacer(modifier = Modifier.height(5.dp)) Row( modifier = Modifier .fillMaxWidth() .height(150.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center ) { Text(text = "截止日期:") SelectDeadLine( ) { homeworkBean.deadLine = it } } Spacer(modifier = Modifier.height(10.dp)) Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween ) { TextButton(onClick = { show.value = false }) { Text(text = "取消") } TextButton(onClick = { deleteId(homeworkBean.id) show.value = false }) { Text(text = "删除") } TextButton(onClick = { newBean(homeworkBean) show.value = false }) { Text(text = "保存") } } } } } } @ExperimentalMaterialApi @ExperimentalPagerApi @Composable fun SelectDeadLine( modifier: Modifier = Modifier, addMillis: (millis: Long) -> Unit ) { val stringList = listOf("明天","一周后", "两周后") StringPicker2( modifier = modifier, value = 1, strList = stringList, onValueChange = { val addDay = when (stringList[it]) { "明天" -> 7 "一周后" -> 1 "两周后" -> 14 else -> 0 } addMillis(GetDataUtil.getDayMillis(addDay)) } ) } @Composable fun EditTextFiled( valueInit: String, onValueChange: (value: String) -> Unit ) { var value by remember { mutableStateOf(valueInit) } TextField( value = value, textStyle = MaterialTheme.typography.h6, onValueChange = { value = it onValueChange(it) }, modifier = Modifier .height(140.dp) .fillMaxWidth(), placeholder = { Text(text = "在这里输入作业") }, colors = TextFieldDefaults.textFieldColors( backgroundColor = Color(0x6B28C76F) ), maxLines = 10 ) } @ExperimentalPagerApi @ExperimentalMaterialApi @Preview(showBackground = true) @Composable fun DialogContentPreview() { val homeworkBean = HomeworkBean( id = 999, "未查询到", "张子龙你多重了\n张子龙你胖了不", deadLine = 0, finished = false, createDate = 0 ) Column( modifier = Modifier .fillMaxWidth() ) { EditTextFiled( valueInit = "aa", onValueChange = { homeworkBean.workContent = it } ) Row( modifier = Modifier .fillMaxWidth() .height(100.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center ) { Text(text = "截止日期:") SelectDeadLine( modifier = Modifier.height(80.dp) ) { homeworkBean.deadLine = it } } Spacer(modifier = Modifier.height(10.dp)) Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween ) { TextButton(onClick = { }) { Text(text = "取消") } TextButton(onClick = { }) { Text(text = "保存") } } } } ======================= File: app/src/main/java/com/liflymark/normalschedule/ui/class_course/courseDialog.kt ======================= <filename>app/src/main/java/com/liflymark/normalschedule/ui/class_course/courseDialog.kt<gh_stars>1-10 package com.liflymark.normalschedule.ui.class_course import androidx.compose.runtime.Composable import androidx.compose.runtime.State import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import com.liflymark.normalschedule.logic.model.DepartmentList import com.liflymark.normalschedule.ui.score_detail.ProgressDialog @Composable fun WaitingDepartList(departState:State<DepartmentList>){ val openDialog = remember { mutableStateOf(false) } openDialog.value = departState.value.status!= "yes" ProgressDialog(openDialog = openDialog,departState.value.status) } ======================= File: app/src/main/java/com/liflymark/normalschedule/logic/bean/HomeworkBean.kt ======================= <gh_stars>1-10 package com.liflymark.normalschedule.logic.bean import androidx.annotation.Keep import androidx.room.Entity import androidx.room.PrimaryKey @Keep @Entity data class HomeworkBean( @PrimaryKey(autoGenerate = true) val id:Int, var courseName:String, var workContent: String, var createDate:Long, var deadLine:Long, var finished:Boolean ) ======================= File: app/src/main/java/com/liflymark/normalschedule/logic/dao/CourseOriginalDao.kt ======================= package com.liflymark.normalschedule.logic.dao import androidx.room.* import com.liflymark.normalschedule.logic.bean.CourseBean @Dao interface CourseOriginalDao { // @Transaction // suspend fun insertSingleCourse(courseBean: CourseBean) { // insertCourse(courseBean) // } @Insert suspend fun insertCourse(course: CourseBean): Long @Insert suspend fun insertCourse(course: List<CourseBean>) @Update suspend fun updateCourse(newCourse: CourseBean) @Update fun updateCourse(newCourse: List<CourseBean>) @Query("select * from CourseBean") suspend fun loadAllUnRemoveCourse(): List<CourseBean> @Query("select * from CourseBean") fun loadAllCourseAs(): List<CourseBean> @Query("select * from CourseBean where courseName=:courseName and classDay=:classDay and classSessions=:classSessions and continuingSession=:continuingSession and teachingBuildName=:buildingName and removed = 0" ) suspend fun loadCourseUnTeacher(courseName: String, classDay:Int, classSessions:Int, continuingSession:Int, buildingName:String):List<CourseBean> @Query("select * from CourseBean where courseName=:courseName and classDay=:classDay and classSessions=:classSessions and continuingSession=:continuingSession and removed = 0" ) suspend fun loadCourseUnTeacher(courseName: String, classDay:Int, classSessions:Int, continuingSession:Int):List<CourseBean> @Query("delete from CourseBean where courseName = :courseName") suspend fun deleteCourseByName(courseName: String) @Query("delete from CourseBean where courseName =:courseName and classSessions = :courseStart and classDay = :whichColumn") suspend fun deleteCourseByNameAndStart(courseName: String, courseStart: Int, whichColumn: Int) @Query("select * from CourseBean where courseName = :courseName") suspend fun loadCourseByName(courseName: String): List<CourseBean> @Query("select * from CourseBean where courseName =:courseName and classSessions = :courseStart and classDay = :whichColumn") suspend fun loadCourseByNameAndStart(courseName: String, courseStart: Int, whichColumn: Int): List<CourseBean> @Query("delete from CourseBean where courseName is not null") suspend fun deleteAllCourseBean() @Query("select distinct courseName from CourseBean") suspend fun loadAllCourseName():List<String> @Query("select * from CourseBean") suspend fun loadRemovedCourse():List<CourseBean> @Query("delete from CourseBean") suspend fun deleteRemovedCourseBean() @Delete suspend fun deleteCourse(course: CourseBean) @Delete suspend fun deleteCourse(course: List<CourseBean>) } ======================= File: app/src/main/java/com/liflymark/normalschedule/logic/model/IdResponse.kt ======================= <filename>app/src/main/java/com/liflymark/normalschedule/logic/model/IdResponse.kt package com.liflymark.normalschedule.logic.model import androidx.annotation.Keep // 用于接收api返回的id @Keep data class IdResponse( val id: String ) ======================= File: app/src/main/java/com/liflymark/normalschedule/logic/utils/text_field/TextField.kt ======================= <reponame>sasaju/NormalSchedule<filename>app/src/main/java/com/liflymark/normalschedule/logic/utils/text_field/TextField.kt package com.liflymark.normalschedule.logic.utils.text_field import androidx.compose.material.Text import androidx.compose.material.TextField import androidx.compose.material.TextFieldDefaults import androidx.compose.runtime.* import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color @Composable fun TransparentTextFiled( value: String, onValueChange: (String) -> Unit, modifier: Modifier = Modifier, placeHolder:String, leadingIcon: @Composable (() -> Unit)? = null, ){ var textFieldValueState by remember { mutableStateOf(value) } val textFieldValue = textFieldValueState TextField( value = value, onValueChange = { textFieldValueState = it if (textFieldValue!= it) { onValueChange(it) } }, modifier = modifier, maxLines = 1, placeholder = { Text(text = placeHolder) }, leadingIcon = leadingIcon, colors = TextFieldDefaults.textFieldColors( backgroundColor = Color.Transparent, focusedIndicatorColor = Color.Transparent, unfocusedIndicatorColor = Color.Transparent, ), singleLine = true ) } @Composable fun BackgroundTransparentTextFiled( value: String, onValueChange: (String) -> Unit, modifier: Modifier = Modifier, placeHolder:String, leadingIcon: @Composable (() -> Unit)? = null, ){ var textFieldValueState by remember { mutableStateOf(value) } val textFieldValue = textFieldValueState TextField( value = value, onValueChange = { textFieldValueState = it if (textFieldValue!= it) { onValueChange(it) } }, modifier = modifier, maxLines = 1, placeholder = { Text(text = placeHolder) }, leadingIcon = leadingIcon, colors = TextFieldDefaults.textFieldColors( backgroundColor = Color.Transparent, ), singleLine = true ) } ======================= File: app/src/main/java/com/liflymark/normalschedule/ui/graduate_import/GraduateImportViewModel.kt ======================= <reponame>sasaju/NormalSchedule package com.liflymark.normalschedule.ui.graduate_import import android.graphics.Bitmap import android.util.Log import androidx.compose.runtime.mutableStateOf import androidx.lifecycle.ViewModel import com.liflymark.normalschedule.logic.Repository import com.liflymark.normalschedule.logic.model.GraduateResponse import com.liflymark.normalschedule.logic.model.GraduateWeb import kotlinx.coroutines.FlowPreview import kotlinx.coroutines.flow.* import java.util.concurrent.Flow class GraduateImportViewModel:ViewModel() { private var loginCount = 0 private val captcha = MutableStateFlow<Int>(0) var user = "" var password = "" private var yzm = "" var cookies = "" val loginWebVPNState = mutableStateOf<String?>(null) val loginURPState = mutableStateOf<GraduateResponse?>(null) val loginVPNorNot = mutableStateOf(false) val showWarning = mutableStateOf(true) val showCounter = flow { var sec = 9 repeat(sec){ kotlinx.coroutines.delay(1000L) sec -= 1 emit(sec) } } @OptIn(FlowPreview::class) val captchaFlow = captcha.flatMapConcat { if (cookies!=""){ Repository.getGraduateCaptcha(cookies) }else{ flow { emit(null) } } } // @OptIn(FlowPreview::class) // val captchaFlow = captcha.flatMapConcat { Repository.getGraduateCaptcha(cookies) } suspend fun loginVPN(user:String, password:String){ loginCount += 1 this.user = user this.password = password if (user=="" || password==""){ loginWebVPNState.value = "请输入账号密码$loginCount" return } val res = Repository.loginWebVPN(user, password).last() Log.d("GradusateViewmodel", res.toString()) if (res.result=="登陆成功"){ this.cookies = res.cookies loginVPNorNot.value = true getCaptcha() } loginWebVPNState.value = res.result + loginCount.toString() } suspend fun loginURP(yzm:String){ this.yzm = yzm if (yzm!="") loginURPState.value = Repository.loginURP(user, password, yzm, cookies).last() else loginURPState.value = GraduateResponse(listOf(),"请输入验证码","no") } fun getCaptcha() { captcha.value += 1 } } ======================= File: app/src/main/java/com/liflymark/normalschedule/logic/dao/AppDatabase.kt ======================= <reponame>sasaju/NormalSchedule package com.liflymark.normalschedule.logic.dao import android.content.Context import androidx.room.* import androidx.room.migration.AutoMigrationSpec import androidx.room.migration.Migration import androidx.sqlite.db.SupportSQLiteDatabase import com.liflymark.normalschedule.logic.bean.* @Database( version = 6, entities = [CourseBean::class, UserBackgroundBean::class, HomeworkBean::class, Bulletin2::class], autoMigrations = [ AutoMigration(from = 2, to = 3), AutoMigration(from = 3, to = 4, spec = AppDatabase.DeleteId::class), AutoMigration(from = 4, to = 5), AutoMigration(from = 5, to = 6)// 创建Bulletin2表 ] ) abstract class AppDatabase: RoomDatabase() { abstract fun courseDao(): CourseOriginalDao abstract fun backgroundDao(): BackgroundDao abstract fun homeworkDao(): HomeworkDao abstract fun StartBulletinDao(): StartBulletinDao // 采用多个键作为主键 故移除id字段 @DeleteColumn(columnName = "id", tableName = "CourseBean") class DeleteId : AutoMigrationSpec { } companion object { private val MIGRATION_1_2 = object : Migration(1, 2){ override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("create table UserBackgroundBean (id integer primary key autoincrement not null, userBackground text not null)") } } private var instance: AppDatabase? = null @Synchronized fun getDatabase(context: Context): AppDatabase { instance?.let { return it } return Room.databaseBuilder(context.applicationContext, AppDatabase::class.java, "app_database.db") .addMigrations(MIGRATION_1_2) .allowMainThreadQueries() .build().apply { instance = this } } } } ======================= File: app/src/main/java/com/liflymark/normalschedule/logic/network/DevBoardService.kt ======================= package com.liflymark.normalschedule.logic.network import com.liflymark.normalschedule.logic.bean.StartBulletinBean import com.liflymark.normalschedule.logic.model.DevBoardResponse import com.liflymark.normalschedule.logic.model.SchoolBusResponse import retrofit2.Call import retrofit2.http.Field import retrofit2.http.GET import retrofit2.http.Path import retrofit2.http.Query interface DevBoardService { @GET("bulletin/") fun getBulletin(): Call<DevBoardResponse> @GET("bulletin/start/") fun getStartBulletin(@Query("id") id:Int, @Query("version") versionCode:Int):Call<StartBulletinBean> @GET("tool/schoolbus/{type}") fun getSchoolBusTime(@Path("type")searchType: String): Call<SchoolBusResponse> } ======================= File: app/src/main/java/com/liflymark/normalschedule/ui/score_detail/ScoreDetailDialog.kt ======================= <reponame>sasaju/NormalSchedule package com.liflymark.normalschedule.ui.score_detail import android.annotation.SuppressLint import androidx.compose.animation.core.animateFloatAsState import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.foundation.layout.Arrangement.Absolute.Center import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.* import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color.Companion.White import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.window.Dialog import androidx.compose.ui.window.DialogProperties @Composable fun WaitDialog(openDialog: MutableState<Boolean>){ if(openDialog.value){ AlertDialog( onDismissRequest = { openDialog.value = false }, title = { Text(text = "正在加载") }, text = { Text(text = "请等待......") }, buttons = { } ) } } @Composable fun ProgressDialog( openDialog: MutableState<Boolean>, label:String, dismissOnClickOutside:Boolean = true, content:@Composable () -> Unit = {}, ){ if (openDialog.value) { Dialog( onDismissRequest = { openDialog.value = false }, DialogProperties(dismissOnBackPress = true, dismissOnClickOutside = dismissOnClickOutside) ) { Box( contentAlignment= Alignment.Center, modifier = Modifier .wrapContentWidth() .height(100.dp) .background(White, shape = RoundedCornerShape(8.dp)) ) { Column(horizontalAlignment = Alignment.CenterHorizontally) { Row(verticalAlignment = Alignment.CenterVertically) { Spacer(modifier = Modifier.width(10.dp)) CircularProgressIndicator() if (label!= "") { Spacer(modifier = Modifier.width(10.dp)) Text(text = label, modifier = Modifier.wrapContentWidth()) } Spacer(modifier = Modifier.width(10.dp)) } content() } } } } } //@Preview(showBackground = true) //@Composable //fun DialogPreview(){ // //} ======================= File: app/src/main/java/com/liflymark/normalschedule/logic/bean/OneByOneCourseBean.kt ======================= <filename>app/src/main/java/com/liflymark/normalschedule/logic/bean/OneByOneCourseBean.kt package com.liflymark.normalschedule.logic.bean import androidx.annotation.Keep import androidx.compose.ui.graphics.Color import com.liflymark.normalschedule.logic.Repository import com.liflymark.normalschedule.logic.utils.Convert.color /**课程表页面真正显示时拿到的类 * @param color 这是个历史遗留值,这个值是因为在显示班级课程时需要用到,我懒得修改代码所以没有移除它 * @param twoColorList 事实上它有三个item,第一个为纯色时的配色,第二、三个为它渐变色时的起止色 * * 如果你希望更改它,请特别小心 * * 同时它并不是一个好的写法,它同时调用了Repository和Convert单例类 */ @Keep data class OneByOneCourseBean( val courseName: String, val start: Int, val end: Int, val whichColumn: Int, val color: Color, val twoColorList: List<Color> = Repository.getDefaultString()[0].map { it.color } ) fun getData(): List<OneByOneCourseBean>{ return listOf( OneByOneCourseBean("点击右上角导入导入\n...\n...", 1, 2, 1, Color.Transparent) ) } ======================= File: app/src/main/java/com/liflymark/normalschedule/ui/tool_box/ToolBoxActivity.kt ======================= <gh_stars>1-10 package com.liflymark.normalschedule.ui.tool_box import android.os.Bundle import android.util.Log import android.webkit.WebSettings import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.material.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.PushPin import androidx.compose.runtime.* import androidx.compose.runtime.livedata.observeAsState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.viewmodel.compose.viewModel import androidx.navigation.NavController import com.liflymark.normalschedule.logic.model.Bulletin import com.liflymark.normalschedule.logic.utils.CustomWebView import com.liflymark.normalschedule.ui.score_detail.UiControl import com.liflymark.normalschedule.ui.sign_in_compose.NormalTopBar import com.liflymark.normalschedule.ui.theme.NorScTheme class ToolBoxActivity : ComponentActivity() { private val viewModel by lazy { ViewModelProvider(this).get(ToolBoxViewModel::class.java) } @OptIn(ExperimentalMaterialApi::class) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { // NorScTheme { // // A surface container using the 'background' color from the theme // Surface(color = MaterialTheme.colors.background) { // DevBoard("Android") // } // } UiControl() ToolBoxNavGraph() } } } /** * 开发者公告页面-总 */ @Composable fun DevBoard( navController: NavController, tbViewModel: ToolBoxViewModel = viewModel() ) { NorScTheme { // Column { // NormalTopBar(label = "工具箱"){ // navController.navigateUp() // } // DevBoardContent(tbViewModel) // } Log.d("DevBoard", "DevBoard重组一次") Scaffold( topBar = { NormalTopBar(label = "开发者公告") { navController.navigateUp() } }, content = { DevBoardContent(tbViewModel) } ) } } /** * 开发者公告页面-所有公告 */ @Composable fun DevBoardContent( tbViewModel: ToolBoxViewModel = viewModel() ) { val bulletins = tbViewModel.bulletinsLiveData.observeAsState(tbViewModel.initialBulletin) Column( Modifier .fillMaxSize() .verticalScroll(rememberScrollState()) ) { for (bulletin in bulletins.value.bulletin_list) { BulletinCard(bulletin) } } } /** * 开发者公告-单个公告 */ @Composable fun BulletinCard(singleBulletin: Bulletin) { // Card( // modifier = Modifier // .fillMaxWidth() // .padding(2.dp) // ) { // Column(modifier = Modifier.padding(2.dp)) { // Text(text = "标题:${singleBulletin.title}") // Text(text = "内容:${singleBulletin.content}") // Text(text = "日期:${singleBulletin.date}") // } // } BoardCard( modifier = Modifier .fillMaxWidth() .padding(2.dp) ) { Column(Modifier.padding(horizontal = 3.dp)) { Text(text = singleBulletin.title, style = MaterialTheme.typography.h6) Spacer(modifier = Modifier.height(5.dp)) Text(text = singleBulletin.content, style = MaterialTheme.typography.subtitle1) Spacer(modifier = Modifier.height(10.dp)) Text( text = "--${singleBulletin.date}", modifier = Modifier.fillMaxWidth(0.98f), textAlign = TextAlign.Right ) } } } @Composable fun HbuCalendar(navController: NavController) { Scaffold( topBar = { NormalTopBar(label = "河大校历") { navController.navigateUp() } }, content = { var rememberWebViewProgress by remember { mutableStateOf(-1) } Box { CustomWebView( modifier = Modifier.fillMaxSize(), url = "https://liflymark.top/tool/schoolcaledar", onProgressChange = { progress -> rememberWebViewProgress = progress }, initSettings = { settings -> settings?.apply { //支持js交互 javaScriptEnabled = true //将图片调整到适合webView的大小 useWideViewPort = true //缩放至屏幕的大小 loadWithOverviewMode = true //缩放操作 setSupportZoom(true) builtInZoomControls = true displayZoomControls = true //是否支持通过JS打开新窗口 javaScriptCanOpenWindowsAutomatically = true //不加载缓存内容 cacheMode = WebSettings.LOAD_NO_CACHE } } ) } LinearProgressIndicator( progress = rememberWebViewProgress * 1.0F / 100F, modifier = Modifier .fillMaxWidth() .height(if (rememberWebViewProgress == 100) 0.dp else 5.dp), color = Color.Red ) } ) } /** * 半圆角卡片 */ @Composable fun BoardCard( modifier: Modifier, contentAlignment: Alignment = Alignment.TopCenter, content: @Composable () -> Unit ) { Surface( modifier = modifier, shape = RoundedCornerShape(20.dp, 20.dp, 0.dp, 0.dp), color = MaterialTheme.colors.primary, ) { Column(Modifier.padding(0.dp, 3.dp, 0.dp, 0.dp)) { Row(Modifier.padding(5.dp)) { Icon(Icons.Default.PushPin, null) Spacer(modifier = Modifier.width(10.dp)) } Box(contentAlignment = contentAlignment) { content() } } } } /** * 半圆角卡片 */ @Composable fun FullCard( modifier: Modifier, contentAlignment: Alignment = Alignment.TopCenter, content: @Composable () -> Unit ) { Surface( modifier = modifier, color = MaterialTheme.colors.primary, shape = RoundedCornerShape(20.dp, 20.dp, 0.dp, 0.dp) ) { Column(Modifier.padding(0.dp, 3.dp, 0.dp, 0.dp)) { Row(Modifier.padding(5.dp)) { Icon(Icons.Default.PushPin, null) Spacer(modifier = Modifier.width(10.dp)) } Box(contentAlignment = contentAlignment) { content() } } } } /** * 上圆角页面 */ @Composable fun RoundedHeader(title: String) { Surface( modifier = Modifier .fillMaxWidth() .height(50.dp) .background(MaterialTheme.colors.primary), elevation = 0.5.dp, shape = RoundedCornerShape(50, 50, 0, 0) ) { val padding = 16.dp Text( text = title, modifier = Modifier.padding(start = padding, top = padding, end = padding), style = MaterialTheme.typography.h6 ) } } /** * 等待开发的界面 */ @Composable fun WaitTime(navController: NavController) { Scaffold( topBar = { NormalTopBar(label = "敬请期待") { navController.navigateUp() } }, content = { Text(text = "开发者玩命完善中......") } ) } @Preview(showBackground = true) @Composable fun DefaultPreview8() { NorScTheme { SchoolBusCard() } } ======================= File: app/src/main/java/com/liflymark/normalschedule/ui/class_course/ClassCourseViewModel.kt ======================= package com.liflymark.normalschedule.ui.class_course import androidx.lifecycle.* import com.liflymark.normalschedule.logic.Repository import com.liflymark.normalschedule.logic.bean.OneByOneCourseBean import com.liflymark.normalschedule.logic.bean.getData import com.liflymark.normalschedule.ui.show_timetable.getNeededClassList import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch class ClassCourseViewModel:ViewModel() { private val putMajor = MutableLiveData<List<String>>() private val loadBean = MutableLiveData<List<String>>() val classCourseListLiveData = Transformations.switchMap(putMajor){ Repository.loadCourseByMajor2(it[0], it[1]).asLiveData() } val classBeanLiveData = Transformations.switchMap(loadBean){ Repository.loadCourseByMajorToAll(it[0], it[1]).asLiveData() } val departmentListFlow = Repository.getDepartmentList() // fun putDepartmentAndMajor(department:String, major: String)= // Repository.loadCourseByMajor(department, major).map { // if (it.isSuccess){ // it.getOrElse { getNeededClassList(getData()) } // } // // } fun putDepartmentAndMajor(department:String, major: String){ putMajor.value = listOf(department, major.replace(".json","")) } fun putDepartmentAndMajorBean(department:String, major: String){ loadBean.value = listOf(department, major.replace(".json","")) } fun saveAccount(){ Repository.saveAccount("", "") } fun getAccount(){ viewModelScope.launch { } } } ======================= File: app/src/main/java/com/liflymark/normalschedule/ui/tool_box/SchoolCalendar.kt ======================= <gh_stars>1-10 package com.liflymark.normalschedule.ui.tool_box import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Surface import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp @Composable fun SingleDayCircle(){ Surface( shape = RoundedCornerShape(10) ) { // Just a fake data... a Pair of Int and String val tableData = (1..100).mapIndexed { index, item -> index to "Item $index" } // Each cell of a column must have the same weight. val column1Weight =.3f // 30% val column2Weight =.7f // 70% // The LazyColumn will be our table. Notice the use of the weights below LazyColumn( Modifier .fillMaxSize() .padding(16.dp)) { // Here is the header item { Column(Modifier.background(Color.Gray)) { } } // Here are all the lines of your table. items(tableData) { val (id, text) = it Row(Modifier.fillMaxWidth()) { } } } } } @Composable fun RowScope.RowCell( text: String, weight: Float ) { Text( text = text, modifier = Modifier .border(1.dp, Color.Black) .weight(weight) .padding(8.dp) ) } @Composable fun ColumnScope.ColumnCell( text: String, weight: Float ){ Text( text = text, modifier = Modifier .border(1.dp, Color.Black) .weight(weight) .padding(8.dp) ) } @Preview(showBackground = true, showSystemUi = true) @Composable fun CalendarPreview(){ SingleDayCircle() } ======================= File: app/src/main/java/com/liflymark/normalschedule/ui/import_course/ImportLoginFragment.kt ======================= package com.liflymark.normalschedule.ui.import_course import android.content.Intent import android.graphics.Color import android.os.Bundle import android.text.SpannableStringBuilder import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import com.gyf.immersionbar.ImmersionBar import com.liflymark.normalschedule.MainActivity import com.liflymark.normalschedule.databinding.FragmentImportLoginBinding import com.liflymark.normalschedule.logic.Repository import com.liflymark.normalschedule.logic.model.AllCourse import com.liflymark.normalschedule.logic.utils.Convert import com.liflymark.normalschedule.logic.utils.Dialog import com.liflymark.normalschedule.logic.utils.RomUtil import com.liflymark.normalschedule.ui.class_course.ClassCourseActivity import com.liflymark.normalschedule.ui.graduate_import.GraduateImportActivity import com.liflymark.normalschedule.ui.import_again.ImportCourseAgain import com.liflymark.normalschedule.ui.show_timetable.ShowTimetableActivity2 import es.dmoral.toasty.Toasty class ImportLoginFragment: Fragment() { private val viewModel by lazy { ViewModelProvider(this).get(CourseViewModel::class.java) } private var _binding: FragmentImportLoginBinding? = null private val binding get() = _binding!! var userName = "" var userPassword = "" private var id = "" override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentImportLoginBinding.inflate(inflater, container, false) return binding.root // return inflater.inflate(R.layout.fragment_import_login, container, false) } override fun onDestroyView() { super.onDestroyView() _binding = null } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) ImmersionBar.with(this).init() val waitDialog by lazy { activity?.let { it1 -> Dialog.getProgressDialog(it1) } } if (viewModel.isAccountSaved()){ // val intent = Intent(context, ImportScoreActivity::class.java).apply { // putExtra("isSaved", true) // } val intent = Intent(context, ShowTimetableActivity2::class.java).apply{ putExtra("isSaved", true) } startActivity(intent) activity?.finish() return } // 如果是不是VIVO系统更改名称 if (!RomUtil.isVivo){ binding.tvTitle.text = "登陆HBU教务系统" } if (activity is ImportCourseAgain){ viewModel.accountLiveData.observe(viewLifecycleOwner){ binding.user.text = SpannableStringBuilder(it[0]) binding.password.text = SpannableStringBuilder(it[1]) } viewModel.getAccount() } binding.selectSignMethod.attachDataSource(listOf("统一认证", "URP登陆")) binding.selectSignMethod.setOnSpinnerItemSelectedListener { parent, view, position, id -> when(position){ 0 -> { binding.inputCode.visibility = View.INVISIBLE binding.rlCode.visibility = View.INVISIBLE binding.tipsText.visibility = View.VISIBLE binding.etCode.setText("") } 1 -> { binding.inputCode.visibility = View.VISIBLE binding.rlCode.visibility = View.VISIBLE binding.tipsText.visibility = View.INVISIBLE } } } viewModel.getId()// 获取cookie viewModel.idLiveData.observe(viewLifecycleOwner, { result -> if (result == null || result.id == "") { binding.serverStatus.text = "目前可能仅允许“统一认证”登陆,如失败请尝试班级导入" binding.selectSignMethod.attachDataSource(listOf("统一认证")) id = "" binding.serverStatus.setTextColor(Color.RED) } else { this.id = result.id binding.serverStatus.text = "服务器正常" } }) viewModel.courseLiveData.observe(viewLifecycleOwner, Observer { result -> if (result == null) { activity?.let { Toasty.error(it, "登陆异常,重启app试试", Toasty.LENGTH_SHORT).show() } waitDialog?.dismiss() } else { val allCourseList = result.allCourse when (result.status) { "yes" -> { saveAccount() activity?.let { Toasty.success(it, "登陆成功,解析成功", Toasty.LENGTH_SHORT).show() } // viewModel.insertOriginalCourse(allCourseList) // for (singleCourse in allCourseList) { // Log.d("ImportLoginFragment", singleCourse.toString()) // } if (activity is MainActivity) { val intent = Intent(context, ShowTimetableActivity2::class.java).apply { putExtra("isSaved", false) putExtra("courseList", Convert.allCourseToJson(allCourseList)) putExtra("user", userName) putExtra("password", <PASSWORD>) } startActivity(intent) activity?.finish() } if (activity is ImportCourseAgain) { val intent = Intent(context, ShowTimetableActivity2::class.java).apply { putExtra("isSaved", false) putExtra("courseList", Convert.allCourseToJson(allCourseList)) putExtra("user", userName) putExtra("password", <PASSWORD>) } startActivity(intent) activity?.finish() } // viewModel.saveAccount(userName, userPassword) } "no" -> { activity?.let { Toasty.error( it, "登陆成功,解析异常,请务必检查课程表是否正确", Toasty.LENGTH_LONG ).show() } if (activity is MainActivity) { val intent = Intent(context, ShowTimetableActivity2::class.java).apply { putExtra("isSaved", false) putExtra("courseList", Convert.allCourseToJson(allCourseList)) putExtra("user", userName) putExtra("password", <PASSWORD>) } startActivity(intent) activity?.finish() } // viewModel.saveAccount(userName, userPassword) } else -> { activity?.let { Toasty.error(it, result.status, Toasty.LENGTH_SHORT).show() } viewModel.getImage(id) waitDialog?.dismiss() } } } }) viewModel.courseNewLiveData.observe(viewLifecycleOwner, Observer { result -> if (result == null) { activity?.let { Toasty.error(it, "登陆异常,将返回主界面", Toasty.LENGTH_SHORT).show() } waitDialog?.dismiss() Repository.saveLogin() val intent = Intent(context, ShowTimetableActivity2::class.java).apply{ putExtra("isSaved", true) } startActivity(intent) activity?.finish() } else { val allCourseList = result.allCourse when (result.status) { "yes" -> { saveAccount() activity?.let { Toasty.success(it, "登陆成功,解析成功", Toasty.LENGTH_SHORT).show() } // viewModel.insertOriginalCourse(allCourseList) // for (singleCourse in allCourseList) { // Log.d("ImportLoginFragment", singleCourse.toString()) // } if (activity is MainActivity) { val intent = Intent(context, ShowTimetableActivity2::class.java).apply { putExtra("isSaved", false) putExtra("courseList", Convert.allCourseToJson(allCourseList)) putExtra("user", userName) putExtra("password", <PASSWORD>) } startActivity(intent) activity?.finish() } if (activity is ImportCourseAgain) { val intent = Intent(context, ShowTimetableActivity2::class.java).apply { putExtra("isSaved", false) putExtra("courseList", Convert.allCourseToJson(allCourseList)) putExtra("user", userName) putExtra("password", <PASSWORD>) } startActivity(intent) activity?.finish() } // viewModel.saveAccount(userName, userPassword) } "no" -> { activity?.let { Toasty.error( it, "登陆成功,解析异常,请务必检查课程表是否正确", Toasty.LENGTH_LONG ).show() } if (activity is MainActivity) { val intent = Intent(context, ShowTimetableActivity2::class.java).apply { putExtra("isSaved", false) putExtra("courseList", Convert.allCourseToJson(allCourseList)) putExtra("user", userName) putExtra("password", <PASSWORD>) } startActivity(intent) activity?.finish() } // viewModel.saveAccount(userName, userPassword) } else -> { activity?.let { Toasty.error(it, result.status, Toasty.LENGTH_SHORT).show() } waitDialog?.dismiss() } } } }) viewModel.courseVisitLiveData.observe(viewLifecycleOwner, { result -> val course = result.getOrNull() if (course == null) { val allCourseList = listOf( AllCourse( "五四路", 1, 1, "<PASSWORD>", 2, "点击右上角导入课程", "", "" ) ) val intent = Intent(context, ShowTimetableActivity2::class.java).apply { putExtra("isSaved", true) putExtra("courseList", Convert.allCourseToJson(allCourseList)) putExtra("user", userName) putExtra("password", <PASSWORD>) } startActivity(intent) activity?.finish() } else { val allCourseList = course.allCourse val intent = Intent(context, ShowTimetableActivity2::class.java).apply { putExtra("isSaved", false) putExtra("courseList", Convert.allCourseToJson(allCourseList)) putExtra("user", userName) putExtra("password", <PASSWORD>) } startActivity(intent) activity?.finish() } }) viewModel.imageLiveData.observe(viewLifecycleOwner, { binding.ivCode.visibility = View.VISIBLE binding.progressBar.visibility = View.INVISIBLE if (it!= null) binding.ivCode.setImageBitmap(it) }) binding.ivCode.setOnClickListener { binding.progressBar.visibility = View.VISIBLE viewModel.getImage(id) } binding.btnSign.setOnClickListener { // 判断是否输入学号密码并提交数据至ViewModel层以更新数据 userName = binding.user.text.toString() userPassword = binding.password.text.toString() waitDialog?.show() // dialog.Content() // dialog.showDialog.value = true val yzm = binding.etCode.text.toString() when { !binding.agreeOrNot.isChecked -> activity?.let { it1 -> Toasty.warning(it1, "您未同意用户协议", Toasty.LENGTH_SHORT).show() waitDialog?.dismiss() } userName == "" -> activity?.let { it1 -> Toasty.warning(it1, "请输入学号", Toasty.LENGTH_SHORT).show() waitDialog?.dismiss() } userPassword == "" -> activity?.let { it1 -> Toasty.warning(it1, "请输入密码", Toasty.LENGTH_SHORT).show() waitDialog?.dismiss() } id == "" -> { viewModel.putValue(userName, userPassword) } else -> viewModel.putValue(userName, userPassword, yzm, id) } } binding.btnSignByGraduate.setOnClickListener { if (binding.agreeOrNot.isChecked){ val intent = Intent(context, GraduateImportActivity::class.java) startActivity(intent) activity?.finish() }else{ context?.let { it1 -> Toasty.warning(it1, "您未同意用户协议", Toasty.LENGTH_SHORT).show() } waitDialog?.dismiss() } } val contractDialog = Dialog.getContractDialog( requireContext(), yes = { // 检测VIVO 如果是VIVO则直接跳过导入 if (RomUtil.isVivo && activity is MainActivity){ Log.d("ImportLogin", "VIVO手机") viewModel.saveAccount("visit", "visit") val allCourseList = listOf( AllCourse( "五四路", 1, 1, "111111111111111111111111", 2, "点击右上角导入课程", "", "" ) ) val intent = Intent(context, ShowTimetableActivity2::class.java).apply { putExtra("isSaved", false) putExtra("courseList", Convert.allCourseToJson(allCourseList)) } startActivity(intent) activity?.finish() } else { Toasty.info(requireContext(), "请点击登陆按钮上方的复选框以再次确认").show() } }, no = { activity?.finish() } ) val userContractDialog = Dialog.getUerContract( requireContext(), yes = { Toasty.info(requireContext(), "请点击登陆按钮上方的复选框以再次确认").show() }, no = { activity?.finish() } ) contractDialog.show() binding.contact.setOnClickListener { contractDialog.show() } binding.userContact.setOnClickListener { userContractDialog.show() } binding.btnSignByClass.setOnClickListener { val intent = Intent(context,ClassCourseActivity::class.java).apply { putExtra("allowImport", true) } if(binding.agreeOrNot.isChecked) { activity?.let { it1 -> startActivity(intent) it1.finish() } } else { activity?.let { it1 -> Toasty.info(it1,"您没有同意用户协议").show() } } } binding.btnSignByVisitor.setOnClickListener { if(binding.agreeOrNot.isChecked) { viewModel.putValue() viewModel.saveAccount("visit", "visit") } else { activity?.let { it1 -> Toasty.info(it1,"您没有同意用户协议").show() } } } } private fun saveAccount() { userName = binding.user.text.toString() userPassword = binding.password.text.toString() viewModel.saveAccount(userName, userPassword) } } ======================= File: app/src/main/java/com/liflymark/normalschedule/logic/dao/AccountDao.kt ======================= <gh_stars>1-10 package com.liflymark.normalschedule.logic.dao import android.content.Context import androidx.core.content.edit import androidx.security.crypto.EncryptedSharedPreferences import androidx.security.crypto.MasterKey import com.liflymark.normalschedule.NormalScheduleApplication object AccountDao { private const val sharedPrefsFile = "userAccount" private val mainKey = MasterKey.Builder(NormalScheduleApplication.context) .setKeyScheme(MasterKey.KeyScheme.AES256_GCM) .build() fun saveAccount(user: String, password: String){ with (pwSharedPreferences().edit()) { putString("passwordEncrypt", password) apply() } with(normalSharePreferences().edit()) { putString("userYes", user) putBoolean("loginOrNot", true) commit() } } fun saveLogin(){ with(normalSharePreferences().edit()) { putBoolean("loginOrNot", true) apply() } } fun getSavedAccount(): Map<String, String> { val user = normalSharePreferences().getString("userYes", "")!! val password = pwSharedPreferences().getString("passwordEncrypt", "")!! return mapOf("user" to user, "password" to password) } fun isAccountSaved() = normalSharePreferences().getBoolean("loginOrNot", false) fun newUserShowed(){ normalSharePreferences().edit(){ putInt("version", 1) commit() } } fun getNewUserOrNot(): Boolean { val userVersion = normalSharePreferences().getInt("version", 0) return userVersion < 1 } fun importedAgain(){ with(normalSharePreferences().edit()) { putBoolean("loginOrNot", false) commit() } } // private fun sharedPreferences() = NormalScheduleApplication.context.getSharedPreferences("normal_schedule", Context.MODE_PRIVATE) private fun pwSharedPreferences() = EncryptedSharedPreferences.create( NormalScheduleApplication.context, sharedPrefsFile, mainKey, EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV, EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM ) private fun normalSharePreferences() = NormalScheduleApplication.context.getSharedPreferences("normal_schedule", Context.MODE_PRIVATE) } ======================= File: app/src/main/java/com/liflymark/normalschedule/ui/app_widget_week/WeekAppwidgetReceiver.kt ======================= <filename>app/src/main/java/com/liflymark/normalschedule/ui/app_widget_week/WeekAppwidgetReceiver.kt<gh_stars>1-10 package com.liflymark.normalschedule.ui.app_widget_week import android.content.Context import android.content.Intent import androidx.glance.appwidget.GlanceAppWidget import androidx.glance.appwidget.GlanceAppWidgetReceiver import com.liflymark.normalschedule.logic.Repository class WeekAppwidgetReceiver:GlanceAppWidgetReceiver() { override val glanceAppWidget: GlanceAppWidget = WeekAppwidgetAppwidget() } ======================= File: app/src/main/java/com/liflymark/normalschedule/ui/settings/SettingsNavHost.kt ======================= <filename>app/src/main/java/com/liflymark/normalschedule/ui/settings/SettingsNavHost.kt package com.liflymark.normalschedule.ui.settings import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.navigation.NavHostController import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController @Composable fun SettingsNavHost( modifier: Modifier = Modifier, navController: NavHostController = rememberNavController(), startDestination: String = "mainSettings", ){ NavHost( navController = navController, startDestination = startDestination, modifier = modifier ) { composable(route = "mainSettings"){ SettingsMainPage(navController = navController) } composable(route = "courseCardSettings"){ SettingsCardPage(navController = navController) } } } ======================= File: app/src/main/java/com/liflymark/normalschedule/MainActivity.kt ======================= package com.liflymark.normalschedule import android.content.res.Configuration import android.content.res.Resources import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.gyf.immersionbar.ImmersionBar import com.liflymark.normalschedule.ui.abase.BaseActivity class MainActivity : BaseActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) ImmersionBar.with(this).init() setContentView(R.layout.activity_main) } override fun getResources(): Resources { val res = super.getResources() if (res.configuration.fontScale!= 1f) { //非默认值 val newConfig = Configuration() newConfig.setToDefaults() //设置默认 res.updateConfiguration(newConfig, res.displayMetrics) } return res } } ======================= File: app/src/main/java/com/liflymark/normalschedule/ui/work_book/AllCourseWork.kt ======================= package com.liflymark.normalschedule.ui.work_book import androidx.compose.foundation.background import androidx.compose.foundation.gestures.scrollable import androidx.compose.foundation.layout.* import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Book import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.key import androidx.compose.runtime.livedata.observeAsState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.lifecycle.viewmodel.compose.viewModel import androidx.navigation.NavController import com.google.accompanist.flowlayout.FlowColumn import com.google.accompanist.flowlayout.FlowMainAxisAlignment import com.google.accompanist.flowlayout.FlowRow import com.liflymark.normalschedule.ui.score_detail.UiControl import com.liflymark.normalschedule.ui.sign_in_compose.NormalTopBar import com.liflymark.normalschedule.ui.theme.NorScTheme @ExperimentalMaterialApi @Composable fun AllCourseBook(navController: NavController){ NorScTheme { UiControl() Scaffold( topBar = { NormalTopBar(label = "作业本") }, content = { ContentAllBook(navController) } ) } } @ExperimentalMaterialApi @Composable fun ContentAllBook( navController: NavController, wbViewModel: WorkBookViewModel = viewModel() ){ val courseNameList = wbViewModel.courseNameListFLow .collectAsState(initial = wbViewModel.initCourseName) FlowRow( modifier = Modifier .fillMaxSize() .verticalScroll(rememberScrollState()) .padding(top = 10.dp), mainAxisAlignment = FlowMainAxisAlignment.Center, mainAxisSpacing = 20.dp, crossAxisSpacing = 20.dp ) { for (courseName in courseNameList.value){ key(courseName){ SingleBookButton(courseName = courseName){ navController.navigate("singleCourse/$courseName") } } } if (courseNameList.value.isEmpty()){ Text( text = "你还没有添加作业\n" + "点击课表主界面的课程格子\n" + "->点击弹窗右下角按钮\n" + "->添加作业", modifier = Modifier.fillMaxWidth(), textAlign = TextAlign.Center ) } } } @ExperimentalMaterialApi @Composable fun SingleBookButton( courseName:String, onClick:(courseName:String)->Unit ){ Card( backgroundColor = Color.Transparent, contentColor = Color.White, modifier = Modifier .width(148.51.dp) .height(210.dp), onClick = { onClick(courseName) } ) { BrushBackground() Column( horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center, modifier = Modifier.padding(5.dp) ) { Text( text = courseName, style = MaterialTheme.typography.h5, textAlign = TextAlign.Center ) Spacer(modifier = Modifier.height(20.dp)) Row( verticalAlignment = Alignment.CenterVertically ) { Icon( Icons.Default.Book, null, ) Text(text = "作业本") } } } } @Composable fun BrushBackground(){ val backgroundColor = listOf( listOf(Color(0xFF5EFCE8), Color(0xFF736EFE)), listOf(Color(0xFFC2FFD8), Color(0xFF465EFB)), listOf(Color(0xFF2AFADF), Color(0xFF4C83FF)) ) Spacer( modifier = Modifier .background( brush = Brush.linearGradient( colors = backgroundColor[2] ) ) .fillMaxSize() ) } //@ExperimentalMaterialApi //@Preview(showBackground = true) //@Composable //fun DefaultPreview2() { // NorScTheme { // ContentAllBook() // } //} @ExperimentalMaterialApi @Preview(showBackground = true) @Composable fun DefaultPreviewNight() { NorScTheme(darkTheme = true) { SingleBookButton("药用高分子材料学"){} } } ======================= File: app/src/main/java/com/liflymark/normalschedule/logic/model/SpaceLoginResponse.kt ======================= package com.liflymark.normalschedule.logic.model import androidx.annotation.Keep @Keep data class SpaceLoginResponse( var result: String ) ======================= File: app/src/main/java/com/liflymark/normalschedule/ui/show_timetable/ShowTimetableViewModel.kt ======================= package com.liflymark.normalschedule.ui.show_timetable import android.content.pm.PackageManager import android.os.Build import android.util.Log import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateOf import androidx.compose.ui.layout.LayoutCoordinates import androidx.lifecycle.* import com.liflymark.normalschedule.NormalScheduleApplication import com.liflymark.normalschedule.logic.Repository import com.liflymark.normalschedule.logic.bean.Bulletin2 import com.liflymark.normalschedule.logic.bean.CourseBean import com.liflymark.normalschedule.logic.model.AllCourse import com.liflymark.normalschedule.logic.utils.Convert import com.liflymark.normalschedule.logic.utils.GetDataUtil import com.liflymark.normalschedule.logic.utils.LayoutCoordinatesAndDescription import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking class ShowTimetableViewModel: ViewModel() { private var courseDatabaseLiveData = MutableLiveData(0) private var backgroundId = MutableLiveData(0) private var needDeleteCourseNameLiveData = MutableLiveData<String>() private var _sentenceLiveDate = MutableLiveData<Boolean>(false) var shouldSaved = true val layoutList = mutableStateListOf<LayoutCoordinatesAndDescription>() val showUserGuide = mutableStateOf<Boolean>(false) var showToast = 0 val newUserFLow = Repository.getNewUserOrNot() val userVersion = Repository.getUserVersion() val courseDatabaseLiveDataVal = Transformations.switchMap(courseDatabaseLiveData) { runBlocking { val colorItems = Repository.getColorListAsync() Repository.loadAllCourse2(colorList = Repository.colorListSettingToStringList(colorItems)) } } val backgroundUriStringLiveData = Transformations.switchMap(backgroundId){ Repository.loadBackground() } val deleteCourseBeanByNameLiveData = Transformations.switchMap(needDeleteCourseNameLiveData){ needDeleteCourseNameLiveData.value?.let { it1 -> Repository.deleteCourseByName(it1) } } val sentenceLiveData = Transformations.switchMap(_sentenceLiveDate){ Repository.getSentences(it).asLiveData() } val settingsLiveData = Repository.getScheduleSettings().asLiveData() val showStartBulletin2 = mutableStateOf<Bulletin2?>(null) init { viewModelScope.launch { val pm: PackageManager = NormalScheduleApplication.context.packageManager val packageName = NormalScheduleApplication.context.packageName val pi = pm.getPackageInfo(packageName, 0) val versionCode = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { pi.longVersionCode } else { pi.versionCode }.toInt() showStartBulletin2.value = Repository.getNewStartBulletin2(versionCode) } } fun loadAllCourse() { courseDatabaseLiveData.value = courseDatabaseLiveData.value?.plus(1) Log.d("ShowTimetable", "loadAllCourse执行") } fun deleteCourse(courseItem:String){ needDeleteCourseNameLiveData.value = courseItem } fun setBackground(){ Log.d("ShowViewModel", "setback") backgroundId.value = backgroundId.value?.plus(1) } suspend fun insertOriginalCourse(allCourseList: List<AllCourse>) { Log.d("CourseViewModel", "获取到课程") Repository.insertCourse2(allCourseList) } suspend fun deleteAllCourse(){ Repository.deleteAllCourseBean2() } fun mergeClass(className: String, classDay: Int, classSessions: Int, continuingSession: Int, buildingName: String){ viewModelScope.launch { var classWeekResult = Integer.parseInt("000000000000000000000000", 2) var teacher = "" val classList = Repository.loadCourseUnTeacher(className, classDay, classSessions, continuingSession, buildingName) for (singleBean in classList){ val singleBeanWeek = Integer.parseInt(singleBean.classWeek,2) classWeekResult = singleBeanWeek or classWeekResult teacher += "${singleBean.teacher} " } var classWeekResultStr = Integer.toBinaryString(classWeekResult) val length = classWeekResultStr.length if (classWeekResultStr.length < 24){ repeat(24-length){ classWeekResultStr = "0$classWeekResultStr" } } val newBean = CourseBean( campusName = "河北大学", classDay = classDay, classSessions = classSessions, classWeek = classWeekResultStr, continuingSession = continuingSession, courseName = className, teacher = teacher, teachingBuildName = buildingName, color = Convert.stringToColor(className) ) if (Integer.parseInt("000000000000000000000000", 2)!=classWeekResult) { Repository.insertCourse(newBean) Repository.deleteCourseByList(classList) // loadAllCourse() } } } fun fetchSentence(force:Boolean = false) { _sentenceLiveDate.value = force } fun getNowWeek(): Int{ return GetDataUtil.whichWeekNow() } fun startSchool(): Boolean{ return GetDataUtil.startSchool() } fun startSchoolDay(): Int{ return GetDataUtil.startSchoolDay() } fun startHoliday(): Boolean{ return GetDataUtil.whichWeekNow() >= 19 } fun putPosition( index:Int, layout:LayoutCoordinates, description:String ){ val hadIndex = layoutList.map { it.index } if (index in hadIndex){ return } layoutList.add( LayoutCoordinatesAndDescription( index = index, layout = layout, description = description ) ) } // size=4 为需要提示的个数,防止页面没有渲染完毕就显示 fun checkShowUserGuide(){ Log.d("ShowViewmodel", "layout"+layoutList.size.toString()) if (layoutList.size==4){ viewModelScope.launch { if (Repository.getUserVersionS() < 4) { showUserGuide.value = true } } } } } ======================= File: app/src/main/java/com/liflymark/normalschedule/logic/utils/Dialog.kt ======================= package com.liflymark.normalschedule.logic.utils import android.annotation.SuppressLint import android.content.Context import android.util.Log import android.widget.TextView import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.CornerBasedShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.material.* import androidx.compose.runtime.* import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.ui.Alignment import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalFocusManager import androidx.compose.ui.platform.LocalSoftwareKeyboardController import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.compose.ui.window.Dialog import androidx.compose.ui.window.DialogProperties import com.afollestad.materialdialogs.MaterialDialog import com.afollestad.materialdialogs.color.colorChooser import com.afollestad.materialdialogs.customview.customView import com.afollestad.materialdialogs.customview.getCustomView import com.google.accompanist.flowlayout.FlowRow import com.google.accompanist.pager.ExperimentalPagerApi import com.google.accompanist.pager.rememberPagerState import com.liflymark.normalschedule.R import com.liflymark.normalschedule.logic.utils.text_field.BackgroundTransparentTextFiled import kotlinx.coroutines.launch import java.util.* object Dialog { fun getContractDialog( _context: Context, yes:() -> Unit = {}, no:() -> Unit = {}, ): MaterialDialog { val dialog = MaterialDialog(_context) .title(text = "APP隐私政策") .message(text = "发布时间:2021年8月21日\n更新时间:2022年3月8日\n本应用尊重并保护所有使用服务用户的个人隐私权。为了给您提供更准确、更有个性化的服务,本应用会按照本隐私权政策的规定使用和披露您的个人信息。但本应用将以高度的勤勉、审慎义务对待这些信息。除本隐私权政策另有规定外,在未征得您事先许可的情况下,本应用不会将这些信息对外披露或向第三方提供。本应用会不时更新本隐私权政策。 您在同意本应用服务使用协议之时,即视为您已经同意本隐私权政策全部内容。本隐私权政策属于本应用服务使用协议不可分割的一部分。 " + "确保用户充分理解本协议中各条款,请审慎阅读并选择接受或不接受本协议。" + "同意并点击确认本协议条款,才能成为本APP用户,并享受各类服务。登录、使用等行为将视为对本协议的接受,并同意接受本协议各项条款的约束。" + "若不同意本协议,或对本协议中的条款存在任何疑问,请立即停止使用该程序,并可以选择不使用APP服务。\n\n" + "1. 适用范围\n" + "(a) 在使用应用时,您提交的账号、密码、班级、课程信息、成绩信息。\n" + "(b) 在您使用本应用网络服务,或访问本应用平台网页时,本应用自动接收并记录的您的浏览器和计算机上的信息,包括但不限于您的IP地址、浏览器的类型、使用的语言、访问日期和时间、软硬件特征信息及您需求的网页记录等数据; \n\n" + "2. 信息存储和交换 \n" + "本应用会在本地,加密存储您的密码,且其他应用无法通过常规手段访问。网络端不会记录您的密码。虽然有上述安全措施,仍然建议用户不要安装未知安全性的APP。\n" + "\n" + "在您使用登陆导入课表或其他需要登陆情况时,会将账号密码提交至服务器,服务器不会记录你的除" + "学号以外的任何信息(如密码、课程表内容、姓名、专业),记录学号仅用于统计本应用用户数,开发者无从得知学号对应的密码、" + "姓名等其他任何信息。虽然网络通信已加密,但仍然建议用户不要使用未知安全性的网络。\n" + "\n" + "3.账号注销\n"+ "(a)若需注销账号请将学号和一卡通学号面(除学号外均可打码)邮件至<EMAIL>,开发者将在48小时之内处理,注销后的账号无法在此APP登陆。\n"+ " 4.敏感权限清单 \n" + "(a)外部存储权限:用于在更换背景时读取设备中的图片\n" + "(b)日历日程增加和删除:用于导入和更新考试安排至日历日程\n" + "(c)联网权限:用于导入课表、查询成绩、查询空教室等基础\n"+ "5.本隐私政策的更改 \n" + "(a)如果决定更改隐私政策,我们会在本政策中、网站中以及我们认为适当的位置发布这些更改,以便您了解我们如何收集、使用您的个人信息,哪些人可以访问这些信息,以及在什么情况下我们会透露这些信息。 \n" + "(b)本人保留随时修改本政策的权利,因此请经常查看。\n\n" + "6.APP运营方信息\n"+ "运营者姓名:李飞;\n 邮箱:<EMAIL>\n办公地址:河北省沧州市献县商业局小区;\n\n用户隐私信息保护负责人电话:15511777580\n开发者名称:考试不挂科(献县)科技发展技术服务中心"+ "\n著作权归APP运营者所有。") .positiveButton(text = "已阅读并同意"){ yes() } .negativeButton(text = "拒绝并停止使用"){ no() } return dialog } fun getUerContract( _context: Context, yes:() -> Unit = {}, no:() -> Unit = {}, ): MaterialDialog{ val dialog = MaterialDialog(_context) .title(text = "用户协议") .message(text = "(a)本应用在导入课表时会模拟您登陆教务系统的操作,如果您错误次数过多造成无法登陆开发者概不负责。 \n" + "(b)开发者会尽量保证您的课表、成绩等信息正确但不做出任何绝对正确的承诺,请在使用前仔细检查,如有必要请自行登陆相关网站进行核实。因为信息不准确造成的不良后果(如挂科、旷课)开发者概不负责。\n" + "(c)开发者保留随时修改本用户协议的权利,因此请经常查看。" ) .positiveButton(text = "已阅读并同意"){ yes() } .negativeButton(text = "拒绝并停止使用"){ no() } return dialog } fun getImportAgain(_context: Context): MaterialDialog{ val dialog = MaterialDialog(_context) .title(text ="请谨慎使用此功能") .message(text = "即将进入重新导入界面,需要将清除当前课表") .positiveButton(text = "清空当前课表") .negativeButton(text = "取消") return dialog } // fun getSelectWeekAndSection(_context: Context) { // val allWeek = listOf("周一","周二","周三","周四","周五","周六","周日",) // val startSection = mutableListOf<String>() // val endSection = mutableListOf<String>() // for (i in 1..11){ // startSection.add("第 $i 节") // endSection.add("第 $i 节") // } // val dialog = OptionsPickerBuilder(_context, OnOptionsSelectListener{ week, startSection_, endSection_, _ -> // if (_context is AddCourseActivity){ // _context.setClassWeek(week, startSection_, endSection_) // } // }) // .setTitleText("选择时间") // .setCyclic(true, false, false) // .isDialog(true) // .setSubmitColor(R.color.purple_500) // .setCancelColor(R.color.purple_500) // .setTitleBgColor(0xFF666666.toInt()) // .build<Any>() // dialog.setNPicker(allWeek, startSection.toList(), endSection.toList()) // dialog.show() // } fun getProgressDialog(_context: Context): MaterialDialog { val dialog = MaterialDialog(_context).customView(R.layout.dialog_progress) dialog.apply { cancelable(true) cancelOnTouchOutside(false) } return dialog } fun getProgressDialog(_context: Context, text:String): MaterialDialog { val dialog = MaterialDialog(_context).customView(R.layout.dialog_progress) val textView = dialog.getCustomView().findViewById<TextView>(R.id.progress_text) textView.text = text dialog.apply { cancelable(true) cancelOnTouchOutside(false) } return dialog } fun String.whichIs1(): List<Int>{ val oneList = mutableListOf<Int>() for (i in this.indices){ when(this[i].toString()){ "1" -> oneList.add(i + 1) } } if(oneList.size==0){ oneList.add(0) } return oneList } fun getWeekNumFormat(oneList: List<Int>): String { var courseTimeFormat = "第" val type: Int if (oneList.last()-oneList.first() == oneList.size-1){ type = 0 } else { // for (i in oneList){ // if (i % 2 == 1){ // type = 1 // } else if (type == 1){ // type = 2 // } // } val singleSize = oneList.filter { it%2 == 0 }.size val doubleSize = oneList.filter { (it+1)%2 == 0 }.size type = if (singleSize==oneList.size || doubleSize==oneList.size){ 1 } else { 2 } } when (type){ 0 -> { courseTimeFormat += " ${oneList.first()} - ${oneList.last()} 周" } 1 -> { courseTimeFormat += if (oneList.first() % 2 == 1) { "${oneList.first()} - ${oneList.last()} 单周" } else { "${oneList.first()} - ${oneList.last()} 双周" } } 2 -> { for (i in oneList) { courseTimeFormat += "$i," } courseTimeFormat += "周" } } return courseTimeFormat } @SuppressLint("CheckResult") fun getColorPickerDialog( context: Context, colors: IntArray, onResult:(dialog:MaterialDialog, color:Int) -> Unit, ):MaterialDialog { return MaterialDialog(context).apply { title(text="选择颜色") colorChooser(colors) { dialog, color -> onResult(dialog, color) } positiveButton(text="确定") } } } @Composable fun SelectWeekDialog(showDialog: MutableState<Boolean>,maxWeekNum:Int = 19, initialR:String, block:(String)->Unit){ val result = remember { mutableStateOf(initialR) } if (showDialog.value) { AlertDialog( onDismissRequest = { showDialog.value = false }, title = { Text(text = "选择周数") }, text = { SelectContent(maxWeekNum = maxWeekNum,initialR = initialR){ result.value = it } }, confirmButton = {}, dismissButton = { TextButton(onClick = { showDialog.value = false block(result.value) }) { Text(text = "确定") } } ) } } @Composable fun SelectContent( maxWeekNum: Int = 19, //原则上不得大于24 initialR: String = "0000000000000000000000000", resultR:(res:String)->Unit ){ val initialList = initialR.split("").toMutableList() val selectList = remember { mutableStateListOf<String>() } initialList.removeFirst() initialList.removeLast() selectList.addAll(initialList) Log.d("Dialog","清空一次$initialList") Column { FlowRow(modifier = Modifier.fillMaxWidth()) { for (i in 1..maxWeekNum){ if (selectList[i-1] == "0"){ key(i){ IntBox(count = i, false){ if (it[i] == true){ selectList[i-1] = "1" }else{ selectList[i-1] = "0" } resultR(selectList.joinToString("")) } } } else { key(i) { IntBox(count = i, true) { if (it[i] == true) { selectList[i - 1] = "1" } else { selectList[i - 1] = "0" } resultR(selectList.joinToString("")) } } } } } Spacer(modifier = Modifier.height(10.dp)) Row{ TextButton(onClick = { for (t in 0 until selectList.size){ if (t % 2 == 0){ selectList[t] = "1" } else { selectList[t] = "0" } } }) { Text(text = "单周") } TextButton(onClick = { for (t in 0 until selectList.size){ if (t % 2 == 0){ selectList[t] = "0" } else { selectList[t] = "1" } } }) { Text(text = "双周") } TextButton(onClick = { for (t in 0 until selectList.size){ selectList[t] = "1" } }) { Text(text = "全选") } TextButton(onClick = { for (t in 0 until selectList.size){ selectList[t] = "0" } }) { Text(text = "全不选") } } } LaunchedEffect(selectList){ Log.d("DialogListChange",selectList.joinToString("")) } } @Composable fun IntBox(count:Int, selectedOr: Boolean=false, selectChanged:(select:Map<Int, Boolean>)->Unit = {}){ var selected by remember { mutableStateOf(selectedOr) } val backgroundColor = if(selected){Color(0xff2196f3)}else{Color.Transparent} Surface( color = backgroundColor, shape = RoundedCornerShape(100), modifier = Modifier.padding(2.dp) ) { Box( contentAlignment = Alignment.Center, modifier = Modifier .size(40.dp) .clickable { selected =!selected } ) { Text(text = "$count", color = contentColorFor(backgroundColor = backgroundColor)) } } LaunchedEffect(selected){ selectChanged(mapOf(count to selected)) } } @ExperimentalPagerApi @ExperimentalMaterialApi @Composable fun SelectSessionDialog( showDialog: MutableState<Boolean>, initialWeek:Int=0, initialStart:Int=0, initialEnd:Int=0, result:(week:Int, start:Int, end:Int)->Unit ){ var week1:Int = initialWeek var start1 = initialStart var end1 = initialEnd if (showDialog.value) { Dialog( onDismissRequest = { showDialog.value = false }, DialogProperties(dismissOnBackPress = true, dismissOnClickOutside = false) ) { Surface( shape = MaterialTheme.shapes.medium, color = MaterialTheme.colors.background ) { Column( modifier = Modifier .wrapContentHeight() .width(300.dp) .verticalScroll(rememberScrollState()), ){ Text(text = " \n 选择周数 \n", fontSize = 19.sp) SelectSessionContent(initialWeek, initialStart, initialEnd){week,start,end -> week1 = week start1 = start end1 = end } Spacer(modifier = Modifier.height(10.dp)) Row(modifier = Modifier.fillMaxWidth(0.98f),horizontalArrangement = Arrangement.End) { TextButton(onClick = { result(week1, start1, end1) showDialog.value = false }) { Text(text = "确定")} } Spacer(modifier = Modifier.height(8.dp)) } } } } } @Composable fun SelectSessionContent2( initialWeek: Int, initialStart: Int, initialEnd: Int, result: (week: Int, start: Int, end: Int) -> Unit, ){ var selectWeek by rememberSaveable { mutableStateOf(initialWeek) } var selectStart by rememberSaveable { mutableStateOf(initialStart) } var selectEnd by rememberSaveable { mutableStateOf(initialEnd) } val weekList = listOf("周一", "周二", "周三", "周四", "周五", "周六", "周日") val startSection = mutableListOf<String>() val endSection = mutableListOf<String>() for (i in 1..11){ startSection.add("第 $i 节") endSection.add("第 $i 节") } Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center ) { StringPicker2( strList = weekList, value = selectWeek, onValueChange = { selectWeek = it result(selectWeek, selectStart, selectEnd) } ) Spacer(modifier = Modifier.width(10.dp)) StringPicker2( strList = startSection, value = selectStart, onValueChange = { selectStart = it if (selectEnd<it) selectEnd = it result(selectWeek, selectStart, selectEnd) } ) Spacer(modifier = Modifier.width(10.dp)) StringPicker2( strList = endSection, value = selectEnd, onValueChange = { selectEnd = it if (selectStart > it) selectStart = it result(selectWeek, selectStart, selectEnd) } ) } } @ExperimentalMaterialApi @ExperimentalPagerApi @Composable fun SelectSessionContent( initialWeek: Int, initialStart: Int, initialEnd: Int, result: (week: Int, start: Int, end: Int) -> Unit, ){ val scope = rememberCoroutineScope() val weekList = listOf("周一", "周二", "周三", "周四", "周五", "周六", "周日") val startSection = mutableListOf<String>() val endSection = mutableListOf<String>() for (i in 1..11){ startSection.add("第 $i 节") endSection.add("第 $i 节") } val weekListPager = rememberPagerState( // pageCount = weekList.size, initialPage = initialWeek, // initialOffscreenLimit = weekList.size, // infiniteLoop = false ) val startPager = rememberPagerState( // pageCount = startSection.size, initialPage = initialStart, // initialOffscreenLimit = startSection.size, // infiniteLoop = false ) val endPager = rememberPagerState( // pageCount = endSection.size, initialPage = initialEnd, // initialOffscreenLimit = endSection.size, // infiniteLoop = false ) Box( modifier = Modifier .height(200.dp) .width(300.dp), contentAlignment = Alignment.Center, propagateMinConstraints = true ){ Row(modifier = Modifier .height(200.dp) .width(300.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center ) { StringPicker( strList = weekList, pagerState = weekListPager, pageChange = { Log.d("Dialog", it.toString()) result(weekListPager.currentPage, startPager.currentPage, endPager.currentPage) }, ) Spacer(modifier = Modifier.width(20.dp)) StringPicker( strList = startSection, pagerState = startPager, pageChange = { Log.d("Dialog", it.toString()) scope.launch { if (endPager.currentPage < it){ endPager.animateScrollToPage(it) } } result(weekListPager.currentPage, startPager.currentPage, endPager.currentPage) }, modifier = Modifier.fillMaxHeight() ) Spacer(modifier = Modifier.width(20.dp)) StringPicker( strList = endSection, pagerState = endPager, pageChange = { Log.d("Dialog", it.toString()) scope.launch { if (startPager.currentPage > it){ startPager.animateScrollToPage(it) } } result(weekListPager.currentPage, startPager.currentPage, endPager.currentPage) }, modifier = Modifier.fillMaxHeight() ) } Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center ){ Column(modifier = Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally) { Spacer(modifier = Modifier .fillMaxWidth(0.9f) .height(2.dp) .background(Color.Gray)) Spacer(modifier = Modifier .height(40.dp) .width(0.dp)) Spacer(modifier = Modifier .fillMaxWidth(0.9f) .height(2.dp) .background(Color.Gray)) } } } } @Composable fun EditDialog(showDialog: MutableState<Boolean>, initialString:String, resultR: (res: String) -> Unit){ var editString by remember { mutableStateOf(initialString) } if (showDialog.value){ AlertDialog( onDismissRequest = { showDialog.value = false }, title = {}, text = { TextField(value = editString, onValueChange ={ editString = it } ) }, dismissButton = { TextButton(onClick = { resultR(editString) showDialog.value = false }) { Text(text = "确定") } }, confirmButton = {} ) } } @ExperimentalMaterialApi @ExperimentalPagerApi @Composable fun SelectDateDialog( showDialog: MutableState<Boolean>, initialYear:Int=0, initialMonth:Int=0, initialDay:Int=0, selectMillis:(millis:Long) -> Unit ){ var year1 = initialYear var month1 = initialMonth var day1 = initialDay val yearList = listOf("2021","2022","2023") if (showDialog.value) { Dialog( onDismissRequest = { showDialog.value = false }, DialogProperties(dismissOnBackPress = true, dismissOnClickOutside = true) ) { Column( modifier = Modifier .wrapContentHeight() .width(300.dp) .verticalScroll(rememberScrollState()) .background(Color.White), ){ Text(text = " \n 选择日期 \n", fontSize = 19.sp) SelectDate( year = year1, initialMonth = month1, initialDay =day1, result = {year, month, day -> year1 = year month1 = month day1 = day } ) Spacer(modifier = Modifier.height(10.dp)) Row(modifier = Modifier.fillMaxWidth(0.98f),horizontalArrangement = Arrangement.End) { TextButton(onClick = { val calendar = GregorianCalendar().apply { set(Calendar.YEAR, yearList[year1].toInt()) set(Calendar.MONTH, month1) set(Calendar.DATE, day1+1) } selectMillis(calendar.timeInMillis) showDialog.value = false }) { Text(text = "确定")} } Spacer(modifier = Modifier.height(8.dp)) } } } } @ExperimentalMaterialApi @ExperimentalPagerApi @Composable fun SelectDate( year:Int, initialMonth:Int, initialDay:Int, result: (year: Int, month: Int, day: Int) -> Unit ){ val scope = rememberCoroutineScope() val yearList = listOf("2021","2022","2023") val monthList = (1..12).toList().map { it.toString() } val monthStrList = monthList.map { "${it}月" } val dayList = remember { mutableStateOf(GetDataUtil.getMonthAllDay( year = yearList[year].toInt(), month = monthList[initialMonth].toInt() )) } Log.d("Dialog","重组一次") var yearIndex by rememberSaveable { mutableStateOf(year) } var monthIndex by rememberSaveable { mutableStateOf(initialMonth) } var dayIndex by rememberSaveable { mutableStateOf(initialDay) } Box( modifier = Modifier .height(200.dp) .width(300.dp), contentAlignment = Alignment.Center, propagateMinConstraints = true ){ Row(modifier = Modifier .height(200.dp) .width(300.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center ) { StringPicker2( strList = yearList, value = year, onValueChange = { Log.d("Dialog", it.toString()) yearIndex = it result(yearIndex, monthIndex, dayIndex) }, // modifier = Modifier.fillMaxHeight() ) Spacer(modifier = Modifier.width(15.dp)) StringPicker2( strList = monthStrList, value = initialMonth, onValueChange = { Log.d("Dialog", it.toString()) monthIndex = it val year_ =yearList[yearIndex].toInt() val month_ = monthList[monthIndex].toInt()-1 scope.launch { dayList.value = GetDataUtil.getMonthAllDay(year_,month_) } result(yearIndex, monthIndex, dayIndex) // result(weekListPager.currentPage, startPager.currentPage, endPager.currentPage) }, ) Spacer(modifier = Modifier.width(15.dp)) StringPicker2( strList = dayList.value, value = initialDay, onValueChange = { Log.d("Dialog", it.toString()) dayIndex = it result(yearIndex, monthIndex, dayIndex) }, ) } // Box(modifier = Modifier.fillMaxSize(), // contentAlignment = Alignment.Center // ){ // Column(modifier = Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally) { // Spacer(modifier = Modifier // .fillMaxWidth(0.9f) // .height(2.dp) // .background(Color.Gray)) // Spacer(modifier = Modifier // .height(40.dp) // .width(0.dp)) // Spacer(modifier = Modifier // .fillMaxWidth(0.9f) // .height(2.dp) // .background(Color.Gray)) // } // } } } /** * 单选弹窗 */ @Composable fun SingleSelectDialog( showDialog: MutableState<Boolean>, modifier: Modifier = Modifier, selectNumInit:Int, selectList:List<String>, result:(res:String) -> Unit ){ var selectNum by remember { mutableStateOf(selectNumInit) } if (showDialog.value) { AlertDialog( title = { Text(text = "请选择") }, modifier = modifier, onDismissRequest = { showDialog.value = false }, confirmButton = { TextButton(onClick = { result(selectList[selectNum]) showDialog.value = false }) { Text(text = "确定") } }, text = { Column( modifier = Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally ) { repeat(selectList.size) { key(it) { RadioTextButton( selected = selectNum == it, text = selectList[it], onClick = { selectNum = it }) } } } } ) } } @Composable fun RadioTextButton( selected:Boolean, text:String, onClick: () -> Unit ){ Row( modifier = Modifier .clickable { onClick() } .fillMaxWidth(), verticalAlignment = Alignment.CenterVertically ) { RadioButton( // modifier = Modifier.padding(15.dp), selected = selected, onClick = { onClick() } ) Text(text = text, style = MaterialTheme.typography.body1) } } @OptIn(ExperimentalComposeUiApi::class) @Composable fun TextFieldDialog( value:String, placeHolder:String, onDismissRequest:()->Unit, onClick: (res:String) -> Unit, properties:DialogProperties = DialogProperties(dismissOnClickOutside = false), shapes: CornerBasedShape = MaterialTheme.shapes.medium, ){ var text by rememberSaveable{ mutableStateOf(value) } val focusRequester = remember { FocusRequester() } val keyboardController = LocalSoftwareKeyboardController.current LaunchedEffect(Unit){ focusRequester.requestFocus() keyboardController?.show() } CornerDialog( onDismissRequest = onDismissRequest, properties = properties, shapes = shapes, ) { Column( modifier = Modifier .fillMaxWidth(0.9f) .padding(5.dp) ) { Spacer(modifier = Modifier.height(10.dp)) BackgroundTransparentTextFiled( value = text, onValueChange = { text = it }, placeHolder = placeHolder, modifier = Modifier.focusRequester(focusRequester) ) Spacer(modifier = Modifier.height(10.dp)) TextButton( onClick = { onClick(text) }, modifier = Modifier.fillMaxWidth() ) { Text(text = "确定") } } } } @Composable fun CornerDialog( onDismissRequest:()->Unit, properties:DialogProperties = DialogProperties(), shapes: CornerBasedShape = MaterialTheme.shapes.medium, content:@Composable () -> Unit ){ Dialog( onDismissRequest = { onDismissRequest() }, properties = properties ) { Surface( shape = shapes ) { content() } } } @ExperimentalMaterialApi @ExperimentalPagerApi @Preview(showBackground = true) @Composable fun DialogPreView(){ // SelectSessionContent(0,0,0){ // _,_,_ -> // } SelectDate(0,0,0){ _,_,_-> } } ======================= File: app/src/main/java/com/liflymark/normalschedule/ui/set_background/DefaultBackgroundViewModel.kt ======================= package com.liflymark.normalschedule.ui.set_background import android.net.Uri import android.util.Log import androidx.compose.runtime.getValue import androidx.compose.runtime.livedata.observeAsState import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.liflymark.normalschedule.logic.Repository import com.liflymark.normalschedule.logic.bean.UserBackgroundBean import kotlinx.coroutines.launch class DefaultBackgroundViewModel:ViewModel() { var userBackgroundUri = "" val pathState = mutableStateOf(Uri.parse("")) init { viewModelScope.launch { pathState.value = Repository.loadBackground2() } } suspend fun updateBackground(){ Log.d("DefaultView", "update") Repository.updateBackground(UserBackgroundBean(userBackgroundUri)) pathState.value = Repository.loadBackground2() } } ======================= File: app/src/main/java/com/liflymark/normalschedule/ui/settings/SettingsActivity.kt ======================= <gh_stars>1-10 package com.liflymark.normalschedule.ui.settings import android.app.Activity import android.os.Bundle import android.util.Log import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.MaterialTheme import androidx.compose.material.Scaffold import androidx.compose.material.Text import androidx.compose.runtime.* import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.withStyle import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.navigation.NavController import com.afollestad.materialdialogs.MaterialDialog import com.liflymark.normalschedule.logic.Repository import com.liflymark.normalschedule.logic.utils.SingleSelectDialog import com.liflymark.normalschedule.ui.score_detail.UiControl import com.liflymark.normalschedule.ui.sign_in_compose.NormalTopBar import com.liflymark.normalschedule.ui.theme.NorScTheme import com.liflymark.schedule.data.Settings import es.dmoral.toasty.Toasty import kotlinx.coroutines.launch class SettingsActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { SettingsAll() } } } @Composable fun SettingsAll() { NorScTheme { UiControl() SettingsNavHost() } } @Composable fun SettingsMainPage( navController: NavController ) { Scaffold( topBar = { NormalTopBar(label = "设置") }, content = { SettingsContent(navController = navController) } ) } @Composable fun SettingsContent( navController: NavController ) { val context = LocalContext.current var nowColor by remember { mutableStateOf("主题") } val settings = Repository.getScheduleSettings().collectAsState( initial = Settings.getDefaultInstance() ) var perHeight by remember { mutableStateOf(0) } val scope = rememberCoroutineScope() var showDarkBack by remember { mutableStateOf(settings.value.darkShowBack) } var showHomeWorkIcon by remember { mutableStateOf("") } LaunchedEffect(settings.value) { nowColor = if (settings.value.colorMode == 0) { "纯色主题" } else { "渐变色主题" } perHeight = if (settings.value.coursePerHeight == 0) { 70 } else { settings.value.coursePerHeight } showDarkBack = settings.value.darkShowBack showHomeWorkIcon = if (settings.value.showRight!= 0) { "显示标识" } else { "不显示标识" } } val showNorSetDialog = remember { mutableStateOf(false) } var selectInit by remember { mutableStateOf(0) } var selectList by remember { mutableStateOf(listOf("")) } var dialogResult by remember { mutableStateOf("") } if (showNorSetDialog.value) { SingleSelectDialog( modifier = Modifier.fillMaxWidth(), showDialog = showNorSetDialog, selectNumInit = selectInit, selectList = selectList, result = { dialogResult = it } ) } LaunchedEffect(dialogResult) { when (dialogResult) { "渐变色主题" -> { scope.launch { Repository.updateMode(1) nowColor = "渐变色主题" } } "纯色主题" -> { scope.launch { Repository.updateMode(0) nowColor = "纯色主题" } } "显示" -> { scope.launch { Repository.updateShowDarkBack(true) showDarkBack = true } } "不显示" -> { scope.launch { Repository.updateShowDarkBack(false) showDarkBack = false } } "显示标识" -> { scope.launch { Repository.updateSettings { it.toBuilder() .setShowRight(1) .build() } showDarkBack = false } } "不显示标识" -> { scope.launch { Repository.updateSettings { it.toBuilder() .setShowRight(0) .build() } showDarkBack = false } } else -> {} } } Column( modifier = Modifier .fillMaxSize() .verticalScroll(rememberScrollState()) ) { SettingsPart( label = "常规" ) { SettingsItem( title = "课程格子主题", description = nowColor ) { selectInit = if (nowColor == "纯色主题") { 0 } else { 1 } selectList = listOf("纯色主题", "渐变色主题") showNorSetDialog.value = true } SettingsItem( title = "课程格子及其他外观配置", description = "更细致的配置项" ) { navController.navigate("courseCardSettings") } SettingsItem( title = "夜间模式显示背景图", description = if (showDarkBack) { "显示" } else { "不显示" } ) { selectInit = if (showDarkBack) (0) else { 1 } selectList = listOf("显示", "不显示") showNorSetDialog.value = true } SettingsItem( title = "有作业时右下角显示标识", description = showHomeWorkIcon ) { selectInit = if (showDarkBack) (0) else { 1 } selectList = listOf("显示标识", "不显示标识") showNorSetDialog.value = true } // SettingsItem( // title = "时间列字体颜色", // description = "暂时只支持黑白色设置" // ) { // // } } Spacer(modifier = Modifier.height(10.dp)) SettingsPart(label = "帮助") { SettingsItem(title = "重新查看帮助", description = "重新打开时,将在主界面重新查看帮助") { scope.launch { Repository.saveUserVersion(3) (context as Activity).finish() } } SettingsItem(title = "加入反馈群", description = "欢迎加入反馈群") { Repository.joinQQGroup(context) } } } } @Composable fun SettingsPart( label: String, content: @Composable () -> Unit ) { Column( Modifier .fillMaxWidth() .border( width = 0.5.dp, color = Color.LightGray, shape = MaterialTheme.shapes.medium ) ) { Text( text = label, style = MaterialTheme.typography.body1, color = Color.Gray, modifier = Modifier .padding( top = 10.dp, start = 10.dp, end = 2.dp, bottom = 3.dp ) ) content() } } @Composable fun SettingsItem( title: String, description: String, onCLick: () -> Unit ) { Column( modifier = Modifier .fillMaxWidth() .height(70.dp) .clickable { onCLick() } .padding(start = 10.dp), verticalArrangement = Arrangement.Center ) { Text( buildAnnotatedString { withStyle( style = SpanStyle( fontSize = MaterialTheme.typography.body1.fontSize, color = Color.Black ) ) { append(title) } withStyle( style = SpanStyle( fontSize = MaterialTheme.typography.body1.fontSize, color = Color.Gray ) ) { append("\n$description") } } ) } } @Preview(showBackground = true) @Composable fun DefaultPreview2() { NorScTheme { SettingsPart( label = "常规" ) { SettingsItem( title = "课程格子主题", description = "渐变色主题" ) { } SettingsItem( title = "课程格子高度", description = "高度:70dp" ) { } SettingsItem( title = "夜间模式显示背景图", description = "显示" ) { } } } } ======================= File: app/src/main/java/com/liflymark/normalschedule/ui/show_timetable/ThisActivityDialog.kt ======================= package com.liflymark.normalschedule.ui.show_timetable import android.app.Activity import android.content.Intent import android.net.Uri import android.util.Log import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.material.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.BookmarkAdd import androidx.compose.material.icons.filled.MenuBook import androidx.compose.material.icons.outlined.* import androidx.compose.runtime.* import androidx.compose.runtime.livedata.observeAsState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.compose.ui.window.DialogProperties import androidx.lifecycle.viewmodel.compose.viewModel import com.liflymark.normalschedule.logic.Repository import com.liflymark.normalschedule.logic.bean.Bulletin2 import com.liflymark.normalschedule.logic.bean.CourseBean import com.liflymark.normalschedule.logic.bean.OneByOneCourseBean import com
1,520
Repo: ibizaman/veewee ======================= File: templates/windows-2012R2-serverdatacenter-amd64/install-chef.bat ======================= <reponame>ibizaman/veewee @REM Loop ten times to make sure outbound networking is up @FOR /L %%n IN (1,1,10) DO ( @PING -n 1 www.opscode.com @IF %ERRORLEVEL% == 0 CALL :wget @TIMEOUT 10 ) :err @ECHO "Couldn't reach Opscode even after 10 retries" @GOTO :done :wget @REM Install Chef using chef-client MSI installer @setlocal @set REMOTE_SOURCE_MSI_URL=https://www.opscode.com/chef/install.msi @set LOCAL_DESTINATION_MSI_PATH=%TEMP%\chef-client-latest.msi @set QUERY_STRING=?DownloadContext=PowerShell @set DOWNLOAD_COMMAND=$webClient=new-object System.Net.WebClient; $webClient.DownloadFile('%REMOTE_SOURCE_MSI_URL%%QUERY_STRING%', '%LOCAL_DESTINATION_MSI_PATH%') @if EXIST "%LOCAL_DESTINATION_MSI_PATH%" del /f /q "%LOCAL_DESTINATION_MSI_PATH%" powershell -noprofile -noninteractive -command "%DOWNLOAD_COMMAND%" @IF NOT ERRORLEVEL 1 ( @ECHO Download succeeded ) else ( @ECHO Failed to download %REMOTE_SOURCE_MSI_URL% @ECHO Subsequent attempt to install the downloaded MSI is likely to fail ) msiexec /qn /i "%LOCAL_DESTINATION_MSI_PATH%" @endlocal EXIT :done EXIT ======================= File: templates/windows-7-enterprise-amd64-winrm/postinstall.bat ======================= REM set -x REM # Create the home directory REM mkdir -p /home/vagrant REM chown vagrant /home/vagrant REM cd /home/vagrant REM # Install ssh certificates REM mkdir /home/vagrant/.ssh REM chmod 700 /home/vagrant/.ssh REM cd /home/vagrant/.ssh REM wget --no-check-certificate 'https://raw.github.com/mitchellh/vagrant/master/keys/vagrant.pub' -O authorized_keys REM chown -R vagrant /home/vagrant/.ssh REM cd.. REM # Install rpm,apt-get like code for cygwin REM # http://superuser.com/questions/40545/upgrading-and-installing-packages-through-the-cygwin-command-line REM wget http://apt-cyg.googlecode.com/svn/trunk/apt-cyg REM chmod +x apt-cyg REM mv apt-cyg /usr/local/bin/ REM # 7zip will allow us to extract a file from an ISO REM wget http://downloads.sourceforge.net/sevenzip/7z922-x64.msi REM msiexec /qb /i 7z922-x64.msi REM # Download Virtualbox Additions REM VBOX_VERSION="4.1.8" #"4.0.8" REM wget http://download.virtualbox.org/virtualbox/$VBOX_VERSION/VBoxGuestAdditions_$VBOX_VERSION.iso REM # Extract the installer from the ISO (WHY WHY WHY isn't this available not bundled within an ISO) REM /cygdrive/c/Program\ Files/7-Zip/7z.exe x VBoxGuestAdditions_$VBOX_VERSION.iso VBoxWindowsAdditions-amd64.exe REM # Mark Oracle as a trusted installer REM #http://blogs.msdn.com/b/steverac/archive/2009/07/09/adding-certificates-to-the-local-certificates-store-and-setting-local-policy-using-a-command-line-system-center-updates-publisher-example.aspx REM certutil -addstore -f "TrustedPublisher" a:oracle-cert.cer REM # Install the Virtualbox Additions REM./VBoxWindowsAdditions-amd64.exe /S REM #Rather than do the manual install of ruby and chef, just use the opscode msi cmd /C cscript %TEMP%\wget.vbs /url:http://www.opscode.com/chef/install.msi /path:%TEMP%\chef-client.msi msiexec /qb /i %TEMP%\chef-client-latest.msi REM #http://www.msfn.org/board/topic/105277-howto-create-a-fully-up-to-date-xp-x64-dvd/ REM #Making aliases REM cat <<EOF > /home/vagrant/.bash_profile REM alias chef-client="chef-client.bat" REM alias gem="gem.bat" REM alias ruby="ruby.exe" REM alias puppet="puppet.bat" REM alias ohai="ohai.bat" REM alias irb="irb.bat" REM alias facter="facter.bat" REM EOF REM cat <<'EOF' > /bin/sudo REM #!/usr/bin/bash REM exec "$@" REM EOF REM chmod 755 /bin/sudo REM # Mounting a directory REM net.exe use '\\vboxsvr\veewee-validation' REM # Reboot REM # http://www.techrepublic.com/blog/datacenter/restart-windows-server-2003-from-the-command-line/245 REM shutdown.exe /s /t 0 /d p:2:4 /c "Vagrant initial reboot" ======================= File: templates/windows-7-enterprise-amd64-winrm/install-puppet.bat ======================= cmd /C cscript %TEMP%\wget.vbs /url:https://downloads.puppetlabs.com/windows/puppet-3.0.1.msi /path:%TEMP%\puppet.msi cmd /C msiexec /qn /i %TEMP%\puppet.msi cmd /C gem install sys-admin win32-process win32-dir win32-taskscheduler cmd /C gem install win32-service --platform=mswin32 ======================= File: templates/windows-2012R2-serverdatacenter-amd64/install-vbox.bat ======================= if exist e:\cert\VBoxCertUtil ( cmd /c e:\cert\VBoxCertUtil add-trusted-publisher e:\cert\oracle-vbox.cer --root e:\cert\oracle-vbox.cer ) else ( cmd /c certutil -addstore -f "TrustedPublisher" a:oracle-cert.cer ) cmd /c e:\VBoxWindowsAdditions-amd64.exe /S cmd /c shutdown.exe /r /t 5 /d p:2:4 /c "Vagrant reboot for VBoxWindowsAdditions" ======================= File: templates/windows-2008R2-amd64/install-winrm.bat ======================= <reponame>ibizaman/veewee<gh_stars>1000+ cmd /c winrm quickconfig -q cmd /c winrm quickconfig -transport:https cmd /c winrm set winrm/config/winrs @{MaxMemoryPerShellMB="300"} cmd /c winrm set winrm/config/service @{AllowUnencrypted="true"} cmd /c winrm set winrm/config/service/auth @{Basic="true"} cmd /c netsh advfirewall firewall set rule group="remote administration" new enable=yes cmd /c netsh advfirewall firewall set rule group="network discovery" new enable=yes ; cmd /c net use x: \\vboxsrv\sharename ======================= File: templates/windows-2008R1-serverweb-amd64/install-guest-additions.bat ======================= <reponame>ibizaman/veewee<filename>templates/windows-2008R1-serverweb-amd64/install-guest-additions.bat # with this, we can open the iso, and extract the VBoxWindowsAdditions.exe! # http://downloads.sourceforge.net/sevenzip/7z920.exe cmd /c certutil -addstore -f "TrustedPublisher" a:oracle-cert.cer cmd /c c:\cygwin\bin\wget https://s3-ap-southeast-1.amazonaws.com/vboxfan/4.1.8/VBoxWindowsAdditions-amd64.exe --no-check-certificate cmd /c.\VBoxWindowsAdditions-amd64.exe /S ======================= File: templates/windows-7-enterprise-amd64-winrm/install-fusion.bat ======================= <filename>templates/windows-7-enterprise-amd64-winrm/install-fusion.bat REM Not much here yet, some notes to make things going REM Enable autorun REM reg add HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Cdrom\Autorun /v Data /t REG_DWORD /f /d 1 REM Install vmware tools REM /Applications/VMware\ Fusion.app/Contents/Library/vmrun installtools /Users/patrick/Documents/Virtual\ Machines.localized/win7.vmwarevm/win7.vmx REM Manually install it REM http://communities.vmware.com/servlet/JiveServlet/previewBody/12413-102-4-13370/VMware%20Tools%20-%20Unattended_Install.pdf REM NOT WORKING REM msiexec /i "VMware Tools.msi" ADDLOCAL=ALL REMOVE="Hgfs,WYSE,GuestSDK,vmdesched" /qn /l* C:\temp\toolsinst.log /norestart REM VMware Tools64.msi for 64 bit REM WORKING REM d:Setup64.exe /s /v "/qn" REM ======================= File: templates/windows-7-premium-amd64/install-chefclient.bat ======================= <gh_stars>1000+ mkdir C:\chef > C:\chef\wget.vbs ( echo.url = WScript.Arguments.Named^("url"^) echo.path = WScript.Arguments.Named^("path"^) echo.Set objXMLHTTP = CreateObject^("MSXML2.ServerXMLHTTP"^) echo.Set wshShell = CreateObject^( "WScript.Shell" ^) echo.Set objUserVariables = wshShell.Environment^("USER"^) echo. echo.'http proxy is optional echo.'attempt to read from HTTP_PROXY env var first echo.On Error Resume Next echo. echo.If NOT ^(objUserVariables^("HTTP_PROXY"^) = ""^) Then echo.objXMLHTTP.setProxy 2, objUserVariables^("HTTP_PROXY"^) echo. echo.'fall back to named arg echo.ElseIf NOT ^(WScript.Arguments.Named^("proxy"^) = ""^) Then echo.objXMLHTTP.setProxy 2, WScript.Arguments.Named^("proxy"^) echo.End If echo. echo.On Error Goto 0 echo. echo.objXMLHTTP.open "GET", url, false echo.objXMLHTTP.send^(^) echo.If objXMLHTTP.Status = 200 Then echo.Set objADOStream = CreateObject^("ADODB.Stream"^) echo.objADOStream.Open echo.objADOStream.Type = 1 echo.objADOStream.Write objXMLHTTP.ResponseBody echo.objADOStream.Position = 0 echo.Set objFSO = Createobject^("Scripting.FileSystemObject"^) echo.If objFSO.Fileexists^(path^) Then objFSO.DeleteFile path echo.Set objFSO = Nothing echo.objADOStream.SaveToFile path echo.objADOStream.Close echo.Set objADOStream = Nothing echo.End if echo.Set objXMLHTTP = Nothing ) @rem Install Chef using chef-client MSI installer cscript /nologo C:\chef\wget.vbs /url:http://www.opscode.com/chef/install.msi /path:%TEMP%\chef-client-latest.msi msiexec /qb /i %TEMP%\chef-client-latest.msi ======================= File: templates/windows-2008R1-serverweb-amd64/install-winrm.bat ======================= <gh_stars>1000+ cmd /c winrm quickconfig -q cmd /c winrm quickconfig -transport:http cmd /c winrm set winrm/config @{MaxTimeoutms="1800000"} cmd /c winrm set winrm/config/winrs @{MaxMemoryPerShellMB="300"} cmd /c winrm set winrm/config/service @{AllowUnencrypted="true"} cmd /c winrm set winrm/config/service/auth @{Basic="true"} cmd /c winrm set winrm/config/listener?Address=*+Transport=HTTP @{Port="5985"} cmd /c netsh advfirewall firewall set rule group="remote administration" new enable=yes cmd /c netsh firewall add portopening TCP 5985 "Port 5985" cmd /c net stop winrm cmd /c sc config winrm start= auto cmd /c net start winrm cmd /c reg add "HKEY_CURRENT_USER\Control Panel\Desktop" /v ScreenSaveActive /t REG_SZ /d 0 /f cmd /c reg add "HKEY_CURRENT_USER\Control Panel\Desktop" /v ScreenSaveIsSecure /t REG_SZ /d 0 /f ======================= File: templates/windows-7-enterprise-amd64-winrm/install-chef.bat ======================= <reponame>ibizaman/veewee cmd /C cscript %TEMP%\wget.vbs /url:http://www.opscode.com/chef/install.msi /path:%TEMP%\chef-client.msi cmd /C msiexec /qn /i %TEMP%\chef-client.msi ======================= File: templates/windows-2012R2-serverdatacenter-amd64/install-puppet.bat ======================= @REM Loop ten times to make sure outbound networking is up @FOR /L %%n IN (1,1,10) DO ( @PING -n 1 downloads.puppetlabs.com @IF %ERRORLEVEL% == 0 CALL :wget @TIMEOUT 10 ) :err @ECHO "Couldn't reach PuppetLabs even after 10 retries" @GOTO :done :wget @REM Install Puppet using MSI installer @setlocal @set REMOTE_SOURCE_MSI_URL=https://downloads.puppetlabs.com/windows/puppet-3.2.1.msi @set LOCAL_DESTINATION_MSI_PATH=%TEMP%\puppet-latest.msi @set QUERY_STRING=?DownloadContext=PowerShell @set DOWNLOAD_COMMAND=$webClient=new-object System.Net.WebClient; $webClient.DownloadFile('%REMOTE_SOURCE_MSI_URL%%QUERY_STRING%', '%LOCAL_DESTINATION_MSI_PATH%') @if EXIST "%LOCAL_DESTINATION_MSI_PATH%" del /f /q "%LOCAL_DESTINATION_MSI_PATH%" powershell -noprofile -noninteractive -command "%DOWNLOAD_COMMAND%" @IF NOT ERRORLEVEL 1 ( @ECHO Download succeeded ) else ( @ECHO Failed to download %REMOTE_SOURCE_MSI_URL% @ECHO Subsequent attempt to install the downloaded MSI is likely to fail ) msiexec /qn /i "%LOCAL_DESTINATION_MSI_PATH%" PUPPET_MASTER_SERVER=dummy_server @endlocal EXIT :done EXIT ======================= File: lib/java/dir2floppy.java ======================= <filename>lib/java/dir2floppy.java<gh_stars>1000+ package be.jedi.dir2floppy; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import de.waldheinz.fs.FileSystem; import de.waldheinz.fs.FsDirectoryEntry; import de.waldheinz.fs.FsFile; import de.waldheinz.fs.fat.SuperFloppyFormatter; import de.waldheinz.fs.util.FileDisk; /** * Hello world! * */ public class Dir2Floppy { public static void main( String[] args ) { if (args.length < 2) { System.out.println("Usage: java -jar dir2floppy.jar <sourcedir> <floppyfile>"); System.exit(-1); } FileDisk device = null; //Create the floppy try { device = FileDisk.create(new File(args[1]),(long)1440 * 1024); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); System.exit(-1); } //Format the floppy FileSystem fs=null; try { fs = SuperFloppyFormatter.get(device).format(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); System.exit(-1); } //Iterate of directories File dir = new File(args[0]); String[] children = dir.list(); if (children == null) { // Either dir does not exist or is not a directory System.out.println("Error. does the directory exist?"); System.exit(-1); } else { for (int i=0; i<children.length; i++) { // Get filename of file or directory File aFile=new File(dir.getAbsolutePath()+System.getProperty("file.separator")+children[i]); try { // Create the entry on the floppy FsDirectoryEntry floppyEntry = fs.getRoot().addFile(children[i]); //floppyEntry.setName(children[i]); System.out.print("- Processing file: "+children[i]+" "); FsFile floppyfile = floppyEntry.getFile(); // Copy the file over if (aFile.isFile()) { FileInputStream fis= new FileInputStream(aFile); FileChannel fci = fis.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(1024); long counter=0; int len; // http://www.kodejava.org/examples/49.html // Here we start to read the source file and write it // to the destination file. We repeat this process // until the read method of input stream channel return // nothing (-1). while(true) { // read a block of data and put it in the buffer int read = fci.read(buffer); // did we reach the end of the channel? if yes // jump out the while-loop if (read == -1) break; // flip the buffer buffer.flip(); // write to the destination channel System.out.print("."); floppyfile.write(counter*1024, buffer); counter++; // clear the buffer and user it for the next read // process buffer.clear(); } System.out.println(); floppyfile.flush(); fis.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } try { fs.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println( "Done" ); } } ======================= File: templates/ubuntu-12.04.3-desktop-i386/README.md ======================= <filename>templates/ubuntu-12.04.3-desktop-i386/README.md # Template Manifest # This file explains the goals of this template definition. For details about the function of veewee template files, see the documentation on how to [Customize Definitions](../../doc/customize.md). ### Overview ### **Template Name:** `Ubuntu-12.04.3-desktop-i386` **Box Objective:** The aim is to setup a vanilla `Ubuntu 32-bit (i386) desktop` plus setup what's needed for veewee automation, VirtualBox guest additions, and to install the foundation so that either `puppet` or `chef` can easily customize as needed. The template was loosely based on `ubuntu-12.04.3-server-i386` and `ubuntu-12.04.2-desktop-amd64`. It improves the `ubuntu-12.04.2-desktop-amd64` template by moving Desktop setup to the `preseed.cfg` file instead of a post installation; which essentially caused setup to run twice (first for the linux server kernel install, then a second time for the install of the standard kernel). As a result, this definition is less complex and the build is faster. #### System Details #### * **Version:** Ubuntu 12.04.3 Desktop * **Locale:** en_US * **Keyboard layout:** US * **Timezone:** UTC * **Extra Language Support:** none * **Machine:** 1.9GB RAM, 30GB HD * **VirtualBox Config:** IO_APIC ON, UTC time, 3D acceleration, Shared clipboard. * **Deviations from a vanilla Ubuntu Desktop:** * Add `vagrant` user and add to `admin group`, disable password requirement for `admin group` to run `sudo` commands. * Install VirtualBox `Guest Additions` * Install `Ruby` * Install `Puppet` * Install `Chef` ### CHANGELOG ### * Completely reorganize `preseed.cfg` based on 12.04 (precise) examples and add useful comments * Change disk size to 30GB (exports to 1.1GB box) * Improve VirtualBox default settings for a desktop image and document * Cleanup various cruft ======================= File: doc/veeweefile.md ======================= <reponame>ibizaman/veewee # Veeweefile In cases were you'd like to set your own paths, feel free to create a `Veeweefile` in the project root: Veewee::Config.run do |config| # Initialize convenience vars cwd = File.dirname(__FILE__) env = config.veewee.env # These env settings will override default settings #env.cwd = cwd #env.definition_dir = File.join(cwd, 'definitions') #env.template_path = [File.join(cwd, 'templates')] #env.iso_dir = File.join(cwd, 'iso') #env.validation_dir = File.join(cwd, 'validation') #env.tmp_dir = "/tmp" end An example where this may be useful is if you'd like create your own barebones project, include the `veewee` gem in that project's Gemfile, and then make sure your local `templates` directory is referenced rather than the templates found inside the veewee gem. ## Up Next Either check out the [guide for Vagrant](vagrant.md) or review one of the various [guides for Providers](providers.md). ======================= File: doc/requirements.md ======================= # Requirements Veewee has a few requirements that must be met before you're able to use Veewee. ## Virtualization Providers You'll need to install at least one of the supported VM providers (see [Providers](providers.md) doc for details). If you're not sure which provider to use, a common choice is [VirtualBox](http://www.virtualbox.org/) since it's free, portable, and supported by Vagrant. ## Development Libraries Veewee is written in Ruby. In order to use Veewee you need Ruby installed as well as some header files in order to compile native extensions that come as dependencies. If you already have experiences with Ruby this should be very straightforward. ### For Linux On Linux, you may need these packages in order to build native rubygems: libxslt1-dev libxml2-dev zlib1g-dev # or build-essential ### For Mac OS X On Macs, either install `Xcode` or use [homebrew](http://mxcl.github.io/homebrew/) to install `apple-gcc42` or `build-essential`. ### For Windows On Windows, you will need to install: * Ruby devkit * msysgit * PowerShell (if on XP or Vista) * PowerShell Community Extensions * And you may need to add VirtualBox to your `PATH`, usually installed to `C:\Program Files\Oracle\VirtualBox`. ## Ruby Environment It is highly recommended that you use either `rvm` or `rbenv` to manage your ruby versions. Veewee currently supports Ruby version `1.9.3` to `2.2.1` IMPORTANT : For best results, please use the latest version of Ruby. ### Option 1: RVM [RVM](https://rvm.io/) is Veewee's prefered ruby version manager. RVM will allow Veewee to install its own [gemset](https://rvm.io/gemsets/basics/) and configure its own ruby version - which keeps Veewee and its dependancies completely separate from your other projects. Please see https://rvm.io/gemsets/basics/ for details if you are new to the concept of 'gemsets'. ##### Installing RVM Please see the [RVM install documentation](https://rvm.io/rvm/install) for up-to-date installation instructions. ### Option 2: rbenv [rbenv](https://github.com/sstephenson/rbenv) is another popular ruby version manager that you can use as an alternative to RVM. ##### Installing rbenv Please see the [rbenv README]( https://github.com/sstephenson/rbenv/#installation) for up-to-date installation instructions. ## Up Next Ok, now that we have cover all the requirements, you can move on with [installing Veewee](installation.md). ======================= File: doc/fusion.md ======================= <gh_stars>1000+ ## VMware Fusion VM Provider To interact with [VMware (Fusion)](http://www.vmware.com/products/fusion/), we leverage (a currently patched) version of [Fission gem](https://github.com/thbishop/fission). This gem takes care of the heavy lifting. To interact with the screen, Veewee enables VNC on the created VMware Fusion machines and uses the [Ruby-VNC gem](http://code.google.com/p/ruby-vnc/) to send the keystrokes. Sending keystrokes too fast is a problem for this setup as well. ======================= File: doc/changes.md ======================= <filename>doc/changes.md<gh_stars>1000+ # Major Changes ## Changes between v0.2 -> v0.3 1. The `Veewee::Session.declare` is now _deprecated_ and you should use `Veewee::Definition.declare`. 'postinstall_files' prefixed with an _underscore_ are not executed by default: ~~~ sh . ├── definitions │   └── myubuntubox │   ├── _postinstall.sh # NOT executed │   ├── postinstall_2.sh # GETS executed ~~~ You can enforce including or excluding files with the `--include` and `--exclude` flag when using the `build` command. This allows you to use different scripts for installing ruby or to disable the installation of puppet or chef. 2. The default user of definitions is now `veewee` and not `vagrant`. This is because on other VMs like `fusion` and `kvm`, there is no relationship with the `vagrant` user. The `vagrant` user is created by the `vagrant.sh` script and not by the _preseed_ or _kickstart_ files. ======================= File: doc/providers.md ======================= # Veewee Virtual Machine Providers Veewee now has multiple virtual machine (VM) providers. Initially Veewee started with only VirtualBox as a provider. VMware Fusion and KVM were introduced in v0.3. Parallels support is the newest addition. * [Guide for VirtualBox](vbox.md) * [Guide for VMware Fusion](fusion.md) * [Guide for KVM](kvm.md) * [Guide for Parallels](parallels.md) ======================= File: doc/commands.md ======================= # Veewee Command Options You can choose from a few different command line options when executing Veewee. ## Veewee with `bundle exec` Unless you've created an alias for `veewee`, always include the `bundle exec` prefix like this: $ bundle exec veewee ## Veewee without `bundle exec` For convenience, it's handy to create an alias for the `veewee` command so we don't have to type `bundle exec` any longer. Add the alias `alias veewee='bundle exec veewee'` to your shell's default startup file (e.g. ~/.bash_profile): echo "alias veewee='bundle exec veewee'" >> ~/.bash_profile **For Ubuntu:** Modify your ~/.profile instead of ~/.bash_profile. <br>**For Zsh:** Modify your ~/.zshrc file instead of ~/.bash_profile. After adding the alias described above you'll be able to use the shorthand `veewee` command: $ veewee ## Veewee as a Vagrant Plugin You can also use Veewee as a [Vagrant plugin](http://docs.vagrantup.com/v2/plugins/index.html). As a plugin, Veewee introduces the subcommand `basebox` on top of the `vagrant` command: $ vagrant basebox Usage: vagrant basebox <command> [<args>] This allows you to use the `vagrant` command style, which may feel more natural if you're already used to working with Vagrant. Please see Veewee's [Vagrant](vagrant.md) doc for more details. ## Up Next [Veewee Basics](basics.md) covers creating standard-issue boxes. ======================= File: templates/CentOS-6.3-x86_64-reallyminimal/README.md ======================= # CentOS 6.3 VirtualBox image for Vagrant `CentOS release 6.3 (Final)` Small as I can make it (which doesn't mean it can't be made smaller…) * All upgrades, as of 2013-Jan-02. * Puppet 3.0.2 from the Puppet Labs Yum repo * Chef 10.16.4 via `gem install chef` * VirtualBox Guest Additions 4.2.6 * EPEL only used for `dkms`, to make VBox Guest Additions survive kernel upgrades (hopefully) * EPEL and Puppet Labs Yum repositories removed after install ======================= File: templates/archlinux-x86_64/README.md ======================= <gh_stars>1000+ # Arch Linux ## Tip Since this is a "net" install and all packages are downloaded, you can speed up the download of the base packages by getting [Pacman][] to use a suitable [mirror][]. For example, I modified the definition to make Pacman use Australian and New Zealand mirrors. @@ -27,6 +27,7 @@ 'passwd<Enter>', "#{root_password}<Enter>", "#{root_password}<Enter>", + "echo 'Server = http://mirror.xnet.co.nz/pub/archlinux/$repo/os/$arch' > /etc/pacman.d/mirrorlist<Enter>", 'systemctl start sshd.service<Enter><Wait>', ], :ssh_login_timeout => '10000', @@ -58,6 +59,6 @@ ], :postinstall_timeout => '10000', :params => { - #:PACMAN_REFLECTOR_ARGS => '--verbose -l 5 --sort rate --save /etc/pacman.d/mirrorlist', + :PACMAN_REFLECTOR_ARGS => '--verbose -c "New Zealand" -c Australia -n 5 --sort rate --save /etc/pacman.d/mirrorlist', } }) You can obtain a suitable mirrorlist for yourself using the [Pacman Mirrorlist Generator][]. The list of countries with mirrors is on that page too. Once the base system is installed, the template uses [Reflector][] to set up Pacman's mirrorlist for the remaining packages. By default, the arguments passed to Reflector favour up-to-date mirrors sorted by their download rate. As shown above, you may customize the arguments to your liking. ## Note * Reflector is uninstalled by the template following the mirrorlist generation * The template currently only supports VirtualBox provider [Pacman]: https://wiki.archlinux.org/index.php/Pacman [mirror]: https://wiki.archlinux.org/index.php/Mirrors [Pacman Mirrorlist Generator]: https://www.archlinux.org/mirrorlist/ [Reflector]: https://wiki.archlinux.org/index.php/Reflector ======================= File: templates/windows-2008R2-amd64/README.md ======================= You can download a free trial of Windows 2008 R2 My downloaded iso was named '7601.17514.101119-1850_x64fre_server_eval_en-us-GRMSXEVAL_EN_DVD.iso' - place it in a directory called iso The installation uses the Standard way for Windows Unattended installation. The XML file was created using the Windows AIK kit, but the file can also be edited by hand. - Building the machine creates a floppy that contains: - AutoUnattend.xml (that will configure the windows) - cygwin-setup.exe (the standard setup.exe cygwin binaries) - cygwin-install.bat (this script will run the cygwin installer + get sshd/openssl going) - winrm-install.bat (activates the http and https listener + punches the firewall hole) Expose the winrm port: <pre> $ gem install chef $ gem install knife-windows #Create a tunnel $ ssh -p 7222 -L5985:localhost:5985 vagrant@localhost $ knife bootstrap windows winrm localhost -x Administrator -P 'vagrant' </pre> - http://wiki.opscode.com/display/chef/Knife+Windows+Bootstrap - https://github.com/opscode/knife-windows/blob/master/lib/chef/knife/bootstrap/windows-shell.erb - https://github.com/zenchild/WinRM - http://devopscloud.net/2011/04/17/managing-chef-from-windows-7/ - http://devopscloud.net/2011/04/28/powershell-userdata-to-start-a-chef-run/ - http://devopscloud.net/2011/03/23/dissection-of-a-chef-recipe-or-two-for-windows/ - https://github.com/pmorton/chef-windows-installer == https://github.com/zenchild/WinRM/issues/unreads#issue/1 http -> requires unencryptedwinrm quickconfig (said yes to enable firewall) winrm p winrm/config/service @{AllowUnencrypted="true"} winrm set winrm/config/service/auth @{Basic="true"}netsh advfirewall firewall set rule group="remote administration" new enable=yes - http://forums.citrix.com/thread.jspa?messageID=1535826 - http://support.microsoft.com/kb/2019527 winrm get winrm/config The purpose of configuring WinRM for HTTPS is to encrypt the data being sent across the wire. WinRM HTTPS requires a local computer "Server Authentication" certificate with a CN matching the hostname, that is not expired, revoked, or self-signed to be installed. To install or view certificates for the local computer: - click Start, run, MMC, "File" menu, "Add or Remove Snap-ins" select "Certificates" and click "Add". Go through the wizard selecting "Computer account". - Install or view the certificates under: Certificates (Local computer) Personal Certificates If you do not have a Sever Authenticating certificate consult your certicate administrator. If you have a microsoft Certificate server you may be abel to request a certificate using the web certificate template from HTTPS://<MyDomainCertificateServer>/certsrv Once the certificate is installed type the following to configure WINRM to listen on HTTPS: winrm quickconfig -transport:https If you do not have an appropriate certificate you can run the following with the authentication methods configured for WinRM however the data will not be encrypted. winrm quickconfig ======================= File: templates/windows-2008R2-serverstandard-amd64-winrm/README.md ======================= You can download a free trial of Windows Server 2008 R2 with Service Pack 1 from two different locations manually: * url: http://technet.microsoft.com/en-us/evalcenter/dd459137.aspx * url: http://msdn.microsoft.com/en-us/evalcenter/ee175713.aspx But they seem to always generate the same url of http://care.dlservice.microsoft.com//dl/download/7/5/E/75EC4E54-5B02-42D6-8879-D8D3A25FBEF7/7601.17514.101119-1850_x64fre_server_eval_en-us-GRMSXEVAL_EN_DVD.iso * 64bit * filename: 7601.17514.101119-1850_x64fre_server_eval_en-us-GRMSXEVAL_EN_DVD.iso * md5sum: 4263be2cf3c59177c45085c0a7bc6ca5 The installation uses the Standard Windows Unattended installation. The XML file was created using the Windows AIK kit, but the file can also be edited by hand. To edit the Autounattend.xml and validate it you can download The Windows® Automated Installation Kit (AIK) for Windows® 7: * url: http://www.microsoft.com/download/en/details.aspx?id=5753 * file: KB3AIK_EN.iso * md5sum: 1e73b24a89eceab9d50585b92db5482f AIK also includes dism, which will allow you to choose a specific version: If you want to install a different version, edit Autoattended.xml and replace the /IMAGE/NAME value with one of the names listed in the 2008r2 install.wim on the install DVD.iso ```xml <InstallFrom> <MetaData wcm:action="add"> <Key>/IMAGE/NAME</Key> <Value>Windows Server 2008 R2 SERVERSTANDARD</Value> </MetaData> </InstallFrom> ``` ``` PS C:\Users\Administrator> Dism /Get-WIMInfo /WimFile:d:\sources\install.wim Deployment Image Servicing and Management tool Version: 6.1.7600.16385 Details for image : d:\sources\install.wim Index : 1 Name : Windows Server 2008 R2 SERVERSTANDARD Description : Windows Server 2008 R2 SERVERSTANDARD Size : 10,510,643,622 bytes Index : 2 Name : Windows Server 2008 R2 SERVERSTANDARDCORE Description : Windows Server 2008 R2 SERVERSTANDARDCORE Size : 3,564,132,307 bytes Index : 3 Name : Windows Server 2008 R2 SERVERENTERPRISE Description : Windows Server 2008 R2 SERVERENTERPRISE Size : 10,511,024,733 bytes Index : 4 Name : Windows Server 2008 R2 SERVERENTERPRISECORE Description : Windows Server 2008 R2 SERVERENTERPRISECORE Size : 3,564,106,331 bytes Index : 5 Name : Windows Server 2008 R2 SERVERDATACENTER Description : Windows Server 2008 R2 SERVERDATACENTER Size : 10,511,131,897 bytes Index : 6 Name : Windows Server 2008 R2 SERVERDATACENTERCORE Description : Windows Server 2008 R2 SERVERDATACENTERCORE Size : 3,564,144,547 bytes Index : 7 Name : Windows Server 2008 R2 SERVERWEB Description : Windows Server 2008 R2 SERVERWEB Size : 10,520,222,743 bytes Index : 8 Name : Windows Server 2008 R2 SERVERWEBCORE Description : Windows Server 2008 R2 SERVERWEBCORE Size : 3,562,750,400 bytes The operation completed successfully. ``` ======================= File: templates/windows-7-professional-amd64/README.md ======================= <reponame>ibizaman/veewee<filename>templates/windows-7-professional-amd64/README.md You can download a free trial of Windows 7 Enterprise 90-day Trial url: http://technet.microsoft.com/en-us/evalcenter/cc442495.aspx file: 7600.16385.090713-1255_x64fre_enterprise_en-us_EVAL_Eval_Enterprise-GRMCENXEVAL_EN_DVD.iso md5sum: 1d0d239a252cb53e466d39e752b17c28 ''' PS C:\Users\Administrator> Dism /Get-WIMInfo /WimFile:d:\sources\install.wim Deployment Image Servicing and Management tool Version: 6.1.7600.16385 Details for image : d:\sources\install.wim Index : 1 Name : Windows 7 ENTERPRISE Description : Windows 7 ENTERPRISE Size : 11,913,037,777 bytes The operation completed successfully. ''' Though I have also used "Windows 7 7600 AIO.ISO" from MSDN * All In One = AIO file: Windows 7 7600 AIO.ISO md5sum: ace6c61269613bf515fd59c62185bbcf ''' PS C:\Users\Administrator> Dism /Get-WIMInfo /WimFile:d:\sources\install.wim Deployment Image Servicing and Management tool Version: 6.1.7600.16385 Details for image : d:\sources\install.wim Index : 1 Name : Windows 7 STARTER Description : Windows 7 STARTER Size : 7,936,340,784 bytes Index : 2 Name : Windows 7 HOMEBASIC Description : Windows 7 HOMEBASIC Size : 7,992,394,907 bytes Index : 3 Name : Windows 7 HOMEPREMIUM Description : Windows 7 HOMEPREMIUM Size : 8,432,859,356 bytes Index : 4 Name : Windows 7 PROFESSIONAL Description : Windows 7 PROFESSIONAL Size : 8,313,318,889 bytes Index : 5 Name : Windows 7 ULTIMATE Description : Windows 7 ULTIMATE Size : 8,471,060,645 bytes Index : 6 Name : Windows 7 Home Basic X64 Description : Windows 7 HOMEBASIC Size : 11,500,789,302 bytes Index : 7 Name : Windows 7 Home Premium X64 Description : Windows 7 HOMEPREMIUM Size : 12,012,660,212 bytes Index : 8 Name : Windows 7 Home Professional X64 Description : Windows 7 PROFESSIONAL Size : 11,910,752,928 bytes Index : 9 Name : Windows 7 Home Ultimate X64 Description : Windows 7 ULTIMATE Size : 12,070,211,908 bytes The operation completed successfully. ''' - place it in a directory called iso The installation uses the Standard way for Windows Unattended installation. The XML file was created using the Windows AIK kit, but the file can also be edited by hand. To edit the Autounattend.xml and validate it: You can download The Windows® Automated Installation Kit (AIK) for Windows® 7: url: http://www.microsoft.com/download/en/details.aspx?id=5753 file: KB3AIK_EN.iso md5sum: 1e73b24a89eceab9d50585b92db5482f - Building the machine creates a floppy that contains: - AutoUnattend.xml (that will configure the windows) - winrm-install.bat (activates the http and https listener + punches the firewall hole) AIK also includes dism, which will allow you to choose a specific version: If you want to install a different version, edit Autoattended.xml and replace the /IMAGE/NAME value with one of the names listed in the sources/install.wim on the install DVD.iso # <InstallFrom> # <MetaData wcm:action="add"> # <Key>/IMAGE/NAME</Key> # <Value>Windows Server 2008 R2 SERVERSTANDARD</Value> # </MetaData> # </InstallFrom> This gets us nearly there, but we still need a winrm provisioner, as I don't like having to install cygwin. Expose the winrm port: <pre> $ gem install chef $ gem install knife-windows #Create a tunnel $ ssh -p 7222 -L5985:localhost:5985 vagrant@localhost $ knife bootstrap windows winrm localhost -x Administrator -P 'vagrant' </pre> - http://wiki.opscode.com/display/chef/Knife+Windows+Bootstrap - https://github.com/opscode/knife-windows/blob/master/lib/chef/knife/bootstrap/windows-shell.erb - https://github.com/zenchild/WinRM - http://devopscloud.net/2011/04/17/managing-chef-from-windows-7/ - http://devopscloud.net/2011/04/28/powershell-userdata-to-start-a-chef-run/ - http://devopscloud.net/2011/03/23/dissection-of-a-chef-recipe-or-two-for-windows/ - https://github.com/pmorton/chef-windows-installer == https://github.com/zenchild/WinRM/issues/unreads#issue/1 http -> requires unencryptedwinrm quickconfig (said yes to enable firewall) winrm p winrm/config/service @{AllowUnencrypted="true"} winrm set winrm/config/service/auth @{Basic="true"}netsh advfirewall firewall set rule group="remote administration" new enable=yes - http://forums.citrix.com/thread.jspa?messageID=1535826 - http://support.microsoft.com/kb/2019527 winrm get winrm/config The purpose of configuring WinRM for HTTPS is to encrypt the data being sent across the wire. WinRM HTTPS requires a local computer "Server Authentication" certificate with a CN matching the hostname, that is not expired, revoked, or self-signed to be installed. To install or view certificates for the local computer: - click Start, run, MMC, "File" menu, "Add or Remove Snap-ins" select "Certificates" and click "Add". Go through the wizard selecting "Computer account". - Install or view the certificates under: Certificates (Local computer) Personal Certificates If you do not have a Sever Authenticating certificate consult your certicate administrator. If you have a microsoft Certificate server you may be abel to request a certificate using the web certificate template from HTTPS://<MyDomainCertificateServer>/certsrv Once the certificate is installed type the following to configure WINRM to listen on HTTPS: winrm quickconfig -transport:https If you do not have an appropriate certificate you can run the following with the authentication methods configured for WinRM however the data will not be encrypted. winrm quickconfig ======================= File: templates/openSUSE-12.3/README.md ======================= <reponame>ibizaman/veewee # openSUSE definition ## Warning! During automated steps a lot of crashes happened, in normal usage it works just fine. ======================= File: templates/windows-7-enterprise-amd64/README.md ======================= <filename>templates/windows-7-enterprise-amd64/README.md You can download a free trial of Windows 7 Enterprise 90-day Trial url: http://technet.microsoft.com/en-us/evalcenter/cc442495.aspx file: 7600.16385.090713-1255_x64fre_enterprise_en-us_EVAL_Eval_Enterprise-GRMCENXEVAL_EN_DVD.iso md5sum: 1d0d239a252cb53e466d39e752b17c28 ''' PS C:\Users\Administrator> Dism /Get-WIMInfo /WimFile:d:\sources\install.wim Deployment Image Servicing and Management tool Version: 6.1.7600.16385 Details for image : d:\sources\install.wim Index : 1 Name : Windows 7 ENTERPRISE Description : Windows 7 ENTERPRISE Size : 11,913,037,777 bytes The operation completed successfully. ''' - place it in a directory called iso The installation uses the Standard way for Windows Unattended installation. The XML file was created using the Windows AIK kit, but the file can also be edited by hand. To edit the Autounattend.xml and validate it: You can download The Windows® Automated Installation Kit (AIK) for Windows® 7: url: http://www.microsoft.com/download/en/details.aspx?id=5753 file: KB3AIK_EN.iso md5sum: 1e73b24a89eceab9d50585b92db5482f - Building the machine creates a floppy that contains: - AutoUnattend.xml (that will configure the windows) - winrm-install.bat (activates the http and https listener + punches the firewall hole) AIK also includes dism, which will allow you to choose a specific version: If you want to install a different version, edit Autoattended.xml and replace the /IMAGE/NAME value with one of the names listed in the sources/install.wim on the install DVD.iso # Use the Name : from 'Dism.exe /Get-WIMInfo /WimFile:d:\sources\install.wim' # <InstallFrom> # <MetaData wcm:action="add"> # <Key>/IMAGE/NAME</Key> # <Value>Windows 7 ENTERPRISE</Value> # </MetaData> # </InstallFrom> ======================= File: templates/windows-2012R2-serverdatacenter-amd64/README.md ======================= <reponame>ibizaman/veewee Microsoft Windows Server 2012 Veewee Definition ----------------------------------------------- You can download a free trial of Windows Server 2012 from Microsoft: * url: http://technet.microsoft.com/en-us/evalcenter/hh670538.aspx Place it in a directory called "iso". The installation uses the standard way for Windows Unattended installation. The XML file was created using the Windows ADK (Automated Deployment Kit), but it can also be edited by hand. To edit the Autounattend.xml and validate it: Download The Windows® Automated Deployment Kit (ADK) for Windows® 8: * url: http://www.microsoft.com/en-us/download/details.aspx?id=30652 Building the machine creates a floppy that contains: - Autounattend.xml (that will configure the windows) - oracle-cert.cer (certificate for VirtualBox tools) AIK also includes dism, which will allow you to choose a specific flavor of Windows 2012 to install. By default, this definition installs Server Standard. If you want to install a different version, edit Autounattend.xml and replace the /IMAGE/NAME value with one of the names listed in the 2012 install.wim on the install DVD ISO. ```xml <InstallFrom> <MetaData wcm:action="add"> <Key>/IMAGE/NAME</Key> <Value>Windows Server 2012 SERVERSTANDARD</Value> </MetaData> </InstallFrom> ``` ``` PS C:\Users\Administrator> Dism /Get-WIMInfo /WimFile:D:\sources\install.wim Deployment Image Servicing and Management tool Version: 6.2.9200.16384 Details for image : D:\sources\install.wim Index : 1 Name : Windows Server 2012 SERVERSTANDARDCORE Description : Windows Server 2012 SERVERSTANDARDCORE Size : 7,182,564,199 bytes Index : 2 Name : Windows Server 2012 SERVERSTANDARD Description : Windows Server 2012 SERVERSTANDARD Size : 12,002,145,363 bytes Index : 3 Name : Windows Server 2012 SERVERDATACENTERCORE Description : Windows Server 2012 SERVERDATACENTERCORE Size : 7,177,138,892 bytes Index : 4 Name : Windows Server 2012 SERVERDATACENTER Description : Windows Server 2012 SERVERDATACENTER Size : 11,997,664,663 bytes The operation completed successfully. ``` You will also need to change the KMS Client Setup key in the Autounattend.xml for the flavor you want: * url: http://technet.microsoft.com/en-us/library/jj612867.aspx ======================= File: templates/windows-7sp1-ultimate-amd64/README.md ======================= <reponame>ibizaman/veewee This uses the All In One "Windows 7 7600 AIO.ISO" from MSDN file: Windows 7 7600 AIO.ISO md5sum: ace6c61269613bf515fd59c62185bbcf ''' PS C:\Users\Administrator> Dism /Get-WIMInfo /WimFile:d:\sources\install.wim Deployment Image Servicing and Management tool Version: 6.1.7600.16385 Details for image : d:\sources\install.wim Index : 1 Name : Windows 7 STARTER Description : Windows 7 STARTER Size : 7,936,340,784 bytes Index : 2 Name : Windows 7 HOMEBASIC Description : Windows 7 HOMEBASIC Size : 7,992,394,907 bytes Index : 3 Name : Windows 7 HOMEPREMIUM Description : Windows 7 HOMEPREMIUM Size : 8,432,859,356 bytes Index : 4 Name : Windows 7 PROFESSIONAL Description : Windows 7 PROFESSIONAL Size : 8,313,318,889 bytes Index : 5 Name : Windows 7 ULTIMATE Description : Windows 7 ULTIMATE Size : 8,471,060,645 bytes Index : 6 Name : Windows 7 Home Basic X64 Description : Windows 7 HOMEBASIC Size : 11,500,789,302 bytes Index : 7 Name : Windows 7 Home Premium X64 Description : Windows 7 HOMEPREMIUM Size : 12,012,660,212 bytes Index : 8 Name : Windows 7 Home Professional X64 Description : Windows 7 PROFESSIONAL Size : 11,910,752,928 bytes Index : 9 Name : Windows 7 Home Ultimate X64 Description : Windows 7 ULTIMATE Size : 12,070,211,908 bytes The operation completed successfully. ''' - place it in a directory called iso The installation uses the Standard way for Windows Unattended installation. The XML file was created using the Windows AIK kit, but the file can also be edited by hand. To edit the Autounattend.xml and validate it: You can download The Windows® Automated Installation Kit (AIK) for Windows® 7: url: http://www.microsoft.com/download/en/details.aspx?id=5753 file: KB3AIK_EN.iso md5sum: 1e73b24a89eceab9d50585b92db5482f - Building the machine creates a floppy that contains: - AutoUnattend.xml (that will configure the windows) - winrm-install.bat (activates the http and https listener + punches the firewall hole) AIK also includes dism, which will allow you to choose a specific version: If you want to install a different version, edit Autoattended.xml and replace the /IMAGE/NAME value with one of the names listed in the sources/install.wim on the install DVD.iso # <InstallFrom> # <MetaData wcm:action="add"> # <Key>/IMAGE/NAME</Key> # <Value>Windows 7 ULTIMATE</Value> # </MetaData> # </InstallFrom> ======================= File: doc/parallels.md ======================= <filename>doc/parallels.md # Parallels VM Provider Documentation related to [Parallels](parallels.md) hasn't been completed yet. ======================= File: doc/vbox.md ======================= # VirtualBox VM Provider To interact with [VirtualBox](http://www.virtualbox.org/), Veewee executes shell-commands through the 'VboxManage' command. The `virtualbox` gem library proved to be less stable. ## Interacting with Guest Machine To simulate the typing, Veewee uses the `VBoxManage` command: `$ VBoxManage controlvm'myubuntu' keyboardputscancode <keycode>` [Scancodes](http://www.win.tue.nl/~aeb/linux/kbd/scancodes-1.html) are injected directly from the keyboard buffer with this command. Because this buffer is small, Veewee can't type fast(er). This is why you'll notice a delay before Veewee types the commands. Speeding it up would make the keyboard buffer lose keystrokes. ## VirtualBox OS_Types VirtualBox supports a wide variety of Guest Operating Systems. The table below is a partial list of a few of the popular `os_types`. *For a complete list* run the `virtualbox` command: `VBoxManage list ostypes` OS_TYPE_ID | DESCRIPTION -------------- | ------------------- ArchLinux_64 | Arch Linux (64 bit) ArchLinux | Arch Linux Debian_64 | Debian (64 bit) Debian | Debian Fedora_64 | Fedora (64 bit) Fedora | Fedora FreeBSD_64 | FreeBSD (64 bit) FreeBSD | FreeBSD Gentoo_64 | Gentoo (64 bit) Gentoo | Gentoo MacOS_64 | Mac OS X (64 bit) MacOS | Mac OS X OpenSUSE_64 | openSUSE (64 bit) Other | Other/Unknown (32bit) RedHat_64 | CentOS (64 bit) RedHat | CentOS RedHat_64 | Red Hat (64 bit) RedHat | Red Hat Ubuntu_64 | Ubuntu (64 bit) Ubuntu | Ubuntu Windows2012_64 | Windows 2012 (64 bit) Windows81_64 | Windows 8.1 (64 bit) Windows81 | Windows 8.1 Windows8 | Windows 8 ## Guest Machine Settings `Virtualbox` creates *default VM settings* for a new Guest Machine based on the internal `os_type`. For example, 64bit machines are setup with IO_APIC on so that guest machines can utilize multiple CPU's. 32bit Machines have IO_APIC off by default, even though modern 32-bit systems have [good support for SMP](http://en.wikipedia.org/wiki/Intel_APIC_Architecture#Problems). Therefore this, and other settings can be overridden within the `definion.rb` file, by using an array similar to: :virtualbox => { :vm_options => [ # Some example settings 'audio' => 'null', # Enable Audio by setting host to null driver 'audiocontroller' => 'hda', # Use simulated Intel HD audio 'ioapic' => 'on', # APIC is necessary for symmetric multiprocessor (SMP) support 'rtcuseutc' => 'on', # UTC internal time 'usb' => 'on', 'mouse' => 'usbtablet', # Enable absolute pointing device 'usbwebcam' => 'on', 'accelerate3d' => 'on', # Necessary for X to start the Unity desktop in Ubuntu 12.10+ -- Useful for 12.04, although can slow the VM if host hardware lacks good 3D support 'clipboard' => 'bidirectional' # Useful for clipboard sharing between host & guest 'nonrotational' => 'on' # Useful for guest OS's like Windows, so disk utilities aren't run # A Full list of settings can be found here: http://virtualbox.org/manual/ch08.html#idp51057568 # Or generated based on the current settings of a virtualbox guest, such a machine named: myubuntu # VBoxManage showvminfo --machinereadable'myubuntu' ] } ======================= File: templates/windows-2008R2-serverwebcore-amd64/README.md ======================= You can download a free trial of Windows Server 2008 R2 with Service Pack 1: url: http://technet.microsoft.com/en-us/evalcenter/dd459137.aspx url: http://msdn.microsoft.com/en-us/evalcenter/ee175713.aspx 64bit file: 7601.17514.101119-1850_x64fre_server_eval_en-us-GRMSXEVAL_EN_DVD.iso md5sum: 4263be2cf3c59177c45085c0a7bc6ca5 - place it in a directory called iso The installation uses the Standard way for Windows Unattended installation. The XML file was created using the Windows AIK kit, but the file can also be edited by hand. To edit the Autounattend.xml and validate it: You can download The Windows® Automated Installation Kit (AIK) for Windows® 7: url: http://www.microsoft.com/download/en/details.aspx?id=5753 file: KB3AIK_EN.iso md5sum: 1e73b24a89eceab9d50585b92db5482f - Building the machine creates a floppy that contains: - AutoUnattend.xml (that will configure the windows) - winrm-install.bat (activates the http and https listener + punches the firewall hole) AIK also includes dism, which will allow you to choose a specific version: If you want to install a different version, edit Autoattended.xml and replace the /IMAGE/NAME value with one of the names listed in the 2008r2 install.wim on the install DVD.iso # <InstallFrom> # <MetaData wcm:action="add"> # <Key>/IMAGE/NAME</Key> # <Value>Windows Server 2008 R2 SERVERSTANDARD</Value> # </MetaData> # </InstallFrom> PS C:\Users\Administrator> Dism /Get-WIMInfo /WimFile:d:\sources\install.wim Deployment Image Servicing and Management tool Version: 6.1.7600.16385 Details for image : d:\sources\install.wim Index : 1 Name : Windows Server 2008 R2 SERVERSTANDARD Description : Windows Server 2008 R2 SERVERSTANDARD Size : 10,510,643,622 bytes Index : 2 Name : Windows Server 2008 R2 SERVERSTANDARDCORE Description : Windows Server 2008 R2 SERVERSTANDARDCORE Size : 3,564,132,307 bytes Index : 3 Name : Windows Server 2008 R2 SERVERENTERPRISE Description : Windows Server 2008 R2 SERVERENTERPRISE Size : 10,511,024,733 bytes Index : 4 Name : Windows Server 2008 R2 SERVERENTERPRISECORE Description : Windows Server 2008 R2 SERVERENTERPRISECORE Size : 3,564,106,331 bytes Index : 5 Name : Windows Server 2008 R2 SERVERDATACENTER Description : Windows Server 2008 R2 SERVERDATACENTER Size : 10,511,131,897 bytes Index : 6 Name : Windows Server 2008 R2 SERVERDATACENTERCORE Description : Windows Server 2008 R2 SERVERDATACENTERCORE Size : 3,564,144,547 bytes Index : 7 Name : Windows Server 2008 R2 SERVERWEB Description : Windows Server 2008 R2 SERVERWEB Size : 10,520,222,743 bytes Index : 8 Name : Windows Server 2008 R2 SERVERWEBCORE Description : Windows Server 2008 R2 SERVERWEBCORE Size : 3,562,750,400 bytes The operation completed successfully. This gets us nearly there, but we still need a winrm provisioner, as I don't like having to install cygwin. Expose the winrm port: <pre> $ gem install chef $ gem install knife-windows #Create a tunnel $ ssh -p 7222 -L5985:localhost:5985 vagrant@localhost $ knife bootstrap windows winrm localhost -x Administrator -P 'vagrant' </pre> - http://wiki.opscode.com/display/chef/Knife+Windows+Bootstrap - https://github.com/opscode/knife-windows/blob/master/lib/chef/knife/bootstrap/windows-shell.erb - https://github.com/zenchild/WinRM - http://devopscloud.net/2011/04/17/managing-chef-from-windows-7/ - http://devopscloud.net/2011/04/28/powershell-userdata-to-start-a-chef-run/ - http://devopscloud.net/2011/03/23/dissection-of-a-chef-recipe-or-two-for-windows/ - https://github.com/pmorton/chef-windows-installer == https://github.com/zenchild/WinRM/issues/unreads#issue/1 http -> requires unencryptedwinrm quickconfig (said yes to enable firewall) winrm p winrm/config/service @{AllowUnencrypted="true"} winrm set winrm/config/service/auth @{Basic="true"}netsh advfirewall firewall set rule group="remote administration" new enable=yes - http://forums.citrix.com/thread.jspa?messageID=1535826 - http://support.microsoft.com/kb/2019527 winrm get winrm/config The purpose of configuring WinRM for HTTPS is to encrypt the data being sent across the wire. WinRM HTTPS requires a local computer "Server Authentication" certificate with a CN matching the hostname, that is not expired, revoked, or self-signed to be installed. To install or view certificates for the local computer: - click Start, run, MMC, "File" menu, "Add or Remove Snap-ins" select "Certificates" and click "Add". Go through the wizard selecting "Computer account". - Install or view the certificates under: Certificates (Local computer) Personal Certificates If you do not have a Sever Authenticating certificate consult your certicate administrator. If you have a microsoft Certificate server you may be abel to request a certificate using the web certificate template from HTTPS://<MyDomainCertificateServer>/certsrv Once the certificate is installed type the following to configure WINRM to listen on HTTPS: winrm quickconfig -transport:https If you do not have an appropriate certificate you can run the following with the authentication methods configured for WinRM however the data will not be encrypted. winrm quickconfig ======================= File: README.md ======================= <gh_stars>1000+ # Veewee [![Build Status](https://travis-ci.org/jedi4ever/veewee.png)](https://travis-ci.org/jedi4ever/veewee) Veewee is a tool for easily (and repeatedly) building custom [Vagrant](https://github.com/mitchellh/vagrant) base boxes, KVMs, and virtual machine images. ## About Vagrant Vagrant is a great tool for creating and configuring lightweight, reproducible, portable virtual machine environments - often used with the addition of automation tools such as [Chef](https://github.com/opscode/chef) or [Puppet](https://github.com/puppetlabs/puppet). The first step to build a new virtual machine is to download an existing 'base box'. I believe this scares a lot of people as they don't know how these unverified boxes were built. Therefore a lot of people end up building their own base box which is often time consuming and cumbersome. Veewee aims to automate all the steps for building base boxes and to collect best practices in a transparent way. ## Veewee's Supported VM Providers Veewee isn't only for Vagrant. It currently supports exporting VM images for the following providers: * [VirtualBox](http://www.virtualbox.org/) - exports to `OVF` filetype * [VMware (Fusion)](http://www.vmware.com/products/fusion/) - exports to `OVA` filetype * [KVM](http://www.linux-kvm.org/) - exports to `IMG` filetype * [Parallels](http://www.parallels.com/) - none yet, but can export to `parallels` format (provided by [vagrant-parallels](https://github.com/yshahin/vagrant-parallels)) ## Getting Started Before you start, we recommend reading through these pages: * [Requirements](doc/requirements.md) that must be met before installing Veewee * [Veewee Installation](doc/installation.md) instructions * [Command Options](doc/commands.md) highlights various approaches for executing Veewee on the command line Next, learn about Veewee fundamentals: * [Veewee Basics](doc/basics.md) covers creating standard-issue boxes * [Customizing Definitions](doc/customize.md) helps you fine tune each box definition to meet your exact needs * [Veeweefile](doc/veeweefile.md) can be used to define your own paths Then depending on how you want to use Veewee, we suggest to read through one of the following guides: * [Guide for Vagrant](doc/vagrant.md) * [Guide for VirtualBox](doc/vbox.md) * [Guide for VMware Fusion](doc/fusion.md) * [Guide for KVM](doc/kvm.md) * [Guide for Parallels Desktop](doc/parallels.md) Major noteworthy changes between versions can be found here: * [Changes](doc/changes.md) between versions A complete list of all docs can be found by viewing the [doc directory](doc). ## Veewee Commands Below is an overview of the `veewee` command options: $ bundle exec veewee # Commands: # veewee add_share # Adds a Share to the Guest # veewee fusion # Subcommand for Vmware fusion # veewee help [COMMAND] # Describe available commands or one specific command # veewee kvm # Subcommand for KVM # veewee parallels # Subcommand for Parallels # veewee vbox # Subcommand for VirtualBox # veewee version # Prints the Veewee version information Learn how to avoid typing `bundle exec` by visiting the [Commands](doc/commands.md) doc. ## Veewee Provider Subcommands Below is an overview of the `veewee` provider subcommand options: $ bundle exec veewee <provider> # Commands: # veewee <provider> build [BOX_NAME] # Build box # veewee <provider> copy [BOXNAME] [SRC] [DST] # Copy a file to the VM # veewee <provider> define [BOXNAME] [TEMPLATE] # Define a new basebox starting from a template # veewee <provider> destroy [BOXNAME] # Destroys the basebox that was built # veewee <provider> halt [BOXNAME] # Activates a shutdown on the basebox # veewee <provider> help [COMMAND] # Describe subcommands or one specific subcommand # veewee <provider> list # Lists all defined boxes # veewee <provider> ostypes # List the available Operating System types # veewee <provider> screenshot [NAME] [PNGFILENAME] # Takes a screenshot of the box # veewee <provider> ssh [BOXNAME] [COMMAND] # Interactive ssh login # veewee <provider> templates # List the currently available templates # veewee <provider> undefine [BOXNAME] # Removes the definition of a basebox # veewee <provider> up [BOXNAME] # Starts a Box # veewee <provider> validate [NAME] # Validates a box against vagrant compliancy rules # veewee <provider> winrm [BOXNAME] [COMMAND] # Execute command via winrm ## Contribute People have reported good experiences, why don't you give it a try? If you have a setup working, share your 'definition' with me. That would be fun! See [CONTRIBUTE.md](CONTRIBUTE.md). ======================= File: templates/CentOS-5.8-x86_64-reallyminimal/README.md ======================= <reponame>ibizaman/veewee # CentOS-5.8-x86_64-reallyminimal This is a really minimal installation of CentOS 5.8. It comes out to 200MB. ======================= File: CONTRIBUTE.md ======================= # Contribute to Veewee If you are looking to improve Veewee in some manner, you've come to the right place. ## TODOs A running [TODO](doc/TODO.md) list is available for ideas on future improvements. ## Steps to Contribute ### Getting started In order to contribute anything, you'll want to follow these steps first: * Get an account on [Github](https://github.com) * Then fork the [veewee repository](https://github.com/jedi4ever/veewee) to your own Github account * If you haven't already, familiarize yourself with the [Requirements](doc/requirements.md) and [Installation](doc/installation.md) docs * Clone the veewee **fork** to your machine: ~~~ sh $ cd <path_to_workspace> $ git clone https://github.com/<your github account>/veewee.git $ cd veewee ~~~ * Check out a new branch to make your changes on: `git checkout -b <your_new_patch>` ### For adding a new Template If you have a new and amazing Veewee definition, share your 'template'. That would be fun! * Before saving changes to a 'template', first try your changes in `definitions/mynewos/` * Build the box and run the **validation** tests * When the box builds OK and all tests are green, move `definition/mynewos/` to a sensible directory under the `templates/` directory. **Hint:** Follow the same naming schema of existing boxes (explained in the [Veewee Basics](doc/basics.md) doc) ### For adding new Features * Run any existing tests that are related to your patch * For bonus points add tests to validate your changes ### To submit your Contribution * Please commit with descriptive messages * Submit a pull request on Github from the __your_new_patch__ branch on __your fork__ to the __master__ branch on __jedi4ever/veewee__ * One of the editors will review the change, and either merge it or provide some feedback. Community review is also encouraged. ======================= File: templates/alpinelinux-3.6.2-x86_64-virtual/README.md ======================= <gh_stars>1000+ # Alpine Linux Minimal build of the 'Virtual'-Image. ## Note * The template currently only supports the VirtualBox provider * shutdown for vagrant is provided under /usr/local/bin * ``who`` and alike do not work because of [musl][] not providing utmp * if you want alpine-sdk with aports include ``aports.sh in`` in ``definition.rb`` [musl]: http://wiki.musl-libc.org/wiki/FAQ#Q:_why_is_the_utmp.2Fwtmp_functionality_only_implemented_as_stubs_.3F # Alpine Linux ======================= File: doc/TODO.md ======================= # TODO ## Ideas * Integrate Veewee with your CI build to create baseboxes on a daily basis * Use of pre_postinstall_file in `definition.rb` _by whren - 2012-04-12_. See [use of pre_postinstall_file in definition.rb](https://github.com/whren/veewee/wiki/use-of-pre_postinstall_file-in-definition.rb)] ## Requirements virtualbox -> kvm -> ruby-libvirt gem v0.8.3 or higher require libvirt 0.8+ version have a default dir pool installed permissions to write create new volumes vmfusion -> VMWare fusion installed Tested on VMWare fusion 0.3.x ## Changes to Definitions Virtualbox options ioapic, pae are now moved to :virtualbox => { vm_options => [ :ioapic => 'on' ]} ; Now you can pass all options you have to virtualbox ## Use as a library ostype_id (not used for all providers) Rakefile contains check iso Rakefile contains test Rakefile contains real_test ## Templates check for.veewee_version or.vmfusion_version to see for which provider we are building this include/exclude can do this default user becomes veewee, vagrant.sh will create the vagrant user if used under vagrant uploading vmware.iso uploading virtualbox.iso ## Validation veewee.feature (depending on virtualbox, vagrant) no more ssh_steps uses @tags per provider # veewee vmfusion export ova # vagrant basebox export box ## New options --postinstall-include/exclude --auto (download yes) --force also for export --debug (debug output) ostypes are now synchronized accross kvm ## More Todos veewee steps (username,password, + VEEWEE env variables) validate vms - + features selection check libvirt version windows test validation of checks (also - include/exclude) check execs with exit code multinetwork card dkms for kernel installs ======================= File: templates/windows-8-preview-amd64/README.md ======================= <reponame>ibizaman/veewee You can download a free trial of Windows Server 2008 Enterprise: (60 day eval, expandable to 240 days) From http://www.microsoft.com/download/en/details.aspx?id=8371 64bit url: http://download.microsoft.com/download/B/4/D/B4DC75A1-D7D2-4F31-87F9-E02C950E8D31/6001.18000.080118-1840_amd64fre_Server_en-us-KRMSXFRE_EN_DVD.iso filename: 6001.18000.080118-1840_amd64fre_Server_en-us-KRMSXFRE_EN_DVD.iso md5sum: 0477c88678efb8ebc5cd7a9e9efd8b82 32bit url: http://download.microsoft.com/download/B/4/D/B4DC75A1-D7D2-4F31-87F9-E02C950E8D31/6001.18000.080118-1840_x86fre_Server_en-us-KRMSFRE_EN_DVD.iso - place it in a directory called iso The installation uses the Standard way for Windows Unattended installation. The XML file was created using the Windows AIK kit, but the file can also be edited by hand. You can download Automated Installation Kit (AIK) for Windows Vista SP1 and Windows Server 2008: from http://www.microsoft.com/download/en/details.aspx?id=9085 file: 6001.18000.080118-1840-kb3aikl_en.iso md5sum: b83fad8fd28e637b82cb4a6bef7d6920 - Building the machine creates a floppy that contains: - AutoUnattend.xml (that will configure the windows) - winrm-install.bat (activates the http and https listener + punches the firewall hole) AIK also includes dism, which will allow you to choose a specific version: If you want to install a different version, edit Autoattended.xml and replace the /IMAGE/NAME value with one of the names listed in the Longhorn install.wim on the install.iso <InstallFrom> <MetaData wcm:action="add"> <Key>/IMAGE/NAME</Key> <Value>Windows Longhorn SERVERSTANDARD</Value> ### This comes from the Name: field below </MetaData> </InstallFrom> PS C:\Users\Administrator> Dism /Get-WIMInfo /WimFile:d:\sources\install.wim Deployment Image Servicing and Management tool Version: 6.1.7600.16385 Details for image : d:\sources\install.wim Index : 1 Name : Windows Longhorn SERVERSTANDARD Description : Windows Longhorn SERVERSTANDARD Size : 8,784,297,519 bytes Index : 2 Name : Windows Longhorn SERVERENTERPRISE Description : Windows Longhorn SERVERENTERPRISE Size : 8,792,036,862 bytes Index : 3 Name : Windows Longhorn SERVERDATACENTER Description : Windows Longhorn SERVERDATACENTER Size : 8,792,568,645 bytes Index : 4 Name : Windows Longhorn SERVERSTANDARDCORE Description : Windows Longhorn SERVERSTANDARDCORE Size : 2,512,939,954 bytes Index : 5 Name : Windows Longhorn SERVERENTERPRISECORE Description : Windows Longhorn SERVERENTERPRISECORE Size : 2,522,686,340 bytes Index : 6 Name : Windows Longhorn SERVERDATACENTERCORE Description : Windows Longhorn SERVERDATACENTERCORE Size : 2,522,615,418 bytes This gets us nearly there, but we still need a winrm provisioner, as I don't like having to install cygwin. Expose the winrm port: <pre> $ gem install chef $ gem install knife-windows #Create a tunnel $ ssh -p 7222 -L5985:localhost:5985 vagrant@localhost $ knife bootstrap windows winrm localhost -x Administrator -P 'vagrant' </pre> - http://wiki.opscode.com/display/chef/Knife+Windows+Bootstrap - https://github.com/opscode/knife-windows/blob/master/lib/chef/knife/bootstrap/windows-shell.erb - https://github.com/zenchild/WinRM - http://devopscloud.net/2011/04/17/managing-chef-from-windows-7/ - http://devopscloud.net/2011/04/28/powershell-userdata-to-start-a-chef-run/ - http://devopscloud.net/2011/03/23/dissection-of-a-chef-recipe-or-two-for-windows/ - https://github.com/pmorton/chef-windows-installer == https://github.com/zenchild/WinRM/issues/unreads#issue/1 http -> requires unencryptedwinrm quickconfig (said yes to enable firewall) winrm p winrm/config/service @{AllowUnencrypted="true"} winrm set winrm/config/service/auth @{Basic="true"}netsh advfirewall firewall set rule group="remote administration" new enable=yes - http://forums.citrix.com/thread.jspa?messageID=1535826 - http://support.microsoft.com/kb/2019527 winrm get winrm/config The purpose of configuring WinRM for HTTPS is to encrypt the data being sent across the wire. WinRM HTTPS requires a local computer "Server Authentication" certificate with a CN matching the hostname, that is not expired, revoked, or self-signed to be installed. To install or view certificates for the local computer: - click Start, run, MMC, "File" menu, "Add or Remove Snap-ins" select "Certificates" and click "Add". Go through the wizard selecting "Computer account". - Install or view the certificates under: Certificates (Local computer) Personal Certificates If you do not have a Sever Authenticating certificate consult your certicate administrator. If you have a microsoft Certificate server you may be abel to request a certificate using the web certificate template from HTTPS://<MyDomainCertificateServer>/certsrv Once the certificate is installed type the following to configure WINRM to listen on HTTPS: winrm quickconfig -transport:https If you do not have an appropriate certificate you can run the following with the authentication methods configured for WinRM however the data will not be encrypted. winrm quickconfig ======================= File: templates/VMware-ESXi-5.1-x86_64/vagrant_key.py ======================= <gh_stars>1000+ #!/bin/python import urllib vagrant_key = "https://raw.github.com/mitchellh/vagrant/master/keys/vagrant.pub" urllib.urlretrieve( vagrant_key, "/etc/ssh/keys-root/authorized_keys") ======================= File: lib/python/parallels_sdk_check.py ======================= import sys import prlsdkapi prlsdk = prlsdkapi.prlsdk consts = prlsdkapi.prlsdk.consts # Initialize the Parallels API Library prlsdk.InitializeSDK(consts.PAM_DESKTOP_MAC) # Obtain a server object identifying the Parallels Service. server = prlsdkapi.Server() # Log in. (local as we do Parallels Desktop login_job=server.login_local() login_job.wait() # Logoff and deinitialize the library server.logoff() prlsdkapi.deinit_sdk ======================= File: lib/python/parallels_send_key.py ======================= <reponame>ibizaman/veewee<filename>lib/python/parallels_send_key.py import sys import prlsdkapi if len(sys.argv)!= 4: print "Usage: parallels_send_keycode '<VM_NAME>' '<keyname>' '<press|release>'" exit() # Parse arguments vm_name=sys.argv[1] # Keycode to use keyname=sys.argv[2] # Release or press state=sys.argv[3] print "Sending keyname '%(keyname)s' to VM '%(vm_name)s'" % {"keyname": keyname, "vm_name":vm_name} prlsdk = prlsdkapi.prlsdk consts = prlsdkapi.prlsdk.consts # Initialize the Parallels API Library prlsdk.InitializeSDK(consts.PAM_DESKTOP_MAC) # Obtain a server object identifying the Parallels Service. server = prlsdkapi.Server() # Log in. (local as we do Parallels Desktop login_job=server.login_local() login_job.wait() # Get a list of virtual machines. # Find the specified virtual machine and # obtain an object identifying it. vm_list = server.get_vm_list() result= vm_list.wait() print prlsdkapi.prlsdk.consts.ScanCodesList # Look for the VM with the name speficied on the CLI found = False for i in range(result.get_params_count()): VM = result.get_param_by_index(i) print VM.get_name() if VM.get_name() == vm_name: found = True break press = consts.PKE_PRESS release = consts.PKE_RELEASE # Access the Remote Desktop Access session vm_io = prlsdkapi.VmIO() try: vm_io.connect_to_vm(VM).wait() except prlsdkapi.PrlSDKError, e: print "Error: %s" % e exit() scan_code = consts.ScanCodesList[keyname] if state == 'press': vm_io.send_key_event(VM,scan_code,press) elif state =='release': vm_io.send_key_event(VM,scan_code,release) else: print "invalid state: %s" % state exit() # End the Remote Deskop Access session vm_io.disconnect_from_vm(VM) # Logoff and deinitialize the library server.logoff() prlsdkapi.deinit_sdk ======================= File: lib/python/parallels_send_string.py ======================= import sys import prlsdkapi import string if len(sys.argv)!= 3: print "Usage: parallels_send_string '<VM_NAME>' '<string>'" exit() # Parse arguments vm_name=sys.argv[1] # String to use keynames = sys.argv[2].split(' '); prlsdk = prlsdkapi.prlsdk consts = prlsdkapi.prlsdk.consts # Initialize the Parallels API Library prlsdk.InitializeSDK(consts.PAM_DESKTOP_MAC) # Obtain a server object identifying the Parallels Service. server = prlsdkapi.Server() # Log in. (local as we do Parallels Desktop login_job=server.login_local() login_job.wait() # Get a list of virtual machines. # Find the specified virtual machine and # obtain an object identifying it. vm_list = server.get_vm_list() result= vm_list.wait() print prlsdkapi.prlsdk.consts.ScanCodesList # Look for the VM with the name speficied on the CLI found = False for i in range(result.get_params_count()): VM = result.get_param_by_index(i) print VM.get_name() if VM.get_name() == vm_name: found = True break press = consts.PKE_PRESS release = consts.PKE_RELEASE # Access the Remote Desktop Access session vm_io = prlsdkapi.VmIO() try: vm_io.connect_to_vm(VM).wait() except prlsdkapi.PrlSDKError, e: print "Error: %s" % e exit() for keyname in keynames: if(keyname!= ''): # Keys can also contain special keys like shift, that has to be pressed before and release after # eg. SHIFT-C (Press shift, then press C) keys = keyname.split('#'); for keypress in keys: scan_code = consts.ScanCodesList[keypress] vm_io.send_key_event(VM,scan_code,press,50) # And now the reversed order # eg. Now release C then SHIFT for keypress in reversed(keys): scan_code = consts.ScanCodesList[keypress] vm_io.send_key_event(VM,scan_code,release,50) # End the Remote Deskop Access session vm_io.disconnect_from_vm(VM) # Logoff and deinitialize the library server.logoff() prlsdkapi.deinit_sdk ======================= File: lib/fission.old/command/snapshot_revert.rb ======================= module Fission class Command class SnapshotRevert < Command def initialize(args=[]) super end def execute unless @args.count == 2 Fission.ui.output self.class.help Fission.ui.output '' Fission.ui.output_and_exit 'Incorrect arguments for snapshot revert command', 1 end vm_name, snap_name = @args.take 2 vm = Fission::VM.new vm_name unless vm.exists? vm_name Fission.ui.output_and_exit "Unable to find the VM #{vm_name} (#{Fission::VM.path(vm_name)})", 1 end if Fission::Fusion.running? Fission.ui.output 'It looks like the Fusion GUI is currently running' Fission.ui.output_and_exit 'Please exit the Fusion GUI and try again', 1 end snaps = vm.snapshots unless snaps.include? snap_name Fission.ui.output_and_exit "Unable to find the snapshot '#{snap_name}'", 1 end Fission.ui.output "Reverting to snapshot '#{snap_name}'" task = vm.revert_to_snapshot snap_name if task.successful? Fission.ui.output "Reverted to snapshot '#{snap_name}'" else Fission.ui.output_and_exit "There was an error reverting to the snapshot. The error was:\n#{task.output}", task.code end end def option_parser optparse = OptionParser.new do |opts| opts.banner = "\nsnapshot revert: fission snapshot revert my_vm snapshot_1" end optparse end end end end ======================= File: templates/Debian-9.1-amd64-netboot/definition.rb ======================= <filename>templates/Debian-9.1-amd64-netboot/definition.rb # # change debian_64_netinst to one of configurations in *.yml in this directory # use the yml files to configure # Veewee::Definition.declare_yaml('definition.yml', "debian_64_net.yml") ======================= File: templates/CentOS-6.5/definition.rb ======================= # # change centos_64_dvd to one of configurations in *.yml in this directory # use the yml files to configure # Veewee::Definition.declare_yaml('definition.yml', "centos_64_minimal.yml") ======================= File: templates/funtoo-unstable-x86_64/definition.rb ======================= password = '<PASSWORD>' builddate = '20131226' iso = "install-amd64-minimal-#{builddate}.iso" Veewee::Session.declare({ :hostiocache => 'off', :cpu_count => '1', :memory_size=> '384', :disk_size => '40560', # 40 GB :disk_format => 'VDI', :os_type_id => 'Gentoo_64', # for 32bit, change to 'Gentoo' :iso_file => iso, :iso_src => "http://mirror.switch.ch/ftp/mirror/gentoo/releases/amd64/autobuilds/#{builddate}/#{iso}", :iso_sha512 => "4a19a59c5fa5f2d3a8fd31cde2379abafcb0e3c720884471e1dc0b2557fda3328198dea728d8c6f792a0ccf3e56f1e4dfadbdcb41e38bb675b8de0bea36ab0a9", :iso_download_timeout => "1000", :boot_wait => "4", :boot_cmd_sequence => [ '<Wait>'*1, '<Enter>', '<Wait>'*9, '<Enter>', '<Wait>'*12, '<Enter><Wait>', # just in case we are out of sync 'net-setup eth0<Enter><Wait><Enter>2<Enter>1<Enter><Wait><Wait>', 'ifconfig -a <Enter><Wait><Wait>', 'passwd<Enter><Wait><Wait>', password + '<Enter><Wait>', password + '<Enter><Wait><Wait>', '/etc/init.d/sshd start<Enter><Wait><Wait>' ], :ssh_login_timeout => "10000", :ssh_user => "root", :ssh_password => password, :ssh_key => "", :ssh_host_port => "7222", :ssh_guest_port => "22", :sudo_cmd => "cat '%f'|su -", :shutdown_cmd => "init 0", :postinstall_files => ["postinstall.sh"], :postinstall_timeout => "15000" }) ======================= File: lib/veewee/command/fusion.rb ======================= module Veewee module Command class Fusion < Veewee::Command::GroupBase register :command => "fusion", :description => "Subcommand for Vmware fusion", :provider => "vmfusion" desc "build [BOX_NAME]", "Build box" # TODO move common build options into array method_option :force,:type => :boolean, :default => false, :aliases => "-f", :desc => "force the build" method_option :nogui,:type => :boolean, :default => false, :aliases => "-n", :desc => "no gui" method_option :auto,:type => :boolean, :default => false, :aliases => "-a", :desc => "auto answers" method_option :checksum, :type => :boolean, :default => false, :desc => "verify checksum" method_option :postinstall_include, :type => :array, :default => [], :aliases => "-i", :desc => "ruby regexp of postinstall filenames to additionally include" method_option :postinstall_exclude, :type => :array, :default => [], :aliases => "-e", :desc => "ruby regexp of postinstall filenames to exclude" method_option :skip_to_postinstall, :aliases => ['--skip-to-postinstall'], :type => :boolean, :default => false, :desc => "Skip to postinstall." def build(box_name) env.get_box(box_name).build(options) end desc "validate [BOX_NAME]", "Validates a box against vmfusion compliancy rules" method_option :tags, :type => :array, :default => %w{vmfusion puppet chef}, :aliases => "-t", :desc => "tags to validate" def validate(box_name) env.get_box(box_name).validate_vmfusion(options) end desc "export [BOX_NAME]", "Exports the basebox to the vagrant format" method_option :force,:type => :boolean, :default => false, :aliases => "-f", :desc => "overwrite existing file" method_option :export_type, :type => :string, :default => "vagrant", :desc => "export into vmware ova or vagrant box format" def export(box_name) env.get_box(box_name).export_vmfusion(options) end desc "add_share [BOX_NAME] [SHARE_NAME] [SHARE_PATH]", "Adds a share to the guest" def add_share(box_name, share_name, share_path) # command="#{File.dirname().shellescape}/vmware-vdiskmanager -c -s #{definition.disk_size}M -a lsilogic -t #{disk_type} #{name}.vmdk" # shell_results=shell_exec("#{command}",{:mute => true}) env.get_box(box_name).add_share(share_name, share_path) end end end end ======================= File: lib/fission.old/command/status.rb ======================= module Fission class Command class Status < Command def initialize(args=[]) super end def execute all_vms=Fission::VM.all vm_with_longest_name = all_vms.max { |a,b| a.name.length <=> b.name.length } max_name_length=vm_with_longest_name.name.length all_vms.each do |vm| status = vm.state Fission.ui.output_printf "%-#{max_name_length}s %s\n", vm.name, "["+status+"]" end end def option_parser optparse = OptionParser.new do |opts| opts.banner = "\nstatus usage: fission status" end optparse end end end end ======================= File: lib/veewee/provider/core/provider.rb ======================= require'veewee/provider/core/helper/shell' module Veewee module Provider module Core class Provider attr_accessor :env attr_accessor :options attr_accessor :type attr_accessor :name include ::Veewee::Provider::Core::Helper::Shell def ui return @_ui if defined?(@_ui) @_ui = @env.ui.dup @_ui.resource = @name @_ui end def initialize(name,options,env) @env=env @name=name @options=options @type=self.class.to_s.split("::")[-2] check_requirements end def get_box(name) begin require_path='veewee/provider/'+type.to_s.downcase+"/box.rb" require require_path # Get a real box object from the Provider box=Object.const_get("Veewee").const_get("Provider").const_get(type.to_s.capitalize).const_get("Box").new(name,env) # Attach the provider to the box box.provider = self return box rescue Error => ex ui.error "Could not instantiate the box #{name} with provider #{type},#{ex}" raise end end def self.available? begin self.check_requirements return true rescue Error return false end end def gem_available?(gemname) env.logger.info "Checking for gem #{gemname}" available=false begin available=true unless Gem::Specification::find_by_name("#{gemname}").nil? rescue Gem::LoadError env.logger.info "Error loading gem #{gemname}" available=false rescue env.logger.info "Falling back to old syntax for #{gemname}" available=Gem.available?("#{gemname}") env.logger.info "Old syntax #{gemname}.available? #{available}" end return available end def gems_available?(names) names.each do |gemname| return false if!gem_available?(gemname) end return true end end #End Class end #End Module end #End Module end #End Module ======================= File: templates/openSUSE-13.1/definition.rb ======================= <reponame>ibizaman/veewee # # change opensuse_64_dvd to one of configurations in *.yml in this directory # use the yml files to configure # Veewee::Definition.declare_yaml('definition.yml', 'opensuse_64_dvd.yml') ======================= File: lib/fission.old/command/suspend.rb ======================= module Fission class Command class Suspend < Command def initialize(args=[]) super @options.all = false end def execute option_parser.parse! @args if @args.count!= 1 &&[email protected] Fission.ui.output self.class.help Fission.ui.output "" Fission.ui.output_and_exit "Incorrect arguments for suspend command", 1 end vms_to_suspend.each do |vm| Fission.ui.output "Suspending '#{vm.name}'" task = vm.suspend if task.successful? Fission.ui.output "VM '#{vm.name}' suspended" else Fission.ui.output_and_exit "There was an error suspending the VM. The error was:\n#{task.output}", task.code end end end def vms_to_suspend if @options.all vms=Fission::VM.all_running else vm_name = @args.first vm=Fission::VM.new(vm_name) unless vm.exists? Fission.ui.output '' Fission.ui.output_and_exit "VM #{vm_name} does not exist (#{Fission::VM.path(vm_name)})", 1 end unless vm.running? Fission.ui.output '' Fission.ui.output_and_exit "VM '#{vm_name}' is not running", 1 end vms = [vm] end vms end def option_parser optparse = OptionParser.new do |opts| opts.banner = "\nsuspend usage: fission suspend [vm | --all]" opts.on '--all', 'Suspend all running VMs' do @options.all = true end end optparse end end end end ======================= File: lib/veewee/provider/kvm/provider.rb ======================= <reponame>ibizaman/veewee<gh_stars>1000+ require'veewee/provider/core/provider' module Veewee module Provider module Kvm class Provider < Veewee::Provider::Core::Provider def check_requirements require 'fog' env.logger.info "Falling back to qemu:///system for libvirt URI if no value is specified in the.fog config file" Fog.credentials[:libvirt_uri] ||= "qemu:///system" env.logger.info "Setting libvirt IP Command if not already defined in.fog config file" Fog.credentials[:libvirt_ip_command] ||= "arp -an |grep -i $mac|cut -d '(' -f 2 | cut -d ')' -f 1" env.logger.info "Opening a libvirt connection using fog.io" begin unless gems_available?(["ruby-libvirt"]) raise Veewee::Error, "Please install ruby-libvirt gem first" end end begin env.logger.info "Opening a libvirt connection using fog.io" conn = Fog::Compute[:libvirt] rescue Exception => ex raise Veewee::Error, "There was a problem opening a connection to libvirt: #{ex}" end env.logger.info "Libvirt connection established" env.logger.debug "Found capabilities:" env.logger.debug "#{conn.client.capabilities}" env.logger.info "Checking libvirt version" # http://www.libvirt.org/html/libvirt-libvirt.html#virGetVersion # format major * 1,000,000 + minor * 1,000 + release conn.client.libversion > 8003 or raise Veewee::Error, "You need at least libvirt version 0.8.3 or higher " env.logger.info "Checking available networks" conn.networks.any? or raise Veewee::Error, "You need at least one (active) network defined in #{Fog.credentials[:libvirt_uri]}." env.logger.info "Checking available storagepools" conn.pools.any? or raise Veewee::Error, "You need at least one (active) storage pool defined in #{Fog.credentials[:libvirt_uri]}." env.logger.info "Checking availability of the arp utility" shell_exec("arp -an").status.zero? or raise Veewee::Error, "Could not execute the arp command. This is required to find the IP address of the VM" end def build(definition_name, box_name, options) super(definition_name, box_name, options) end end #End Class end # End Module end # End Module end # End Module ======================= File: lib/veewee/provider/core/box/halt.rb ======================= require'veewee/provider/core/helper/ssh' module Veewee module Provider module Core module BoxCommand def halt(options={}) if self.running? if options["force"]==true self.poweroff else if definition.winrm_user && definition.winrm_password # prefer winrm self.exec("#{definition.shutdown_cmd}") else self.exec("echo '#{definition.shutdown_cmd}' > /tmp/shutdown.sh") self.exec("chmod +x /tmp/shutdown.sh") self.exec(sudo("/tmp/shutdown.sh")) end end else raise Veewee::Error,"Box is not running" end end end # Module end # Module end # Module end # Module ======================= File: lib/veewee/provider/vmfusion/box/helper/status.rb ======================= <gh_stars>1000+ module Veewee module Provider module Vmfusion module BoxCommand # Check if box is running def running? return false if raw.nil? return raw.running? end # Check if the box already exists def exists? return raw.exists? end end end end end ======================= File: templates/freebsd-10.0-RELEASE-amd64/definition.rb ======================= Veewee::Definition.declare({ :cpu_count => '1', :memory_size=> '512', :disk_size => '10140', :disk_format => 'VDI', :hostiocache => 'off', :os_type_id => 'FreeBSD_64', :iso_file => "mfsbsd-se-10.0-RELEASE-amd64.iso", :iso_src => "http://mfsbsd.vx.sk/files/iso/10/amd64/mfsbsd-se-10.0-RELEASE-amd64.iso", :iso_md5 => "a6f9d9a41e8dc1ddb13f3387c8487837", :iso_download_timeout => "1000", :boot_wait => "90", :boot_cmd_sequence => [ 'root', '<Enter>', 'mfsroot', '<Enter>', 'mount_cd9660 /dev/cd0 /cdrom', '<Enter>', 'zfsinstall -d /dev/ada0 -u /cdrom/10.0-RELEASE-amd64 -s 1G', '<Enter>', '<Wait><Wait><Wait><Wait><Wait><Wait><Wait><Wait><Wait><Wait>', '<Wait><Wait><Wait><Wait><Wait><Wait><Wait><Wait><Wait><Wait>', '<Wait><Wait><Wait><Wait><Wait><Wait><Wait><Wait><Wait><Wait>', '<Wait><Wait><Wait><Wait><Wait><Wait><Wait><Wait><Wait><Wait>', '<Wait><Wait><Wait><Wait><Wait><Wait><Wait><Wait><Wait><Wait>', '<Wait><Wait><Wait><Wait><Wait><Wait><Wait><Wait><Wait><Wait>', 'shutdown -r now', '<Enter>', '<Wait><Wait><Wait><Wait><Wait><Wait><Wait><Wait><Wait><Wait>', '<Wait><Wait><Wait><Wait><Wait><Wait><Wait><Wait><Wait><Wait>', '<Wait><Wait><Wait><Wait><Wait><Wait><Wait><Wait><Wait><Wait>', '<Wait><Wait><Wait><Wait><Wait><Wait><Wait><Wait><Wait><Wait>', '<Wait><Wait><Wait><Wait><Wait><Wait><Wait><Wait><Wait><Wait>', '<Wait><Wait><Wait><Wait><Wait><Wait><Wait><Wait><Wait><Wait>', '<Wait><Wait><Wait><Wait><Wait><Wait><Wait><Wait><Wait><Wait>', '<Wait><Wait><Wait><Wait><Wait><Wait><Wait><Wait><Wait><Wait>', '<Wait><Wait><Wait><Wait><Wait><Wait><Wait><Wait><Wait><Wait>', 'root', '<Enter>', 'dhclient em0', '<Enter><Wait><Wait><Wait>', 'fetch -o /tmp/install.sh http://%IP%:%PORT%/install.sh && chmod +x /tmp/install.sh && /tmp/install.sh %NAME%<Enter>' ], :kickstart_port => "7122", :kickstart_timeout => "300", :kickstart_file => "install.sh", :ssh_login_timeout => "10000", :ssh_user => "vagrant", :ssh_password => "<PASSWORD>", :ssh_key => "", :ssh_host_port => "7222", :ssh_guest_port => "22", :sudo_cmd => "cat '%f' | su -", :shutdown_cmd => "shutdown -p now", :postinstall_files => [ "postinstall.csh"], :postinstall_timeout => "10000" }) ======================= File: lib/veewee/provider/vmfusion/box/export.rb ======================= <filename>lib/veewee/provider/vmfusion/box/export.rb require 'tempfile' module Veewee module Provider module Vmfusion module BoxCommand # This function 'exports' the box based on the definition def export_vmfusion(options) case options["export_type"] when "ova" debug="--X:logToConsole=true --X:logLevel=\"verbose\"" debug="" flags="--compress=9" if File.exists?("#{name}.ova") if options["force"] env.logger.debug("#{name}.ova exists, but --force was provided") env.logger.debug("removing #{name}.ova first") FileUtils.rm("#{name}.ova") env.logger.debug("#{name}.ova removed") else raise Veewee::Error, "export file #{name}.ova already exists. Use --force option to overwrite." end end # before exporting the system needs to be shut down ensure_vm_stopped(options) # otherwise the debug log will show - The specified virtual disk needs repair env.ui.info "Exporting VM to #{options["export_type"]}" shell_exec("#{File.dirname(vmrun_cmd).shellescape}#{"/VMware OVF Tool/ovftool".shellescape} #{debug} #{flags} #{vmx_file_path.shellescape} #{name}.ova") when "vagrant" debug="" flags="-tt=OVF" ensure_vm_stopped(options) optimize_disk # get a temp dir Dir.mktmpdir do |tmpdir| env.ui.info "Exporting VM to #{options["export_type"]} box" FileUtils.cp_r(Dir["#{vm_path}/*"],tmpdir) # Inject a Vagrantfile unless one is provided if options['vagrantfile'] FileUtils.cp(options['vagrantfile'], File.join(tmpdir, 'Vagrantfile')) else File.open(File.join(tmpdir, 'Vagrantfile'), 'w') {|f| f.write(template_vagrantfile()) } end #Inject a metadata.json file File.open(File.join(tmpdir,'metadata.json'), 'w') {|f| f.write(template_metadatafile()) } # Tar it up into the destination pwd = Dir.pwd shell_exec("cd #{tmpdir} && tar -czf #{File.join(pwd, name)}.box *") end end end protected def ensure_vm_stopped(options={}) # Need to check binary first if self.running?.data # Wait for the shutdown to complete begin Timeout::timeout(60) do self.halt(options) loop do sleep 4 break unless self.running?.data end end rescue TimeoutError => ex raise Veewee::Error,ex end end end def template_metadatafile %Q({"provider": "vmware_fusion"}\n) end def template_vagrantfile <<EOF Vagrant::Config.run do |config| # This Vagrantfile is auto-generated by `vagrant package` to contain # the MAC address of the box. Custom configuration should be placed in # the actual `Vagrantfile` in this box. config.vm.base_mac = "080027AC6969" end # Load include vagrant file if it exists after the auto-generated # so it can override any of the settings include_vagrantfile = File.expand_path("../include/_Vagrantfile", __FILE__) load include_vagrantfile if File.exist?(include_vagrantfile) EOF end def optimize_disk current_dir=Dir.pwd FileUtils.chdir(vm_path) env.ui.info "Optimizing Disk" shell_exec("#{File.dirname(vmrun_cmd).shellescape}#{"/vmware-vdiskmanager".shellescape} -d #{name}.vmdk") shell_exec("#{File.dirname(vmrun_cmd).shellescape}#{"/vmware-vdiskmanager".shellescape} -k #{name}.vmdk") [name, "#{name}.plist", "quicklook-cache.png" ].each do |file| File.delete(file) if File.exist?(file) end Dir.glob("*.log").map { |f| File.delete(f) } FileUtils.chdir(current_dir) end end end end end ======================= File: lib/fission.old/cli.rb ======================= module Fission class CLI def self.execute(args=ARGV) optparse = OptionParser.new do |opts| opts.banner = "\nUsage: fission [options] COMMAND [arguments]" opts.on_head('-v', '--version', 'Output the version of fission') do Fission.ui.output Fission::VERSION exit(0) end opts.on_head('-h', '--help', 'Displays this message') do show_all_help(optparse) exit(0) end opts.define_tail do commands_banner end end begin optparse.order! args rescue OptionParser::InvalidOption => e Fission.ui.output e show_all_help(optparse) exit(1) end if commands.include?(args.first) @cmd = Fission::Command.const_get(args.first.capitalize).new args.drop 1 elsif is_snapshot_command?(args) klass = args.take(2).map {|c| c.capitalize}.join('') @cmd = Fission::Command.const_get(klass).new args.drop 2 else show_all_help(optparse) exit(1) end begin @cmd.execute rescue Error => e puts "Error: #{e}" end end def self.commands cmds = Dir.entries(File.join(File.dirname(__FILE__), 'command')).select do |file| !File.directory? file end cmds.map { |cmd| File.basename(cmd, '.rb').gsub '_','' } end private def self.is_snapshot_command?(args) args.first =='snapshot' && args.count > 1 && commands.include?(args.take(2).join(' ')) end def self.commands_banner text = "\nCommands:\n" Fission::Command.descendants.each do |command_klass| text << (command_klass.send :help) end text end def self.show_all_help(options) Fission.ui.output options Fission.ui.output commands_banner end end end ======================= File: templates/windows-2008R1-serverweb-amd64/definition.rb ======================= <reponame>ibizaman/veewee<gh_stars>1000+ # Download Windows Web Server 2008 : (60 day eval, expandable to 240 days) # http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=20407 # 64bit # http://download.microsoft.com/download/B/4/D/B4DC75A1-D7D2-4F31-87F9-E02C950E8D31/6001.18000.080118-1840_amd64fre_Server_en-us-KRMSXFRE_EN_DVD.iso # md5sum 0477c88678efb8ebc5cd7a9e9efd8b82 6001.18000.080118-1840_amd64fre_Server_en-us-KRMSXFRE_EN_DVD.iso # 32bit # http://download.microsoft.com/download/B/4/D/B4DC75A1-D7D2-4F31-87F9-E02C950E8D31/6001.18000.080118-1840_x86fre_Server_en-us-KRMSFRE_EN_DVD.iso # To get to 2008R1-SP2 you'l need # 64bit # Windows Server 2008 Service Pack 2 and Windows Vista Service Pack 2 - Five Language Standalone for x64-based systems (KB948465) # http://www.microsoft.com/download/en/details.aspx?id=17669 # http://download.microsoft.com/download/4/7/3/473B909B-7B52-49FE-A443-2E2985D3DFC3/Windows6.0-KB948465-X64.exe # 32bit # Windows Server 2008 Service Pack 2 and Windows Vista Service Pack 2 - Five Language Standalone (KB948465) # http://www.microsoft.com/download/en/details.aspx?id=16468 # http://download.microsoft.com/download/E/7/7/E77CBA41-0B6B-4398-BBBF-EE121EEC0535/Windows6.0-KB948465-X86.exe # Win2008 requires at least 10gig hard drive to install... Veewee::Session.declare({ :os_type_id => 'Windows2008_64', # :iso_file => "en_windows_web_server_2008_x64_dvd_x14-26683.iso", :iso_file => "6001.18000.080118-1840_amd64fre_ServerWeb_en-us-KRMWXFRE_EN_DVD.iso", :iso_md5 => "a95ad42cee261333d28891f4868e6d3b", :iso_src => "http://download.microsoft.com/download/1/e/3/1e332e6c-9f8a-47ba-b380-8fdef29e9d57/6001.18000.080118-1840_amd64fre_ServerWeb_en-us-KRMWXFRE_EN_DVD.iso", :iso_download_timeout => "1000", :cpu_count => '1', :memory_size=> '384', :disk_size => '20280', :disk_format => 'VDI', :hostiocache => 'off', #:kickstart_port => "7122", #:kickstart_timeout => 300, #:kickstart_file => ["VBoxWindowsAdditions-amd64.exe"], :floppy_files => [ "Autounattend.xml", # automate install and setup winrm "install-winrm.bat", "install-cygwin-sshd.bat", "install-vbox-guest.bat", "oracle-cert.cer" ], :boot_wait => "50", # after 40 seconds, hit these keys to not enter a product key and fully automate the install # if your machine is slower it may take more time :boot_cmd_sequence => [ '<Tab><Tab><Spacebar>', '<Tab><Tab><Tab><Spacebar>', '<Tab><Spacebar>' ], :ssh_login_timeout => "10000", # Actively attempt to ssh in for 10000 seconds :ssh_user => "vagrant", :ssh_password => "<PASSWORD>", :ssh_key => "", :ssh_host_port => "7233", :ssh_guest_port => "22", # And run postinstall.sh for up to 10000 seconds :postinstall_timeout => "10000", :postinstall_files => ["postinstall.sh"], # No sudo on windows :sudo_cmd => "sh '%f'", # Shutdown is different as well :shutdown_cmd => "shutdown /s /t 0 /d P:4:1 /c \"Vagrant Shutdown\"", }) # To edit the Autounattend.xml and validate it: # Download Automated Installation Kit (AIK) for Windows Vista SP1 and Windows Server 2008: # http://www.microsoft.com/download/en/details.aspx?id=9085 # Resulting in 6001.18000.080118-1840-kb3aikl_en.iso # md5sum b83fad8fd28e637b82cb4a6bef7d6920 6001.18000.080118-1840-kb3aikl_en.iso # AIK also includes dism, which will allow you to choose a specific version: # If you want to install a different version, edit Autoattended.xml and replace the /IMAGE/NAME value with # one of the names listed in the Longhorn install.wim on the install.iso # <InstallFrom> # <MetaData wcm:action="add"> # <Key>/IMAGE/NAME</Key> # <Value>Windows Longhorn SERVERSTANDARD</Value> ### This comes from the Name: field below # </MetaData> # </InstallFrom> # PS C:\Users\Administrator> Dism /Get-WIMInfo /WimFile:d:\sources\install.wim # Deployment Image Servicing and Management tool # Version: 6.1.7600.16385 # Details for image : d:\sources\install.wim # Index : 1 # Name : Windows Longhorn SERVERSTANDARD # Description : Windows Longhorn SERVERSTANDARD # Size : 8,784,297,519 bytes # Index : 2 # Name : Windows Longhorn SERVERENTERPRISE # Description : Windows Longhorn SERVERENTERPRISE # Size : 8,792,036,862 bytes # Index : 3 # Name : Windows Longhorn SERVERDATACENTER # Description : Windows Longhorn SERVERDATACENTER # Size : 8,792,568,645 bytes # Index : 4 # Name : Windows Longhorn SERVERSTANDARDCORE # Description : Windows Longhorn SERVERSTANDARDCORE # Size : 2,512,939,954 bytes # Index : 5 # Name : Windows Longhorn SERVERENTERPRISECORE # Description : Windows Longhorn SERVERENTERPRISECORE # Size : 2,522,686,340 bytes # Index : 6 # Name : Windows Longhorn SERVERDATACENTERCORE # Description : Windows Longhorn SERVERDATACENTERCORE # Size : 2,522,615,418 bytes ======================= File: lib/veewee/config.rb ======================= require'veewee/config/veewee' require'veewee/config/collection' require 'fileutils' module Veewee class Config attr_accessor :veewee attr_reader :env def initialize(options) @env = options[:env] # Initialize with defaults @veewee = ::Veewee::Config::Veewee.new(self) end def define() config = OpenStruct.new # Expose the veewee config config.veewee = @veewee # Process config file yield config end # We put a long name to not clash with any function in the Veewee file itself def load_veewee_config() veewee_configurator = self begin filename = @env.config_filepath if File.exists?(filename) env.logger.info("Loading config file: #{filename}") veeweefile = File.read(filename) veeweefile["Veewee::Config.run"] = "veewee_configurator.define" # http://www.dan-manges.com/blog/ruby-dsls-instance-eval-with-delegation instance_eval(veeweefile) else env.logger.info "No configfile found" end rescue LoadError => e env.ui.error "An error occurred" env.ui.error e.message rescue NoMethodError => e env.ui.error "Some method got an error in the configfile - Sorry" env.ui.error $! env.ui.error e.message raise Veewee::Error "Some method got an error in the configfile - Sorry" rescue Error => e env.ui.error "Error processing configfile - Sorry" env.ui.error e.message raise Veewee::Error "Error processing configfile - Sorry" end return self end end #End Class end #End Module ======================= File: lib/veewee/provider/kvm/box/helper/console_type.rb ======================= <reponame>ibizaman/veewee require'veewee/provider/core/box' require'veewee/provider/core/box/vnc' require'veewee/provider/kvm/box/validate_kvm' module Veewee module Provider module Kvm module BoxCommand # Type on the console def console_type(sequence,type_options={}) [email protected](:name => name).first.display[:port] display_port=tcp_port.to_i - 5900 ui.success "Sending keystrokes to VNC port :#{display_port} - TCP port: #{tcp_port}" vnc_type(sequence,"127.0.0.1",display_port) end end # End Module end # End Module end # End Module end # End Module ======================= File: lib/veewee/provider/virtualbox/box/helper/status.rb ======================= module Veewee module Provider module Virtualbox module BoxCommand def exists? return check?(:exists) end def running? return check?(:running) end private def check? type command = COMMANDS[type] % @vboxcmd shell_results=shell_exec("#{command}",{:mute => true}) status=shell_results.stdout.split(/\n/).grep(/\"#{Regexp.escape(name)}\"/).size!=0 env.logger.info("Vm #{type}? #{status}") return status end COMMANDS = { :running => "%s list runningvms", :exists => "%s list vms" } end end end end ======================= File: lib/veewee/provider/vmfusion/box/add_share.rb ======================= module Veewee module Provider module Vmfusion module BoxCommand # This function 'adds a share' the box based on the definition def add_share(share_name, share_path) shell_exec("#{(vmrun_cmd).shellescape} -T fusion addSharedFolder #{vmx_file_path.shellescape} '#{share_name}' #{::File.expand_path(share_path).shellescape}") end def add_share_from_defn definition.add_shares.each do |share_name, share_path| add_share(share_name, share_path) end end end end end end ======================= File: lib/fission.old/vm.rb ======================= <reponame>ibizaman/veewee require 'fission/leasesfile' require'shellwords' require 'fission/error' module Fission class VM attr_reader :name def initialize(name) @name = name end ##################################################### # Path Helpers ##################################################### # Returns the topdir of the vm def path File.join Fission.config.attributes['vm_dir'], "#{@name}.vmwarevm" end # Returns a string to the path of the config file # There is no guarantee it exists def vmx_path return File.join(path, "#{@name}.vmx") end #################################################################### # State information #################################################################### def running? raise Fission::Error,"VM #{@name} does not exist" unless self.exists? command = "#{vmrun_cmd} list" output = `#{command}` response = Fission::Response.new :code => $?.exitstatus if response.successful? vms = output.split("\n").select do |vm| vm.include?('.vmx') && File.exists?(vm) && File.extname(vm) == '.vmx' end return vms.include?(self.vmx_path) else raise Fission::Error,"Error listing the state of vm #{@name}:\n#{output}" end end def suspended? raise Fission::Error,"VM #{@name} does not exist" unless self.exists? suspend_filename=File.join(File.dirname(vmx_path), File.basename(vmx_path,".vmx")+".vmem") return File.exists?(suspend_filename) end # Checks to see if a vm exists def exists? File.exists? vmx_path end # Returns the state of a vm def state return "not created" unless self.exists? return "suspend" if self.suspended? return "running" if self.running? return "not running" end #################################################################### # VM information #################################################################### # Returns an Array of snapshot names def snapshots raise Fission::Error,"VM #{@name} does not exist" unless self.exists? command = "#{vmrun_cmd} listSnapshots #{vmx_path.shellescape} 2>&1" output = `#{command}` raise "There was an error listing the snapshots of #{@name} :\n #{output}" unless $?.exitstatus==0 snaps_unfiltered = output.split("\n").select { |s|!s.include? 'Total snapshots:' } snaps=snaps_unfiltered.map { |s| s.strip } return snaps end # Retrieve the first mac address for a vm # This will only retrieve the first auto generate mac address def mac_address raise ::Fission::Error,"VM #{@name} does not exist" unless self.exists? line=File.new(vmx_path).grep(/^ethernet0.generatedAddress =/) if line.nil? #Fission.ui.output "Hmm, the vmx file #{vmx_path} does not contain a generated mac address " return nil end address=line.first.split("=")[1].strip.split(/\"/)[1] return address end # Retrieve the ip address for a vm. # This will only look for dynamically assigned ip address via vmware dhcp def ip_address raise ::Fission::Error,"VM #{@name} does not exist" unless self.exists? unless mac_address.nil? lease=LeasesFile.new("/var/db/vmware/vmnet-dhcpd-vmnet8.leases").find_lease_by_mac(mac_address) if lease.nil? return nil else return lease.ip end else # No mac address was found for this machine so we can't calculate the ip-address return nil end end #################################################################### # VMS information #################################################################### # Returns an array of vm objects def self.all vm_dirs = Dir[File.join Fission.config.attributes['vm_dir'], '*.vmwarevm'].select do |d| File.directory? d end vm_names=vm_dirs.map { |d| File.basename d, '.vmwarevm' } vms=[] vm_names.each do |vmname| vm=Fission::VM.new vmname vms << vm end return vms end # Returns an array of vms that are running def self.all_running running_vms=self.all.select do |vm| vm.state=="running" end return running_vms end # Returns an existing vm def self.get(name) return Fission::VM.new(name) end ##################################################### # VM Class Actions ##################################################### def self.clone(source_vm, target_vm) raise Fission::Error,"VM #{source_vm} does not exist" unless Fission::VM.new(source_vm).exists? raise Fission::Error,"VM #{target_vm} already exists" if Fission::VM.new(target_vm).exists? FileUtils.cp_r Fission::VM.new(source_vm).path, Fission::VM.new(target_vm).path rename_vm_files source_vm, target_vm update_config source_vm, target_vm response = Response.new :code => 0 end def self.delete(vm_name) raise Fission::Error,"VM #{vm_name} does not exist" unless Fission::VM.new(vm_name).exists? vm=Fission::VM.new(vm_name) FileUtils.rm_rf vm.path Fission::Metadata.delete_vm_info(vm.path) Response.new :code => 0 end ##################################################### # VM Instance Actions ##################################################### def create_snapshot(name) raise Fission::Error,"VM #{@name} does not exist" unless self.exists? command = "#{vmrun_cmd} snapshot #{vmx_path.shellescape} \"#{name}\" 2>&1" output = `#{command}` response = Fission::Response.new :code => $?.exitstatus response.output = output unless response.successful? response end def start(args={}) raise Fission::Error,"VM #{@name} does not exist" unless self.exists? raise Fission::Error,"VM #{@name} is already started" if self.running? command = "#{vmrun_cmd} start #{vmx_path.shellescape}" if!args[:headless].blank? && args[:headless] command << " nogui 2>&1" else command << " gui 2>&1" end output = `#{command}` response = Fission::Response.new :code => $?.exitstatus response.output = output unless response.successful? response end def stop raise Fission::Error,"VM #{@name} does not exist" unless self.exists? raise Fission::Error,"VM #{@name} is not running" unless self.running? command = "#{vmrun_cmd} stop #{vmx_path.shellescape} 2>&1" output = `#{command}` response = Fission::Response.new :code => $?.exitstatus response.output = output unless response.successful? response end def halt raise Fission::Error,"VM #{@name} does not exist" unless self.exists? raise Fission::Error,"VM #{@name} is not running" unless self.running? command = "#{vmrun_cmd} stop #{vmx_path.shellescape} hard 2>&1" output = `#{command}` response = Fission::Response.new :code => $?.exitstatus response.output = output unless response.successful? response end def resume raise Fission::Error,"VM #{@name} does not exist" unless self.exists? raise Fission::Error,"VM #{@name} is already running" if self.running? if self.suspended? self.start end end def suspend raise Fission::Error,"VM #{@name} does not exist" unless self.exists? raise Fission::Error,"VM #{@name} is not running" unless self.running? command = "#{vmrun_cmd} suspend #{vmx_path.shellescape} hard 2>&1" output = `#{command}` response = Fission::Response.new :code => $?.exitstatus response.output = output unless response.successful? response end # Action to revert to a snapshot # Returns a response object def revert_to_snapshot(name) raise Fission::Error,"VM #{@name} does not exist" unless self.exists? command = "#{vmrun_cmd} revertToSnapshot #{vmx_path.shellescape} \"#{name}\" 2>&1" output = `#{command}` response = Fission::Response.new :code => $?.exitstatus response.output = output unless response.successful? response end ##################################################### # Helpers ##################################################### private def self.rename_vm_files(from, to) to_vm=Fission::VM.new(to) files_to_rename(from, to).each do |filename| text_to_replace = File.basename(filename, File.extname(filename)) if File.extname(filename) == '.vmdk' if filename.match /\-s\d+\.vmdk/ text_to_replace = filename.partition(/\-s\d+.vmdk/).first end end unless File.exists?(File.join(to_vm.path, filename.gsub(text_to_replace, to))) FileUtils.mv File.join(to_vm.path, filename), File.join(to_vm.path, filename.gsub(text_to_replace, to)) end end end def self.files_to_rename(from, to) files_which_match_source_vm = [] other_files = [] from_vm=Fission::VM.new(from) Dir.entries(from_vm.path).each do |f| unless f == '.' || f == '..' f.include?(from)? files_which_match_source_vm << f : other_files << f end end files_which_match_source_vm + other_files end def self.vm_file_extensions ['.nvram', '.vmdk', '.vmem', '.vmsd', '.vmss', '.vmx', '.vmxf'] end # This is done after a clone has been done # All files are already at the to location # The content of the text files will be substituted with strings from => to def self.update_config(from, to) to_vm=Fission::VM.new(to) ['.vmx', '.vmxf', '.vmdk'].each do |ext| file = File.join to_vm.path, "#{to}#{ext}" unless File.binary?(file) text = (File.read file).gsub from, to # Force binary mode to prevent windows from putting CR-LF end line style # http://www.ruby-forum.com/topic/60697#58748 File.open(file, 'wb'){ |f| f.print text } end end # Rewrite vmx file to avoid messages new_vmx_file=File.open(File.join(to_vm.vmx_path),'r') content=new_vmx_file.read # Filter out other values content=content.gsub(/^tools.remindInstall.*\n/, "") content=content.gsub(/^uuid.action.*\n/,"").strip # Remove generate mac addresses content=content.gsub(/^ethernet.+generatedAddress.*\n/,"").strip # Add the correct values content=content+"\ntools.remindInstall = \"FALSE\"\n" content=content+"uuid.action = \"create\"\n" # Now rewrite the vmx file # Force binary mode to prevent windows from putting CR-LF end line style # http://www.ruby-forum.com/topic/60697#58748 File.open(new_vmx_file,'wb'){ |f| f.print content} end def vmrun_cmd if File.exists?("/Library/Application Support/VMware Fusion/vmrun") return("/Library/Application Support/VMware Fusion/vmrun").shellescape end if File.exists?("/Applications/VMware Fusion.app/Contents/Library/vmrun") return("/Applications/VMware Fusion.app/Contents/Library/vmrun").shellescape end end end end ======================= File: lib/veewee/templates.rb ======================= require "gem-content" module Veewee class Templates attr_accessor :env def initialize(env) @env = env return self end def [](name) result = nil valid_paths(env.template_path).each do |template_dir| template = Veewee::Template.new(name, File.join(template_dir, name), @env) if template.exists? result = template return result end end return nil end # Fetch all Templates def each(&block) templates = Hash.new valid_paths(env.template_path).each do |template_dir| env.logger.debug("[Template] Searching #{template_dir} for templates") subdirs = Dir.glob("#{template_dir}/*") subdirs.each do |sub| if File.directory?("#{sub}") name = sub.sub(/#{template_dir}\//, '') template = Veewee::Template.new(name, sub, @env) if template.exists? env.logger.debug("[Template] template '#{name}' found") templates[name] = template end end end end if templates.length == 0 env.logger.debug("[Template] no templates found") end Hash[templates.sort].each(&block) end private # Traverses path to see which exist or not # and checks if available def valid_paths(paths) paths = GemContent.get_gem_paths("veewee-templates") valid_paths = paths.collect { |path| if File.exists?(path) && File.directory?(path) env.logger.info "Path #{path} exists" File.expand_path(path) else env.logger.info "Path #{path} does not exist, skipping" nil end } return valid_paths.compact end end end ======================= File: lib/veewee/provider/parallels/box/up.rb ======================= module Veewee module Provider module Parallels module BoxCommand def up(options={}) gui_enabled=options[:nogui]==true? false : true command="prlctl start '#{self.name}'" shell_exec("#{command}") end end end end end ======================= File: templates/Debian-7/definition.rb ======================= Veewee::Definition.declare_yaml('definition.yml', "7.10.yml") ======================= File: templates/CentOS-5.10/definition.rb ======================= <reponame>ibizaman/veewee # # change centos_64_dvd to one of configurations in *.yml in this directory # use the yml files to configure # Veewee::Definition.declare_yaml('definition.yml', "centos_64_dvd.yml") ======================= File: lib/veewee/provider/virtualbox/box/winrm.rb ======================= <filename>lib/veewee/provider/virtualbox/box/winrm.rb module Veewee module Provider module Virtualbox module BoxCommand def winrm(command,options={}) super(command,options) end end end end end ======================= File: test/environment_test.rb ======================= <reponame>ibizaman/veewee<filename>test/environment_test.rb require 'test/unit' require'veewee' require 'tempfile' class TestVeeweeEnvironment < Test::Unit::TestCase def test_environment_default_to_currentdir # unset the VEEWEE_DIR environment which overwrites cwd ENV['VEEWEE_DIR'] = nil tempdir = Dir.mktmpdir Dir.chdir(tempdir) tempdir=Dir.pwd begin ve=Veewee::Environment.new() assert_equal(ve.cwd,tempdir) ensure FileUtils.remove_entry_secure tempdir end end # If a cwd is passed, it take precendence over currentdir def test_environment_override_environmentdir # Create a temp directory to simulate a currentdir tempdir = Dir.mktmpdir Dir.chdir(tempdir) tempdir=Dir.pwd # Now change to another dir Dir.chdir("/tmp") begin ve=Veewee::Environment.new({:cwd => tempdir}) assert_equal(ve.cwd,tempdir) ensure FileUtils.remove_entry_secure tempdir end end # parent of isodir or definitiondir not writeable should raise an error def test_environment_parentdir_should_be_writeable end # definition_dir, iso_dir by default are relative to the environmentdir def test_environment_iso_dir_relative_to_environmentdir # Create a temp directory to simulate a currentdir tempdir = Dir.mktmpdir Dir.chdir(tempdir) tempdir=Dir.pwd begin ve=Veewee::Environment.new({:cwd => tempdir}) assert_equal(ve.definition_dir,File.join(tempdir,"definitions")) assert_equal(ve.iso_dir,File.join(tempdir,"iso")) ensure FileUtils.remove_entry_secure tempdir end end # definition_dir, iso_dir by default are relative to the environmentdir def test_environment_definition_dir_relative_to_environmentdir # Goto top dir, to make pwd another dir Dir.chdir("/") ve=Veewee::Environment.new({:definition_dir => "/tmp"}) assert_equal(ve.definition_dir,"/tmp") end end ======================= File: templates/Sysrescuecd-2.0.0-experimental/definition.rb ======================= Veewee::Definition.declare({ :cpu_count => '1', :memory_size=> '256', :disk_size => '10140', :disk_format => 'VDI', :hostiocache => 'off', :os_type_id => 'Linux', :iso_file => "systemrescuecd-x86-2.0.0.iso", :iso_src => "http://downloads.sourceforge.net/project/systemrescuecd/sysresccd-x86/2.0.0/systemrescuecd-x86-2.0.0.iso", :iso_md5 => "51012e0bb943cff6367e5cea3a61cdbe", :iso_download_timeout => "1000", :boot_wait => "10", :boot_cmd_sequence => [ '<Tab> ', 'setkmap=us dodhcp=eth0 dhcphostname=%NAME% ar_source=http://%IP%:%PORT%/ autoruns=0 rootpass=<PASSWORD>', '<Enter>' ], :kickstart_port => "7122", :kickstart_timeout => "300", :kickstart_file => "autorun0", :ssh_login_timeout => "10000", :ssh_user => "root", :ssh_password => "<PASSWORD>", :ssh_key => "", :ssh_host_port => "7222", :ssh_guest_port => "22", :sudo_cmd => "sh '%f'", :shutdown_cmd => "shutdown -H", :postinstall_files => [ ], :postinstall_timeout => "10000" }) ======================= File: test/definition_test.rb ======================= <filename>test/definition_test.rb<gh_stars>1000+ require 'test/unit' require'veewee' class TestVeeweeDefinition < Test::Unit::TestCase def test_environment_load_definition # Set the definition dir to our template dir ve=Veewee::Environment.new({:definition_dir => [ File.expand_path(File.join(File.dirname(__FILE__),"..", "templates")) ] }) vd=ve.definitions["ubuntu-10.10-server-amd64"] assert_equal(vd.os_type_id,"Ubuntu_64") end end ======================= File: lib/veewee/provider/kvm/box/build.rb ======================= <gh_stars>1000+ module Veewee module Provider module Kvm module BoxCommand def build(options) super(options) end end end # End Module end # End Module end # End Module ======================= File: lib/veewee/provider/parallels/provider.rb ======================= require'veewee/provider/core/provider' module Veewee module Provider module Parallels class Provider < Veewee::Provider::Core::Provider #include ::Veewee::Provider::Vmfusion::ProviderCommand def check_requirements unless self.shell_exec("prlctl --version").status == 0 raise Veewee::Error,"Could not execute prlctl command. Please install Parallels or make sure prlctl is in the Path" end unless self.shell_exec("arp -an").status == 0 raise Veewee::Error,"Could not execute arp command. That should never happen :)" end unless self.shell_exec("python --version").status == 0 raise Veewee::Error,"Could not execute python command. Please install or make it available in your path" end check_file=File.join(File.dirname(__FILE__),'..','..','..','python','parallels_sdk_check.py') unless self.shell_exec("python #{check_file}").status == 0 raise Veewee::Error,"Could not connect to the parallels local service. To make it work, install the Parallels SDK that matches your version of parallels" end end end #End Class end # End Module end # End Module end # End Module ======================= File: lib/veewee/command/vbox.rb ======================= <reponame>ibizaman/veewee module Veewee module Command class Vbox < Veewee::Command::GroupBase register :command => "vbox", :description => "Subcommand for VirtualBox", :provider => "virtualbox" desc "build [BOX_NAME]", "Build box" # TODO move common build options into array method_option :force,:type => :boolean, :default => false, :aliases => "-f", :desc => "force the build" method_option :nogui,:type => :boolean, :default => false, :aliases => "-n", :desc => "no gui" method_option :auto,:type => :boolean, :default => false, :aliases => "-a", :desc => "auto answers" method_option :checksum, :type => :boolean, :default => false, :desc => "verify checksum" method_option :redirectconsole,:type => :boolean, :default => false, :aliases => "-r", :desc => "redirects console output" method_option :postinstall_include, :type => :array, :default => [], :aliases => "-i", :desc => "ruby regexp of postinstall filenames to additionally include" method_option :postinstall_exclude, :type => :array, :default => [], :aliases => "-e", :desc => "ruby regexp of postinstall filenames to exclude" method_option :skip_to_postinstall, :aliases => ['--skip-to-postinstall'], :type => :boolean, :default => false, :desc => "Skip to postinstall." def build(box_name) env.get_box(box_name).build(options) end desc "export [BOX_NAME]", "Exports the basebox to the vagrant format" method_option :debug,:type => :boolean, :default => false, :aliases => "-d", :desc => "enable debugging" method_option :force,:type => :boolean, :default => false, :aliases => "-f", :desc => "overwrite existing file" method_option :vagrantfile,:type => :string, :default => "", :desc => "specify Vagrantfile" def export(box_name) env.get_box(box_name).export_vagrant(options) end desc "validate [BOX_NAME]", "Validates a box against vagrant compliancy rules" method_option :tags, :type => :array, :default => %w{vagrant virtualbox puppet chef}, :aliases => "-t", :desc => "tags to validate" def validate(box_name) begin venv=Veewee::Environment.new(options) venv.ui = ::Veewee::UI::Shell.new(venv, shell) venv.providers[@provider].get_box(box_name).validate_vagrant(options) rescue Veewee::Error => ex venv.ui.error(ex, :prefix => false) exit -1 end end desc "screenshot [BOX_NAME] [PNGFILENAME]", "Takes a screenshot of the box" def screenshot(box_name,pngfilename) begin venv=Veewee::Environment.new(options) venv.ui = ::Veewee::UI::Shell.new(venv, shell) venv.providers[@provider].get_box(box_name).screenshot(pngfilename,options) rescue Veewee::Error => ex venv.ui.error(ex, :prefix => false) exit -1 end end end end end ======================= File: lib/veewee/provider/virtualbox/box/helper/ssh_options.rb ======================= <filename>lib/veewee/provider/virtualbox/box/helper/ssh_options.rb module Veewee module Provider module Virtualbox module BoxCommand def ssh_options build_ssh_options.tap do |options| port = definition.ssh_host_port if self.exists? forward=self.forwarding("guestssh") unless forward.nil? port=forward[:host_port] end end options[:port] = port end end end end end end ======================= File: templates/nixos64/definition.rb ======================= iso = { :file => 'nixos-minimal-13.10.35497.60b0467-x86_64-linux.iso', :md5 => 'db3b34cd4cf2030b1a425cd6af6a9a09', } session = { :boot_cmd_sequence => [ '<Enter>', '<Wait>'*15, 'root', '<Enter>', 'fdisk /dev/sda', '<Enter>', 'n', '<Enter>'*5, 'a', '<Enter>', '1', '<Enter>', 'w', '<Enter>', 'mkfs.ext4 -j -L nixos /dev/sda1', '<Enter>', 'mount LABEL=nixos /mnt', '<Enter>', 'curl -O http://10.0.2.2:7122/configuration.nix &&', '<Enter>', 'mkdir -p /mnt/etc/nixos &&', '<Enter>', 'mv configuration.nix /mnt/etc/nixos &&', '<Enter>', 'nixos-install &&', '<Enter>', 'reboot', '<Enter>' ], :boot_wait => '5', :cpu_count => '1', :disk_format => 'VDI', :disk_size => '20400', :hostiocache => 'off', :iso_download_timeout => '1000', :iso_file => iso[:file], :iso_md5 => iso[:md5], :iso_src => "http://releases.nixos.org/13.10/nixos-13.10.35497.60b0467/#{iso[:file]}", :kickstart_file => 'configuration.nix', :kickstart_port => '7122', :kickstart_timeout => '10000', :memory_size => '512', :os_type_id => 'Linux26_64', :postinstall_files => [ 'postinstall.sh' ], :postinstall_timeout => '10000', :shutdown_cmd =>'shutdown -h now', :ssh_guest_port => '22', :ssh_host_port => '7222', :ssh_key => '', :ssh_login_timeout => '10000', :ssh_password => '<PASSWORD>', :ssh_user => 'vagrant', :sudo_cmd => "sudo '%f'" } Veewee::Definition.declare session ======================= File: test/veewee/provider/core/helper/web_test.rb ======================= <filename>test/veewee/provider/core/helper/web_test.rb `VBoxManage -v` rescue nil if $?.success? require 'test/unit' require'veewee' class TestVeeweeDownload < Test::Unit::TestCase def setup @definition_dir = File.expand_path("../../../../../definitions", __FILE__) @definition_name = "erb_definition" ve = Veewee::Environment.new({ :definition_dir => @definition_dir }) @box = ve.providers["virtualbox"].get_box(@definition_name) end def test_box_1_build assert_equal( "\ #!/bin/bash echo \"Testing one Linux26\" echo DVD ", @box.send(:read_content, File.join(@definition_dir, @definition_name, "autorun0.erb")) ) end end end ======================= File: lib/fission/config.rb ======================= <reponame>ibizaman/veewee module Fission class Config # Public: Gets/Sets the Hash of attributes. attr_accessor :attributes # Public: Path to the Fission conf file (default: ~/.fissionrc). CONF_FILE = File.expand_path '~/.fissionrc' # Public: Initializes a Config object. This also sets the default config # attributes for 'vmrun_bin', 'vmrun_cmd', 'vm_dir', 'plist_file', and # 'gui_bin'. # # Examples # # Fission::Config.new # # Returns a new Config instance. def initialize @attributes = {} @attributes['vm_dir'] = File.expand_path('~/Documents/Virtual Machines.localized/') @attributes['lease_file'] = '/var/db/vmware/vmnet-dhcpd-vmnet8.leases' fusion_version = :unknown @attributes['vmrun_bin'] = [ '/Library/Application Support/VMware Fusion/vmrun', '/Applications/VMware Fusion.app/Contents/Library/vmrun', '/usr/local/bin/vmrun' ].find { |path| File.exists?(path) } if fusion_version == :unknown end @attributes['plist_file'] = File.expand_path('~/Library/Preferences/com.vmware.fusion.plist') @attributes['gui_bin'] = '/Applications/VMware Fusion.app/Contents/MacOS/vmware' load_from_file @attributes['vmrun_cmd'] = "#{@attributes['vmrun_bin'].gsub(' ', '\ ')} -T fusion" @attributes['gui_bin'] = File.expand_path(@attributes['gui_bin']) end # Public: Helper method to access config atributes. This is a shortcut for # querying the config attributes. # # item - The config item to query. # # Examples # # Fission.config['vmrun_bin'] # # => '/foo/bar/vmrun' # # Returns the value of the specified config item. def [](item) @attributes[item] end private # Internal: Loads config values from the Fission conf file into attributes. # # Examples # # load_from_file # # Returns nothing. def load_from_file if File.file?(CONF_FILE) @attributes.merge!(YAML.load_file(CONF_FILE)) end end end end ======================= File: lib/veewee/provider/parallels/box/destroy.rb ======================= <filename>lib/veewee/provider/parallels/box/destroy.rb module Veewee module Provider module Parallels module BoxCommand def destroy(options={}) unless self.exists? raise Veewee::Error, "Error:: You tried to destroy a non-existing box '#{name}'" end if self.running? self.poweroff sleep 2 end command="prlctl delete '#{self.name}'" shell_exec("#{command}") end end end end end ======================= File: test/veewee/provider/virtualbox/box/helper/guest_additions_test.rb ======================= <filename>test/veewee/provider/virtualbox/box/helper/guest_additions_test.rb require 'test/unit' require'veewee/provider/virtualbox/box/helper/guest_additions' require'veewee/provider/virtualbox/box/helper/version' require 'logger' class TestVboxGuestAdditionsHelper < Test::Unit::TestCase include Veewee::Provider::Virtualbox::BoxCommand def setup @fd = IO.sysopen("/dev/null", "w") end def ui @ui ||= Logger.new(IO.new(@fd)) end def affected_versions { "4.2.1" => "4.2.0", "4.1.23" => "4.1.22" } end def verify_version(vbox_version, guest_version, msg="", scope) set_vbox_version(vbox_version) scope.class.instance_eval do define_method :download_iso do |url, isofile| expected_url_prefix = "http://download.virtualbox.org/virtualbox/#{guest_version}/" assert(url.include?(expected_url_prefix), msg) assert_equal("VBoxGuestAdditions_#{guest_version}.iso", isofile, msg) end end download_vbox_guest_additions_iso({}) end def verify_affected_versions(msg="", scope) affected_versions.each do |vbox_version, guest_version| verify_version(vbox_version, guest_version, msg, scope) end end def test_affected_osx_version_returns_downpatched_ga_version set_ruby_platform("darwin") msg = "affected osx version did not return downpatched ga version" verify_affected_versions(msg, self) end def test_unaffected_osx_version_returns_same_version set_ruby_platform("darwin") msg = "unaffected osx version did not return same version" verify_version("4.1.22","4.1.22", msg, self) end def test_affected_linux_version_returns_same_version set_ruby_platform("linux") msg = "affected linux version did not return same version" affected_versions.keys.each do |version| verify_version(version, version, msg, self) end end def test_unaffected_linux_version_returns_same_version set_ruby_platform("linux") msg = "unaffected linux version did not return same version" verify_version("4.0.19","4.0.19", msg, self) end def test_affected_mswin_version_returns_same_version set_ruby_platform("mswin") msg = "affected mswin version did not return same version" affected_versions.keys.each do |version| verify_version(version, version, msg, self) end end def test_unaffected_mswin_version_returns_same_version set_ruby_platform("mswin") msg = "unaffected mswin version did not return same version" verify_version("4.0.19","4.0.19", msg, self) end private def set_ruby_platform(platform) Object.const_set("RUBY_PLATFORM", platform) end def set_vbox_version(ver) Veewee::Provider::Virtualbox::BoxCommand.send(:define_method, :vbox_version) do ver end end end ======================= File: test/veewee/provider/core/helper/scancode_test.rb ======================= require 'test/unit' require'veewee/provider/core/helper/scancode' class TestVeeweeScancode < Test::Unit::TestCase def setup @helper = Veewee::Provider::Core::Helper::Scancode end def test_simple_strings assert_equal( "1e 9e ", @helper.string_to_keycode("a") ) end def test_specials assert_equal( "01 81 ", @helper.string_to_keycode("<Esc>") ) end def test_specials_lowercase assert_equal( "01 81 ", @helper.string_to_keycode("<esc>") ) end def test_spaces assert_equal( "39 b9 ", @helper.string_to_keycode(" ") ) end def test_regexps assert_equal( "wait11 ", @helper.string_to_keycode("<Wait11>") ) end def test_regexps assert_equal( "wait ", @helper.string_to_keycode("<Wait>") ) end def test_combinations assert_equal( "wait10 01 81 1e 9e 39 b9 30 b0 ", @helper.string_to_keycode("<Wait10><Esc>a b") ) end end ======================= File: lib/veewee/command.rb ======================= <filename>lib/veewee/command.rb module Veewee module Command autoload :Base,'veewee/command/base' autoload :GroupBase,'veewee/command/group_base' autoload :Helpers,'veewee/command/helpers' autoload :NamedBase,'veewee/command/named_base' end end # The built-in commands must always be loaded require'veewee/command/version' require'veewee/command/kvm' require'veewee/command/vbox' require'veewee/command/fusion' require'veewee/command/parallels' ======================= File: lib/fission.old/response.rb ======================= module Fission class Response attr_accessor :code, :output, :data def initialize(args={}) @code = args.fetch :code, 1 @output = args.fetch :output, '' @data = args.fetch :data, nil end def successful? @code == 0 end end end ======================= File: templates/openindiana-148-ai-x86/definition.rb ======================= Veewee::Definition.declare({ :cpu_count => '1', :memory_size=> '768', #Disk size needs to be 12Gig + :disk_size => '15140', :disk_format => 'VDI', :hostiocache => 'on', :hwvirtex => 'on', :os_type_id => 'OpenSolaris', :iso_file => "oi-dev-148-ai-x86.iso", :iso_src => "http://dlc.openindiana.org/isos/148/oi-dev-148-ai-x86.iso", :iso_md5 => "a8e17584f58ff1d1c90464d8051a8f38", :iso_download_timeout => 1000, :boot_wait => "15", :boot_cmd_sequence => [ 'e', 'e', '<Backspace>'*22, 'false', '<Enter>', 'b', '<Wait>'*190, # login as root 'root<Enter><Wait>', 'openindiana<Enter><Wait>', # Background check when install is complete, add vagrant to the sudo 'while (true); do sleep 5; test -f /a/etc/sudoers && grep -v "vagrant" "/a/etc/sudoers" 2> /dev/null', '&& echo "vagrant ALL=(ALL) NOPASSWD: ALL" >> /a/etc/sudoers && break ; done &<Enter>', # Background check to see if install has finished and reboot '<Enter>while (true); do grep "You may wish to reboot" "/tmp/install_log" 2> /dev/null', '&& reboot; sleep 10; done &<Enter>', # Wait for 5 seconds, so the webserver will be up 'sleep 5; curl http://%IP%:%PORT%/default.xml -o default.xml;', 'cp default.xml /tmp/ai_combined_manifest.xml;', # Start the installer 'svcadm enable svc:/application/auto-installer:default;', '<Wait>'*2, # Wait for the installer to launch and display the logfile 'sleep 3; tail -f /tmp/install_log<Enter>' ], :kickstart_port => "7122", :kickstart_timeout => 300, :kickstart_file => "default.xml", :ssh_login_timeout => "10000", :ssh_user => "vagrant", :ssh_password => "<PASSWORD>", :ssh_key => "", :ssh_host_port => "7222", :ssh_guest_port => "22", :sudo_cmd => "echo '%p'|sudo -S bash./%f", :shutdown_cmd => "/usr/sbin/halt", :postinstall_files => [ "postinstall.sh"], :postinstall_timeout => 10000 }) # Notes: # http://dlc.sun.com/osol/docs/content/dev/AIinstall/aimanifest.html # http://download.oracle.com/docs/cd/E19963-01/html/820-6566/media-ai.html#gklco # default.xml # /.cdrom/auto_install/default.xml # /usr/share/auto_install/default.xml #tail -f /tmp/install.log ======================= File: lib/veewee/provider/kvm/box/poweroff.rb ======================= <reponame>ibizaman/veewee module Veewee module Provider module Kvm module BoxCommand def poweroff(options={}) [email protected](:name => name) matched_servers.first.stop unless matched_servers.nil? end end # End Module end # End Module end # End Module end # End Module ======================= File: lib/veewee/provider/core/box/floppy.rb ======================= module Veewee module Provider module Core module BoxCommand def create_floppy(floppy_filename) # Todo Check for java # Todo check output of commands # Todo allow for.erb templates # Check for floppy unless definition.floppy_files.nil? require 'tmpdir' temp_dir=Dir.mktmpdir definition.floppy_files.each do |filename| full_filename=full_filename=File.join(definition.path,filename) FileUtils.cp("#{full_filename}","#{temp_dir}") end javacode_dir=File.expand_path(File.join(__FILE__,'..','..','..','..','..','java')) floppy_file=File.join(definition.path,floppy_filename) if File.exists?(floppy_file) env.logger.info "Removing previous floppy file" FileUtils.rm(floppy_file) end command="java -jar \"#{javacode_dir}/dir2floppy.jar\" \"#{temp_dir}\" \"#{floppy_file}\"" shell_exec("#{command}") end end end end end end ======================= File: lib/veewee/provider/virtualbox/box/helper/natinterface.rb ======================= module Veewee module Provider module Virtualbox module BoxCommand def natinterface command="#{@vboxcmd} showvminfo --details --machinereadable \"#{self.name}\"" shell_results=shell_exec("#{command}") nic_id=shell_results.stdout.split(/\n/).grep(/^nic/).grep(/nat/)[0].split('=')[0][-1,1] return nic_id end end end end end ======================= File: lib/veewee/provider/virtualbox/box/helper/console_type.rb ======================= <reponame>ibizaman/veewee<filename>lib/veewee/provider/virtualbox/box/helper/console_type.rb require'veewee/provider/core/helper/scancode' require'veewee/provider/core/helper/tcp' require'veewee/provider/core/helper/shell' module Veewee module Provider module Virtualbox module BoxCommand def console_type(sequence) send_virtualbox_sequence(sequence) end def send_virtualbox_sequence(sequence) ui.info "" counter=0 sequence.each { |s| counter=counter+1 ui.info "Typing:[#{counter}]: "+s keycodes=Veewee::Provider::Core::Helper::Scancode.string_to_keycode(s) env.logger.info "Sending keycodes: #{keycodes}" # VBox seems to have issues with sending the scancodes as one big #.join()-ed string. It seems to get them out or order or ignore some. # A workaround is to send the scancodes one-by-one. codes="" for keycode in keycodes.split(' ') do case keycode when /^wait(\d*)$/ then sleep_guess($1) else send_keycode(keycode) sleep 0.01 end end #sleep after each sequence (needs to be param) sleep 0.5 } ui.info "Done typing." ui.info "" end def sleep_guess(str) str = "1" if str == "" sleep str.to_i end def send_keycode(keycode) command= "#{@vboxcmd} controlvm \"#{name}\" keyboardputscancode #{keycode}" env.logger.debug "#{command}" sshresult = shell_exec("#{command}",{:mute => true}) env.logger.debug "\ sshresult.stdout: #{sshresult.stdout.inspect}, sshresult.stderr: #{sshresult.stderr.inspect}" if sshresult.stdout.index("E_ACCESSDENIED") error= "There was an error typing the commands on the console" error+="Probably the VM did not get started." error+= "" error+= "#{sshresult.stdout}" raise Veewee::Error, error end end end #Module end #Module end #Module end #Module ======================= File: lib/veewee/config/collection.rb ======================= <reponame>ibizaman/veewee<gh_stars>1000+ require'veewee/config/component' require 'ostruct' module Veewee class Config class Collection attr_accessor :components attr_accessor :type attr_accessor :config attr_reader :env def initialize(type,config) @type=type @components=Hash.new @providers=config.providers @config=config @env=config.env end def define(name) # We do this for vagrant syntax # Depending on type, we create a variable of that type # f.i. component_stub.vm or component_stub.lb component_stub=OpenStruct.new component_stub.send("#{@type}=",::Veewee::Config::Component.new(config)) env.logger.info("config collection"){ "First pass of reading the config"} # Now we can 'execute' the config file using our stub component # For guessing the provider type yield component_stub env.logger.debug("config collection"){ "Stubs collection type #{@type} is loaded"} # After processing we extract the component again component=component_stub.send("#{@type}") provider=@providers[component.provider.to_s] env.logger.debug("config collection"){ "We get here"} abort "Provider #{component.provider.to_s} does not (yet) exist" if provider.nil? real_component=provider.get_component(@type.capitalize,env) begin # And repeat the same process with a real component env.logger.debug("config collection"){ "Component of #{@type}"} component_stub.send("#{@type}=",real_component) yield component_stub # After processing we extract the component again component=component_stub.send("#{@type}") # And we set the name component.name=name # We set the provider for this component component.provider=provider # And register this component with the provider # if it is a vm, we add to the hash vms # if it is an ip, we add it to the hash ips provider_collection=provider.instance_variable_get("@#{@type}s") provider_collection[name]=component # And we also add it to the global config element # So we can have all components of a similar type in one place [email protected]_variable_get("@#{@type}s") config_collection[name]=component # Now we can ask the component to validate itself #component_stub.validate components[name.to_s]=component rescue Error => e env.ui.error "Error loading component with #{name} of type #{@type} for provider #{component.provider.type}" end end end end end #Module Veewee ======================= File: test/definitions/test_definition/definition.rb ======================= <gh_stars>1000+ Veewee::Definition.declare({ :cpu_count => '1', :memory_size=> '512', :disk_size => '10140', :disk_format => 'VDI', :hostiocache => 'off', :os_type_id => 'Linux26', :iso_file => "systemrescuecd-x86-2.3.1.iso", :iso_src => "http://downloads.sourceforge.net/project/systemrescuecd/sysresccd-x86/2.3.1/systemrescuecd-x86-2.3.1.iso", :iso_md5 => "8813aa38506f6e6be1c02e871eb898ca", #:iso_file => "systemrescuecd-x86-2.0.0.iso", #:iso_src => "http://downloads.sourceforge.net/project/systemrescuecd/sysresccd-x86/2.0.0/systemrescuecd-x86-2.0.0.iso", #:iso_md5 => "51012e0bb943cff6367e5cea3a61cdbe", :iso_download_timeout => "1000", :boot_wait => "10", :boot_cmd_sequence => [ '<Tab> raid=noautodetect setkmap=us dodhcp=eth0 fastboot dhcphostname=%NAME% rootpass=vagrant ar_source=http://%IP%:%PORT%/ autoruns=0 ar_nowait dns=127.0.0.1 nomodeset nodetect nodmraid nomadm edd=off quiet nosata nosound nosmp nohotplug acpi=off noresume load=eth1000 nonet noload=ipv6,floppy,md,raid10,raid456,raid1,raid0,multipath,linear,i2c_piix4,i2c_core,udev scandelay=0 nousb<Enter>' ], :kickstart_port => "7122", :kickstart_timeout => "10000", :kickstart_file => "autorun0", :ssh_login_timeout => "10000", :ssh_user => "root", :ssh_password => "<PASSWORD>", :ssh_key => "", :ssh_host_port => "7222", :ssh_guest_port => "22", :sudo_cmd => "sh '%f'", :shutdown_cmd => "shutdown -h -H now", :postinstall_files => ["_disabled_postinstall.sh", "enabled_postinstall.sh" ], :postinstall_timeout => "10000" }) ======================= File: lib/veewee/provider/kvm/box/destroy.rb ======================= <reponame>ibizaman/veewee module Veewee module Provider module Kvm module BoxCommand # Destroy a vm def destroy(options={}) unless exists_vm? or exists_volume? env.ui.error "Error:: You tried to destroy a non-existing box '#{name}'" raise Veewee::Error,"Error:: You tried to destroy a non-existing box '#{name}'" end self.poweroff if running? destroy_vm if exists_vm? vol_exists = exists_volume? env.logger.info "Volume exists?: #{vol_exists}" destroy_volume if vol_exists end def destroy_vm [email protected](:name => name) matched_servers.first.destroy() unless matched_servers.nil? end def destroy_volume @connection.volumes.all(:name => @volume_name).first.destroy end end # End Module end # End Module end # End Module end # End Module ======================= File: templates/windows-8-preview-amd64/winrm.rb ======================= <gh_stars>1000+ require 'winrm' endpoint = 'http://localhost:5985/wsman' winrm=WinRM::WinRMWebService.new(endpoint, :plaintext, :user => 'Administrator', :pass => '<PASSWORD>', :basic_auth_only => true) winrm.cmd('ifconfig /all') do |stdout, stderr| STDOUT.print stdout STDERR.print stderr end #winrm.open_shell ======================= File: lib/veewee/definitions.rb ======================= require 'grit' require'veewee/definition' require'veewee/templates' require'veewee/template' require 'erb' module Veewee class Definitions attr_accessor :env def initialize(env) @env = env @definitions = {} return self end def [](name) if @definitions[name].nil? begin @definitions[name] = Veewee::Definition.load(name, env) rescue Veewee::DefinitionNotExist return nil end end @definitions[name] end # Fetch all definitions def each(&block) definitions = Hash.new env.logger.debug("[Definition] Searching #{env.definition_dir} for definitions:") subdirs = Dir.glob("#{env.definition_dir}/*") subdirs.each do |sub| name = File.basename(sub) env.logger.debug("[Definition] possible definition '#{name}' found") begin definitions[name] = Veewee::Definition.load(name, env) rescue Veewee::DefinitionError => ex env.logger.debug("[Definition] failed to load definition from directory '#{name}' #{ex}") end end if definitions.length == 0 env.logger.debug("[Definition] no definitions found") end definitions.each(&block) end # This function 'defines'/'clones'/'instantiates a template: # It copies from a template dir with template_name # to a new definition dir with definition_name # # Options are : :force => true to overwrite an existing definition # # Returns definition object def define(definition_name, template_name, options = {}) # Default is not to overwrite options = { 'force' => false }.merge(options) env.logger.debug("Forceflag : #{options['force']}") git_template = false # Check if the template is a git repo if template_name.start_with?("git://", "git+ssh://", "git+http://") git_template = true end # Check if template exists template = env.templates[template_name] if template.nil? and! git_template env.logger.fatal("Template '#{template_name}' does not exist") raise Veewee::TemplateError, "Template '#{template_name}' does not exist" else env.logger.debug("Template '#{template_name}' exists") end create_definition_dir_if_needed # Check if definition does not exist definition = env.definitions[definition_name] unless definition.nil? env.logger.debug("Definition '#{definition_name}' exists") if options['force'] == true self.undefine(definition_name, options) else raise Veewee::DefinitionError, "Definition #{definition_name} already exists and no force option was given" end end env.logger.info("Creating definition #{definition_name} in directory '#{env.definition_dir}' ") dst_dir = "#{File.join(env.definition_dir, definition_name)}" FileUtils.mkdir(dst_dir) env.logger.debug("Definition Directory '#{File.join(env.definition_dir, definition_name)}' succesfuly created") # Start copying/cloning the directory of the template to the definition directory if (git_template) begin env.logger.info("Starting git clone #{template_name} #{dst_dir}") g = Grit::Git.new(dst_dir) g.clone({ :timeout => false }, template_name, dst_dir) rescue Exception => ex err = "git clone #{template_name} #{dst_dir} failed: #{ex}" env.logger.fatal(err) raise Veewee::DefinitionError, err end else begin env.logger.debug("Starting copy '#{template.path}' to '#{dst_dir}'") FileUtils.cp_r(template.path + "/.", dst_dir, :preserve => true) env.logger.debug("Copy '#{template.path}' to '#{dst_dir}' succesful") rescue Exception => ex env.logger.fatal("Copy '#{template.path}' to #{dst_dir}' failed: #{ex}") raise Veewee::Error, "Copy '#{template.path}' to #{dst_dir}' failed: #{ex}" end end # If the template includes a NOTICE.erb or NOTICE.txt file, display it to the user #.erb file takes priority, then.txt notice_erb = File.join(dst_dir, 'NOTICE.erb') notice_txt = File.join(dst_dir, 'NOTICE.txt') if File.exist?(notice_erb) template = File.read(notice_erb) text = ERB.new(template).result(binding) elsif File.exist?(notice_txt) text = File.read(notice_txt) end if text env.ui.warn("Template #{template_name} includes this NOTICE text you should first read:\n") env.ui.info("#{text}\n") end definition = env.definitions[definition_name] return definition end # This function undefines/removes the definition by removing the directoy with definition_name # under env.definition_dir def undefine(definition_name, options = {}) definition = env.definitions[definition_name] unless definition.nil? #TODO: Needs to be more defensive!! env.logger.debug("[Undefine] About to remove '#{definition.path} for '#{definition_name}'") begin if File.exists?(File.join(definition.path, "definition.rb")) FileUtils.rm_rf(definition.path) else env.logger.fatal("Aborting delete: The directory definition.path does not contain a definition.rb file") raise Veewee::DefinitionError, "Aborting delete: The directory definition.path does not contain a definition.rb file" end rescue Exception => ex env.logger.fatal("Removing '#{definition.path} for '#{definition_name}' failed: #{ex}") raise Veewee::Error, "Removing '#{definition.path }for '#{definition_name}' failed: #{ex}" end env.logger.debug("Removing '#{definition.path} for '#{definition_name}' succesful") else raise Veewee::DefinitionError, "Definition '#{definition_name}' does not exist" end end def create_definition_dir_if_needed # Check if definition_dir already exists unless File.exists?(env.definition_dir) env.logger.debug("Creating definition base directory '#{env.definition_dir}' ") FileUtils.mkdir(env.definition_dir) env.logger.debug("Definition base directory '#{env.definition_dir}' succesfuly created") end if File.writable?(env.definition_dir) env.logger.debug("DefinitionDir '#{env.definition_dir}' is writable") if File.exists?("#{env.definition_dir}") env.logger.debug("DefinitionDir '#{env.definition_dir}' already exists") else env.logger.debug("DefinitionDir '#{env.definition_dir}' does not exist, creating it") FileUtils.mkdir(definition_dir) env.logger.debug("DefinitionDir '#{env.definition_dir}' succesfuly created") end else env.logger.fatal("DefinitionDir '#{env.definition_dir}' is not writable") raise Veewee::Error, "DefinitionDir '#{env.definition_dir}' is not writable" end end end end ======================= File: lib/fission.old/command/clone.rb ======================= module Fission class Command class Clone < Command def initialize(args=[]) super @options.start = false end def execute option_parser.parse! @args unless @args.count > 1 Fission.ui.output self.class.help Fission.ui.output "" Fission.ui.output_and_exit "Incorrect arguments for clone command", 1 end source_vm_name = @args.first target_vm_name = @args[1] source_vm=Fission::VM.new(source_vm_name) target_vm=Fission::VM.new(target_vm_name) unless source_vm.exists? Fission.ui.output_and_exit "Unable to find the source vm #{source_vm_name} (#{source_vm.path})", 1 end if target_vm.exists? Fission::ui.output_and_exit "The target vm #{target_vm_name} already exists", 1 end clone_task = Fission::VM.clone source_vm_name, target_vm_name if clone_task.successful? Fission.ui.output '' Fission.ui.output 'Clone complete!' if @options.start Fission.ui.output "Starting '#{target_vm_name}'" start_task = target_vm.start if start_task.successful? Fission.ui.output "VM '#{target_vm_name}' started" else Fission.ui.output_and_exit "There was an error starting the VM. The error was:\n#{start_task.output}", start_task.code end end else Fission.ui.output_and_exit "There was an error cloning the VM. The error was:\n#{clone_task.output}", clone_task.code end end def option_parser optparse = OptionParser.new do |opts| opts.banner = "\nclone usage: fission clone source_vm target_vm [options]" opts.on '--start', 'Start the VM after cloning' do @options.start = true end end optparse end end end end ======================= File: lib/veewee/config/definition.rb ======================= <reponame>ibizaman/veewee require'veewee/config/component' require'veewee/definition' require 'ostruct' module Veewee class Config class Definition attr_accessor :components attr_reader :env def initialize(config) @env=config.env @components=Hash.new end # Currently not used, this is in case we will specify the a definition in the Veeweefile # This is for future needs def define(name) # Depending on type, we create a variable of that type definition_stub=OpenStruct.new begin # Get a real definition object real_definition=::Veewee::Definition.new(name,env) rescue Error => e env.ui.error("Error loading provider with #{name},#{$!}",:prefix => false) end definition_stub.definition=real_definition env.logger.debug("config definition"){ "Start defining definition"} yield definition_stub env.logger.debug("config definition"){ "End defining definition #{definition_stub.definition.name}"} components[name.to_s]=definition_stub.definition end end end end #Module Veewee ======================= File: templates/SLES-11-SP1-DVD-i586-GM/definition.rb ======================= Veewee::Session.declare({ :os_type_id => 'OpenSUSE', :cpu_count => '1', :memory_size => '1024', :disk_size => '20480', :disk_format => 'VDI', :hostiocache => 'off', :iso_file => "SLES-11-SP1-DVD-i586-GM-DVD1.iso", :iso_src => "", :iso_md5 => "0dd6886858d93501c38854552b9b1b0d", :iso_download_timeout => "1000", :boot_wait => "10", :boot_cmd_sequence => [ '<Esc><Enter>', 'linux netdevice=eth0 netsetup=dhcp install=cd:/', 'lang=en_US autoyast=http://%IP%:%PORT%/autoinst_en.xml', ### disable prev line and enable next line to install with german settings #' lang=de_DE autoyast=http://%IP%:%PORT%/autoinst_de.xml', 'textmode=1', '<Enter>' ], :kickstart_port => "7122", :kickstart_timeout => "300", :kickstart_file => ["autoinst_en.xml", "autoinst_en.xml"], ### disable prev line and enable next line to install with german settings #:kickstart_file => ["autoinst_de.xml", "autoinst_de.xml"], :ssh_login_timeout => "10000", :ssh_user => "vagrant", :ssh_password => "<PASSWORD>", :ssh_key => "", :ssh_host_port => "7222", :ssh_guest_port => "22", :sudo_cmd => "echo '%p'|sudo -S sh '%f'", :shutdown_cmd => "shutdown -P now", :postinstall_files => ["postinstall.sh"], :postinstall_timeout => "10000" }) ======================= File: lib/veewee/provider/parallels/box/halt.rb ======================= module Veewee module Provider module Parallels module BoxCommand #FIXME def halt(options={}) super(options) end end end end end ======================= File: templates/windows-2012-serverstandard-amd64/definition.rb ======================= # -*- coding: utf-8 -*- Veewee::Session.declare({ :os_type_id => 'Windows8_64', :iso_download_instructions => "Download and install full featured software for 180-day trial at http://technet.microsoft.com/en-US/evalcenter/hh670538.aspx", :iso_file => "9200.16384.WIN8_RTM.120725-1247_X64FRE_SERVER_EVAL_EN-US-HRM_SSS_X64FREE_EN-US_DV5.ISO", :iso_md5 => "8503997171f731d9bd1cb0b0edc31f3d", :iso_src => "http://care.dlservice.microsoft.com//dl/download/6/D/A/6DAB58BA-F939-451D-9101-7DE07DC09C03/9200.16384.WIN8_RTM.120725-1247_X64FRE_SERVER_EVAL_EN-US-HRM_SSS_X64FREE_EN-US_DV5.ISO", :iso_download_timeout => "1000", :cpu_count => '1', :memory_size=> '512', :disk_size => '10140', :disk_format => 'VDI', :hostiocache => 'off', :floppy_files => [ "Autounattend.xml", "oracle-cert.cer"], :boot_wait => "1", :boot_cmd_sequence => [''], :kickstart_port => "7122", :winrm_user => "vagrant", :winrm_password => "<PASSWORD>", # And run postinstall.sh for up to 10000 seconds :postinstall_timeout => "10000", :postinstall_files => ["install-chef.bat", "install-puppet.bat", "install-vbox.bat"], # No sudo on windows :sudo_cmd => "%f", :shutdown_cmd => "shutdown /s /t 10 /f /d p:4:1 /c \"Vagrant Shutdown\"", }) ======================= File: lib/veewee/provider/virtualbox/provider.rb ======================= <filename>lib/veewee/provider/virtualbox/provider.rb require'veewee/provider/core/provider' require'veewee/provider/virtualbox/box' module Veewee module Provider module Virtualbox class Provider < Veewee::Provider::Core::Provider # include ::Veewee::Provider::Virtualbox::ProviderCommand def check_requirements command = Box.determine_vboxcmd unless self.shell_exec("#{command} -v").status == 0 raise Veewee::Error,"Could not execute VBoxManage command. Please install Virtualbox or make sure VBoxManage is in the Path" end end end #End Class end # End Module end # End Module end # End Module ======================= File: lib/veewee/provider/vmfusion/box/poweroff.rb ======================= <filename>lib/veewee/provider/vmfusion/box/poweroff.rb module Veewee module Provider module Vmfusion module BoxCommand def poweroff(options={}) raw.stop(:hard => true) unless raw.nil? end end end end end ======================= File: templates/openSUSE-12.3/definition.rb ======================= <gh_stars>1000+ Veewee::Definition.declare_yaml('definition.yml', :hooks => { :before_ssh => Proc.new { sleep 10 } }) ======================= File: templates/alpinelinux-3.6.2-x86_64-virtual/definition.rb ======================= require 'net/http' iso_name = 'alpine-virt-3.6.2-x86_64.iso' iso_mirror = 'http://dl-cdn.alpinelinux.org/alpine/v3.6/releases/x86_64' iso_uri = "#{iso_mirror}/#{iso_name}" check_sum = "#{iso_mirror}/#{iso_name}.sha256" root_password = '<PASSWORD>' Veewee::Definition.declare({ :cpu_count => "1", :memory_size => "256", :disk_size => "10140", :disk_format => "VDI", :hostiocache => "off", :os_type_id => "Linux26_64", :iso_file => iso_name, :iso_src => iso_uri, :iso_sha256 => check_sum, :iso_download_timeout => "1000", :boot_wait => "5", :boot_cmd_sequence => [ '<Enter>', '<Wait30>', 'root<Enter>', 'ifconfig eth0 up<Enter>', 'udhcpc eth0<Enter>', 'passwd<Enter>', "#{root_password}<Enter>", "#{root_password}<Enter>", 'setup-apkrepos -1<Enter>', 'apk add openssh<Enter>', 'echo "PermitRootLogin yes" >> /etc/ssh/sshd_config<Enter>', '/etc/init.d/sshd start<Enter>', ], :ssh_login_timeout => "10000", :ssh_user => "root", :ssh_password => "#{<PASSWORD>}", :ssh_key => "", :ssh_host_port => "7222", :ssh_guest_port => "22", :sudo_cmd => "echo '%p'|sudo -S sh '%f'", :shutdown_cmd => "poweroff", :postinstall_files => [ 'settings.sh', 'base.sh', 'sudo.sh', 'user.sh', 'apk.sh', 'virtualbox.sh', 'vagrant.sh', # 'aports.sh', 'ruby.sh', 'puppet.sh', 'chef.sh', 'cleanup.sh', 'zerodisk.sh', 'reboot.sh', ], :postinstall_timeout => "10000", :params => { #:PACMAN_REFLECTOR_ARGS => '--verbose -l 5 --sort rate --save /etc/pacman.d/mirrorlist', } }) ======================= File: lib/veewee/provider/virtualbox/box/helper/forwarding.rb ======================= <reponame>ibizaman/veewee<filename>lib/veewee/provider/virtualbox/box/helper/forwarding.rb module Veewee module Provider module Virtualbox module BoxCommand def forwarding(name) command="#{@vboxcmd} showvminfo --details --machinereadable \"#{self.name}\"" shell_results=shell_exec("#{command}") rules=shell_results.stdout.split(/\n/).grep(/^Forward/) result=nil rules.each do |rule| #Forwarding(0) nr=rule.split('=')[0].split('(')[1].split(')')[0].to_i + 1 # guestssh,tcp,,2222,,22 details=rule.split('=')[1].split('"')[1].split(',') result = { :nr => nr, :name => details[0], :protocol => details[1], :host_ip => details[2], :host_port => details[3], :guest_ip => details[4], :guest_port => details[5] } end return result end def delete_forwarding(name) forward=self.forwarding(name) if self.running? command="#{@vboxcmd} controlvm \"#{self.name}\" natpf#{self.natinterface} delete \"#{name}\"" else command="#{@vboxcmd} modifyvm \"#{self.name}\" --natpf#{self.natinterface} delete \"#{name}\"" end shell_results=shell_exec("#{command}") end end end end end ======================= File: lib/fission.old/version.rb ======================= <filename>lib/fission.old/version.rb module Fission VERSION = "0.4.0a" end ======================= File: lib/fission.old/command/snapshot_list.rb ======================= module Fission class Command class SnapshotList < Command def initialize(args=[]) super end def execute unless @args.count == 1 Fission.ui.output self.class.help Fission.ui.output "" Fission.ui.output_and_exit "Incorrect arguments for snapshot list command", 1 end vm_name = @args.first vm = Fission::VM.new vm_name unless vm.exists? Fission.ui.output_and_exit "Unable to find the VM #{vm_name} (#{vm.path})", 1 end snaps=vm.snapshots unless snaps.empty? Fission.ui.output snaps.join("\n") else Fission.ui.output "No snapshots found for VM '#{vm_name}'" end # TODO Fission.ui.output_and_exit "There was an error listing the snapshots. The error was:\n#{task.output}", task.code end def option_parser optparse = OptionParser.new do |opts| opts.banner = "\nsnapshot list: fission snapshot list my_vm" end optparse end end end end ======================= File: test/build_realtest.rb ======================= <gh_stars>1000+ require 'test/unit' require'veewee' class TestVeeweeBuild < Test::Unit::TestCase def setup definition_dir=File.expand_path(File.join(File.dirname(__FILE__),"definitions")) #ENV['VEEWEE_LOG']="STDOUT" @ve=Veewee::Environment.new({ :definition_dir => definition_dir }) @definition_name="test_definition" @[email protected][@definition_name] @box_name=@definition_name @vd.postinstall_files=["_test_me.sh"] @[email protected]["virtualbox"].get_box(@box_name) end # First build of box # - the creation # - kickstart fetch # - postinstall execution def test_box_1_build assert_nothing_raised { @box.build({'auto' => true,'force' => true, 'nogui' => true, 'disk_count' => 2}) #@box.build({"auto" => true,"force" => true }) } end # Run an ssh command def test_box_2_ssh assert_nothing_raised { [email protected]("who am i") assert_match(/root/,result.stdout) } end # Type on console def test_box_3_console_type assert_nothing_raised { @box.console_type(['echo "bla" > console.txt<Enter>']) [email protected]("cat console.txt") assert_match(/bla/,result.stdout) } end # Are there as many disks as in disk_count? def test_box_4_check_disk_count assert_nothing_raised { [email protected]("lsblk -lo MODEL|grep -i harddisk|wc -l") assert_match(/#{@box.definition.disk_count}/,result.stdout) } end # Try shutdown def test_box_5_shutdown assert_nothing_raised { @box.halt } end # Now try build again (with no force flag) def test_box_6_build #assert_raise(Veewee::Error) { assert_nothing_raised { #@box.build({"auto" => true}) @box.build({"auto" => true,'force' => true, 'nogui' => true }) } end def test_box_7_destroy assert_nothing_raised { @box.destroy } end # # def teardown # #@ve.destroy(@vm_name,@vd) # # end end ======================= File: lib/veewee/command/vagrant/ostypes.rb ======================= require 'optparse' module Veewee module Command module Vagrant class Ostypes < ::Vagrant::Command::Base def execute options = {} opts = OptionParser.new do |opts| opts.banner = "List the available Operating System types" opts.separator "" opts.separator "Usage: vagrant basebox ostypes" opts.on("-d", "--debug", "enable debugging") do |d| options['debug'] = d end end # Parse the options argv = parse_options(opts) return if!argv begin venv=Veewee::Environment.new(options) venv.ui = @env.ui venv.ostypes.each do |name| venv.ui.info("- #{name}", :prefix => false) end rescue Veewee::Error => ex venv.ui.error(ex,:prefix => false) exit -1 end end end end end end ======================= File: lib/veewee/provider/core/helper/tcp.rb ======================= <filename>lib/veewee/provider/core/helper/tcp.rb<gh_stars>1000+ require'socket' require 'timeout' module Veewee module Provider module Core module Helper module Tcp def is_tcp_port_open?(ip, port) begin Timeout::timeout(1) do begin s = TCPSocket.new(ip, port) s.close env.logger.debug("TCP port #{ip}:#{port} is used.") return true rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH,Errno::ENETDOWN return false end end rescue Timeout::Error end return false end # This tries to guess a local free tcp port def guess_free_port(min_port,max_port) ui.info "Finding unused TCP port in range: #{min_port} - #{max_port}" guessed_port=nil (min_port..max_port).each do |port| unless is_tcp_port_open?(get_local_ip, port) guessed_port=port break end end if guessed_port.nil? message = "No free TCP port available in range: #{min_port} - #{max_port}" ui.error message raise Veewee::Error, message end ui.info "Selected TCP port #{guessed_port}" return guessed_port end def guess_free_ssh_port(min_port, max_port) if definition.force_ssh_port ui.warn "SSH port auto-configuration is disabled in the definition (force_ssh_port=true)." if is_tcp_port_open?(get_local_ip, min_port) ui.warn "TCP port #{min_port} is in use. You may execute the postinstall scripts on a different machine than intended!" end return min_port else return guess_free_port(min_port, max_port) end end def execute_when_tcp_available(ip="127.0.0.1", options = { }, &block) defaults={ :port => 22, :timeout => 2, :pollrate => 5} options=defaults.merge(options) timeout=options[:timeout] timeout=ENV['VEEWEE_TIMEOUT'].to_i unless ENV['VEEWEE_TIMEOUT'].nil? begin Timeout::timeout(timeout) do connected=false while!connected do begin ui.info "trying connection" s = TCPSocket.new(ip, options[:port]) s.close block.call(ip); return true rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH,Errno::ENETDOWN sleep options[:pollrate] end end end rescue Timeout::Error raise "Timeout connecting to TCP port {options[:port]} exceeded #{timeout} secs." end return false end def host_ip_as_seen_by_guest get_local_ip end def get_local_ip orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true # turn off reverse DNS resolution temporarily UDPSocket.open do |s| s.connect '192.168.127.12', 1 s.addr.last end ensure Socket.do_not_reverse_lookup = orig end end #Module end #Module end #Module end #Module end #Module ======================= File: lib/veewee/provider/core/box/sudo.rb ======================= module Veewee module Provider module Core module BoxCommand def sudo(scriptname) if definition.ssh_user=="root" return "#{scriptname}" else command=definition.sudo_cmd newcommand=command.gsub(/%p/,"#{definition.ssh_password}") newcommand.gsub!(/%u/,"#{definition.ssh_user}") newcommand.gsub!(/%f/,"#{scriptname}") return newcommand end end end #Module end #Module end #Module end #Module ======================= File: lib/veewee/provider/vmfusion/box/helper/buildinfo.rb ======================= module Veewee module Provider module Vmfusion module BoxCommand def build_info info=super output=IO.popen("#{vmrun_cmd.shellescape}").readlines info << {:filename => ".vmfusion_version",:content => @provider.fusion_version } end def guest_iso_directory # use vmware fusion 3.x as default path iso_images_dir="/Library/Application Support/VMware Fusion/isoimages" # if path doesn't exist check for vmware fusion >= 4.x path if(! File.exists?(iso_images_dir) ) iso_images_dir="/Applications/VMware Fusion.app/Contents/Library/isoimages" end return iso_images_dir end # Determine the iso of the guest additions def guest_iso_path # So we begin by transferring the ISO file of the vmware tools iso_image=File.join(guest_iso_directory, "linux.iso") iso_image=File.join(guest_iso_directory, "darwin.iso") if definition.os_type_id=~/^Darwin/ iso_image=File.join(guest_iso_directory, "freebsd.iso") if definition.os_type_id=~/^Free/ iso_image=File.join(guest_iso_directory, "windows.iso") if definition.os_type_id=~/^Win/ return iso_image end # Transfer information provide by the provider to the box # # def transfer_buildinfo(options) super(options) # Initialize download_tools to true if null if definition.vmfusion[:vm_options]['download_tools'].nil? definition.vmfusion[:vm_options]['download_tools'] = true end # When we get here, ssh is available and no postinstall scripts have been executed yet # So we begin by transferring the ISO file of the vmware tools if!(definition.winrm_user && definition.winrm_password) && definition.vmfusion[:vm_options]['download_tools'] # with windows, we just use the mounted volume env.logger.info "About to transfer vmware tools iso buildinfo to the box #{name} - #{ip_address} - #{ssh_options}" iso_image=guest_iso_path if File.exists?(iso_image) self.copy_to_box(iso_image,File.basename(iso_image)) else raise Veewee::Error, "We could not find the file #{iso_image}. In newer versions of Fusion, you might have to download the Guest Additions yourself. You can do this by first manually creating a vm and than 'installing the guest additions'" end end end end end end end ======================= File: lib/veewee/provider/virtualbox/box/screenshot.rb ======================= module Veewee module Provider module Virtualbox module BoxCommand def screenshot(filename,options={}) raise Veewee::Error, "The VM needs to exist before we can take a screenshot" unless self.exists? raise Veewee::Error, "The VM needs to be running before we can test a screenshot" unless self.running? # If the vm is not powered off, take a screenshot if (self.exists? && self.running?) ui.info "Saving screenshot of vm #{name} in #{filename}" command="#{@vboxcmd} controlvm \"#{name}\" screenshotpng \"#{filename}\"" shell_exec("#{command}") unless File.exists?(filename) raise Veewee::Error,"Saving Screenshot #{filename} failed" end end end end end end end ======================= File: lib/veewee/command/vagrant.rb ======================= <reponame>ibizaman/veewee require'veewee' require'veewee/command/vagrant/basebox' Vagrant.commands.register(:basebox) { Veewee::Command::Vagrant::Basebox } ======================= File: lib/veewee/providers.rb ======================= <filename>lib/veewee/providers.rb module Veewee class Providers def initialize(env, options = {}) @env = env @options = options @providers = Hash.new end def [](name) return @providers[name] if @providers.has_key?(name) begin require_path ='veewee/provider/' + name.to_s.downcase + "/provider" require require_path provider = Object.const_get("Veewee").const_get("Provider").const_get(name.to_s.capitalize).const_get("Provider").new(name, @options, @env) @providers[name] = provider rescue ::Veewee::Error => e raise rescue Error => e env.ui.error "Error loading provider with #{name}, #{$!}", :prefix => false end end def length @providers.length end end end #Module Veewee ======================= File: lib/veewee/provider/virtualbox/box/helper/version.rb ======================= <filename>lib/veewee/provider/virtualbox/box/helper/version.rb module Veewee module Provider module Virtualbox module BoxCommand UNSYNCED_VERSIONS = {"4.2.1" => "4.2.0", "4.1.23" => "4.1.22"} # Return the major/minor/incremental version of VirtualBox. # For example: 4.1.8_Debianr75467 -> 4.1.8 def vbox_version command="#{@vboxcmd} --version" stderr = "/dev/null" is_windows = (RbConfig::CONFIG['host_os'] =~ /mswin|mingw|cygwin/) stderr = "nul" if is_windows shell_results=shell_exec("#{command}",{:mute => true, :stderr => stderr}) version=shell_results.stdout.strip.split(/[^0-9\.]/)[0] return version end def vboxga_version affected_version?(self.vbox_version)? UNSYNCED_VERSIONS[self.vbox_version] : self.vbox_version end protected def affected_version?(ver) RUBY_PLATFORM.downcase.include?("darwin") && UNSYNCED_VERSIONS.has_key?(ver) end end end end end ======================= File: lib/veewee/provider/kvm/box/up.rb ======================= module Veewee module Provider module Kvm module BoxCommand def up(options={}) [email protected](:name => name) matched_servers.first.start unless matched_servers.nil? rescue Libvirt::Error => e warn " Libvirt Error! Make sure your user has permissions to run anything. " raise e end end # End Module end # End Module end # End Module end # End Module ======================= File: lib/veewee/provider/core/box.rb ======================= <filename>lib/veewee/provider/core/box.rb require'veewee/provider/core/helper/tcp' require'veewee/provider/core/helper/ssh' require'veewee/provider/core/helper/web' require'veewee/provider/core/helper/shell' require'veewee/provider/core/helper/iso' require'veewee/provider/core/helper/comm' require'veewee/provider/core/box/build' require'veewee/provider/core/box/scp' require'veewee/provider/core/box/copy' require'veewee/provider/core/box/exec' require'veewee/provider/core/box/poweroff' require'veewee/provider/core/box/halt' require'veewee/provider/core/box/sudo' require'veewee/provider/core/box/ssh' require'veewee/provider/core/box/issh' require'veewee/provider/core/box/floppy' require'veewee/provider/core/box/validate_tags' module Veewee module Provider module Core class Box attr_accessor :definition attr_accessor :env attr_accessor :name attr_accessor :provider include ::Veewee::Provider::Core::Helper::Tcp include ::Veewee::Provider::Core::Helper::Web include ::Veewee::Provider::Core::Helper::Shell include ::Veewee::Provider::Core::Helper::Ssh include ::Veewee::Provider::Core::Helper::Comm include ::Veewee::Provider::Core::Helper::Iso include ::Veewee::Provider::Core::BoxCommand def ui return @_ui if defined?(@_ui) @_ui = @env.ui.dup @_ui.resource = @name @_ui end def initialize(name,env) @env=env @name=name self.set_definition(name) end def gem_available?(gemname) env.logger.info "Checking for gem #{gemname}" available=false begin available=true unless Gem::Specification::find_by_name("#{gemname}").nil? rescue Gem::LoadError env.logger.info "Error loading gem #{gemname}" available=false rescue env.logger.info "Falling back to old syntax for #{gemname}" available=Gem.available?("#{gemname}") env.logger.info "Old syntax #{gemname}.available? #{available}" end return available end def set_definition(definition_name) @definition=env.definitions[definition_name] unless @definition.nil? # We check for windows as em-winrm is not available on ruby1.9 is_windows = @definition.os_type_id.start_with?('Windows') # On windows systems if is_windows # Check if winrm is available if gem_available?('em-winrm') require'veewee/provider/core/box/winrm' require'veewee/provider/core/helper/winrm' require'veewee/provider/core/box/wincp' self.class.send(:include, ::Veewee::Provider::Core::Helper::Winrm) else raise Veewee::Error, "\nTo build a windows basebox you need to install the gem 'em-winrm' first" end end else raise Veewee::Error, "definition '#{definition_name}' does not exist. Are you sure you are in the top directory?" end return self end def reload @raw=nil end end #End Class end # End Module end # End Module end # End Module ======================= File: lib/veewee/provider/kvm/box/helper/status.rb ======================= module Veewee module Provider module Kvm module BoxCommand def running? if exists_vm? @connection.servers.all(:name => name).first.ready? else false end end def exists? exists_volume? || exists_vm? end def exists_volume? [email protected]_volumes(:name => @volume_name).first.empty? end def exists_vm? begin @connection.list_domains(:name => name) rescue Libvirt::RetrieveError false end end end # End Module end # End Module end # End Module end # End Module ======================= File: lib/fission.old/config.rb ======================= <reponame>ibizaman/veewee<filename>lib/fission.old/config.rb module Fission class Config attr_accessor :attributes CONF_FILE = File.expand_path '~/.fissionrc' def initialize @attributes = {} load_from_file if @attributes['vm_dir'].blank? @attributes['vm_dir'] = File.expand_path('~/Documents/Virtual Machines.localized/') end if File.exists?('/Library/Application Support/VMware Fusion/vmrun') @attributes['vmrun_bin'] = '/Library/Application Support/VMware Fusion/vmrun' else @attributes['vmrun_bin'] = '/Applications/VMware Fusion.app/Contents/Library/vmrun' end @attributes['vmrun_cmd'] = "#{@attributes['vmrun_bin'].gsub(' ', '\ ')} -T fusion" @attributes['plist_file'] = File.expand_path('~/Library/Preferences/com.vmware.fusion.plist') @attributes['gui_bin'] = File.expand_path('/Applications/VMware Fusion.app/Contents/MacOS/vmware') end private def load_from_file if File.file?(CONF_FILE) @attributes.merge!(YAML.load_file(CONF_FILE)) end end end end ======================= File: lib/veewee/provider/core/helper/comm.rb ======================= module Veewee module Provider module Core module Helper module Comm def comm_method if (definition.winrm_user && definition.winrm_password) :winrm else :ssh end end def when_comm_login_works(ip="127.0.0.1", options = { }, &block) case comm_method when :winrm when_winrm_login_works(ip,options,block) when :ssh when_ssh_login_works(ip,options,block) end end def comm_transfer_file(host,filename,destination = '.', options = {}) case comm_method when :winrm winrm_transfer_file(host,filename,destination,options) when :ssh ssh_transfer_file(host,filename,destination,options) end end def comm_execute(host,command, options = { :progress => "on"} ) case comm_method when :winrm winrm_execute(host,command, options ) when :ssh ssh_execute(host,command, options ) end end end #Class end #Module end #Module end #Module end #Module ======================= File: test/veewee/provider/virtualbox/box/helper/version.rb ======================= require 'test/unit' require'veewee/provider/virtualbox/box/helper/version' require 'logger' class TestVboxGuestAdditionsHelper < Test::Unit::TestCase include Veewee::Provider::Virtualbox::BoxCommand def affected_versions { "4.2.1" => "4.2.0", "4.1.23" => "4.1.22" } end def test_affected_osx_version_returns_downpatched_ga_version set_ruby_platform("darwin") affected_versions.each do |vbox_version, guest_version| set_vbox_version(vbox_version) assert_equal(guest_version, self.vboxga_version) end end def test_unaffected_osx_version_returns_same_version set_ruby_platform("darwin") set_vbox_version("4.1.22") assert_equal("4.1.22", self.vboxga_version) end def test_affected_linux_version_returns_same_version set_ruby_platform("linux") affected_versions.keys.each do |version| set_vbox_version(version) assert_equal(version, self.vboxga_version) end end def test_unaffected_linux_version_returns_same_version set_ruby_platform("linux") set_vbox_version("4.0.19") assert_equal("4.0.19", self.vboxga_version) end def test_affected_mswin_version_returns_same_version set_ruby_platform("mswin") affected_versions.keys.each do |version| set_vbox_version(version) assert_equal(version, self.vboxga_version) end end def test_unaffected_mswin_version_returns_same_version set_ruby_platform("mswin") set_vbox_version("4.0.19") assert_equal("4.0.19", self.vboxga_version) end private def set_ruby_platform(platform) Object.const_set("RUBY_PLATFORM", platform) end def set_vbox_version(ver) Veewee::Provider::Virtualbox::BoxCommand.send(:define_method, :vbox_version) do ver end end end ======================= File: lib/veewee/command/version.rb ======================= module Veewee module Command class VersionCommand < Base register "version", "Prints the Veewee version information" def execute env.ui.info "Version : #{Veewee::VERSION} - use at your own risk" end end end end ======================= File: lib/veewee/config/component.rb ======================= module Veewee class Config class Component attr_accessor :provider attr_reader :env def initialize(config) @env=config.env end def method_missing(m, *args, &block) # env.ui.info "There's no method called #{m} here -- please try again." end end end end #Module Veewee ======================= File: templates/kali-1.0.9a-amd64/definition.rb ======================= <filename>templates/kali-1.0.9a-amd64/definition.rb Veewee::Session.declare({ :cpu_count => '1', :memory_size => '512', :disk_size => '20480', :disk_format => 'VDI', :hostiocache => 'off', :os_type_id => 'Debian_64', :iso_file => "kali-linux-1.0.9a-amd64.iso", :iso_src => "http://cdimage.kali.org/kali-1.0.9a/kali-linux-1.0.9a-amd64.iso", :iso_md5 => "401e2b14921de5f808c7786b3b84dc57", :iso_download_timeout => "2000", :boot_wait => "10", :boot_cmd_sequence => [ '<Esc>', 'install ', 'preseed/url=http://%IP%:%PORT%/preseed.cfg ', 'debian-installer=en_US ', 'auto ', 'locale=en_US ', 'kbd-chooser/method=us ', 'netcfg/get_hostname=%NAME% ', 'netcfg/get_domain=vagrantup.com ', 'fb=false ', 'debconf/frontend=noninteractive ', 'console-setup/ask_detect=false ', 'console-keymaps-at/keymap=us ', 'keyboard-configuration/xkb-keymap=us ', '<Enter>' ], :kickstart_port => "7122", :kickstart_timeout => "10000", :kickstart_file => "preseed.cfg", :ssh_login_timeout => "10000", :ssh_user => "vagrant", :ssh_password => "<PASSWORD>", :ssh_key => "", :ssh_host_port => "7222", :ssh_guest_port => "22", :sudo_cmd => "echo '%p'|sudo -S bash '%f'", :shutdown_cmd => "halt -h -p", :postinstall_files => [ "base.sh", "virtualbox.sh", "vagrant.sh", "chef.sh", "puppet.sh", "cleanup.sh", "zerodisk.sh" ], :postinstall_timeout => "10000" }) ======================= File: templates/windows-2008R2-serverstandard-amd64/definition.rb ======================= # -*- coding: utf-8 -*- Veewee::Session.declare({ :os_type_id => 'Windows2008_64', # http://technet.microsoft.com/en-us/evalcenter/dd459137.aspx # Download and install full featured software for 180-day trial :iso_file => "7601.17514.101119-1850_x64fre_server_eval_en-us-GRMSXEVAL_EN_DVD.iso", :iso_md5 => "4263be2cf3c59177c45085c0a7bc6ca5", :iso_src => "http://care.dlservice.microsoft.com//dl/download/7/5/E/75EC4E54-5B02-42D6-8879-D8D3A25FBEF7/7601.17514.101119-1850_x64fre_server_eval_en-us-GRMSXEVAL_EN_DVD.iso", :iso_download_timeout => "1000", :cpu_count => '1', :memory_size=> '384', :disk_size => '10140', :disk_format => 'VDI', :hostiocache => 'off', :floppy_files => [ "Autounattend.xml", "install-cygwin-sshd.bat", "install-winrm.bat", "oracle-cert.cer"], #:boot_wait => "35", :boot_wait => "1", # after 35 seconds, hit these keys to not enter a product key and fully automate the install # if your machine is slower it may take more time # :boot_cmd_sequence => [ # '<Tab><Tab><Tab><Enter>', # '<Enter>' # ], :boot_cmd_sequence => [''], :ssh_login_timeout => "10000", # Actively attempt to winrm (no ssh on base windows) in for 10000 seconds :ssh_user => "vagrant", :ssh_password => "<PASSWORD>", :ssh_key => "", :ssh_host_port => "59856", :ssh_guest_port => "22", # And run postinstall.sh for up to 10000 seconds :postinstall_timeout => "10000", :postinstall_files => ["postinstall.sh"], # No sudo on windows :sudo_cmd => "sh '%f'", # Shutdown is different as well :shutdown_cmd => "shutdown /s /t 60 /d p:4:1 /c \"Vagrant Shutdown\"", }) ======================= File: lib/fission.old/error.rb ======================= <reponame>ibizaman/veewee<gh_stars>1000+ module Fission class Error < StandardError attr_reader :original def initialize(msg, original=$!) super(msg) @original = original end end end ======================= File: templates/gentoo-latest/definition.rb ======================= require 'net/http' # Change the file for definitionVariation to one of the.yml configurations in this directory for the box you would like to build. definitionVariation = 'gentoo_amd64_minimal.yml' Veewee::Definition.declare_yaml('definition.yml', definitionVariation) file = YAML.load_file(definitionVariation); arch = file[:architecture] template_uri = "http://distfiles.gentoo.org/releases/#{arch}/autobuilds/latest-install-#{arch}-minimal.txt" template_build = Net::HTTP.get_response(URI.parse(template_uri)).body.split(/\n/).last.split(/\ /) # If you are finding you need to run this process many times, manually download the stage3 and portage file # and tar them together as postinstall-gentoo.tar in your veewee working directory then uncomment the hooks # lines below. Refer to setting_*.sh for how to determine the URL for the appropriate stage3 and portage files. Veewee::Definition.declare({ # :cpu_count => '2', # :memory_size => '4096', :iso_file => template_build.first.split(/\//).last, :iso_src => "http://distfiles.gentoo.org/releases/#{arch}/autobuilds/#{template_build.first}", # :hooks => { # :before_postinstall => Proc.new { definition.box.scp('postinstall-gentoo.tar', 'postinstall-gentoo.tar') } # } }) ======================= File: lib/veewee/provider/vmfusion/box/create.rb ======================= <reponame>ibizaman/veewee<filename>lib/veewee/provider/vmfusion/box/create.rb require 'erb' module Veewee module Provider module Vmfusion module BoxCommand # When we create a new box # We assume the box is not running def create(options) create_vm create_disk self.create_floppy("virtualfloppy.img") end def create_disk #Disk types: # 0 : single growable virtual disk # 1 : growable virtual disk split in 2GB files # 2 : preallocated virtual disk # 3 : preallocated virtual disk split in 2GB files # 4 : preallocated ESX-type virtual disk # 5 : compressed disk optimized for streaming # 6 : thin provisioned virtual disk - ESX 3.x and above disk_type=1 current_dir=FileUtils.pwd FileUtils.chdir(vm_path) env.ui.info "Creating disk" command="#{File.dirname(vmrun_cmd).shellescape}/vmware-vdiskmanager -c -s #{definition.disk_size}M -a lsilogic -t #{disk_type} #{name}.vmdk" shell_results=shell_exec("#{command}",{:mute => true}) FileUtils.chdir(current_dir) end def fusion_os_type(type_id) env.logger.info "Translating #{type_id} into fusion type" fusiontype=env.ostypes[type_id][:fusion] env.logger.info "Found fusion type #{fusiontype}" return fusiontype end def create_vm fusion_definition=definition.dup fusion_definition.os_type_id=fusion_os_type(definition.os_type_id) FileUtils.mkdir_p(vm_path) current_dir=FileUtils.pwd FileUtils.chdir(vm_path) unless definition.vmdk_file.nil? src = "#{File.join(definition.path,definition.vmdk_file)}" FileUtils.cp(src, vm_path) end aFile = File.new(vmx_file_path, "w") aFile.write(vmx_template(fusion_definition)) aFile.close FileUtils.chdir(current_dir) end end end end end ======================= File: lib/veewee/command/vagrant/build.rb ======================= <filename>lib/veewee/command/vagrant/build.rb<gh_stars>1000+ require 'optparse' module Veewee module Command module Vagrant class Build < ::Vagrant::Command::Base def execute options = {} opts = OptionParser.new do |opts| opts.banner = "Build the box <boxname>" opts.separator "" opts.separator "Usage: vagrant basebox build <boxname>" opts.on("-f", "--force", "overwrite the basebox") do |f| options['force'] = f end opts.on("-n", "--nogui", "no gui") do |n| options['nogui'] = n end opts.on("-a", "--auto", "auto answers") do |a| options['auto'] = a end opts.on("-d", "--debug", "enable debugging") do |d| options['debug'] = d end opts.on("-r", "--redirect-console", "redirects serial console") do |r| options['redirectconsole'] = r end opts.on("-i", "--include",Array,"ruby regexp of postinstall filenames to additionally include") do |i| options['postinstall_include'] = i end opts.on("-e", "--exclude",Array,"ruby regexp of postinstall filenames to exclude") do |e| options['postinstall_list'] = e end opts.on("--[no-]checksum","force to check iso file check sum") do |v| options['checksum'] = v end end # Parse the options argv = parse_options(opts) return if!argv raise ::Vagrant::Errors::CLIInvalidUsage, :help => opts.help.chomp if argv.length < 1 begin venv=Veewee::Environment.new(options) [email protected] venv.providers["virtualbox"].get_box(argv[0]).build(options) rescue Veewee::Error => ex venv.ui.error(ex, :prefix => false) exit -1 end end end end end end ======================= File: templates/archlinux-x86_64/definition.rb ======================= <gh_stars>1000+ require 'net/http' iso_mirror = 'http://mirrors.kernel.org/archlinux/iso/2015.03.01' uri = "#{iso_mirror}/md5sums.txt" response = Net::HTTP.get_response(URI.parse(uri)).body.split iso = response[1] iso_md5 = response[0] root_password = '<PASSWORD>' Veewee::Definition.declare({ :cpu_count => "1", :memory_size => "256", :disk_size => "10140", :disk_format => "VDI", :hostiocache => "off", :os_type_id => "ArchLinux_64", :iso_file => iso, :iso_src => "#{iso_mirror}/#{iso}", :iso_md5 => iso_md5, :iso_download_timeout => "1000", :boot_wait => "5", :boot_cmd_sequence => [ '<Enter>', '<Wait30>', 'echo "sshd: ALL" > /etc/hosts.allow<Enter>', 'passwd<Enter>', "#{root_password}<Enter>", "#{root_password}<Enter>", 'systemctl start sshd.service<Enter><Wait>', ], :ssh_login_timeout => "10000", :ssh_user => "root", :ssh_password => "#{<PASSWORD>}", :ssh_key => "", :ssh_host_port => "7222", :ssh_guest_port => "22", :sudo_cmd => "sh '%f'", :shutdown_cmd => "shutdown -h now", :postinstall_files => [ 'base.sh', 'pacman.sh', 'bootloader.sh', 'ssh.sh', 'reboot.sh', 'sudo.sh', 'user.sh', 'aur.sh', 'virtualbox.sh', 'ruby.sh', 'chef.sh', 'puppet.sh', 'vagrant.sh', 'reboot.sh', 'cleanup.sh', 'zerodisk.sh', ], :postinstall_timeout => "10000", :params => { #:PACMAN_REFLECTOR_ARGS => '--verbose -l 5 --sort rate --save /etc/pacman.d/mirrorlist', } }) ======================= File: lib/veewee/provider/kvm/box/create.rb ======================= require 'nokogiri' require 'fileutils' module Veewee module Provider module Kvm module BoxCommand # Create a new vm def create(options={}) # Assemble the Virtualmachine and set all the memory and other stuff" create_server(options) create_volume(options) add_virtio_drivers if File.exists?(File.join(definition.path, 'Autounattend.xml')) self.create_floppy("virtualfloppy.img") FileUtils.move(File.join(definition.path, 'Autounattend.xml.virtio'), File.join(definition.path, 'Autounattend.xml')) if File.exists?(File.join(definition.path, 'Autounattend.xml.virtio')) add_floppy unless definition.floppy_files.nil? end def create_server(options) # set volume pool name to user specified volume pool and fall back to first available volume pool if options["pool_name"] raise Veewee::Error, "Specified storage pool #{options["pool_name"]} does not exist" if @connection.pools.select { |pool| pool.name == options["pool_name"] }.empty? volume_pool_name = options["pool_name"] end volume_pool_name ||= @connection.pools.first.name env.logger.info "Using storage pool #{volume_pool_name}" # set network name to user specified network and fall back to default network or first available network if options["network_name"] raise Veewee::Error, "Specified network #{options["network_name"]} does not exist" if @connection.networks.select { |net| net.name == options["network_name"] }.empty? network_name = options["network_name"] end network_name ||= "default" unless @connection.networks.select { |net| net.name == 'default' }.empty? network_name ||= @connection.networks.first.name env.logger.info "Using network #{network_name}" # Create the "server" attributes = { :name => name, :memory_size => definition.memory_size.to_i*1024, :cpus => definition.cpu_count.to_i, :volume_capacity => "#{definition.disk_size}M", :domain_type => options['use_emulation']? 'qemu' : 'kvm', :iso_file => definition.iso_file, :arch => definition.os_type_id.end_with?("_64")? "x86_64" : "i686", :iso_dir => env.config.veewee.iso_dir, :volume_pool_name => volume_pool_name, :volume_format_type => definition.disk_format, :network_nat_network => network_name } @connection.servers.create(attributes) end # Create the volume of a new vm def create_volume(options) # Creating the volume is part of the server creation end def add_floppy env.logger.info 'Adding floppy disk' # Get a raw libvirt connection conn = @connection.client # Retrieve the domain domain=conn.lookup_domain_by_name(name) # Retrieve the existing XML from the domain domain_xml=domain.xml_desc # Convert the xml nokogiri doc domain_doc=Nokogiri::XML(domain_xml) # Find the device section devices=domain_doc.xpath('/domain/devices').first # The floppy xml representation floppy_xml="<disk type='file' device='floppy'><driver name='qemu' type='raw'/><source file='"+ File.join(definition.path, "virtualfloppy.img") + "'/><target dev='fda' bus='fdc'/><address type='drive' controller='0' bus='0' unit='0'/></disk> <controller type='fdc' index='0'>" # Convert the floppy xml to nokogiri floppy_doc=Nokogiri::XML(floppy_xml) # Add the floppy to the devices section devices.add_child(floppy_doc.root) # Get the raw xml of the changed document new_xml=domain_doc.to_xml # Undefine the existing domain domain.undefine # Re-define the domain conn.define_domain_xml(new_xml) end def add_virtio_drivers env.logger.info 'Adding virtio drivers for windows system to the virtual machine' # Get a raw libvirt connection conn = @connection.client # Retrieve the domain domain=conn.lookup_domain_by_name(name) # Retrieve the existing XML from the domain domain_xml=domain.xml_desc # Convert the xml nokogiri doc domain_doc=Nokogiri::XML(domain_xml) # Find the device section devices=domain_doc.xpath('/domain/devices').first # get latest version of virtio drivers url ='http://alt.fedoraproject.org/pub/alt/virtio-win/latest/images/bin/' filename = open(url).read.scan(/\"(virtio-win-.*.iso)\"/).first.first download_iso(url + filename, filename) path = File.join(env.config.veewee.iso_dir, filename) # The disk xml representation disk_xml="<disk type='file' device='cdrom'><driver name='qemu' type='raw'/><source file='" + path + "'/><target dev='hdd' bus='ide'/></disk>" # Convert the disk xml to nokogiri disk_doc=Nokogiri::XML(disk_xml) # Add the floppy to the devices section devices.add_child(disk_doc.root) # Get the raw xml of the changed document new_xml=domain_doc.to_xml # Undefine the existing domain domain.undefine # Re-define the domain conn.define_domain_xml(new_xml) env.logger.info 'Add search path for virtio drivers to Autounattend.xml' # parse Autoattend.xml to document FileUtils.copy(File.join(definition.path, 'Autounattend.xml'), File.join(definition.path, 'Autounattend.xml.virtio')) doc = Nokogiri::XML.parse(File.read(File.join(definition.path, 'Autounattend.xml'))) # determine platform and windows version platform = definition.os_type_id.end_with?("_64")? "amd64" : "x86" version = case definition.os_type_id.downcase when /windows-?7/ 'win7' when /windows-?2008/ 'win7' when /windows-?8/ 'win8' when /xp/ 'xp' when /vista/ 'vista' else raise 'could not determine windows version' end # create new element component=Nokogiri::XML(%Q|<component name="Microsoft-Windows-PnpCustomizationsWinPE" processorArchitecture="#{platform}" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <DriverPaths> <PathAndCredentials wcm:keyValue="1" wcm:action="add"> <Path>e:\\#{version}\\#{platform}</Path> </PathAndCredentials> </DriverPaths> </component>|) doc.xpath('//unattend:settings[@pass="windowsPE"]', 'unattend' => 'urn:schemas-microsoft-com:unattend').first.add_child component.root file = File.open(File.join(definition.path, 'Autounattend.xml'), 'w') file.write(doc) file.close end end #End Module end # End Module end # End Module end # End Module ======================= File: lib/veewee/cli.rb ======================= <gh_stars>1000+ require 'thor' module Veewee # Entrypoint for the Veewee CLI. This class should never be # initialized directly (like a typical Thor class). Instead, # use {Environment#cli} to invoke the CLI. # # # Defining Custom CLI Commands # # If you're looking to define custom CLI commands, then look at # one of the two following classes: # # * {Command::Base} - Implementing a single command such as `mccloud up`, e.g. # one without subcommands. Also take a look at {Command::NamedBase}. # * {Command::GroupBase} - Implementing a command with subcommands, such as # `mccloud box`, which has the `list`, `add`, etc. subcommands. # # The above linked classes contain the main documentation for each # type of command. class CLI < Thor # Registers the given class with the CLI so it can be accessed. # The class must be a subclass of either {Command::Base} or {Command::GroupBase}. # Don't call this method directly, instead call the {Command::Base.register} # or {Command::GroupBase.register} methods. # # @param [Class] klass Command class # @param [String] name Command name, accessed at `mccloud NAME` # @param [String] usage Command usage, such as "mccloud NAME [--option]" # @param [String] description Description of the command shown during the # command listing. # @param [Hash] opts Other options (not gone into detail here, look at # the source instead). def self.register(klass, name, usage, description, opts = nil) opts ||= {} if klass <= Command::GroupBase # A subclass of GroupBase is a subcommand, since it contains # many smaller commands within it. desc usage, description, opts subcommand name, klass elsif klass <= Command::Base # A subclass of Base is a single command, since it # is invoked as a whole (as Thor::Group) desc usage, description, opts define_method(name) { |*args| invoke klass, args } end if opts[:alias] # Alises are defined for this command, so properly alias the # newly defined method/subcommand: map opts[:alias] => name end end end end #Veewee ======================= File: lib/veewee/provider/core/box/poweroff.rb ======================= <reponame>ibizaman/veewee module Veewee module Provider module Core module BoxCommand def poweroff(options={}) end end # Module end # Module end # Module end # Module ======================= File: lib/veewee/provider/virtualbox/box/build.rb ======================= module Veewee module Provider module Virtualbox module BoxCommand def build(options={}) download_vbox_guest_additions_iso(options) super(options) unless definition.floppy_files.nil? unless self.shell_exec("java -version").status == 0 raise Veewee::Error,"This box contains floppyfiles, to create it you require to have java installed or have it in your path" end end end end end end end ======================= File: lib/veewee/template.rb ======================= <gh_stars>1000+ module Veewee class Template attr_accessor :env attr_reader :name, :path def initialize(name, path, env) @name = name @path = path @env = env return self end def exists? filename = Dir.glob("#{path}/definition.rb") if filename.length!= 0 env.logger.debug("[Template] template '#{name}' is valid") return true else return false end end end end ======================= File: templates/Debian-8/definition.rb ======================= Veewee::Definition.declare_yaml('definition.yml', '8.6.yml') ======================= File: lib/veewee/provider/vmfusion/box/helper/console_type.rb ======================= module Veewee module Provider module Vmfusion module BoxCommand # Type on the console def console_type(sequence,type_options={}) if vnc_enabled? vnc_type(sequence,"127.0.0.1",vnc_display_port) else raise Veewee::Error, "VNC is not enabled" end end end end end end ======================= File: lib/veewee/error.rb ======================= <gh_stars>1000+ module Veewee class Error < StandardError attr_reader :original def initialize(msg, original = $!) super(msg) @original = original end end class DefinitionError < Error end class DefinitionNotExist < DefinitionError end class TemplateError < Error end class SshError < Error end class WinrmError < Error end end #Usage (from the exceptional ruby book) #begin # begin # raise "Error A" # rescue => error # raise MyError, "Error B" # end #rescue => error # env.ui.info "Current failure: #{error.inspect}" # env.ui.info "Original failure: #{error.original.inspect}" #end ======================= File: lib/fission.old/command/delete.rb ======================= <filename>lib/fission.old/command/delete.rb module Fission class Command class Delete < Command def initialize(args=[]) super @options.force = false end def execute option_parser.parse! @args if @args.count < 1 Fission.ui.output self.class.help Fission.ui.output "" Fission.ui.output_and_exit "Incorrect arguments for delete command", 1 end target_vm_name = @args.first target_vm=Fission::VM.new(target_vm_name) unless target_vm.exists? Fission.ui.output_and_exit "Vm #{target_vm_name} does not exist at (#{target_vm.path})", 1 end if target_vm.running? Fission.ui.output 'VM is currently running' if @options.force Fission.ui.output 'Going to stop it' Fission::Command::Stop.new([target_vm_name]).execute else Fission.ui.output_and_exit "Either stop/suspend the VM or use '--force' and try again.", 1 end end if Fission::Fusion.running? Fission.ui.output 'It looks like the Fusion GUI is currently running' if @options.force Fission.ui.output 'The Fusion metadata for the VM may not be removed completely' else Fission.ui.output "Either exit the Fusion GUI or use '--force' and try again" Fission.ui.output_and_exit "NOTE: Forcing a VM deletion with the Fusion GUI running may not clean up all of the VM metadata", 1 end end delete_task = Fission::VM.delete target_vm_name if delete_task.successful? Fission.ui.output '' Fission.ui.output "Deletion complete!" else Fission.ui.output_and_exit "There was an error deleting the VM. The error was:\n#{delete_task.output}", delete_task.code end end def option_parser optparse = OptionParser.new do |opts| opts.banner = "\ndelete usage: fission delete target_vm [--force]" opts.on '--force', "Stop the VM if it's running and then delete it" do @options.force = true end end optparse end end end end ======================= File: lib/veewee/provider/parallels/box/create.rb ======================= <filename>lib/veewee/provider/parallels/box/create.rb module Veewee module Provider module Parallels module BoxCommand # When we create a new box # We assume the box is not running def create(options) create_vm create_disk #self.create_floppy("virtualfloppy.img") end def create_disk end def parallels_os_type(type_id) env.logger.info "Translating #{type_id} into parallels type" parallelstype=env.ostypes[type_id][:parallels] env.logger.info "Found Parallels type #{parallelstype}" return parallelstype end def create_vm parallels_definition=definition.dup distribution=parallels_os_type(definition.os_type_id) # Create the vm command="prlctl create '#{self.name}' --distribution '#{distribution}'" shell_exec("#{command}") command="prlctl set '#{self.name}' --cpus #{definition.cpu_count} --memsize #{definition.memory_size}" shell_exec("#{command}") #NOTE: order is important: as this determines the boot order sequence # # Remove the network to disable pxe boot command="prlctl set '#{self.name}' --device-del net0" shell_exec("#{command}") # Remove default cdrom command ="prlctl set '#{self.name}' --device-del cdrom0" shell_exec("#{command}") # # Attach cdrom full_iso_file=File.join(env.config.veewee.iso_dir,definition.iso_file) ui.info "Mounting cdrom: #{full_iso_file}" command ="prlctl set '#{self.name}' --device-add cdrom --enable --image '#{full_iso_file}'" shell_exec("#{command}") #Enable the network again command="prlctl set '#{self.name}' --device-add net --enable --type shared" shell_exec("#{command}") end end end end end ======================= File: lib/veewee/provider/virtualbox/box/validate_vagrant.rb ======================= module Veewee module Provider module Virtualbox module BoxCommand def validate_vagrant(options = {}) validate_tags( options['tags'],options) end end #Module end #Module end #Module end #Module ======================= File: templates/windows-7-professional-amd64/definition.rb ======================= # -*- coding: utf-8 -*- #video memory size should be at least 32meg for windows 7 to do full screen on my desktop # I'm not sure how to set that with veewee::session yet Veewee::Session.declare({ :os_type_id => 'Windows7_64', :iso_file => "Windows 7 7600 AIO.ISO", :iso_src => "", # Manual download :iso_md5 => "", :iso_download_timeout => "1000", :cpu_count => '1', :memory_size=> '512', :disk_size => '20280', :disk_format => 'VDI', :hostiocache => 'off', :floppy_files => [ "Autounattend.xml", "install-winrm.bat", "oracle-cert.cer", "install-cygwin-sshd.bat" ], :boot_wait => "720", #12 minutes.. should be long enough # this is waiting for the screene where we could put in our product key # this is the command sequence to bybass it and to not try to register once online :boot_cmd_sequence => [ '<Tab><Spacebar><Tab><Tab><Tab><Spacebar>' ], :ssh_login_timeout => "10000", # Actively attempt to winrm (no ssh on base windows) in for 10000 seconds :ssh_user => "vagrant", :ssh_password => "<PASSWORD>", :ssh_key => "", :ssh_host_port => "59957", :ssh_guest_port => "22", # And run postinstall.sh for up to 10000 seconds :postinstall_timeout => "10000", :postinstall_files => ["postinstall.sh"], # No sudo on windows :sudo_cmd => "sh '%f'", # Shutdown is different as well :shutdown_cmd => "shutdown /p /t 60 /c \"Vagrant Shutdown\" /f /d p:4:1", }) ======================= File: lib/veewee/provider/core/box/vnc.rb ======================= <gh_stars>1000+ # Include the gem library require 'net/vnc' # Monkey patch the vnc require 'net/vnc/vnc.rb' module Veewee module Provider module Core module BoxCommand def vnc_type(sequence,host,display=20) counter=0 env.logger.info "Opening VNC #{host} on display #{display}" Net::VNC.open("#{host}:#{display}",{:wait => 0.001}) do |vnc| sequence.each { |s| counter=counter+1 ui.info "Typing:[#{counter}]: "+s keycodes=string_to_vnccode(s) keycodes.each do |keycode| if keycode==:wait sleep 1 else send_vnc_keycode(vnc,keycode) end end } ui.info "Done typing." ui.info "" end end def send_vnc_keycode(vnc,keycode) if keycode.is_a?(Symbol) vnc.key_press keycode sleep 1 else vnc.type_string keycode,{:wait => 0.1} end end def string_to_vnccode(thestring) # https://github.com/aquasync/ruby-vnc/blob/master/data/keys.yaml special=Hash.new # Specific veewee special['<Wait>'] = :wait # VNC Codes special['<Enter>'] = :return special['<Return>'] = :return special['<Esc>'] = :escape # These still need some work! special['<Backspace>'] = :backspace special['<Spacebar>'] ='' special['<Tab>'] = :tab # Hmm, what would the equivalent be here special['<KillX>'] = '1d 38 0e'; special['<Up>'] = :up special['<Down>'] = :down special['<PageUp>'] = :page_up special['<PageDown>'] = :page_down special['<End>'] = :end special['<Insert>'] = :insert special['<Delete>'] = :delete special['<Left>'] = :left special['<Right>'] = :right special['<Home>'] = :home special['<F1>'] = :f1 special['<F2>'] = :f2 special['<F3>'] = :f3 special['<F4>'] = :f4 special['<F5>'] = :f5 special['<F6>'] = :f6 special['<F7>'] = :f7 special['<F8>'] = :f8 special['<F9>'] = :f9 special['<F10>'] = :f10 keycodes=Array.new thestring.gsub!(/ /,"<Spacebar>") until thestring.length == 0 nospecial=true; special.keys.each { |key| if thestring.start_with?(key) #take thestring #check if it starts with a special key + pop special string keycodes<<special[key]; thestring=thestring.slice(key.length,thestring.length-key.length) nospecial=false; break; end } if nospecial code = thestring.slice(0,1) keycodes << code #pop one thestring=thestring.slice(1,thestring.length-1) end end return keycodes end end #Module end #Module end #Module end #Module ======================= File: lib/veewee.rb ======================= require 'json' require 'i18n' require 'yaml' require 'pathname' module Veewee # The source root is the path to the root directory of # the Veewee gem. def self.source_root @source_root ||= Pathname.new(File.expand_path('../../', __FILE__)) end end # # Default I18n to load the en locale I18n.load_path << File.expand_path("lib/veewee/templates/locales/en.yml", Veewee.source_root) # Load the things which must be loaded before anything else require'veewee/error' require'veewee/cli' require'veewee/ui' require'veewee/command' require'veewee/environment' require'veewee/version' ======================= File: lib/veewee/provider/virtualbox/box/destroy.rb ======================= <filename>lib/veewee/provider/virtualbox/box/destroy.rb module Veewee module Provider module Virtualbox module BoxCommand def destroy(option={}) unless self.exists? raise Veewee::Error, "Error:: You tried to destroy a non-existing box '#{name}'" end # If it has a save state,remove that first if self.running? # Poweroff self.poweroff # Wait for it to happen sleep 2 end command="#{@vboxcmd} unregistervm \"#{name}\" --delete" ui.info command ui.info "Deleting vm #{name}" #Exec and system stop the execution here shell_exec("#{command}",{:mute => true}) sleep 1 #if the disk was not attached when the machine was destroyed we also need to delete the disk pattern= File::SEPARATOR+name+"." #+definition.disk_format.downcase found=false command="#{@vboxcmd} list hdds -l" hdds=shell_exec("#{command}",{:mute => true}).stdout.split(/\n\n/) hdds.each do |hdd_text| location=hdd_text.split(/\n/).grep(/^Location/).first.split(':')[1].strip if location.match(/#{pattern}/) if File.exists?(location) command="#{@vboxcmd} closemedium disk \"#{location}\" --delete" else command="#{@vboxcmd} closemedium disk \"#{location}\"" end ui.info "Deleting disk #{location}" ui.info "#{command}" shell_exec("#{command}",{:mute => true}) if File.exists?(location) ui.info "We tried to delete the disk file via virtualbox '#{location} but failed" ui.info "Removing it manually" FileUtils.rm(location) end break end end end end #Module end #Module end #Module end #Module ======================= File: lib/fission.old/leasesfile.rb ======================= require 'date' class Lease attr_accessor :name,:mac,:start,:end,:ip def initialize(name) @name=name @ip=name end def expired? @end < DateTime.now end end class LeasesFile attr_reader :leases def initialize(filename) @filename=filename @leases=Array.new load end def load @leases=Array.new File.open(@filename,"r") do |leasefile| lease=nil while (line = leasefile.gets) line=line.lstrip.gsub(';','') case line when /^lease/ @leases << lease unless lease.nil? name=line.split(' ')[1] lease=Lease.new(name) when /^hardware/ lease.mac=line.split(" ")[2] when /^starts/ lease.start=DateTime.parse(line.split(" ")[2..3].join(" ")) when /^ends/ lease.end=DateTime.parse(line.split(" ")[2..3].join(" ")) end end @leases << lease unless lease.nil? end return @leases end def all_leases return @leases end def current_leases hash_list=Hash.new @leases.each do |lease| hash_list[lease.name]=lease end collapsed_list=Array.new hash_list.each do |key,value| collapsed_list << value end return collapsed_list end def find_lease_by_mac(mac) matches=current_leases.select{|l| l.mac==mac} return nil if matches.nil? return matches[0] end end ======================= File: lib/veewee/provider/core/box/winrm.rb ======================= require'veewee/provider/core/helper/winrm' module Veewee module Provider module Core module BoxCommand def winrm(command=nil,options={}) raise Veewee::Error,"Box is not running" unless self.running? winrm_options={:user => definition.winrm_user,:password => <PASSWORD>, :port => definition.winrm_host_port, :exitcode => '*'} if (command.nil?) env.ui.info "This is a simple interactive shell" env.ui.info "To exit interactive mode, use 'quit!'" while 1 command = ui.ask("veewee>") case command.strip when 'quit!' env.ui.info 'Bye!' break else winrm_execute(self.ip_address,command,winrm_options.merge(options)) end end else winrm_execute(self.ip_address,command,winrm_options.merge(options)) end end end # Module end # Module end # Module end # Module ======================= File: templates/nixos-minimal-0.2-i686/definition.rb ======================= <gh_stars>1000+ iso = { :url => 'http://nixos.org/releases/nixos/nixos-0.2pre4476_a5e4432-b076ab9/nixos-minimal-0.2pre4476_a5e4432-b076ab9-i686-linux.iso', :md5 => 'f035bb375f0fbcbbc4e33a12131e91d4', } session = { :boot_cmd_sequence => [ '<Enter>', '<Wait>'*15, 'root', '<Enter>', 'stop sshd', '<Enter>', # Make sure we don't accept connections until reboot 'fdisk /dev/sda', '<Enter>', 'n', '<Enter>'*5, 'a', '<Enter>', '1', '<Enter>', 'w', '<Enter>', 'mkfs.ext4 -j -L nixos /dev/sda1', '<Enter>', 'mount LABEL=nixos /mnt', '<Enter>', 'nixos-option --install', '<Enter>', 'curl http://%IP%:%PORT%/configuration.nix > /mnt/etc/nixos/configuration.nix &&', '<Enter>', 'nixos-install &&', '<Enter>', 'reboot', '<Enter>', ], :boot_wait => '5', :cpu_count => '1', :disk_format => 'VDI', :disk_size => '20400', :hostiocache => 'off', :iso_download_timeout => '1000', :iso_file => File.basename(iso[:url]), :iso_md5 => iso[:md5], :iso_src => iso[:url], :kickstart_file => 'configuration.nix', :kickstart_port => '7122', :kickstart_timeout => '10000', :memory_size => '256', :os_type_id => 'Linux26', :postinstall_files => [ 'postinstall.sh' ], :postinstall_timeout => '10000', :shutdown_cmd =>'shutdown -h now', :ssh_guest_port => '22', :ssh_host_port => '7222', :ssh_key => '', :ssh_login_timeout => '10000', :ssh_password => '<PASSWORD>', :ssh_user => 'vagrant', :sudo_cmd => "sudo '%f'" } Veewee::Definition.declare session ======================= File: templates/windows-2008R2-amd64/definition.rb ======================= Veewee::Definition.declare({ :cpu_count => '1', :memory_size=> '384', :disk_size => '10140', :disk_format => 'VDI', :hostiocache => 'off', :os_type_id => 'Windows2008_64', :iso_file => "7601.17514.101119-1850_x64fre_server_eval_en-us-GRMSXEVAL_EN_DVD.iso", :iso_src => "", :iso_md5 => "", :floppy_files => ["Autounattend.xml","cygwin-setup.exe","install-cygwin-sshd.bat","install-winrm.bat","oracle-cert.cer"], :iso_download_timeout => "1000", :boot_wait => "10", :boot_cmd_sequence => [ ], :ssh_login_timeout => "10000", :ssh_user => "vagrant", :ssh_password => "<PASSWORD>", :ssh_key => "", :ssh_host_port => "7222", :ssh_guest_port => "22", :sudo_cmd => "sh '%f'", :shutdown_cmd => "shutdown /s /t 0 /d P:4:1 /c \"Vagrant Shutdown\"", :postinstall_files => ["postinstall.sh"], :postinstall_timeout => "10000" }) ======================= File: lib/veewee/provider/parallels/box/validate_parallels.rb ======================= module Veewee module Provider module Parallels module BoxCommand def validate_parallels(options) validate_tags([ 'parallels','puppet','chef'],options) end end #Module end #Module end #Module end #Module ======================= File: lib/veewee/provider/core/box/copy.rb ======================= <filename>lib/veewee/provider/core/box/copy.rb<gh_stars>1000+ module Veewee module Provider module Core module BoxCommand def copy_to_box(localfile,remotefile,options={}) raise Veewee::Error,"Box is not running" unless self.running? if definition.winrm_user && definition.winrm_password # prefer winrm then self.wincp(localfile,remotefile,options) elsif definition.os_type_id =~ /^Windows/ then raise "Trying to transfer #{localfile} to windows machine without 'winrm_user' and 'winrm_password' set in definition." else self.scp(localfile,remotefile,options) end end end # Module end # Module end # Module end # Module ======================= File: lib/veewee/provider/vmfusion/box/validate_vmfusion.rb ======================= <filename>lib/veewee/provider/vmfusion/box/validate_vmfusion.rb module Veewee module Provider module Vmfusion module BoxCommand def validate_vmfusion(options) validate_tags( options['tags'],options) end end #Module end #Module end #Module end #Module ======================= File: lib/veewee/config/veewee.rb ======================= <filename>lib/veewee/config/veewee.rb module Veewee class Config class Veewee attr_reader :env def initialize(config) @env=config.env env.logger.info("Initializing veewee config object") end def method_missing(m, *args, &block) @env.send(m, *args) end end #Class end #Module end #Module ======================= File: lib/veewee/command/parallels.rb ======================= module Veewee module Command class Parallels < Veewee::Command::GroupBase register :command => "parallels", :description => "Subcommand for Parallels", :provider => "parallels" desc "build [BOX_NAME]", "Build box" # TODO move common build options into array method_option :force,:type => :boolean, :default => false, :aliases => "-f", :desc => "force the build" method_option :auto,:type => :boolean, :default => false, :aliases => "-a", :desc => "auto answers" method_option :checksum, :type => :boolean, :default => false, :desc => "verify checksum" method_option :postinstall_include, :type => :array, :default => [], :aliases => "-i", :desc => "ruby regexp of postinstall filenames to additionally include" method_option :postinstall_exclude, :type => :array, :default => [], :aliases => "-e", :desc => "ruby regexp of postinstall filenames to exclude" method_option :skip_to_postinstall, :aliases => ['--skip-to-postinstall'], :type => :boolean, :default => false, :desc => "Skip to postinstall." def build(box_name) env.get_box(box_name).build(options) end desc "export [BOX_NAME]", "Exports the basebox to the vagrant-parallels format" method_option :debug,:type => :boolean, :default => false, :aliases => "-d", :desc => "enable debugging" method_option :force,:type => :boolean, :default => false, :aliases => "-f", :desc => "overwrite existing file" method_option :vagrantfile,:type => :string, :default => "", :desc => "specify Vagrantfile" def export(box_name) env.get_box(box_name).export_vagrant(options) end desc "validate [BOX_NAME]", "Validates a box against parallels compliancy rules" method_option :tags,:type => :array, :default => %w{parallels puppet chef}, :aliases => "-t", :desc => "tags to validate" def validate(box_name) env.get_box(box_name).validate_parallels(options) end end end end ======================= File: lib/fission.old/command.rb ======================= module Fission class Command attr_reader :options, :args def initialize(args=[]) @options = OpenStruct.new @args = args end def self.help self.new.option_parser.to_s end end end ======================= File: lib/veewee/provider/virtualbox/box/helper/winrm_options.rb ======================= <filename>lib/veewee/provider/virtualbox/box/helper/winrm_options.rb module Veewee module Provider module Virtualbox module BoxCommand def winrm_options build_winrm_options.tap do |options| port=definition.winrm_host_port if self.exists? forward=self.forwarding("guestwinrm") unless forward.nil? port=forward[:host_port] end end options[:port] = port end end end end end end ======================= File: lib/fission.old/command/snapshot_create.rb ======================= <reponame>ibizaman/veewee module Fission class Command class SnapshotCreate < Command def initialize(args=[]) super end def execute unless @args.count == 2 Fission.ui.output self.class.help Fission.ui.output "" Fission.ui.output_and_exit "Incorrect arguments for snapshot create command", 1 end vm_name, snap_name = @args.take 2 vm = Fission::VM.new vm_name unless vm.exists? Fission.ui.output_and_exit "Unable to find the VM #{vm_name} (#{Fission::VM.path(vm_name)})", 1 end unless vm.running? Fission.ui.output "VM '#{vm_name}' is not running" Fission.ui.output_and_exit 'A snapshot cannot be created unless the VM is running', 1 end if vm.snapshots.include? snap_name Fission.ui.output_and_exit "VM '#{vm_name}' already has a snapshot named '#{snap_name}'", 1 end Fission.ui.output "Creating snapshot" task = vm.create_snapshot(snap_name) if task.successful? Fission.ui.output "Snapshot '#{snap_name}' created" else Fission.ui.output_and_exit "There was an error creating the snapshot. The error was:\n#{task.output}", task.code end end def option_parser optparse = OptionParser.new do |opts| opts.banner = "\nsnapshot create: fission snapshot create my_vm snapshot_1" end optparse end end end end ======================= File: lib/veewee/provider/vmfusion/box/up.rb ======================= <filename>lib/veewee/provider/vmfusion/box/up.rb module Veewee module Provider module Vmfusion module BoxCommand def up(options={}) gui_enabled=options[:nogui]==true? false : true if gui_enabled raw.start unless raw.nil? else raw.start({:headless => true}) unless raw.nil? end end end end end end ======================= File: lib/veewee/provider/core/helper/web.rb ======================= <reponame>ibizaman/veewee module Veewee module Provider module Core module Helper require 'webrick' include WEBrick module Web def wait_for_http_request(filename, urlname, options) # thread with timeout thread = allow_for_http_request(filename, urlname, options) timeout = options[:timeout] || 60 thread.join(timeout) or begin thread.kill raise "File #{filename.inspect} was not requested as #{urlname.inspect} in #{timeout} seconds, are you using firewall blocking connections to port: #{options[:port]}?" end end def allow_for_http_request(filename, urlname, options) # start in new thread thread = Thread.new do server_for_http_request(filename, urlname, options) end thread.abort_on_exception = true trap("INT") { thread.kill; exit } thread end private def server_for_http_request(filename, urlname, options) initialize_server(options[:port]) mount_file(filename, urlname) @server.start ensure server_shutdown end def initialize_server(port) # Calculate the OS equivalent of /dev/null, on windows this is NUL: # http://www.ruby-forum.com/topic/115472 fn = test(?e, '/dev/null')? '/dev/null' : 'NUL:' webrick_logger = WEBrick::Log.new(fn, WEBrick::Log::INFO) @server = ::WEBrick::HTTPServer.new( :Port => port, :Logger => webrick_logger, :AccessLog => webrick_logger, ) end def mount_file(filename, urlname) urlname = urlname[0..-5] if File.extname(urlname) == ".erb" @server.mount_proc(urlname) do |request, response| ui.info "Serving content for #{urlname}" response['Content-Type']='text/plain' response.status = 200 response.body = read_content(filename) server_shutdown end end def read_content(filename) ui.info "Reading content #{filename}" content = File.open(filename, "r").read if File.extname(filename) == ".erb" ui.info "Evaluating template #{filename}" content = ::ERB.new(content).result(binding) end content end def server_shutdown if @server ui.info "Stopping webserver" yield @server if block_given? @server.shutdown @server = nil end end end #Class end #Module end #Module end #Module end #Module ======================= File: lib/veewee/provider/kvm/box/validate_kvm.rb ======================= module Veewee module Provider module Kvm module BoxCommand def validate_kvm(options) validate_tags( [ 'kvm', 'puppet', 'chef'],options) end end #Module end #Module end #Module end #Module ======================= File: lib/veewee/provider/vmfusion/box/helper/ip.rb ======================= <reponame>ibizaman/veewee<filename>lib/veewee/provider/vmfusion/box/helper/ip.rb module Veewee module Provider module Vmfusion module BoxCommand # Retrieve the first mac address for a vm # This will only retrieve the first auto generate mac address def mac_address raise ::Fission::Error,"VM #{name} does not exist" unless self.exists? line=File.new(vmx_file_path).grep(/^ethernet0.generatedAddress =/) if line.nil? #Fission.ui.output "Hmm, the vmx file #{vmx_path} does not contain a generated mac address " return nil end address=line.first.split("=")[1].strip.split(/\"/)[1] return address end # Retrieve the ip address for a vm. # This will only look for dynamically assigned ip address via vmware dhcp def ip_address # Does not work for now as the vmx path is not escape correctly by fission 0.4.0 #return raw.network_info.data.first['ip_address'] raise ::Fission::Error,"VM #{name} does not exist" unless self.exists? # Use alternate method to retrieve the IP address using vmrun readVariable ip_address = shell_exec("#{vmrun_cmd.shellescape} readVariable \"#{vmx_file_path}\" guestVar ip", { :mute => true}).stdout.strip return ip_address unless ip_address.empty? || ip_address == 'unknown' unless mac_address.nil? lease = Fission::Lease.find_by_mac_address(mac_address).data return lease.ip_address unless lease.nil? return nil else # No mac address was found for this machine so we can't calculate the ip-address return nil end end # http://www.thirdbit.net/articles/2008/03/04/dhcp-on-vmware-fusion/ def host_ip_as_seen_by_guest # if File.exists?("/Library/Application Support/VMware Fusion/vmnet8/nat.conf") # file = "/Library/Application Support/VMware Fusion/vmnet8/nat.conf" # end # if File.exists?("/Library/Preferences/VMware Fusion/vmnet8/nat.conf") # file = "/Library/Preferences/VMware Fusion/vmnet8/nat.conf" # end # File.open(file).readlines.grep(/ip = /).first.split(" ")[2] # The above is not always correct # There seems also an entry for vmnet8 in the dhcpd.conf # /Library/Preferences/VMware Fusion/vmnet8/dhcpd.conf # host vmnet8 { # fixed-address # The above is fancy but doesn't always agree, we need to do is ifconfig vmnet8 # Ifconfig never lies shell_results = shell_exec("ifconfig vmnet8", { :mute => true}) shell_results.stdout.split(/\n/).grep(/inet /)[0].strip.split(/ /)[1] end end end end end ======================= File: lib/fission.old/ui.rb ======================= <reponame>ibizaman/veewee<gh_stars>1000+ module Fission class UI attr_reader :stdout def initialize(stdout=$stdout) @stdout = stdout end def output(s) @stdout.puts s end def output_printf(string, key, value) @stdout.send :printf, string, key, value end def output_and_exit(s, exit_code) output s exit exit_code end end end ======================= File: lib/veewee/provider/parallels/box/helper/ip.rb ======================= <filename>lib/veewee/provider/parallels/box/helper/ip.rb<gh_stars>1000+ module Veewee module Provider module Parallels module BoxCommand # Get the IP address of the box def ip_address mac=mac_address command="grep #{mac} /Library/Preferences/Parallels/parallels_dhcp_leases|cut -d '=' -f 1" ip=shell_exec("#{command}").stdout.strip.downcase return ip end def mac_address command="prlctl list -i '#{self.name}'|grep 'net0 (' | cut -d '=' -f 3 | cut -d'' -f 1 " mac=shell_exec("#{command}").stdout.strip.downcase return mac end end end end end ======================= File: lib/veewee/provider/core/provider/transaction.rb ======================= <gh_stars>1000+ ##Note: this is currently not used anymore, it seems no one is using it module Veewee class Transaction def transaction(name,params, &block) end def transaction2(name,options= { :checksum => "nochecksum"}, &block) if snapshot_exists(@vmname,name+"-"+options[:checksum]) load_snapshot_vmachine(@vmname,name+"-"+options[:checksum]) else if snapshot_version_exists(@vmname,name) rollback_snapshot(@vmname,name) #rollback to snapshot prior to this one end yield create_snapshot_vmachine(@vmname,name+"-"+options[:checksum]) end #end end end end ======================= File: lib/veewee/provider/virtualbox/box/poweroff.rb ======================= <reponame>ibizaman/veewee<filename>lib/veewee/provider/virtualbox/box/poweroff.rb module Veewee module Provider module Virtualbox module BoxCommand def poweroff(options={}) # If the vm is not powered off, perform a shutdown if (self.exists? && self.running?) ui.info "Shutting down vm #{name}" #We force it here, maybe vm.shutdown is cleaner command="#{@vboxcmd} controlvm \"#{name}\" poweroff" shell_exec("#{command}") end end end end end end ======================= File: lib/fission.old/command/stop.rb ======================= module Fission class Command class Stop < Command def initialize(args=[]) super end def execute unless @args.count == 1 Fission.ui.output self.class.help Fission.ui.output "" Fission.ui.output_and_exit "Incorrect arguments for stop command", 1 end vm_name = @args.first vm = Fission::VM.new vm_name unless vm.exists? Fission.ui.output_and_exit "VM #{vm_name} does not exist at (#{vm.path})", 1 end unless vm.running? Fission.ui.output '' F
1,521
) .def("changeLevel", &CyUnit::changeLevel) .def("getCargo", &CyUnit::getCargo, "int ()") .def("getFortifyTurns", &CyUnit::getFortifyTurns, "int ()") .def("getBlitzCount", &CyUnit::getBlitzCount, "int ()") .def("isBlitz", &CyUnit::isBlitz, "bool ()") .def("getAmphibCount", &CyUnit::getAmphibCount, "int ()") .def("isAmphib", &CyUnit::isAmphib, "bool ()") .def("getRiverCount", &CyUnit::getRiverCount, "int ()") .def("isRiver", &CyUnit::isRiver, "bool ()") .def("isEnemyRoute", &CyUnit::isEnemyRoute, "bool ()") .def("isAlwaysHeal", &CyUnit::isAlwaysHeal, "bool ()") .def("isHillsDoubleMove", &CyUnit::isHillsDoubleMove, "bool ()") .def("getExtraVisibilityRange", &CyUnit::getExtraVisibilityRange, "int ()") .def("getExtraMoves", &CyUnit::getExtraMoves, "int ()") .def("getExtraMoveDiscount", &CyUnit::getExtraMoveDiscount, "int ()") .def("getExtraFirstStrikes", &CyUnit::getExtraFirstStrikes, "int ()") .def("getExtraChanceFirstStrikes", &CyUnit::getExtraChanceFirstStrikes, "int ()") .def("getExtraWithdrawal", &CyUnit::getExtraWithdrawal, "int ()") .def("getExtraCollateralDamage", &CyUnit::getExtraCollateralDamage, "int ()") .def("getExtraEnemyHeal", &CyUnit::getExtraEnemyHeal, "int ()") .def("getExtraNeutralHeal", &CyUnit::getExtraNeutralHeal, "int ()") .def("getExtraFriendlyHeal", &CyUnit::getExtraFriendlyHeal, "int ()") .def("getSameTileHeal", &CyUnit::getSameTileHeal, "int ()") .def("getAdjacentTileHeal", &CyUnit::getAdjacentTileHeal, "int ()") .def("getExtraCombatPercent", &CyUnit::getExtraCombatPercent, "int ()") .def("getExtraCityAttackPercent", &CyUnit::getExtraCityAttackPercent, "int ()") .def("getExtraCityDefensePercent", &CyUnit::getExtraCityDefensePercent, "int ()") .def("getExtraHillsDefensePercent", &CyUnit::getExtraHillsDefensePercent, "int ()") .def("isMadeAttack", &CyUnit::isMadeAttack, "bool ()") .def("setMadeAttack", &CyUnit::setMadeAttack, "void (int iNewValue)") .def("isMadeInterception", &CyUnit::isMadeInterception, "bool ()") .def("setMadeInterception", &CyUnit::setMadeInterception, "void (int iNewValue)") .def("isPromotionReady", &CyUnit::isPromotionReady, "bool ()") .def("setPromotionReady", &CyUnit::setPromotionReady, "void (int iNewValue)") .def("getOwner", &CyUnit::getOwner, "int ()") .def("getTeam", &CyUnit::getTeam, "int ()") .def("getUnitType", &CyUnit::getUnitType, "int ()") .def("getUnitClassType", &CyUnit::getUnitClassType, "int ()") .def("getTransportUnit", &CyUnit::getTransportUnit, python::return_value_policy<python::manage_new_object>(), "CyUnit* ()") .def("isCargo", &CyUnit::isCargo, "bool ()") .def("getExtraDomainModifier", &CyUnit::getExtraDomainModifier, "int ()") .def("getName", &CyUnit::getName, "str () - Returns the name of a unit along with its type description in parens if using a custom name") .def("getNameForm", &CyUnit::getNameForm, "str (int iForm)") .def("getNameKey", &CyUnit::getNameKey, "str ()") .def("getNameNoDesc", &CyUnit::getNameNoDesc, "str () - Returns the name of a unit without any description afterwards") .def("setName", &CyUnit::setName, "void (str)") .def("getScriptData", &CyUnit::getScriptData, "str ()") .def("setScriptData", &CyUnit::setScriptData, "void (str)") .def("isTerrainDoubleMove", &CyUnit::isTerrainDoubleMove, "bool (TerrainType)") .def("isFeatureDoubleMove", &CyUnit::isFeatureDoubleMove, "bool (FeatureType)") .def("getExtraTerrainDefensePercent", &CyUnit::getExtraTerrainDefensePercent, "int ()") .def("getExtraFeatureDefensePercent", &CyUnit::getExtraFeatureDefensePercent, "int ()") .def("getExtraUnitCombatModifier", &CyUnit::getExtraUnitCombatModifier, "int ()") .def("canAcquirePromotion", &CyUnit::canAcquirePromotion, "bool (int /*PromotionTypes*/ ePromotion)") .def("canAcquirePromotionAny", &CyUnit::canAcquirePromotionAny, "bool ()") .def("isHasPromotion", &CyUnit::isHasPromotion, "bool (int /*PromotionTypes*/ ePromotion)") .def("setHasPromotion", &CyUnit::setHasPromotion, "void (int (PromotionTypes) eIndex, bool bNewValue)") .def("IsSelected", &CyUnit::IsSelected) .def("getUnitAIType", &CyUnit::getUnitAIType, "int UnitAIType () - returns the int value of the UnitAIType") .def("setUnitAIType", &CyUnit::setUnitAIType, "void UnitAIType (int iUnitAIType) - sets the unit's UnitAIType") // Python Helper Functions .def("centerCamera", &CyUnit::centerCamera, "void () - Centers the Camera on the unit") ; } ======================= File: BtS/CvGameCoreDLL/CyCityInterface1.cpp ======================= #include "CvGameCoreDLL.h" #include "CyCity.h" #include "CyPlot.h" #include "CyArea.h" #include "CvInfos.h" //# include <boost/python/manage_new_object.hpp> //# include <boost/python/return_value_policy.hpp> // // published python interface for CyCity // void CyCityPythonInterface1(python::class_<CyCity>& x) { OutputDebugString("Python Extension Module - CyCityPythonInterface1\n"); x .def("isNone", &CyCity::isNone, "void () - is the instance valid?") .def("kill", &CyCity::kill, "void () - kill the city") .def("doTask", &CyCity::doTask, "void (int eTaskTypes, int iData1, int iData2, bool bOption) - Enacts the TaskType passed") .def("chooseProduction", &CyCity::chooseProduction, "void (int /*UnitTypes*/ eTrainUnit, int /*BuildingTypes*/ eConstructBuilding, int /*ProjectTypes*/ eCreateProject, bool bFinish, bool bFront) - Chooses production for a city") .def("createGreatPeople", &CyCity::createGreatPeople, "void (int /*UnitTypes*/ eGreatPersonUnit, bool bIncrementThreshold) - Creates a great person in this city and whether it should increment the threshold to the next level") .def("getCityPlotIndex", &CyCity::getCityPlotIndex, "int (CyPlot* pPlot)") .def("getCityIndexPlot", &CyCity::getCityIndexPlot, python::return_value_policy<python::manage_new_object>(), "CyPlot* (int iIndex)") .def("canWork", &CyCity::canWork, "bool (CyPlot*) - can the city work the plot?") .def("clearWorkingOverride", &CyCity::clearWorkingOverride, "void (int iIndex)") .def("countNumImprovedPlots", &CyCity::countNumImprovedPlots, "int ()") .def("countNumWaterPlots", &CyCity::countNumWaterPlots, "int ()") .def("countNumRiverPlots", &CyCity::countNumRiverPlots, "int ()") .def("findPopulationRank", &CyCity::findPopulationRank, "int ()") .def("findBaseYieldRateRank", &CyCity::findBaseYieldRateRank, "int (int /*YieldTypes*/ eYield)") .def("findYieldRateRank", &CyCity::findYieldRateRank, "int (int /*YieldTypes*/ eYield)") .def("findCommerceRateRank", &CyCity::findCommerceRateRank, "int (int /*CommerceTypes*/ eCommerce)") .def("allUpgradesAvailable", &CyCity::allUpgradesAvailable, "int UnitTypes (int eUnit, int iUpgradeCount)") .def("isWorldWondersMaxed", &CyCity::isWorldWondersMaxed, "bool ()") .def("isTeamWondersMaxed", &CyCity::isTeamWondersMaxed, "bool ()") .def("isNationalWondersMaxed", &CyCity::isNationalWondersMaxed, "bool ()") .def("isBuildingsMaxed", &CyCity::isBuildingsMaxed, "bool ()") .def("canTrain", &CyCity::canTrain, "bool (int eUnit, bool bContinue, bool bTestVisible)") .def("canConstruct", &CyCity::canConstruct, "bool (int eBuilding, bool bContinue, bool bTestVisible, bool bIgnoreCost)") .def("canCreate", &CyCity::canCreate, "bool (int eProject, bool bContinue, bool bTestVisible)") .def("canMaintain", &CyCity::canMaintain, "bool (int eProcess, bool bContinue)") .def("canJoin", &CyCity::canJoin, "bool () - can a Great Person join the city") .def("getFoodTurnsLeft", &CyCity::getFoodTurnsLeft, "int () - how many food turns remain?") .def("isProduction", &CyCity::isProduction, "bool () - is city producing?") .def("isProductionLimited", &CyCity::isProductionLimited, "bool ()") .def("isProductionUnit", &CyCity::isProductionUnit, "bool () - is city training a unit?") .def("isProductionBuilding", &CyCity::isProductionBuilding, "bool () - is city constructing a building?") .def("isProductionProject", &CyCity::isProductionProject, "bool ()") .def("isProductionProcess", &CyCity::isProductionProcess, "bool () - is city maintaining a process?") .def("canContinueProduction", &CyCity::canContinueProduction, "bool (OrderData order)") .def("getProductionExperience", &CyCity::getProductionExperience, "int (int /*UnitTypes*/ eUnit)") .def("addProductionExperience", &CyCity::addProductionExperience, "void (CyUnit* pUnit, bool bConscript)") .def("getProductionUnit", &CyCity::getProductionUnit, "UnitID () - ID for unit that is being trained") .def("getProductionUnitAI", &CyCity::getProductionUnitAI, "int eUnitAIType ()") .def("getProductionBuilding", &CyCity::getProductionBuilding, "BuildingID () - ID for building that is under construction") .def("getProductionProject", &CyCity::getProductionProject, "int /*ProjectTypes*/ ()") .def("getProductionProcess", &CyCity::getProductionProcess, "int /*ProcessTypes*/ ()") .def("getProductionName", &CyCity::getProductionName, "str () - description of item that the city is working on") .def("getGeneralProductionTurnsLeft", &CyCity::getGeneralProductionTurnsLeft, "int - # of production turns left for the top order node item in a city...") .def("getProductionNameKey", &CyCity::getProductionNameKey, "str () - description of item that the city is working on") .def("isFoodProduction", &CyCity::isFoodProduction, "bool () - is item under construction being created with food instead of production?") .def("getFirstUnitOrder", &CyCity::getFirstUnitOrder, "int (int /*UnitTypes*/ eUnit)") .def("getFirstBuildingOrder", &CyCity::getFirstBuildingOrder, "int (int /*BuildingTypes*/ eBuilding)") .def("getFirstProjectOrder", &CyCity::getFirstProjectOrder, "int (int /*ProjectTypes*/ eProject)") .def("isUnitFoodProduction", &CyCity::isUnitFoodProduction, "bool (UnitID) - does UnitID require food to be trained?") .def("getProduction", &CyCity::getProduction, "int () - returns the current production towards whatever is top of this city's OrderQueue") .def("getProductionNeeded", &CyCity::getProductionNeeded, "int () - # of production needed to complete construction") .def("getProductionTurnsLeft", &CyCity::getProductionTurnsLeft, "int () - # of turns remaining until item is completed") .def("getUnitProductionTurnsLeft", &CyCity::getUnitProductionTurnsLeft, "int (UnitID, int iNum) - # of turns remaining to complete UnitID") .def("getBuildingProductionTurnsLeft", &CyCity::getBuildingProductionTurnsLeft, "int (BuildingID, int iNum) - # of turns remaining to complete UnitID") .def("getProjectProductionTurnsLeft", &CyCity::getProjectProductionTurnsLeft, "int (int /*ProjectTypes*/ eProject, int iNum)") .def("setProduction", &CyCity::setProduction, "void (int iNewValue)") .def("changeProduction", &CyCity::changeProduction, "void (int iChange)") .def("getProductionModifier", &CyCity::getProductionModifier, "int () - multiplier (if any) for item being produced") .def("getCurrentProductionDifference", &CyCity::getCurrentProductionDifference, "int (bool bIgnoreFood, bool bOverflow)") .def("getUnitProductionModifier", &CyCity::getUnitProductionModifier, "int (UnitID) - production multiplier for UnitID") .def("getBuildingProductionModifier", &CyCity::getBuildingProductionModifier, "int (BuildingID) - production multiplier for BuildingID") .def("getProjectProductionModifier", &CyCity::getProductionModifier, "int (int /*ProjectTypes*/ eProject)") .def("getExtraProductionDifference", &CyCity::getExtraProductionDifference, "int (int iExtra)") .def("canHurry", &CyCity::canHurry, "bool (HurryTypes eHurry, bool bTestVisible = 0) - can player eHurry in this city?") .def("hurry", &CyCity::hurry, "void (HurryTypes eHurry) - forces the city to rush production using eHurry") .def("getConscriptUnit", &CyCity::getConscriptUnit, "UnitID () - UnitID for the best unit the city can conscript") .def("getConscriptPopulation", &CyCity::getConscriptPopulation, "int ()") .def("conscriptMinCityPopulation", &CyCity::conscriptMinCityPopulation, "int ()") .def("flatConscriptAngerLength", &CyCity::flatConscriptAngerLength, "int ()") .def("canConscript", &CyCity::canConscript, "bool () - can the city conscript units?") .def("conscript", &CyCity::conscript, "void () - conscripts a unit") .def("getBonusHealth", &CyCity::getBonusHealth, "int (BonusID) - total health bonus from BonusID") .def("getBonusHappiness", &CyCity::getBonusHappiness, "int (BonusID) - total happiness bonus from BonusID") .def("getBonusPower", &CyCity::getBonusPower, "int (int /*BonusTypes*/ eBonus, bool bDirty)") .def("getBonusYieldRateModifier", &CyCity::getBonusYieldRateModifier, "int (int /*YieldTypes*/ eIndex, int /*BonusTypes*/ eBonus)") .def("getHandicapType", &CyCity::getHandicapType, "HandicapType () - owners difficulty level") .def("getCivilizationType", &CyCity::getCivilizationType, "CivilizationID () - owners CivilizationID") .def("getPersonalityType", &CyCity::getPersonalityType, "int /*LeaderHeadTypes*/ ()") .def("getArtStyleType", &CyCity::getArtStyleType, "int /*ArtStyleTypes*/ ()") .def("getCitySizeType", &CyCity::getCitySizeType, "int /*CitySizeTypes*/ ()") .def("hasTrait", &CyCity::hasTrait, "bool (TraitID) - does owner have TraitID?") .def("isBarbarian", &CyCity::isBarbarian, "bool () - is owner a barbarian?") .def("isHuman", &CyCity::isHuman, "bool () - is owner human?") .def("isVisible", &CyCity::isVisible, "bool (int /*TeamTypes*/ eTeam, bool bDebug)") .def("isCapital", &CyCity::isCapital, "bool () - is city the owners capital?") .def("isCoastal", &CyCity::isCoastal, "bool (int) - is the city on the coast?") .def("isDisorder", &CyCity::isDisorder, "bool () - is the city in disorder?") .def("isHolyCityByType", &CyCity::isHolyCityByType, "bool (ReligionID) - is the city ReligionID's holy city?") .def("isHolyCity", &CyCity::isHolyCity, "bool () - is the city ReligionID's holy city?") .def("isHeadquartersByType", &CyCity::isHeadquartersByType, "bool (CorporationID) - is the city CorporationID's headquarters?") .def("isHeadquarters", &CyCity::isHeadquarters, "bool () - is the city CorporationID's headquarters?") .def("getOvercrowdingPercentAnger", &CyCity::getOvercrowdingPercentAnger, "int (iExtra)") .def("getNoMilitaryPercentAnger", &CyCity::getNoMilitaryPercentAnger, "int ()") .def("getCulturePercentAnger", &CyCity::getCulturePercentAnger, "int ()") .def("getReligionPercentAnger", &CyCity::getReligionPercentAnger, "int ()") .def("getWarWearinessPercentAnger", &CyCity::getWarWearinessPercentAnger, "int ()") .def("getLargestCityHappiness", &CyCity::getLargestCityHappiness, "int ()") .def("unhappyLevel", &CyCity::unhappyLevel, "int (int iExtra)") .def("happyLevel", &CyCity::happyLevel, "int ()") .def("angryPopulation", &CyCity::angryPopulation, "int (iExtra) - # of unhappy citizens") .def("totalFreeSpecialists", &CyCity::totalFreeSpecialists) .def("extraFreeSpecialists", &CyCity::extraFreeSpecialists, "int () - # of specialist that are allowed for free") .def("extraPopulation", &CyCity::extraPopulation, "int () - # of extra/available citizens") .def("extraSpecialists", &CyCity::extraSpecialists, "int () - # of extra/available specialists") .def("unhealthyPopulation", &CyCity::unhealthyPopulation, "int (bool bNoAngry), int (iExtra)") .def("totalGoodBuildingHealth", &CyCity::totalGoodBuildingHealth, "int ()") .def("totalBadBuildingHealth", &CyCity::totalBadBuildingHealth, "int ()") .def("goodHealth", &CyCity::goodHealth, "int () - total health") .def("badHealth", &CyCity::badHealth, "int (bool bNoAngry) - total unhealthiness") .def("healthRate", &CyCity::healthRate, "int (bool bNoAngry, int iExtra)") .def("foodConsumption", &CyCity::foodConsumption, "int (bool bNoAngry, int iExtra)") .def("foodDifference", &CyCity::foodDifference, "int (bool bBottom) - result of getYieldRate(Food) - foodConsumption()") .def("growthThreshold", &CyCity::growthThreshold, "int () - value needed for growth") .def("productionLeft", &CyCity::productionLeft, "int () - result of (getProductionNeeded() - getProduction()") .def("hurryCost", &CyCity::hurryCost, "int (bool bExtra)") .def("hurryGold", &CyCity::hurryGold, "int (HurryID) - total value of gold when hurrying") .def("hurryPopulation", &CyCity::hurryPopulation, "int (HurryID) - value of each pop when hurrying") .def("hurryProduction", &CyCity::hurryProduction, "int (HurryID)") .def("flatHurryAngerLength", &CyCity::flatHurryAngerLength, "int ()") .def("hurryAngerLength", &CyCity::hurryAngerLength, "int (HurryID)") .def("maxHurryPopulation", &CyCity::maxHurryPopulation, "int ()") .def("cultureDistance", &CyCity::cultureDistance, "int (iDX, iDY) - culture distance") .def("cultureStrength", &CyCity::cultureStrength, "int (ePlayer)") .def("cultureGarrison", &CyCity::cultureGarrison, "int (ePlayer)") .def("getNumBuilding", &CyCity::getNumBuilding, "int - (BuildingID) - How many BuildingID does this city have (real or free)?") .def("isHasBuilding", &CyCity::isHasBuilding, "bool (int iBuildingID) - This function actually no longer exists in C++, this is a helper function which hooks up to getNumBuilding() to help mod backwards compatibility") .def("getNumActiveBuilding", &CyCity::getNumActiveBuilding, "bool (BuildingID) - is BuildingID active in the city (present & not obsolete)?") .def("getID", &CyCity::getID, "int () - index ID # for the city - use with pPlayer.getCity(ID) to obtain city instance") .def("getX", &CyCity::getX, "int () - X coordinate for the cities plot") .def("getY", &CyCity::getY, "int () - Y coordinate for the cities plot") .def("at", &CyCity::at, "bool (iX, iY) - is the city at (iX, iY)?") .def("atPlot", &CyCity::atPlot, "bool (CyPlot) - is pPlot the cities plot?") .def("plot", &CyCity::plot, python::return_value_policy<python::manage_new_object>(), "CyPlot () - returns cities plot instance") .def("isConnectedTo", &CyCity::isConnectedTo, "bool (CyCity*) - is city connected to CyCity* via the Trade Network?") .def("isConnectedToCapital", &CyCity::isConnectedToCapital, "bool (iOwner) - connected to the capital?") .def("area", &CyCity::area, python::return_value_policy<python::manage_new_object>(), "CyArea() () - returns CyArea instance for location of city") .def("waterArea", &CyCity::waterArea, python::return_value_policy<python::manage_new_object>(), "CyArea* ()") .def("getRallyPlot", &CyCity::getRallyPlot, python::return_value_policy<python::manage_new_object>(), "CyPlot () - returns city's rally plot instance") .def("getGameTurnFounded", &CyCity::getGameTurnFounded, "int () - GameTurn the city was founded") .def("getGameTurnAcquired", &CyCity::getGameTurnAcquired, "int ()") .def("getPopulation", &CyCity::getPopulation, "int () - total city population") .def("setPopulation", &CyCity::setPopulation, "void (int iNewValue) - sets the city population to iNewValue") .def("changePopulation", &CyCity::changePopulation, "void (int iChange) - adjusts the city population by iChange") .def("getRealPopulation", &CyCity::getRealPopulation, "int () - total city population in \"real\" numbers") .def("getHighestPopulation", &CyCity::getHighestPopulation, "int () ") .def("setHighestPopulation", &CyCity::setHighestPopulation, "void (iNewValue)") .def("getWorkingPopulation", &CyCity::getWorkingPopulation, "int () - # of citizens who are working") .def("getSpecialistPopulation", &CyCity::getSpecialistPopulation, "int () - # of specialists") .def("getNumGreatPeople", &CyCity::getNumGreatPeople, "int () - # of great people who are joined to the city") .def("getBaseGreatPeopleRate", &CyCity::getBaseGreatPeopleRate, "int () - base great person rate") .def("getGreatPeopleRate", &CyCity::getGreatPeopleRate, "int () - total Great Person rate") .def("getTotalGreatPeopleRateModifier", &CyCity::getTotalGreatPeopleRateModifier, "int ()") .def("changeBaseGreatPeopleRate", &CyCity::changeBaseGreatPeopleRate) .def("getGreatPeopleProgress", &CyCity::getGreatPeopleProgress, "int () - current great person progress") .def("getGreatPeopleRateModifier", &CyCity::getGreatPeopleRateModifier, "int ()") .def("getNumWorldWonders", &CyCity::getNumWorldWonders, "int ()") .def("getNumTeamWonders", &CyCity::getNumTeamWonders, "int ()") .def("getNumNationalWonders", &CyCity::getNumNationalWonders, "int ()") .def("getNumBuildings", &CyCity::getNumBuildings, "int ()") .def("changeGreatPeopleProgress", &CyCity::changeGreatPeopleProgress, "void (int iChange) - adjusts great person progress by iChange") .def("isGovernmentCenter", &CyCity::isGovernmentCenter, "bool () - is city the government center?") .def("getMaintenance", &CyCity::getMaintenance, "int () - cities current maintenance cost") .def("getMaintenanceTimes100", &CyCity::getMaintenanceTimes100, "int () - cities current maintenance cost") .def("calculateDistanceMaintenance", &CyCity::calculateDistanceMaintenance, "int ()") .def("calculateDistanceMaintenanceTimes100", &CyCity::calculateDistanceMaintenanceTimes100, "int ()") .def("calculateNumCitiesMaintenance", &CyCity::calculateNumCitiesMaintenance, "int ()") .def("calculateNumCitiesMaintenanceTimes100", &CyCity::calculateNumCitiesMaintenanceTimes100, "int ()") .def("calculateColonyMaintenance", &CyCity::calculateColonyMaintenance, "int ()") .def("calculateColonyMaintenanceTimes100", &CyCity::calculateColonyMaintenanceTimes100, "int ()") .def("calculateCorporationMaintenance", &CyCity::calculateCorporationMaintenance, "int ()") .def("calculateCorporationMaintenanceTimes100", &CyCity::calculateCorporationMaintenanceTimes100, "int ()") .def("getMaintenanceModifier", &CyCity::getMaintenanceModifier, "int () - total value of the city maintenance modifier") .def("getWarWearinessModifier", &CyCity::getWarWearinessModifier) .def("getHurryAngerModifier", &CyCity::getHurryAngerModifier) .def("changeHealRate", &CyCity::changeHealRate, "void (int iChange) - changes the heal rate of this city to iChange") .def("getEspionageHealthCounter", &CyCity::getEspionageHealthCounter, "int ()") .def("changeEspionageHealthCounter", &CyCity::changeEspionageHealthCounter, "void (int iChange)") .def("getEspionageHappinessCounter", &CyCity::getEspionageHappinessCounter, "int ()") .def("changeEspionageHappinessCounter", &CyCity::changeEspionageHappinessCounter, "void (int iChange)") .def("getFreshWaterGoodHealth", &CyCity::getFreshWaterGoodHealth, "int ()") .def("getFreshWaterBadHealth", &CyCity::getFreshWaterBadHealth, "int ()") .def("getBuildingGoodHealth", &CyCity::getBuildingGoodHealth, "int ()") .def("getBuildingBadHealth", &CyCity::getBuildingBadHealth, "int ()") .def("getFeatureGoodHealth", &CyCity::getFeatureGoodHealth, "int () - returns the good health provided by the feature this city is built on") .def("getFeatureBadHealth", &CyCity::getFeatureBadHealth, "int () - returns the bad health provided by the feature this city is built on") .def("getBuildingHealth", &CyCity::getBuildingHealth, "int (int eBuilding)") .def("getPowerGoodHealth", &CyCity::getPowerGoodHealth, "int ()") .def("getPowerBadHealth", &CyCity::getPowerBadHealth, "int ()") .def("getBonusGoodHealth", &CyCity::getBonusGoodHealth, "int ()") .def("getBonusBadHealth", &CyCity::getBonusBadHealth, "int ()") .def("getMilitaryHappiness", &CyCity::getMilitaryHappiness, "int () - happiness created by military units stationed in the city") .def("getMilitaryHappinessUnits", &CyCity::getMilitaryHappinessUnits, "number of military units creating happiness") .def("getBuildingGoodHappiness", &CyCity::getBuildingGoodHappiness, "int ()") .def("getBuildingBadHappiness", &CyCity::getBuildingBadHappiness, "int ()") .def("getBuildingHappiness", &CyCity::getBuildingHappiness, "int (int eBuilding)") .def("getExtraBuildingGoodHappiness", &CyCity::getExtraBuildingGoodHappiness, "int ()") .def("getExtraBuildingBadHappiness", &CyCity::getExtraBuildingBadHappiness, "int ()") .def("getFeatureGoodHappiness", &CyCity::getFeatureGoodHappiness, "int ()") .def("getFeatureBadHappiness", &CyCity::getFeatureBadHappiness, "int ()") .def("getBonusGoodHappiness", &CyCity::getBonusGoodHappiness, "int ()") .def("getReligionGoodHappiness", &CyCity::getReligionGoodHappiness, "int ()") .def("getReligionBadHappiness", &CyCity::getReligionBadHappiness, "int ()") .def("getReligionHappiness", &CyCity::getReligionHappiness, "int (int eReligion)") .def("getExtraHappiness", &CyCity::getExtraHappiness, "int ()") .def("getExtraHealth", &CyCity::getExtraHealth, "int ()") .def("changeExtraHealth", &CyCity::changeExtraHealth, "void (int iChange)") .def("changeExtraHappiness", &CyCity::changeExtraHappiness, "void (int iChange)") .def("getHurryAngerTimer", &CyCity::getHurryAngerTimer, "int () - Anger caused by Hurrying timer") .def("changeHurryAngerTimer", &CyCity::changeHurryAngerTimer, "void (iChange) - adjust Hurry Angry timer by iChange") .def("getConscriptAngerTimer", &CyCity::getConscriptAngerTimer, "int () - returns the amount of time left on the conscript anger timer") .def("changeConscriptAngerTimer", &CyCity::changeConscriptAngerTimer, "void (int iChange) -changes the amount of time left on the conscript anger timer") .def("getDefyResolutionAngerTimer", &CyCity::getDefyResolutionAngerTimer, "int () - returns the amount of time left on the anger timer") .def("changeDefyResolutionAngerTimer", &CyCity::changeDefyResolutionAngerTimer, "void (int iChange) -changes the amount of time left on the anger timer") .def("flatDefyResolutionAngerLength", &CyCity::flatDefyResolutionAngerLength, "int ()") .def("getHappinessTimer", &CyCity::getHappinessTimer, "int () - Temporary Happiness timer") .def("changeHappinessTimer", &CyCity::changeHappinessTimer, "void (iChange) - adjust Happiness timer by iChange") .def("isNoUnhappiness", &CyCity::isNoUnhappiness, "bool () - is the city unaffected by unhappiness?") .def("isNoUnhealthyPopulation", &CyCity::isNoUnhealthyPopulation, "bool () - is the city unaffected by unhealthiness?") .def("isBuildingOnlyHealthy", &CyCity::isBuildingOnlyHealthy, "bool () - is the city?") .def("getFood", &CyCity::getFood, "int () - stored food") .def("setFood", &CyCity::setFood, "void (iNewValue) - set stored food to iNewValue") .def("changeFood", &CyCity::changeFood, "void (iChange) - adjust stored food by iChange") .def("getFoodKept", &CyCity::getFoodKept, "int ()") .def("getMaxFoodKeptPercent", &CyCity::getMaxFoodKeptPercent, "int ()") .def("getOverflowProduction", &CyCity::getOverflowProduction, "int () - value of overflow production") .def("setOverflowProduction", &CyCity::setOverflowProduction, "void (iNewValue) - set overflow production to iNewValue") .def("getFeatureProduction", &CyCity::getFeatureProduction, "int () - value of feature production") .def("setFeatureProduction", &CyCity::setFeatureProduction, "void (iNewValue) - set feature production to iNewValue") .def("getMilitaryProductionModifier", &CyCity::getMilitaryProductionModifier, "int () - value of adjustments to military production") .def("getSpaceProductionModifier", &CyCity::getSpaceProductionModifier, "int ()") .def("getExtraTradeRoutes", &CyCity::getExtraTradeRoutes, "int () - returns the number of extra trade routes this city has") .def("changeExtraTradeRoutes", &CyCity::changeExtraTradeRoutes, "void (iChange) - Change the number of trade routes this city has") .def("getTradeRouteModifier", &CyCity::getTradeRouteModifier, "int ()") .def("getForeignTradeRouteModifier", &CyCity::getForeignTradeRouteModifier, "int ()") .def("getBuildingDefense", &CyCity::getBuildingDefense, "int () - building defense") .def("getBuildingBombardDefense", &CyCity::getBuildingBombardDefense, "int () - building defense") .def("getFreeExperience", &CyCity::getFreeExperience, "int () - # of free experience newly trained units receive") .def("getCurrAirlift", &CyCity::getCurrAirlift, "int ()") .def("getMaxAirlift", &CyCity::getMaxAirlift, "int ()") .def("getAirModifier", &CyCity::getAirModifier, "int () - returns the air defense modifier") .def("getAirUnitCapacity", &CyCity::getAirUnitCapacity, "int (int /*TeamTypes*/ eTeam) - returns the number of air units allowed here") .def("getNukeModifier", &CyCity::getNukeModifier, "int ()") .def("getFreeSpecialist", &CyCity::getFreeSpecialist, "int ()") .def("isPower", &CyCity::isPower, "bool ()") .def("isAreaCleanPower", &CyCity::isAreaCleanPower, "bool ()") .def("isDirtyPower", &CyCity::isDirtyPower, "bool ()") .def("getDefenseDamage", &CyCity::getDefenseDamage, "int () - value of damage city defenses can receive") .def("changeDefenseDamage", &CyCity::changeDefenseDamage, "void (iChange) - adjust damage value by iChange") .def("isBombardable", &CyCity::isBombardable, "bool (CyUnit* pUnit)") .def("getNaturalDefense", &CyCity::getNaturalDefense, "int ()") .def("getTotalDefense", &CyCity::getTotalDefense, "int (bool bIgnoreBuilding)") .def("getDefenseModifier", &CyCity::getDefenseModifier, "int (bool bIgnoreBuilding)") .def("getOccupationTimer", &CyCity::getOccupationTimer, "int () - total # of turns remaining on occupation timer") .def("isOccupation", &CyCity::isOccupation, "bool () - is the city under occupation?") .def("setOccupationTimer", &CyCity::setOccupationTimer, "void (iNewValue) - set the Occupation Timer to iNewValue") .def("changeOccupationTimer", &CyCity::changeOccupationTimer, "void (iChange) - adjusts the Occupation Timer by iChange") .def("getCultureUpdateTimer", &CyCity::getCultureUpdateTimer, "int () - Culture Update Timer") .def("changeCultureUpdateTimer", &CyCity::changeCultureUpdateTimer, "void (iChange) - adjusts the Culture Update Timer by iChange") .def("isNeverLost", &CyCity::isNeverLost, "bool ()") .def("setNeverLost", &CyCity::setNeverLost, "void (iNewValue)") .def("isBombarded", &CyCity::isBombarded, "bool ()") .def("setBombarded", &CyCity::setBombarded, "void (iNewValue)") .def("isDrafted", &CyCity::isDrafted, "bool ()") .def("setDrafted", &CyCity::setDrafted, "void (iNewValue)") .def("isAirliftTargeted", &CyCity::isAirliftTargeted, "bool ()") .def("setAirliftTargeted", &CyCity::setAirliftTargeted, "void (iNewValue)") .def("isCitizensAutomated", &CyCity::isCitizensAutomated, "bool () - are citizens under automation?") .def("setCitizensAutomated", &CyCity::setCitizensAutomated, "void (bool bNewValue) - set city animation bNewValue") .def("isProductionAutomated", &CyCity::isProductionAutomated, "bool () - is production under automation?") .def("setProductionAutomated", &CyCity::setProductionAutomated, "void (bool bNewValue) - set city production automation to bNewValue") .def("isWallOverride", &CyCity::isWallOverride, "bool isWallOverride()") .def("setWallOverride", &CyCity::setWallOverride, "setWallOverride(bool bOverride)") .def("setCitySizeBoost", &CyCity::setCitySizeBoost, "setCitySizeBoost(int iBoost)") .def("isPlundered", &CyCity::isPlundered, "bool ()") .def("setPlundered", &CyCity::setPlundered, "void (iNewValue)") .def("getOwner", &CyCity::getOwner, "int /*PlayerTypes*/ ()") .def("getTeam", &CyCity::getTeam, "int /*TeamTypes*/ ()") .def("getPreviousOwner", &CyCity::getPreviousOwner, "int /*PlayerTypes*/ ()") .def("getOriginalOwner", &CyCity::getOriginalOwner, "int /*PlayerTypes*/ ()") .def("getCultureLevel", &CyCity::getCultureLevel, "int /*CultureLevelTypes*/ ()") .def("getCultureThreshold", &CyCity::getCultureThreshold) .def("getSeaPlotYield", &CyCity::getSeaPlotYield, "int (int /*YieldTypes*/) - total YieldType for water plots") .def("getRiverPlotYield", &CyCity::getRiverPlotYield, "int (int /*YieldTypes*/) - total YieldType for river plots") .def("getBaseYieldRate", &CyCity::getBaseYieldRate, "int (int /*YieldTypes*/) - base rate for YieldType") .def("setBaseYieldRate", &CyCity::setBaseYieldRate, "int (int /*YieldTypes*/, int iNewValue) - sets the base rate for YieldType") .def("changeBaseYieldRate", &CyCity::changeBaseYieldRate, "int (int /*YieldTypes*/, int iChange) - changes the base rate for YieldType") .def("getBaseYieldRateModifier", &CyCity::getBaseYieldRateModifier) .def("getYieldRate", &CyCity::getYieldRate, "int (int /*YieldTypes*/) - total value of YieldType") .def("getYieldRateModifier", &CyCity::getYieldRateModifier, "int (int /*YieldTypes*/) - yield rate modifier for YieldType") .def("getTradeYield", &CyCity::getTradeYield, "int (int /*YieldTypes*/) - trade adjustment to YieldType") .def("totalTradeModifier", &CyCity::totalTradeModifier, "int () - total trade adjustment") .def("calculateTradeProfit", &CyCity::calculateTradeProfit, "int (CyCity) - returns the trade profit created by CyCity") .def("calculateTradeYield", &CyCity::calculateTradeYield, "int (YieldType, int iTradeProfit) - calculates Trade Yield") .def("getExtraSpecialistYield", &CyCity::getExtraSpecialistYield, "int (int /*YieldTypes*/ eIndex)") .def("getExtraSpecialistYieldOfType", &CyCity::getExtraSpecialistYieldOfType, "int (int /*YieldTypes*/ eIndex, int /*SpecialistTypes*/ eSpecialist)") .def("getCommerceRate", &CyCity::getCommerceRate, "int (int /*CommerceTypes*/) - total Commerce rate") .def("getCommerceRateTimes100", &CyCity::getCommerceRateTimes100, "int (int /*CommerceTypes*/) - total Commerce rate") .def("getCommerceFromPercent", &CyCity::getCommerceFromPercent, "int (int /*CommerceTypes*/, int iYieldRate)") .def("getBaseCommerceRate", &CyCity::getBaseCommerceRate, "int (int /*CommerceTypes*/)") .def("getBaseCommerceRateTimes100", &CyCity::getBaseCommerceRateTimes100, "int (int /*CommerceTypes*/)") .def("getTotalCommerceRateModifier", &CyCity::getTotalCommerceRateModifier, "int (int /*CommerceTypes*/)") .def("getProductionToCommerceModifier", &CyCity::getProductionToCommerceModifier, "int (int /*CommerceTypes*/) - value of production to commerce modifier") .def("getBuildingCommerce", &CyCity::getBuildingCommerce, "int (int /*CommerceTypes*/) - total effect of cities buildings on CommerceTypes") .def("getBuildingCommerceByBuilding", &CyCity::getBuildingCommerceByBuilding, "int (int /*CommerceTypes*/, BuildingTypes) - total value of CommerceType from BuildingTypes") .def("getSpecialistCommerce", &CyCity::getSpecialistCommerce, "int (int /*CommerceTypes*/) - value of CommerceType adjustment from Specialists") .def("changeSpecialistCommerce", &CyCity::changeSpecialistCommerce, "void (int /*CommerceTypes*/, iChange) - adjusts Specialist contribution to CommerceType by iChange") .def("getReligionCommerce", &CyCity::getReligionCommerce, "int (int /*CommerceTypes*/) - effect on CommerceType by Religions") .def("getReligionCommerceByReligion", &CyCity::getReligionCommerceByReligion, "int (int /*CommerceTypes*/, ReligionType) - CommerceType effect from ReligionType") .def("getCorporationCommerce", &CyCity::getCorporationCommerce, "int (int /*CommerceTypes*/) - effect on CommerceType by Corporation") .def("getCorporationCommerceByCorporation", &CyCity::getCorporationCommerceByCorporation, "int (int /*CommerceTypes*/, CorporationType) - CommerceType effect from CorporationType") .def("getCorporationYield", &CyCity::getCorporationYield, "int (int /*CommerceTypes*/) - effect on YieldTypes by Corporation") .def("getCorporationYieldByCorporation", &CyCity::getCorporationYieldByCorporation, "int (int /*YieldTypes*/, CorporationType) - YieldTypes effect from CorporationType") .def("getCommerceRateModifier", &CyCity::getCommerceRateModifier, "int (int /*CommerceTypes*/) - indicates the total rate modifier on CommerceType") .def("getCommerceHappinessPer", &CyCity::getCommerceHappinessPer, "int (int /*CommerceTypes*/) - happiness from each level of entertainment") .def("getCommerceHappinessByType", &CyCity::getCommerceHappinessByType, "int (int /*CommerceTypes*/) - happiness from CommerceType") .def("getCommerceHappiness", &CyCity::getCommerceHappiness, "int () - happiness from all CommerceTypes") .def("getDomainFreeExperience", &CyCity::getDomainFreeExperience, "int (int /*DomainTypes*/)") .def("getDomainProductionModifier", &CyCity::getDomainProductionModifier, "int (int /*DomainTypes*/)") .def("getCulture", &CyCity::getCulture, "int /*PlayerTypes*/ ()") .def("getCultureTimes100", &CyCity::getCultureTimes100, "int /*PlayerTypes*/ ()") .def("countTotalCultureTimes100", &CyCity::countTotalCultureTimes100, "int ()") .def("findHighestCulture", &CyCity::findHighestCulture, "PlayerTypes ()") .def("calculateCulturePercent", &CyCity::calculateCulturePercent, "int (int eIndex)") .def("calculateTeamCulturePercent", &CyCity::calculateTeamCulturePercent, "int /*TeamTypes*/ ()") .def("setCulture", &CyCity::setCulture, "void (int PlayerTypes eIndex`, bool bPlots)") .def("setCultureTimes100", &CyCity::setCultureTimes100, "void (int PlayerTypes eIndex, int iNewValue, bool bPlots)") .def("changeCulture", &CyCity::changeCulture, "void (int PlayerTypes eIndex, int iChange, bool bPlots)") .def("changeCultureTimes100", &CyCity::changeCultureTimes100, "void (int PlayerTypes eIndex, int iChange, bool bPlots)") .def("isTradeRoute", &CyCity::isTradeRoute, "bool ()") .def("isEverOwned", &CyCity::isEverOwned, "bool ()") .def("isRevealed", &CyCity::isRevealed, "bool (int /*TeamTypes*/ eIndex, bool bDebug)") .def("setRevealed", &CyCity::setRevealed, "void (int /*TeamTypes*/ eIndex, bool bNewValue)") .def("getEspionageVisibility", &CyCity::getEspionageVisibility, "bool (int /*TeamTypes*/ eIndex)") .def("getName", &CyCity::getName, "string () - city name") .def("getNameForm", &CyCity::getNameForm, "string () - city name") .def("getNameKey", &CyCity::getNameKey, "string () - city name") .def("setName", &CyCity::setName, "void (TCHAR szNewValue, bool bFound) - sets the name to szNewValue") .def("isNoBonus", &CyCity::isNoBonus, "bool (int eIndex)") .def("changeNoBonusCount", &CyCity::changeNoBonusCount, "void (int eIndex, int iChange)") .def("getFreeBonus", &CyCity::getFreeBonus, "int (int eIndex)") .def("changeFreeBonus", &CyCity::changeFreeBonus, "void (int eIndex, int iChange)") .def("getNumBonuses", &CyCity::getNumBonuses, "int (PlayerID)") .def("hasBonus", &CyCity::hasBonus, "bool - (BonusID) - is BonusID connected to the city?") .def("getBuildingProduction", &CyCity::getBuildingProduction, "int (BuildingID) - current production towards BuildingID") .def("setBuildingProduction", &CyCity::setBuildingProduction, "void (BuildingID, iNewValue) - set progress towards BuildingID as iNewValue") .def("changeBuildingProduction", &CyCity::changeBuildingProduction, "void (BuildingID, iChange) - adjusts progress towards BuildingID by iChange") .def("getBuildingProductionTime", &CyCity::getBuildingProductionTime, "int (int eIndex)") .def("setBuildingProductionTime", &CyCity::setBuildingProductionTime, "int (int eIndex, int iNewValue)") .def("changeBuildingProductionTime", &CyCity::changeBuildingProductionTime, "int (int eIndex, int iChange)") .def("getBuildingOriginalOwner", &CyCity::getBuildingOriginalOwner, "int (BuildingType) - index of original building owner") .def("getBuildingOriginalTime", &CyCity::getBuildingOriginalTime, "int (BuildingType) - original build date") .def("getUnitProduction", &CyCity::getUnitProduction, "int (UnitID) - gets current production towards UnitID") .def("setUnitProduction", &CyCity::setUnitProduction, "void (UnitID, iNewValue) - sets production towards UnitID as iNewValue") .def("changeUnitProduction", &CyCity::changeUnitProduction, "void (UnitID, iChange) - adjusts production towards UnitID by iChange") .def("getGreatPeopleUnitRate", &CyCity::getGreatPeopleUnitRate, "int (int /*UnitTypes*/ iIndex)") .def("getGreatPeopleUnitProgress", &CyCity::getGreatPeopleUnitProgress, "int (int /*UnitTypes*/ iIndex)") .def("setGreatPeopleUnitProgress", &CyCity::setGreatPeopleUnitProgress, "int (int /*UnitTypes*/ iIndex, int iNewValue)") .def("changeGreatPeopleUnitProgress", &CyCity::changeGreatPeopleUnitProgress, "int (int /*UnitTypes*/ iIndex, int iChange)") .def("getSpecialistCount", &CyCity::getSpecialistCount, "int (int /*SpecialistTypes*/ eIndex)") .def("alterSpecialistCount", &CyCity::alterSpecialistCount, "int (int /*SpecialistTypes*/ eIndex, int iChange)") .def("getMaxSpecialistCount", &CyCity::getMaxSpecialistCount, "int (int /*SpecialistTypes*/ eIndex)") .def("isSpecialistValid", &CyCity::isSpecialistValid, "bool (int /*SpecialistTypes*/ eIndex, int iExtra)") .def("getForceSpecialistCount", &CyCity::getForceSpecialistCount, "int (int /*SpecialistTypes*/ eIndex)") .def("isSpecialistForced", &CyCity::isSpecialistForced, "bool ()") .def("setForceSpecialistCount", &CyCity::setForceSpecialistCount, "int (int /*SpecialistTypes*/ eIndex, int iNewValue") .def("changeForceSpecialistCount", &CyCity::changeForceSpecialistCount, "int (int /*SpecialistTypes*/ eIndex, int iChange") .def("getFreeSpecialistCount", &CyCity::getFreeSpecialistCount, "int (int /*SpecialistTypes*/ eIndex") .def("setFreeSpecialistCount", &CyCity::setFreeSpecialistCount, "int (int /*SpecialistTypes*/ eIndex, iNewValue") .def("changeFreeSpecialistCount", &CyCity::changeFreeSpecialistCount, "int (int /*SpecialistTypes*/ eIndex, iChange") .def("getAddedFreeSpecialistCount", &CyCity::getAddedFreeSpecialistCount, "int (int /*SpecialistTypes*/ eIndex") .def("getImprovementFreeSpecialists", &CyCity::getImprovementFreeSpecialists, "int (ImprovementID)") .def("changeImprovementFreeSpecialists", &CyCity::changeImprovementFreeSpecialists, "void (ImprovementID, iChange) - adjust ImprovementID free specialists by iChange") .def("getReligionInfluence", &CyCity::getReligionInfluence, "int (ReligionID) - value of influence from ReligionID") .def("changeReligionInfluence", &CyCity::changeReligionInfluence, "void (ReligionID, iChange) - adjust ReligionID influence by iChange") .def("getCurrentStateReligionHappiness", &CyCity::getCurrentStateReligionHappiness, "int ()") .def("getStateReligionHappiness", &CyCity::getStateReligionHappiness, "int (int /*ReligionTypes*/ ReligionID)") .def("changeStateReligionHappiness", &CyCity::changeStateReligionHappiness, "void (int /*ReligionTypes*/ ReligionID, iChange)") .def("getUnitCombatFreeExperience", &CyCity::getUnitCombatFreeExperience, "int (int /*UnitCombatTypes*/ eIndex)") .def("getFreePromotionCount", &CyCity::getFreePromotionCount, "int (int /*PromotionTypes*/ eIndex)") .def("isFreePromotion", &CyCity::isFreePromotion, "bool (int /*PromotionTypes*/ eIndex)") .def("getSpecialistFreeExperience", &CyCity::getSpecialistFreeExperience, "int ()") .def("getEspionageDefenseModifier", &CyCity::getEspionageDefenseModifier, "int ()") .def("isWorkingPlotByIndex", &CyCity::isWorkingPlotByIndex, "bool (iIndex) - true if a worker is working this city's plot iIndex") .def("isWorkingPlot", &CyCity::isWorkingPlot, "bool (iIndex) - true if a worker is working this city's pPlot") .def("alterWorkingPlot", &CyCity::alterWorkingPlot, "void (iIndex)") .def("getNumRealBuilding", &CyCity::getNumRealBuilding, "int (BuildingID) - get # real building of this type") .def("setNumRealBuilding", &CyCity::setNumRealBuilding, "(BuildingID, iNum) - Sets number of buildings in this city of BuildingID type") .def("getNumFreeBuilding", &CyCity::getNumFreeBuilding, "int (BuildingID) - # of free Building ID (ie: from a Wonder)") .def("isHasReligion", &CyCity::isHasReligion, "bool (ReligionID) - does city have ReligionID?") .def("setHasReligion", &CyCity::setHasReligion, "void (ReligionID, bool bNewValue, bool bAnnounce, bool bArrows) - religion begins to spread") .def("isHasCorporation", &CyCity::isHasCorporation, "bool (CorporationID) - does city have CorporationID?") .def("setHasCorporation", &CyCity::setHasCorporation, "void (CorporationID, bool bNewValue, bool bAnnounce, bool bArrows) - corporation begins to spread") .def("isActiveCorporation", &CyCity::isActiveCorporation, "bool (CorporationID) - does city have active CorporationID?") .def("getTradeCity", &CyCity::getTradeCity, python::return_value_policy<python::manage_new_object>(), "CyCity (int iIndex) - remove SpecialistType[iIndex]") .def("getTradeRoutes", &CyCity::getTradeRoutes, "int ()") .def("clearOrderQueue", &CyCity::clearOrderQueue, "void ()") .def("pushOrder", &CyCity::pushOrder, "void (OrderTypes eOrder, int iData1, int iData2, bool bSave, bool bPop, bool bAppend, bool bForce)") .def("popOrder", &CyCity::popOrder, "int (int iNum, bool bFinish, bool bChoose)") .def("getOrderQueueLength", &CyCity::getOrderQueueLength, "void ()") .def("getOrderFromQueue", &CyCity::getOrderFromQueue, python::return_value_policy<python::manage_new_object>(), "OrderData* (int iIndex)") .def("setWallOverridePoints", &CyCity::setWallOverridePoints, "setWallOverridePoints(const python::tuple& kPoints)") .def("getWallOverridePoints", &CyCity::getWallOverridePoints, "python::tuple getWallOverridePoints()") .def("AI_avoidGrowth", &CyCity::AI_avoidGrowth, "bool ()") .def("AI_isEmphasize", &CyCity::AI_isEmphasize, "bool (int iEmphasizeType)") .def("AI_countBestBuilds", &CyCity::AI_countBestBuilds, "int (CyArea* pArea)") .def("AI_cityValue", &CyCity::AI_cityValue, "int ()") .def("getScriptData", &CyCity::getScriptData, "str () - Get stored custom data (via pickle)") .def("setScriptData", &CyCity::setScriptData, "void (str) - Set stored custom data (via pickle)") .def("visiblePopulation", &CyCity::visiblePopulation, "int ()") .def("getBuildingYieldChange", &CyCity::getBuildingYieldChange, "int (int /*BuildingClassTypes*/ eBuildingClass, int /*YieldTypes*/ eYield)") .def("setBuildingYieldChange", &CyCity::setBuildingYieldChange, "void (int /*BuildingClassTypes*/ eBuildingClass, int /*YieldTypes*/ eYield, int iChange)") .def("getBuildingCommerceChange", &CyCity::getBuildingCommerceChange, "int (int /*BuildingClassTypes*/ eBuildingClass, int /*CommerceTypes*/ eCommerce)") .def("setBuildingCommerceChange", &CyCity::setBuildingCommerceChange, "void (int /*BuildingClassTypes*/ eBuildingClass, int /*CommerceTypes*/ eCommerce, int iChange)") .def("getBuildingHappyChange", &CyCity::getBuildingHappyChange, "int (int /*BuildingClassTypes*/ eBuildingClass)") .def("setBuildingHappyChange", &CyCity::setBuildingHappyChange, "void (int /*BuildingClassTypes*/ eBuildingClass, int iChange)") .def("getBuildingHealthChange", &CyCity::getBuildingHealthChange, "int (int /*BuildingClassTypes*/ eBuildingClass)") .def("setBuildingHealthChange", &CyCity::setBuildingHealthChange, "void (int /*BuildingClassTypes*/ eBuildingClass, int iChange)") .def("getLiberationPlayer", &CyCity::getLiberationPlayer, "int ()") .def("liberate", &CyCity::liberate, "void ()") ; } ======================= File: Warlords/CvGameCoreDLL/CvSelectionGroup.cpp ======================= <gh_stars>0 // selectionGroup.cpp #include "CvGameCoreDLL.h" #include "CvGlobals.h" #include "CvSelectionGroup.h" #include "CvGameAI.h" #include "CvPlayerAI.h" #include "CvTeamAI.h" #include "CvUnit.h" #include "CvGameCoreUtils.h" #include "CvMap.h" #include "CvPlot.h" #include "CvDLLEntityIFaceBase.h" #include "CvDLLInterfaceIFaceBase.h" #include "CvDLLFAStarIFaceBase.h" #include "FAStarNode.h" #include "CvInfos.h" #include "FProfiler.h" #include "CvDLLEventReporterIFaceBase.h" // Public Functions... CvSelectionGroup::CvSelectionGroup() { reset(0, NO_PLAYER, true); } CvSelectionGroup::~CvSelectionGroup() { uninit(); } void CvSelectionGroup::init(int iID, PlayerTypes eOwner) { //-------------------------------- // Init saved data reset(iID, eOwner); //-------------------------------- // Init non-saved data //-------------------------------- // Init other game data AI_init(); } void CvSelectionGroup::uninit() { m_units.clear(); m_missionQueue.clear(); } // FUNCTION: reset() // Initializes data members that are serialized. void CvSelectionGroup::reset(int iID, PlayerTypes eOwner, bool bConstructorCall) { //-------------------------------- // Uninit class uninit(); m_iID = iID; m_iMissionTimer = 0; m_bForceUpdate = false; m_eOwner = eOwner; m_eActivityType = ACTIVITY_AWAKE; m_eAutomateType = NO_AUTOMATE; if (!bConstructorCall) { AI_reset(); } } void CvSelectionGroup::kill() { FAssert(getOwnerINLINE()!= NO_PLAYER); FAssertMsg(getID()!= FFreeList::INVALID_INDEX, "getID() is not expected to be equal with FFreeList::INVALID_INDEX"); FAssertMsg(getNumUnits() == 0, "The number of units is expected to be 0"); GET_PLAYER(getOwnerINLINE()).removeGroupCycle(getID()); GET_PLAYER(getOwnerINLINE()).deleteSelectionGroup(getID()); } void CvSelectionGroup::doTurn() { PROFILE("CvSelectionGroup::doTurn()") CLLNode<IDInfo>* pUnitNode; CvUnit* pLoopUnit; bool bHurt; int iWaitTurns; int iBestWaitTurns; FAssert(getOwnerINLINE()!= NO_PLAYER); if (getNumUnits() > 0) { bHurt = false; pUnitNode = headUnitNode(); while (pUnitNode!= NULL) { pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = nextUnitNode(pUnitNode); pLoopUnit->doTurn(); if (pLoopUnit->isHurt()) { bHurt = true; } } if ((getActivityType() == ACTIVITY_HOLD) || ((getActivityType() == ACTIVITY_HEAL) &&!bHurt) || ((getActivityType() == ACTIVITY_SENTRY) && (GET_PLAYER(getOwnerINLINE()).AI_getPlotDanger(plot(), 1) > 0))) { setActivityType(ACTIVITY_AWAKE); } if (AI_isControlled()) { if ((getActivityType()!= ACTIVITY_MISSION) || (!canFight() && (GET_PLAYER(getOwnerINLINE()).AI_getPlotDanger(plot()) > 0))) { setForceUpdate(true); } } else { if (getActivityType() == ACTIVITY_MISSION) { if (GET_PLAYER(getOwnerINLINE()).AI_getPlotDanger(plot(), 1) > 0) { clearMissionQueue(); } } } if (isHuman()) { if (GC.getGameINLINE().isMPOption(MPOPTION_SIMULTANEOUS_TURNS)) { iBestWaitTurns = 0; pUnitNode = headUnitNode(); while (pUnitNode!= NULL) { pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = nextUnitNode(pUnitNode); iWaitTurns = (GC.getDefineINT("MIN_TIMER_UNIT_DOUBLE_MOVES") - (GC.getGameINLINE().getTurnSlice() - pLoopUnit->getLastMoveTurn())); if (iWaitTurns > iBestWaitTurns) { iBestWaitTurns = iWaitTurns; } } setMissionTimer(max(iBestWaitTurns, getMissionTimer())); if (iBestWaitTurns > 0) { // Cycle selection if the current group is selected CvUnit* pSelectedUnit = gDLL->getInterfaceIFace()->getHeadSelectedUnit(); if (pSelectedUnit && pSelectedUnit->getGroup() == this) { gDLL->getInterfaceIFace()->selectGroup(pSelectedUnit, false, false, false); } } } } } doDelayedDeath(); } void CvSelectionGroup::updateTimers() { CLLNode<IDInfo>* pUnitNode; CvUnit* pLoopUnit; bool bCombat; FAssert(getOwnerINLINE()!= NO_PLAYER); if (getNumUnits() > 0) { bCombat = false; pUnitNode = headUnitNode(); while (pUnitNode!= NULL) { pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = nextUnitNode(pUnitNode); if (pLoopUnit->isCombat()) { pLoopUnit->updateCombat(); bCombat = true; break; } } if (!bCombat) { updateMission(); } } doDelayedDeath(); } // Returns true if group was killed... bool CvSelectionGroup::doDelayedDeath() { CLLNode<IDInfo>* pUnitNode; CvUnit* pLoopUnit; FAssert(getOwnerINLINE()!= NO_PLAYER); if (isBusy()) { return false; } pUnitNode = headUnitNode(); while (pUnitNode!= NULL) { pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = nextUnitNode(pUnitNode); pLoopUnit->doDelayedDeath(); } if (getNumUnits() == 0) { kill(); return true; } return false; } void CvSelectionGroup::playActionSound() { // Pitboss should not be playing sounds! #ifndef PITBOSS CvUnit *pHeadUnit; int iScriptId = -1; pHeadUnit = getHeadUnit(); if ( pHeadUnit ) { CvUnitInfo *pUnitInfo; pUnitInfo = &GC.getUnitInfo( pHeadUnit->getUnitType() ); if ( pUnitInfo ) { iScriptId = pUnitInfo->getArtInfo(0, GET_PLAYER(getOwner()).getCurrentEra())->getActionSoundScriptId(); } } if ( (iScriptId == -1) && pHeadUnit ) { CvCivilizationInfo *pCivInfo; pCivInfo = &GC.getCivilizationInfo( pHeadUnit->getCivilizationType() ); if ( pCivInfo ) { iScriptId = pCivInfo->getActionSoundScriptId(); } } if ( (iScriptId!= -1) && pHeadUnit ) { CvPlot *pPlot = GC.getMapINLINE().plotINLINE(pHeadUnit->getX_INLINE(),pHeadUnit->getY_INLINE()); if ( pPlot ) { gDLL->Do3DSound( iScriptId, pPlot->getPoint() ); } } #endif // n PITBOSS } void CvSelectionGroup::pushMission(MissionTypes eMission, int iData1, int iData2, int iFlags, bool bAppend, bool bManual, MissionAITypes eMissionAI, CvPlot* pMissionAIPlot, CvUnit* pMissionAIUnit) { PROFILE_FUNC(); MissionData mission; FAssert(getOwnerINLINE()!= NO_PLAYER); if (!bAppend) { if (isBusy()) { return; } clearMissionQueue(); } if (bManual) { setAutomateType(NO_AUTOMATE); } mission.eMissionType = eMission; mission.iData1 = iData1; mission.iData2 = iData2; mission.iFlags = iFlags; mission.iPushTurn = GC.getGameINLINE().getGameTurn(); AI_setMissionAI(eMissionAI, pMissionAIPlot, pMissionAIUnit); insertAtEndMissionQueue(mission,!bAppend); if (bManual) { if (getOwnerINLINE() == GC.getGameINLINE().getActivePlayer()) { if (isBusy() && GC.getMissionInfo(eMission).isSound()) { playActionSound(); } gDLL->getInterfaceIFace()->setHasMovedUnit(true); } gDLL->getEventReporterIFace()->selectionGroupPushMission(this, eMission); doDelayedDeath(); } } void CvSelectionGroup::popMission() { CLLNode<MissionData>* pTailNode; FAssert(getOwnerINLINE()!= NO_PLAYER); pTailNode = tailMissionQueueNode(); if (pTailNode!= NULL) { deleteMissionQueueNode(pTailNode); } } void CvSelectionGroup::autoMission() { FAssert(getOwnerINLINE()!= NO_PLAYER); if (getNumUnits() > 0) { if (headMissionQueueNode()!= NULL) { if (!isBusy()) { if (isHuman() && GET_PLAYER(getOwnerINLINE()).AI_getPlotDanger(plot(), 1) > 0) { clearMissionQueue(); } else { if (getActivityType() == ACTIVITY_MISSION) { continueMission(); } else { startMission(); } } } } } doDelayedDeath(); } void CvSelectionGroup::updateMission() { FAssert(getOwnerINLINE()!= NO_PLAYER); if (getMissionTimer() > 0) { changeMissionTimer(-1); if (getMissionTimer() == 0) { if (getActivityType() == ACTIVITY_MISSION) { continueMission(); } else { if (getOwnerINLINE() == GC.getGameINLINE().getActivePlayer()) { if (gDLL->getInterfaceIFace()->getHeadSelectedUnit() == NULL) { gDLL->getInterfaceIFace()->changeCycleSelectionCounter(1); } } } } } } CvPlot* CvSelectionGroup::lastMissionPlot() { CLLNode<MissionData>* pMissionNode; CvUnit* pTargetUnit; pMissionNode = tailMissionQueueNode(); while (pMissionNode!= NULL) { switch (pMissionNode->m_data.eMissionType) { case MISSION_MOVE_TO: case MISSION_ROUTE_TO: return GC.getMapINLINE().plotINLINE(pMissionNode->m_data.iData1, pMissionNode->m_data.iData2); break; case MISSION_MOVE_TO_UNIT: pTargetUnit = GET_PLAYER((PlayerTypes)pMissionNode->m_data.iData1).getUnit(pMissionNode->m_data.iData2); if (pTargetUnit!= NULL) { return pTargetUnit->plot(); } break; case MISSION_SKIP: case MISSION_SLEEP: case MISSION_FORTIFY: case MISSION_AIRPATROL: case MISSION_HEAL: case MISSION_SENTRY: case MISSION_AIRLIFT: case MISSION_NUKE: case MISSION_RECON: case MISSION_AIRBOMB: case MISSION_BOMBARD: case MISSION_PILLAGE: case MISSION_SABOTAGE: case MISSION_DESTROY: case MISSION_STEAL_PLANS: case MISSION_FOUND: case MISSION_SPREAD: case MISSION_JOIN: case MISSION_CONSTRUCT: case MISSION_DISCOVER: case MISSION_HURRY: case MISSION_TRADE: case MISSION_GREAT_WORK: case MISSION_GOLDEN_AGE: case MISSION_BUILD: case MISSION_LEAD: break; default: FAssert(false); break; } pMissionNode = prevMissionQueueNode(pMissionNode); } return plot(); } bool CvSelectionGroup::canStartMission(int iMission, int iData1, int iData2, CvPlot* pPlot, bool bTestVisible) { CLLNode<IDInfo>* pUnitNode; CvUnit* pTargetUnit; CvUnit* pLoopUnit; if (isBusy()) { return false; } if (pPlot == NULL) { pPlot = plot(); } pUnitNode = headUnitNode(); while (pUnitNode!= NULL) { pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = nextUnitNode(pUnitNode); switch (iMission) { case MISSION_MOVE_TO: if (!(pPlot->at(iData1, iData2))) { return true; } break; case MISSION_ROUTE_TO: if (!(pPlot->at(iData1, iData2)) || (getBestBuildRoute(pPlot)!= NO_ROUTE)) { return true; } break; case MISSION_MOVE_TO_UNIT: FAssertMsg(iData1!= NO_PLAYER, "iData1 should be a valid Player"); pTargetUnit = GET_PLAYER((PlayerTypes)iData1).getUnit(iData2); if ((pTargetUnit!= NULL) &&!(pTargetUnit->atPlot(pPlot))) { return true; } break; case MISSION_SKIP: if (pLoopUnit->canHold(pPlot)) { return true; } break; case MISSION_SLEEP: if (pLoopUnit->canSleep(pPlot)) { return true; } break; case MISSION_FORTIFY: if (pLoopUnit->canFortify(pPlot)) { return true; } break; case MISSION_AIRPATROL: if (pLoopUnit->canAirPatrol(pPlot)) { return true; } break; case MISSION_HEAL: if (pLoopUnit->canHeal(pPlot)) { return true; } break; case MISSION_SENTRY: if (pLoopUnit->canSentry(pPlot)) { return true; } break; case MISSION_AIRLIFT: if (pLoopUnit->canAirliftAt(pPlot, iData1, iData2)) { return true; } break; case MISSION_NUKE: if (pLoopUnit->canNukeAt(pPlot, iData1, iData2)) { return true; } break; case MISSION_RECON: if (pLoopUnit->canReconAt(pPlot, iData1, iData2)) { return true; } break; case MISSION_AIRBOMB: if (pLoopUnit->canAirBombAt(pPlot, iData1, iData2)) { return true; } break; case MISSION_BOMBARD: if (pLoopUnit->canBombard(pPlot)) { return true; } break; case MISSION_PILLAGE: if (pLoopUnit->canPillage(pPlot)) { return true; } break; case MISSION_SABOTAGE: if (pLoopUnit->canSabotage(pPlot, bTestVisible)) { return true; } break; case MISSION_DESTROY: if (pLoopUnit->canDestroy(pPlot, bTestVisible)) { return true; } break; case MISSION_STEAL_PLANS: if (pLoopUnit->canStealPlans(pPlot, bTestVisible)) { return true; } break; case MISSION_FOUND: if (pLoopUnit->canFound(pPlot, bTestVisible)) { return true; } break; case MISSION_SPREAD: if (pLoopUnit->canSpread(pPlot, ((ReligionTypes)iData1), bTestVisible)) { return true; } break; case MISSION_JOIN: if (pLoopUnit->canJoin(pPlot, ((SpecialistTypes)iData1))) { return true; } break; case MISSION_CONSTRUCT: if (pLoopUnit->canConstruct(pPlot, ((BuildingTypes)iData1), bTestVisible)) { return true; } break; case MISSION_DISCOVER: if (pLoopUnit->canDiscover(pPlot)) { return true; } break; case MISSION_HURRY: if (pLoopUnit->canHurry(pPlot, bTestVisible)) { return true; } break; case MISSION_TRADE: if (pLoopUnit->canTrade(pPlot, bTestVisible)) { return true; } break; case MISSION_GREAT_WORK: if (pLoopUnit->canGreatWork(pPlot)) { return true; } break; case MISSION_GOLDEN_AGE: if (pLoopUnit->canGoldenAge(pPlot, bTestVisible)) { return true; } break; case MISSION_BUILD: if (pLoopUnit->canBuild(pPlot, ((BuildTypes)iData1), bTestVisible)) { return true; } break; case MISSION_LEAD: if (pLoopUnit->canLead(pPlot, iData1)) { return true; } break; case MISSION_BEGIN_COMBAT: case MISSION_END_COMBAT: case MISSION_AIRSTRIKE: case MISSION_SURRENDER: case MISSION_IDLE: case MISSION_DIE: case MISSION_DAMAGE: case MISSION_MULTI_SELECT: case MISSION_MULTI_DESELECT: break; default: FAssert(false); break; } } return false; } void CvSelectionGroup::startMission() { CLLNode<IDInfo>* pUnitNode; CvUnit* pLoopUnit; bool bDelete; bool bAction; bool bNuke; bool bNotify; FAssert(!isBusy()); FAssert(getOwnerINLINE()!= NO_PLAYER); FAssert(headMissionQueueNode()!= NULL); if (!(GC.getGameINLINE().isMPOption(MPOPTION_SIMULTANEOUS_TURNS))) { if (!(GET_PLAYER(getOwnerINLINE()).isTurnActive())) { if (getOwnerINLINE() == GC.getGameINLINE().getActivePlayer()) { if (IsSelected()) { gDLL->getInterfaceIFace()->changeCycleSelectionCounter(1); } } return; } } if (canAllMove()) { setActivityType(ACTIVITY_MISSION); } else { setActivityType(ACTIVITY_HOLD); } bDelete = false; bAction = false; bNuke = false; bNotify = false; if (!canStartMission(headMissionQueueNode()->m_data.eMissionType, headMissionQueueNode()->m_data.iData1, headMissionQueueNode()->m_data.iData2, plot())) { bDelete = true; } else { FAssertMsg(GET_PLAYER(getOwnerINLINE()).isTurnActive() || GET_PLAYER(getOwnerINLINE()).isHuman(), "It's expected that either the turn is active for this player or the player is human"); switch (headMissionQueueNode()->m_data.eMissionType) { case MISSION_MOVE_TO: case MISSION_ROUTE_TO: case MISSION_MOVE_TO_UNIT: break; case MISSION_SKIP: setActivityType(ACTIVITY_HOLD); bDelete = true; break; case MISSION_SLEEP: setActivityType(ACTIVITY_SLEEP); bNotify = true; bDelete = true; break; case MISSION_FORTIFY: setActivityType(ACTIVITY_SLEEP); bNotify = true; bDelete = true; break; case MISSION_AIRPATROL: setActivityType(ACTIVITY_INTERCEPT); bDelete = true; break; case MISSION_HEAL: setActivityType(ACTIVITY_HEAL); bNotify = true; bDelete = true; break; case MISSION_SENTRY: setActivityType(ACTIVITY_SENTRY); bNotify = true; bDelete = true; break; case MISSION_AIRLIFT: case MISSION_NUKE: case MISSION_RECON: case MISSION_AIRBOMB: case MISSION_BOMBARD: case MISSION_PILLAGE: case MISSION_SABOTAGE: case MISSION_DESTROY: case MISSION_STEAL_PLANS: case MISSION_FOUND: case MISSION_SPREAD: case MISSION_JOIN: case MISSION_CONSTRUCT: case MISSION_DISCOVER: case MISSION_HURRY: case MISSION_TRADE: case MISSION_GREAT_WORK: case MISSION_GOLDEN_AGE: case MISSION_BUILD: case MISSION_LEAD: break; default: FAssert(false); break; } if ( bNotify ) { NotifyEntity( headMissionQueueNode()->m_data.eMissionType ); } pUnitNode = headUnitNode(); while (pUnitNode!= NULL) { pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = nextUnitNode(pUnitNode); if (pLoopUnit->canMove()) { switch (headMissionQueueNode()->m_data.eMissionType) { case MISSION_MOVE_TO: case MISSION_ROUTE_TO: case MISSION_MOVE_TO_UNIT: case MISSION_SKIP: case MISSION_SLEEP: case MISSION_FORTIFY: case MISSION_AIRPATROL: case MISSION_HEAL: case MISSION_SENTRY: break; case MISSION_AIRLIFT: if (pLoopUnit->airlift(headMissionQueueNode()->m_data.iData1, headMissionQueueNode()->m_data.iData2)) { bAction = true; } break; case MISSION_NUKE: if (pLoopUnit->nuke(headMissionQueueNode()->m_data.iData1, headMissionQueueNode()->m_data.iData2)) { bAction = true; if (GC.getMapINLINE().plotINLINE(headMissionQueueNode()->m_data.iData1, headMissionQueueNode()->m_data.iData2)->isVisibleToWatchingHuman()) { bNuke = true; } } break; case MISSION_RECON: if (pLoopUnit->recon(headMissionQueueNode()->m_data.iData1, headMissionQueueNode()->m_data.iData2)) { bAction = true; } break; case MISSION_AIRBOMB: if (pLoopUnit->airBomb(headMissionQueueNode()->m_data.iData1, headMissionQueueNode()->m_data.iData2)) { bAction = true; } break; case MISSION_BOMBARD: if (pLoopUnit->bombard()) { bAction = true; } break; case MISSION_PILLAGE: if (pLoopUnit->pillage()) { bAction = true; } break; case MISSION_SABOTAGE: if (pLoopUnit->sabotage()) { bAction = true; } break; case MISSION_DESTROY: if (pLoopUnit->destroy()) { bAction = true; } break; case MISSION_STEAL_PLANS: if (pLoopUnit->stealPlans()) { bAction = true; } break; case MISSION_FOUND: if (pLoopUnit->found()) { bAction = true; } break; case MISSION_SPREAD: if (pLoopUnit->spread((ReligionTypes)(headMissionQueueNode()->m_data.iData1))) { bAction = true; } break; case MISSION_JOIN: if (pLoopUnit->join((SpecialistTypes)(headMissionQueueNode()->m_data.iData1))) { bAction = true; } break; case MISSION_CONSTRUCT: if (pLoopUnit->construct((BuildingTypes)(headMissionQueueNode()->m_data.iData1))) { bAction = true; } break; case MISSION_DISCOVER: if (pLoopUnit->discover()) { bAction = true; } break; case MISSION_HURRY: if (pLoopUnit->hurry()) { bAction = true; } break; case MISSION_TRADE: if (pLoopUnit->trade()) { bAction = true; } break; case MISSION_GREAT_WORK: if (pLoopUnit->greatWork()) { bAction = true; } break; case MISSION_GOLDEN_AGE: if (pLoopUnit->goldenAge()) { bAction = true; } break; case MISSION_BUILD: break; case MISSION_LEAD: if (pLoopUnit->lead(headMissionQueueNode()->m_data.iData1)) { bAction = true; } break; default: FAssert(false); break; } if (getNumUnits() == 0) { break; } if (headMissionQueueNode() == NULL) { break; } } } } if ((getNumUnits() > 0) && (headMissionQueueNode()!= NULL)) { if (bAction) { if (isHuman()) { if (plot()->isVisibleToWatchingHuman()) { updateMissionTimer(); } } } if (bNuke) { setMissionTimer(GC.getMissionInfo(MISSION_NUKE).getTime()); } if (!isBusy()) { if (bDelete) { if (getOwnerINLINE() == GC.getGameINLINE().getActivePlayer()) { if (IsSelected()) { gDLL->getInterfaceIFace()->changeCycleSelectionCounter((GET_PLAYER(getOwnerINLINE()).isOption(PLAYEROPTION_QUICK_MOVES))? 1 : 2); } } deleteMissionQueueNode(headMissionQueueNode()); } else if (getActivityType() == ACTIVITY_MISSION) { continueMission(); } } } } void CvSelectionGroup::continueMission(int iSteps) { CvUnit* pTargetUnit; bool bDone; bool bAction; FAssert(!isBusy()); FAssert(headMissionQueueNode()!= NULL); FAssert(getOwnerINLINE()!= NO_PLAYER); FAssert(getActivityType() == ACTIVITY_MISSION); if (headMissionQueueNode() == NULL) { // just in case... setActivityType(ACTIVITY_AWAKE); return; } bDone = false; bAction = false; if (headMissionQueueNode()->m_data.iPushTurn == GC.getGameINLINE().getGameTurn()) { if (headMissionQueueNode()->m_data.eMissionType == MISSION_MOVE_TO) { if (groupAttack(headMissionQueueNode()->m_data.iData1, headMissionQueueNode()->m_data.iData2, headMissionQueueNode()->m_data.iFlags)) { bDone = true; } } } if (canAllMove()) { if (getNumUnits() > 0) { if (!bDone && canAllMove()) { switch (headMissionQueueNode()->m_data.eMissionType) { case MISSION_MOVE_TO: if (getDomainType() == DOMAIN_AIR) { groupPathTo(headMissionQueueNode()->m_data.iData1, headMissionQueueNode()->m_data.iData2, headMissionQueueNode()->m_data.iFlags); bDone = true; } else if (groupPathTo(headMissionQueueNode()->m_data.iData1, headMissionQueueNode()->m_data.iData2, headMissionQueueNode()->m_data.iFlags)) { bAction = true; if (getNumUnits() > 0) { if (!canAllMove()) { if (headMissionQueueNode()!= NULL) { if (groupAmphibMove(GC.getMapINLINE().plotINLINE(headMissionQueueNode()->m_data.iData1, headMissionQueueNode()->m_data.iData2), headMissionQueueNode()->m_data.iFlags)) { bAction = false; bDone = true; } } } } } else { bDone = true; } break; case MISSION_ROUTE_TO: if (groupRoadTo(headMissionQueueNode()->m_data.iData1, headMissionQueueNode()->m_data.iData2, headMissionQueueNode()->m_data.iFlags)) { bAction = true; } else { bDone = true; } break; case MISSION_MOVE_TO_UNIT: pTargetUnit = GET_PLAYER((PlayerTypes)headMissionQueueNode()->m_data.iData1).getUnit(headMissionQueueNode()->m_data.iData2); if ((pTargetUnit!= NULL) && groupPathTo(pTargetUnit->getX_INLINE(), pTargetUnit->getY_INLINE(), headMissionQueueNode()->m_data.iFlags)) { bAction = true; } else { bDone = true; } break; case MISSION_SKIP: case MISSION_SLEEP: case MISSION_FORTIFY: case MISSION_AIRPATROL: case MISSION_HEAL: case MISSION_SENTRY: FAssert(false); break; case MISSION_AIRLIFT: case MISSION_NUKE: case MISSION_RECON: case MISSION_AIRBOMB: case MISSION_BOMBARD: case MISSION_PILLAGE: case MISSION_SABOTAGE: case MISSION_DESTROY: case MISSION_STEAL_PLANS: case MISSION_FOUND: case MISSION_SPREAD: case MISSION_JOIN: case MISSION_CONSTRUCT: case MISSION_DISCOVER: case MISSION_HURRY: case MISSION_TRADE: case MISSION_GREAT_WORK: case MISSION_GOLDEN_AGE: case MISSION_LEAD: break; case MISSION_BUILD: if (!groupBuild((BuildTypes)(headMissionQueueNode()->m_data.iData1))) { bDone = true; } break; default: FAssert(false); break; } } } } if ((getNumUnits() > 0) && (headMissionQueueNode()!= NULL)) { if (!bDone) { switch (headMissionQueueNode()->m_data.eMissionType) { case MISSION_MOVE_TO: if (at(headMissionQueueNode()->m_data.iData1, headMissionQueueNode()->m_data.iData2)) { bDone = true; } break; case MISSION_ROUTE_TO: if (at(headMissionQueueNode()->m_data.iData1, headMissionQueueNode()->m_data.iData2)) { if (getBestBuildRoute(plot()) == NO_ROUTE) { bDone = true; } } break; case MISSION_MOVE_TO_UNIT: pTargetUnit = GET_PLAYER((PlayerTypes)headMissionQueueNode()->m_data.iData1).getUnit(headMissionQueueNode()->m_data.iData2); if ((pTargetUnit == NULL) || atPlot(pTargetUnit->plot())) { bDone = true; } break; case MISSION_SKIP: case MISSION_SLEEP: case MISSION_FORTIFY: case MISSION_AIRPATROL: case MISSION_HEAL: case MISSION_SENTRY: FAssert(false); break; case MISSION_AIRLIFT: case MISSION_NUKE: case MISSION_RECON: case MISSION_AIRBOMB: case MISSION_BOMBARD: case MISSION_PILLAGE: case MISSION_SABOTAGE: case MISSION_DESTROY: case MISSION_STEAL_PLANS: case MISSION_FOUND: case MISSION_SPREAD: case MISSION_JOIN: case MISSION_CONSTRUCT: case MISSION_DISCOVER: case MISSION_HURRY: case MISSION_TRADE: case MISSION_GREAT_WORK: case MISSION_GOLDEN_AGE: case MISSION_LEAD: bDone = true; break; case MISSION_BUILD: // XXX what happens if two separate worker groups are both building the mine... /*if (plot()->getBuildType()!= ((BuildTypes)(headMissionQueueNode()->m_data.iData1))) { bDone = true; }*/ break; default: FAssert(false); break; } } } if ((getNumUnits() > 0) && (headMissionQueueNode()!= NULL)) { if (bAction) { if (bDone ||!canAllMove()) { if (plot()->isVisibleToWatchingHuman()) { updateMissionTimer(iSteps); getHeadUnit()->ExecuteMove(((float)(getMissionTimer() * gDLL->getMillisecsPerTurn())) / 1000.0f); if (GC.getGameINLINE().showAllMoves(getTeam())) { if (GC.getGameINLINE().getActivePlayer()!= NO_PLAYER) { if (getOwnerINLINE()!= GC.getGameINLINE().getActivePlayer()) { if (plot()->isActiveVisible(false)) { gDLL->getInterfaceIFace()->lookAt(plot()->getPoint(), CAMERALOOKAT_NORMAL); } } } } } } } if (bDone) { if (!isBusy()) { if (getOwnerINLINE() == GC.getGameINLINE().getActivePlayer()) { if (IsSelected()) { if ((headMissionQueueNode()->m_data.eMissionType == MISSION_MOVE_TO) || (headMissionQueueNode()->m_data.eMissionType == MISSION_ROUTE_TO) || (headMissionQueueNode()->m_data.eMissionType == MISSION_MOVE_TO_UNIT)) { gDLL->getInterfaceIFace()->changeCycleSelectionCounter((GET_PLAYER(getOwnerINLINE()).isOption(PLAYEROPTION_QUICK_MOVES))? 1 : 2); } } } deleteMissionQueueNode(headMissionQueueNode()); } } else { if (canAllMove()) { continueMission(iSteps + 1); } else if (!isBusy()) { if (getOwnerINLINE() == GC.getGameINLINE().getActivePlayer()) { if (IsSelected()) { gDLL->getInterfaceIFace()->changeCycleSelectionCounter(1); } } } } } } bool CvSelectionGroup::canDoCommand(CommandTypes eCommand, int iData1, int iData2, bool bTestVisible) { CLLNode<IDInfo>* pUnitNode; CvUnit* pLoopUnit; if (isBusy()) { return false; } pUnitNode = headUnitNode(); while (pUnitNode!= NULL) { pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = nextUnitNode(pUnitNode); if (pLoopUnit->canDoCommand(eCommand, iData1, iData2, bTestVisible, false)) { return true; } } return false; } // Returns true if one of the units can support the interface mode... bool CvSelectionGroup::canDoInterfaceMode(InterfaceModeTypes eInterfaceMode) { CLLNode<IDInfo>* pUnitNode; CvUnit* pLoopUnit; FAssertMsg(eInterfaceMode!= NO_INTERFACEMODE, "InterfaceMode is not assigned a valid value"); if (isBusy()) { return false; } pUnitNode = headUnitNode(); while (pUnitNode!= NULL) { pLoopUnit = ::getUnit(pUnitNode->m_data); switch (eInterfaceMode) { case INTERFACEMODE_GO_TO: if ((getDomainType()!= DOMAIN_AIR) && (getDomainType()!= DOMAIN_IMMOBILE)) { return true; } break; case INTERFACEMODE_GO_TO_TYPE: if ((getDomainType()!= DOMAIN_AIR) && (getDomainType()!= DOMAIN_IMMOBILE)) { if (pLoopUnit->plot()->plotCount(PUF_isUnitType, pLoopUnit->getUnitType(), -1, pLoopUnit->getOwnerINLINE()) > 1) { return true; } } break; case INTERFACEMODE_GO_TO_ALL: if ((getDomainType()!= DOMAIN_AIR) && (getDomainType()!= DOMAIN_IMMOBILE)) { if (pLoopUnit->plot()->plotCount(NULL, -1, -1, pLoopUnit->getOwnerINLINE()) > 1) { return true; } } break; case INTERFACEMODE_ROUTE_TO: if (pLoopUnit->AI_getUnitAIType() == UNITAI_WORKER) { if (pLoopUnit->canBuildRoute()) { return true; } } break; case INTERFACEMODE_AIRLIFT: if (pLoopUnit->canAirlift(pLoopUnit->plot())) { return true; } break; case INTERFACEMODE_NUKE: if (pLoopUnit->canNuke(pLoopUnit->plot())) { return true; } break; case INTERFACEMODE_RECON: if (pLoopUnit->canRecon(pLoopUnit->plot())) { return true; } break; case INTERFACEMODE_AIRBOMB: if (pLoopUnit->canAirBomb(pLoopUnit->plot())) { return true; } break; case INTERFACEMODE_AIRSTRIKE: if (pLoopUnit->getDomainType() == DOMAIN_AIR) { if (pLoopUnit->canAirAttack()) { return true; } } break; case INTERFACEMODE_REBASE: if (pLoopUnit->getDomainType() == DOMAIN_AIR) { return true; } break; } pUnitNode = nextUnitNode(pUnitNode); } return false; } // Returns true if one of the units can execute the interface mode at the specified plot... bool CvSelectionGroup::canDoInterfaceModeAt(InterfaceModeTypes eInterfaceMode, CvPlot* pPlot) { CLLNode<IDInfo>* pUnitNode; CvUnit* pLoopUnit; FAssertMsg(eInterfaceMode!= NO_INTERFACEMODE, "InterfaceMode is not assigned a valid value"); pUnitNode = headUnitNode(); while (pUnitNode!= NULL) { pLoopUnit = ::getUnit(pUnitNode->m_data); switch (eInterfaceMode) { case INTERFACEMODE_AIRLIFT: if (pLoopUnit!= NULL) { if (pLoopUnit->canAirliftAt(pLoopUnit->plot(), pPlot->getX_INLINE(), pPlot->getY_INLINE())) { return true; } } break; case INTERFACEMODE_NUKE: if (pLoopUnit!= NULL) { if (pLoopUnit->canNukeAt(pLoopUnit->plot(), pPlot->getX_INLINE(), pPlot->getY_INLINE())) { return true; } } break; case INTERFACEMODE_RECON: if (pLoopUnit!= NULL) { if (pLoopUnit->canReconAt(pLoopUnit->plot(), pPlot->getX_INLINE(), pPlot->getY_INLINE())) { return true; } } break; case INTERFACEMODE_AIRBOMB: if (pLoopUnit!= NULL) { if (pLoopUnit->canAirBombAt(pLoopUnit->plot(), pPlot->getX_INLINE(), pPlot->getY_INLINE())) { return true; } } break; case INTERFACEMODE_AIRSTRIKE: if (pLoopUnit!= NULL) { if (pLoopUnit->canMoveInto(pPlot, true)) { return true; } } break; case INTERFACEMODE_REBASE: if (pLoopUnit!= NULL) { if (pLoopUnit->canMoveInto(pPlot)) { return true; } } break; default: return true; break; } pUnitNode = nextUnitNode(pUnitNode); } return false; } bool CvSelectionGroup::isHuman() { if (getOwnerINLINE()!= NO_PLAYER) { return GET_PLAYER(getOwnerINLINE()).isHuman(); } return true; } bool CvSelectionGroup::isBusy() { CLLNode<IDInfo>* pUnitNode; CvUnit* pLoopUnit; CvPlot* pPlot; if (getNumUnits() == 0) { return false; } if (getMissionTimer() > 0) { return true; } pPlot = plot(); pUnitNode = headUnitNode(); while (pUnitNode!= NULL) { pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = nextUnitNode(pUnitNode); if (pLoopUnit!= NULL) { if (pLoopUnit->isCombat()) { return true; } } } return false; } bool CvSelectionGroup::isCargoBusy() { CLLNode<IDInfo>* pUnitNode1; CLLNode<IDInfo>* pUnitNode2; CvUnit* pLoopUnit1; CvUnit* pLoopUnit2; CvPlot* pPlot; if (getNumUnits() == 0) { return false; } pPlot = plot(); pUnitNode1 = headUnitNode(); while (pUnitNode1!= NULL) { pLoopUnit1 = ::getUnit(pUnitNode1->m_data); pUnitNode1 = nextUnitNode(pUnitNode1); if (pLoopUnit1!= NULL) { if (pLoopUnit1->getCargo() > 0) { pUnitNode2 = pPlot->headUnitNode(); while (pUnitNode2!= NULL) { pLoopUnit2 = ::getUnit(pUnitNode2->m_data); pUnitNode2 = pPlot->nextUnitNode(pUnitNode2); if (pLoopUnit2->getTransportUnit() == pLoopUnit1) { if (pLoopUnit2->getGroup()->isBusy()) { return true; } } } } } } return false; } int CvSelectionGroup::baseMoves() { CLLNode<IDInfo>* pUnitNode; CvUnit* pLoopUnit; int iValue; int iBestValue; iBestValue = MAX_INT; pUnitNode = headUnitNode(); while (pUnitNode!= NULL) { pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = nextUnitNode(pUnitNode); iValue = pLoopUnit->baseMoves(); if (iValue < iBestValue) { iBestValue = iValue; } } return iBestValue; } bool CvSelectionGroup::isWaiting() const { return ((getActivityType() == ACTIVITY_HOLD) || (getActivityType() == ACTIVITY_SLEEP) || (getActivityType() == ACTIVITY_HEAL) || (getActivityType() == ACTIVITY_SENTRY) || (getActivityType() == ACTIVITY_INTERCEPT)); } bool CvSelectionGroup::isFull() { CLLNode<IDInfo>* pUnitNode; CvUnit* pLoopUnit; if (getNumUnits() > 0) { pUnitNode = headUnitNode(); while (pUnitNode!= NULL) { pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = nextUnitNode(pUnitNode); if (!(pLoopUnit->isFull())) { return false; } } return true; } return false; } bool CvSelectionGroup::hasCargo() { CLLNode<IDInfo>* pUnitNode; CvUnit* pLoopUnit; pUnitNode = headUnitNode(); while (pUnitNode!= NULL) { pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = nextUnitNode(pUnitNode); if (pLoopUnit->hasCargo()) { return true; } } return false; } bool CvSelectionGroup::canAllMove() { CLLNode<IDInfo>* pUnitNode; CvUnit* pLoopUnit; if (getNumUnits() > 0) { pUnitNode = headUnitNode(); while (pUnitNode!= NULL) { pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = nextUnitNode(pUnitNode); if (!(pLoopUnit->canMove())) { return false; } } return true; } return false; } bool CvSelectionGroup::canAnyMove() { CLLNode<IDInfo>* pUnitNode; CvUnit* pLoopUnit; pUnitNode = headUnitNode(); while (pUnitNode!= NULL) { pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = nextUnitNode(pUnitNode); if (pLoopUnit->canMove()) { return true; } } return false; } bool CvSelectionGroup::hasMoved() { CLLNode<IDInfo>* pUnitNode; CvUnit* pLoopUnit; pUnitNode = headUnitNode(); while (pUnitNode!= NULL) { pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = nextUnitNode(pUnitNode); if (pLoopUnit->hasMoved()) { return true; } } return false; } bool CvSelectionGroup::canEnterTerritory(TeamTypes eTeam, bool bIgnoreRightOfPassage) const { CLLNode<IDInfo>* pUnitNode; CvUnit* pLoopUnit; if (getNumUnits() > 0) { pUnitNode = headUnitNode(); while (pUnitNode!= NULL) { pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = nextUnitNode(pUnitNode); if (!(pLoopUnit->canEnterTerritory(eTeam, bIgnoreRightOfPassage))) { return false; } } return true; } return false; } bool CvSelectionGroup::canEnterArea(TeamTypes eTeam, const CvArea* pArea, bool bIgnoreRightOfPassage) const { CLLNode<IDInfo>* pUnitNode; CvUnit* pLoopUnit; if (getNumUnits() > 0) { pUnitNode = headUnitNode(); while (pUnitNode!= NULL) { pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = nextUnitNode(pUnitNode); if (!(pLoopUnit->canEnterArea(eTeam, pArea, bIgnoreRightOfPassage))) { return false; } } return true; } return false; } bool CvSelectionGroup::canMoveInto(CvPlot* pPlot, bool bAttack) { CLLNode<IDInfo>* pUnitNode; CvUnit* pLoopUnit; if (getNumUnits() > 0) { pUnitNode = headUnitNode(); while (pUnitNode!= NULL) { pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = nextUnitNode(pUnitNode); if (pLoopUnit->canMoveInto(pPlot, bAttack)) { return true; } } } return false; } bool CvSelectionGroup::canMoveOrAttackInto(CvPlot* pPlot, bool bDeclareWar) { CLLNode<IDInfo>* pUnitNode; CvUnit* pLoopUnit; if (getNumUnits() > 0) { pUnitNode = headUnitNode(); while (pUnitNode!= NULL) { pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = nextUnitNode(pUnitNode); if (pLoopUnit->canMoveOrAttackInto(pPlot, bDeclareWar)) { return true; } } } return false; } bool CvSelectionGroup::canMoveThrough(CvPlot* pPlot) { CLLNode<IDInfo>* pUnitNode; CvUnit* pLoopUnit; if (getNumUnits() > 0) { pUnitNode = headUnitNode(); while (pUnitNode!= NULL) { pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = nextUnitNode(pUnitNode); if (!(pLoopUnit->canMoveThrough(pPlot))) { return false; } } return true; } return false; } bool CvSelectionGroup::canFight() { CLLNode<IDInfo>* pUnitNode; CvUnit* pLoopUnit; pUnitNode = headUnitNode(); while (pUnitNode!= NULL) { pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = nextUnitNode(pUnitNode); if (pLoopUnit->canFight()) { return true; } } return false; } bool CvSelectionGroup::canDefend() { CLLNode<IDInfo>* pUnitNode; CvUnit* pLoopUnit; pUnitNode = headUnitNode(); while (pUnitNode!= NULL) { pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = nextUnitNode(pUnitNode); if (pLoopUnit->canDefend()) { return true; } } return false; } bool CvSelectionGroup::alwaysInvisible() { CLLNode<IDInfo>* pUnitNode; CvUnit* pLoopUnit; if (getNumUnits() > 0) { pUnitNode = headUnitNode(); while (pUnitNode!= NULL) { pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = nextUnitNode(pUnitNode); if (!(pLoopUnit->alwaysInvisible())) { return false; } } return true; } return false; } int CvSelectionGroup::countNumUnitAIType(UnitAITypes eUnitAI) { CLLNode<IDInfo>* pUnitNode; CvUnit* pLoopUnit; int iCount; FAssertMsg(headUnitNode()!= NULL, "headUnitNode() is not expected to be equal with NULL"); iCount = 0; pUnitNode = headUnitNode(); while (pUnitNode!= NULL) { pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = nextUnitNode(pUnitNode); if (pLoopUnit->AI_getUnitAIType() == eUnitAI) { iCount++; } } return iCount; } bool CvSelectionGroup::hasWorker() { return ((countNumUnitAIType(UNITAI_WORKER) > 0) || (countNumUnitAIType(UNITAI_WORKER_SEA) > 0)); } bool CvSelectionGroup::IsSelected() { CLLNode<IDInfo>* pUnitNode; CvUnit* pLoopUnit; pUnitNode = headUnitNode(); while (pUnitNode!= NULL) { pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = nextUnitNode(pUnitNode); if (pLoopUnit->IsSelected()) { return true; } } return false; } void CvSelectionGroup::NotifyEntity(MissionTypes eMission) { CLLNode<IDInfo>* pUnitNode; pUnitNode = headUnitNode(); while (pUnitNode!= NULL) { ::getUnit(pUnitNode->m_data)->NotifyEntity(eMission); pUnitNode = nextUnitNode(pUnitNode); } } void CvSelectionGroup::airCircle(bool bStart) { CLLNode<IDInfo>* pUnitNode; pUnitNode = headUnitNode(); while (pUnitNode!= NULL) { ::getUnit(pUnitNode->m_data)->airCircle(bStart); pUnitNode = nextUnitNode(pUnitNode); } } int CvSelectionGroup::getX() const { CvUnit* pHeadUnit; pHeadUnit = getHeadUnit(); if (pHeadUnit!= NULL) { return getHeadUnit()->getX_INLINE(); } else { return INVALID_PLOT_COORD; } } int CvSelectionGroup::getY() const { CvUnit* pHeadUnit; pHeadUnit = getHeadUnit(); if (pHeadUnit!= NULL) { return getHeadUnit()->getY_INLINE(); } else { return INVALID_PLOT_COORD; } } bool CvSelectionGroup::at(int iX, int iY) const { return((getX() == iX) && (getY() == iY)); } bool CvSelectionGroup::atPlot( const CvPlot* pPlot) const { return (plot() == pPlot); } CvPlot* CvSelectionGroup::plot() const { CvUnit* pHeadUnit; pHeadUnit = getHeadUnit(); if (pHeadUnit!= NULL) { return getHeadUnit()->plot(); } else { return NULL; } } CvArea* CvSelectionGroup::area() const { CvUnit* pHeadUnit; pHeadUnit = getHeadUnit(); if (pHeadUnit!= NULL) { return getHeadUnit()->area(); } else { return NULL; } } DomainTypes CvSelectionGroup::getDomainType() const { CvUnit* pHeadUnit; pHeadUnit = getHeadUnit(); if (pHeadUnit!= NULL) { return getHeadUnit()->getDomainType(); } else { return NO_DOMAIN; } } RouteTypes CvSelectionGroup::getBestBuildRoute(CvPlot* pPlot, BuildTypes* peBestBuild) { PROFILE_FUNC(); CLLNode<IDInfo>* pUnitNode; CvUnit* pLoopUnit; RouteTypes eRoute; RouteTypes eBestRoute; int iValue; int iBestValue; int iI; if (peBestBuild!= NULL) { *peBestBuild = NO_BUILD; } iBestValue = 0; eBestRoute = NO_ROUTE; pUnitNode = headUnitNode(); while (pUnitNode!= NULL) { pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = nextUnitNode(pUnitNode); for (iI = 0; iI < GC.getNumBuildInfos(); iI++) { eRoute = ((RouteTypes)(GC.getBuildInfo((BuildTypes) iI).getRoute())); if (eRoute!= NO_ROUTE) { if (pLoopUnit->canBuild(pPlot, ((BuildTypes)iI))) { iValue = GC.getRouteInfo(eRoute).getValue(); if (iValue > iBestValue) { iBestValue = iValue; eBestRoute = eRoute; if (peBestBuild!= NULL) { *peBestBuild = ((BuildTypes)iI); } } } } } } return eBestRoute; } // Returns true if group was bumped... bool CvSelectionGroup::groupDeclareWar(CvPlot* pPlot) { int iNumUnits; if (!AI_isDeclareWar()) { return false; } iNumUnits = getNumUnits(); if (!canEnterArea(pPlot->getTeam(), pPlot->area(), true)) { if (pPlot->getTeam()!= NO_TEAM && GET_TEAM(getTeam()).AI_isSneakAttackReady(pPlot->getTeam())) { if (GET_TEAM(getTeam()).canDeclareWar(pPlot->getTeam())) { GET_TEAM(getTeam()).declareWar(pPlot->getTeam(), true); } } } return (iNumUnits!= getNumUnits()); } // Returns true if attack was made... bool CvSelectionGroup::groupAttack(int iX, int iY, int iFlags) { CvUnit* pBestAttackUnit; CvPlot* pDestPlot; bool bStack; bool bAttack; pDestPlot = GC.getMapINLINE().plotINLINE(iX, iY); FAssertMsg(pDestPlot!= NULL, "DestPlot is not assigned a valid value"); bStack = (isHuman() && ((getDomainType() == DOMAIN_AIR) || GET_PLAYER(getOwnerINLINE()).isOption(PLAYEROPTION_STACK_ATTACK))); bAttack = false; if (getNumUnits() > 0) { if ((getDomainType() == DOMAIN_AIR) || (stepDistance(getX(), getY(), pDestPlot->getX_INLINE(), pDestPlot->getY_INLINE()) == 1)) { if ((iFlags & MOVE_DIRECT_ATTACK) || (getDomainType() == DOMAIN_AIR) || (generatePath(plot(), pDestPlot, iFlags) && (getPathFirstPlot() == pDestPlot))) { pBestAttackUnit = AI_getBestGroupAttacker(pDestPlot, true); if (pBestAttackUnit) { bool bNoBlitz = (!pBestAttackUnit->isBlitz() ||!pBestAttackUnit->isMadeAttack()); if (groupDeclareWar(pDestPlot)) { return true; } while (true) { pBestAttackUnit = AI_getBestGroupAttacker(pDestPlot, false, false, bNoBlitz); if (pBestAttackUnit == NULL) { break; } bAttack = true; if (getNumUnits() > 1) { if (pBestAttackUnit->plot()->isFighting() || pDestPlot->isFighting()) { break; } pBestAttackUnit->attack(pDestPlot, bStack); } else { pBestAttackUnit->attack(pDestPlot, false); break; } if (!bStack) { break; } } } } } } return bAttack; } void CvSelectionGroup::groupMove(CvPlot* pPlot, bool bCombat, CvUnit* pCombatUnit) { PROFILE_FUNC(); CLLNode<IDInfo>* pUnitNode; CvUnit* pLoopUnit; pUnitNode = headUnitNode(); while (pUnitNode!= NULL) { pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = nextUnitNode(pUnitNode); if ((pLoopUnit->canMove() && ((bCombat && (!(pLoopUnit->isNoCapture()) ||!(pPlot->isEnemyCity(getTeam()))))? pLoopUnit->canMoveOrAttackInto(pPlot) : pLoopUnit->canMoveInto(pPlot))) || (pLoopUnit == pCombatUnit)) { pLoopUnit->move(pPlot,!bCombat); } else { pLoopUnit->joinGroup(NULL, true); } } } // Returns true if move was made... bool CvSelectionGroup::groupPathTo(int iX, int iY, int iFlags) { CvPlot* pDestPlot; CvPlot* pPathPlot; if (at(iX, iY)) { return false; // XXX is this necessary? } FAssert(!isBusy()); FAssert(getOwnerINLINE()!= NO_PLAYER); FAssert(headMissionQueueNode()!= NULL); pDestPlot = GC.getMapINLINE().plotINLINE(iX, iY); FAssertMsg(pDestPlot!= NULL, "DestPlot is not assigned a valid value"); FAssertMsg(canAllMove(), "canAllMove is expected to be true"); if (getDomainType() == DOMAIN_AIR) { if (!canMoveInto(pDestPlot)) { return false; } pPathPlot = pDestPlot; } else { if (!generatePath(plot(), pDestPlot, iFlags)) { return false; } pPathPlot = getPathFirstPlot(); if (groupAmphibMove(pPathPlot, iFlags)) { return false; } } if (groupDeclareWar(pPathPlot)) { return false; } groupMove(pPathPlot, false); return true; } // Returns true if move was made... bool CvSelectionGroup::groupRoadTo(int iX, int iY, int iFlags) { CvPlot* pPlot; RouteTypes eBestRoute; BuildTypes eBestBuild; if (!AI_isControlled() ||!at(iX, iY) || (getLengthMissionQueue() == 1)) { pPlot = plot(); eBestRoute = getBestBuildRoute(pPlot, &eBestBuild); if (eBestBuild!= NO_BUILD) { groupBuild(eBestBuild); return true; } } return groupPathTo(iX, iY, iFlags); } // Returns true if build should continue... bool CvSelectionGroup::groupBuild(BuildTypes eBuild) { CLLNode<IDInfo>* pUnitNode; CvUnit* pLoopUnit; CvPlot* pPlot; bool bContinue; FAssert(getOwnerINLINE()!= NO_PLAYER); bContinue = false; pPlot = plot(); if (GC.getBuildInfo(eBuild).getImprovement()!= NO_IMPROVEMENT) { if (AI_isControlled()) { if (GET_PLAYER(getOwnerINLINE()).isOption(PLAYEROPTION_SAFE_AUTOMATION)) { if (pPlot->getImprovementType()!= NO_IMPROVEMENT) { return false; } } } } pUnitNode = headUnitNode(); while (pUnitNode!= NULL) { pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = nextUnitNode(pUnitNode); FAssertMsg(pLoopUnit->atPlot(pPlot), "pLoopUnit is expected to be at pPlot"); if (pLoopUnit->canBuild(pPlot, eBuild)) { bContinue = true; if (pLoopUnit->build(eBuild)) { bContinue = false; break; } } } return bContinue; } bool CvSelectionGroup::isAmphibPlot(CvPlot* pPlot) { return ((getDomainType() == DOMAIN_SEA) && pPlot->isCoastalLand() &&!(pPlot->isFriendlyCity(getHeadTeam()))); } // Returns true if attempted an amphib landing... bool CvSelectionGroup::groupAmphibMove(CvPlot* pPlot, int iFlags) { CLLNode<IDInfo>* pUnitNode1; CLLNode<IDInfo>* pUnitNode2; CvUnit* pLoopUnit1; CvUnit* pLoopUnit2; FAssert(getOwnerINLINE()!= NO_PLAYER); if (groupDeclareWar(pPlot)) { return true; } if (isAmphibPlot(pPlot)) { if (stepDistance(getX(), getY(), pPlot->getX_INLINE(), pPlot->getY_INLINE()) == 1) { pUnitNode1 = headUnitNode(); while (pUnitNode1!= NULL) { pLoopUnit1 = ::getUnit(pUnitNode1->m_data); pUnitNode1 = nextUnitNode(pUnitNode1); if ((pLoopUnit1->getCargo() > 0) && (pLoopUnit1->domainCargo() == DOMAIN_LAND)) { pUnitNode2 = plot()->headUnitNode(); while (pUnitNode2!= NULL) { pLoopUnit2 = ::getUnit(pUnitNode2->m_data); pUnitNode2 = plot()->nextUnitNode(pUnitNode2); if (pLoopUnit2->getTransportUnit() == pLoopUnit1) { if (pLoopUnit2->isGroupHead()) { pLoopUnit2->getGroup()->pushMission(MISSION_MOVE_TO, pPlot->getX_INLINE(), pPlot->getY_INLINE(), (MOVE_IGNORE_DANGER | iFlags)); } } } } } return true; } } return false; } bool CvSelectionGroup::readyToSelect(bool bAny) { return (readyToMove(bAny) &&!isAutomated()); } bool CvSelectionGroup::readyToMove(bool bAny) { return (((bAny)? canAnyMove() : canAllMove()) && (headMissionQueueNode() == NULL) && (getActivityType() == ACTIVITY_AWAKE) &&!isBusy() &&!isCargoBusy()); } bool CvSelectionGroup::readyToAuto() { return (canAllMove() && (headMissionQueueNode()!= NULL)); } int CvSelectionGroup::getID() { return m_iID; } void CvSelectionGroup::setID(int iID) { m_iID = iID; } PlayerTypes CvSelectionGroup::getOwner() const { return getOwnerINLINE(); } TeamTypes CvSelectionGroup::getTeam() const { if (getOwnerINLINE()!= NO_PLAYER) { return GET_PLAYER(getOwnerINLINE()).getTeam(); } return NO_TEAM; } int CvSelectionGroup::getMissionTimer() { return m_iMissionTimer; } void CvSelectionGroup::setMissionTimer(int iNewValue) { FAssert(getOwnerINLINE()!= NO_PLAYER); m_iMissionTimer = iNewValue; FAssert(getMissionTimer() >= 0); } void CvSelectionGroup::changeMissionTimer(int iChange) { setMissionTimer(getMissionTimer() + iChange); } void CvSelectionGroup::updateMissionTimer(int iSteps) { CvUnit* pTargetUnit; CvPlot* pTargetPlot; int iTime; if (!isHuman() &&!(GC.getGameINLINE().showAllMoves(getTeam()))) { iTime = 0; } else if (headMissionQueueNode()!= NULL) { iTime = GC.getMissionInfo((MissionTypes)(headMissionQueueNode()->m_data.eMissionType)).getTime(); if ((headMissionQueueNode()->m_data.eMissionType == MISSION_MOVE_TO) || (headMissionQueueNode()->m_data.eMissionType == MISSION_ROUTE_TO) || (headMissionQueueNode()->m_data.eMissionType == MISSION_MOVE_TO_UNIT)) { if (headMissionQueueNode()->m_data.eMissionType == MISSION_MOVE_TO_UNIT) { pTargetUnit = GET_PLAYER((PlayerTypes)headMissionQueueNode()->m_data.iData1).getUnit(headMissionQueueNode()->m_data.iData2); if (pTargetUnit!= NULL) { pTargetPlot = pTargetUnit->plot(); } else { pTargetPlot = NULL; } } else { pTargetPlot = GC.getMapINLINE().plotINLINE(headMissionQueueNode()->m_data.iData1, headMissionQueueNode()->m_data.iData2); } if (atPlot(pTargetPlot)) { iTime += iSteps; } else { iTime = min(iTime, 2); } } if (isHuman() && (isAutomated() || (GET_PLAYER((GC.getGameINLINE().isNetworkMultiPlayer())? getOwnerINLINE() : GC.getGameINLINE().getActivePlayer()).isOption(PLAYEROPTION_QUICK_MOVES)))) { iTime = min(iTime, 1); } } else { iTime = 0; } setMissionTimer(iTime); } bool CvSelectionGroup::isForceUpdate() { return m_bForceUpdate; } void CvSelectionGroup::setForceUpdate(bool bNewValue) { m_bForceUpdate = bNewValue; } ActivityTypes CvSelectionGroup::getActivityType() const { return m_eActivityType; } void CvSelectionGroup::setActivityType(ActivityTypes eNewValue) { CLLNode<IDInfo>* pUnitNode; CvUnit* pLoopUnit; CvPlot* pPlot; FAssert(getOwnerINLINE()!= NO_PLAYER); if (getActivityType()!= eNewValue) { pPlot = plot(); if (getActivityType() == ACTIVITY_INTERCEPT) { airCircle(false); } m_eActivityType = eNewValue; if (getActivityType() == ACTIVITY_INTERCEPT) { airCircle(true); } if (getActivityType()!= ACTIVITY_MISSION) { pUnitNode = headUnitNode(); while (pUnitNode!= NULL) { pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = nextUnitNode(pUnitNode); pLoopUnit->NotifyEntity(MISSION_IDLE); } if (getTeam() == GC.getGameINLINE().getActiveTeam()) { if (pPlot!= NULL) { pPlot->setFlagDirty(true); } } } if (pPlot == gDLL->getInterfaceIFace()->getSelectionPlot()) { gDLL->getInterfaceIFace()->setDirty(PlotListButtons_DIRTY_BIT, true); gDLL->getInterfaceIFace()->setDirty(SelectionButtons_DIRTY_BIT, true); } } } AutomateTypes CvSelectionGroup::getAutomateType() { return m_eAutomateType; } bool CvSelectionGroup::isAutomated() { return (getAutomateType()!= NO_AUTOMATE); } void CvSelectionGroup::setAutomateType(AutomateTypes eNewValue) { FAssert(getOwnerINLINE()!= NO_PLAYER); if (getAutomateType()!= eNewValue) { m_eAutomateType = eNewValue; clearMissionQueue(); setActivityType(ACTIVITY_AWAKE); } } FAStarNode* CvSelectionGroup::getPathLastNode() const { return gDLL->getFAStarIFace()->GetLastNode(&GC.getPathFinder()); } CvPlot* CvSelectionGroup::getPathFirstPlot() const { FAStarNode* pNode; pNode = getPathLastNode(); if (pNode->m_pParent == NULL) { return GC.getMapINLINE().plotSorenINLINE(pNode->m_iX, pNode->m_iY); } while (pNode!= NULL) { if (pNode->m_pParent->m_pParent == NULL) { return GC.getMapINLINE().plotSorenINLINE(pNode->m_iX, pNode->m_iY); } pNode = pNode->m_pParent; } FAssert(false); return NULL; } CvPlot* CvSelectionGroup::getPathEndTurnPlot() const { FAStarNode* pNode; pNode = getPathLastNode(); if ((pNode->m_pParent == NULL) || (pNode->m_iData2 == 1)) { return GC.getMapINLINE().plotSorenINLINE(pNode->m_iX, pNode->m_iY); } while (pNode->m_pParent!= NULL) { if (pNode->m_pParent->m_iData2 == 1) { return GC.getMapINLINE().plotSorenINLINE(pNode->m_pParent->m_iX, pNode->m_pParent->m_iY); } pNode = pNode->m_pParent; } FAssert(false); return NULL; } bool CvSelectionGroup::generatePath( const CvPlot* pFromPlot, const CvPlot* pToPlot, int iFlags, bool bReuse, int* piPathTurns) const { PROFILE("CvSelectionGroup::generatePath()") FAStarNode* pNode; bool bSuccess; gDLL->getFAStarIFace()->SetData(&GC.getPathFinder(), this); bSuccess = gDLL->getFAStarIFace()->GeneratePath(&GC.getPathFinder(), pFromPlot->getX_INLINE(), pFromPlot->getY_INLINE(), pToPlot->getX_INLINE(), pToPlot->getY_INLINE(), false, iFlags, bReuse); if (piPathTurns!= NULL) { *piPathTurns = MAX_INT; if (bSuccess) { pNode = getPathLastNode(); if (pNode!= NULL) { *piPathTurns = pNode->m_iData2; } } } return bSuccess; } void CvSelectionGroup::resetPath() { gDLL->getFAStarIFace()->ForceReset(&GC.getPathFinder()); } void CvSelectionGroup::clearUnits() { CLLNode<IDInfo>* pUnitNode; pUnitNode = headUnitNode(); while (pUnitNode!= NULL) { pUnitNode = deleteUnitNode(pUnitNode); } } // Returns true if the unit is added... bool CvSelectionGroup::addUnit(CvUnit* pUnit) { CLLNode<IDInfo>* pUnitNode; CvUnit* pLoopUnit; bool bAdded; if (!(pUnit->canJoinGroup(pUnit->plot(), this))) { return false; } bAdded = false; pUnitNode = headUnitNode(); while (pUnitNode!= NULL) { pLoopUnit = ::getUnit(pUnitNode->m_data); if ((pUnit->AI_groupFirstVal() > pLoopUnit->AI_groupFirstVal()) || ((pUnit->AI_groupFirstVal() == pLoopUnit->AI_groupFirstVal()) && (pUnit->AI_groupSecondVal() > pLoopUnit->AI_groupSecondVal()))) { m_units.insertBefore(pUnit->getIDInfo(), pUnitNode); bAdded = true; break; } pUnitNode = nextUnitNode(pUnitNode); } if (!bAdded) { m_units.insertAtEnd(pUnit->getIDInfo()); } if (getOwnerINLINE() == NO_PLAYER) { if (getNumUnits() > 0) { pUnitNode = headUnitNode(); while (pUnitNode!= NULL) { if (pUnitNode!= headUnitNode()) { ::getUnit(pUnitNode->m_data)->NotifyEntity(MISSION_MULTI_SELECT); } pUnitNode = nextUnitNode(pUnitNode); } } } return true; } void CvSelectionGroup::removeUnit(CvUnit* pUnit) { CLLNode<IDInfo>* pUnitNode; pUnitNode = headUnitNode(); while (pUnitNode!= NULL) { if (::getUnit(pUnitNode->m_data) == pUnit) { deleteUnitNode(pUnitNode); break; } else { pUnitNode = nextUnitNode(pUnitNode); } } } CLLNode<IDInfo>* CvSelectionGroup::deleteUnitNode(CLLNode<IDInfo>* pNode) { CLLNode<IDInfo>* pNextUnitNode; if (getOwnerINLINE()!= NO_PLAYER) { setAutomateType(NO_AUTOMATE); clearMissionQueue(); if (getActivityType()!= ACTIVITY_SLEEP) { setActivityType(ACTIVITY_AWAKE); } } pNextUnitNode = m_units.deleteNode(pNode); return pNextUnitNode; } CLLNode<IDInfo>* CvSelectionGroup::nextUnitNode(CLLNode<IDInfo>* pNode) const { return m_units.next(pNode); } int CvSelectionGroup::getNumUnits() const { return m_units.getLength(); } //------------------------------------------------------------------------------------------------ // FUNCTION: CvSelectionGroup::getUnitIndex //! \brief Returns the index of the given unit in the selection group //! \param pUnit The unit to find the index of within the group //! \retval The zero-based index of the unit within the group, or -1 if it is not in the group. //------------------------------------------------------------------------------------------------ int CvSelectionGroup::getUnitIndex(CvUnit* pUnit) const { CLLNode<IDInfo>* pUnitNode; CvUnit* pLoopUnit; int iIndex; iIndex = 0; pUnitNode = headUnitNode(); while (pUnitNode!= NULL) { pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = nextUnitNode(pUnitNode); if (pLoopUnit == pUnit) { return iIndex; } iIndex++; } return -1; } CLLNode<IDInfo>* CvSelectionGroup::headUnitNode() const { return m_units.head(); } CvUnit* CvSelectionGroup::getHeadUnit() const { CLLNode<IDInfo>* pUnitNode; pUnitNode = headUnitNode(); if (pUnitNode!= NULL) { return ::getUnit(pUnitNode->m_data); } else { return NULL; } } UnitAITypes CvSelectionGroup::getHeadUnitAI() const { CvUnit* pHeadUnit; pHeadUnit = getHeadUnit(); if (pHeadUnit!= NULL) { return pHeadUnit->AI_getUnitAIType(); } return NO_UNITAI; } PlayerTypes CvSelectionGroup::getHeadOwner() const { CvUnit* pHeadUnit; pHeadUnit = getHeadUnit(); if (pHeadUnit!= NULL) { return pHeadUnit->getOwnerINLINE(); } return NO_PLAYER; } TeamTypes CvSelectionGroup::getHeadTeam() const { CvUnit* pHeadUnit; pHeadUnit = getHeadUnit(); if (pHeadUnit!= NULL) { return pHeadUnit->getTeam(); } return NO_TEAM; } void CvSelectionGroup::clearMissionQueue() { FAssert(getOwnerINLINE()!= NO_PLAYER); deactivateHeadMission(); m_missionQueue.clear(); if ((getOwnerINLINE() == GC.getGameINLINE().getActivePlayer()) && IsSelected()) { gDLL->getInterfaceIFace()->setDirty(Waypoints_DIRTY_BIT, true); gDLL->getInterfaceIFace()->setDirty(SelectionButtons_DIRTY_BIT, true); gDLL->getInterfaceIFace()->setDirty(InfoPane_DIRTY_BIT, true); } } int CvSelectionGroup::getLengthMissionQueue() { return m_missionQueue.getLength(); } MissionData* CvSelectionGroup::getMissionFromQueue(int iIndex) { CLLNode<MissionData>* pMissionNode; pMissionNode = m_missionQueue.nodeNum(iIndex); if (pMissionNode!= NULL) { return &(pMissionNode->m_data); } else { return NULL; } } void CvSelectionGroup::insertAtEndMissionQueue(MissionData mission, bool bStart) { FAssert(getOwnerINLINE()!= NO_PLAYER); m_missionQueue.insertAtEnd(mission); if ((getLengthMissionQueue() == 1) && bStart) { activateHeadMission(); } if ((getOwnerINLINE() == GC.getGameINLINE().getActivePlayer()) && IsSelected()) { gDLL->getInterfaceIFace()->setDirty(Waypoints_DIRTY_BIT, true); gDLL->getInterfaceIFace()->setDirty(SelectionButtons_DIRTY_BIT, true); gDLL->getInterfaceIFace()->setDirty(InfoPane_DIRTY_BIT, true); } } CLLNode<MissionData>* CvSelectionGroup::deleteMissionQueueNode(CLLNode<MissionData>* pNode) { CLLNode<MissionData>* pNextMissionNode; FAssertMsg(pNode!= NULL, "Node is not assigned a valid value"); FAssert(getOwnerINLINE()!= NO_PLAYER); if (pNode == headMissionQueueNode()) { deactivateHeadMission(); } pNextMissionNode = m_missionQueue.deleteNode(pNode); if (pNextMissionNode == headMissionQueueNode()) { activateHeadMission(); } if ((getOwnerINLINE() == GC.getGameINLINE().getActivePlayer()) && IsSelected()) { gDLL->getInterfaceIFace()->setDirty(Waypoints_DIRTY_BIT, true); gDLL->getInterfaceIFace()->setDirty(SelectionButtons_DIRTY_BIT, true); gDLL->getInterfaceIFace()->setDirty(InfoPane_DIRTY_BIT, true); } return pNextMissionNode; } CLLNode<MissionData>* CvSelectionGroup::nextMissionQueueNode(CLLNode<MissionData>* pNode) const { return m_missionQueue.next(pNode); } CLLNode<MissionData>* CvSelectionGroup::prevMissionQueueNode(CLLNode<MissionData>* pNode) const { return m_missionQueue.prev(pNode); } CLLNode<MissionData>* CvSelectionGroup::headMissionQueueNode() const { return m_missionQueue.head(); } CLLNode<MissionData>* CvSelectionGroup::tailMissionQueueNode() const { return m_missionQueue.tail(); } int CvSelectionGroup::getMissionType(int iNode) { int iCount = 0; CLLNode<MissionData>* pMissionNode; pMissionNode = headMissionQueueNode(); while (pMissionNode!= NULL) { if ( iNode == iCount ) { return pMissionNode->m_data.eMissionType; } iCount++; pMissionNode = nextMissionQueueNode(pMissionNode); } return -1; } int CvSelectionGroup::getMissionData1(int iNode) { int iCount = 0; CLLNode<MissionData>* pMissionNode; pMissionNode = headMissionQueueNode(); while (pMissionNode!= NULL) { if ( iNode == iCount ) { return pMissionNode->m_data.iData1; } iCount++; pMissionNode = nextMissionQueueNode(pMissionNode); } return -1; } int CvSelectionGroup::getMissionData2(int iNode) { int iCount = 0; CLLNode<MissionData>* pMissionNode; pMissionNode = headMissionQueueNode(); while (pMissionNode!= NULL) { if ( iNode == iCount ) { return pMissionNode->m_data.iData2; } iCount++; pMissionNode = nextMissionQueueNode(pMissionNode); } return -1; } void CvSelectionGroup::read(FDataStreamBase* pStream) { // Init saved data reset(); uint uiFlag=0; pStream->Read(&uiFlag); // flags for expansion pStream->Read(&m_iID); pStream->Read(&m_iMissionTimer); pStream->Read(&m_bForceUpdate); pStream->Read((int*)&m_eOwner); pStream->Read((int*)&m_eActivityType); pStream->Read((int*)&m_eAutomateType); m_units.Read(pStream); m_missionQueue.Read(pStream); } void CvSelectionGroup::write(FDataStreamBase* pStream) { uint uiFlag=0; pStream->Write(uiFlag); // flag for expansion pStream->Write(m_iID); pStream->Write(m_iMissionTimer); pStream->Write(m_bForceUpdate); pStream->Write(m_eOwner); pStream->Write(m_eActivityType); pStream->Write(m_eAutomateType); m_units.Write(pStream); m_missionQueue.Write(pStream); } // Protected Functions... void CvSelectionGroup::activateHeadMission() { FAssert(getOwnerINLINE()!= NO_PLAYER); if (headMissionQueueNode()!= NULL) { if (!isBusy()) { startMission(); } } } void CvSelectionGroup::deactivateHeadMission() { FAssert(getOwnerINLINE()!= NO_PLAYER); if (headMissionQueueNode()!= NULL) { if (getActivityType() == ACTIVITY_MISSION) { setActivityType(ACTIVITY_AWAKE); } setMissionTimer(0); if (getOwnerINLINE() == GC.getGameINLINE().getActivePlayer()) { if (IsSelected()) { gDLL->getInterfaceIFace()->changeCycleSelectionCounter(1); } } } } ======================= File: BtS/CvGameCoreDLL/CyUnit.cpp ======================= <reponame>f1rpo/Civ4CE // // Python wrapper class for CvUnit // // #include "CvGameCoreDLL.h" #include "CyUnit.h" #include "CyCity.h" #include "CvArea.h" #include "CvPlot.h" #include "CvUnit.h" #include "CyPlot.h" #include "CyArea.h" #include "CvArtFileMgr.h" #include "CySelectionGroup.h" #include "CvDLLInterfaceIFaceBase.h" #include "CvGlobals.h" CyUnit::CyUnit() : m_pUnit(NULL) { } CyUnit::CyUnit(CvUnit* pUnit) : m_pUnit(pUnit) { } void CyUnit::convert(CyUnit* pUnit) { if (m_pUnit) m_pUnit->convert(pUnit->getUnit()); } void CyUnit::kill(bool bDelay, int /*PlayerTypes*/ ePlayer) { if (m_pUnit) m_pUnit->kill(bDelay, (PlayerTypes)ePlayer); } void CyUnit::NotifyEntity(int /*MissionTypes*/ eEvent) { if (m_pUnit) m_pUnit->NotifyEntity((MissionTypes)eEvent); } bool CyUnit::isActionRecommended(int i) { if ( m_pUnit ) { return m_pUnit->isActionRecommended(i); } return false; } bool CyUnit::isBetterDefenderThan(CyUnit* pDefender, CyUnit* pAttacker) { return m_pUnit? m_pUnit->isBetterDefenderThan(pDefender->getUnit(), pAttacker->getUnit()) : false; } bool CyUnit::canDoCommand(CommandTypes eCommand, int iData1, int iData2, bool bTestVisible) { return m_pUnit? m_pUnit->canDoCommand(eCommand, iData1, iData2, bTestVisible) : false; } void CyUnit::doCommand(CommandTypes eCommand, int iData1, int iData2) { if (m_pUnit) return m_pUnit->doCommand(eCommand, iData1, iData2); } CyPlot* CyUnit::getPathEndTurnPlot() { return m_pUnit? new CyPlot(m_pUnit->getPathEndTurnPlot()) : false; } bool CyUnit::generatePath(CyPlot* pToPlot, int iFlags, bool bReuse, int* piPathTurns) { return m_pUnit? m_pUnit->generatePath(pToPlot->getPlot(), iFlags, bReuse, piPathTurns) : false; } bool CyUnit::canEnterTerritory(int /*TeamTypes*/ eTeam, bool bIgnoreRightOfPassage) { return m_pUnit? (int) m_pUnit->canEnterTerritory((TeamTypes) eTeam, bIgnoreRightOfPassage) : false; } bool CyUnit::canEnterArea(int /*TeamTypes*/ eTeam, CyArea* pArea, bool bIgnoreRightOfPassage) { return m_pUnit? (int) m_pUnit->canEnterArea((TeamTypes) eTeam, pArea->getArea(), bIgnoreRightOfPassage) : false; } int /*TeamTypes*/ CyUnit::getDeclareWarMove(CyPlot* pPlot) { return m_pUnit? (int) m_pUnit->getDeclareWarMove(pPlot->getPlot()) : (int) NO_TEAM; } bool CyUnit::canMoveInto(CyPlot* pPlot, bool bAttack, bool bDeclareWar, bool bIgnoreLoad) { return m_pUnit? m_pUnit->canMoveInto(pPlot->getPlot(), bAttack, bDeclareWar, bIgnoreLoad) : false; } bool CyUnit::canMoveOrAttackInto(CyPlot* pPlot, bool bDeclareWar) { return m_pUnit? m_pUnit->canMoveOrAttackInto(pPlot->getPlot(), bDeclareWar) : false; } bool CyUnit::canMoveThrough(CyPlot* pPlot) { return m_pUnit? m_pUnit->canMoveThrough(pPlot->getPlot()) : false; } bool CyUnit::jumpToNearestValidPlot() { return m_pUnit? m_pUnit->jumpToNearestValidPlot() : false; } bool CyUnit::canAutomate(AutomateTypes eAutomate) { return m_pUnit? m_pUnit->canAutomate(eAutomate) : false; } bool CyUnit::canScrap() { return m_pUnit? m_pUnit->canScrap() : false; } bool CyUnit::canGift(bool bTestVisible) { return m_pUnit? m_pUnit->canGift(bTestVisible) : false; } bool CyUnit::canLoadUnit(CyUnit* pUnit, CyPlot* pPlot) { return m_pUnit? m_pUnit->canLoadUnit(pUnit->getUnit(), pPlot->getPlot()) : false; } bool CyUnit::canLoad(CyPlot* pPlot) { return m_pUnit? m_pUnit->canLoad(pPlot->getPlot()) : false; } bool CyUnit::canUnload() { return m_pUnit? m_pUnit->canUnload() : false; } bool CyUnit::canUnloadAll() { return m_pUnit? m_pUnit->canUnloadAll() : false; } bool CyUnit::canHold(CyPlot* pPlot) { return m_pUnit? m_pUnit->canHold(pPlot->getPlot()) : false; } bool CyUnit::canSleep(CyPlot* pPlot) { return m_pUnit? m_pUnit->canSleep(pPlot->getPlot()) : false; } bool CyUnit::canFortify(CyPlot* pPlot) { return m_pUnit? m_pUnit->canFortify(pPlot->getPlot()) : false; } bool CyUnit::canPlunder(CyPlot* pPlot) { return m_pUnit? m_pUnit->canPlunder(pPlot->getPlot()) : false; } bool CyUnit::canAirPatrol(CyPlot* pPlot) { return m_pUnit? m_pUnit->canAirPatrol(pPlot->getPlot()) : false; } bool CyUnit::canSeaPatrol(CyPlot* pPlot) { return m_pUnit? m_pUnit->canSeaPatrol(pPlot->getPlot()) : false; } bool CyUnit::canHeal(CyPlot* pPlot) { return m_pUnit? m_pUnit->canHeal(pPlot->getPlot()) : false; } bool CyUnit::canSentry(CyPlot* pPlot) { return m_pUnit? m_pUnit->canSentry(pPlot->getPlot()) : false; } bool CyUnit::canAirlift(CyPlot* pPlot) { return m_pUnit? m_pUnit->canAirlift(pPlot->getPlot()) : false; } bool CyUnit::canAirliftAt(CyPlot* pPlot, int iX, int iY) { return m_pUnit? m_pUnit->canAirliftAt(pPlot->getPlot(), iX, iY) : false; } bool CyUnit::isNukeVictim(CyPlot* pPlot, int /*TeamTypes*/ eTeam) { return m_pUnit? m_pUnit->isNukeVictim(pPlot->getPlot(), (TeamTypes) eTeam) : false; } bool CyUnit::canNuke(CyPlot* pPlot) { return m_pUnit? m_pUnit->canNuke(pPlot->getPlot()) : false; } bool CyUnit::canNukeAt(CyPlot* pPlot, int iX, int iY) { return m_pUnit? m_pUnit->canNukeAt(pPlot->getPlot(), iX, iY) : false; } bool CyUnit::canRecon(CyPlot* pPlot) { return m_pUnit? m_pUnit->canRecon(pPlot->getPlot()) : false; } bool CyUnit::canReconAt(CyPlot* pPlot, int iX, int iY) { return m_pUnit? m_pUnit->canReconAt(pPlot->getPlot(), iX, iY) : false; } bool CyUnit::canParadrop(CyPlot* pPlot) { return m_pUnit? m_pUnit->canParadrop(pPlot->getPlot()) : false; } bool CyUnit::canParadropAt(CyPlot* pPlot, int iX, int iY) { return m_pUnit? m_pUnit->canParadropAt(pPlot->getPlot(), iX, iY) : false; } bool CyUnit::canAirBomb(CyPlot* pPlot) { return m_pUnit? m_pUnit->canAirBomb(pPlot->getPlot()) : false; } bool CyUnit::canAirBombAt(CyPlot* pPlot, int iX, int iY) { return m_pUnit? m_pUnit->canAirBombAt(pPlot->getPlot(), iX, iY) : false; } CyCity* CyUnit::bombardTarget(CyPlot* pPlot) { return m_pUnit? new CyCity(m_pUnit->bombardTarget(pPlot->getPlot())) : false; } bool CyUnit::canBombard(CyPlot* pPlot) { return m_pUnit? m_pUnit->canBombard(pPlot->getPlot()) : false; } bool CyUnit::canPillage(CyPlot* pPlot) { return m_pUnit? m_pUnit->canPillage(pPlot->getPlot()) : false; } int CyUnit::sabotageCost(CyPlot* pPlot) { return m_pUnit? m_pUnit->sabotageCost(pPlot->getPlot()) : -1; } int CyUnit::sabotageProb(CyPlot* pPlot, int /*ProbabilityTypes*/ eProbStyle) { return m_pUnit? m_pUnit->sabotageProb(pPlot->getPlot(), (ProbabilityTypes)eProbStyle) : -1; } bool CyUnit::canSabotage(CyPlot* pPlot, bool bTestVisible) { return m_pUnit? m_pUnit->canSabotage(pPlot->getPlot(), bTestVisible) : false; } int CyUnit::destroyCost(CyPlot* pPlot) { return m_pUnit? m_pUnit->destroyCost(pPlot->getPlot()) : -1; } int CyUnit::destroyProb(CyPlot* pPlot, int /*ProbabilityTypes*/ eProbStyle) { return m_pUnit? m_pUnit->destroyProb(pPlot->getPlot(), (ProbabilityTypes)eProbStyle) : -1; } bool CyUnit::canDestroy(CyPlot* pPlot, bool bTestVisible) { return m_pUnit? m_pUnit->canDestroy(pPlot->getPlot(), bTestVisible) : false; } int CyUnit::stealPlansCost(CyPlot* pPlot) { return m_pUnit? m_pUnit->stealPlansCost(pPlot->getPlot()) : -1; } int CyUnit::stealPlansProb(CyPlot* pPlot, int /*ProbabilityTypes*/ eProbStyle) { return m_pUnit? m_pUnit->stealPlansProb(pPlot->getPlot(), (ProbabilityTypes) eProbStyle) : -1; } bool CyUnit::canStealPlans(CyPlot* pPlot, bool bTestVisible) { return m_pUnit? m_pUnit->canStealPlans(pPlot->getPlot(), bTestVisible) : false; } bool CyUnit::canFound(CyPlot* pPlot, bool bTestVisible) { return m_pUnit? m_pUnit->canFound(pPlot->getPlot(), bTestVisible) : false; } bool CyUnit::canSpread(CyPlot* pPlot, int /*ReligionTypes*/ eReligion, bool bTestVisible) { return m_pUnit? m_pUnit->canSpread(pPlot->getPlot(), (ReligionTypes) eReligion, bTestVisible) : false; } bool CyUnit::canJoin(CyPlot* pPlot, int /*SpecialistTypes*/ eSpecialist) { return m_pUnit? m_pUnit->canFound(pPlot->getPlot(), (SpecialistTypes) eSpecialist) : false; } bool CyUnit::canConstruct(CyPlot* pPlot, int /*BuildingTypes*/ eBuilding) { return m_pUnit? m_pUnit->canConstruct(pPlot->getPlot(), (BuildingTypes) eBuilding) : false; } int /*TechTypes*/ CyUnit::getDiscoveryTech() { return m_pUnit? (TechTypes) m_pUnit->getDiscoveryTech() : -1; } int CyUnit::getDiscoverResearch(int /*TechTypes*/ eTech) { return m_pUnit? m_pUnit->getDiscoverResearch((TechTypes) eTech) : -1; } bool CyUnit::canDiscover(CyPlot* pPlot) { return m_pUnit? m_pUnit->canDiscover(pPlot->getPlot()) : false; } int CyUnit::getMaxHurryProduction(CyCity* pCity) { return m_pUnit? m_pUnit->getMaxHurryProduction(pCity->getCity()) : -1; } int CyUnit::getHurryProduction(CyPlot* pPlot) { return m_pUnit? m_pUnit->getHurryProduction(pPlot->getPlot()) : -1; } bool CyUnit::canHurry(CyPlot* pPlot, bool bTestVisible) { return m_pUnit? m_pUnit->canHurry(pPlot->getPlot(), bTestVisible) : false; } int CyUnit::getTradeGold(CyPlot* pPlot) { return m_pUnit? m_pUnit->getTradeGold(pPlot->getPlot()) : -1; } bool CyUnit::canTrade(CyPlot* pPlot, bool bTestVisible) { return m_pUnit? m_pUnit->canTrade(pPlot->getPlot(), bTestVisible) : false; } int CyUnit::getGreatWorkCulture(CyPlot* pPlot) { return m_pUnit? m_pUnit->getGreatWorkCulture(pPlot->getPlot()) : -1; } bool CyUnit::canGreatWork(CyPlot* pPlot) { return m_pUnit? m_pUnit->canGreatWork(pPlot->getPlot()) : false; } int CyUnit::getEspionagePoints(CyPlot* pPlot) { return m_pUnit? m_pUnit->getEspionagePoints(pPlot->getPlot()) : -1; } bool CyUnit::canInfiltrate(CyPlot* pPlot, bool bTestVisible) { return m_pUnit? m_pUnit->canInfiltrate(pPlot->getPlot(), bTestVisible) : false; } bool CyUnit::canEspionage(CyPlot* pPlot) { return m_pUnit? m_pUnit->canEspionage(pPlot->getPlot()) : false; } bool CyUnit::canGoldenAge(CyPlot* pPlot, bool bTestVisible) { return m_pUnit? m_pUnit->canGoldenAge(pPlot->getPlot(), bTestVisible) : false; } bool CyUnit::canBuild(CyPlot* pPlot, int /*BuildTypes*/ eBuild, bool bTestVisible) { return m_pUnit? m_pUnit->canBuild(pPlot->getPlot(), (BuildTypes) eBuild, bTestVisible) : false; } int CyUnit::canLead(CyPlot* pPlot, int iUnitId) const { return m_pUnit? m_pUnit->canLead(pPlot->getPlot(), iUnitId) : 0; } bool CyUnit::lead(int iUnitId) { return m_pUnit? m_pUnit->lead(iUnitId) : false; } int CyUnit::canGiveExperience(CyPlot* pPlot) const { return m_pUnit? m_pUnit->canGiveExperience(pPlot->getPlot()) : 0; } bool CyUnit::giveExperience() { return m_pUnit? m_pUnit->giveExperience() : false; } bool CyUnit::canPromote(int /*PromotionTypes*/ ePromotion, int iLeaderUnitId) { return m_pUnit? m_pUnit->canPromote((PromotionTypes) ePromotion, iLeaderUnitId) : false; } void CyUnit::promote(int /*PromotionTypes*/ ePromotion, int iLeaderUnitId) { if (m_pUnit) m_pUnit->promote((PromotionTypes) ePromotion, iLeaderUnitId); } int CyUnit::upgradePrice(int /*UnitTypes*/ eUnit) { return m_pUnit? m_pUnit->upgradePrice((UnitTypes) eUnit) : -1; } bool CyUnit::upgradeAvailable(int /*UnitTypes*/ eFromUnit, int /*UnitClassTypes*/ eToUnitClass, int iCount) { return m_pUnit? m_pUnit->upgradeAvailable((UnitTypes) eFromUnit, (UnitClassTypes) eToUnitClass, iCount) : false; } bool CyUnit::canUpgrade(int /*UnitTypes*/ eUnit, bool bTestVisible) { return m_pUnit? m_pUnit->canUpgrade((UnitTypes)eUnit, bTestVisible) : false; } bool CyUnit::hasUpgrade(bool bSearch) { return m_pUnit? m_pUnit->hasUpgrade(bSearch) : false; } int /*HandicapTypes*/ CyUnit::getHandicapType() { return m_pUnit? (int) m_pUnit->getHandicapType() : (int) NO_HANDICAP; } int /*CivilizationTypes*/ CyUnit::getCivilizationType() { return m_pUnit? (int) m_pUnit->getCivilizationType() : (int) NO_CIVILIZATION; } int /*SpecialUnitTypes*/ CyUnit::getSpecialUnitType() { return m_pUnit? (int) m_pUnit->getSpecialUnitType() : (int) NO_SPECIALUNIT; } int /*UnitTypes*/ CyUnit::getCaptureUnitType(int /*CivilizationTypes*/ eCivilization) { return m_pUnit? m_pUnit->getCaptureUnitType((CivilizationTypes)eCivilization) : -1; } int /*UnitCombatTypes*/ CyUnit::getUnitCombatType() { return m_pUnit? (int) m_pUnit->getUnitCombatType() : (int) NO_UNITCOMBAT; } int /*DomainTypes*/ CyUnit::getDomainType() { return m_pUnit? (int) m_pUnit->getDomainType() : (int) NO_DOMAIN; } int /*InvisibleTypes*/ CyUnit::getInvisibleType() { return m_pUnit? (int) m_pUnit->getInvisibleType() : (int) NO_INVISIBLE; } int CyUnit::getNumSeeInvisibleTypes() { return m_pUnit? m_pUnit->getNumSeeInvisibleTypes() : -1; } int /*InvisibleTypes*/ CyUnit::getSeeInvisibleType(int i) { return m_pUnit? (int) m_pUnit->getSeeInvisibleType(i) : (int) NO_INVISIBLE; } int CyUnit::flavorValue(int /*FlavorTypes*/ eFlavor) { return m_pUnit? m_pUnit->flavorValue((FlavorTypes) eFlavor) : -1; } bool CyUnit::isBarbarian() { return m_pUnit? m_pUnit->isBarbarian() : false; } bool CyUnit::isHuman() { return m_pUnit? m_pUnit->isHuman() : false; } int CyUnit::visibilityRange() { return m_pUnit? m_pUnit->visibilityRange() : -1; } int CyUnit::baseMoves() { return m_pUnit? m_pUnit->baseMoves() : -1; } int CyUnit::maxMoves() { return m_pUnit? m_pUnit->maxMoves() : -1; } int CyUnit::movesLeft() { return m_pUnit? m_pUnit->movesLeft() : -1; } bool CyUnit::canMove() { return m_pUnit? m_pUnit->canMove() : false; } bool CyUnit::hasMoved() { return m_pUnit? m_pUnit->hasMoved() : false; } int CyUnit::airRange() { return m_pUnit? m_pUnit->airRange() : -1; } int CyUnit::nukeRange() { return m_pUnit? m_pUnit->nukeRange() : -1; } bool CyUnit::canBuildRoute() { return m_pUnit? m_pUnit->canBuildRoute() : false; } int /*BuildTypes*/ CyUnit::getBuildType() { return (int) m_pUnit? m_pUnit->getBuildType() : (int) NO_BUILD; } int CyUnit::workRate(bool bMax) { return m_pUnit? m_pUnit->workRate(bMax) : -1; } bool CyUnit::isAnimal() { return m_pUnit? m_pUnit->isAnimal() : false; } bool CyUnit::isNoBadGoodies() { return m_pUnit? m_pUnit->isNoBadGoodies() : false; } bool CyUnit::isOnlyDefensive() { return m_pUnit? m_pUnit->isOnlyDefensive() : false; } bool CyUnit::isNoCapture() { return m_pUnit? m_pUnit->isNoCapture() : false; } bool CyUnit::isRivalTerritory() { return m_pUnit? m_pUnit->isRivalTerritory() : false; } bool CyUnit::isMilitaryHappiness() { return m_pUnit? m_pUnit->isMilitaryHappiness() : false; } bool CyUnit::isInvestigate() { return m_pUnit? m_pUnit->isInvestigate() : false; } bool CyUnit::isCounterSpy() { return m_pUnit? m_pUnit->isCounterSpy() : false; } bool CyUnit::isFound() { return m_pUnit? m_pUnit->isFound() : false; } bool CyUnit::isGoldenAge() { return m_pUnit? m_pUnit->isGoldenAge() : false; } bool CyUnit::canCoexistWithEnemyUnit(int /*TeamTypes*/ eTeam) { return m_pUnit? m_pUnit->canCoexistWithEnemyUnit((TeamTypes)eTeam) : false; } bool CyUnit::isFighting() { return m_pUnit? m_pUnit->isFighting() : false; } bool CyUnit::isAttacking() { return m_pUnit? m_pUnit->isAttacking() : false; } bool CyUnit::isDefending() { return m_pUnit? m_pUnit->isDefending() : false; } bool CyUnit::isCombat() { return m_pUnit? m_pUnit->isCombat() : false; } int CyUnit::maxHitPoints() { return m_pUnit? m_pUnit->maxHitPoints() : -1; } int CyUnit::currHitPoints() { return m_pUnit? m_pUnit->currHitPoints() : -1; } bool CyUnit::isHurt() { return m_pUnit? m_pUnit->isHurt() : false; } bool CyUnit::isDead() { return m_pUnit? m_pUnit->isDead() : false; } void CyUnit::setBaseCombatStr(int iCombat) { if (m_pUnit) { m_pUnit->setBaseCombatStr(iCombat); } } int CyUnit::baseCombatStr() { return m_pUnit? m_pUnit->baseCombatStr() : -1; } int CyUnit::maxCombatStr(CyPlot* pPlot, CyUnit* pAttacker) { return m_pUnit? m_pUnit->maxCombatStr(pPlot->getPlot(), pAttacker->getUnit()) : -1; } int CyUnit::currCombatStr(CyPlot* pPlot, CyUnit* pAttacker) { return m_pUnit? m_pUnit->currCombatStr(pPlot->getPlot(), pAttacker->getUnit()) : -1; } int CyUnit::currFirepower(CyPlot* pPlot, CyUnit* pAttacker) { return m_pUnit? m_pUnit->currFirepower(pPlot->getPlot(), pAttacker->getUnit()) : -1; } float CyUnit::maxCombatStrFloat(CyPlot* pPlot, CyUnit* pAttacker) { return m_pUnit? m_pUnit->maxCombatStrFloat(pPlot->getPlot(), pAttacker->getUnit()) : 0.0f; } float CyUnit::currCombatStrFloat(CyPlot* pPlot, CyUnit* pAttacker) { return m_pUnit? m_pUnit->currCombatStrFloat(pPlot->getPlot(), pAttacker->getUnit()) : 0.0f; } bool CyUnit::canFight() { return m_pUnit? m_pUnit->canFight() : false; } bool CyUnit::canAttack() { return m_pUnit? m_pUnit->canAttack() : false; } bool CyUnit::canDefend(CyPlot* pPlot) { return m_pUnit? m_pUnit->canDefend(pPlot->getPlot()) : false; } bool CyUnit::canSiege(int /*TeamTypes*/ eTeam) { return m_pUnit? m_pUnit->canSiege((TeamTypes) eTeam) : false; } int CyUnit::airBaseCombatStr() { return m_pUnit? m_pUnit->airBaseCombatStr() : -1; } int CyUnit::airMaxCombatStr(CyUnit* pOther) { return m_pUnit? m_pUnit->airMaxCombatStr(pOther->getUnit()) : -1; } int CyUnit::airCurrCombatStr(CyUnit* pOther) { return m_pUnit? m_pUnit->airCurrCombatStr(pOther->getUnit()) : -1; } float CyUnit::airMaxCombatStrFloat(CyUnit* pOther) { return m_pUnit? m_pUnit->airMaxCombatStrFloat(pOther->getUnit()) : -1; } float CyUnit::airCurrCombatStrFloat(CyUnit* pOther) { return m_pUnit? m_pUnit->airCurrCombatStrFloat(pOther->getUnit()) : -1; } int CyUnit::combatLimit() { return m_pUnit? m_pUnit->combatLimit() : -1; } int CyUnit::airCombatLimit() { return m_pUnit? m_pUnit->airCombatLimit() : -1; } bool CyUnit::canAirAttack() { return m_pUnit? m_pUnit->canAirAttack() : false; } bool CyUnit::canAirDefend(CyPlot* pPlot) { return m_pUnit? m_pUnit->canAirDefend(pPlot->getPlot()) : false; } int CyUnit::airCombatDamage(CyUnit* pDefender) { return m_pUnit? m_pUnit->airCombatDamage(pDefender->getUnit()) : -1; } CyUnit* CyUnit::bestInterceptor(CyPlot* pPlot) { return m_pUnit? new CyUnit(m_pUnit->bestInterceptor(pPlot->getPlot())) : false; } bool CyUnit::isAutomated() { return m_pUnit? m_pUnit->isAutomated() : false; } bool CyUnit::isWaiting() { return m_pUnit? m_pUnit->isWaiting() : false; } bool CyUnit::isFortifyable() { return m_pUnit? m_pUnit->isFortifyable() : false; } int CyUnit::fortifyModifier() { return m_pUnit? m_pUnit->fortifyModifier() : -1; } int CyUnit::experienceNeeded() { return m_pUnit? m_pUnit->experienceNeeded() : -1; } int CyUnit::attackXPValue() { return m_pUnit? m_pUnit->attackXPValue() : -1; } int CyUnit::defenseXPValue() { return m_pUnit? m_pUnit->defenseXPValue() : -1; } int CyUnit::maxXPValue() { return m_pUnit? m_pUnit->maxXPValue() : -1; } int CyUnit::firstStrikes() { return m_pUnit? m_pUnit->firstStrikes() : -1; } int CyUnit::chanceFirstStrikes() { return m_pUnit? m_pUnit->chanceFirstStrikes() : -1; } int CyUnit::maxFirstStrikes() { return m_pUnit? m_pUnit->maxFirstStrikes() : -1; } bool CyUnit::isRanged() { return m_pUnit? m_pUnit->isRanged() : false; } bool CyUnit::alwaysInvisible() { return m_pUnit? m_pUnit->alwaysInvisible() : false; } bool CyUnit::immuneToFirstStrikes() { return m_pUnit? m_pUnit->immuneToFirstStrikes() : false; } bool CyUnit::noDefensiveBonus() { return m_pUnit? m_pUnit->noDefensiveBonus() : false; } bool CyUnit::ignoreBuildingDefense() { return m_pUnit? m_pUnit->ignoreBuildingDefense() : false; } bool CyUnit::canMoveImpassable() { return m_pUnit? m_pUnit->canMoveImpassable() : false; } bool CyUnit::canMoveAllTerrain() { return m_pUnit? m_pUnit->canMoveAllTerrain() : false; } bool CyUnit::flatMovementCost() { return m_pUnit? m_pUnit->flatMovementCost() : false; } bool CyUnit::ignoreTerrainCost() { return m_pUnit? m_pUnit->ignoreTerrainCost() : false; } bool CyUnit::isNeverInvisible() { return m_pUnit? m_pUnit->isNeverInvisible() : false; } bool CyUnit::isInvisible(int /*TeamTypes*/ eTeam, bool bDebug) { return m_pUnit? m_pUnit->isInvisible((TeamTypes) eTeam, bDebug) : false; } bool CyUnit::isNukeImmune() { return m_pUnit? m_pUnit->isNukeImmune() : false; } int CyUnit::maxInterceptionProbability() { return m_pUnit? m_pUnit->maxInterceptionProbability() : -1; } int CyUnit::currInterceptionProbability() { return m_pUnit? m_pUnit->currInterceptionProbability() : -1; } int CyUnit::evasionProbability() { return m_pUnit? m_pUnit->evasionProbability() : -1; } int CyUnit::withdrawalProbability() { return m_pUnit? m_pUnit->withdrawalProbability() : -1; } int CyUnit::collateralDamage() { return m_pUnit? m_pUnit->collateralDamage() : -1; } int CyUnit::collateralDamageLimit() { return m_pUnit? m_pUnit->collateralDamageLimit() : -1; } int CyUnit::collateralDamageMaxUnits() { return m_pUnit? m_pUnit->collateralDamageMaxUnits() : -1; } int CyUnit::cityAttackModifier() { return m_pUnit? m_pUnit->cityAttackModifier() : -1; } int CyUnit::cityDefenseModifier() { return m_pUnit? m_pUnit->cityDefenseModifier() : -1; } int CyUnit::animalCombatModifier() { return m_pUnit? m_pUnit->animalCombatModifier() : -1; } int CyUnit::hillsAttackModifier() { return m_pUnit? m_pUnit->hillsAttackModifier() : -1; } int CyUnit::hillsDefenseModifier() { return m_pUnit? m_pUnit->hillsDefenseModifier() : -1; } int CyUnit::terrainAttackModifier(int /*TerrainTypes*/ eTerrain) { return m_pUnit? m_pUnit->terrainAttackModifier((TerrainTypes) eTerrain) : -1; } int CyUnit::terrainDefenseModifier(int /*TerrainTypes*/ eTerrain) { return m_pUnit? m_pUnit->terrainDefenseModifier((TerrainTypes) eTerrain) : -1; } int CyUnit::featureAttackModifier(int /*FeatureTypes*/ eFeature) { return m_pUnit? m_pUnit->featureAttackModifier((FeatureTypes) eFeature) : -1; } int CyUnit::featureDefenseModifier(int /*FeatureTypes*/ eFeature) { return m_pUnit? m_pUnit->featureDefenseModifier((FeatureTypes) eFeature) : -1; } int CyUnit::unitClassAttackModifier(int /*UnitClassTypes*/ eUnitClass) { return m_pUnit? m_pUnit->unitClassAttackModifier((UnitClassTypes) eUnitClass) : -1; } int CyUnit::unitClassDefenseModifier(int /*UnitClassTypes*/ eUnitClass) { return m_pUnit? m_pUnit->unitClassDefenseModifier((UnitClassTypes) eUnitClass) : -1; } int CyUnit::unitCombatModifier(int /*UnitCombatTypes*/ eUnitCombat) { return m_pUnit? m_pUnit->unitCombatModifier((UnitCombatTypes) eUnitCombat) : -1; } int CyUnit::domainModifier(int /*DomainTypes*/ eDomain) { return m_pUnit? m_pUnit->domainModifier((DomainTypes) eDomain) : -1; } int CyUnit::bombardRate() { return m_pUnit? m_pUnit->bombardRate() : -1; } int CyUnit::airBombBaseRate() { return m_pUnit? m_pUnit->airBombBaseRate() : -1; } int CyUnit::airBombCurrRate() { return m_pUnit? m_pUnit->airBombCurrRate() : -1; } int /*SpecialUnitTypes*/ CyUnit::specialCargo() { return m_pUnit? (int) m_pUnit->specialCargo() : (int) NO_SPECIALUNIT; } int /*DomainTypes*/ CyUnit::domainCargo() { return m_pUnit? (int) m_pUnit->domainCargo() : (int) NO_DOMAIN; } int CyUnit::cargoSpace() { return m_pUnit? m_pUnit->cargoSpace() : -1; } void CyUnit::changeCargoSpace(int iChange) { if (m_pUnit) m_pUnit->changeCargoSpace(iChange); } bool CyUnit::isFull() { return m_pUnit? m_pUnit->isFull() : false; } int CyUnit::cargoSpaceAvailable(int /*SpecialUnitTypes*/ eSpecialCargo, int /*DomainTypes*/ eDomainCargo) { return m_pUnit? m_pUnit->cargoSpaceAvailable((SpecialUnitTypes) eSpecialCargo, (DomainTypes) eDomainCargo) : -1; } bool CyUnit::hasCargo() { return m_pUnit? m_pUnit->hasCargo() : false; } bool CyUnit::canCargoAllMove() { return m_pUnit? m_pUnit->canCargoAllMove() : false; } int CyUnit::getUnitAICargo(UnitAITypes eUnitAI) { return m_pUnit? m_pUnit->getUnitAICargo(eUnitAI) : -1; } int CyUnit::getID() { return m_pUnit? m_pUnit->getID() : -1; } int CyUnit::getGroupID() { return m_pUnit? m_pUnit->getGroupID() : -1; } bool CyUnit::isInGroup() { return m_pUnit? m_pUnit->isInGroup() : false; } bool CyUnit::isGroupHead() { return m_pUnit? m_pUnit->isGroupHead() : false; } CySelectionGroup* CyUnit::getGroup() { return m_pUnit? new CySelectionGroup( m_pUnit->getGroup() ) : NULL; } int CyUnit::getHotKeyNumber() { return m_pUnit? m_pUnit->getHotKeyNumber() : -1; } void CyUnit::setHotKeyNumber(int iNewValue) { if (m_pUnit) m_pUnit->setHotKeyNumber(iNewValue); } int CyUnit::getX() { return m_pUnit? m_pUnit->getX_INLINE() : -1; } int CyUnit::getY() { return m_pUnit? m_pUnit->getY_INLINE() : -1; } void CyUnit::setXY(int iX, int iY, bool bGroup, bool bUpdate, bool bShow) { if (m_pUnit) return m_pUnit->setXY(iX, iY, bGroup, bUpdate, bShow); } bool CyUnit::at(int iX, int iY) { return m_pUnit? m_pUnit->at(iX, iY) : false; } bool CyUnit::atPlot(CyPlot* pPlot) { return m_pUnit? m_pUnit->atPlot(pPlot->getPlot()) : false; } CyPlot* CyUnit::plot() { return m_pUnit? new CyPlot(m_pUnit->plot()) : NULL; } CyArea* CyUnit::area() { return m_pUnit? new CyArea(m_pUnit->area()) : NULL; } CyPlot* CyUnit::getReconPlot() { return m_pUnit? new CyPlot(m_pUnit->getReconPlot()) : NULL; } void CyUnit::setReconPlot(CyPlot* pNewValue) { if (m_pUnit) m_pUnit->setReconPlot(pNewValue->getPlot()); } int CyUnit::getGameTurnCreated() { return m_pUnit? m_pUnit->getGameTurnCreated() : -1; } int CyUnit::getDamage() { return m_pUnit? m_pUnit->getDamage() : -1; } void CyUnit::setDamage(int iNewValue, int /*PlayerTypes*/ ePlayer) { if (m_pUnit) m_pUnit->setDamage(iNewValue, (PlayerTypes)ePlayer); } void CyUnit::changeDamage(int iChange, int /*PlayerTypes*/ ePlayer) { if (m_pUnit) m_pUnit->changeDamage(iChange, (PlayerTypes)ePlayer); } int CyUnit::getMoves() { return m_pUnit? m_pUnit->getMoves() : -1; } void CyUnit::setMoves(int iNewValue) { if (m_pUnit) m_pUnit->setMoves(iNewValue); } void CyUnit::changeMoves(int iChange) { if (m_pUnit) m_pUnit->changeMoves(iChange); } void CyUnit::finishMoves() { if (m_pUnit) m_pUnit->finishMoves(); } int CyUnit::getExperience() { return m_pUnit? m_pUnit->getExperience() : -1; } void CyUnit::setExperience(int iNewValue, int iMax) { if (m_pUnit) m_pUnit->setExperience(iNewValue, iMax); } void CyUnit::changeExperience(int iChange, int iMax, bool bFromCombat, bool bInBorders, bool bUpdateGlobal) { if (m_pUnit) m_pUnit->changeExperience(iChange, iMax, bFromCombat, bInBorders, bUpdateGlobal); } int CyUnit::getLevel() { return m_pUnit? m_pUnit->getLevel() : -1; } void CyUnit::setLevel(int iNewLevel) { if (m_pUnit) m_pUnit->setLevel(iNewLevel); } void CyUnit::changeLevel(int iChange) { if (m_pUnit) m_pUnit->changeLevel(iChange); } int CyUnit::getFacingDirection() { if(m_pUnit) return m_pUnit->getFacingDirection(false); else return NO_DIRECTION; } void CyUnit::rotateFacingDirectionClockwise() { if(m_pUnit) return m_pUnit->rotateFacingDirectionClockwise(); } void CyUnit::rotateFacingDirectionCounterClockwise() { if(m_pUnit) return m_pUnit->rotateFacingDirectionCounterClockwise(); } int CyUnit::getCargo() { return m_pUnit? m_pUnit->getCargo() : -1; } int CyUnit::getFortifyTurns() { return m_pUnit? m_pUnit->getFortifyTurns() : -1; } int CyUnit::getBlitzCount() { return m_pUnit? m_pUnit->getBlitzCount() : -1; } bool CyUnit::isBlitz() { return m_pUnit? m_pUnit->isBlitz() : false; } int CyUnit::getAmphibCount() { return m_pUnit? m_pUnit->getAmphibCount() : -1; } bool CyUnit::isAmphib() { return m_pUnit? m_pUnit->isAmphib() : false; } int CyUnit::getRiverCount() { return m_pUnit? m_pUnit->getRiverCount() : -1; } bool CyUnit::isRiver() { return m_pUnit? m_pUnit->isRiver() : false; } bool CyUnit::isEnemyRoute() { return m_pUnit? m_pUnit->isEnemyRoute(): false; } bool CyUnit::isAlwaysHeal() { return m_pUnit? m_pUnit->isAlwaysHeal(): false; } bool CyUnit::isHillsDoubleMove() { return m_pUnit? m_pUnit->isHillsDoubleMove(): false; } int CyUnit::getExtraVisibilityRange() { return m_pUnit? m_pUnit->getExtraVisibilityRange() : -1; } int CyUnit::getExtraMoves() { return m_pUnit? m_pUnit->getExtraMoves() : -1; } int CyUnit::getExtraMoveDiscount() { return m_pUnit? m_pUnit->getExtraMoveDiscount() : -1; } int CyUnit::getExtraAirRange() { return m_pUnit? m_pUnit->getExtraAirRange() : -1; } int CyUnit::getExtraIntercept() { return m_pUnit? m_pUnit->getExtraIntercept() : -1; } int CyUnit::getExtraEvasion() { return m_pUnit? m_pUnit->getExtraEvasion() : -1; } int CyUnit::getExtraFirstStrikes() { return m_pUnit? m_pUnit->getExtraFirstStrikes() : -1; } int CyUnit::getExtraChanceFirstStrikes() { return m_pUnit? m_pUnit->getExtraChanceFirstStrikes() : -1; } int CyUnit::getExtraWithdrawal() { return m_pUnit? m_pUnit->getExtraWithdrawal() : -1; } int CyUnit::getExtraCollateralDamage() { return m_pUnit? m_pUnit->getExtraCollateralDamage() : -1; } int CyUnit::getExtraEnemyHeal() { return m_pUnit? m_pUnit->getExtraEnemyHeal() : -1; } int CyUnit::getExtraNeutralHeal() { return m_pUnit? m_pUnit->getExtraNeutralHeal() : -1; } int CyUnit::getExtraFriendlyHeal() { return m_pUnit? m_pUnit->getExtraFriendlyHeal() : -1; } int CyUnit::getSameTileHeal() { return m_pUnit? m_pUnit->getSameTileHeal() : -1; } int CyUnit::getAdjacentTileHeal() { return m_pUnit? m_pUnit->getAdjacentTileHeal() : -1; } int CyUnit::getExtraCombatPercent() { return m_pUnit? m_pUnit->getExtraCombatPercent() : -1; } int CyUnit::getExtraCityAttackPercent() { return m_pUnit? m_pUnit->getExtraCityAttackPercent() : -1; } int CyUnit::getExtraCityDefensePercent() { return m_pUnit? m_pUnit->getExtraCityDefensePercent() : -1; } int CyUnit::getExtraHillsAttackPercent() { return m_pUnit? m_pUnit->getExtraHillsAttackPercent() : -1; } int CyUnit::getExtraHillsDefensePercent() { return m_pUnit? m_pUnit->getExtraHillsDefensePercent() : -1; } int CyUnit::getRevoltProtection() const { return m_pUnit? m_pUnit->getRevoltProtection() : -1; } int CyUnit::getCollateralDamageProtection() const { return m_pUnit? m_pUnit->getCollateralDamageProtection() : -1; } int CyUnit::getPillageChange() const { return m_pUnit? m_pUnit->getPillageChange() : -1; } int CyUnit::getUpgradeDiscount() const { return m_pUnit? m_pUnit->getUpgradeDiscount() : -1; } int CyUnit::getExperiencePercent() const { return m_pUnit? m_pUnit->getExperiencePercent() : -1; } int CyUnit::getKamikazePercent() const { return m_pUnit? m_pUnit->getKamikazePercent() : -1; } int CyUnit::getImmobileTimer() const { return m_pUnit? m_pUnit->getImmobileTimer() : -1; } void CyUnit::setImmobileTimer(int iNewValue) { if (m_pUnit) { m_pUnit->setImmobileTimer(iNewValue); } } bool CyUnit::isMadeAttack() { return m_pUnit? m_pUnit->isMadeAttack() : false; } void CyUnit::setMadeAttack(bool bNewValue) { if (m_pUnit) m_pUnit->setMadeAttack(bNewValue); } bool CyUnit::isMadeInterception() { return m_pUnit? m_pUnit->isMadeInterception() : false; } void CyUnit::setMadeInterception(bool bNewValue) { if (m_pUnit) m_pUnit->setMadeInterception(bNewValue); } bool CyUnit::isPromotionReady() { return m_pUnit? m_pUnit->isPromotionReady() : false; } void CyUnit::setPromotionReady(bool bNewValue) { if (m_pUnit) m_pUnit->setPromotionReady(bNewValue); } int CyUnit::getOwner() { return m_pUnit? m_pUnit->getOwnerINLINE() : -1; } int CyUnit::getVisualOwner() { return m_pUnit? m_pUnit->getVisualOwner() : -1; } int CyUnit::getCombatOwner(int iForTeam) { return m_pUnit? m_pUnit->getCombatOwner((TeamTypes)iForTeam, m_pUnit->plot()) : -1; } int CyUnit::getTeam() { return m_pUnit? m_pUnit->getTeam() : -1; } int /*UnitTypes*/ CyUnit::getUnitType() { return m_pUnit? (int)m_pUnit->getUnitType() : -1; } int /*UnitClassTypes*/ CyUnit::getUnitClassType() { return m_pUnit? (int)m_pUnit->getUnitClassType() : -1; } int /*UnitTypes*/ CyUnit::getLeaderUnitType() { return m_pUnit? (int)m_pUnit->getLeaderUnitType() : -1; } void CyUnit::setLeaderUnitType(int leaderUnitType) { if (m_pUnit) m_pUnit->setLeaderUnitType((UnitTypes) leaderUnitType); } CyUnit* CyUnit::getTransportUnit() const { return m_pUnit? new CyUnit(m_pUnit->getTransportUnit()) : NULL; } bool CyUnit::isCargo() { return m_pUnit? m_pUnit->isCargo() : false; } void CyUnit::setTransportUnit(CyUnit* pTransportUnit) { if (m_pUnit) m_pUnit->setTransportUnit(pTransportUnit->getUnit()); } int CyUnit::getExtraDomainModifier(int /*DomainTypes*/ eIndex) { return m_pUnit? m_pUnit->getExtraDomainModifier((DomainTypes) eIndex) : -1; } std::wstring CyUnit::getName() { return m_pUnit? m_pUnit->getName() : L""; } std::wstring CyUnit::getNameForm(int iForm) { return m_pUnit? m_pUnit->getName((uint)iForm) : L""; } std::wstring CyUnit::getNameKey() { return m_pUnit? m_pUnit->getNameKey() : L""; } std::wstring CyUnit::getNameNoDesc() { return m_pUnit? m_pUnit->getNameNoDesc() : L""; } void CyUnit::setName(std::wstring szNewValue) { if (m_pUnit) m_pUnit->setName(szNewValue); } std::string CyUnit::getScriptData() const { return m_pUnit? m_pUnit->getScriptData() : ""; } void CyUnit::setScriptData(std::string szNewValue) { if (m_pUnit) m_pUnit->setScriptData(szNewValue.c_str()); } bool CyUnit:: isTerrainDoubleMove(int /*TerrainTypes*/ eIndex) { return m_pUnit? m_pUnit->isTerrainDoubleMove((TerrainTypes) eIndex): false; } bool CyUnit:: isFeatureDoubleMove(int /*FeatureTypes*/ eIndex) { return m_pUnit? m_pUnit->isFeatureDoubleMove((FeatureTypes) eIndex): false; } int CyUnit::getExtraTerrainAttackPercent(int /*TerrainTypes*/ eIndex) { return m_pUnit? m_pUnit->getExtraTerrainAttackPercent((TerrainTypes) eIndex) : -1; } int CyUnit::getExtraTerrainDefensePercent(int /*TerrainTypes*/ eIndex) { return m_pUnit? m_pUnit->getExtraTerrainDefensePercent((TerrainTypes) eIndex) : -1; } int CyUnit::getExtraFeatureAttackPercent(int /*FeatureTypes*/ eIndex) { return m_pUnit? m_pUnit->getExtraFeatureAttackPercent((FeatureTypes) eIndex) : -1; } int CyUnit::getExtraFeatureDefensePercent(int /*FeatureTypes*/ eIndex) { return m_pUnit? m_pUnit->getExtraFeatureDefensePercent((FeatureTypes) eIndex) : -1; } int CyUnit::getExtraUnitCombatModifier(int /*UnitCombatTypes*/ eIndex) { return m_pUnit? m_pUnit->getExtraUnitCombatModifier((UnitCombatTypes) eIndex) : -1; } bool CyUnit::canAcquirePromotion(int /*PromotionTypes*/ ePromotion) { return m_pUnit? m_pUnit->canAcquirePromotion((PromotionTypes) ePromotion) : false; } bool CyUnit::canAcquirePromotionAny() { return m_pUnit? m_pUnit->canAcquirePromotionAny() : false; } bool CyUnit::isPromotionValid(int /*PromotionTypes*/ ePromotion) { return m_pUnit? m_pUnit->isPromotionValid((PromotionTypes) ePromotion) : false; } bool CyUnit::isHasPromotion(int /*PromotionTypes*/eIndex) { return m_pUnit? m_pUnit->isHasPromotion((PromotionTypes)eIndex) : false; } void CyUnit::setHasPromotion(int /*PromotionTypes*/ eIndex, bool bNewValue) { if (m_pUnit) m_pUnit->setHasPromotion((PromotionTypes) eIndex, bNewValue); } int /*UnitAITypes*/ CyUnit::getUnitAIType() { return m_pUnit? (int)m_pUnit->AI_getUnitAIType() : -1; } void CyUnit::setUnitAIType(int /*UnitAITypes*/ iNewValue) { if (m_pUnit) { m_pUnit->AI_setUnitAIType((UnitAITypes)iNewValue); } } bool CyUnit::IsSelected( void ) { return m_pUnit? m_pUnit->IsSelected() : false; } // Python Helper Functions void CyUnit::centerCamera() { if (m_pUnit) { gDLL->getInterfaceIFace()->centerCamera(m_pUnit); } } void CyUnit::attackForDamage(CyUnit *defender, int attakerDamageChange, int defenderDamageChange) { if(m_pUnit!= NULL) { m_pUnit->attackForDamage(defender->m_pUnit, attakerDamageChange, defenderDamageChange); } } void CyUnit::rangeStrike(int iX, int iY) { if(m_pUnit!= NULL) { m_pUnit->rangeStrike(iX, iY); } } const CvArtInfoUnit* CyUnit::getArtInfo(int i, EraTypes eEra) const { return m_pUnit? m_pUnit->getArtInfo(i, eEra) : NULL; } std::string CyUnit::getButton() const { return m_pUnit? m_pUnit->getButton() : ""; } ======================= File: BtS/CvGameCoreDLL/CyGlobalContextInterface2.cpp ======================= <gh_stars>10-100 // // published python interface for CyGlobalContext // Author - <NAME> // #include "CvGameCoreDLL.h" #include "CyMap.h" #include "CyPlayer.h" #include "CyGame.h" #include "CyGlobalContext.h" #include "CvRandom.h" //#include "CvStructs.h" #include "CvInfos.h" #include "CyTeam.h" void CyGlobalContextPythonInterface2(python::class_<CyGlobalContext>& x) { OutputDebugString("Python Extension Module - CyGlobalContextPythonInterface2\n"); x // global defines.xml .def("getDefineINT", &CyGlobalContext::getDefineINT, "int ( string szName )" ) .def("getDefineFLOAT", &CyGlobalContext::getDefineFLOAT, "float ( string szName )" ) .def("getDefineSTRING", &CyGlobalContext::getDefineSTRING, "string getDefineSTRING( string szName )" ) .def("setDefineINT", &CyGlobalContext::setDefineINT, "void ( string szName, int iValue )" ) .def("setDefineFLOAT", &CyGlobalContext::setDefineFLOAT, "void setDefineFLOAT( string szName, float fValue )" ) .def("setDefineSTRING", &CyGlobalContext::setDefineSTRING, "void ( string szName, string szValue )" ) .def("getMOVE_DENOMINATOR", &CyGlobalContext::getMOVE_DENOMINATOR, "int ()") .def("getNUM_UNIT_PREREQ_OR_BONUSES", &CyGlobalContext::getNUM_UNIT_PREREQ_OR_BONUSES, "int ()") .def("getNUM_BUILDING_PREREQ_OR_BONUSES", &CyGlobalContext::getNUM_BUILDING_PREREQ_OR_BONUSES, "int ()") .def("getFOOD_CONSUMPTION_PER_POPULATION", &CyGlobalContext::getFOOD_CONSUMPTION_PER_POPULATION, "int ()") .def("getMAX_HIT_POINTS", &CyGlobalContext::getMAX_HIT_POINTS, "int ()") .def("getHILLS_EXTRA_DEFENSE", &CyGlobalContext::getHILLS_EXTRA_DEFENSE, "int ()") .def("getRIVER_ATTACK_MODIFIER", &CyGlobalContext::getRIVER_ATTACK_MODIFIER, "int ()") .def("getAMPHIB_ATTACK_MODIFIER", &CyGlobalContext::getAMPHIB_ATTACK_MODIFIER, "int ()") .def("getHILLS_EXTRA_MOVEMENT", &CyGlobalContext::getHILLS_EXTRA_MOVEMENT, "int ()") .def("getMAX_PLOT_LIST_ROWS", &CyGlobalContext::getMAX_PLOT_LIST_ROWS, "int ()") .def("getUNIT_MULTISELECT_MAX", &CyGlobalContext::getUNIT_MULTISELECT_MAX, "int ()") .def("getPERCENT_ANGER_DIVISOR", &CyGlobalContext::getPERCENT_ANGER_DIVISOR, "int ()") .def("getEVENT_MESSAGE_TIME", &CyGlobalContext::getEVENT_MESSAGE_TIME, "int ()") .def("getROUTE_FEATURE_GROWTH_MODIFIER", &CyGlobalContext::getROUTE_FEATURE_GROWTH_MODIFIER, "int ()") .def("getFEATURE_GROWTH_MODIFIER", &CyGlobalContext::getFEATURE_GROWTH_MODIFIER, "int ()") .def("getMIN_CITY_RANGE", &CyGlobalContext::getMIN_CITY_RANGE, "int ()") .def("getCITY_MAX_NUM_BUILDINGS", &CyGlobalContext::getCITY_MAX_NUM_BUILDINGS, "int ()") .def("getNUM_UNIT_AND_TECH_PREREQS", &CyGlobalContext::getNUM_UNIT_AND_TECH_PREREQS, "int ()") .def("getNUM_AND_TECH_PREREQS", &CyGlobalContext::getNUM_AND_TECH_PREREQS, "int ()") .def("getNUM_OR_TECH_PREREQS", &CyGlobalContext::getNUM_OR_TECH_PREREQS, "int ()") .def("getLAKE_MAX_AREA_SIZE", &CyGlobalContext::getLAKE_MAX_AREA_SIZE, "int ()") .def("getNUM_ROUTE_PREREQ_OR_BONUSES", &CyGlobalContext::getNUM_ROUTE_PREREQ_OR_BONUSES, "int ()") .def("getNUM_BUILDING_AND_TECH_PREREQS", &CyGlobalContext::getNUM_BUILDING_AND_TECH_PREREQS, "int ()") .def("getMIN_WATER_SIZE_FOR_OCEAN", &CyGlobalContext::getMIN_WATER_SIZE_FOR_OCEAN, "int ()") .def("getFORTIFY_MODIFIER_PER_TURN", &CyGlobalContext::getFORTIFY_MODIFIER_PER_TURN, "int ()") .def("getMAX_CITY_DEFENSE_DAMAGE", &CyGlobalContext::getMAX_CITY_DEFENSE_DAMAGE, "int ()") .def("getNUM_CORPORATION_PREREQ_BONUSES", &CyGlobalContext::getNUM_CORPORATION_PREREQ_BONUSES, "int ()") .def("getPEAK_SEE_THROUGH_CHANGE", &CyGlobalContext::getPEAK_SEE_THROUGH_CHANGE, "int ()") .def("getHILLS_SEE_THROUGH_CHANGE", &CyGlobalContext::getHILLS_SEE_THROUGH_CHANGE, "int ()") .def("getSEAWATER_SEE_FROM_CHANGE", &CyGlobalContext::getSEAWATER_SEE_FROM_CHANGE, "int ()") .def("getPEAK_SEE_FROM_CHANGE", &CyGlobalContext::getPEAK_SEE_FROM_CHANGE, "int ()") .def("getHILLS_SEE_FROM_CHANGE", &CyGlobalContext::getHILLS_SEE_FROM_CHANGE, "int ()") .def("getUSE_SPIES_NO_ENTER_BORDERS", &CyGlobalContext::getUSE_SPIES_NO_ENTER_BORDERS, "int ()") .def("getCAMERA_MIN_YAW", &CyGlobalContext::getCAMERA_MIN_YAW, "float ()") .def("getCAMERA_MAX_YAW", &CyGlobalContext::getCAMERA_MAX_YAW, "float ()") .def("getCAMERA_FAR_CLIP_Z_HEIGHT", &CyGlobalContext::getCAMERA_FAR_CLIP_Z_HEIGHT, "float ()") .def("getCAMERA_MAX_TRAVEL_DISTANCE", &CyGlobalContext::getCAMERA_MAX_TRAVEL_DISTANCE, "float ()") .def("getCAMERA_START_DISTANCE", &CyGlobalContext::getCAMERA_START_DISTANCE, "float ()") .def("getAIR_BOMB_HEIGHT", &CyGlobalContext::getAIR_BOMB_HEIGHT, "float ()") .def("getPLOT_SIZE", &CyGlobalContext::getPLOT_SIZE, "float ()") .def("getCAMERA_SPECIAL_PITCH", &CyGlobalContext::getCAMERA_SPECIAL_PITCH, "float ()") .def("getCAMERA_MAX_TURN_OFFSET", &CyGlobalContext::getCAMERA_MAX_TURN_OFFSET, "float ()") .def("getCAMERA_MIN_DISTANCE", &CyGlobalContext::getCAMERA_MIN_DISTANCE, "float ()") .def("getCAMERA_UPPER_PITCH", &CyGlobalContext::getCAMERA_UPPER_PITCH, "float ()") .def("getCAMERA_LOWER_PITCH", &CyGlobalContext::getCAMERA_LOWER_PITCH, "float ()") .def("getFIELD_OF_VIEW", &CyGlobalContext::getFIELD_OF_VIEW, "float ()") .def("getSHADOW_SCALE", &CyGlobalContext::getSHADOW_SCALE, "float ()") .def("getUNIT_MULTISELECT_DISTANCE", &CyGlobalContext::getUNIT_MULTISELECT_DISTANCE, "float ()") .def("getMAX_CIV_PLAYERS", &CyGlobalContext::getMAX_CIV_PLAYERS, "int ()") .def("getMAX_PLAYERS", &CyGlobalContext::getMAX_PLAYERS, "int ()") .def("getMAX_CIV_TEAMS", &CyGlobalContext::getMAX_CIV_TEAMS, "int ()") .def("getMAX_TEAMS", &CyGlobalContext::getMAX_TEAMS, "int ()") .def("getBARBARIAN_PLAYER", &CyGlobalContext::getBARBARIAN_PLAYER, "int ()") .def("getBARBARIAN_TEAM", &CyGlobalContext::getBARBARIAN_TEAM, "int ()") .def("getINVALID_PLOT_COORD", &CyGlobalContext::getINVALID_PLOT_COORD, "int ()") .def("getNUM_CITY_PLOTS", &CyGlobalContext::getNUM_CITY_PLOTS, "int ()") .def("getCITY_HOME_PLOT", &CyGlobalContext::getCITY_HOME_PLOT, "int ()") ; } ======================= File: BtS/CvGameCoreDLL/CvStatistics.cpp ======================= <filename>BtS/CvGameCoreDLL/CvStatistics.cpp<gh_stars>10-100 #include "CvGameCoreDLL.h" #include "CvStatistics.h" #include "CvUnit.h" #include "CvCity.h" #include "CvGlobals.h" #include "CvGameAI.h" #include "CvPlayerAI.h" CvGameRecord::CvGameRecord() { init(); } CvGameRecord::~CvGameRecord() { uninit(); } void CvGameRecord::init() { reset(); } void CvGameRecord::uninit() { } void CvGameRecord::reset() { uninit(); m_eEra = NO_ERA; m_szMapName.clear(); } void CvGameRecord::setMapName(const char * szMapName) { m_szMapName = szMapName; } const CvString& CvGameRecord::getMapName() const { return m_szMapName; } void CvGameRecord::setEra( EraTypes eEra ) { m_eEra = eEra; } EraTypes CvGameRecord::getEra() const { return m_eEra; } void CvGameRecord::read(FDataStreamBase* pStream) { // reset before loading reset(); uint uiFlag=0; pStream->Read(&uiFlag); // flags for expansion pStream->Read((int*)&m_eEra); pStream->ReadString(m_szMapName); } void CvGameRecord::write(FDataStreamBase* pStream) { uint uiFlag=0; pStream->Write(uiFlag); // flags for expansion pStream->Write(m_eEra); pStream->WriteString(m_szMapName); } CvPlayerRecord::CvPlayerRecord() { m_piNumUnitsBuilt = NULL; m_piNumUnitsKilled = NULL; m_piNumUnitsWasKilled = NULL; m_piNumBuildingsBuilt = NULL; m_pbReligionFounded = NULL; init(); } CvPlayerRecord::~CvPlayerRecord() { uninit(); } void CvPlayerRecord::init() { reset(); } void CvPlayerRecord::uninit() { SAFE_DELETE_ARRAY(m_piNumUnitsBuilt); SAFE_DELETE_ARRAY(m_piNumUnitsKilled); SAFE_DELETE_ARRAY(m_piNumUnitsWasKilled); SAFE_DELETE_ARRAY(m_piNumBuildingsBuilt); SAFE_DELETE_ARRAY(m_pbReligionFounded); } void CvPlayerRecord::reset() { uninit(); m_iID = -1; m_iTime = 0; m_eVictory = NO_VICTORY; m_eLeader = NO_LEADER; m_piNumUnitsBuilt = new int[GC.getNumUnitInfos()]; m_piNumUnitsKilled = new int[GC.getNumUnitInfos()]; m_piNumUnitsWasKilled = new int[GC.getNumUnitInfos()]; m_piNumBuildingsBuilt = new int[GC.getNumBuildingInfos()]; m_pbReligionFounded = new bool[GC.getNumReligionInfos()]; int i; for (i = 0; i < GC.getNumUnitInfos(); ++i) { m_piNumUnitsBuilt[i] = 0; m_piNumUnitsKilled[i] = 0; m_piNumUnitsWasKilled[i] = 0; } for (i = 0; i < GC.getNumBuildingInfos(); ++i) { m_piNumBuildingsBuilt[i] = 0; } for (i = 0; i < GC.getNumReligionInfos(); ++i) { m_pbReligionFounded[i] = false; } m_iNumCitiesBuilt = 0; m_iNumCitiesRazed = 0; m_iNumGoldenAges = 0; } void CvPlayerRecord::unitBuilt( CvUnit *pUnit ) { ++m_piNumUnitsBuilt[pUnit->getUnitType()]; } int CvPlayerRecord::getNumUnitsBuilt(int iUnitType) const { return m_piNumUnitsBuilt[iUnitType]; } void CvPlayerRecord::unitKilled( CvUnit * pUnit ) { ++m_piNumUnitsKilled[pUnit->getUnitType()]; } int CvPlayerRecord::getNumUnitsKilled(int iUnitType) const { return m_piNumUnitsKilled[iUnitType]; } void CvPlayerRecord::unitWasKilled( CvUnit * pUnit ) { ++m_piNumUnitsWasKilled[pUnit->getUnitType()]; } int CvPlayerRecord::getNumUnitsWasKilled(int iUnitType) const { return m_piNumUnitsWasKilled[iUnitType]; } void CvPlayerRecord::buildingBuilt( BuildingTypes eBuilding ) { ++m_piNumBuildingsBuilt[(int)eBuilding]; } int CvPlayerRecord::getNumBuildingsBuilt(BuildingTypes eBuilding) const { return m_piNumBuildingsBuilt[(int)eBuilding]; } void CvPlayerRecord::religionFounded( ReligionTypes eReligion ) { m_pbReligionFounded[(int)eReligion] = true; } bool CvPlayerRecord::getReligionFounded( ReligionTypes eReligion ) const { return m_pbReligionFounded[(int)eReligion]; } void CvPlayerRecord::setPlayerID( int iID ) { m_iID = iID; } int CvPlayerRecord::getPlayerID() const { return m_iID; } void CvPlayerRecord::setVictory(VictoryTypes eVictory) { m_eVictory = eVictory; } int CvPlayerRecord::getVictory() const { return m_eVictory; } void CvPlayerRecord::setTimePlayed( int iTime ) { m_iTime = iTime; } int CvPlayerRecord::getMinutesPlayed() const { return m_iTime; } void CvPlayerRecord::setLeader( LeaderHeadTypes eLeader ) { m_eLeader = eLeader; } LeaderHeadTypes CvPlayerRecord::getLeader() const { return m_eLeader; } void CvPlayerRecord::cityBuilt() { ++m_iNumCitiesBuilt; } int CvPlayerRecord::getNumCitiesBuilt() const { return m_iNumCitiesBuilt; } void CvPlayerRecord::cityRazed() { ++m_iNumCitiesRazed; } int CvPlayerRecord::getNumCitiesRazed() const { return m_iNumCitiesRazed; } void CvPlayerRecord::goldenAge() { ++m_iNumGoldenAges; } int CvPlayerRecord::getNumGoldenAges() const { return m_iNumGoldenAges; } void CvPlayerRecord::read(FDataStreamBase* pStream) { // reset before loading reset(); uint uiFlag=0; pStream->Read(&uiFlag); // flags for expansion pStream->Read(&m_iID); pStream->Read(&m_iTime); pStream->Read((int*)&m_eVictory); pStream->Read((int*)&m_eLeader); pStream->Read(GC.getNumUnitInfos(), m_piNumUnitsBuilt); pStream->Read(GC.getNumUnitInfos(), m_piNumUnitsKilled); pStream->Read(GC.getNumUnitInfos(), m_piNumUnitsWasKilled); pStream->Read(GC.getNumBuildingInfos(), m_piNumBuildingsBuilt); pStream->Read(GC.getNumReligionInfos(), m_pbReligionFounded); pStream->Read(&m_iNumCitiesBuilt); pStream->Read(&m_iNumCitiesRazed); pStream->Read(&m_iNumGoldenAges); } void CvPlayerRecord::write(FDataStreamBase* pStream) { uint uiFlag=0; pStream->Write(uiFlag); // flags for expansion pStream->Write(m_iID); pStream->Write(m_iTime); pStream->Write(m_eVictory); pStream->Write(m_eLeader); pStream->Write(GC.getNumUnitInfos(), m_piNumUnitsBuilt); pStream->Write(GC.getNumUnitInfos(), m_piNumUnitsKilled); pStream->Write(GC.getNumUnitInfos(), m_piNumUnitsWasKilled); pStream->Write(GC.getNumBuildingInfos(), m_piNumBuildingsBuilt); pStream->Write(GC.getNumReligionInfos(), m_pbReligionFounded); pStream->Write(m_iNumCitiesBuilt); pStream->Write(m_iNumCitiesRazed); pStream->Write(m_iNumGoldenAges); } //////////////////////////////////////////////////////////////////// // CvStatistics /////////////////////////////////////////////////////////////////// CvStatistics::~CvStatistics() { uninit(); } // // Initialization // void CvStatistics::init() { reset(); } void CvStatistics::uninit() { for(int i=0;i<(int)m_PlayerRecords.size();i++) { SAFE_DELETE(m_PlayerRecords[i]); // free memory - MT } m_PlayerRecords.clear(); } void CvStatistics::reset() { uninit(); } // // Setting game-specific stats // void CvStatistics::setMapName(const char * szMapName) { m_GameRecord.setMapName(szMapName); } void CvStatistics::setEra(EraTypes eEra) { m_GameRecord.setEra(eEra); } // // Setting player-specific stats // void CvStatistics::setVictory( TeamTypes eWinner, VictoryTypes eVictory ) { // Report a victory for all players on this team... for (int i = 0; i < MAX_CIV_PLAYERS; ++i) { if (GET_PLAYER((PlayerTypes)i).isEverAlive()) { // DAN: They could be eliminated and still watching the game and get a win! // How to prevent this? if ( (GET_PLAYER((PlayerTypes)i).isHuman()) && (GET_PLAYER((PlayerTypes)i).getTeam() == eWinner) ) { // If this guy is still alive and on the winning team, record the victory getPlayerRecord(i)->setVictory(eVictory); } else { // Record the loss getPlayerRecord(i)->setVictory(NO_VICTORY); } } } } void CvStatistics::setTimePlayed( PlayerTypes ePlayer, int iTime ) { getPlayerRecord((int)ePlayer)->setTimePlayed(iTime); } void CvStatistics::setLeader( PlayerTypes ePlayer, LeaderHeadTypes eLeader ) { getPlayerRecord((int)ePlayer)->setLeader(eLeader); } // // Player-specific stat events // void CvStatistics::unitBuilt( CvUnit *pUnit ) { getPlayerRecord( pUnit->getOwner() )->unitBuilt( pUnit ); } void CvStatistics::unitKilled( CvUnit *pUnit, PlayerTypes eAttacker ) { getPlayerRecord( eAttacker )->unitKilled( pUnit ); getPlayerRecord( pUnit->getOwner() )->unitWasKilled( pUnit ); } void CvStatistics::cityBuilt( CvCity *pCity ) { getPlayerRecord( pCity->getOwner() )->cityBuilt(); } void CvStatistics::cityRazed( CvCity * pCity, PlayerTypes ePlayer ) { getPlayerRecord( ePlayer )->cityRazed(); } void CvStatistics::buildingBuilt( CvCity *pCity, BuildingTypes eBuilding ) { getPlayerRecord( pCity->getOwner() )->buildingBuilt(eBuilding); } void CvStatistics::religionFounded( ReligionTypes eReligion, PlayerTypes eFounder ) { getPlayerRecord( eFounder )->religionFounded(eReligion); } void CvStatistics::goldenAge( PlayerTypes ePlayer ) { getPlayerRecord( ePlayer )->goldenAge(); } void CvStatistics::read(FDataStreamBase* pStream) { // Read game data into record m_GameRecord.read(pStream); // Read player data into records for (int i = 0; i < MAX_PLAYERS; ++i) { if (GET_PLAYER((PlayerTypes)i).isEverAlive()) { getPlayerRecord(i)->read(pStream); } } } void CvStatistics::write(FDataStreamBase* pStream) { // Write game data into record m_GameRecord.write(pStream); // Write player data into records for (int i = 0; i < MAX_PLAYERS; ++i) { if (GET_PLAYER((PlayerTypes)i).isEverAlive()) { getPlayerRecord(i)->write(pStream); } } } // // Player record accessor // CvPlayerRecord *CvStatistics::getPlayerRecord(int iIndex) { FAssert(iIndex >= 0); FAssert(iIndex < MAX_PLAYERS); if ( iIndex >= (int)m_PlayerRecords.size() || m_PlayerRecords[iIndex] == NULL ) { CvPlayerRecord *pRecord = new CvPlayerRecord; pRecord->init(); pRecord->setPlayerID( iIndex ); m_PlayerRecords.resize(iIndex + 1, NULL); m_PlayerRecords[iIndex] = pRecord; } return m_PlayerRecords[iIndex]; } const char* CvStatistics::getMapName() const { return m_GameRecord.getMapName().GetCString(); } EraTypes CvStatistics::getEra() const { return m_GameRecord.getEra(); } ======================= File: Warlords/CvGameCoreDLL/CvPopupReturn.cpp ======================= #include "CvGameCoreDLL.h" #include "CvPopupReturn.h" #define CvPopup_SetAtGrow(kArray, iIdx, kValue)\ if((int)kArray.size() <= iIdx) kArray.resize(iIdx+1);\ kArray[iIdx] = kValue; PopupReturn::PopupReturn(const PopupReturn &popupReturn) { int iI; for (iI = 0; iI < popupReturn.getRadioButtonSize(); iI++) { CvPopup_SetAtGrow(m_aiSelectedRadioButton, iI, popupReturn.getSelectedRadioButton( iI )); } for (iI = 0; iI < popupReturn.getCheckboxSize(); iI++) { CvPopup_SetAtGrow(m_aiBitField, iI, popupReturn.getCheckboxBitfield( iI )); } for (iI = 0; iI < popupReturn.getEditboxSize(); iI++) { CvPopup_SetAtGrow(m_aszEditBoxString, iI, popupReturn.getEditBoxString( iI )); } for (iI = 0; iI < popupReturn.getSpinnerWidsize(); iI++) { CvPopup_SetAtGrow(m_aiSpinnerWidgetValues, iI, popupReturn.getSpinnerWidgetValue( iI )); } for (iI = 0; iI < popupReturn.getPulldownSize(); iI++) { CvPopup_SetAtGrow(m_aiPulldownID, iI, popupReturn.getSelectedPullDownValue( iI )); } for (iI = 0; iI < popupReturn.getListBoxSize(); iI++) { CvPopup_SetAtGrow(m_aiListBoxID, iI, popupReturn.getSelectedListBoxValue( iI )); } for (iI = 0; iI < popupReturn.getSpinBoxSize(); iI++) { CvPopup_SetAtGrow(m_aiSpinBoxID, iI, popupReturn.getSpinnerWidgetValue( iI )); } for (iI = 0; iI < popupReturn.getButtonSize(); iI++) { CvPopup_SetAtGrow(m_aiButtonID, iI, popupReturn.getButtonClicked( iI )); } } // Assignment operator PopupReturn &PopupReturn::operator=(const PopupReturn &source) { int iI; for (iI = 0; iI < source.getRadioButtonSize(); iI++) { CvPopup_SetAtGrow(m_aiSelectedRadioButton, iI, source.getSelectedRadioButton( iI )); } for (iI = 0; iI < source.getCheckboxSize(); iI++) { CvPopup_SetAtGrow(m_aiBitField, iI, source.getCheckboxBitfield( iI )); } for (iI = 0; iI < source.getEditboxSize(); iI++) { CvPopup_SetAtGrow(m_aszEditBoxString, iI, source.getEditBoxString( iI )); } for (iI = 0; iI < source.getSpinnerWidsize(); iI++) { CvPopup_SetAtGrow(m_aiSpinnerWidgetValues, iI, source.getSpinnerWidgetValue( iI )); } for (iI = 0; iI < source.getPulldownSize(); iI++) { CvPopup_SetAtGrow(m_aiPulldownID, iI, source.getSelectedPullDownValue( iI )); } for (iI = 0; iI < source.getListBoxSize(); iI++) { CvPopup_SetAtGrow(m_aiListBoxID, iI, source.getSelectedListBoxValue( iI )); } for (iI = 0; iI < source.getSpinBoxSize(); iI++) { CvPopup_SetAtGrow(m_aiSpinBoxID, iI, source.getSpinnerWidgetValue( iI )); } for (iI = 0; iI < source.getButtonSize(); iI++) { CvPopup_SetAtGrow(m_aiButtonID, iI, source.getButtonClicked( iI )); } return ( *this ); } // // read object from a stream // void PopupReturn::read(FDataStreamBase* pStream) { int iSize; int iValue; int i; wchar szValue[1024]; pStream->Read( &iSize ); for (i = 0; i < iSize; i++) { pStream->Read( &iValue ); CvPopup_SetAtGrow(m_aiSelectedRadioButton, i, iValue ); } pStream->Read( &iSize ); for (i = 0; i < iSize; i++) { pStream->Read( &iValue ); CvPopup_SetAtGrow(m_aiBitField, i, iValue ); } pStream->Read( &iSize ); for (i = 0; i < iSize; i++) { pStream->ReadString( szValue ); CvPopup_SetAtGrow(m_aszEditBoxString, i, szValue ); } pStream->Read( &iSize ); for (i = 0; i < iSize; i++) { pStream->Read( &iValue ); CvPopup_SetAtGrow(m_aiSpinnerWidgetValues, i, iValue ); } pStream->Read( &iSize ); for (i = 0; i < iSize; i++) { pStream->Read( &iValue ); CvPopup_SetAtGrow(m_aiPulldownID, i, iValue ); } pStream->Read( &iSize ); for (i = 0; i < iSize; i++) { pStream->Read( &iValue ); CvPopup_SetAtGrow(m_aiListBoxID, i, iValue ); } pStream->Read( &iSize ); for (i = 0; i < iSize; i++) { pStream->Read( &iValue ); CvPopup_SetAtGrow(m_aiSpinBoxID, i, iValue); } pStream->Read( &iSize ); for (i = 0; i < iSize; i++) { pStream->Read( &iValue ); CvPopup_SetAtGrow(m_aiButtonID, i, iValue ); } } // // write object to a stream // void PopupReturn::write(FDataStreamBase* pStream) const { unsigned int iI; //char szString[1024]; pStream->Write( m_aiSelectedRadioButton.size() ); for (iI = 0; iI < m_aiSelectedRadioButton.size(); iI++) { pStream->Write( m_aiSelectedRadioButton[iI] ); } pStream->Write( m_aiBitField.size() ); for (iI = 0; iI < m_aiBitField.size(); iI++) { pStream->Write( m_aiBitField[iI] ); } pStream->Write( m_aszEditBoxString.size() ); for (iI = 0; iI < m_aszEditBoxString.size(); iI++) { CvWString ws(m_aszEditBoxString[iI]); pStream->WriteString( ws.c_str() ); } pStream->Write( m_aiSpinnerWidgetValues.size() ); for (iI = 0; iI < m_aiSpinnerWidgetValues.size(); iI++) { pStream->Write( m_aiSpinnerWidgetValues[iI] ); } pStream->Write( m_aiPulldownID.size() ); for (iI = 0; iI < m_aiPulldownID.size(); iI++) { pStream->Write( m_aiPulldownID[iI] ); } pStream->Write( m_aiListBoxID.size() ); for (iI = 0; iI < m_aiListBoxID.size(); iI++) { pStream->Write( m_aiListBoxID[iI] ); } pStream->Write( m_aiSpinBoxID.size() ); for (iI = 0; iI < m_aiSpinBoxID.size(); iI++) { pStream->Write( m_aiSpinBoxID[iI] ); } pStream->Write( m_aiButtonID.size() ); for (iI = 0; iI < m_aiButtonID.size(); iI++) { pStream->Write( m_aiButtonID[iI] ); } } ======================= File: Warlords/CvGameCoreDLL/CyHallOfFameInfo.cpp ======================= #include "CvGameCoreDLL.h" #include "CyHallOfFameInfo.h" #include "CyReplayInfo.h" CyHallOfFameInfo::CyHallOfFameInfo() { } void CyHallOfFameInfo::loadReplays() { m_hallOfFame.loadReplays(); } int CyHallOfFameInfo::getNumGames() const { return m_hallOfFame.getNumGames(); } CyReplayInfo* CyHallOfFameInfo::getReplayInfo(int i) { return (new CyReplayInfo(m_hallOfFame.getReplayInfo(i))); } ======================= File: Warlords/CvGameCoreDLL/CyMap.cpp ======================= // // Python wrapper class for CvMap // #include "CvGameCoreDLL.h" #include "cyMap.h" #include "CyPlot.h" #include "CvMap.h" #include "CyCity.h" #include "CySelectionGroup.h" #include "CyUnit.h" #include "CyArea.h" #include "CvGlobals.h" #include "CvMapGenerator.h" #include "CvInitCore.h" CyMap::CyMap() : m_pMap(NULL) { m_pMap = &GC.getMapINLINE(); } CyMap::CyMap(CvMap* pMap) : m_pMap(pMap) { } void CyMap::erasePlots() { if (m_pMap) m_pMap->erasePlots(); } void CyMap::setRevealedPlots(int /*TeamTypes*/ eTeam, bool bNewValue, bool bTerrainOnly) { if (m_pMap) m_pMap->setRevealedPlots((TeamTypes) eTeam, bNewValue, bTerrainOnly); } void CyMap::setAllPlotTypes(int /*PlotTypes*/ ePlotType) { if (m_pMap) m_pMap->setAllPlotTypes((PlotTypes) ePlotType); } void CyMap::updateVisibility() { if (m_pMap) m_pMap->updateVisibility(); } CyPlot* CyMap::syncRandPlot(int iFlags, int iArea, int iMinUnitDistance, int iTimeout) { return m_pMap? new CyPlot(m_pMap->syncRandPlot(iFlags, iArea, iMinUnitDistance, iTimeout)) : NULL; } CyCity* CyMap::findCity(int iX, int iY, int /*PlayerTypes*/ eOwner, int /*TeamTypes*/ eTeam, bool bSameArea, bool bCoastalOnly, int /*TeamTypes*/ eTeamAtWarWith, int /*DirectionTypes*/ eDirection, CyCity* pSkipCity) { return m_pMap? new CyCity(m_pMap->findCity(iX, iY, (PlayerTypes)eOwner, (TeamTypes)eTeam, bSameArea, bCoastalOnly, ((TeamTypes)eTeamAtWarWith), (DirectionTypes)eDirection, pSkipCity->getCity())) : NULL; } CySelectionGroup* CyMap::findSelectionGroup(int iX, int iY, int /*PlayerTypes*/ eOwner, bool bReadyToSelect, bool bWorkers) { return m_pMap? new CySelectionGroup(m_pMap->findSelectionGroup(iX, iY, (PlayerTypes)eOwner, bReadyToSelect, bWorkers)) : NULL; } CyArea* CyMap::findBiggestArea(bool bWater) { return m_pMap? new CyArea(m_pMap->findBiggestArea(bWater)) : NULL; } int CyMap::getMapFractalFlags() { return m_pMap? m_pMap->getMapFractalFlags() : -1; } bool CyMap::findWater(CyPlot* pPlot, int iRange, bool bFreshWater) { return m_pMap? m_pMap->findWater(pPlot->getPlot(), iRange, bFreshWater) : false; } bool CyMap::isPlot(int iX, int iY) { return m_pMap? m_pMap->isPlotINLINE(iX, iY) : false; } int CyMap::numPlots() { return m_pMap? m_pMap->numPlotsINLINE() : -1; } int CyMap::plotNum(int iX, int iY) { return m_pMap? m_pMap->plotNumINLINE(iX, iY) : -1; } int CyMap::plotX(int iIndex) { return m_pMap? m_pMap->plotX(iIndex) : -1; } int CyMap::plotY(int iIndex) { return m_pMap? m_pMap->plotY(iIndex) : -1; } int CyMap::getGridWidth() { return m_pMap->getGridWidthINLINE(); } int CyMap::getGridHeight() { return m_pMap->getGridHeightINLINE(); } int CyMap::getLandPlots() { return m_pMap? m_pMap->getLandPlots() : -1; } int CyMap::getOwnedPlots() { return m_pMap? m_pMap->getOwnedPlots() : -1; } int CyMap::getTopLatitude() { return m_pMap? m_pMap->getTopLatitude() : -1; } int CyMap::getBottomLatitude() { return m_pMap? m_pMap->getBottomLatitude() : -1; } int CyMap::getNextRiverID() { return m_pMap? m_pMap->getNextRiverID() : -1; } void CyMap::incrementNextRiverID() { if (m_pMap) m_pMap->incrementNextRiverID(); } bool CyMap::isWrapX() { return m_pMap? m_pMap->isWrapXINLINE() : false; } bool CyMap::isWrapY() { return m_pMap? m_pMap->isWrapYINLINE() : false; } std::wstring CyMap::getMapScriptName() { return GC.getInitCore().getMapScriptName().GetCString(); } WorldSizeTypes CyMap::getWorldSize() { return m_pMap? m_pMap->getWorldSize() : NO_WORLDSIZE; } ClimateTypes CyMap::getClimate() { return m_pMap? m_pMap->getClimate() : NO_CLIMATE; } SeaLevelTypes CyMap::getSeaLevel() { return m_pMap? m_pMap->getSeaLevel() : NO_SEALEVEL; } int CyMap::getNumCustomMapOptions() { return m_pMap? m_pMap->getNumCustomMapOptions() : 0; } CustomMapOptionTypes CyMap::getCustomMapOption(int iOption) { return m_pMap? m_pMap->getCustomMapOption(iOption) : NO_CUSTOM_MAPOPTION; } int CyMap::getNumBonuses(int /* BonusTypes */ eIndex) { return m_pMap? m_pMap->getNumBonuses((BonusTypes)eIndex) : -1; } int CyMap::getNumBonusesOnLand(int /* BonusTypes */ eIndex) { return m_pMap? m_pMap->getNumBonusesOnLand((BonusTypes)eIndex) : -1; } CyPlot* CyMap::plotByIndex(int iIndex) { return m_pMap? new CyPlot(m_pMap->plotByIndexINLINE(iIndex)) : NULL; } // // static version // CyPlot* CyMap::sPlotByIndex(int iIndex) { static CyPlot plot; if (m_pMap) { plot.setPlot(m_pMap->plotByIndexINLINE(iIndex)); return &plot; } return NULL; } CyPlot* CyMap::plot(int iX, int iY) { return new CyPlot(m_pMap->plotINLINE(iX, iY)); } // // static version // CyPlot* CyMap::sPlot(int iX, int iY) { static CyPlot p; p.setPlot(m_pMap->plotINLINE(iX, iY)); return &p; } CyPlot* CyMap::pointToPlot(float fX, float fY) { return m_pMap? new CyPlot(m_pMap->pointToPlot(fX, fY)) : NULL; } int CyMap::getIndexAfterLastArea() { return m_pMap? m_pMap->getIndexAfterLastArea() : -1; } int CyMap::getNumAreas() { return m_pMap? m_pMap->getNumAreas() : -1; } int CyMap::getNumLandAreas() { return m_pMap? m_pMap->getNumLandAreas() : -1; } CyArea* CyMap::getArea(int iID) { return m_pMap? new CyArea(m_pMap->getArea(iID)) : NULL; } void CyMap::recalculateAreas() { if (m_pMap) m_pMap->recalculateAreas(); } void CyMap::resetPathDistance() { if (m_pMap) m_pMap->resetPathDistance(); } int CyMap::calculatePathDistance(CyPlot* pSource, CyPlot* pDest) { if (m_pMap) return m_pMap->calculatePathDistance(pSource->getPlot(), pDest->getPlot()); return -1; } void CyMap::rebuild(int iGridW, int iGridH, int iTopLatitude, int iBottomLatitude, bool bWrapX, bool bWrapY, WorldSizeTypes eWorldSize, ClimateTypes eClimate, SeaLevelTypes eSeaLevel, int iNumCustomMapOptions, CustomMapOptionTypes * aeCustomMapOptions) { if (m_pMap) { m_pMap->rebuild(iGridW, iGridH, iTopLatitude, iBottomLatitude, bWrapX, bWrapY, eWorldSize, eClimate, eSeaLevel, iNumCustomMapOptions, aeCustomMapOptions); } } void CyMap::regenerateGameElements() { if (m_pMap) { CvMapGenerator* pMapGen = &CvMapGenerator::GetInstance(); pMapGen->eraseRivers(); pMapGen->eraseFeatures(); pMapGen->eraseBonuses(); pMapGen->eraseGoodies(); pMapGen->addGameElements(); } } void CyMap::updateFog() { if (m_pMap) { m_pMap->updateFog(); } } void CyMap::updateMinimapColor() { if (m_pMap) { m_pMap->updateMinimapColor(); } } void CyMap::updateMinOriginalStartDist(CyArea* pArea) { if (m_pMap) { m_pMap->updateMinOriginalStartDist(pArea->getArea()); } } ======================= File: Warlords/CvGameCoreDLL/CvGameAI.cpp ======================= // gameAI.cpp #include "CvGameCoreDLL.h" #include "CvGameAI.h" #include "CvPlayerAI.h" #include "CvGlobals.h" #include "CvInfos.h" // Public Functions... CvGameAI::CvGameAI() { AI_reset(); } CvGameAI::~CvGameAI() { AI_uninit(); } void CvGameAI::AI_init() { AI_reset(); //-------------------------------- // Init other game data } void CvGameAI::AI_uninit() { } void CvGameAI::AI_reset() { AI_uninit(); m_iPad = 0; } void CvGameAI::AI_makeAssignWorkDirty() { int iI; for (iI = 0; iI < MAX_PLAYERS; iI++) { if (GET_PLAYER((PlayerTypes)iI).isAlive()) { GET_PLAYER((PlayerTypes)iI).AI_makeAssignWorkDirty(); } } } void CvGameAI::AI_updateAssignWork() { int iI; for (iI = 0; iI < MAX_PLAYERS; iI++) { if (GET_PLAYER((PlayerTypes)iI).isAlive()) { GET_PLAYER((PlayerTypes)iI).AI_updateAssignWork(); } } } bool CvGameAI::AI_isFirstTech(TechTypes eTech) { int iI; for (iI = 0; iI < GC.getNumReligionInfos(); iI++) { if (GC.getReligionInfo((ReligionTypes)iI).getTechPrereq() == eTech) { if (!(GC.getGameINLINE().isReligionFounded((ReligionTypes)iI))) { return true; } } } if (GC.getGameINLINE().countKnownTechNumTeams(eTech) == 0) { if ((GC.getTechInfo(eTech).getFirstFreeUnitClass()!= NO_UNITCLASS) || (GC.getTechInfo(eTech).getFirstFreeTechs() > 0)) { return true; } } return false; } int CvGameAI::AI_combatValue(UnitTypes eUnit) { int iValue; iValue = 100; if (GC.getUnitInfo(eUnit).getDomainType() == DOMAIN_AIR) { iValue *= GC.getUnitInfo(eUnit).getAirCombat(); } else { iValue *= GC.getUnitInfo(eUnit).getCombat(); iValue *= ((((GC.getUnitInfo(eUnit).getFirstStrikes() * 2) + GC.getUnitInfo(eUnit).getChanceFirstStrikes()) * ((GC.getDefineINT("COMBAT_DAMAGE") * 2) / 5)) + 100); iValue /= 100; } iValue /= getBestLandUnitCombat(); return iValue; } int CvGameAI::AI_turnsPercent(int iTurns, int iPercent) { if (iTurns!= MAX_INT) { iTurns *= (iPercent + 100); iTurns /= 200; } return max(1, iTurns); } void CvGameAI::read(FDataStreamBase* pStream) { CvGame::read(pStream); uint uiFlag=0; pStream->Read(&uiFlag); // flags for expansion pStream->Read(&m_iPad); } void CvGameAI::write(FDataStreamBase* pStream) { CvGame::write(pStream); uint uiFlag=0; pStream->Write(uiFlag); // flag for expansion pStream->Write(m_iPad); } // Protected Functions... // Private Functions... ======================= File: Civ4/CvGameCoreDLL/CvGameCoreUtils.cpp ======================= #include "CvGameCoreDLL.h" #include "CvGameCoreUtils.h" #include <algorithm> #include "CvUnit.h" #include "CvGameAI.h" #include "CvPlayerAI.h" #include "CvMap.h" #include "CvPlot.h" #include "CvRandom.h" #include "FAStarNode.h" #include "CvCity.h" #include "CvTeamAI.h" #include "CvInfos.h" #include "CvGlobals.h" #include "FProfiler.h" #include "CvDLLInterfaceIFaceBase.h" #include "CvDLLEntityIFaceBase.h" #include "CvDLLFAStarIFaceBase.h" #define PATH_MOVEMENT_WEIGHT (1000) #define PATH_RIVER_WEIGHT (100) #define PATH_CITY_WEIGHT (100) #define PATH_DEFENSE_WEIGHT (10) #define PATH_TERRITORY_WEIGHT (3) #define PATH_STEP_WEIGHT (2) #define PATH_STRAIGHT_WEIGHT (1) CvPlot* plotCity(int iX, int iY, int iIndex) { return GC.getMapINLINE().plotINLINE((iX + GC.getCityPlotX()[iIndex]), (iY + GC.getCityPlotY()[iIndex])); } int plotCityXY(int iDX, int iDY) { if ((abs(iDX) > CITY_PLOTS_RADIUS) || (abs(iDY) > CITY_PLOTS_RADIUS)) { return -1; } else { return GC.getXYCityPlot((iDX + CITY_PLOTS_RADIUS), (iDY + CITY_PLOTS_RADIUS)); } } int plotCityXY(const CvCity* pCity, const CvPlot* pPlot) { return plotCityXY(dxWrap(pPlot->getX_INLINE() - pCity->getX_INLINE()), dyWrap(pPlot->getY_INLINE() - pCity->getY_INLINE())); } CardinalDirectionTypes getOppositeCardinalDirection(CardinalDirectionTypes eDir) { return (CardinalDirectionTypes)((eDir + 2) % NUM_CARDINALDIRECTION_TYPES); } DirectionTypes cardinalDirectionToDirection(CardinalDirectionTypes eCard) { switch (eCard) { case CARDINALDIRECTION_NORTH: return DIRECTION_NORTH; case CARDINALDIRECTION_EAST: return DIRECTION_EAST; case CARDINALDIRECTION_SOUTH: return DIRECTION_SOUTH; case CARDINALDIRECTION_WEST: return DIRECTION_WEST; } return NO_DIRECTION; } bool isCardinalDirection(DirectionTypes eDirection) { switch( eDirection ) { case DIRECTION_EAST: case DIRECTION_NORTH: case DIRECTION_SOUTH: case DIRECTION_WEST: return true; } return false; } DirectionTypes estimateDirection(int iDX, int iDY) { bool bXSign, bYSign; bXSign = (iDX >= 0); bYSign = (iDY >= 0); iDX = abs(iDX); iDY = abs(iDY); if (iDX > iDY) { if ((iDX * 2) > (iDY * 3)) { if (bXSign) { return DIRECTION_EAST; } else { return DIRECTION_WEST; } } } else { if ((iDY * 2) > (iDX * 3)) { if (bYSign) { return DIRECTION_NORTH; } else { return DIRECTION_SOUTH; } } } if (bXSign) { if (bYSign) { return DIRECTION_NORTHEAST; } else { return DIRECTION_SOUTHEAST; } } else { if (bYSign) { return DIRECTION_NORTHWEST; } else { return DIRECTION_SOUTHWEST; } } } float directionAngle( DirectionTypes eDirection ) { switch( eDirection ) { case DIRECTION_NORTHEAST: return (float)(M_PI * 0.25f); case DIRECTION_EAST: return (float)(M_PI * 0.5f); case DIRECTION_SOUTHEAST: return (float)(M_PI * 0.75f); case DIRECTION_SOUTH: return (float)(M_PI); case DIRECTION_SOUTHWEST: return (float)(M_PI * 1.25f); case DIRECTION_WEST: return (float)(M_PI * 1.5f); case DIRECTION_NORTHWEST: return (float)(M_PI * 1.75f); default: case DIRECTION_NORTH: return 0.0f; } } bool atWar(TeamTypes eTeamA, TeamTypes eTeamB) { if ((eTeamA == NO_TEAM) || (eTeamB == NO_TEAM)) { return false; } FAssert(GET_TEAM(eTeamA).isAtWar(eTeamB) == GET_TEAM(eTeamB).isAtWar(eTeamA)); FAssert((eTeamA!= eTeamB) ||!(GET_TEAM(eTeamA).isAtWar(eTeamB))); return GET_TEAM(eTeamA).isAtWar(eTeamB); } bool isPotentialEnemy(TeamTypes eOurTeam, TeamTypes eTheirTeam) { FAssert(eOurTeam!= NO_TEAM); if (eTheirTeam == NO_TEAM) { return false; } return (atWar(eOurTeam, eTheirTeam) || GET_TEAM(eOurTeam).AI_isSneakAttackReady(eTheirTeam)); } CvCity* getCity(IDInfo city) { if ((city.eOwner >= 0) && city.eOwner < MAX_PLAYERS) { return (GET_PLAYER((PlayerTypes)city.eOwner).getCity(city.iID)); } return NULL; } CvUnit* getUnit(IDInfo unit) { if ((unit.eOwner >= 0) && unit.eOwner < MAX_PLAYERS) { return (GET_PLAYER((PlayerTypes)unit.eOwner).getUnit(unit.iID)); } return NULL; } bool isBeforeUnitCycle(const CvUnit* pFirstUnit, const CvUnit* pSecondUnit) { FAssert(pFirstUnit!= NULL); FAssert(pSecondUnit!= NULL); FAssert(pFirstUnit!= pSecondUnit); if (pFirstUnit->getOwnerINLINE()!= pSecondUnit->getOwnerINLINE()) { return (pFirstUnit->getOwnerINLINE() < pSecondUnit->getOwnerINLINE()); } if (pFirstUnit->getDomainType()!= pSecondUnit->getDomainType()) { return (pFirstUnit->getDomainType() < pSecondUnit->getDomainType()); } if (pFirstUnit->baseCombatStr()!= pSecondUnit->baseCombatStr()) { return (pFirstUnit->baseCombatStr() > pSecondUnit->baseCombatStr()); } if (pFirstUnit->getUnitType()!= pSecondUnit->getUnitType()) { return (pFirstUnit->getUnitType() > pSecondUnit->getUnitType()); } if (pFirstUnit->getLevel()!= pSecondUnit->getLevel()) { return (pFirstUnit->getLevel() > pSecondUnit->getLevel()); } if (pFirstUnit->getExperience()!= pSecondUnit->getExperience()) { return (pFirstUnit->getExperience() > pSecondUnit->getExperience()); } return (pFirstUnit->getID() < pSecondUnit->getID()); } bool isPromotionValid(PromotionTypes ePromotion, UnitTypes eUnit) { if (GC.getUnitInfo(eUnit).getUnitCombatType() == NO_UNITCOMBAT) { return false; } if (!(GC.getPromotionInfo(ePromotion).getUnitCombat(GC.getUnitInfo(eUnit).getUnitCombatType()))) { return false; } if (GC.getUnitInfo(eUnit).isOnlyDefensive()) { if ((GC.getPromotionInfo(ePromotion).getCityAttackPercent()!= 0) || (GC.getPromotionInfo(ePromotion).getWithdrawalChange()!= 0) || (GC.getPromotionInfo(ePromotion).getCollateralDamageChange()!= 0) || (GC.getPromotionInfo(ePromotion).isBlitz()) || (GC.getPromotionInfo(ePromotion).isAmphib()) || (GC.getPromotionInfo(ePromotion).isRiver())) { return false; } } if (GC.getUnitInfo(eUnit).isIgnoreTerrainCost()) { if (GC.getPromotionInfo(ePromotion).getMoveDiscountChange()!= 0) { return false; } } if (GC.getUnitInfo(eUnit).getMoves() == 1) { if (GC.getPromotionInfo(ePromotion).isBlitz()) { return false; } } if ((GC.getUnitInfo(eUnit).getCollateralDamageLimit() == 0) || (GC.getUnitInfo(eUnit).getCollateralDamageMaxUnits() == 0)) { if (GC.getPromotionInfo(ePromotion).getCollateralDamageChange()!= 0) { return false; } } return true; } int getPopulationAsset(int iPopulation) { return (iPopulation * 2); } int getLandPlotsAsset(int iLandPlots) { return iLandPlots; } int getPopulationPower(int iPopulation) { return (iPopulation / 2); } int getPopulationScore(int iPopulation) { return iPopulation; } int getLandPlotsScore(int iLandPlots) { return iLandPlots; } int getTechScore(TechTypes eTech) { return (GC.getTechInfo(eTech).getEra() + 1); } int getWonderScore(BuildingClassTypes eWonderClass) { if (isLimitedWonderClass(eWonderClass)) { return 5; } else { return 0; } } ImprovementTypes finalImprovementUpgrade(ImprovementTypes eImprovement, int iCount) { FAssertMsg(eImprovement!= NO_IMPROVEMENT, "Improvement is not assigned a valid value"); if (iCount > GC.getNumImprovementInfos()) { return NO_IMPROVEMENT; } if (GC.getImprovementInfo(eImprovement).getImprovementUpgrade()!= NO_IMPROVEMENT) { return finalImprovementUpgrade(((ImprovementTypes)(GC.getImprovementInfo(eImprovement).getImprovementUpgrade())), (iCount + 1)); } else { return eImprovement; } } int getWorldSizeMaxConscript(CivicTypes eCivic) { int iMaxConscript; iMaxConscript = GC.getCivicInfo(eCivic).getMaxConscript(); iMaxConscript *= max(0, (GC.getWorldInfo(GC.getMapINLINE().getWorldSize()).getMaxConscriptModifier() + 100)); iMaxConscript /= 100; return iMaxConscript; } bool isReligionTech(TechTypes eTech) { int iI; for (iI = 0; iI < GC.getNumReligionInfos(); iI++) { if (GC.getReligionInfo((ReligionTypes)iI).getTechPrereq() == eTech) { return true; } } return false; } bool isTechRequiredForUnit(TechTypes eTech, UnitTypes eUnit) { int iI; CvUnitInfo& info = GC.getUnitInfo(eUnit); if (info.getPrereqAndTech() == eTech) { return true; } for (iI = 0; iI < GC.getDefineINT("NUM_UNIT_AND_TECH_PREREQS"); iI++) { if (info.getPrereqAndTechs(iI) == eTech) { return true; } } return false; } bool isTechRequiredForBuilding(TechTypes eTech, BuildingTypes eBuilding) { int iI; CvBuildingInfo& info = GC.getBuildingInfo(eBuilding); if (info.getPrereqAndTech() == eTech) { return true; } for (iI = 0; iI < GC.getDefineINT("NUM_BUILDING_AND_TECH_PREREQS"); iI++) { if (info.getPrereqAndTechs(iI) == eTech) { return true; } } SpecialBuildingTypes eSpecial = (SpecialBuildingTypes)info.getSpecialBuildingType(); if (NO_SPECIALBUILDING!= eSpecial && GC.getSpecialBuildingInfo(eSpecial).getTechPrereq() == eTech) { return true; } return false; } bool isTechRequiredForProject(TechTypes eTech, ProjectTypes eProject) { if (GC.getProjectInfo(eProject).getTechPrereq() == eTech) { return true; } return false; } bool isWorldUnitClass(UnitClassTypes eUnitClass) { return (GC.getUnitClassInfo(eUnitClass).getMaxGlobalInstances()!= -1); } bool isTeamUnitClass(UnitClassTypes eUnitClass) { return (GC.getUnitClassInfo(eUnitClass).getMaxTeamInstances()!= -1); } bool isNationalUnitClass(UnitClassTypes eUnitClass) { return (GC.getUnitClassInfo(eUnitClass).getMaxPlayerInstances()!= -1); } bool isLimitedUnitClass(UnitClassTypes eUnitClass) { return (isWorldUnitClass(eUnitClass) || isTeamUnitClass(eUnitClass) || isNationalUnitClass(eUnitClass)); } bool isWorldWonderClass(BuildingClassTypes eBuildingClass) { return (GC.getBuildingClassInfo(eBuildingClass).getMaxGlobalInstances()!= -1); } bool isTeamWonderClass(BuildingClassTypes eBuildingClass) { return (GC.getBuildingClassInfo(eBuildingClass).getMaxTeamInstances()!= -1); } bool isNationalWonderClass(BuildingClassTypes eBuildingClass) { return (GC.getBuildingClassInfo(eBuildingClass).getMaxPlayerInstances()!= -1); } bool isLimitedWonderClass(BuildingClassTypes eBuildingClass) { return (isWorldWonderClass(eBuildingClass) || isTeamWonderClass(eBuildingClass) || isNationalWonderClass(eBuildingClass)); } bool isWorldProject(ProjectTypes eProject) { return (GC.getProjectInfo(eProject).getMaxGlobalInstances()!= -1); } bool isTeamProject(ProjectTypes eProject) { return (GC.getProjectInfo(eProject).getMaxTeamInstances()!= -1); } bool isLimitedProject(ProjectTypes eProject) { return (isWorldProject(eProject) || isTeamProject(eProject)); } // FUNCTION: getBinomialCoefficient // Needed for getCombatOdds // Returns int value, being the possible number of combinations // of k draws out of a population of n // Written by DeepO __int64 getBinomialCoefficient(int iN, int iK) { __int64 iTemp = 1; int iI; for (iI = iN; iI > iK; iI--) { iTemp *= iI; } // Make sure iTemp fits in an integer (and thus doesn't overflow) FAssert(iTemp < MAX_INT); for (iI = 2; iI < (iN-iK+1); iI++) { // integer math. no roundings will occur. iTemp /= iI; } return iTemp; } // FUNCTION: getCombatOdds // Calculates combat odds, given two units // Returns value from 0-1000 // Written by DeepO int getCombatOdds(CvUnit* pAttacker, CvUnit* pDefender) { float fOddsEvent; float fOddsAfterEvent; int iAttackerStrength; int iAttackerFirepower; int iDefenderStrength; int iDefenderFirepower; int iDefenderOdds; int iAttackerOdds; int iStrengthFactor; int iDamageToAttacker; int iDamageToDefender; int iNeededRoundsAttacker; int iNeededRoundsDefender; int iMaxRounds; int iAttackerLowFS; int iAttackerHighFS; int iDefenderLowFS; int iDefenderHighFS; int iFirstStrikes; int iI; int iJ; int iI3; int iI4; int iOdds = 0; // setup battle, calculate strengths and odds ////// //Added ST iAttackerStrength = pAttacker->currCombatStr(NULL, NULL); iAttackerFirepower = pAttacker->currFirepower(NULL, NULL); iDefenderStrength = pDefender->currCombatStr(pDefender->plot(), pAttacker); iDefenderFirepower = pDefender->currFirepower(pDefender->plot(), pAttacker); FAssert((iAttackerStrength + iDefenderStrength) > 0); FAssert((iAttackerFirepower + iDefenderFirepower) > 0); iDefenderOdds = ((GC.getDefineINT("COMBAT_DIE_SIDES") * iDefenderStrength) / (iAttackerStrength + iDefenderStrength)); if (iDefenderOdds == 0) { return 1000; } iAttackerOdds = ((GC.getDefineINT("COMBAT_DIE_SIDES") * iAttackerStrength) / (iAttackerStrength + iDefenderStrength)); if (iAttackerOdds == 0) { return 0; } iStrengthFactor = ((iAttackerFirepower + iDefenderFirepower + 1) / 2); // calculate damage done in one round ////// iDamageToAttacker = max(1,((GC.getDefineINT("COMBAT_DAMAGE") * (iDefenderFirepower + iStrengthFactor)) / (iAttackerFirepower + iStrengthFactor))); iDamageToDefender = max(1,((GC.getDefineINT("COMBAT_DAMAGE") * (iAttackerFirepower + iStrengthFactor)) / (iDefenderFirepower + iStrengthFactor))); // calculate needed rounds. // Needed rounds = round_up(health/damage) ////// iNeededRoundsAttacker = (pDefender->currHitPoints() + iDamageToDefender - 1 ) / iDamageToDefender; iNeededRoundsDefender = (pAttacker->currHitPoints() + iDamageToAttacker - 1 ) / iDamageToAttacker; iMaxRounds = iNeededRoundsAttacker + iNeededRoundsDefender - 1; // calculate possible first strikes distribution. // We can't use the getCombatFirstStrikes() function (only one result, // no distribution), so we need to mimic it. ////// iAttackerLowFS = (pDefender->immuneToFirstStrikes())? 0 : pAttacker->firstStrikes(); iAttackerHighFS = (pDefender->immuneToFirstStrikes())? 0 : (pAttacker->firstStrikes() + pAttacker->chanceFirstStrikes()); iDefenderLowFS = (pAttacker->immuneToFirstStrikes())? 0 : pDefender->firstStrikes(); iDefenderHighFS = (pAttacker->immuneToFirstStrikes())? 0 : (pDefender->firstStrikes() + pDefender->chanceFirstStrikes()); // For every possible first strike event, calculate the odds of combat. // Then, add these to the total, weighted to the chance of that first // strike event occurring ////// for (iI = iAttackerLowFS; iI < iAttackerHighFS + 1; iI++) { for (iJ = iDefenderLowFS; iJ < iDefenderHighFS + 1; iJ++) { // for every possible combination of fs results, calculate the chance if (iI >= iJ) { // Attacker gets more or equal first strikes than defender iFirstStrikes = iI - iJ; // For every possible first strike getting hit, calculate both // the chance of that event happening, as well as the rest of // the chance assuming the event has happened. Multiply these // together to get the total chance (Bayes rule). // iI3 counts the number of successful first strikes ////// for (iI3 = 0; iI3 < (iFirstStrikes + 1); iI3++) { // event: iI3 first strikes hit the defender // calculate chance of iI3 first strikes hitting: fOddsEvent // f(k;n,p)=C(n,k)*(p^k)*((1-p)^(n-k)) // this needs to be in floating point math ////// fOddsEvent = ((float)getBinomialCoefficient(iFirstStrikes, iI3)) * pow((((float)iAttackerOdds) / GC.getDefineINT("COMBAT_DIE_SIDES")), iI3) * pow((1.0f - (((float)iAttackerOdds) / GC.getDefineINT("COMBAT_DIE_SIDES"))), (iFirstStrikes - iI3)); // calculate chance assuming iI3 first strike hits: fOddsAfterEvent ////// if (iI3 >= iNeededRoundsAttacker) { fOddsAfterEvent = 1; } else { fOddsAfterEvent = 0; // odds for _at_least_ (iNeededRoundsAttacker - iI3) (the remaining hits // the attacker needs to make) out of (iMaxRounds - iI3) (the left over // rounds) is the sum of each _exact_ draw ////// for (iI4 = (iNeededRoundsAttacker - iI3); iI4 < (iMaxRounds - iI3 + 1); iI4++) { // odds of exactly iI4 out of (iMaxRounds - iI3) draws. // f(k;n,p)=C(n,k)*(p^k)*((1-p)^(n-k)) // this needs to be in floating point math ////// fOddsAfterEvent += ((float)getBinomialCoefficient((iMaxRounds - iI3), iI4)) * pow((((float)iAttackerOdds) / GC.getDefineINT("COMBAT_DIE_SIDES")), iI4) * pow((1.0f - (((float)iAttackerOdds) / GC.getDefineINT("COMBAT_DIE_SIDES"))), ((iMaxRounds - iI3) - iI4)); } } // Multiply these together, round them properly, and add // the result to the total iOdds ////// iOdds += ((int)(1000.0 * (fOddsEvent*fOddsAfterEvent + 0.0005))); } } else // (iI < iJ) { // Attacker gets less first strikes than defender iFirstStrikes = iJ - iI; // For every possible first strike getting hit, calculate both // the chance of that event happening, as well as the rest of // the chance assuming the event has happened. Multiply these // together to get the total chance (Bayes rule). // iI3 counts the number of successful first strikes ////// for (iI3 = 0; iI3 < (iFirstStrikes + 1); iI3++) { // event: iI3 first strikes hit the defender // First of all, check if the attacker is still alive. // Otherwise, no further calculations need to occur ///// if (iI3 < iNeededRoundsDefender) { // calculate chance of iI3 first strikes hitting: fOddsEvent // f(k;n,p)=C(n,k)*(p^k)*((1-p)^(n-k)) // this needs to be in floating point math ////// fOddsEvent = ((float)getBinomialCoefficient(iFirstStrikes, iI3)) * pow((((float)iDefenderOdds) / GC.getDefineINT("COMBAT_DIE_SIDES")), iI3) * pow((1.0f - (((float)iDefenderOdds) / GC.getDefineINT("COMBAT_DIE_SIDES"))), (iFirstStrikes - iI3)); // calculate chance assuming iI3 first strike hits: fOddsAfterEvent ////// fOddsAfterEvent = 0; // odds for _at_least_ iNeededRoundsAttacker (the remaining hits // the attacker needs to make) out of (iMaxRounds - iI3) (the left over // rounds) is the sum of each _exact_ draw ////// for (iI4 = iNeededRoundsAttacker; iI4 < (iMaxRounds - iI3 + 1); iI4++) { // odds of exactly iI4 out of (iMaxRounds - iI3) draws. // f(k;n,p)=C(n,k)*(p^k)*((1-p)^(n-k)) // this needs to be in floating point math ////// fOddsAfterEvent += ((float)getBinomialCoefficient((iMaxRounds - iI3), iI4)) * pow((((float)iAttackerOdds) / GC.getDefineINT("COMBAT_DIE_SIDES")), iI4) * pow((1.0f - (((float)iAttackerOdds) / GC.getDefineINT("COMBAT_DIE_SIDES"))), ((iMaxRounds - iI3) - iI4)); } // Multiply these together, round them properly, and add // the result to the total iOdds ////// iOdds += ((int)(1000.0 * (fOddsEvent*fOddsAfterEvent + 0.0005))); } } } } } // Weigh the total to the number of possible combinations of first strikes events // note: the integer math breaks down when #FS > 656 (with a die size of 1000) ////// iOdds /= (((pDefender->immuneToFirstStrikes())? 0 : pAttacker->chanceFirstStrikes()) + 1) * (((pAttacker->immuneToFirstStrikes())? 0 : pDefender->chanceFirstStrikes()) + 1); // finished! ////// return iOdds; } void setTradeItem(TradeData* pItem, TradeableItems eItemType, int iData) { pItem->m_eItemType = eItemType; pItem->m_iData = iData; pItem->m_bOffering = false; pItem->m_bHidden = false; } void clear(char* szString) { szString[0] = '\0'; } void clear(wchar* szString) { szString[0] = L'\0'; } void clear(std::wstring& szString) { szString.clear(); } void clear(std::string& szString) { szString.clear(); } void safecpy(CvWString& szDest, const CvWString& szSource, int iMaxLen) { szDest = szSource; if (szDest.size()>(uint)iMaxLen) szDest[iMaxLen-1]=0; } void safecpy(char * szDest, const char * szSource, int iMaxLen) { if (szSource) { strncpy(szDest, szSource, iMaxLen-1); szDest[iMaxLen-1] = 0; } else { szDest[0] = '\0'; } } void safecpy(wchar * szDest, const wchar * szSource, int iMaxLen) { if (szSource) { wcsncpy(szDest, szSource, iMaxLen-1); szDest[iMaxLen-1] = L'\0'; } else { szDest[0] = L'\0'; } } bool isEmpty(const char* szString) { return (szString[0] == '\0'); } bool isEmpty(const std::string& szStr) { return (szStr.empty() || szStr[0] == '\0'); } bool isEmpty(const wchar* szString) { return (szString[0] == L'\0'); } bool isEmpty(const std::wstring& szStr) { return (szStr.empty() || szStr[0] == L'\0'); } void setListHelp(wchar* szBuffer, const wchar* szStart, const wchar* szItem, const wchar* szSeparator, bool bFirst) { if (bFirst) { wcscat(szBuffer, szStart); } else { wcscat(szBuffer, szSeparator); } wcscat(szBuffer, szItem); } void setListHelp(CvWString& szBuffer, const wchar* szStart, const wchar* szItem, const wchar* szSeparator, bool bFirst) { if (bFirst) { szBuffer += szStart; } else { szBuffer += szSeparator; } szBuffer += szItem; } bool PUF_isGroupHead(const CvUnit* pUnit, int iData1, int iData2) { return (pUnit->isGroupHead()); } bool PUF_isPlayer(const CvUnit* pUnit, int iData1, int iData2) { FAssertMsg(iData1!= -1, "Invalid data argument, should be >= 0"); return (pUnit->getOwnerINLINE() == iData1); } bool PUF_isTeam(const CvUnit* pUnit, int iData1, int iData2) { FAssertMsg(iData1!= -1, "Invalid data argument, should be >= 0"); return (pUnit->getTeam() == iData1); } bool PUF_isOtherPlayer(const CvUnit* pUnit, int iData1, int iData2) { FAssertMsg(iData1!= -1, "Invalid data argument, should be >= 0"); return (pUnit->getOwnerINLINE()!= iData1); } bool PUF_isOtherTeam(const CvUnit* pUnit, int iData1, int iData2) { FAssertMsg(iData1!= -1, "Invalid data argument, should be >= 0"); return (pUnit->getTeam()!= GET_PLAYER((PlayerTypes)iData1).getTeam()); } bool PUF_isEnemy(const CvUnit* pUnit, int iData1, int iData2) { FAssertMsg(iData1!= -1, "Invalid data argument, should be >= 0"); return atWar(GET_PLAYER((PlayerTypes)iData1).getTeam(), pUnit->getTeam()); } bool PUF_isVisible(const CvUnit* pUnit, int iData1, int iData2) { FAssertMsg(iData1!= -1, "Invalid data argument, should be >= 0"); return!(pUnit->isInvisible(GET_PLAYER((PlayerTypes)iData1).getTeam(), false)); } bool PUF_isVisibleDebug(const CvUnit* pUnit, int iData1, int iData2) { FAssertMsg(iData1!= -1, "Invalid data argument, should be >= 0"); return!(pUnit->isInvisible(GET_PLAYER((PlayerTypes)iData1).getTeam(), true)); } bool PUF_canSiege(const CvUnit* pUnit, int iData1, int iData2) { FAssertMsg(iData1!= -1, "Invalid data argument, should be >= 0"); return pUnit->canSiege(GET_PLAYER((PlayerTypes)iData1).getTeam()); } bool PUF_isPotentialEnemy(const CvUnit* pUnit, int iData1, int iData2) { FAssertMsg(iData1!= -1, "Invalid data argument, should be >= 0"); return isPotentialEnemy(GET_PLAYER((PlayerTypes)iData1).getTeam(), pUnit->getTeam()); } bool PUF_canDeclareWar( const CvUnit* pUnit, int iData1, int iData2) { FAssertMsg(iData1!= -1, "Invalid data argument, should be >= 0"); return GET_TEAM(GET_PLAYER((PlayerTypes)iData1).getTeam()).canDeclareWar(pUnit->getTeam()); } bool PUF_canDefend(const CvUnit* pUnit, int iData1, int iData2) { return pUnit->canDefend(); } bool PUF_cannotDefend(const CvUnit* pUnit, int iData1, int iData2) { return!(pUnit->canDefend()); } bool PUF_canDefendGroupHead(const CvUnit* pUnit, int iData1, int iData2) { return (PUF_canDefend(pUnit, iData1, iData2) && PUF_isGroupHead(pUnit, iData1, iData2)); } bool PUF_canDefendEnemy(const CvUnit* pUnit, int iData1, int iData2) { FAssertMsg(iData1!= -1, "Invalid data argument, should be >= 0"); return (PUF_canDefend(pUnit, iData1, iData2) && PUF_isEnemy(pUnit, iData1, iData2)); } bool PUF_canDefendPotentialEnemy(const CvUnit* pUnit, int iData1, int iData2) { FAssertMsg(iData1!= -1, "Invalid data argument, should be >= 0"); return (PUF_canDefend(pUnit, iData1, iData2) && PUF_isPotentialEnemy(pUnit, iData1, iData2)); } bool PUF_canAirAttack(const CvUnit* pUnit, int iData1, int iData2) { return pUnit->canAirAttack(); } bool PUF_canAirDefend(const CvUnit* pUnit, int iData1, int iData2) { return pUnit->canAirDefend(); } bool PUF_isFighting(const CvUnit* pUnit, int iData1, int iData2) { return pUnit->isFighting(); } bool PUF_isAnimal( const CvUnit* pUnit, int iData1, int iData2) { return pUnit->isAnimal(); } bool PUF_isMilitaryHappiness(const CvUnit* pUnit, int iData1, int iData2) { return pUnit->isMilitaryHappiness(); } bool PUF_isInvestigate(const CvUnit* pUnit, int iData1, int iData2) { return pUnit->isInvestigate(); } bool PUF_isCounterSpy(const CvUnit* pUnit, int iData1, int iData2) { return pUnit->isCounterSpy(); } bool PUF_isDomainType(const CvUnit* pUnit, int iData1, int iData2) { FAssertMsg(iData1!= -1, "Invalid data argument, should be >= 0"); return (pUnit->getDomainType() == iData1); } bool PUF_isUnitType(const CvUnit* pUnit, int iData1, int iData2) { FAssertMsg(iData1!= -1, "Invalid data argument, should be >= 0"); return (pUnit->getUnitType() == iData1); } bool PUF_isUnitAIType(const CvUnit* pUnit, int iData1, int iData2) { FAssertMsg(iData1!= -1, "Invalid data argument, should be >= 0"); return (pUnit->AI_getUnitAIType() == iData1); } bool PUF_isCityAIType(const CvUnit* pUnit, int iData1, int iData2) { return pUnit->AI_isCityAIType(); } bool PUF_isNotCityAIType(const CvUnit* pUnit, int iData1, int iData2) { return!(PUF_isCityAIType(pUnit, iData1, iData2)); } bool PUF_isSelected(const CvUnit* pUnit, int iData1, int iData2) { return pUnit->IsSelected(); } bool PUF_makeInfoBarDirty(CvUnit* pUnit, int iData1, int iData2) { pUnit->setInfoBarDirty(true); return true; } int potentialIrrigation(FAStarNode* parent, FAStarNode* node, int data, const void* pointer, FAStar* finder) { if (parent == NULL) { return TRUE; } return ((GC.getMapINLINE().plotSorenINLINE(node->m_iX, node->m_iY)->isPotentialIrrigation())? TRUE : FALSE); } int checkFreshWater(FAStarNode* parent, FAStarNode* node, int data, const void* pointer, FAStar* finder) { if (data == ASNL_ADDCLOSED) { if (GC.getMapINLINE().plotSorenINLINE(node->m_iX, node->m_iY)->isFreshWater()) { *((bool *)pointer) = true; } } return 1; } int changeIrrigated(FAStarNode* parent, FAStarNode* node, int data, const void* pointer, FAStar* finder) { if (data == ASNL_ADDCLOSED) { GC.getMapINLINE().plotSorenINLINE(node->m_iX, node->m_iY)->setIrrigated(*((bool *)pointer)); } return 1; } int pathDestValid(int iToX, int iToY, const void* pointer, FAStar* finder) { PROFILE_FUNC(); CLLNode<IDInfo>* pUnitNode1; CLLNode<IDInfo>* pUnitNode2; CvSelectionGroup* pSelectionGroup; CvUnit* pLoopUnit1; CvUnit* pLoopUnit2; CvPlot* pToPlot; bool bAIControl; bool bValid; pToPlot = GC.getMapINLINE().plotSorenINLINE(iToX, iToY); FAssert(pToPlot!= NULL); pSelectionGroup = ((CvSelectionGroup *)pointer); if (pSelectionGroup->atPlot(pToPlot)) { return TRUE; } if (pSelectionGroup->getDomainType() == DOMAIN_IMMOBILE) { return FALSE; } bAIControl = pSelectionGroup->AI_isControlled(); if (bAIControl) { if (!(gDLL->getFAStarIFace()->GetInfo(finder) & MOVE_IGNORE_DANGER)) { if (!(pSelectionGroup->canFight()) &&!(pSelectionGroup->alwaysInvisible())) { if (GET_PLAYER(pSelectionGroup->getHeadOwner()).AI_getPlotDanger(pToPlot) > 0) { return FALSE; } } } if (pSelectionGroup->getDomainType() == DOMAIN_LAND) { if (pToPlot->area()!= pSelectionGroup->area()) { if (!(pToPlot->isAdjacentToArea(pSelectionGroup->area()))) { return FALSE; } } } } if (bAIControl || pToPlot->isRevealed(pSelectionGroup->getHeadTeam(), false)) { if (pSelectionGroup->isAmphibPlot(pToPlot)) { pUnitNode1 = pSelectionGroup->headUnitNode(); while (pUnitNode1!= NULL) { pLoopUnit1 = ::getUnit(pUnitNode1->m_data); pUnitNode1 = pSelectionGroup->nextUnitNode(pUnitNode1); if ((pLoopUnit1->getCargo() > 0) && (pLoopUnit1->domainCargo() == DOMAIN_LAND)) { bValid = false; pUnitNode2 = pLoopUnit1->plot()->headUnitNode(); while (pUnitNode2!= NULL) { pLoopUnit2 = ::getUnit(pUnitNode2->m_data); pUnitNode2 = pLoopUnit1->plot()->nextUnitNode(pUnitNode2); if (pLoopUnit2->getTransportUnit() == pLoopUnit1) { if (pLoopUnit2->isGroupHead()) { if (pLoopUnit2->getGroup()->canMoveOrAttackInto(pToPlot, (pSelectionGroup->AI_isDeclareWar() || (gDLL->getFAStarIFace()->GetInfo(finder) & MOVE_DECLARE_WAR)))) { bValid = true; break; } } } } if (bValid) { return TRUE; } } } return FALSE; } else { if (!(pSelectionGroup->canMoveOrAttackInto(pToPlot, (pSelectionGroup->AI_isDeclareWar() || (gDLL->getFAStarIFace()->GetInfo(finder) & MOVE_DECLARE_WAR))))) { return FALSE; } } } return TRUE; } int pathHeuristic(int iFromX, int iFromY, int iToX, int iToY) { return (stepDistance(iFromX, iFromY, iToX, iToY) * PATH_MOVEMENT_WEIGHT); } int pathCost(FAStarNode* parent, FAStarNode* node, int data, const void* pointer, FAStar* finder) { PROFILE_FUNC(); CLLNode<IDInfo>* pUnitNode; CvSelectionGroup* pSelectionGroup; CvUnit* pLoopUnit; CvPlot* pFromPlot; CvPlot* pToPlot; int iWorstCost; int iCost; int iWorstMovesLeft; int iMovesLeft; int iWorstMax; int iMax; pFromPlot = GC.getMapINLINE().plotSorenINLINE(parent->m_iX, parent->m_iY); FAssert(pFromPlot!= NULL); pToPlot = GC.getMapINLINE().plotSorenINLINE(node->m_iX, node->m_iY); FAssert(pToPlot!= NULL); pSelectionGroup = ((CvSelectionGroup *)pointer); iWorstCost = MAX_INT; iWorstMovesLeft = MAX_INT; iWorstMax = MAX_INT; pUnitNode = pSelectionGroup->headUnitNode(); while (pUnitNode!= NULL) { pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = pSelectionGroup->nextUnitNode(pUnitNode); FAssertMsg(pLoopUnit->getDomainType()!= DOMAIN_AIR, "pLoopUnit->getDomainType() is not expected to be equal with DOMAIN_AIR"); if (parent->m_iData1 > 0) { iMax = parent->m_iData1; } else { iMax = pLoopUnit->maxMoves(); } iCost = pToPlot->movementCost(pLoopUnit, pFromPlot); iMovesLeft = max(0, (iMax - iCost)); if (iMovesLeft <= iWorstMovesLeft) { if ((iMovesLeft < iWorstMovesLeft) || (iMax <= iWorstMax)) { if (iMovesLeft == 0) { iCost = (PATH_MOVEMENT_WEIGHT * iMax); if (pToPlot->getTeam()!= pLoopUnit->getTeam()) { iCost += PATH_TERRITORY_WEIGHT; } } else { iCost = (PATH_MOVEMENT_WEIGHT * iCost); } if (pLoopUnit->canFight()) { if (iMovesLeft == 0) { iCost += (PATH_DEFENSE_WEIGHT * max(0, (200 - ((pLoopUnit->noDefensiveBonus())? 0 : pToPlot->defenseModifier(false))))); } if (pSelectionGroup->AI_isControlled()) { if (pLoopUnit->canAttack()) { if (gDLL->getFAStarIFace()->IsPathDest(finder, pToPlot->getX_INLINE(), pToPlot->getY_INLINE())) { if (pToPlot->isVisibleEnemyDefender(pLoopUnit->getOwnerINLINE())) { iCost += (PATH_DEFENSE_WEIGHT * max(0, (200 - ((pLoopUnit->noDefensiveBonus())? 0 : pFromPlot->defenseModifier(false))))); if (!(pFromPlot->isCity())) { iCost += PATH_CITY_WEIGHT; } if (pFromPlot->isRiverCrossing(directionXY(pFromPlot, pToPlot))) { if (!(pLoopUnit->isRiver())) { iCost += (PATH_RIVER_WEIGHT * -(GC.getRIVER_ATTACK_MODIFIER())); iCost += (PATH_MOVEMENT_WEIGHT * iMovesLeft); } } } } } } } if (iCost < iWorstCost) { iWorstCost = iCost; iWorstMovesLeft = iMovesLeft; iWorstMax = iMax; } } } } FAssert(iWorstCost!= MAX_INT); iWorstCost += PATH_STEP_WEIGHT; if ((pFromPlot->getX_INLINE()!= pToPlot->getX_INLINE()) && (pFromPlot->getY_INLINE()!= pToPlot->getY_INLINE())) { iWorstCost += PATH_STRAIGHT_WEIGHT; } FAssert(iWorstCost > 0); return iWorstCost; } int pathValid(FAStarNode* parent, FAStarNode* node, int data, const void* pointer, FAStar* finder) { PROFILE_FUNC(); CvSelectionGroup* pSelectionGroup; CvPlot* pFromPlot; CvPlot* pToPlot; bool bAIControl; if (parent == NULL) { return TRUE; } pFromPlot = GC.getMapINLINE().plotSorenINLINE(parent->m_iX, parent->m_iY); FAssert(pFromPlot!= NULL); pToPlot = GC.getMapINLINE().plotSorenINLINE(node->m_iX, node->m_iY); FAssert(pToPlot!= NULL); pSelectionGroup = ((CvSelectionGroup *)pointer); // XXX might want to take this out... if (pSelectionGroup->getDomainType() == DOMAIN_SEA) { PROFILE("pathValid 1"); if (pFromPlot->isWater() && pToPlot->isWater()) { if (!(GC.getMapINLINE().plotINLINE(parent->m_iX, node->m_iY)->isWater()) &&!(GC.getMapINLINE().plotINLINE(node->m_iX, parent->m_iY)->isWater())) { return FALSE; } } } if (pSelectionGroup->atPlot(pFromPlot)) { return TRUE; } if (gDLL->getFAStarIFace()->GetInfo(finder) & MOVE_SAFE_TERRITORY) { PROFILE("pathValid 2"); if (!(pFromPlot->isRevealed(pSelectionGroup->getHeadTeam(), false))) { return FALSE; } if (pFromPlot->isOwned()) { if (pFromPlot->getTeam()!= pSelectionGroup->getHeadTeam()) { return FALSE; } } } if (gDLL->getFAStarIFace()->GetInfo(finder) & MOVE_NO_ENEMY_TERRITORY) { PROFILE("pathValid 3"); if (pFromPlot->isOwned()) { if (atWar(pFromPlot->getTeam(), pSelectionGroup->getHeadTeam())) { return FALSE; } } } bAIControl = pSelectionGroup->AI_isControlled(); if (bAIControl) { PROFILE("pathValid 4"); if ((parent->m_iData2 > 1) || (parent->m_iData1 == 0)) { if (!(gDLL->getFAStarIFace()->GetInfo(finder) & MOVE_IGNORE_DANGER))
1,522
value type stored in this Either * (will capture the lowest common type) * * <pre> * {@code * * myEither.to(Either3::consumeAny) .accept(System.out::println); * } * </pre> * * @param either Either to consume value for * @return Consumer we can applyHKT to consume value */ static <X, LT extends X, M extends X, RT extends X> Consumer<Consumer<? super X>> consumeAny(LazyEither3<LT, M, RT> either){ return in->visitAny(in,either); } static <X, LT extends X, M extends X, RT extends X,R> Function<Function<? super X, R>,R> applyAny(LazyEither3<LT, M, RT> either){ return in->visitAny(either,in); } static <X, LT extends X, M extends X, RT extends X,R> R visitAny(LazyEither3<LT, M, RT> either, Function<? super X,? extends R> fn){ return either.fold(fn, fn,fn); } static <X, LT extends X, M extends X, RT extends X> X visitAny(Consumer<? super X> c, LazyEither3<LT, M, RT> either){ Function<? super X, X> fn = x ->{ c.accept(x); return x; }; return visitAny(either,fn); } /** * Construct a Either3#Right from an Eval * * @param right Eval to construct Either3#Right from * @return Either3 right instance */ public static <LT, B, RT> LazyEither3<LT, B, RT> rightEval(final Eval<RT> right) { return new Right<>( right); } /** * Construct a Either3#Left1 from an Eval * * @param left Eval to construct Either3#Left from * @return Either3 left instance */ public static <LT, B, RT> LazyEither3<LT, B, RT> left1Eval(final Eval<LT> left) { return new Left1<>( left); } /** * Construct a Either3#Right * * @param right Value to store * @return Either3 Right instance */ public static <LT, B, RT> LazyEither3<LT, B, RT> right(final RT right) { return new Right<>( Eval.later(()->right)); } /** * Construct a Either3#Left1 * * @param left Value to store * @return Left instance */ public static <LT, B, RT> LazyEither3<LT, B, RT> left1(final LT left) { return new Left1<>( Eval.now(left)); } /** * Construct a Either3#Left2 * * @param middle Value to store * @return Left2 instance */ public static <LT, B, RT> LazyEither3<LT, B, RT> left2(final B middle) { return new Left2<>( Eval.now(middle)); } /** * Construct a Either3#Left2 from an Eval * * @param middle Eval to construct Either3#middle from * @return Either3 Left2 instance */ public static <LT, B, RT> LazyEither3<LT, B, RT> left2Eval(final Eval<B> middle) { return new Left2<>( middle); } /** * Visit the types in this Either3, only one user supplied function is executed depending on the type * * @param left1 Function to execute if this Either3 is a Left instance * @param mid Function to execute if this Either3 is a middle instance * @param right Function to execute if this Either3 is a right instance * @return Result of executed function */ <R> R fold(final Function<? super LT1,? extends R> left1, final Function<? super LT2,? extends R> mid, final Function<? super RT,? extends R> right); /** * Filter this Either3 resulting in a Maybe#none if it is not a Right instance or if the predicate does not * hold. Otherwise results in a Maybe containing the current value * * @param test Predicate to applyHKT to filter this Either3 * @return Maybe containing the current value if this is a Right instance and the predicate holds, otherwise Maybe#none */ Maybe<RT> filter(Predicate<? super RT> test); /** * Flattening transformation on this Either3. Contains an internal trampoline so will convert tail-recursive calls * to iteration. * * @param mapper Mapping function * @return Mapped Either3 */ <R2> LazyEither3<LT1, LT2, R2> flatMap(Function<? super RT,? extends LazyEither3<LT1,LT2,? extends R2>> mapper); /** * @return Swap the middle and the right types */ LazyEither3<LT1, RT, LT2> swap2(); /** * @return Swap the right and left types */ LazyEither3<RT, LT2, LT1> swap1(); /** * @return True if this lazy contains the right type */ boolean isRight(); /** * @return True if this lazy contains the left1 type */ boolean isLeft1(); /** * @return True if this lazy contains the left2 type */ boolean isLeft2(); /** * Return an Ior that can be this object or a Ior.right or Ior.left * @return new Ior */ default Ior<LT1, RT> toIor() { return this.fold(l->Ior.left(l), m->Ior.left(null), r->Ior.right(r)); } default Either<LT1, RT> toEither() { return this.fold(l-> Either.left(l), m-> Either.left(null), r-> Either.right(r)); } Option<RT> get(); @Override default <U> Maybe<U> ofType(Class<? extends U> type) { return (Maybe<U> )Filters.super.ofType(type); } @Override default Maybe<RT> filterNot(Predicate<? super RT> predicate) { return (Maybe<RT>)Filters.super.filterNot(predicate); } default Trampoline<LazyEither3<LT1,LT2,RT>> toTrampoline() { return Trampoline.more(()->Trampoline.done(this)); } @Override default Maybe<RT> notNull() { return (Maybe<RT>)Filters.super.notNull(); } default <R> LazyEither3<LT1,LT2,R> coflatMap(Function<? super LazyEither3<LT1,LT2,RT>, R> mapper) { return mapper.andThen(r -> unit(r)) .apply(this); } default LazyEither3<LT1,LT2,LazyEither3<LT1,LT2,RT>> nest() { return this.map(t -> unit(t)); } default <T2, R1, R2, R3, R> LazyEither3<LT1,LT2,R> forEach4(Function<? super RT,? extends LazyEither3<LT1,LT2,R1>> value1, BiFunction<? super RT,? super R1,? extends LazyEither3<LT1,LT2,R2>> value2, Function3<? super RT,? super R1,? super R2,? extends LazyEither3<LT1,LT2,R3>> value3, Function4<? super RT,? super R1,? super R2,? super R3,? extends R> yieldingFunction) { return this.flatMap(in-> { LazyEither3<LT1,LT2,R1> a = value1.apply(in); return a.flatMap(ina-> { LazyEither3<LT1,LT2,R2> b = value2.apply(in,ina); return b.flatMap(inb-> { LazyEither3<LT1,LT2,R3> c= value3.apply(in,ina,inb); return c.map(in2 -> yieldingFunction.apply(in, ina, inb, in2)); }); }); }); } default <T2, R1, R2, R> LazyEither3<LT1,LT2,R> forEach3(Function<? super RT,? extends LazyEither3<LT1,LT2,R1>> value1, BiFunction<? super RT,? super R1,? extends LazyEither3<LT1,LT2,R2>> value2, Function3<? super RT,? super R1,? super R2,? extends R> yieldingFunction) { return this.flatMap(in-> { LazyEither3<LT1,LT2,R1> a = value1.apply(in); return a.flatMap(ina-> { LazyEither3<LT1,LT2,R2> b = value2.apply(in,ina); return b.map(in2->yieldingFunction.apply(in,ina, in2)); }); }); } default <R1, R> LazyEither3<LT1,LT2,R> forEach2(Function<? super RT,? extends LazyEither3<LT1,LT2,R1>> value1, BiFunction<? super RT,? super R1,? extends R> yieldingFunction) { return this.flatMap(in-> { LazyEither3<LT1,LT2,R1> b = value1.apply(in); return b.map(in2->yieldingFunction.apply(in, in2)); }); } /* * (non-Javadoc) * * @see com.oath.cyclops.types.functor.BiTransformable#bimap(java.util.function.Function, * java.util.function.Function) */ @Override <R1, R2> LazyEither3<LT1, R1, R2> bimap(Function<? super LT2,? extends R1> fn1, Function<? super RT,? extends R2> fn2); /* * (non-Javadoc) * * @see com.oath.cyclops.types.Functor#transform(java.util.function.Function) */ @Override <R> LazyEither3<LT1, LT2, R> map(Function<? super RT,? extends R> fn); /* * (non-Javadoc) * * @see com.oath.cyclops.types.Pure#unit(java.lang.Object) */ @Override <T> LazyEither3<LT1, LT2, T> unit(T unit); /* * (non-Javadoc) * * @see com.oath.cyclops.types.functor.BiTransformable#bipeek(java.util.function.Consumer, * java.util.function.Consumer) */ @Override default LazyEither3<LT1, LT2, RT> bipeek(final Consumer<? super LT2> c1, final Consumer<? super RT> c2) { return (LazyEither3<LT1, LT2, RT>) BiTransformable.super.bipeek(c1, c2); } /* * (non-Javadoc) * * @see com.oath.cyclops.types.Functor#peek(java.util.function.Consumer) */ @Override default LazyEither3<LT1, LT2, RT> peek(final Consumer<? super RT> c) { return (LazyEither3<LT1, LT2, RT>) Transformable.super.peek(c); } @AllArgsConstructor(access = AccessLevel.PRIVATE) final static class Lazy<ST, M, PT> implements LazyEither3<ST, M, PT> { private final Eval<LazyEither3<ST, M, PT>> lazy; public LazyEither3<ST, M, PT> resolve() { return lazy.get() .fold(LazyEither3::left1, LazyEither3::left2, LazyEither3::right); } private static <ST, M, PT> Lazy<ST, M, PT> lazy(final Eval<LazyEither3<ST, M, PT>> lazy) { return new Lazy<>( lazy); } @Override public <R> LazyEither3<ST, M, R> map(final Function<? super PT,? extends R> mapper) { return flatMap(t -> LazyEither3.right(mapper.apply(t))); } @Override public <RT1> LazyEither3<ST, M, RT1> flatMap( final Function<? super PT,? extends LazyEither3<ST,M,? extends RT1>> mapper) { return LazyEither3.fromLazy(lazy.map(m->m.flatMap(mapper))); } @Override public Trampoline<LazyEither3<ST,M,PT>> toTrampoline() { Trampoline<LazyEither3<ST,M,PT>> trampoline = lazy.toTrampoline(); return new Trampoline<LazyEither3<ST,M,PT>>() { @Override public LazyEither3<ST,M,PT> get() { LazyEither3<ST,M,PT> either = lazy.get(); while (either instanceof LazyEither3.Lazy) { either = ((LazyEither3.Lazy<ST,M,PT>) either).lazy.get(); } return either; } @Override public boolean complete(){ return false; } @Override public Trampoline<LazyEither3<ST,M,PT>> bounce() { LazyEither3<ST,M,PT> either = lazy.get(); if(either instanceof LazyEither3.Lazy){ return either.toTrampoline(); } return Trampoline.done(either); } }; } @Override public Maybe<PT> filter(final Predicate<? super PT> test) { return Maybe.fromEval(Eval.later(() -> resolve().filter(test))) .flatMap(Function.identity()); } public Option<PT> get() { return trampoline().get(); } private LazyEither3<ST,M,PT> trampoline(){ LazyEither3<ST,M,PT> maybe = lazy.get(); while (maybe instanceof Lazy) { maybe = ((Lazy<ST,M,PT>) maybe).lazy.get(); } return maybe; } @Override public ReactiveSeq<PT> stream() { return trampoline() .stream(); } @Override public Iterator<PT> iterator() { return trampoline() .iterator(); } @Override public <R> R fold(final Function<? super PT,? extends R> present, final Supplier<? extends R> absent) { return trampoline() .fold(present, absent); } @Override public void subscribe(final Subscriber<? super PT> s) { lazy.get() .subscribe(s); } @Override public <R> R fold(final Function<? super ST,? extends R> secondary, final Function<? super M,? extends R> mid, final Function<? super PT,? extends R> primary) { return trampoline() .fold(secondary, mid, primary); } @Override public LazyEither3<ST, PT, M> swap2() { return lazy(Eval.later(() -> resolve().swap2())); } @Override public LazyEither3<PT, M, ST> swap1() { return lazy(Eval.later(() -> resolve().swap1())); } @Override public boolean isRight() { return trampoline() .isRight(); } @Override public boolean isLeft1() { return trampoline() .isLeft1(); } @Override public boolean isLeft2() { return trampoline() .isLeft2(); } @Override public <R1, R2> LazyEither3<ST, R1, R2> bimap(final Function<? super M,? extends R1> fn1, final Function<? super PT,? extends R2> fn2) { return lazy(Eval.later(() -> resolve().bimap(fn1, fn2))); } @Override public <T> LazyEither3<ST, M, T> unit(final T unit) { return LazyEither3.right(unit); } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { return this.fold(LazyEither3::left1, LazyEither3::left2, LazyEither3::right).hashCode(); } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { return this.fold(LazyEither3::left1, LazyEither3::left2, LazyEither3::right).equals(obj); } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return trampoline().toString(); } } @AllArgsConstructor(access = AccessLevel.PRIVATE) static class Right<ST, M, PT> implements LazyEither3<ST, M, PT> { private final Eval<PT> value; @Override public <R> LazyEither3<ST, M, R> map(final Function<? super PT,? extends R> fn) { return new Right<ST, M, R>( value.map(fn)); } @Override public LazyEither3<ST, M, PT> peek(final Consumer<? super PT> action) { return map(i -> { action.accept(i); return i; }); } @Override public Maybe<PT> filter(final Predicate<? super PT> test) { return Maybe.fromEval(Eval.later(() -> test.test(value.get())? Maybe.just(value.get()) : Maybe.<PT>nothing())) .flatMap(Function.identity()); } @Override public Option<PT> get() { return Option.some(value.get()); } @Override public <RT1> LazyEither3<ST, M, RT1> flatMap( final Function<? super PT,? extends LazyEither3<ST,M,? extends RT1>> mapper) { Eval<? extends LazyEither3<? extends ST,? extends M,? extends RT1>> et = value.map(mapper); final Eval<LazyEither3<ST, M, RT1>> e3 = (Eval<LazyEither3<ST, M, RT1>>)et; return new Lazy<>( e3); } @Override public boolean isRight() { return true; } @Override public boolean isLeft1() { return false; } @Override public String toString() { return mkString(); } @Override public String mkString() { return "Either3.right[" + value.get() + "]"; } @Override public <R> R fold(final Function<? super ST,? extends R> secondary, final Function<? super M,? extends R> mid, final Function<? super PT,? extends R> primary) { return primary.apply(value.get()); } @Override public <R1, R2> LazyEither3<ST, R1, R2> bimap(final Function<? super M,? extends R1> fn1, final Function<? super PT,? extends R2> fn2) { return (LazyEither3<ST, R1, R2>) this.map(fn2); } @Override public ReactiveSeq<PT> stream() { return value.stream(); } @Override public Iterator<PT> iterator() { return value.iterator(); } @Override public <R> R fold(final Function<? super PT,? extends R> present, final Supplier<? extends R> absent) { return value.fold(present, absent); } @Override public void subscribe(final Subscriber<? super PT> s) { value.subscribe(s); } @Override public <T> LazyEither3<ST, M, T> unit(final T unit) { return LazyEither3.right(unit); } @Override public LazyEither3<ST, PT, M> swap2() { return new Left2<>(value); } @Override public LazyEither3<PT, M, ST> swap1() { return new Left1<>( value); } @Override public boolean isLeft2() { return false; } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((value == null)? 0 : value.hashCode()); return result; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if(obj instanceof Lazy){ return ((Lazy)obj).equals(this); } if (getClass()!= obj.getClass()) return false; Right other = (Right) obj; if (value == null) { if (other.value!= null) return false; } else if (!value.equals(other.value)) return false; return true; } } @AllArgsConstructor(access = AccessLevel.PRIVATE) static class Left1<ST, M, PT> implements LazyEither3<ST, M, PT> { private final Eval<ST> value; @Override public <R> LazyEither3<ST, M, R> map(final Function<? super PT,? extends R> fn) { return (LazyEither3<ST, M, R>) this; } @Override public LazyEither3<ST, M, PT> peek(final Consumer<? super PT> action) { return this; } @Override public void subscribe(final Subscriber<? super PT> s) { s.onComplete(); } @Override public Maybe<PT> filter(final Predicate<? super PT> test) { return Maybe.nothing(); } @Override public Option<PT> get() { return Option.none(); } @Override public <RT1> LazyEither3<ST, M, RT1> flatMap( final Function<? super PT,? extends LazyEither3<ST,M,? extends RT1>> mapper) { return (LazyEither3) this; } @Override public boolean isRight() { return false; } @Override public boolean isLeft1() { return true; } @Override public String toString() { return mkString(); } @Override public String mkString() { return "Either3.left1[" + value.get() + "]"; } @Override public <R> R fold(final Function<? super ST,? extends R> secondary, final Function<? super M,? extends R> mid, final Function<? super PT,? extends R> primary) { return secondary.apply(value.get()); } @Override public <R1, R2> LazyEither3<ST, R1, R2> bimap(final Function<? super M,? extends R1> fn1, final Function<? super PT,? extends R2> fn2) { return (LazyEither3<ST, R1, R2>) this; } @Override public ReactiveSeq<PT> stream() { return ReactiveSeq.empty(); } @Override public Iterator<PT> iterator() { return Arrays.<PT> asList() .iterator(); } @Override public <R> R fold(final Function<? super PT,? extends R> present, final Supplier<? extends R> absent) { return absent.get(); } @Override public <T> LazyEither3<ST, M, T> unit(final T unit) { return LazyEither3.right(unit); } @Override public LazyEither3<ST, PT, M> swap2() { return (LazyEither3<ST, PT, M>) this; } @Override public LazyEither3<PT, M, ST> swap1() { return new Right<>( value); } @Override public boolean isLeft2() { return false; } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((value == null)? 0 : value.hashCode()); return result; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if(obj instanceof Lazy){ return ((Lazy)obj).equals(this); } if (getClass()!= obj.getClass()) return false; Left1 other = (Left1) obj; if (value == null) { if (other.value!= null) return false; } else if (!value.equals(other.value)) return false; return true; } } @AllArgsConstructor(access = AccessLevel.PRIVATE) static class Left2<ST, M, PT> implements LazyEither3<ST, M, PT> { private final Eval<M> value; @Override public <R> LazyEither3<ST, M, R> map(final Function<? super PT,? extends R> fn) { return (LazyEither3<ST, M, R>) this; } @Override public LazyEither3<ST, M, PT> peek(final Consumer<? super PT> action) { return this; } @Override public Maybe<PT> filter(final Predicate<? super PT> test) { return Maybe.nothing(); } @Override public Option<PT> get() { return Option.none(); } @Override public <RT1> LazyEither3<ST, M, RT1> flatMap( final Function<? super PT,? extends LazyEither3<ST,M,? extends RT1>> mapper) { return (LazyEither3) this; } @Override public boolean isRight() { return false; } @Override public boolean isLeft1() { return false; } @Override public String toString() { return mkString(); } @Override public String mkString() { return "Either3.left2[" + value.get() + "]"; } @Override public <R> R fold(final Function<? super ST,? extends R> secondary, final Function<? super M,? extends R> mid, final Function<? super PT,? extends R> primary) { return mid.apply(value.get()); } @Override public <R1, R2> LazyEither3<ST, R1, R2> bimap(final Function<? super M,? extends R1> fn1, final Function<? super PT,? extends R2> fn2) { return (LazyEither3<ST, R1, R2>) this; } @Override public ReactiveSeq<PT> stream() { return ReactiveSeq.empty(); } @Override public Iterator<PT> iterator() { return Arrays.<PT> asList() .iterator(); } @Override public <R> R fold(final Function<? super PT,? extends R> present, final Supplier<? extends R> absent) { return absent.get(); } @Override public void subscribe(final Subscriber<? super PT> s) { s.onComplete(); } @Override public <T> LazyEither3<ST, M, T> unit(final T unit) { return LazyEither3.right(unit); } @Override public LazyEither3<ST, PT, M> swap2() { return new Right<>( value); } @Override public LazyEither3<PT, M, ST> swap1() { return (LazyEither3<PT, M, ST>) this; } @Override public boolean isLeft2() { return true; } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((value == null)? 0 : value.hashCode()); return result; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass()!= obj.getClass()) return false; if(obj instanceof Lazy){ return ((Lazy)obj).equals(this); } Left2 other = (Left2) obj; if (value == null) { if (other.value!= null) return false; } else if (!value.equals(other.value)) return false; return true; } } public static <L1,L2,T> LazyEither3<L1,L2,T> narrowK3(final Higher3<lazyEither3, L1,L2,T> xor) { return (LazyEither3<L1,L2,T>)xor; } public static <L1,L2,T> LazyEither3<L1,L2,T> narrowK(final Higher<Higher<Higher<lazyEither3, L1>,L2>,T> xor) { return (LazyEither3<L1,L2,T>)xor; } } ======================= File: cyclops-futurestream/src/test/java/cyclops/futurestream/react/simple/ResultCollectionTest.java ======================= <reponame>zmyer/cyclops-react package cyclops.futurestream.react.simple; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import java.util.List; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.stream.Collectors; import org.junit.Test; import cyclops.futurestream.SimpleReact; public class ResultCollectionTest { @Test public void testBlock() throws InterruptedException, ExecutionException { List<String> strings = new SimpleReact() .<Integer> ofAsync(() -> 1, () -> 2, () -> 3) .then(it -> it * 100) .then(it -> "*" + it) .block(); assertThat(strings.size(), is(3)); } @Test public void testBlockToSet() throws InterruptedException, ExecutionException { Set<String> strings = new SimpleReact() .<Integer> ofAsync(() -> 1, () -> 1, () -> 3) .then(it -> it * 100) .then(it -> "*" + it) .block(Collectors.toSet()); assertThat(strings.size(), is(2)); } @Test public void testBreakout() throws InterruptedException, ExecutionException { Throwable[] error = { null }; List<String> strings = new SimpleReact() .<Integer> ofAsync(() -> 1, () -> 2, () -> 3) .then(it -> it * 100) .then(it -> { if (it == 100) throw new RuntimeException("boo!"); return it; }).onFail(e -> 1).then((it) -> "*" + it) .block(status -> status.getCompleted() > 1); assertThat(strings.size(), greaterThan(1)); } @Test public void testBreakoutToSet() throws InterruptedException, ExecutionException { Throwable[] error = { null }; Set<String> strings = new SimpleReact() .<Integer> ofAsync(() -> 1, () -> 2, () -> 3) .then(it -> it * 100) .then(it -> { if (it == 100) throw new RuntimeException("boo!"); return it; }).onFail(e -> 1).then((it) -> "*" + it) .block(Collectors.toSet(),status -> status.getCompleted() > 1); assertThat(strings.size(), is(2)); } @Test public void testBreakoutException() throws InterruptedException, ExecutionException { Throwable[] error = { null }; List<String> strings = new SimpleReact() .<Integer> ofAsync(() -> 1, () -> 2, () -> 3) .then(it -> it * 100) .<String>then(it -> { throw new RuntimeException("boo!"); }).capture(e -> error[0] = e) .block(status -> status.getCompleted() >= 1); assertThat(strings.size(), is(0)); assertThat(error[0], instanceOf(RuntimeException.class)); } volatile int count =0; @Test public void testBreakoutExceptionTimes() throws InterruptedException, ExecutionException { count =0; List<String> strings = new SimpleReact() .<Integer> ofAsync(() -> 1, () -> 2, () -> 3) .then(it -> it * 100) .<String>then(it -> { throw new RuntimeException("boo!"); }).capture(e -> count++) .block(status -> status.getCompleted() >= 1); assertThat(strings.size(), is(0)); assertThat(count, is(3)); } @Test public void testBreakoutAllCompleted() throws InterruptedException, ExecutionException { count =0; List<Integer> results = new SimpleReact() .<Integer> ofAsync(() -> 1, () -> 2, () -> 3) .then(it -> it * 100) .then(it -> { if(it==100) throw new RuntimeException("boo!"); else sleep(it); return it; }).capture(e -> count++) .block(status -> status.getAllCompleted() >0); assertThat(results.size(), is(0)); assertThat(count, is(1)); } @Test public void testBreakoutAllCompletedAndTime() throws InterruptedException, ExecutionException { count =0; List<Integer> results = new SimpleReact() .<Integer> ofAsync(() -> 1, () -> 2, () -> 3) .then(it -> it * 100) .then(it -> { sleep(it); return it; }).capture(e -> count++) .block(status -> status.getAllCompleted() >1 && status.getElapsedMillis()>200); assertThat(results.size(), greaterThan(1)); assertThat(count, is(0)); } @Test public void testBreakoutInEffective() throws InterruptedException, ExecutionException { Throwable[] error = { null }; List<String> strings = new SimpleReact() .<Integer> ofAsync(() -> 1, () -> 2, () -> 3) .then(it -> it * 100) .then(it -> { if (it == 100) throw new RuntimeException("boo!"); return it; }).onFail(e -> 1) .then(it -> "*" + it) .block(status -> status.getCompleted() > 5); assertThat(strings.size(), is(3)); } private Object sleep(Integer it) { try { Thread.sleep(it); } catch (InterruptedException e) { e.printStackTrace(); } return it; } } ======================= File: cyclops/src/main/java/com/oath/cyclops/internal/stream/spliterators/LimitLastSpliterator.java ======================= package com.oath.cyclops.internal.stream.spliterators; import java.util.ArrayDeque; import java.util.Spliterator; import java.util.Spliterators; import java.util.Spliterators.AbstractSpliterator; import java.util.function.Consumer; public class LimitLastSpliterator<T> extends AbstractSpliterator<T> implements CopyableSpliterator<T>{ public static <T> Spliterator<T> limitLast(Spliterator<T> source, int limit){ if(limit==0){ return Spliterators.emptySpliterator(); } if(limit==source.getExactSizeIfKnown()){ //right sized already return source; } if(limit==1) return new LimitLastOneSpliterator<T>(source); return new LimitLastSpliterator<T>(source,limit); } private final ArrayDeque<T> buffer; private final int limit; private final Spliterator<T> source; public LimitLastSpliterator(final Spliterator<T> source, final int limit) { super(source.estimateSize(),source.characteristics() & Spliterator.ORDERED); buffer = new ArrayDeque<>( limit); this.source = source;; this.limit = limit; } boolean requestedAll =false; @Override public boolean tryAdvance(Consumer<? super T> action) { if(!requestedAll) { source.forEachRemaining(e -> { if (buffer.size() == limit) { buffer.poll(); } buffer.offer(e); }); } requestedAll=true; if(buffer.size()>0){ action.accept(buffer.pop()); } //need to handle case where external subscription is not closed return buffer.size()>0; } @Override public Spliterator<T> copy() { return new LimitLastSpliterator<T>(CopyableSpliterator.copy(source),limit); } } ======================= File: cyclops-pure/src/main/java/cyclops/typeclasses/functor/ContravariantFunctor.java ======================= <gh_stars>100-1000 package cyclops.typeclasses.functor; import com.oath.cyclops.hkt.Higher; import java.util.function.Function; public interface ContravariantFunctor<W>{ <T, R> Higher<W,R> contramap(Function<? super R,? extends T> fn, Higher<W,T> ds); } ======================= File: cyclops/src/main/java/com/oath/cyclops/internal/stream/spliterators/push/OnEmptyOperator.java ======================= <filename>cyclops/src/main/java/com/oath/cyclops/internal/stream/spliterators/push/OnEmptyOperator.java<gh_stars>100-1000 package com.oath.cyclops.internal.stream.spliterators.push; import java.util.concurrent.locks.LockSupport; import java.util.function.Consumer; import java.util.function.Supplier; /** * Created by johnmcclean on 12/01/2017. */ public class OnEmptyOperator<T> extends BaseOperator<T,T> { Supplier<? extends T> value; public OnEmptyOperator(Operator<T> source, Supplier<? extends T> value){ super(source); this.value = value; } @Override public StreamSubscription subscribe(Consumer<? super T> onNext, Consumer<? super Throwable> onError, Runnable onComplete) { boolean[] data ={ false}; return source.subscribe(e->{ if(!data[0]) data[0]=true; onNext.accept(e); } ,onError,()->{ if(data[0]==false) onNext.accept(value.get()); onComplete.run(); }); } @Override public void subscribeAll(Consumer<? super T> onNext, Consumer<? super Throwable> onError, Runnable onCompleteDs) { boolean[] data ={ false}; source.subscribeAll(e->{ if(!data[0]) data[0]=true; onNext.accept(e); } ,onError,()->{ if(data[0]==false) onNext.accept(value.get()); onCompleteDs.run(); }); } } ======================= File: cyclops/src/test/java/cyclops/control/FutureTest.java ======================= package cyclops.control; import com.oath.cyclops.types.persistent.PersistentSet; import com.oath.cyclops.util.box.Mutable; import cyclops.companion.*; import cyclops.data.HashSet; import cyclops.function.Monoid; import cyclops.reactive.ReactiveSeq; import cyclops.reactive.Spouts; import cyclops.data.tuple.Tuple; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import reactor.core.publisher.Flux; import java.util.Arrays; import java.util.NoSuchElementException; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.stream.StreamSupport; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; public class FutureTest { static Executor ex = Executors.newFixedThreadPool(5); Future<Integer> just; Future<Integer> none; NoSuchElementException exception = new NoSuchElementException(); @Before public void setUp() throws Exception { just = Future.of(CompletableFuture.completedFuture(10)); none = Future.ofError(exception); } private void sleep(long time){ try { Thread.sleep(time); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Test public void combine(){ Monoid<Integer> add = Monoid.of(0,Semigroups.intSum); System.out.println("Just " + just.zip(add,none)); assertThat(just.zip(add,none).orElse(-1),equalTo(none.orElse(-1))); } @Test public void sub(){ Future<Integer> f = Future.future(); Spouts.from(f).forEachSubscribe(System.out::println); f.complete(10); } @Test public void testVisitAsync(){ int r = Future.ofResult(10) .visitAsync(i->i*2, e->-1).toOptional() .get(); assertThat(20,equalTo(r)); } @Test public void testVisitFailAsync(){ int r = Future.<Integer>ofError(new RuntimeException()) .visitAsync(i->i*2, e->-1).toOptional() .get(); assertThat(-1,equalTo(r)); } @Test public void testVisit(){ int r = Future.ofResult(10) .fold(i->i*2, e->-1); assertThat(20,equalTo(r)); } @Test public void testVisitFail(){ int r = Future.<Integer>ofError(new RuntimeException()) .fold(i->i*2, e->-1); assertThat(-1,equalTo(r)); } @Test public void testFirstSuccess(){ Future<Integer> ft = Future.future(); Future<Integer> result = Future.firstSuccess(Future.of(()->1),ft); ft.complete(10); assertThat(result.get(), is(equalTo(Try.success(1)))); } @Test public void testZip(){ assertThat(Future.ofResult(10).zip(Eval.now(20),(a, b)->a+b).orElse(-100),equalTo(30)); assertThat(Future.ofResult(10).zip((a, b)->a+b, Eval.now(20)).orElse(-100),equalTo(30)); assertThat(Future.ofResult(10).zip(ReactiveSeq.of(20),(a, b)->a+b).orElse(-100),equalTo(30)); assertThat(Future.ofResult(10).zip(ReactiveSeq.of(20)).orElse(null),equalTo(Tuple.tuple(10,20))); assertThat(Future.ofResult(10).zip(Eval.now(20)).orElse(null),equalTo(Tuple.tuple(10,20))); } @Test public void apNonBlocking(){ Future<String> f = Future.of(()->{ sleep(1000l); return "hello";},ex) .zip(Future.of(()->" world",ex),String::concat); System.out.println("hello"); long start=System.currentTimeMillis(); System.out.println(f.get()); assertThat(System.currentTimeMillis()-start,greaterThan(400l)); } @Test public void FutureFromIterableTest() { ReactiveSeq<Integer> stream = ReactiveSeq.of(1, 2, 3); Future<Integer> maybe = Future.fromPublisher(stream); assertThat(maybe.toOptional().get(), equalTo(1)); } @Test public void FutureAsyncFromIterableTest() { ReactiveSeq<Integer> stream = ReactiveSeq.of(1, 2, 3); Future<Integer> maybe = Future.fromIterable(stream, ex); assertThat(maybe.toOptional().get(), equalTo(1)); } @Test public void scheduleDelay(){ long start = System.currentTimeMillis(); String res = Future.schedule(100, Executors.newScheduledThreadPool(1), ()->"hello").toOptional() .get(); assertThat(100l,lessThan(System.currentTimeMillis()-start)); assertThat(res,equalTo("hello")); } @Test public void scheduleCron(){ long start = System.currentTimeMillis(); Future.schedule("* * * * *?", Executors.newScheduledThreadPool(1), ()->"hello").toOptional() .get(); String res = Future.schedule("* * * * *?", Executors.newScheduledThreadPool(1), ()->"hello").toOptional() .get(); assertThat(1000l,lessThan(System.currentTimeMillis()-start)); assertThat(res,equalTo("hello")); } @Test public void combine2(){ Monoid<Integer> add = Monoid.of(0,Semigroups.intSum); assertThat(just.zip(add, Maybe.just(10)).toMaybe(),equalTo(Maybe.just(20))); Monoid<Integer> firstNonNull = Monoid.of(null, Semigroups.firstNonNull()); assertThat(just.zip(firstNonNull,Future.ofResult(null)).get(),equalTo(just.get())); } @Test public void testToMaybe() { assertThat(just.toMaybe(),equalTo(Maybe.of(10))); assertThat(none.toMaybe(),equalTo(Maybe.nothing())); } private int add1(int i){ return i+1; } @Test public void testOfT() { assertThat(Ior.right(1),equalTo(Ior.right(1))); } @Test public void testSequence() { Future<ReactiveSeq<Integer>> maybes = Future.sequence(Arrays.asList(just, Future.ofResult(1))); assertThat(maybes.map(s->s.toList()).orElse(Arrays.asList()),equalTo(Arrays.asList(10,1))); } @Test public void testSequenceCF() { CompletableFuture<ReactiveSeq<Integer>> maybes = CompletableFutures.sequence(Arrays.asList(just.getFuture(),none.getFuture(), Future.ofResult(1).getFuture())); assertThat(maybes.isCompletedExceptionally(),equalTo(true)); } @Test public void testAccumulateSuccessSemigroup() { Future<Integer> maybes = Future.accumulateSuccess(Monoid.of(0,(a,b)->a+1),Arrays.asList(just,none, Future.ofResult(1))); assertThat(maybes.get(),equalTo(Try.success(2))); } @Test public void testAccumulateSuccess() { Future<PersistentSet<Integer>> maybes = Future.accumulateSuccess(Arrays.asList(just,none, Future.ofResult(1)), Reducers.toPersistentSet()); assertThat(maybes.get(),equalTo(Try.success(HashSet.of(10,1)))); } @Test @Ignore public void testAccumulateJNonBlocking() { Future<PersistentSet<Integer>> maybes = Future.accumulateSuccess(Arrays.asList(just,none, Future.of(()->{while(true){System.out.println("hello");}},Executors.newFixedThreadPool(1)), Future.ofResult(1)),Reducers.toPersistentSet()); System.out.println("not blocked"); } @Test public void testAccumulateNoValue() { Future<String> maybes = Future.accumulate(Arrays.asList(), i->""+i,Monoids.stringConcat); assertThat(maybes.orElse("npo"),equalTo("")); } @Test public void testAccumulateOneValue() { Future<String> maybes = Future.accumulate(Arrays.asList(just), i->""+i,Monoids.stringConcat); assertThat(maybes.get(),equalTo(Try.success("10"))); } @Test public void testAccumulateJustCollectionXOfMaybeOfTFunctionOfQsuperTRSemigroupOfR() { Future<String> maybes = Future.accumulate(Arrays.asList(just, Future.ofResult(1)), i->""+i,Monoids.stringConcat); assertThat(maybes.get(),equalTo(Try.success("101"))); } @Test public void testAccumulateJust() { Future<Integer> maybes = Future.accumulate(Monoids.intSum,Arrays.asList(just, Future.ofResult(1))); assertThat(maybes.get(),equalTo(Try.success(11))); } @Test public void testAccumulateError() { Future<Integer> maybes = Future.accumulate(Monoids.intSum,Arrays.asList(none, Future.ofResult(1))); assertTrue(maybes.isFailed()); } @Test public void testUnitT() { assertThat(just.unit(20).get(),equalTo(Future.ofResult(20).get())); } @Test public void testisPrimary() { assertTrue(just.isSuccess()); assertTrue(none.isFailed()); } @Test public void testMapFunctionOfQsuperTQextendsR() { assertThat(just.map(i->i+5).get(),equalTo(Try.success(15))); assertTrue(none.map(i->i+5).isFailed()); } @Test public void testFlatMap() { assertThat(just.flatMap(i-> Future.ofResult(i+5) ).get(),equalTo(Future.ofResult(15).get() )); assertTrue(none.flatMap(i-> Future.ofResult(i+5)).isFailed()); } @Test public void testWhenFunctionOfQsuperTQextendsRSupplierOfQextendsR() { assertThat(just.fold(i->i+1,()->20),equalTo(11)); assertThat(none.fold(i->i+1,()->20),equalTo(20)); } @Test public void testStream() { assertThat(just.stream().toList(),equalTo(Arrays.asList(10))); assertThat(none.stream().toList(),equalTo(Arrays.asList())); } @Test public void testOfSupplierOfT() { } @Test public void testConvertTo() { Stream<Integer> toStream = just.fold(m->Stream.of(m),()->Stream.of()); assertThat(toStream.collect(Collectors.toList()),equalTo(Arrays.asList(10))); } @Test public void testConvertToAsync() { Future<Stream<Integer>> async = Future.of(()->just.fold(f->Stream.of((int)f),()->Stream.of())); assertThat(async.orElse(Stream.empty()).collect(Collectors.toList()),equalTo(Arrays.asList(10))); } @Test public void testIterate() { assertThat(just.asSupplier(-100).iterate(i->i+1).limit(10).sumInt(i->i),equalTo(145)); } @Test public void testGenerate() { assertThat(just.asSupplier(-100).generate().limit(10).sumInt(i->i),equalTo(100)); } @Test public void testToXor() { assertThat(just.toEither(-5000),equalTo(Either.right(10))); } @Test public void testToXorNone(){ Either<Throwable,Integer> xor = none.toEither(); assertTrue(xor.isLeft()); assertThat(xor,equalTo(Either.left(exception))); } @Test public void testToXorSecondary() { assertThat(just.toEither(-5000).swap(),equalTo(Either.left(10))); } @Test public void testToXorSecondaryNone(){ Either<Integer, Throwable> xorNone = none.toEither().swap(); assertThat(xorNone,equalTo(Either.right(exception))); } @Test public void testToTry() { assertTrue(none.toTry().isFailure()); assertThat(just.toTry(),equalTo(Try.success(10))); } @Test public void testToTryClassOfXArray() { assertTrue(none.toTry(Throwable.class).isFailure()); } @Test public void testToIor() { assertThat(just.toIor(),equalTo(Ior.right(10))); } @Test public void testToIorNone(){ Ior<Integer, Throwable> ior = none.toIor().swap(); assertTrue(ior.isRight()); assertThat(ior,equalTo(Ior.right(exception))); } @Test public void testToIorSecondary() { assertThat(just.toIor().swap(),equalTo(Ior.left(10))); } @Test public void testToIorSecondaryNone(){ Ior<Integer,Throwable> ior = none.toIor().swap(); assertTrue(ior.isRight()); assertThat(ior,equalTo(Ior.right(exception))); } @Test public void testMkString() { assertThat(just.mkString(),containsString("Future[")); assertThat(none.mkString(),containsString("Future[")); } @Test public void testGet() { assertThat(just.get(),equalTo(Try.success(10))); } @Test public void testFilter() { assertFalse(just.filter(i->i<5).isPresent()); assertTrue(just.filter(i->i>5).isPresent()); assertFalse(none.filter(i->i<5).isPresent()); assertFalse(none.filter(i->i>5).isPresent()); } @Test public void testOfType() { assertFalse(just.ofType(String.class).isPresent()); assertTrue(just.ofType(Integer.class).isPresent()); assertFalse(none.ofType(String.class).isPresent()); assertFalse(none.ofType(Integer.class).isPresent()); } @Test public void testFilterNot() { assertTrue(just.filterNot(i->i<5).isPresent()); assertFalse(just.filterNot(i->i>5).isPresent()); assertFalse(none.filterNot(i->i<5).isPresent()); assertFalse(none.filterNot(i->i>5).isPresent()); } @Test public void testNotNull() { assertTrue(just.notNull().isPresent()); assertFalse(none.notNull().isPresent()); } private int add(int a, int b){ return a+b; } private int add3(int a, int b, int c){ return a+b+c; } private int add4(int a, int b, int c,int d){ return a+b+c+d; } private int add5(int a, int b, int c,int d,int e){ return a+b+c+d+e; } @Test public void testFoldRightMonoidOfT() { assertThat(just.fold(Monoid.of(1, Semigroups.intMult)),equalTo(10)); } @Test public void testWhenFunctionOfQsuperMaybeOfTQextendsR() { assertThat(just.fold(s->"hello", ()->"world"),equalTo("hello")); assertThat(none.fold(s->"hello", ()->"world"),equalTo("world")); } @Test public void testOrElseGet() { assertThat(none.orElseGet(()->2),equalTo(2)); assertThat(just.orElseGet(()->2),equalTo(10)); } @Test public void testToOptional() { assertFalse(none.toOptional().isPresent()); assertTrue(just.toOptional().isPresent()); assertThat(just.toOptional(),equalTo(Optional.of(10))); } @Test public void testToStream() { assertThat(none.stream().collect(Collectors.toList()).size(),equalTo(0)); assertThat(just.stream().collect(Collectors.toList()).size(),equalTo(1)); } @Test public void testOrElse() { assertThat(none.orElse(20),equalTo(20)); assertThat(just.orElse(20),equalTo(10)); } @Test public void testToCompletableFuture() { CompletableFuture<Integer> cf = just.toCompletableFuture(); assertThat(cf.join(),equalTo(10)); } Executor exec = Executors.newFixedThreadPool(1); @Test public void testIterator1() { assertThat(Streams.stream(just.iterator()).collect(Collectors.toList()), equalTo(Arrays.asList(10))); } @Test public void testForEach() { Mutable<Integer> capture = Mutable.of(null); none.forEach(c->capture.set(c)); assertNull(capture.get()); just.forEach(c->capture.set(c)); assertThat(capture.get(),equalTo(10)); } @Test public void testSpliterator() { assertThat(StreamSupport.stream(just.spliterator(),false).collect(Collectors.toList()), equalTo(Arrays.asList(10))); } @Test public void testMapFunctionOfQsuperTQextendsR1() { assertThat(just.map(i->i+5).get(),equalTo(Try.success(15))); } @Test public void testPeek() { Mutable<Integer> capture = Mutable.of(null); just = just.peek(c->capture.set(c)); assertThat(capture.get(),equalTo(10)); } private Trampoline<Integer> sum(int times, int sum){ return times ==0? Trampoline.done(sum) : Trampoline.more(()->sum(times-1,sum+times)); } @Test public void mapBoth(){ assertThat(Future.ofResult(1).map(i->i*2, e->-1).get(),equalTo(Try.success(2))); } @Test public void testUnitT1() { assertThat(none.unit(10).get(),equalTo(just.get())); } @Test public void testRecover() { assertThat(Future.ofError(new RuntimeException()).recover(__ -> true).get(), equalTo(Try.success(true))); } @Test public void testRecoverSupplier() { assertThat(Future.ofError(new RuntimeException()).recover(() -> true).get(), equalTo(Try.success(true))); } @Test public void testFlatMapPublisher() { Future<Integer> f = just.mergeMap(i -> Flux.just(100, i)); assertThat(f.get(), equalTo(Try.success(100))); } } ======================= File: cyclops-anym/src/main/java/com/oath/cyclops/anym/internal/adapters/EitherAdapter.java ======================= package com.oath.cyclops.anym.internal.adapters; import com.oath.cyclops.anym.AnyMValue; import com.oath.cyclops.anym.extensability.AbstractMonadAdapter; import com.oath.cyclops.anym.extensability.MonadAdapter; import com.oath.cyclops.anym.extensability.ValueAdapter; import cyclops.control.Option; import cyclops.control.Either; import cyclops.monads.AnyM; import cyclops.monads.Witness; import cyclops.monads.Witness.either; import lombok.AllArgsConstructor; import java.util.Iterator; import java.util.function.Function; import java.util.function.Predicate; import static cyclops.monads.AnyM.fromEither; import static cyclops.monads.Witness.either; @AllArgsConstructor public class EitherAdapter extends AbstractMonadAdapter<either> implements ValueAdapter<either> { @Override public boolean isFilterable(){ return false; } public <T> Option<T> get(AnyMValue<either,T> t){ return xor(t).toOption(); } @Override public <T> Iterable<T> toIterable(AnyM<either, T> t) { return xor(t); } public <R> R fold(Function<? super MonadAdapter<either>,? extends R> fn1, Function<? super ValueAdapter<either>,? extends R> fn2){ return fn2.apply(this); } public <T> Either<?,T> xor(AnyM<either, T> t){ return (Either<?,T>)t.unwrap(); } @Override public <T> AnyM<either, T> filter(AnyM<either, T> t, Predicate<? super T> fn) { return t; } @Override public <T> AnyM<either, T> empty() { return fromEither(Either.left(null)); } @Override public <T, R> AnyM<either, R> ap(AnyM<either,? extends Function<? super T,? extends R>> fn, AnyM<either, T> apply) { return flatMap(apply,x->fn.map(fnA->fnA.apply(x))); } @Override public <T, R> AnyM<either, R> flatMap(AnyM<either, T> t, Function<? super T,? extends AnyM<either,? extends R>> fn) { return fromEither(either(t).flatMap(fn.andThen(Witness::either))); } @Override public <T, R> AnyM<either, R> map(AnyM<either, T> t, Function<? super T,? extends R> fn) { return fromEither(either(t).map(fn)); } @Override public <T> AnyM<either, T> unitIterable(Iterable<T> it) { return fromEither(fromIterable(it)); } @Override public <T> AnyM<either, T> unit(T o) { return fromEither(Either.right(o)); } public static <ST, T> Either<ST, T> fromIterable(final Iterable<T> iterable) { final Iterator<T> it = iterable.iterator(); return it.hasNext()? Either.right( it.next()) : Either.left(null); } } ======================= File: cyclops-pure/src/main/java/cyclops/typeclasses/Show.java ======================= package cyclops.typeclasses; import com.oath.cyclops.hkt.Higher; public interface Show<W> { default <T> String show(Higher<W,T> ds){ return ds.toString(); } } ======================= File: cyclops/src/test/java/com/oath/cyclops/functions/fluent/FluentSupplierTest.java ======================= <filename>cyclops/src/test/java/com/oath/cyclops/functions/fluent/FluentSupplierTest.java<gh_stars>0 package com.oath.cyclops.functions.fluent; import cyclops.function.FluentFunctions; import cyclops.control.Try; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.util.Arrays; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.*; public class FluentSupplierTest { @Before public void setup(){ this.times =0; } int called; public int getOne(){ called++; return 1; } @Test public void testGet() { assertThat(FluentFunctions.of(this::getOne) .name("mySupplier") .println() .get(),equalTo(1)); } @Test public void testCache() { called=0; Supplier<Integer> fn = FluentFunctions.of(this::getOne) .name("myFunction") .memoize(); fn.get(); fn.get(); fn.get(); assertThat(called,equalTo(1)); } @Test public void testCacheGuava() { Cache<Object, Integer> cache = CacheBuilder.newBuilder() .maximumSize(1000) .expireAfterWrite(10, TimeUnit.MINUTES) .build(); called=0; Supplier<Integer> fn = FluentFunctions.of(this::getOne) .name("myFunction") .memoize((key,f)->cache.get(key,()->f.apply(key))); fn.get(); fn.get(); fn.get(); assertThat(called,equalTo(1)); } int set; public boolean events(){ return set == 10; } @Test public void testBefore(){ set = 0; assertTrue(FluentFunctions.of(this::events) .before(()->set=10) .println() .get()); } int in; boolean out; @Test public void testAfter(){ set = 0; assertFalse(FluentFunctions.of(this::events) .after(out->out=true) .println() .get()); boolean result = FluentFunctions.of(this::events) .after((out2)->{ out=out2; } ) .println() .get(); assertTrue(out==result); } @Test public void testAround(){ set = 0; assertThat(FluentFunctions.of(this::getOne) .around(advice->advice.proceed()) .println() .get(),equalTo(1)); } int times =0; public String exceptionalFirstTime() throws IOException{ if(times==0){ times++; throw new IOException(); } return "hello world"; } @Test public void retry(){ assertThat(FluentFunctions.ofChecked(this::exceptionalFirstTime) .println() .retry(2,500) .get(),equalTo("hello world")); } @Test public void recover(){ assertThat(FluentFunctions.ofChecked(this::exceptionalFirstTime) .recover(IOException.class, ()->"hello boo!") .println() .get(),equalTo("hello boo!")); } @Test(expected=IOException.class) public void recoverDont(){ assertThat(FluentFunctions.ofChecked(this::exceptionalFirstTime) .recover(RuntimeException.class, ()->"hello boo!") .println() .get(),equalTo("hello boo!")); } public String gen(String input){ return input+System.currentTimeMillis(); } @Test public void generate(){ assertThat(FluentFunctions.of(this::gen) .println() .generate("next element") .onePer(1, TimeUnit.SECONDS) .limit(2) .toList().size(),equalTo(2)); } @Test public void testLift(){ FluentFunctions.of(this::getOne) .lift() .get(); } @Test public void testTry(){ Try<String,IOException> tried = FluentFunctions.ofChecked(this::exceptionalFirstTime) .liftTry(IOException.class) .get(); if(tried.isSuccess()) fail("expecting failure"); } Executor ex = Executors.newFixedThreadPool(1); @Test public void liftAsync(){ assertThat(FluentFunctions.of(this::getOne) .liftAsync(ex) .get() .join(),equalTo(1)); } @Test public void async(){ assertThat(FluentFunctions.of(this::getOne) .async(ex) .thenApply(f->f.get()) .join(),equalTo(1)); } } ======================= File: cyclops-futurestream/src/main/java/com/oath/cyclops/react/collectors/lazy/LazyResultConsumer.java ======================= <reponame>zmyer/cyclops-react<filename>cyclops-futurestream/src/main/java/com/oath/cyclops/react/collectors/lazy/LazyResultConsumer.java package com.oath.cyclops.react.collectors.lazy; import java.util.Collection; import java.util.function.Consumer; import java.util.function.Function; import com.oath.cyclops.internal.react.async.future.FastFuture; /** * Interface that defines the rules for Collecting results from Infinite SimpleReact Streams * * @author johnmcclean * */ public interface LazyResultConsumer<T> extends Consumer<FastFuture<T>> { /** * Used to generate a new instance for result toX - populates the supplied Collection * * @param t Collection to be populated * @return Consumer that will populate the toX */ public LazyResultConsumer<T> withResults(Collection<FastFuture<T>> t); /** * @return Completed results */ public Collection<FastFuture<T>> getResults(); /** * @return Completed and active results */ public Collection<FastFuture<T>> getAllResults(); public void block(Function<FastFuture<T>, T> safeJoin); } ======================= File: cyclops-reactive-collections/src/test/java/cyclops/reactive/collections/standard/ListXCollectableTest.java ======================= <filename>cyclops-reactive-collections/src/test/java/cyclops/reactive/collections/standard/ListXCollectableTest.java package cyclops.reactive.collections.standard; import com.oath.cyclops.types.foldable.Folds; import cyclops.reactive.collections.mutable.ListX; import cyclops.streams.CollectableTest; public class ListXCollectableTest extends CollectableTest { @Override public <T> Folds<T> of(T... values) { return ListX.of(values); } } ======================= File: cyclops-futurestream/src/main/java/com/oath/cyclops/internal/react/stream/InfiniteProcessingException.java ======================= package com.oath.cyclops.internal.react.stream; import com.oath.cyclops.internal.react.exceptions.SimpleReactProcessingException; public class InfiniteProcessingException extends SimpleReactProcessingException { /** * */ private static final long serialVersionUID = 1L; public InfiniteProcessingException(final String message) { super(message); } } ======================= File: cyclops/src/main/java/com/oath/cyclops/internal/stream/spliterators/push/MultiCastOperator.java ======================= package com.oath.cyclops.internal.stream.spliterators.push; import cyclops.data.Seq; import java.util.function.Consumer; /** * Created by johnmcclean on 12/01/2017. */ public class MultiCastOperator<T> extends BaseOperator<T,T> { public MultiCastOperator(Operator<T> source,int expect){ super(source); this.expect =expect; } final int expect; Seq<Consumer<? super T>> registeredOnNext = Seq.empty(); Seq<Consumer<? super Throwable>> registeredOnError= Seq.empty(); Seq<Runnable> registeredOnComplete= Seq.empty(); Seq<StreamSubscription> subs = Seq.empty(); @Override public StreamSubscription subscribe(Consumer<? super T> onNext, Consumer<? super Throwable> onError, Runnable onComplete) { registeredOnNext= registeredOnNext.plus(onNext); registeredOnError=registeredOnError.plus(onError); registeredOnComplete =registeredOnComplete.plus(onComplete); StreamSubscription result = new StreamSubscription(){ }; return result; } @Override public void subscribeAll(Consumer<? super T> onNext, Consumer<? super Throwable> onError, Runnable onCompleteDs) { registeredOnNext= registeredOnNext.plus(onNext); registeredOnError = registeredOnError.plus(onError); registeredOnComplete=registeredOnComplete.plus(onCompleteDs); source.subscribeAll(e -> { registeredOnNext.forEach(n -> n.accept(e)); } , e -> registeredOnError.forEach(t -> t.accept(e)), () -> registeredOnComplete.forEach(n -> n.run())); } } ======================= File: cyclops-futurestream/src/main/java/com/oath/cyclops/react/threads/ParallelElasticPools.java ======================= package com.oath.cyclops.react.threads; import java.util.concurrent.ForkJoinPool; import cyclops.futurestream.LazyReact; import cyclops.futurestream.SimpleReact; /** * A ReactPool of each type for parallel Streams * Thread pool will be sized to number of processors * * @author johnmcclean * */ public class ParallelElasticPools { public final static ReactPool<SimpleReact> simpleReact = ReactPool.elasticPool(() -> new SimpleReact( new ForkJoinPool( Runtime.getRuntime() .availableProcessors()))); public final static ReactPool<LazyReact> lazyReact = ReactPool.elasticPool(() -> new LazyReact( new ForkJoinPool( Runtime.getRuntime() .availableProcessors()))); } ======================= File: cyclops/src/main/java/com/oath/cyclops/types/functor/FilterableTransformable.java ======================= package com.oath.cyclops.types.functor; import com.oath.cyclops.types.Filters; import java.util.function.Function; import java.util.function.Predicate; /** * Represents a Transformable that is also Filters (e.g. a Stream or Optional type) * * @author johnmcclean * * @param <T> Data type of the element(s) in this FilterableTransformable */ public interface FilterableTransformable<T> extends Filters<T>, Transformable<T> { /* (non-Javadoc) * @see com.oath.cyclops.types.Filters#filter(java.util.function.Predicate) */ @Override FilterableTransformable<T> filter(Predicate<? super T> fn); /* (non-Javadoc) * @see com.oath.cyclops.types.functor.Transformable#transform(java.util.function.Function) */ @Override <R> FilterableTransformable<R> map(Function<? super T,? extends R> fn); } ======================= File: cyclops/src/main/java/cyclops/companion/Groups.java ======================= package cyclops.companion; import cyclops.function.Group; import java.math.BigInteger; public interface Groups { /** * Combine two Integers by summing them */ static Group<Integer> intSum = Group.of(a->-a, Monoids.intSum); /** * Combine two Longs by summing them */ static Group<Long> longSum = Group.of(a->-a, Monoids.longSum); /** * Combine two Doubles by summing them */ static Group<Double> doubleSum = Group.of(a->-a, Monoids.doubleSum); /** * Combine two BigIngegers by summing them */ static Group<BigInteger> bigIntSum = Group.of(a->BigInteger.ZERO.subtract(a), Monoids.bigIntSum); } ======================= File: cyclops/src/test/java/cyclops/control/Eval2Test.java ======================= <reponame>zmyer/cyclops-react<gh_stars>0 package cyclops.control; import com.oath.cyclops.types.persistent.PersistentSet; import cyclops.data.HashSet; import cyclops.companion.Monoids; import cyclops.companion.Reducers; import cyclops.companion.Semigroups; import cyclops.companion.Streams; import cyclops.control.Eval.Module.Later; import com.oath.cyclops.util.box.Mutable; import cyclops.function.Monoid; import cyclops.reactive.ReactiveSeq; import org.junit.Before; import org.junit.Test; import java.util.Arrays; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.stream.StreamSupport; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.*; public class Eval2Test { Eval<Integer> just; Eval<Integer> none; @Before public void setUp() throws Exception { just = Eval.now(10); none = Eval.now(null); } @Test public void equals(){ assertTrue(Eval.always(()->10).equals(Eval.later(()->10))); assertTrue(Eval.always(()->10).equals(Eval.now(10))); assertTrue(Eval.now(10).equals(Eval.later(()->10))); assertTrue(Eval.later(()->10).equals(Eval.always(()->10))); assertTrue(Eval.always(()->null).equals(Eval.later(()->null))); assertFalse(Eval.always(()->10).equals(Eval.later(()->null))); assertFalse(Eval.always(()->null).equals(Eval.later(()->10))); } @Test public void combine(){ just.combineEager(Monoid.of(0,(a,b)->a+1),Eval.now(10)).printOut(); Monoid<Integer> add = Monoid.of(0,Semigroups.intSum); assertThat(just.combineEager(add,Eval.now(10)),equalTo(Eval.now(20))); Monoid<Integer> firstNonNull = Monoid.of(null, Semigroups.firstNonNull()); assertThat(just.combineEager(firstNonNull,none),equalTo(just)); } @Test public void testToMaybe() { assertThat(just.toMaybe(),equalTo(Maybe.of(10))); assertThat(none.toMaybe(),equalTo(Maybe.nothing())); } private int add1(int i){ return i+1; } @Test public void testFromOptional() { assertThat(Maybe.fromOptional(Optional.of(10)),equalTo(just.toMaybe())); } @Test public void testFromEvalSome() { assertThat(Maybe.fromEval(Eval.now(10)),equalTo(just.toMaybe())); } @Test public void testOfT() { assertThat(Maybe.of(1),equalTo(Maybe.of(1))); } @Test public void testOfNullable() { assertFalse(Maybe.ofNullable(null).isPresent()); assertThat(Maybe.ofNullable(1),equalTo(Maybe.of(1))); } @Test public void testNarrow() { assertThat(Maybe.ofNullable(1),equalTo(Maybe.narrow(Maybe.of(1)))); } @Test public void testSequence() { Eval<ReactiveSeq<Integer>> maybes =Eval.sequence(Arrays.asList(just,Eval.now(1))); assertThat(maybes.map(s->s.toList()),equalTo(Eval.now(Arrays.asList(10,1)))); } @Test public void testAccumulateJustCollectionXOfMaybeOfTReducerOfR() { Eval<PersistentSet<Integer>> maybes =Eval.accumulate(Arrays.asList(just,Eval.now(1)),Reducers.toPersistentSet()); assertThat(maybes,equalTo(Eval.now(HashSet.of(10,1)))); } @Test public void testAccumulateJustCollectionXOfMaybeOfTFunctionOfQsuperTRSemigroupOfR() { Eval<String> maybes =Eval.accumulate(Arrays.asList(just,Eval.later(()->1)),i->""+i, Monoids.stringConcat); assertThat(maybes,equalTo(Eval.now("101"))); } @Test public void testAccumulateJust() { Eval<Integer> maybes =Eval.accumulate(Monoids.intSum,Arrays.asList(just,Eval.now(1))); assertThat(maybes,equalTo(Eval.now(11))); } @Test public void testUnitT() { assertThat(just.unit(20),equalTo(Eval.now(20))); } @Test public void testIsPresent() { assertTrue(just.toMaybe().isPresent()); assertFalse(none.toMaybe().isPresent()); } @Test public void testRecoverSupplierOfT() { assertThat(just.toMaybe().recover(20),equalTo(Maybe.of(10))); assertThat(none.toMaybe().recover(10),equalTo(Maybe.of(10))); } @Test public void testRecoverT() { assertThat(just.toMaybe().recover(()->20),equalTo(Maybe.of(10))); assertThat(none.toMaybe().recover(()->10),equalTo(Maybe.of(10))); } @Test public void testMapFunctionOfQsuperTQextendsR() { assertThat(just.map(i->i+5),equalTo(Eval.now(15))); assertThat(none.toMaybe().map(i->i+5),equalTo(Maybe.nothing())); } @Test public void testFlatMap() { assertThat(just.flatMap(i->Eval.now(i+5)),equalTo(Eval.later(()->15))); assertThat(none.toMaybe().flatMap(i->Maybe.of(i+5)),equalTo(Maybe.nothing())); } @Test public void testWhenFunctionOfQsuperTQextendsRSupplierOfQextendsR() { assertThat(just.fold(i->i+1,()->20),equalTo(11)); assertThat(none.fold(i->i+1,()->20),equalTo(20)); } @Test public void testStream() { assertThat(just.stream().toList(),equalTo(Arrays.asList(10))); assertThat(none.stream().filter(i->i!=null).toList(),equalTo(Arrays.asList())); } @Test public void testOfSupplierOfT() { } public void testConvertTo() { Stream<Integer> toStream = just.fold(m->Stream.of(m),()->Stream.of()); assertThat(toStream.collect(Collectors.toList()),equalTo(Arrays.asList(10))); } @Test public void testConvertToAsync() { Future<Stream<Integer>> async = Future.of(()->just.fold(f->Stream.of((int)f),()->Stream.of())); assertThat(async.toOptional().get().collect(Collectors.toList()),equalTo(Arrays.asList(10))); } @Test public void testIterate() { assertThat(just.asSupplier(-10000).iterate(i->i+1).limit(10).sumInt(i->i),equalTo( Stream.iterate(just.get(),i->i+1).limit(10).mapToInt(i->i).sum())); assertThat(just.asSupplier(-10000).iterate(i->i+1).limit(10).sumInt(i->i),equalTo(145)); } @Test public void testGenerate() { assertThat(just.asSupplier(-10000).generate().limit(10).sumInt(i->i),equalTo(100)); } @Test public void testToXor() { assertThat(just.toEither(-5000),equalTo(Either.right(10))); } @Test public void testToXorNone(){ Either<?,Integer> empty = none.toEither(-50000); assertTrue(empty.swap().map(__->10).toOptional().get()==10); } @Test public void testToXorSecondary() { assertThat(just.toEither(-5000).swap(),equalTo(Either.left(10))); } @Test public void testToXorSecondaryNone(){ Either<Integer,?> empty = none.toEither(-50000).swap(); assertTrue(empty.isRight()); assertThat(empty.map(__->10),equalTo(Either.right(10))); } @Test public void testToTry() { assertTrue(none.toTry().isFailure()); assertThat(just.toTry(),equalTo(Try.success(10))); assertTrue(Try.fromPublisher(none).isFailure()); assertThat(Try.fromPublisher(just),equalTo(Try.success(10))); } @Test public void testToTryClassOfXArray() { System.out.println(none.toTry(Throwable.class)); assertFalse(none.toTry(Throwable.class).isSuccess()); } @Test public void testToIorNone(){ Either<Integer,?> empty = none.toEither(-50000).swap(); assertTrue(empty.isRight()); assertThat(empty.map(__->10),equalTo(Either.right(10))); } @Test public void testMkString() { assertThat(just.mkString(),equalTo("Always[10]")); assertThat(none.mkString(),equalTo("Always[]")); } @Test public void testGet() { assertThat(just.get(),equalTo(10)); } @Test public void testGetNone() { assertThat(none.get(),nullValue()); } @Test public void testFilter() { assertFalse(just.filter(i->i<5).isPresent()); assertTrue(just.filter(i->i>5).isPresent()); assertFalse(none.filter(i->i!=null).isPresent()); assertFalse(none.filter(i->i!=null).isPresent()); } @Test public void testOfType() { assertFalse(just.ofType(String.class).isPresent()); assertTrue(just.ofType(Integer.class).isPresent()); assertFalse(none.ofType(String.class).isPresent()); assertFalse(none.ofType(Integer.class).isPresent()); } @Test public void testFilterNot() { assertTrue(just.filterNot(i->i<5).isPresent()); assertFalse(just.filterNot(i->i>5).isPresent()); assertFalse(none.filterNot(i->i==null).isPresent()); assertFalse(none.filterNot(i->i==null).isPresent()); } @Test public void testNotNull() { assertTrue(just.notNull().isPresent()); assertFalse(none.notNull().isPresent()); } private int add(int a, int b){ return a+b; } @Test public void testZipEval() { assertThat(just.zip(Eval.later(()->20),this::add),equalTo(Eval.now(30))); } @Test public void testZipEvalLazy(){ assertTrue(Eval.later(()->10).zip(Eval.later(()->20),this::add) instanceof Later); } @Test public void testZipPubEval() { assertThat(just.zip(Eval.later(()->20),this::add),equalTo(Eval.now(30))); } @Test public void testZipPubEvalLazy(){ assertTrue(Eval.later(()->10).zip(this::add, Eval.later(()->20)) instanceof Eval.Module.FutureAlways); } private int add3(int a, int b, int c){ return a+b+c; } private int add4(int a, int b, int c,int d){ return a+b+c+d; } private int add5(int a, int b, int c,int d,int e){ return a+b+c+d+e; } @Test public void testFoldRightMonoidOfT() { assertThat(just.fold(Monoid.of(1,Semigroups.intMult)),equalTo(10)); } @Test public void testWhenFunctionOfQsuperMaybeOfTQextendsR() { assertThat(just.fold(s->"hello", ()->"world"),equalTo("hello")); assertThat(none.fold(s->"hello", ()->"world"),equalTo("world")); } @Test public void testOrElseGet() { assertThat(none.orElseGet(()->2),equalTo(2)); assertThat(just.orElseGet(()->2),equalTo(10)); } @Test public void testToOptional() { assertFalse(none.toOptional().isPresent()); assertTrue(just.toOptional().isPresent()); assertThat(just.toOptional(),equalTo(Optional.of(10))); } @Test public void testToStream() { assertThat(none.stream().collect(Collectors.toList()).size(),equalTo(1)); assertThat(just.stream().collect(Collectors.toList()).size(),equalTo(1)); } @Test public void testOrElse() { assertThat(none.orElse(20),equalTo(20)); assertThat(just.orElse(20),equalTo(10)); } @Test public void testToFuture() { Future<Integer> cf = just.toFuture(); assertThat(cf.orElse(-1),equalTo(10)); } @Test public void testIterator1() { assertThat(Streams.stream(just.iterator()).collect(Collectors.toList()), equalTo(Arrays.asList(10))); } @Test public void testForEach() { Mutable<Integer> capture = Mutable.of(null); none.forEach(c->capture.set(c)); assertNull(capture.get()); just.forEach(c->capture.set(c)); assertThat(capture.get(),equalTo(10)); } @Test public void testSpliterator() { assertThat(StreamSupport.stream(just.spliterator(),false).collect(Collectors.toList()), equalTo(Arrays.asList(10))); } @Test public void testMapFunctionOfQsuperTQextendsR1() { assertThat(just.map(i->i+5),equalTo(Eval.now(15))); } @Test public void testPeek() { Mutable<Integer> capture = Mutable.of(null); just = just.peek(c->capture.set(c)); just.get(); assertThat(capture.get(),equalTo(10)); } private Trampoline<Integer> sum(int times, int sum){ return times ==0? Trampoline.done(sum) : Trampoline.more(()->sum(times-1,sum+times)); } @Test public void testUnitT1() { assertThat(none.unit(10),equalTo(just)); } } ======================= File: cyclops-reactive-collections/src/main/java/cyclops/reactive/collections/mutable/MapX.java ======================= package cyclops.reactive.collections.mutable; import com.oath.cyclops.ReactiveConvertableSequence; import com.oath.cyclops.data.collections.extensions.FluentMapX; import com.oath.cyclops.types.Unwrapable; import com.oath.cyclops.types.foldable.Folds; import com.oath.cyclops.types.foldable.To; import com.oath.cyclops.types.functor.BiTransformable; import com.oath.cyclops.types.functor.Transformable; import com.oath.cyclops.types.persistent.PersistentMap; import com.oath.cyclops.types.reactive.ReactiveStreamsTerminalOperations; import com.oath.cyclops.types.recoverable.OnEmpty; import com.oath.cyclops.types.recoverable.OnEmptySwitch; import com.oath.cyclops.types.traversable.IterableFilterable; import cyclops.companion.Streams; import cyclops.data.tuple.Tuple; import cyclops.data.tuple.Tuple2; import cyclops.reactive.ReactiveSeq; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import java.util.*; import java.util.function.*; import java.util.stream.Collector; import java.util.stream.Collectors; import java.util.stream.Stream; import com.oath.cyclops.data.collections.extensions.standard.MapXImpl; /** * An eXtended Map type, that offers additional eagerly executed functional style operators such as bimap, filter and more * * @author johnmcclean * * @param <K> Key type * @param <V> Value type */ public interface MapX<K, V> extends To<MapX<K,V>>,Map<K, V>,Unwrapable, FluentMapX<K, V>, BiTransformable<K, V>, Transformable<V>, IterableFilterable<Tuple2<K, V>>, OnEmpty<Tuple2<K, V>>, OnEmptySwitch<Tuple2<K, V>, Map<K, V>>, Publisher<Tuple2<K, V>>, Folds<Tuple2<K, V>>,ReactiveStreamsTerminalOperations<Tuple2<K,V>> { /** * * @return A Collector that generates a mutable Map from a Collection of Tuple2 */ static <K, V> Collector<Tuple2<? extends K,? extends V>,?, Map<K, V>> defaultCollector() { return Collectors.toMap(t -> t._1(), t -> t._2()); } /** * @return A Collector that generates an Immutable Map from a Collection of Tuple2 */ static <K, V> Collector<Tuple2<? extends K,? extends V>,?, Map<K, V>> immutableCollector() { return Collectors.collectingAndThen(defaultCollector(), Collections::unmodifiableMap); } /** * @return A Collector that generates a mutable MapX from a Collection of Tuple2 */ static <K, V> Collector<Tuple2<? extends K,? extends V>,?, Map<K, V>> toMapX() { return Collectors.collectingAndThen(defaultCollector(), (final Map<K, V> d) -> new MapXImpl<K, V>( d, defaultCollector())); } /** * @return The currently configured Map Collector for this MapX */ public <K, V> Collector<Tuple2<? extends K,? extends V>,?, Map<K, V>> getCollector(); /* (non-Javadoc) * @see com.oath.cyclops.types.foldable.Folds#stream() */ @Override default ReactiveSeq<Tuple2<K, V>> stream() { return ReactiveSeq.fromIterable(entrySet()) .map(e -> Tuple.tuple(e.getKey(), e.getValue())); } /** * @return An zero MapX */ static <K, V> MapX<K, V> empty() { return fromMap(new HashMap<K, V>()); } static <K, V> MapX<K, V> fromPersistentMap(PersistentMap<K,V> map) { return fromMap(map.mapView()); } /** * Wrap a Map in a MapX * * @param map to wrap * @return MapX wrapping the supplied Map */ public static <K, V> MapX<K, V> fromMap(final Map<? extends K,? extends V> map) { return fromMap(defaultCollector(), map); } /** * Wrap a transform in a MapX, also supplying a Collector for use in operations * * @param collector To generate new MapX's from * @param map to wrap * @return MapX wrapping the supplied Map */ public static <K, V> MapX<K, V> fromMap(final Collector<Tuple2<? extends K,? extends V>,?, Map<K, V>> collector, final Map<? extends K,? extends V> map) { if (map instanceof MapX) return (MapX) map; if (map instanceof Map) return new MapXImpl<K, V>( (Map) map, collector); return new MapXImpl<K, V>( Streams.stream(map) .map(e -> Tuple.tuple(e.getKey(), e.getValue())) .collect(collector), collector); } /** * Construct a new MapX with the same collector from the supplied Stream * * @param stream ot Tuples to convert into a MapX * @return MapX */ default MapX<K, V> fromStream(final ReactiveSeq<Tuple2<K, V>> stream) { return new MapXImpl<K,V>( stream.toMap(t -> t._1(), t -> t._2()), getCollector()); } /* (non-Javadoc) * @see java.lang.Iterable#iterator() */ @Override default Iterator<Tuple2<K, V>> iterator() { return stream().iterator(); } /* (non-Javadoc) * @see com.oath.cyclops.lambda.monads.Transformable#transform(java.util.function.Function) */ default <KR, VR> MapX<KR, VR> flatMap(final BiFunction<? super K,? super V,? extends MapX<KR, VR>> fn) { final ReactiveSeq<Tuple2<KR, VR>> s = stream().flatMap(t -> fn.apply(t._1(), t._2()) .stream()); return new MapXImpl<>( s.<KR, VR> toMap(t -> t._1(), t -> t._2()), getCollector()); } /* (non-Javadoc) * @see com.oath.cyclops.lambda.monads.Transformable#transform(java.util.function.Function) */ @Override default <R> MapX<K, R> map(final Function<? super V,? extends R> fn) { final ReactiveSeq<Tuple2<K, R>> s = stream().map(t -> t.map2(v -> fn.apply(v))); return new MapXImpl<>( s.<K, R> toMap(t -> t._1(), t -> t._2()), getCollector()); } /* (non-Javadoc) * @see com.oath.cyclops.lambda.monads.MapX#bimap(java.util.function.Function, java.util.function.Function) */ @Override default <R1, R2> MapX<R1, R2> bimap(final Function<? super K,? extends R1> fn1, final Function<? super V,? extends R2> fn2) { final ReactiveSeq<Tuple2<R1, V>> s1 = stream().map(t -> t.map1(v -> fn1.apply(v))); final ReactiveSeq<Tuple2<R1, R2>> s2 = s1.map(t -> t.map2(v -> fn2.apply(v))); return new MapXImpl<>( s2.<R1, R2> toMap(t -> t._1(), t -> t._2()), getCollector()); } @Override int size(); @Override boolean isEmpty(); /* (non-Javadoc) * @see com.oath.cyclops.types.stream.CyclopsCollectable#allMatch(java.util.function.Predicate) */ @Override default boolean allMatch(final Predicate<? super Tuple2<K, V>> c) { return Folds.super.allMatch(c); } /* (non-Javadoc) * @see com.oath.cyclops.types.stream.CyclopsCollectable#anyMatch(java.util.function.Predicate) */ @Override default boolean anyMatch(final Predicate<? super Tuple2<K, V>> c) { return Folds.super.anyMatch(c); } /* (non-Javadoc) * @see com.oath.cyclops.types.stream.CyclopsCollectable#noneMatch(java.util.function.Predicate) */ @Override default boolean noneMatch(final Predicate<? super Tuple2<K, V>> c) { return Folds.super.noneMatch(c); } /* (non-Javadoc) * @see FluentMapX#plus(java.lang.Object, java.lang.Object) */ @Override default MapX<K, V> plus(final K key, final V value) { return (MapX<K, V>) FluentMapX.super.plus(key, value); } /* (non-Javadoc) * @see FluentMapX#plusAll(com.oath.cyclops.types.persistent.PersistentMap) */ @Override default MapX<K, V> plusAll(final PersistentMap<? extends K,? extends V> map) { return (MapX<K, V>) FluentMapX.super.plusAll(map); } /* (non-Javadoc) * @see FluentMapX#plusAll(java.util.Map) */ @Override default MapX<K, V> plusAll(final Map<? extends K,? extends V> map) { return (MapX<K, V>) FluentMapX.super.plusAll(map); } /* (non-Javadoc) * @see FluentMapX#removeValue(java.lang.Object) */ @Override default MapX<K, V> minus(final K key) { return (MapX<K, V>) FluentMapX.super.minus(key); } /* (non-Javadoc) * @see FluentMapX#removeAll(java.util.Collection) */ @Override default MapX<K, V> minusAll(final Collection<? extends K> keys) { return (MapX<K, V>) FluentMapX.super.minusAll(keys); } /* (non-Javadoc) * @see com.oath.cyclops.lambda.monads.Transformable#peek(java.util.function.Consumer) */ @Override default MapX<K, V> peek(final Consumer<? super V> c) { return (MapX<K, V>) Transformable.super.peek(c); } /* (non-Javadoc) * @see com.oath.cyclops.lambda.monads.Filters#filter(java.util.function.Predicate) */ @Override default MapX<K, V> filter(final Predicate<? super Tuple2<K, V>> fn) { return stream().filter(fn).to(ReactiveConvertableSequence::converter) .mapX(t -> t._1(), t -> t._2()); } /* (non-Javadoc) * @see com.oath.cyclops.lambda.monads.Filters#filterNot(java.util.function.Predicate) */ @Override default MapX<K, V> filterNot(final Predicate<? super Tuple2<K, V>> fn) { return (MapX<K, V>) IterableFilterable.super.filterNot(fn); } /* (non-Javadoc) * @see com.oath.cyclops.lambda.monads.Filters#notNull() */ @Override default MapX<K, V> notNull() { return (MapX<K, V>) IterableFilterable.super.notNull(); } /* (non-Javadoc) * @see com.oath.cyclops.lambda.monads.Filters#removeAll(java.util.stream.Stream) */ @Override default MapX<K, V> removeStream(final Stream<? extends Tuple2<K, V>> stream) { return (MapX<K, V>) IterableFilterable.super.removeStream(stream); } /* (non-Javadoc) * @see com.oath.cyclops.lambda.monads.Filters#removeAll(java.lang.Iterable) */ @Override default MapX<K, V> removeAll(final Iterable<? extends Tuple2<K, V>> it) { return (MapX<K, V>) IterableFilterable.super.removeAll(it); } /* (non-Javadoc) * @see com.oath.cyclops.lambda.monads.Filters#removeAll(java.lang.Object[]) */ @Override default MapX<K, V> removeAll(final Tuple2<K, V>... values) { return (MapX<K, V>) IterableFilterable.super.removeAll(values); } /* (non-Javadoc) * @see com.oath.cyclops.lambda.monads.Filters#retainAllI(java.lang.Iterable) */ @Override default MapX<K, V> retainAll(final Iterable<? extends Tuple2<K, V>> it) { return (MapX<K, V>) IterableFilterable.super.retainAll(it); } /* (non-Javadoc) * @see com.oath.cyclops.lambda.monads.Filters#retainAllI(java.util.stream.Stream) */ @Override default MapX<K, V> retainStream(final Stream<? extends Tuple2<K, V>> stream) { return (MapX<K, V>) IterableFilterable.super.retainStream(stream); } /* (non-Javadoc) * @see com.oath.cyclops.lambda.monads.Filters#retainAllI(java.lang.Object[]) */ @Override default MapX<K, V> retainAll(final Tuple2<K, V>... values) { return (MapX<K, V>) IterableFilterable.super.retainAll(values); } /* (non-Javadoc) * @see com.oath.cyclops.types.functor.BiTransformable#bipeek(java.util.function.Consumer, java.util.function.Consumer) */ @Override default MapX<K, V> bipeek(final Consumer<? super K> c1, final Consumer<? super V> c2) { return (MapX<K, V>) BiTransformable.super.bipeek(c1, c2); } /* (non-Javadoc) * @see com.oath.cyclops.types.traversable.Traversable#forEachAsync(org.reactivestreams.Subscriber) */ @Override default void subscribe(final Subscriber<? super Tuple2<K, V>> s) { stream().subscribe(s); } /* (non-Javadoc) * @see com.oath.cyclops.types.recoverable.OnEmpty#onEmpty(java.lang.Object) */ @Override default MapX<K, V> onEmpty(final Tuple2<K, V> value) { return fromStream(stream().onEmpty(value)); } /* (non-Javadoc) * @see com.oath.cyclops.types.recoverable.OnEmpty#onEmptyGet(java.util.function.Supplier) */ @Override default MapX<K, V> onEmptyGet(final Supplier<? extends Tuple2<K, V>> supplier) { return fromStream(stream().onEmptyGet(supplier)); } /* (non-Javadoc) * @see com.oath.cyclops.types.recoverable.OnEmptySwitch#onEmptySwitch(java.util.function.Supplier) */ @Override default MapX<K, V> onEmptySwitch(final Supplier<? extends Map<K, V>> supplier) { if (isEmpty()) return MapX.fromMap(supplier.get()); return this; } /** * Convert this MapX to a ListX via the provided transformation function * * @param fn Mapping function to transform each Map entry into a single value * @return ListX of transformed values */ default <T> ListX<T> toListX(final Function<? super Tuple2<? super K,? super V>,? extends T> fn) { return ListX.narrow(stream().map(fn).to(ReactiveConvertableSequence::converter) .listX()); } /** * Convert this MapX to a SetX via the provided transformation function * * @param fn Mapping function to transform each Map entry into a single value * @return SetX of transformed values */ default <T> SetX<T> toSetX(final Function<? super Tuple2<? super K,? super V>,? extends T> fn) { return SetX.narrow(stream().map(fn).to(ReactiveConvertableSequence::converter) .setX()); } /** * Convert this MapX to a SortedSetX via the provided transformation function * * @param fn Mapping function to transform each Map entry into a single value * @return SortedSetX of transformed values */ default <T> SortedSetX<T> toSortedSetX(final Function<? super Tuple2<? super K,? super V>,? extends T> fn) { return SortedSetX.narrow(stream().map(fn).to(ReactiveConvertableSequence::converter) .sortedSetX()); } /** * Convert this MapX to a QueueX via the provided transformation function * * @param fn Mapping function to transform each Map entry into a single value * @return QueueX of transformed values */ default <T> QueueX<T> toQueueX(final Function<? super Tuple2<? super K,? super V>,? extends T> fn) { return QueueX.narrow(stream().map(fn).to(ReactiveConvertableSequence::converter) .queueX()); } /** * Convert this MapX to a DequeX via the provided transformation function * * @param fn Mapping function to transform each Map entry into a single value * @return DequeX of transformed values */ default <T> DequeX<T> toDequeX(final Function<? super Tuple2<? super K,? super V>,? extends T> fn) { return DequeX.narrow(stream().map(fn).to(ReactiveConvertableSequence::converter) .dequeX()); } } ======================= File: cyclops/src/main/java/com/oath/cyclops/internal/stream/operators/RecoverOperator.java ======================= <gh_stars>100-1000 package com.oath.cyclops.internal.stream.operators; import java.util.Iterator; import java.util.function.Function; import java.util.stream.Stream; import com.oath.cyclops.util.ExceptionSoftener; import cyclops.companion.Streams; import lombok.AllArgsConstructor; @AllArgsConstructor public class RecoverOperator<T> { private final Stream<T> stream; private final Class<Throwable> type; private static final Object UNSET = new Object(); public Stream<T> recover(final Function<Throwable,? extends T> fn) { final Iterator<T> it = stream.iterator(); return Streams.stream(new Iterator<T>() { T result = (T) UNSET; @Override public boolean hasNext() { try { return it.hasNext(); } catch (final Throwable t) { if (type.isAssignableFrom(t.getClass())) { result = fn.apply(t); return true; } ExceptionSoftener.throwSoftenedException(t); return false; } } @Override public T next() { if (result!= UNSET) { final T toReturn = result; result = (T) UNSET; return toReturn; } return it.next(); } }); } } ======================= File: cyclops-futurestream/src/test/java/cyclops/futurestream/react/lazy/ToOptionalCompletableFutureTest.java ======================= package cyclops.futurestream.react.lazy; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import java.util.Arrays; import com.oath.cyclops.ReactiveConvertableSequence; import cyclops.futurestream.LazyReact; import org.junit.Test; public class ToOptionalCompletableFutureTest { @Test public void toCompletableFuture(){ assertThat(LazyReact.sequentialBuilder().of(1,2,3,4) .toCompletableFuture() .join(),equalTo(Arrays.asList(1,2,3,4))); } @Test public void toOptional(){ assertThat(LazyReact.sequentialBuilder().of(1,2,3,4).to(ReactiveConvertableSequence::converter) .optional() .get(),equalTo(Arrays.asList(1,2,3,4))); } @Test public void toOptionalEmpty(){ assertFalse(LazyReact.sequentialBuilder().of().to(ReactiveConvertableSequence::converter) .optional().isPresent()); } } ======================= File: cyclops/src/main/java/cyclops/control/Eval.java ======================= <filename>cyclops/src/main/java/cyclops/control/Eval.java package cyclops.control; import com.oath.cyclops.hkt.Higher; import com.oath.cyclops.matching.Deconstruct.Deconstruct1; import com.oath.cyclops.types.MonadicValue; import com.oath.cyclops.types.Zippable; import com.oath.cyclops.types.foldable.To; import com.oath.cyclops.types.reactive.Completable; import com.oath.cyclops.util.box.Mutable; import cyclops.function.*; import com.oath.cyclops.hkt.DataWitness.eval; import cyclops.reactive.ReactiveSeq; import cyclops.reactive.Spouts; import lombok.AllArgsConstructor; import cyclops.data.tuple.*; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import java.util.*; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.*; import java.util.stream.Stream; /** * Represents a computation that can be deferred (always), cached (later) or immediate(now). * Supports tail recursion via transform / flatMap. * Eval are always Lazy even when performed against a Now instance. * Heavily inspired by Cats Eval @link https://github.com/typelevel/cats/blob/master/core/src/main/scala/cats/Eval.scala * * Tail Recursion example * <pre> * {@code * * public void odd(){ System.out.println(even(Eval.now(200000)).getValue()); } public Eval<String> odd(Eval<Integer> n ) { return n.flatMap(x->even(Eval.now(x-1))); } public Eval<String> even(Eval<Integer> n ) { return n.flatMap(x->{ return x<=0? Eval.now("done") : odd(Eval.now(x-1)); }); } * } * </pre> * * @author johnmcclean * * @param <T> Type of value storable in this Eval */ public interface Eval<T> extends To<Eval<T>>,Function0<T>, Deconstruct1<T>, Zippable<T>, MonadicValue<T>, Higher<eval,T>{ default Tuple1<T> unapply(){ return Tuple.tuple(get()); } public static <T,R> Eval<R> tailRec(T initial, Function<? super T,? extends Eval<? extends Either<T, R>>> fn){ return narrowK(fn.apply(initial)).flatMap( eval -> eval.fold(s->tailRec(s,fn), p-> Eval.now(p))); } public static <T> Higher<eval, T> widen(Eval<T> narrow) { return narrow; } static <T> Eval<T> async(final Executor ex, final Supplier<T> s){ return fromFuture(Future.of(s,ex)); } /** * Convert the raw Higher Kinded Type for Evals types into the Eval interface * * @param future HKT encoded list into a OptionalType * @return Eval */ public static <T> Eval<T> narrowK(final Higher<eval, T> future) { return (Eval<T>)future; } /** * Create an Eval instance from a reactive-streams publisher * * <pre> * {@code * Eval<Integer> e = Eval.fromPublisher(Mono.just(10)); * //Eval[10] * } * </pre> * * * @param pub Publisher to create the Eval from * @return Eval created from Publisher */ public static <T> Eval<T> fromPublisher(final Publisher<T> pub) { return fromFuture(Future.fromPublisher(pub)); } /** * Create a reactive CompletableEval * * <pre> * {@code * CompletableEval<Integer,Integer> completable = Eval.eval(); Eval<Integer> mapped = completable.map(i->i*2) .flatMap(i->Eval.later(()->i+1)); completable.complete(5); mapped.printOut(); //11 * } * </pre> * * @param <T> Data input type to the Eval * @return A reactive CompletableEval */ static <T> CompletableEval<T,T> eval(){ Completable.CompletablePublisher<T> c = new Completable.CompletablePublisher<T>(); return new CompletableEval<T, T>(c,fromFuture(Future.fromPublisher(c))); } default ReactiveSeq<T> streamWhile(Predicate<? super T> p){ return ReactiveSeq.generate(this).takeWhile(p); } default ReactiveSeq<T> streamUntil(Predicate<? super T> p){ return ReactiveSeq.generate(this).takeUntil(p); } default ReactiveSeq<T> streamUntil(long time,TimeUnit unit){ return ReactiveSeq.generate(this).take(time,unit); } @Override default ReactiveSeq<T> stream() { return Function0.super.stream(); } @AllArgsConstructor static class CompletableEval<ORG,T2> implements Eval<T2>, Completable<ORG>{ public final CompletablePublisher<ORG> complete; public final Eval<T2> lazy; @Override public boolean isFailed() { return complete.isFailed(); } @Override public boolean isDone() { return complete.isDone(); } @Override public boolean complete(ORG complete) { return this.complete.complete(complete); } @Override public boolean completeExceptionally(Throwable error) { return complete.completeExceptionally(error); } @Override public <T> Eval<T> unit(T unit) { return lazy.unit(unit); } @Override public <R> Eval<R> map(Function<? super T2,? extends R> mapper) { return lazy.map(mapper); } @Override public <R> Eval<R> flatMap(Function<? super T2,? extends MonadicValue<? extends R>> mapper) { return lazy.flatMap(mapper); } @Override public T2 get() { return lazy.get(); } } public static <T> Eval<T> coeval(final Future<Eval<T>> pub) { return new Module.FutureAlways<T>(pub); } public static <T> Eval<T> fromFuture(final Future<T> pub) { return coeval(pub.map(Eval::now)); } /** * Create an Eval instance from an Iterable * * <pre> * {@code * Eval<Integer> e = Eval.fromIterable(Arrays.asList(10)); * //Eval[10] * } * </pre> * @param iterable to create the Eval from * @return Eval created from Publisher */ public static <T> Eval<T> fromIterable(final Iterable<T> iterable) { if(iterable instanceof Eval) return (Eval<T>)iterable; final Iterator<T> it = iterable.iterator(); return Eval.later(() -> it.hasNext()? it.next() : null); } /** * Create an Eval with the value specified * * <pre> * {@code * Eval<Integer> e = Eval.now(10); * //Eval[10] * }</pre> * * @param value of Eval * @return Eval with specified value */ public static <T> Eval<T> now(final T value) { return always(() -> value); } /** * Lazily create an Eval from the specified Supplier. Supplier#getValue will only be called once. Return values of Eval operations will also * be cached (later indicates maybe and caching - characteristics can be changed using flatMap). * * <pre> * {@code * Eval<Integer> e = Eval.later(()->10) * .map(i->i*2); * //Eval[20] - maybe so will not be executed until the value is accessed * }</pre> * * * @param value Supplier to (lazily) populate this Eval * @return Eval with specified value */ public static <T> Eval<T> later(final Supplier<T> value) { return new Module.Later<T>( () -> value == null? null : value.get()); } public static <T> Eval<T> defer(final Supplier<Eval<T>> value) { return new Module.Later<T>( () -> value == null || value.get() == null? null : value.get().get()); } /** * Lazily create an Eval from the specified Supplier. Supplier#getValue will only be every time getValue is called on the resulting Eval. * * <pre> * {@code * Eval<Integer> e = Eval.always(()->10) * .map(i->i*2); * //Eval[20] - maybe so will not be executed until the value is accessed * }</pre> * * * @param value Supplier to (lazily) populate this Eval * @return Eval with specified value */ public static <T> Eval<T> always(final Supplier<T> value) { return new Module.Always<T>( () -> value == null? null : value.get()); } /** * Turn a toX of Evals into a single Eval with a List of values. * * <pre> * {@code * Eval<Seq<Integer>> maybes =Eval.sequence(Seq.of(Eval.now(10),Eval.now(1))); //Eval.now(Seq.of(10,1))); * * } * </pre> * * @param evals Collection of evals to convert into a single eval with a List of values * @return Eval with a list of values */ public static <T> Eval<ReactiveSeq<T>> sequence(final Iterable<? extends Eval<T>> evals) { return sequence(ReactiveSeq.fromIterable(evals)); } /** * Turn a Stream of Evals into a single Eval with a Stream of values. * * <pre> * {@code * Eval<ReactiveSeq<Integer>> maybes =Eval.sequence(Stream.of(Eval.now(10),Eval.now(1))); //Eval.now(ReactiveSeq.of(10,1))); * * } * </pre> * * @param evals Collection of evals to convert into a single eval with a List of values * @return Eval with a list of values */ public static <T> Eval<ReactiveSeq<T>> sequence(final Stream<? extends Eval<T>> evals) { return sequence(ReactiveSeq.fromStream(evals)); } public static <T> Eval<ReactiveSeq<T>> sequence(ReactiveSeq<? extends Eval<T>> stream) { Eval<ReactiveSeq<T>> identity = Eval.now(ReactiveSeq.empty()); BiFunction<Eval<ReactiveSeq<T>>,Eval<T>,Eval<ReactiveSeq<T>>> combineToStream = (acc, next) ->acc.zip(next,(a, b)->a.append(b)); BinaryOperator<Eval<ReactiveSeq<T>>> combineStreams = (a, b)-> a.zip(b,(z1, z2)->z1.appendStream(z2)); return stream.reduce(identity,combineToStream,combineStreams); } public static <T,R> Eval<ReactiveSeq<R>> traverse(Function<? super T,? extends R> fn, ReactiveSeq<Eval<T>> stream) { ReactiveSeq<Eval<R>> s = stream.map(h -> h.map(fn)); return sequence(s); } /** * Sequence and reduce a CollectionX of Evals into an Eval with a reduced value * * <pre> * {@code * Eval<PersistentSetX<Integer>> accumulated = Eval.accumulate(Seq.of(just,Eval.now(1)),Reducers.toPersistentSetX()); //Eval.now(PersistentSetX.of(10,1))) * } * </pre> * * @param evals Collection of Evals to accumulate * @param reducer Reducer to fold nest values into * @return Eval with a value */ public static <T, R> Eval<R> accumulate(final Iterable<Eval<T>> evals, final Reducer<R, T> reducer) { return sequence(evals).map(s -> s.foldMap(reducer)); } /** * Sequence and reduce an Iterable of Evals into an Eval with a reduced value * * <pre> * {@code * Eval<String> evals =Eval.accumulate(Seq.of(just,Eval.later(()->1)),i->""+i,Monoids.stringConcat); //Eval.now("101") * } * </pre> * * * @param evals Collection of Evals to accumulate * @param mapper Funtion to transform Eval contents to type required by Semigroup accumulator * @param reducer Combiner function to applyHKT to converted values * @return Eval with a value */ public static <T, R> Eval<R> accumulate(final Iterable<Eval<T>> evals, final Function<? super T, R> mapper, final Monoid<R> reducer) { return sequence(evals).map(s -> s.map(mapper) .reduce(reducer) ); } public static <T> Eval<T> accumulate(final Monoid<T> reducer, final Iterable<Eval<T>> evals) { return sequence(evals).map(s -> s.reduce(reducer)); } default Trampoline<T> toTrampoline(){ return Trampoline.more(()->Trampoline.done(get())); } @Override default Maybe<T> toMaybe(){ return Maybe.fromEvalNullable(this); } @Override public <T> Eval<T> unit(T unit); @Override default <R> Eval<R> map(Function<? super T,? extends R> mapper){ return flatMap(i->Eval.now(mapper.apply(i))); } @Override <R> Eval<R> flatMap(Function<? super T,? extends MonadicValue<? extends R>> mapper); /* (non-Javadoc) * @see com.oath.cyclops.types.MonadicValue#combineEager(cyclops2.function.Monoid, com.oath.cyclops.types.MonadicValue) */ default Eval<T> combineEager(final Monoid<T> monoid, final MonadicValue<? extends T> v2) { return unit(this.forEach2( t1 -> v2, (t1, t2) -> monoid .apply(t1, t2)).orElseGet(() -> orElseGet(() -> monoid.zero()))); } /* (non-Javadoc) * @see com.oath.cyclops.types.MonadicValue#concatMap(java.util.function.Function) */ @Override default <R> Eval<R> concatMap(Function<? super T,? extends Iterable<? extends R>> mapper) { return (Eval<R>)MonadicValue.super.concatMap(mapper); } /* (non-Javadoc) * @see com.oath.cyclops.types.MonadicValue#flatMapP(java.util.function.Function) */ @Override default <R> Eval<R> mergeMap(Function<? super T,? extends Publisher<? extends R>> mapper) { return this.flatMap(a -> { final Publisher<? extends R> publisher = mapper.apply(a); return Eval.fromPublisher(publisher); }); } /* (non-Javadoc) * @see java.util.function.Supplier#getValue() */ @Override public T get(); /* (non-Javadoc) * @see com.oath.cyclops.types.Filters#ofType(java.lang.Class) */ @Override default <U> Maybe<U> ofType(final Class<? extends U> type) { return (Maybe<U>) MonadicValue.super.ofType(type); } /* (non-Javadoc) * @see com.oath.cyclops.types.Filters#filterNot(java.util.function.Predicate) */ @Override default Maybe<T> filterNot(final Predicate<? super T> fn) { return (Maybe<T>) MonadicValue.super.filterNot(fn); } /* (non-Javadoc) * @see com.oath.cyclops.types.Filters#notNull() */ @Override default Maybe<T> notNull() { return (Maybe<T>) MonadicValue.super.notNull(); } /* (non-Javadoc) * @see com.oath.cyclops.types.Filters#filter(java.util.function.Predicate) */ @Override default Maybe<T> filter(final Predicate<? super T> pred) { return toMaybe().filter(pred); } /* (non-Javadoc) * @see com.oath.cyclops.lambda.monads.Functor#peek(java.util.function.Consumer) */ @Override default Eval<T> peek(final Consumer<? super T> c) { return (Eval<T>) MonadicValue.super.peek(c); } /* (non-Javadoc) * @see com.oath.cyclops.types.foldable.Convertable#visit(java.util.function.Function, java.util.function.Supplier) */ @Override default <R> R fold(final Function<? super T,? extends R> present, final Supplier<? extends R> absent) { final T value = get(); if (value!= null) return present.apply(value); return absent.get(); } /** * Narrow covariant type parameter * * @param broad Eval with covariant type parameter * @return Narrowed Eval */ static <R> Eval<R> narrow(final Eval<? extends R> broad) { return (Eval<R>) broad; } @Override default <T2, R> Eval<R> zip(final Iterable<? extends T2> app, final BiFunction<? super T,? super T2,? extends R> fn) { return fromIterable(ReactiveSeq.fromIterable(this).zip(app,fn)); } @Override default <T2, R> Eval<R> zip(final BiFunction<? super T,? super T2,? extends R> fn, final Publisher<? extends T2> app) { return Eval.fromPublisher(Spouts.from(this).zip(fn,app)); } /* (non-Javadoc) * @see com.oath.cyclops.types.Zippable#zip(java.lang.Iterable) */ @Override default <U> Eval<Tuple2<T, U>> zip(final Iterable<? extends U> other) { return (Eval) Zippable.super.zip(other); } @Override default <U> Eval<Tuple2<T, U>> zipWithPublisher(final Publisher<? extends U> other) { return (Eval)Zippable.super.zipWithPublisher(other); } @Override default <S, U> Eval<Tuple3<T, S, U>> zip3(final Iterable<? extends S> second, final Iterable<? extends U> third) { return (Eval)Zippable.super.zip3(second,third); } @Override default <S, U, R> Eval<R> zip3(final Iterable<? extends S> second, final Iterable<? extends U> third, final Function3<? super T,? super S,? super U,? extends R> fn3) { return (Eval<R>)Zippable.super.zip3(second,third,fn3); } @Override default <T2, T3, T4> Eval<Tuple4<T, T2, T3, T4>> zip4(final Iterable<? extends T2> second, final Iterable<? extends T3> third, final Iterable<? extends T4> fourth) { return (Eval)Zippable.super.zip4(second,third,fourth); } @Override default <T2, T3, T4, R> Eval<R> zip4(final Iterable<? extends T2> second, final Iterable<? extends T3> third, final Iterable<? extends T4> fourth, final Function4<? super T,? super T2,? super T3,? super T4,? extends R> fn) { return (Eval<R>)Zippable.super.zip4(second,third,fourth,fn); } /* (non-Javadoc) * @see com.oath.cyclops.types.MonadicValue#forEach4(java.util.function.Function, java.util.function.BiFunction, com.oath.cyclops.util.function.TriFunction, com.oath.cyclops.util.function.QuadFunction) */ @Override default <T2, R1, R2, R3, R> Eval<R> forEach4(Function<? super T,? extends MonadicValue<R1>> value1, BiFunction<? super T,? super R1,? extends MonadicValue<R2>> value2, Function3<? super T,? super R1,? super R2,? extends MonadicValue<R3>> value3, Function4<? super T,? super R1,? super R2,? super R3,? extends R> yieldingFunction) { return (Eval<R>)MonadicValue.super.forEach4(value1, value2, value3, yieldingFunction); } /* (non-Javadoc) * @see com.oath.cyclops.types.MonadicValue#forEach4(java.util.function.Function, java.util.function.BiFunction, com.oath.cyclops.util.function.TriFunction, com.oath.cyclops.util.function.QuadFunction, com.oath.cyclops.util.function.QuadFunction) */ @Override default <T2, R1, R2, R3, R> Eval<R> forEach4(Function<? super T,? extends MonadicValue<R1>> value1, BiFunction<? super T,? super R1,? extends MonadicValue<R2>> value2, Function3<? super T,? super R1,? super R2,? extends MonadicValue<R3>> value3, Function4<? super T,? super R1,? super R2,? super R3, Boolean> filterFunction, Function4<? super T,? super R1,? super R2,? super R3,? extends R> yieldingFunction) { return (Eval<R>)MonadicValue.super.forEach4(value1, value2, value3, filterFunction, yieldingFunction); } /* (non-Javadoc) * @see com.oath.cyclops.types.MonadicValue#forEach3(java.util.function.Function, java.util.function.BiFunction, com.oath.cyclops.util.function.TriFunction) */ @Override default <T2, R1, R2, R> Eval<R> forEach3(Function<? super T,? extends MonadicValue<R1>> value1, BiFunction<? super T,? super R1,? extends MonadicValue<R2>> value2, Function3<? super T,? super R1,? super R2,? extends R> yieldingFunction) { return (Eval<R>)MonadicValue.super.forEach3(value1, value2, yieldingFunction); } /* (non-Javadoc) * @see com.oath.cyclops.types.MonadicValue#forEach3(java.util.function.Function, java.util.function.BiFunction, com.oath.cyclops.util.function.TriFunction, com.oath.cyclops.util.function.TriFunction) */ @Override default <T2, R1, R2, R> Eval<R> forEach3(Function<? super T,? extends MonadicValue<R1>> value1, BiFunction<? super T,? super R1,? extends MonadicValue<R2>> value2, Function3<? super T,? super R1,? super R2, Boolean> filterFunction, Function3<? super T,? super R1,? super R2,? extends R> yieldingFunction) { return (Eval<R>)MonadicValue.super.forEach3(value1, value2, filterFunction, yieldingFunction); } /* (non-Javadoc) * @see com.oath.cyclops.types.MonadicValue#forEach2(java.util.function.Function, java.util.function.BiFunction) */ @Override default <R1, R> Eval<R> forEach2(Function<? super T,? extends MonadicValue<R1>> value1, BiFunction<? super T,? super R1,? extends R> yieldingFunction) { return (Eval<R>)MonadicValue.super.forEach2(value1, yieldingFunction); } /* (non-Javadoc) * @see com.oath.cyclops.types.MonadicValue#forEach2(java.util.function.Function, java.util.function.BiFunction, java.util.function.BiFunction) */ @Override default <R1, R> Eval<R> forEach2(Function<? super T,? extends MonadicValue<R1>> value1, BiFunction<? super T,? super R1, Boolean> filterFunction, BiFunction<? super T,? super R1,? extends R> yieldingFunction) { return (Eval<R>)MonadicValue.super.forEach2(value1, filterFunction, yieldingFunction); } default <R> Eval<R> emptyUnit(){ return Eval.now(null); } default Future<T> toFuture(){ return Future.of(this); } static class Module { static <T> Eval<T> asEval(final MonadicValue<T> value) { if (value instanceof Eval) return (Eval<T>) value; return Eval.now(value.orElse(null)); } public static class Later<T> implements Eval<T> { private final Supplier<T> memo; private final Trampoline<T> evaluate; Later(Rec<?, T> in) { memo = Memoize.memoizeSupplier(()->in.toTrampoline().get()); evaluate = in.toTrampoline(); } Later(Supplier<T> s){ memo = Memoize.memoizeSupplier(s); evaluate = Trampoline.more(()->Trampoline.done(memo.get())); } @Override public <R> Eval<R> map(Function<? super T,? extends R> mapper) { return flatMap(i->Eval.later(()-> mapper.apply(i))); } @Override public <R> Eval<R> flatMap(final Function<? super T,? extends MonadicValue<? extends R>> mapper) { return new Later<R>( new Rec<T, R>(this, Memoize.memoizeFunction(mapper))); } @Override public Trampoline<T> toTrampoline(){ return evaluate; } @Override public T get() { return memo.get(); } @Override public <T> Eval<T> unit(final T unit) { return Eval.later(() -> unit); } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { return get().hashCode(); } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(final Object obj) { if (!(obj instanceof Eval)) return false; return Objects.equals(get(), ((Eval) obj).get()); } @Override public String toString() { return mkString(); } } public static class Always<T> implements Eval<T> { private final Trampoline<T> evaluate; Always(Rec<?, T> in) { evaluate = in.toTrampoline(); } Always(Supplier<T> in) { evaluate = Trampoline.more(()->Trampoline.done(in.get())); } public Maybe<T> filter(Predicate<? super T> predicate ){ return Maybe.fromEval(this).filter(predicate); } @Override public <R> Eval<R> flatMap(final Function<? super T,? extends MonadicValue<? extends R>> mapper) { Rec<T, R> rec = new Rec<T, R>(this, mapper); return new Always<R>( rec); } @Override public T get() { return evaluate.get(); } @Override public Trampoline<T> toTrampoline(){ return evaluate; } @Override public <T> Eval<T> unit(final T unit) { return Eval.always(() -> unit); } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { return get().hashCode(); } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(final Object obj) { if (!(obj instanceof Eval)) return false; return Objects.equals(get(), ((Eval) obj).get()); } @Override public String toString() { return mkString(); } } public static class FutureAlways<T> implements Eval<T> { final Future<Eval<T>> input; FutureAlways( Future<Eval<T>> input) { this.input= input; } public void forEach(Consumer<? super T> cons){ input.peek(e->e.forEach(cons)); } @Override public <R> Eval<R> map(final Function<? super T,? extends R> mapper) { return new FutureAlways<R>(input.map(e->e.map(mapper))); } @Override public <R> Eval<R> flatMap(final Function<? super T,? extends MonadicValue<? extends R>> mapper) { return new FutureAlways<R>(input.map(e->e.flatMap(mapper))); } @Override public ReactiveSeq<T> iterate(UnaryOperator<T> fn) { return Spouts.from(input).map(Eval::get).flatMap(i->Spouts.iterate(i,fn)); } @Override public ReactiveSeq<T> generate() { return Spouts.from(input).map(Eval::get).flatMap(i->Spouts.generate(()->i)); } /** * @return This convertable converted to a Future */ @Override public Future<T> toFuture() { return input.map(Eval::get); } /** * This convertable converted to a Future asyncrhonously using the supplied Executor * * @param ex Executor to execute the conversion on * @return This convertable converted to a Future asyncrhonously */ @Override public Future<T> future(final Executor ex) { return toFuture(); } @Override public final void subscribe(final Subscriber<? super T> sub) { Mutable<Future<Eval<T>>> future = Mutable.of(input); sub.onSubscribe(new Subscription() { AtomicBoolean running = new AtomicBoolean( true); AtomicBoolean cancelled = new AtomicBoolean(false); @Override public void request(final long n) { if (n < 1) { sub.onError(new IllegalArgumentException( "3.9 While the Subscription is not cancelled, Subscription.request(long n) MUST throw a java.lang.IllegalArgumentException if the argument is <= 0.")); } if (!running.compareAndSet(true, false)) { return; } future.mutate(f -> f.peek(e->{ e.forEach(v->{ sub.onNext(v); }); }) .recover(t -> { sub.onError(t); return null; }) .peek(i -> sub.onComplete())); } @Override public void cancel() { cancelled.set(true); future.get().cancel(); } }); } @Override public T get() { Eval<T> eval = input.fold(i->i,()->null); return eval.get(); } @Override public ReactiveSeq<T> stream() { return Spouts.from(this); } @Override public <T> Eval<T> unit(final T unit) { return Eval.always(() -> unit); } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { return get().hashCode(); } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(final Object obj) { if (!(obj instanceof Eval)) return false; return Objects.equals(get(), ((Eval) obj).get()); } @Override public String toString() { return mkString(); } } @AllArgsConstructor private static class Rec<T,R> { private final Eval<T> eval; private final Function<? super T,? extends MonadicValue<? extends R>> fn; public Trampoline<R> toTrampoline() { Trampoline<? extends R> x = Trampoline.more(() -> { Trampoline<? extends R> t = eval.toTrampoline().flatMap(v -> { Trampoline<? extends R> t2 = Eval.fromIterable(fn.apply(v)).toTrampoline(); return t2; }); return t; }); return Trampoline.narrow(x); } } } public static class Comprehensions { public static <T,F,R1, R2, R3,R4,R5,R6,R7> Eval<R7> forEach(Eval<T> eval, Function<? super T,? extends Eval<R1>> value2, Function<? super Tuple2<? super T,? super R1>,? extends Eval<R2>> value3, Function<? super Tuple3<? super T,? super R1,? super R2>,? extends Eval<R3>> value4, Function<? super Tuple4<? super T,? super R1,? super R2,? super R3>,? extends Eval<R4>> value5, Function<? super Tuple5<T,? super R1,? super R2,? super R3,? super R4>,? extends Eval<R5>> value6, Function<? super Tuple6<T,? super R1,? super R2,? super R3,? super R4,? super R5>,? extends Eval<R6>> value7, Function<? super Tuple7<T,? super R1,? super R2,? super R3,? super R4,? super R5,? super R6>,? extends Eval<R7>> value8 ) { return eval.flatMap(in -> { Eval<R1> a = value2.apply(in); return a.flatMap(ina -> { Eval<R2> b = value3.apply(Tuple.tuple(in,ina)); return b.flatMap(inb -> { Eval<R3> c = value4.apply(Tuple.tuple(in,ina,inb)); return c.flatMap(inc->{ Eval<R4> d = value5.apply(Tuple.tuple(in,ina,inb,inc)); return d.flatMap(ind->{ Eval<R5> e = value6.apply(Tuple.tuple(in,ina,inb,inc,ind)); return e.flatMap(ine->{ Eval<R6> f = value7.apply(Tuple.tuple(in,ina,inb,inc,ind,ine)); return f.flatMap(inf->{ Eval<R7> g = value8.apply(Tuple.tuple(in,ina,inb,inc,ind,ine,inf)); return g; }); }); }); }); }); }); }); } public static <T,F,R1, R2, R3,R4,R5,R6> Eval<R6> forEach(Eval<T> eval, Function<? super T,? extends Eval<R1>> value2, Function<? super Tuple2<? super T,? super R1>,? extends Eval<R2>> value3, Function<? super Tuple3<? super T,? super R1,? super R2>,? extends Eval<R3>> value4, Function<? super Tuple4<? super T,? super R1,? super R2,? super R3>,? extends Eval<R4>> value5, Function<? super Tuple5<T,? super R1,? super R2,? super R3,? super R4>,? extends Eval<R5>> value6, Function<? super Tuple6<T,? super R1,? super R2,? super R3,? super R4,? super R5>,? extends Eval<R6>> value7 ) { return eval.flatMap(in -> { Eval<R1> a = value2.apply(in); return a.flatMap(ina -> { Eval<R2> b = value3.apply(Tuple.tuple(in,ina)); return b.flatMap(inb -> { Eval<R3> c = value4.apply(Tuple.tuple(in,ina,inb)); return c.flatMap(inc->{ Eval<R4> d = value5.apply(Tuple.tuple(in,ina,inb,inc)); return d.flatMap(ind->{ Eval<R5> e = value6.apply(Tuple.tuple(in,ina,inb,inc,ind)); return e.flatMap(ine->{ Eval<R6> f = value7.apply(Tuple.tuple(in,ina,inb,inc,ind,ine)); return f; }); }); }); }); }); }); } public static <T,F,R1, R2, R3,R4,R5> Eval<R5> forEach(Eval<T> eval, Function<? super T,? extends Eval<R1>> value2, Function<? super Tuple2<? super T,? super R1>,? extends Eval<R2>> value3, Function<? super Tuple3<? super T,? super R1,? super R2>,? extends Eval<R3>> value4, Function<? super Tuple4<? super T,? super R1,? super R2,? super R3>,? extends Eval<R4>> value5, Function<? super Tuple5<T,? super R1,? super R2,? super R3,? super R4>,? extends Eval<R5>> value6 ) { return eval.flatMap(in -> { Eval<R1> a = value2.apply(in); return a.flatMap(ina -> { Eval<R2> b = value3.apply(Tuple.tuple(in,ina)); return b.flatMap(inb -> { Eval<R3> c = value4.apply(Tuple.tuple(in,ina,inb)); return c.flatMap(inc->{ Eval<R4> d = value5.apply(Tuple.tuple(in,ina,inb,inc)); return d.flatMap(ind->{ Eval<R5> e = value6.apply(Tuple.tuple(in,ina,inb,inc,ind)); return e; }); }); }); }); }); } public static <T,F,R1, R2, R3,R4> Eval<R4> forEach(Eval<T> eval, Function<? super T,? extends Eval<R1>> value2, Function<? super Tuple2<? super T,? super R1>,? extends Eval<R2>> value3, Function<? super Tuple3<? super T,? super R1,? super R2>,? extends Eval<R3>> value4, Function<? super Tuple4<? super T,? super R1,? super R2,? super R3>,? extends Eval<R4>> value5 ) { return eval.flatMap(in -> { Eval<R1> a = value2.apply(in); return a.flatMap(ina -> { Eval<R2> b = value3.apply(Tuple.tuple(in,ina)); return b.flatMap(inb -> { Eval<R3> c = value4.apply(Tuple.tuple(in,ina,inb)); return c.flatMap(inc->{ Eval<R4> d = value5.apply(Tuple.tuple(in,ina,inb,inc)); return d; }); }); }); }); } public static <T,F,R1, R2, R3> Eval<R3> forEach(Eval<T> eval, Function<? super T,? extends Eval<R1>> value2, Function<? super Tuple2<? super T,? super R1>,? extends Eval<R2>> value3, Function<? super Tuple3<? super T,? super R1,? super R2>,? extends Eval<R3>> value4 ) { return eval.flatMap(in -> { Eval<R1> a = value2.apply(in); return a.flatMap(ina -> { Eval<R2> b = value3.apply(Tuple.tuple(in,ina)); return b.flatMap(inb -> { Eval<R3> c = value4.apply(Tuple.tuple(in,ina,inb)); return c; }); }); }); } public static <T,F,R1, R2> Eval<R2> forEach(Eval<T> eval, Function<? super T,? extends Eval<R1>> value2, Function<? super Tuple2<? super T,? super R1>,? extends Eval<R2>> value3 ) { return eval.flatMap(in -> { Eval<R1> a = value2.apply(in); return a.flatMap(ina -> { Eval<R2> b = value3.apply(Tuple.tuple(in,ina)); return b; }); }); } public static <T,F,R1> Eval<R1> forEach(Eval<T> eval, Function<? super T,? extends Eval<R1>> value2 ) { return eval.flatMap(in -> { Eval<R1> a = value2.apply(in); return a; }); } } } ======================= File: cyclops/src/main/java/com/oath/cyclops/async/QueueFactories.java ======================= package com.oath.cyclops.async; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.SynchronousQueue; import com.oath.cyclops.async.adapters.Queue; import com.oath.cyclops.async.adapters.QueueFactory; import org.agrona.concurrent.ManyToOneConcurrentArrayQueue; import org.agrona.concurrent.OneToOneConcurrentArrayQueue; import com.oath.cyclops.async.wait.NoWaitRetry; import com.oath.cyclops.async.wait.WaitStrategy; /** * Methods for generating QueueFactories for plumbing Streams together * * * <pre> * {@code * Queue<String> transferQueue = QueueFactories.<String>boundedQueue(4) .build(); new LazyReact(Executors.newFixedThreadPool(4)).generate(()->"data") .map(d->"emitted on " + Thread.currentThread().getId()) .peek(System.out::println) .peek(d->transferQueue.offer(d)) .run(); transferQueue.stream() .map(e->"Consumed on " + Thread.currentThread().getId()) .futureOperations(Executors.newFixedThreadPool(1)) .forEach(System.out::println); * * * } * </pre> * * @author johnmcclean * */ public class QueueFactories { /** * Create a QueueFactory for boundedQueues where bound is determined by the provided queueSize parameter * Generated Queues will be backed by a LinkedBlockingQueue * * <pre> * {@code * Queue<String> transferQueue = QueueFactories.<String>boundedQueue(4) .build(); new LazyReact(Executors.newFixedThreadPool(4)).generate(()->"data") .map(d->"emitted on " + Thread.currentThread().getId()) .peek(System.out::println) .peek(d->transferQueue.offer(d)) .run(); transferQueue.stream() .map(e->"Consumed on " + Thread.currentThread().getId()) .futureOperations(Executors.newFixedThreadPool(1)) .forEach(System.out::println); * * } * </pre> * * @param queueSize Max queue size * @return QueueFactory for bounded Queues backed by a LinkedBlockingQueue */ public static <T> QueueFactory<T> boundedQueue(final int queueSize) { return () -> new Queue<T>( new LinkedBlockingQueue<>( queueSize)); } /** * <pre> * {@code * ReactiveSeq.of(1,2,3) .flatMapP(i->ReactiveSeq.range(i,1500),1000,QueueFactories.unboundedQueue()) .listX() * } * </pre> * * @return A QueueFactory for unbounded Queues backed by a LinkedBlockingQueue */ public static <T> QueueFactory<T> unboundedQueue() { return () -> new Queue<T>(); } /** * Creates an async.Queue backed by a JDK Wait Free unbounded ConcurrentLinkedQueue * Wait strategy used is NoWaitRetry by default for both Consumers and Producers * (both Consumers and Producers will repeatedly retry until successful). Use * withConsumerWaitStrategy &amp; withProducerWaitStrategy methods on the returned queue to change the * wait strategy * <pre> * {@code * queue.withConsumerWaitStrategy(new DirectWaitStrategy()) * .withProducerWaitStrategy(new YieldWait()); * }</pre> * * * @return Factory for unbounded wait free queue backed by ConcurrentLinkedQueue */ public static <T> QueueFactory<T> unboundedNonBlockingQueue() { return () -> new Queue<T>( new ConcurrentLinkedQueue<>(), new NoWaitRetry<>(), new NoWaitRetry<>()); } /** * Creates an async.Queue backed by a JDK Wait Free unbounded ConcurrentLinkedQueue * The provided WaitStrategy is used to determine behaviour of both producers and consumers when the Queue is full (producer) * or zero (consumer). {@see WaitStrategy#spinWait(), @see WaitStrategy#exponentialBackOff(), @see WaitStrategy#noWaitRetry() } * * @param strategy Strategy to be employed by producers when Queue is full, or consumers when Queue is zero * @return Factory for unbounded wait free queue backed by ConcurrentLinkedQueue */ public static <T> QueueFactory<T> unboundedNonBlockingQueue(final WaitStrategy<T> strategy) { return () -> new Queue<T>( new ConcurrentLinkedQueue<>(), strategy, strategy); } /** * Creates an async.Queue backed by an Agrona ManyToOneConcurrentArrayQueue bounded by specified queueSize * Wait strategy used is NoWaitRetry by default for both Consumers and Producers * (both Consumers and Producers will repeatedly retry until successful). Use * withConsumerWaitStrategy &amp; withProducerWaitStrategy methods on the returned queue to change the * wait strategy * <pre> * {@code * queue.withConsumerWaitStrategy(new DirectWaitStrategy()) * .withProducerWaitStrategy(new YieldWait()); * }</pre> * * @param queueSize upper bound for Queue * @return bounded wait free Queue Factory backed by an Agrona ManyToOneConcurrentArrayQueue */ public static <T> QueueFactory<T> boundedNonBlockingQueue(final int queueSize) { return () -> new Queue<T>( new ManyToOneConcurrentArrayQueue<>( queueSize), new NoWaitRetry<>(), new NoWaitRetry<>()); } /** * Generate QueueFactory for bounded non blocking queues. Max queue size is determined by the input parameter. * The provided WaitStrategy is used to determine behaviour of both producers and consumers when the Queue is full (producer) * or zero (consumer). {@see WaitStrategy#spinWait(), @see WaitStrategy#exponentialBackOff(), @see WaitStrategy#noWaitRetry() } * * @param queueSize Max Queue size * @param strategy Strategy to be employed by producers when Queue is full, or consumers when Queue is zero * @return bounded wait free Queue Factory backed by an Agrona ManyToOneConcurrentArrayQueue */ public static <T> QueueFactory<T> boundedNonBlockingQueue(final int queueSize, final WaitStrategy<T> strategy) { return () -> new Queue<T>( new ManyToOneConcurrentArrayQueue<>( queueSize), strategy, strategy); } /** * Creates an async.Queue backed by an Agrona OneToOneConcurrentArrayQueue bounded by specified queueSize * Wait strategy used is NoWaitRetry by default for both Consumers and Producers * (both Consumers and Producers will repeatedly retry until successful). Use * withConsumerWaitStrategy &amp; withProducerWaitStrategy methods on the returned queue to change the * wait strategy * <pre> * {@code * queue.withConsumerWaitStrategy(new DirectWaitStrategy()) * .withProducerWaitStrategy(new YieldWait()); * }</pre> * * @param queueSize * @return */ public static <T> QueueFactory<T> singleWriterboundedNonBlockingQueue(final int queueSize) { return () -> new Queue<T>( new OneToOneConcurrentArrayQueue<>( queueSize), new NoWaitRetry<>(), new NoWaitRetry<>()); } /** * Generate QueueFactory for bounded non blocking queues. Max queue size is determined by the input parameter. * The provided WaitStrategy is used to determine behaviour of both producers and consumers when the Queue is full (producer) * or zero (consumer). {@see WaitStrategy#spinWait(), @see WaitStrategy#exponentialBackOff(), @see WaitStrategy#noWaitRetry() } * * @param queueSize Max Queue size * @param strategy Strategy to be employed by producers when Queue is full, or consumers when Queue is zero * @return bounded wait free Queue Factory backed by an Agrona OneToOneConcurrentArrayQueue */ public static <T> QueueFactory<T> singleWriterboundedNonBlockingQueue(final int queueSize, final WaitStrategy<T> strategy) { return () -> new Queue<T>( new OneToOneConcurrentArrayQueue<>( queueSize), strategy, strategy); } /** * @return async.Queue backed by a Synchronous Queue */ public static <T> QueueFactory<T> synchronousQueue() { return () -> new Queue<T>( new SynchronousQueue<>()); } } ======================= File: cyclops-pure/src/main/java/cyclops/typeclasses/monad/Traverse.java ======================= <filename>cyclops-pure/src/main/java/cyclops/typeclasses/monad/Traverse.java package cyclops.typeclasses.monad; import com.oath.cyclops.hkt.Higher; import cyclops.data.LazySeq; import cyclops.control.Constant; import cyclops.control.Maybe; import cyclops.control.State; import cyclops.function.Monoid; import cyclops.instances.control.ConstantInstances; import cyclops.instances.control.StateInstances; import cyclops.typeclasses.foldable.Foldable; import cyclops.data.tuple.Tuple; import cyclops.data.tuple.Tuple2; import java.util.Iterator; import java.util.function.BiFunction; import java.util.function.Function; import static cyclops.control.State.state; import static cyclops.data.tuple.Tuple.tuple; //HighJ Traverse, ScalaZ Traverse and Cats Traverse Influences public interface Traverse<CRE> extends Applicative<CRE>{ <C2,T,R> Higher<C2, Higher<CRE, R>> traverseA(Applicative<C2> applicative, Function<? super T,? extends Higher<C2, R>> fn, Higher<CRE, T> ds); <C2,T> Higher<C2, Higher<CRE, T>> sequenceA(Applicative<C2> applicative, Higher<CRE, Higher<C2, T>> ds); default <C2, T, R> Higher<C2, Higher<CRE, R>> flatTraverse(Applicative<C2> applicative, Monad<CRE> monad, Higher<CRE, T> fa, Function<? super T,? extends Higher<C2, Higher<CRE, R>>>f) { return applicative.map_(traverseA(applicative,f,fa), it->monad.flatten(it)); } default <C2, T> Higher<C2, Higher<CRE, T>> flatSequence(Applicative<C2> applicative, Monad<CRE> monad,Higher<CRE,Higher<C2,Higher<CRE,T>>> fgfa) { return applicative.map(i -> monad.flatMap(Function.identity(), i), sequenceA(applicative, fgfa)); } //traverse with a State, State has an inbuilt trampoline in cyclops-react default <S,T,R> State<S,Higher<CRE,R>> traverseS(Function<? super T,? extends State<S,R>> fn,Higher<CRE, T> ds){ return State.narrowK(traverseA(StateInstances.applicative(), fn, ds)); } default <S,T,R> Tuple2<S, Higher<CRE, R>> runTraverseS(Function<? super T,? extends State<S,R>> fn,Higher<CRE, T> ds, S val) { return traverseS(fn, ds).run(val); } //based on ScalaZ mapAccumL default <S,T,R> Tuple2<S, Higher<CRE, R>> mapAccumL (BiFunction<? super S,? super T,? extends Tuple2<S,R>> f,Higher<CRE, T> ds,S z) { return runTraverseS(a-> { return State.<S>get().forEach2(s1->{ Tuple2<S, R> t2 = f.apply(s1, a); return State.state(__->t2); },(s1,b)->b); },ds, z); } default <T> Higher<CRE,T> reverse(Higher<CRE, T> ds){ Tuple2<LazySeq<T>, Higher<CRE, T>> t2 = mapAccumL((t, h)-> tuple(t.plus(h),h),ds, LazySeq.empty()); return runTraverseS(t -> State.<LazySeq<T>>get() .forEach2(e -> State.put(e.tailOrElse(LazySeq.empty())), (a, b) -> a.headOrElse(null)) , t2._2(), t2._1())._2(); } default <T, R> R foldMap(Monoid<R> mb, final Function<? super T,? extends R> fn, Higher<CRE, T> ds) { return Constant.narrowK(traverseA(ConstantInstances.applicative(mb), a -> Constant.of(fn.apply(a)), ds)).get(); } default <T,R> Higher<CRE,R> mapWithIndex(BiFunction<? super T,Long,? extends R> f, Higher<CRE, T> ds) { State<Long, Higher<CRE, R>> st = State.narrowK(traverseA(StateInstances.applicative(), a -> state((Long s) -> tuple(s + 1, f.apply(a, s))), ds)); return st.run(0l)._2(); } default <T,C2,T2,R> Higher<CRE,R> zipWith(Foldable<C2> foldable, BiFunction<? super T,? super Maybe<T2>,? extends R> f, Higher<CRE, T> ds, Higher<C2, T2> ds2) { Iterator<T2> list =foldable.seq(ds2) .iterator(); State<Maybe<T2>, Higher<CRE, R>> st = State.narrowK(traverseA(StateInstances.applicative(), a -> { State<Maybe<T2>,R> xz = state((Maybe<T2> s) -> tuple(list.hasNext()? Maybe.just(list.next()) : Maybe.nothing(), f.apply(a, s))); return xz; }, ds)); Maybe<T2> opt = list.hasNext()? Maybe.of(list.next()) : Maybe.nothing(); return st.run(opt)._2(); } default <T,R> Higher<CRE,Tuple2<T,Long>> zipWithIndex(Higher<CRE, T> ds) { return mapWithIndex(Tuple::tuple, ds); } } ======================= File: cyclops/src/test/java/cyclops/control/trampoline/MaybeTrampolineTest.java ======================= package cyclops.control.trampoline; import cyclops.control.Eval; import cyclops.control.Maybe; import cyclops.data.tuple.Tuple2; import cyclops.data.tuple.Tuple3; import org.junit.Test; import static cyclops.control.Eval.now; import static cyclops.control.Maybe.just; import static cyclops.data.tuple.Tuple.tuple; public class MaybeTrampolineTest { @Test public void fib() { fibonacci(just(tuple(100_000, 1l, 0l))).toTrampoline(); System.out.println(fibonacci(just(tuple(100_000, 1l, 0l)))); } @Test public void gcdTest(){ System.out.println(gcd(now(100), now(10000))); } public Maybe<Long> fibonacci(Maybe<Tuple3<Integer, Long, Long>> fib) { return fib.flatMap(t -> t._1() == 0? just(t._3()) : fibonacci(just(tuple(t._1() - 1, t._2() + t._3(), t._2())))); } @Test public void concurrent(){ Maybe<Long> fib = fibonacci(just(tuple(100_000, 1l, 0l))); Eval<Integer> gcd = gcd(now(100), now(10000)); Tuple2<Maybe<Long>, Integer> res = fib.toTrampoline() .zip(gcd.toTrampoline()).get(); System.out.println("Result is " + res); } public Eval<Integer> gcd(Eval<Integer> ea, Eval<Integer> eb){ return eb.flatMap(b->ea.flatMap(a->b==0?ea :gcd(eb, now(a%b)))); } @Test public void bounce() { even(just(200000)).toTrampoline().bounce(); } @Test public void odd(){ System.out.println(even(just(200000)).toTrampoline() .zip(odd1(just(200000)).toTrampoline()).get()); //use zip to interleave execution of even and odd algorithms! even(just(200000)) .toTrampoline() .zip(odd1(just(200000)) .toTrampoline()).get(); } @Test public void interleave(){ //use zip to interleave execution of even and odd algorithms! even(just(200000)) .toTrampoline() .zip(odd1(just(200000)) .toTrampoline()).get(); } public Maybe<String> odd(Maybe<Integer> n ) { System.out.println("A"); return n.flatMap(x->even(just(x-1))); } public Maybe<String> even(Maybe<Integer> n ) { return n.flatMap(x->{ return x<=0? just("done") : odd(just(x-1)); }); } public Maybe<String> odd1(Maybe<Integer> n ) { System.out.println("B"); return n.flatMap(x->even1(just(x-1))); } public Maybe<String> even1(Maybe<Integer> n ) { return n.flatMap(x->{ return x<=0? just("done") : odd1(just(x-1)); }); } } ======================= File: cyclops-reactor-integration/src/main/java/cyclops/reactive/FluxIO.java ======================= <reponame>zmyer/cyclops-react<filename>cyclops-reactor-integration/src/main/java/cyclops/reactive/FluxIO.java package cyclops.reactive; import cyclops.companion.reactor.Fluxs; import cyclops.control.Future; import cyclops.control.Try; import cyclops.data.Seq; import lombok.AccessLevel; import lombok.AllArgsConstructor; import org.reactivestreams.Publisher; import reactor.core.publisher.Flux; import reactor.core.scheduler.Scheduler; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; @AllArgsConstructor(access = AccessLevel.PRIVATE) public final class FluxIO<T> implements IO<T> { private final Flux<T> flowable; public static <T> IO<T> of(Flux<T> flowable){ return new FluxIO<>(flowable); } public static <T> IO<T> just(T s){ return new FluxIO<T>(Flux.just(s)); } public static <T> IO<T> of(Supplier<? extends T> s){ return new FluxIO<T>(Fluxs.generate(()->s.get())); } public static <T> IO<T> of(Supplier<? extends T> s, Scheduler ex){ Flux<T> x = Fluxs.generate(() -> s.get()); x = x.subscribeOn(ex); return new FluxIO<T>(x); } public static <T> IO<T> fromPublisher(Publisher<T> p){ return new FluxIO<T>(Flux.from(p)); } public static <T,X extends Throwable> IO<Try<T,X>> withCatch(Try.CheckedSupplier<T, X> cf, Class<? extends X>... classes){ return of(()-> Try.withCatch(cf,classes)); } public static <T1,T2,R> IO<R> merge(Publisher<T1> p1, Publisher<T2> p2, BiFunction<? super T1,? super T2,? extends R> fn2){ Flux<T1> s1 = Flux.from(p1); Flux<T2> s2 = Flux.from(p2); return fromPublisher(s1.zipWith(s2,(a,b)->fn2.apply(a,b))); } @Override public <B, R> IO<R> par(IO<B> that, BiFunction<? super T,? super B,? extends R> fn) { return IO.fromPublisher(flowable.zipWith(that,fn)); } @Override public IO<T> race(IO<T> that) { return fromPublisher(Flux.first(Seq.of(publisher(), that.publisher()))); } @Override public <R> IO<R> map(Function<? super T,? extends R> s) { return of(flowable.map(s)); } @Override public <R> IO<R> flatMap(Function<? super T, IO<? extends R>> s) { return of(flowable.flatMap(s)); } @Override public void forEach(Consumer<? super T> consumerElement, Consumer<? super Throwable> consumerError, Runnable onComplete) { flowable.subscribe(consumerElement,consumerError,onComplete); } @Override public Future<T> future() { return Future.fromPublisher(flowable); } @Override public Publisher<T> publisher() { return flowable; } @Override public ReactiveSeq<T> stream() { return Spouts.from(flowable); } } ======================= File: cyclops-rxjava2-integration/src/main/java/cyclops/monads/MaybeAnyM.java ======================= package cyclops.monads; import com.oath.cyclops.anym.AnyMValue; import cyclops.monads.Rx2Witness.maybe; import cyclops.monads.transformers.rx2.MaybeT; import io.reactivex.Maybe; public interface MaybeAnyM { public static <W1 extends WitnessType<W1>,T> XorM<W1,maybe,T> xorM(Maybe<T> type){ return XorM.right(anyM(type)); } public static <T> Maybe<T> raw(AnyM<maybe,T> anyM){ return Rx2Witness.maybe(anyM); } public static <W extends WitnessType<W>,T> MaybeT<W,T> liftM(AnyM<W,Maybe<T>> nested){ return MaybeT.of(nested); } /** * Construct an AnyM type from a Maybe. This allows the Maybe to be manipulated according to a standard interface * along with a vast array of other Java Monad implementations * * <pre> * {@code * * AnyMSeq<Integer> maybe = Fluxs.anyM(Maybe.just(1,2,3)); * AnyMSeq<Integer> transformedMaybe = myGenericOperation(maybe); * * public AnyMSeq<Integer> myGenericOperation(AnyMSeq<Integer> monad); * } * </pre> * * @param maybe To wrap inside an AnyM * @return AnyMSeq wrapping a Maybe */ public static <T> AnyMValue<maybe,T> anyM(Maybe<T> maybe) { return AnyM.ofValue(maybe, Rx2Witness.maybe.INSTANCE); } } ======================= File: cyclops-anym/src/main/java/cyclops/monads/AnyMs.java ======================= <reponame>zmyer/cyclops-react<filename>cyclops-anym/src/main/java/cyclops/monads/AnyMs.java<gh_stars>100-1000 package cyclops.monads; import com.oath.cyclops.anym.AnyMSeq; import com.oath.cyclops.anym.AnyMValue; import cyclops.control.*; import cyclops.monads.transformers.jdk.CompletableFutureT; import cyclops.monads.transformers.jdk.OptionalT; import cyclops.reactive.collections.immutable.LinkedListX; import cyclops.reactive.collections.immutable.VectorX; import cyclops.reactive.collections.mutable.ListX; import cyclops.companion.Functions; import cyclops.companion.Streams; import cyclops.function.Function1; import cyclops.monads.transformers.*; import cyclops.reactive.ReactiveSeq; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.function.BiFunction; import java.util.function.Function; import java.util.stream.Stream; public interface AnyMs { /** * KleisliM arrow : A function that takes an input value t and embeds it inside a monadic context. * arrowM makes use of Witness Types to simulate higher-kinded types, and wraps the new monadic type * inside an AnyM. AnyM makes use of sub-type polymorphism (Object Orientd inheritance) to define monadic * arrow (transform / flatMap etc) on the returned Object (for parametric polymorphism use {@link Functions#arrow} * * @param w WitnessType Object: defines the returned monad type (e.g. see {@link Witness.stream} for HKT encoding for Streams) * @param <T> Value type to be embedded inside a monad * @param <W> The type of the WitnessType (Witness.stream, Witness.Future, Witness.list and so on) * @return A function that can embed a value inisde a Monad */ public static <T,W extends WitnessType<W>> Function1<? super T,? extends AnyM<W,T>> arrowM(W w){ return t-> w.adapter().unit(t); } public static <W extends WitnessType<W>,T> ListT<W, T> liftM(VectorX<T> v, W witness) { return ListT.of(witness.adapter().unit(v)); } public static <W extends WitnessType<W>,T> Function<W,ListT<W, T>> liftM(VectorX<T> s) { return w->liftM(s,w); } public static <W extends WitnessType<W>,T> ListT<W, T> liftM(ListX<T> l, W witness) { return ListT.of(witness.adapter().unit(l)); } public static <W extends WitnessType<W>,T> Function<W,ListT<W, T>> liftM(ListX<T> s) { return w->liftM(s,w); } public static <W extends WitnessType<W>,ST,PT> EitherT<W, ST,PT> liftM(Either<ST,PT> e, W witness) { return EitherT.of(witness.adapter().unit(e)); } public static <W extends WitnessType<W>,ST,PT> Function<W,EitherT<W, ST,PT>> liftM(Either<ST,PT> s) { return w->liftM(s,w); } public static <W extends WitnessType<W>,T> EvalT<W, T> liftM(Eval<T> e, W witness) { return EvalT.of(witness.adapter().unit(e)); } public static <W extends WitnessType<W>,T> Function<W,EvalT<W, T>> liftM(Eval<T> s) { return w->liftM(s,w); } public static <W extends WitnessType<W>,T> MaybeT<W, T> liftM(Maybe<T> m, W witness) { return MaybeT.of(witness.adapter().unit(m)); } public static <W extends WitnessType<W>,T> Function<W,MaybeT<W, T>> liftM(Maybe<T> s) { return w->liftM(s,w); } public static <W extends WitnessType<W>,T> OptionT<W, T> liftM(Option<T> m, W witness) { return OptionT.of(witness.adapter().unit(m)); } public static <W extends WitnessType<W>,T> Function<W,OptionT<W, T>> liftM(Option<T> s) { return w->liftM(s,w); } public static <W extends WitnessType<W>,T> FutureT<W, T> liftM(Future<T> f, W witness) { return FutureT.of(witness.adapter().unit(f)); } public static <W extends WitnessType<W>,T> Function<W,FutureT<W, T>> liftM(Future<T> s) { return w->liftM(s,w); } public static <W extends WitnessType<W>,T> ListT<W, T> liftM(LinkedListX<T> l, W witness) { return ListT.of(witness.adapter().unit(l)); } public static <W extends WitnessType<W>,T> Function<W,ListT<W, T>> liftM(LinkedListX<T> s) { return w->liftM(s,w); } public static <T,W extends WitnessType<W>> CompletableFutureT<W, T> liftM(CompletableFuture<T> opt, W witness) { return CompletableFutureT.of(witness.adapter().unit(opt)); } public static <W extends WitnessType<W>,T> Function<W,CompletableFutureT<W, T>> liftM(CompletableFuture<T> s) { return w->liftM(s,w); } public static <T,W extends WitnessType<W>> OptionalT<W, T> liftM(Optional<T> opt, W witness) { return OptionalT.of(witness.adapter().unit(opt)); } public static <T,W extends WitnessType<W>> Function<W,OptionalT<W, T>> liftM(Optional<T> opt) { return w->liftM(opt,w); } public static <T> StreamT<Witness.reactiveSeq,T> combinationsT(ReactiveSeq<T> s,final int size) { return StreamT.fromReactiveSeq(s.combinations(size)); } public static <W extends WitnessType<W>,T> Function<W,StreamT<W, T>> liftM(ReactiveSeq<T> s) { return w->liftM(s,w); } public static <W extends WitnessType<W>,T> StreamT<W, T> liftM(ReactiveSeq<T> s, W witness) { return StreamT.of(witness.adapter().unit(s)); } public static <T> StreamT<Witness.reactiveSeq,T> combinationsT(ReactiveSeq<T> s) { return StreamT.fromReactiveSeq(s.combinations()); } public static <T> StreamT<Witness.reactiveSeq,T> permutationsT(ReactiveSeq<T> s) { return StreamT.fromReactiveSeq(s.permutations()); } /** * Generic zip function. E.g. Zipping a Stream and an Optional * * <pre> * {@code * Stream<List<Integer>> zipped = Streams.zip(Stream.of(1,2,3) ,fromEither5(Optional.of(2)), (a,b) -> Arrays.asList(a,b)); List<Integer> zip = zipped.collect(CyclopsCollectors.toList()).getValue(0); assertThat(zip.getValue(0),equalTo(1)); assertThat(zip.getValue(1),equalTo(2)); * * } * </pre> */ public static <T, S, R> Stream<R> zipAnyM(final Stream<T> stream, final AnyM<Witness.stream,? extends S> second, final BiFunction<? super T,? super S,? extends R> zipper) { return Streams.zipSequence(stream, second.to(Witness::stream), zipper); } public static <W extends WitnessType<W>,T> Either<AnyMValue<W,T>, AnyMSeq<W,T>> anyM(final AnyM<W,T> anyM) { return anyM instanceof AnyMValue? Either.left((AnyMValue<W,T>) anyM) : Either.right((AnyMSeq<W,T>) anyM); } } ======================= File: cyclops-futurestream/src/test/java/cyclops/futurestream/react/lazy/futures/PartitionAndSplittingTest.java ======================= <filename>cyclops-futurestream/src/test/java/cyclops/futurestream/react/lazy/futures/PartitionAndSplittingTest.java package cyclops.futurestream.react.lazy.futures; import static java.util.Arrays.asList; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import java.util.function.Supplier; import cyclops.futurestream.react.lazy.DuplicationTest; import cyclops.control.Option; import cyclops.futurestream.FutureStream; import org.junit.Assert; import org.junit.Test; public class PartitionAndSplittingTest { @Test public void testSplitAt() { for (int i = 0; i < 1000; i++) { Supplier<FutureStream<Integer>> s = () -> cyclops.futurestream.react.lazy.DuplicationTest.of(1, 2, 3, 4, 5, 6); Assert.assertEquals(asList(), s.get().actOnFutures().splitAt(0)._1().toList()); assertTrue(s.get().actOnFutures().splitAt(0)._2().toList().containsAll(asList(1, 2, 3, 4, 5, 6))); Assert.assertEquals(1, s.get().actOnFutures().splitAt(1)._1().toList().size()); Assert.assertEquals(s.get().actOnFutures().splitAt(1)._2().toList().size(), 5); Assert.assertEquals(3, s.get().actOnFutures().splitAt(3)._1().toList().size()); Assert.assertEquals(3, s.get().actOnFutures().splitAt(3)._2().count()); Assert.assertEquals(6, s.get().actOnFutures().splitAt(6)._1().toList().size()); Assert.assertEquals(asList(), s.get().actOnFutures().splitAt(6)._2().toList()); assertThat(s.get().actOnFutures().splitAt(7)._1().toList().size(), is(6)); Assert.assertEquals(asList(), s.get().actOnFutures().splitAt(7)._2().toList()); } } @Test public void testSplitAtHead() { Assert.assertEquals(asList(), cyclops.futurestream.react.lazy.DuplicationTest.of(1).actOnFutures().splitAtHead()._2().toList()); Assert.assertEquals(Option.none(), cyclops.futurestream.react.lazy.DuplicationTest.of().actOnFutures().splitAtHead()._1()); Assert.assertEquals(asList(), cyclops.futurestream.react.lazy.DuplicationTest.of().actOnFutures().splitAtHead()._2().toList()); Assert.assertEquals(Option.of(1), cyclops.futurestream.react.lazy.DuplicationTest.of(1).actOnFutures().splitAtHead()._1()); Assert.assertEquals(Option.of(1), cyclops.futurestream.react.lazy.DuplicationTest.of(1, 2).actOnFutures().splitAtHead()._1()); Assert.assertEquals(asList(2), cyclops.futurestream.react.lazy.DuplicationTest.of(1, 2).actOnFutures().splitAtHead()._2().toList()); Assert.assertEquals(Option.of(1), cyclops.futurestream.react.lazy.DuplicationTest.of(1, 2, 3).actOnFutures().splitAtHead()._1()); Assert.assertEquals(Option.of(2), cyclops.futurestream.react.lazy.DuplicationTest.of(1, 2, 3).actOnFutures().splitAtHead()._2().splitAtHead()._1()); Assert.assertEquals(Option.of(3), cyclops.futurestream.react.lazy.DuplicationTest.of(1, 2, 3).actOnFutures().splitAtHead()._2().splitAtHead()._2().splitAtHead()._1()); Assert.assertEquals(asList(2, 3), cyclops.futurestream.react.lazy.DuplicationTest.of(1, 2, 3).splitAtHead()._2().toList()); Assert.assertEquals(asList(3), cyclops.futurestream.react.lazy.DuplicationTest.of(1, 2, 3).actOnFutures().splitAtHead()._2().splitAtHead()._2().toList()); Assert.assertEquals(asList(), DuplicationTest.of(1, 2, 3).actOnFutures().splitAtHead()._2().splitAtHead()._2().splitAtHead()._2().toList()); } } ======================= File: cyclops/src/jmh/java/scrabble/ShakespearePlaysScrabble.java ======================= <reponame>zmyer/cyclops-react //JMH Benchmarking test file : not part of distribution /* * Copyright (C) 2015 <NAME> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; lazyEither version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package scrabble; import java.util.Set; import org.openjdk.jmh.annotations.*; import scrabble.Util; @State(Scope.Benchmark) public class ShakespearePlaysScrabble { static class MutableLong { long value; long get() { return value; } MutableLong set(long l) { value = l; return this; } MutableLong incAndSet() { value++; return this; } MutableLong add(MutableLong other) { value += other.value; return this; } } interface Wrapper<T> { T get() ; default Wrapper<T> set(T t) { return () -> t ; } } interface IntWrapper { int get() ; default IntWrapper set(int i) { return () -> i ; } default IntWrapper incAndSet() { return () -> get() + 1 ; } } interface LongWrapper { long get() ; default LongWrapper set(long l) { return () -> l ; } default LongWrapper incAndSet() { return () -> get() + 1L ; } default LongWrapper add(LongWrapper other) { return () -> get() + other.get() ; } } public static final int [] letterScores = { // a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z 1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 1, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10} ; public static final int [] scrabbleAvailableLetters = { // a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z 9, 2, 2, 1, 12, 2, 3, 2, 9, 1, 1, 4, 2, 6, 8, 2, 1, 6, 4, 6, 4, 2, 2, 1, 2, 1} ; public Set<String> scrabbleWords; public Set<String> shakespeareWords; @Setup public void init() { scrabbleWords = Util.readScrabbleWords() ; shakespeareWords = Util.readShakespeareWords() ; } } ======================= File: cyclops-anym/src/test/java/cyclops/monads/anym/value/IorAnyMValueTest.java ======================= package cyclops.monads.anym.value; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; import com.oath.cyclops.util.box.Mutable; import cyclops.monads.Witness; import cyclops.monads.Witness.ior; import org.junit.Before; import org.junit.Test; import cyclops.monads.AnyM; import cyclops.control.Ior; public class IorAnyMValueTest extends BaseAnyMValueTest<ior> { @Before public void setUp() throws Exception { just = AnyM.fromIor(Ior.right(10)); none = AnyM.fromIor(Ior.left(null)); } @Test public void testPeek() { Mutable<Integer> capture = Mutable.of(null); just = just.peek(c->capture.set(c)); just.get(); assertThat(capture.get(),equalTo(10)); } } ======================= File: cyclops/src/test/java/cyclops/reactive/SpoutsTest.java ======================= <filename>cyclops/src/test/java/cyclops/reactive/SpoutsTest.java package cyclops.reactive; import com.oath.cyclops.types.reactive.AsyncSubscriber; import com.oath.cyclops.types.reactive.ReactiveSubscriber; import cyclops.companion.Monoids; import cyclops.companion.Semigroups; import com.oath.cyclops.async.QueueFactories; import com.oath.cyclops.async.adapters.Topic; import cyclops.function.Effect; import org.hamcrest.CoreMatchers; import org.hamcrest.Matchers; import cyclops.data.tuple.Tuple2; import org.junit.Before; import org.junit.Test; import org.reactivestreams.Subscription; import reactor.core.publisher.Flux; import java.util.*; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.Collector; import java.util.stream.Collectors; import java.util.stream.Stream; import static com.oath.cyclops.types.foldable.Evaluation.LAZY; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.hasItems; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.isOneOf; import static org.hamcrest.core.IsCollectionContaining.hasItem; import static org.junit.Assert.*; /** * Created by johnmcclean on 20/01/2017. */ public class SpoutsTest { int i=0; Executor ex = Executors.newFixedThreadPool(5); int count = 0; @Before public void setup(){ i=0; count=0; err = null; } Throwable err; @Test public void generateErrorTest(){ Spouts.generate(()->{throw new RuntimeException();}).forEach(System.out::println,t->err=t); assertNotNull(err); } @Test public void deferErrorTest(){ Spouts.defer(()->{throw new RuntimeException();}).forEach(System.out::println,t->err=t); assertNotNull(err); } @Test public void reactiveBuffer() throws InterruptedException { Subscription sub = Spouts.reactiveBuffer(16, s -> { s.onSubscribe(new Subscription() { @Override public void request(long n) { if(i==0) { Effect e = () -> { s.onNext("hello " + i++); }; e.cycle(30).runAsync(); } } @Override public void cancel() { } }); }).forEach(2, in->count++); //count will be 2, buffer will be 16 Thread.sleep(500); sub.request(30); assertThat(i,equalTo(30)); assertThat(count,equalTo(18)); } AtomicInteger counter; @Test public void reactiveBufferCycle() throws InterruptedException { counter = new AtomicInteger(0); Subscription sub = Spouts.reactiveBuffer(10, s -> { s.onSubscribe(new Subscription() { @Override public void request(long n) { if(counter.get()==0) { Effect e = () -> { s.onNext("hello " +counter.incrementAndGet()); }; e.cycleAsync(30,ex).run(); } } @Override public void cancel() { } }); }).forEach(2, in->count++); Thread.sleep(510); sub.request(30); assertThat(counter.get(),equalTo(30)); assertThat(count,equalTo(18)); } @Test public void reactiveBufferBlock() throws InterruptedException { Subscription sub = Spouts.reactiveBufferBlock(10, s -> { s.onSubscribe(new Subscription() { @Override public void request(long n) { if(i==0) { Effect e = () -> { s.onNext("hello " + i++); }; e.cycle(30).runAsync(); } } @Override public void cancel() { } }); }).forEach(2, in->count++); Thread.sleep(500); sub.request(30); Thread.sleep(500); assertThat(i,equalTo(30)); assertThat(count,equalTo(30)); } @Test public void asyncBufferBlock() throws InterruptedException { Subscription sub = Spouts.asyncBufferBlock(10, s -> { if (i == 0) { Effect e = () -> { s.onNext("hello " + i++); }; e.cycle(30).runAsync(); } } ).forEach(2, in->count++); Thread.sleep(500); sub.request(30); Thread.sleep(500); assertThat(i,equalTo(30)); assertThat(count,equalTo(30)); } @Test public void asyncStream(){ assertThat(Arrays.asList(1,2,3),equalTo(Spouts.async(ReactiveSeq.of(1,2,3),Executors.newFixedThreadPool(1)).toList())); } @Test public void asyncStreamAsync(){ assertThat(Arrays.asList(1,2,3),equalTo(Spouts.async(ReactiveSeq.of(1,2,3),Executors.newFixedThreadPool(1)).toList())); } @Test public void combineLatest(){ for(int i=0;i<10_000;i++) { assertThat("Iteration " + i,Spouts.of(100, 200, 300) .zipLatest(nextAsyncRS(), (a, b) -> b) .toList(), hasItems(1,2)); assertThat("Iteration " + i,Spouts.of(100, 200, 300) .zipLatest(nextAsyncRS(), (a, b) -> a) .toList(), hasItems(300)); } } @Test public void iteratePredicate(){ Iterator<Integer> it = Spouts.iterate(1,i->i<4,i->i+1).iterator(); List<Integer> list = new ArrayList<>(); while(it.hasNext()){ list.add(it.next()); } assertThat(list,equalTo(Arrays.asList(1,2,3))); } @Test public void iterate(){ Spouts.iterate(1,i->i+1).limit(3).printOut(); Iterator<Integer> it = Spouts.iterate(1,i->i+1).limit(3).iterator(); List<Integer> list = new ArrayList<>(); while(it.hasNext()){ list.add(it.next()); } assertThat(list,equalTo(Arrays.asList(1,2,3))); } @Test public void array(){ Iterator<Integer> it = Spouts.of(1, 2, 3).iterator(); List<Integer> list = new ArrayList<>(); while(it.hasNext()){ list.add(it.next()); } assertThat(list,equalTo(Arrays.asList(1,2,3))); } @Test public void iterable(){ Iterator<Integer> it = Spouts.fromIterable(Arrays.asList(1, 2, 3)).iterator(); List<Integer> list = new ArrayList<>(); while(it.hasNext()){ list.add(it.next()); } assertThat(list,equalTo(Arrays.asList(1,2,3))); } @Test public void range(){ Iterator<Integer> it = Spouts.range(1,4).iterator(); List<Integer> list = new ArrayList<>(); while(it.hasNext()){ list.add(it.next()); } assertThat(list,equalTo(Arrays.asList(1,2,3))); } @Test public void rangeLong(){ Iterator<Long> it = Spouts.rangeLong(1,4).iterator(); List<Long> list = new ArrayList<>(); while(it.hasNext()){ list.add(it.next()); } assertThat(list,equalTo(Arrays.asList(1l,2l,3l))); } @Test public void fluxConcat(){ Iterator<Integer> it = Spouts.from(Flux.concat(Flux.just(1, 2, 3), Flux.just(10, 20, 30))).iterator(); while(it.hasNext()){ System.out.println("next " + it.next()); } } @Test public void fluxMerge(){ Iterator<Integer> it = Spouts.from(Flux.merge(Flux.just(1, 2, 3), Flux.just(10, 20, 30))).iterator(); while(it.hasNext()){ System.out.println("next " + it.next()); } } @Test public void publishOn(){ assertThat(Spouts.reactive(Stream.of(1,2),Executors.newFixedThreadPool(1)).toList(), CoreMatchers.equalTo(Arrays.asList(1,2))); } @Test public void iteratorTest(){ for(int x=100;x<10000;x=x+1000) { Set<Integer> result = new HashSet<>(x); int max = x; Iterator<Integer> it = Spouts.<Integer>async(sub -> { for (int i = 0; i < max; i++) { sub.onNext(i); } sub.onComplete(); }).iterator(); while (it.hasNext()) { result.add(it.next()); } assertThat(result.size(),equalTo(x)); } } @Test public void parallelFanOut2(){ assertThat(Spouts.of(1,2,3,4) .parallelFanOut(ForkJoinPool.commonPool(), s1->s1.filter(i->i%2==0).map(i->i*2), s2->s2.filter(i->i%2!=0).map(i->i*100)) .toList(), Matchers.equalTo(Arrays.asList(4,100,8,300))); assertThat(Spouts.of(1,2,3,4,5,6,7,8,9) .parallelFanOut(ForkJoinPool.commonPool(),s1->s1.filter(i->i%3==0).map(i->i*2), s2->s2.filter(i->i%3==1).map(i->i*100), s3->s3.filter(i->i%3==2).map(i->i*1000)) .toList(), Matchers.equalTo(Arrays.asList(6, 100, 2000, 12, 400, 5000, 18, 700, 8000))); assertThat(Spouts.of(1,2,3,4,5,6,7,8,9,10,11,12) .parallelFanOut(ForkJoinPool.commonPool(),s1->s1.filter(i->i%4==0).map(i->i*2), s2->s2.filter(i->i%4==1).map(i->i*100), s3->s3.filter(i->i%4==2).map(i->i*1000), s4->s4.filter(i->i%4==3).map(i->i*10000)) .toList(), Matchers.equalTo(Arrays.asList(8, 100, 2000, 30000, 16, 500, 6000, 70000, 24, 900, 10000, 110000))); } @Test public void async(){ assertThat(Spouts.async(sub->{ sub.onNext(1); sub.onNext(2); sub.onComplete(); }).toList(),equalTo(Arrays.asList(1,2))); } @Test public void generate() throws Exception { assertThat(Spouts.generate(()->1) .limit(5) .toList(),equalTo(Arrays.asList(1,1,1,1,1))); assertThat(Spouts.generate(()->Spouts.of(1)) .limit(1) .flatMap(i->i) .toList(),equalTo(Arrays.asList(1))); assertThat(Spouts.generate(()->Spouts.of(1,2)) .limit(1) .flatMap(i->i) .collect(Collectors.toList()),equalTo(Arrays.asList(1,2))); } @Test public void interval() throws Exception { assertThat(Spouts.interval(10, Executors.newScheduledThreadPool(1)) .limit(4) .collect(Collectors.toList()).size(),greaterThan(0)); } @Test public void intervalCron() throws Exception { assertThat(Spouts.interval("* * * * *?", Executors.newScheduledThreadPool(1)) .limit(2) .collect(Collectors.toList()).size(),greaterThan(0)); } @Test public void collect(){ assertThat(Spouts.of(1,2,3).collect(Collectors.toList()),equalTo(Arrays.asList(1,2,3))); } @Test public void defer() throws Exception { Flux.just(1,2,3).publish(f->f); assertThat(Spouts.of(1,2,3).flatMap(i->Spouts.of(i)).collect(Collectors.toList()) ,equalTo(Arrays.asList(1,2,3))); assertThat(Spouts.defer(()-> Flux.just(1,2,3)) .collect(Collectors.toList()),equalTo(Arrays.asList(1,2,3))); assertThat(Spouts.deferFromStream(()-> ReactiveSeq.of(1,2,3)) .collect(Collectors.toList()),equalTo(Arrays.asList(1,2,3))); } @Test public void ambMonoid(){ for(int i=0;i<1000;i++) { assertThat(Monoids.<Integer>ambReactiveSeq().foldLeft(Stream.of((Spouts.of(1, 2, 3)), Spouts.of(100, 200, 300))).toList(), isOneOf(Arrays.asList(100, 200, 300), Arrays.asList(1, 2, 3))); } // assertThat(Monoids.<Integer>amb() // .applyHKT(nextAsync(),Spouts.of(100,200,300)).listX(),equalTo(ListX.of(100,200,300))); // assertThat(Monoids.<Integer>amb().reduce(Stream.of((nextAsync()),Spouts.of(100,200,300))).listX(),equalTo(ListX.of(100,200,300))); // assertThat(Spouts.amb(ListX.of(nextAsync(),Spouts.of(100,200,300))).listX(),equalTo(ListX.of(100,200,300))); } @Test public void nextAsyncToListX(){ System.out.println(nextAsync().toList()); } @Test public void publishToAndMerge(){ com.oath.cyclops.async.adapters.Queue<Integer> queue = QueueFactories.<Integer>boundedNonBlockingQueue(10) .build(); Thread t= new Thread( ()-> { while(true) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Closing!"); queue.close(); } }); t.start(); assertThat(Spouts.of(1,2,3) .publishTo(queue) .peek(System.out::println) .merge(queue) .toList(), Matchers.equalTo(Arrays.asList(1,1,2,2,3,3))); } @Test public void duplicateTest(){ Tuple2<ReactiveSeq<Integer>, ReactiveSeq<Integer>> tp = Spouts.of(1, 2, 3, 4).duplicate(); // tp._1.printOut(); // tp._2.printOut(); System.out.println("Merge!"); // tp._1.mergeP(tp._2).printOut(); Spouts.of("a","b","c").mergeP(ReactiveSeq.of("bb","cc")).printOut(); } @Test public void fanOut2(){ assertThat(Spouts.of(1,2,3,4) .fanOut(s1->s1.filter(i->i%2==0).map(i->i*2), s2->s2.filter(i->i%2!=0).map(i->i*100)) .toList(), Matchers.equalTo(Arrays.asList(4, 100, 8, 300))); } @Test public void fanOut(){ assertThat(Spouts.of(1,2,3,4) .fanOut(s1->s1.filter(i->i%2==0).map(i->i*2), s2->s2.filter(i->i%2!=0).map(i->i*100)) .toList(), Matchers.equalTo(Arrays.asList(4, 100, 8, 300))); assertThat(Spouts.of(1,2,3,4,5,6,7,8,9) .fanOut(s1->s1.filter(i->i%3==0).map(i->i*2), s2->s2.filter(i->i%3==1).map(i->i*100), s3->s3.filter(i->i%3==2).map(i->i*1000)) .toList(), Matchers.equalTo(Arrays.asList(6, 100, 2000, 12, 400, 5000, 18, 700, 8000))); assertThat(Spouts.of(1,2,3,4,5,6,7,8,9,10,11,12) .fanOut(s1->s1.filter(i->i%4==0).map(i->i*2), s2->s2.filter(i->i%4==1).map(i->i*100), s3->s3.filter(i->i%4==2).map(i->i*1000), s4->s4.filter(i->i%4==3).map(i->i*10000)) .toList(), Matchers.equalTo(Arrays.asList(8, 100, 2000, 30000, 16, 500, 6000, 70000, 24, 900, 10000, 110000))); } @Test public void iteratePred(){ System.out.println(Spouts.iterate(0,i->i<10,i->i+1).toList()); assertThat(Spouts.iterate(0,i->i<10,i->i+1) .toList().size(), Matchers.equalTo(10)); } @Test public void broadcastTest(){ Topic<Integer> topic = Spouts.of(1,2,3) .broadcast(); ReactiveSeq<Integer> stream1 = topic.stream(); ReactiveSeq<Integer> stream2 = topic.stream(); assertThat(stream1.toList(), Matchers.equalTo(Arrays.asList(1,2,3))); assertThat(stream2.toList(), Matchers.equalTo(Arrays.asList(1,2,3))); } @Test public void broadcastThreads() throws InterruptedException { Topic<Integer> topic = Spouts.range(0,100_000) .broadcast(); Thread t= new Thread( ()-> { ReactiveSeq<Integer> stream2 = topic.stream(); assertThat(stream2.takeRight(1).singleOrElse(null), Matchers.equalTo(99_999)); }); t.start(); ReactiveSeq<Integer> stream1 = topic.stream(); assertThat(stream1.takeRight(1).singleOrElse(null), Matchers.equalTo(99_999)); t.join(); } @Test public void ambTest(){ assertThat(Spouts.of(1,2,3).ambWith(Flux.just(10,20,30)).toList(), Matchers.isOneOf(Arrays.asList(1,2,3),Arrays.asList(10,20,30))); } @Test public void merge(){ Spouts.mergeLatest(Spouts.of(1,2,3),Spouts.of(5,6,7)).printOut(); Spouts.mergeLatest(Spouts.of(10,20,30),nextAsyncRS()).printOut(); } @Test public void mergeLatest(){ Spouts.mergeLatest(Spouts.of(1,2,3),Spouts.of(5,6,7)).printOut(); Spouts.mergeLatest(Spouts.of(10,20,30),nextAsyncRS()).printOut(); } @Test public void testCollector(){ Collector<Integer,?, List<Integer>> list = Collectors.toList(); List<Integer> res= null; res =Stream.of(1,2,3) .map(i->i+2) .collect(list); System.out.println("res " + res); // Stream.of(1,2,3).collect((Supplier)list.supplier(),list.accumulator(),list.combiner()); } @Test public void ambSemigroupTest(){ System.out.println(ReactiveSeq.fromPublisher( Semigroups.<Integer>amb() .apply(Spouts.of(100,200,300),nextAsyncRS())).collect(Collectors.toList())); /** ReactiveSeq.fromPublisher(Flux.amb(nextAsync(),nextAsyncRS())) .forEach(System.out::println); **/ /** assertThat(SemigroupK.<Integer>amb() .applyHKT(Spouts.of(100,200,300),nextAsyncRS()).listX(),equalTo(ListX.of(100,200,300))); assertThat(SemigroupK.<Integer>amb() .applyHKT(nextAsyncRS(),Spouts.of(100,200,300)).listX(),equalTo(ListX.of(100,200,300))); **/ } AtomicInteger start= new AtomicInteger(0); private ReactiveSeq<Integer> nextAsyncRS() { ReactiveSubscriber<Integer> sub = Spouts.reactiveSubscriber(); AtomicLong req = new AtomicLong(0); int id = start.incrementAndGet(); sub.onSubscribe(new Subscription() { @Override public void request(long n) { req.addAndGet(n); } @Override public void cancel() { } public String toString(){ return "subscription " + id; } }); new Thread(()->{ int sent=0; while(sent<2){ if(req.get()>0){ sub.onNext( ++sent); req.decrementAndGet(); } } sub.onComplete(); // Flux.just(1,2).forEachAsync(sub); }).start(); return sub.reactiveStream(); } private ReactiveSeq<Integer> nextAsync() { AsyncSubscriber<Integer> sub = Spouts.asyncSubscriber(); new Thread(()->{ sub.awaitInitialization(); try { //not a reactive-stream so we don't know with certainty when demand signalled Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } sub.onNext(1); sub.onNext(2); sub.onComplete(); }).start(); return sub.stream(); } } ======================= File: cyclops/src/test/java/com/oath/cyclops/internal/stream/spliterators/push/grouping/groupedWhile/GroupedWhileTest.java ======================= <gh_stars>100-1000 package com.oath.cyclops.internal.stream.spliterators.push.grouping.groupedWhile; import cyclops.reactive.Spouts; import org.junit.Before; import org.junit.Test; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; /** * Created by johnmcclean on 19/01/2017. */ public class GroupedWhileTest { Subscription sub ; AtomicInteger count = new AtomicInteger(); AtomicInteger error = new AtomicInteger(); AtomicInteger complete = new AtomicInteger(); @Before public void setup(){ count = new AtomicInteger(); error = new AtomicInteger(); complete = new AtomicInteger(); } @Test public void groupedWhile(){ assertThat(Spouts.iterate(0l, i->i+1l) .groupedWhile(i->false) .map(l->l.get(0)) .limit(100) .collect(Collectors.toList()).size(),equalTo(100)); } @Test public void groupedWhile10(){ Spouts.iterate(0l, i->i+1l) .groupedWhile(i->false) .map(l->l.getOrElse(0,-1l)) .limit(3).subscribe(new Subscriber<Long>() { @Override public void onSubscribe(Subscription s) { sub = s; } @Override public void onNext(Long aLong) { if(aLong.equals(2l)) System.out.println("Recieved " + aLong); count.incrementAndGet(); } @Override public void onError(Throwable t) { error.incrementAndGet(); } @Override public void onComplete() { complete.incrementAndGet(); } }); sub.request(10l); assertThat(count.get(),equalTo(3)); assertThat(complete.get(),equalTo(1)); } } ======================= File: cyclops-reactive-collections/src/main/java/com/oath/cyclops/data/collections/extensions/CollectionXImpl.java ======================= <reponame>zmyer/cyclops-react package com.oath.cyclops.data.collections.extensions; import java.util.Collection; import java.util.Iterator; import java.util.Spliterator; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; import com.oath.cyclops.types.foldable.Evaluation; import com.oath.cyclops.data.collections.extensions.standard.LazyCollectionX; import cyclops.reactive.ReactiveSeq; import cyclops.reactive.collections.mutable.ListX; import lombok.AllArgsConstructor; @AllArgsConstructor public class CollectionXImpl<T> implements LazyCollectionX<T> { private final Collection<T> delegate; @Override public <R> CollectionX<R> unit(final R value) { return ListX.singleton(value); } @Override public <R> FluentCollectionX<R> unit(final Iterable<R> col) { return ListX.fromIterable(col); } /** * @param action * @see java.lang.Iterable#forEach(java.util.function.Consumer) */ @Override public void forEach(final Consumer<? super T> action) { delegate.forEach(action); } /** * @return * @see java.util.Collection#size() */ @Override public int size() { return delegate.size(); } /** * @return * @see java.util.Collection#isEmpty() */ @Override public boolean isEmpty() { return delegate.isEmpty(); } /** * @param o * @return * @see java.util.Collection#contains(java.lang.Object) */ @Override public boolean containsValue(final Object o) { return delegate.contains(o); } @Override public boolean contains(Object o){ return delegate.contains(o); } @Override public boolean isLazy() { return false; } @Override public boolean isEager() { return true; } @Override public Evaluation evaluation() { return Evaluation.EAGER; } @Override public CollectionX<T> lazy() { return this; } @Override public CollectionX<T> eager() { return this; } /** * @return * @see java.util.Collection#iterator() */ @Override public Iterator<T> iterator() { return delegate.iterator(); } /** * @return * @see java.util.Collection#toArray() */ @Override public Object[] toArray() { return delegate.toArray(); } /** * @param a * @return * @see java.util.Collection#toArray(java.lang.Object[]) */ @Override public <T> T[] toArray(final T[] a) { return delegate.toArray(a); } /** * @param e * @return * @see java.util.Collection#add(java.lang.Object) */ @Override public boolean add(final T e) { return delegate.add(e); } /** * @param o * @return * @see java.util.Collection#remove(java.lang.Object) */ @Override public boolean remove(final Object o) { return delegate.remove(o); } /** * @param c * @return * @see java.util.Collection#containsAll(java.util.Collection) */ @Override public boolean containsAll(final Collection<?> c) { return delegate.containsAll(c); } /** * @param c * @return * @see java.util.Collection#addAll(java.util.Collection) */ @Override public boolean addAll(final Collection<? extends T> c) { return delegate.addAll(c); } /** * @param c * @return * @see java.util.Collection#removeAll(java.util.Collection) */ @Override public boolean removeAll(final Collection<?> c) { return delegate.removeAll(c); } /** * @param filter * @return * @see java.util.Collection#removeIf(java.util.function.Predicate) */ @Override public boolean removeIf(final Predicate<? super T> filter) { return delegate.removeIf(filter); } /** * @param c * @return * @see java.util.Collection#retainAll(java.util.Collection) */ @Override public boolean retainAll(final Collection<?> c) { return delegate.retainAll(c); } /** * * @see java.util.Collection#clear() */ @Override public void clear() { delegate.clear(); } /** * @param o * @return * @see java.util.Collection#equals(java.lang.Object) */ @Override public boolean equals(final Object o) { return delegate.equals(o); } /** * @return * @see java.util.Collection#hashCode() */ @Override public int hashCode() { return delegate.hashCode(); } /** * @return * @see java.util.Collection#spliterator() */ @Override public Spliterator<T> spliterator() { return delegate.spliterator(); } /** * @return * @see java.util.Collection#stream() */ @Override public ReactiveSeq<T> stream() { return ReactiveSeq.fromIterable(this); } @Override public boolean isMaterialized() { return true; } /** * @return * @see java.util.Collection#parallelStream() */ @Override public Stream<T> parallelStream() { return delegate.parallelStream(); } /* (non-Javadoc) * @see com.oath.cyclops.collections.extensions.CollectionX#from(java.util.Collection) */ @Override public <T1> CollectionX<T1> from(final Iterable<T1> c) { if (c instanceof CollectionX) return (CollectionX) c; return new CollectionXImpl( ListX.fromIterable(c)); } /* (non-Javadoc) * @see com.oath.cyclops.lambda.monads.IterableFunctor#unitIterable(java.util.Iterator) */ @Override public <U> CollectionX<U> unitIterable(final Iterable<U> u) { return ListX.fromIterable(u); } /* (non-Javadoc) * @see com.oath.cyclops.collections.extensions.standard.LazyCollectionX#fromStream(java.util.stream.Stream) */ @Override public <X> LazyCollectionX<X> fromStream(final ReactiveSeq<X> stream) { return ListX.fromIterable(stream.collect(Collectors.toList())); } @Override public String toString() { return String.format("%s", delegate); } } ======================= File: cyclops-jackson-integration/src/test/java/com/oath/cyclops/jackson/FutureTest.java ======================= package com.oath.cyclops.jackson; import cyclops.control.Eval; import cyclops.control.Future; import org.junit.Ignore; import org.junit.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; public class FutureTest { Future<Integer> some = Future.ofResult(10); @Test @Ignore public void roundTrip(){ String json =JacksonUtil.serializeToJson(Eval.now(10)); System.out.println("Json " + json); Future<Integer> des = JacksonUtil.convertFromJson(json,Future.class); assertThat(des,equalTo(some)); } @Test public void some(){ assertThat(JacksonUtil.serializeToJson(Future.ofResult(5)),equalTo("5")); } } ======================= File: cyclops-reactive-collections/src/test/java/cyclops/reactive/data/collections/PStacksTest.java ======================= <filename>cyclops-reactive-collections/src/test/java/cyclops/reactive/data/collections/PStacksTest.java package cyclops.reactive.data.collections; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; import java.util.Arrays; import cyclops.data.Seq; import org.junit.Test; import cyclops.companion.Reducers; import cyclops.reactive.ReactiveSeq; import cyclops.reactive.collections.immutable.LinkedListX; public class PStacksTest { @Test public void testOf() { assertThat(LinkedListX.of("a","b","c"),equalTo(Arrays.asList("a","b","c"))); } @Test public void testEmpty() { assertThat(LinkedListX.empty(),equalTo(Arrays.asList())); } @Test public void testSingleton() { assertThat(LinkedListX.of("a"),equalTo(Arrays.asList("a"))); } @Test public void testFromCollection() { assertThat(LinkedListX.fromIterable(Arrays.asList("a","b","c")),equalTo(Arrays.asList("a","b","c"))); } @Test public void testToPStackstreamOfTReveresed() { assertThat(LinkedListX.linkedListX(ReactiveSeq.of("a","b","c")), equalTo(Arrays.asList("a","b","c"))); } @Test public void testToPStackReversed() { assertThat(ReactiveSeq.of("a","b","c").foldMap(Reducers.toPersistentListReversed()), equalTo(Seq.of("c","b","a"))); } @Test public void testToPStackstreamOf() { assertThat(LinkedListX.linkedListX(ReactiveSeq.of("a","b","c")), equalTo(Arrays.asList("a","b","c"))); } @Test public void testToPStack() { assertThat(ReactiveSeq.of("a","b","c").foldMap(Reducers.toPersistentList()), equalTo(Seq.of("a","b","c"))); } } ======================= File: cyclops-pure/src/main/java/cyclops/instances/control/IdentityInstances.java ======================= <filename>cyclops-pure/src/main/java/cyclops/instances/control/IdentityInstances.java<gh_stars>0 package cyclops.instances.control; import com.oath.cyclops.hkt.DataWitness; import com.oath.cyclops.hkt.Higher; import cyclops.arrow.Cokleisli; import cyclops.arrow.Kleisli; import cyclops.control.Either; import cyclops.control.Identity; import cyclops.control.Maybe; import cyclops.control.Option; import cyclops.function.Monoid; import cyclops.hkt.Active; import cyclops.hkt.Coproduct; import cyclops.hkt.Nested; import cyclops.hkt.Product; import cyclops.typeclasses.*; import cyclops.typeclasses.comonad.Comonad; import cyclops.typeclasses.comonad.ComonadByPure; import cyclops.typeclasses.foldable.Foldable; import cyclops.typeclasses.foldable.Unfoldable; import cyclops.arrow.MonoidK; import cyclops.typeclasses.functor.Functor; import cyclops.typeclasses.monad.*; import java.util.function.Function; import static cyclops.control.Identity.narrowK; import static cyclops.control.Identity.of; public class IdentityInstances { public static <W1,T> Nested<DataWitness.identity,W1,T> nested(Identity<Higher<W1,T>> nested, InstanceDefinitions<W1> def2){ return Nested.of(nested, IdentityInstances.definitions(),def2); } public <W1,T> Product<DataWitness.identity,W1,T> product(Identity<T> id, Active<W1,T> active){ return Product.of(allTypeclasses(id),active); } public <W1,T> Coproduct<W1,DataWitness.identity,T> coproduct(Identity<T> id, InstanceDefinitions<W1> def2){ return Coproduct.right(id,def2, IdentityInstances.definitions()); } public <T> Active<DataWitness.identity,T> allTypeclasses(Identity<T> id){ return Active.of(id, IdentityInstances.definitions()); } public <W2,R,T> Nested<DataWitness.identity,W2,R> mapM(Identity<T> id,Function<? super T,? extends Higher<W2,R>> fn, InstanceDefinitions<W2> defs){ return Nested.of(id.map(fn), IdentityInstances.definitions(), defs); } public static <T> Kleisli<DataWitness.identity,Identity<T>,T> kindKleisli(){ return Kleisli.of(IdentityInstances.monad(), Identity::widen); } public static <T> Cokleisli<DataWitness.identity,T,Identity<T>> kindCokleisli(){ return Cokleisli.of(Identity::narrowK); } public static InstanceDefinitions<DataWitness.identity> definitions(){ return new InstanceDefinitions<DataWitness.identity>() { @Override public <T, R> Functor<DataWitness.identity> functor() { return IdentityInstances.functor(); } @Override public <T> Pure<DataWitness.identity> unit() { return IdentityInstances.unit(); } @Override public <T, R> Applicative<DataWitness.identity> applicative() { return IdentityInstances.applicative(); } @Override public <T, R> Monad<DataWitness.identity> monad() { return IdentityInstances.monad(); } @Override public <T, R> Option<MonadZero<DataWitness.identity>> monadZero() { return Maybe.nothing(); } @Override public <T> Option<MonadPlus<DataWitness.identity>> monadPlus() { return Maybe.nothing(); } @Override public <T> MonadRec<DataWitness.identity> monadRec() { return IdentityInstances.monadRec(); } @Override public <T> Option<MonadPlus<DataWitness.identity>> monadPlus(MonoidK<DataWitness.identity> m) { return Maybe.nothing(); } @Override public <C2, T> Traverse<DataWitness.identity> traverse() { return IdentityInstances.traverse(); } @Override public <T> Foldable<DataWitness.identity> foldable() { return IdentityInstances.foldable(); } @Override public <T> Option<Comonad<DataWitness.identity>> comonad() { return Maybe.just(IdentityInstances.comonad()); } @Override public <T> Option<Unfoldable<DataWitness.identity>> unfoldable() { return Maybe.nothing(); } }; } public static Functor<DataWitness.identity> functor(){ return new Functor<DataWitness.identity>(){ @Override public <T, R> Higher<DataWitness.identity, R> map(Function<? super T,? extends R> fn, Higher<DataWitness.identity, T> ds) { return narrowK(ds).map(fn); } }; } public static Pure<DataWitness.identity> unit(){ return new Pure<DataWitness.identity>(){ @Override public <T> Higher<DataWitness.identity, T> unit(T value) { return of(value); } }; } public static Applicative<DataWitness.identity> applicative(){ return new Applicative<DataWitness.identity>(){ @Override public <T, R> Higher<DataWitness.identity, R> ap(Higher<DataWitness.identity,? extends Function<T, R>> fn, Higher<DataWitness.identity, T> apply) { Identity<? extends Function<T, R>> f = narrowK(fn); Identity<T> ap = narrowK(apply); return f.flatMap(x -> ap.map(x)); } @Override public <T, R> Higher<DataWitness.identity, R> map(Function<? super T,? extends R> fn, Higher<DataWitness.identity, T> ds) { return functor().map(fn,ds); } @Override public <T> Higher<DataWitness.identity, T> unit(T value) { return IdentityInstances.unit().unit(value); } }; } public static Monad<DataWitness.identity> monad(){ return new Monad<DataWitness.identity>(){ @Override public <T, R> Higher<DataWitness.identity, R> ap(Higher<DataWitness.identity,? extends Function<T, R>> fn, Higher<DataWitness.identity, T> apply) { return applicative().ap(fn,apply); } @Override public <T, R> Higher<DataWitness.identity, R> map(Function<? super T,? extends R> fn, Higher<DataWitness.identity, T> ds) { return functor().map(fn,ds); } @Override public <T> Higher<DataWitness.identity, T> unit(T value) { return IdentityInstances.unit().unit(value); } @Override public <T, R> Higher<DataWitness.identity, R> flatMap(Function<? super T,? extends Higher<DataWitness.identity, R>> fn, Higher<DataWitness.identity, T> ds) { return narrowK(ds).flatMap(fn.andThen(i->narrowK(i))); } }; } public static MonadRec<DataWitness.identity> monadRec() { return new MonadRec<DataWitness.identity>(){ @Override public <T, R> Higher<DataWitness.identity, R> tailRec(T initial, Function<? super T,? extends Higher<DataWitness.identity,? extends Either<T, R>>> fn) { return Identity.tailRec(initial,fn.andThen(Identity::narrowK)); } }; } public static Traverse<DataWitness.identity> traverse(){ return new Traverse<DataWitness.identity>(){ @Override public <T, R> Higher<DataWitness.identity, R> ap(Higher<DataWitness.identity,? extends Function<T, R>> fn, Higher<DataWitness.identity, T> apply) { return applicative().ap(fn,apply); } @Override public <T, R> Higher<DataWitness.identity, R> map(Function<? super T,? extends R> fn, Higher<DataWitness.identity, T> ds) { return functor().map(fn,ds); } @Override public <T> Higher<DataWitness.identity, T> unit(T value) { return IdentityInstances.unit().unit(value); } @Override public <C2, T, R> Higher<C2, Higher<DataWitness.identity, R>> traverseA(Applicative<C2> applicative, Function<? super T,? extends Higher<C2, R>> fn, Higher<DataWitness.identity, T> ds) { Identity<T> id = narrowK(ds); Function<R, Identity<R>> rightFn = r -> of(r); return applicative.map(rightFn, fn.apply(id.value)); } @Override public <C2, T> Higher<C2, Higher<DataWitness.identity, T>> sequenceA(Applicative<C2> applicative, Higher<DataWitness.identity, Higher<C2, T>> ds) { return traverseA(applicative,Function.identity(),ds); } }; } public static Foldable<DataWitness.identity> foldable(){ return new Foldable<DataWitness.identity>(){ @Override public <T> T foldRight(Monoid<T> monoid, Higher<DataWitness.identity, T> ds) { return monoid.apply(narrowK(ds).get(),monoid.zero()); } @Override public <T> T foldLeft(Monoid<T> monoid, Higher<DataWitness.identity, T> ds) { return monoid.apply(monoid.zero(),narrowK(ds).get()); } @Override public <T, R> R foldMap(Monoid<R> mb, Function<? super T,? extends R> fn, Higher<DataWitness.identity, T> nestedA) { return foldLeft(mb,narrowK(nestedA).<R>map(fn)); } }; } public static Comonad<DataWitness.identity> comonad(){ return new ComonadByPure<DataWitness.identity>(){ @Override public <T> T extract(Higher<DataWitness.identity, T> ds) { return narrowK(ds).extract(); } @Override public <T, R> Higher<DataWitness.identity, R> map(Function<? super T,? extends R> fn, Higher<DataWitness.identity, T> ds) { return functor().map(fn,ds); } @Override public <T> Higher<DataWitness.identity, T> unit(T value) { return IdentityInstances.unit().unit(value); } }; } } ======================= File: cyclops/src/main/java/com/oath/cyclops/types/persistent/views/SetView.java ======================= package com.oath.cyclops.types.persistent.views; import com.oath.cyclops.types.persistent.PersistentIndexed; import com.oath.cyclops.types.persistent.PersistentSet; import lombok.AllArgsConstructor; import java.util.*; import java.util.function.Predicate; import java.util.function.UnaryOperator; public interface SetView<T> extends Set<T> { @Override @Deprecated default boolean removeIf(Predicate<? super T> filter) { return false; } @Override @Deprecated boolean add(T t); @Override @Deprecated boolean remove(Object o); @Override @Deprecated boolean addAll(Collection<? extends T> c); @Override @Deprecated boolean removeAll(Collection<?> c); @Override @Deprecated boolean retainAll(Collection<?> c); @Override void clear(); @AllArgsConstructor public static class Impl<T> extends AbstractSet<T> implements SetView<T> { private final PersistentSet<T> host; @Override public int size() { return host.size(); } @Override public boolean isEmpty() { return host.isEmpty(); } @Override public boolean contains(Object o) { return host.containsValue((T)o); } @Override public Iterator<T> iterator() { return host.iterator(); } @Override public Object[] toArray() { return host.stream().toArray(); } @Override public boolean add(T t) { return false; } @Override public boolean remove(Object o) { return false; } @Override public boolean containsAll(Collection<?> c) { for(Object n : c){ if(!contains(n)) return false; } return true; } @Override public boolean addAll(Collection<? extends T> c) { return false; } @Override public boolean removeAll(Collection<?> c) { return false; } @Override public boolean retainAll(Collection<?> c) { return false; } @Override public void clear() { } } } ======================= File: cyclops-reactor-integration/src/test/java/cyclops/streams/syncflux/SyncRSCollectableTest.java ======================= package cyclops.streams.syncflux; import cyclops.companion.reactor.Fluxs; import cyclops.reactive.FluxReactiveSeq; import cyclops.reactive.ReactiveSeq; import cyclops.streams.CollectableTest; import reactor.core.publisher.Flux; public class SyncRSCollectableTest extends CollectableTest { public <T> ReactiveSeq<T> of(T... values){ return FluxReactiveSeq.reactiveSeq(Flux.just(values)); } } ======================= File: cyclops/src/jmh/java/cyclops/reactiveSeq/FlatMapLarge.java ======================= package cyclops.reactiveSeq; import cyclops.reactive.ReactiveSeq; import org.openjdk.jmh.annotations.*; import org.openjdk.jmh.infra.Blackhole; import java.util.concurrent.TimeUnit; import java.util.stream.Stream; public class FlatMapLarge { @Benchmark @BenchmarkMode(Mode.SampleTime) @OutputTimeUnit(TimeUnit.MILLISECONDS) @Warmup( iterations = 10 ) @Measurement( iterations = 10 ) @Fork(1) public void streamFlatMap(Blackhole bh){ Stream.iterate(1,i->i+1) .limit(10000) .flatMap(i -> Stream.of(i * 2,i*2,i*2,i*2)) .forEach(bh::consume); } @Benchmark @BenchmarkMode(Mode.SampleTime) @OutputTimeUnit(TimeUnit.MILLISECONDS) @Warmup( iterations = 10 ) @Measurement( iterations = 10 ) @Fork(1) public void reactiveSeqFlatMap(Blackhole bh) { ReactiveSeq.iterate(1,i->i+1) .limit(10000) .flatMap(i -> Stream.of(i * 2,i*2,i*2,i*2)) .forEach(bh::consume); } } ======================= File: cyclops/src/main/java/com/oath/cyclops/internal/stream/spliterators/push/CompleteOperator.java ======================= <filename>cyclops/src/main/java/com/oath/cyclops/internal/stream/spliterators/push/CompleteOperator.java package com.oath.cyclops.internal.stream.spliterators.push; import java.util.function.Consumer; /** * Created by wyang14 on 17/07/2017. */ public class CompleteOperator<T> extends BaseOperator<T, T> { final Runnable complete; public CompleteOperator(Operator<T> source, Runnable complete) { super(source); this.complete = complete; } @Override public StreamSubscription subscribe(Consumer<? super T> onNext, Consumer<? super Throwable> onError, Runnable onComplete) { return source.subscribe(onNext, onError, () -> { complete.run(); onComplete.run(); }); } @Override public void subscribeAll(Consumer<? super T> onNext, Consumer<? super Throwable> onError, Runnable onCompleteDs) { source.subscribeAll(onNext, onError, () -> { complete.run(); onCompleteDs.run(); }); } } ======================= File: cyclops-futurestream/src/test/java/cyclops/futurestream/react/simple/MergeTest.java ======================= package cyclops.futurestream.react.simple; import static org.hamcrest.Matchers.endsWith; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import java.util.List; import java.util.concurrent.ExecutionException; import com.oath.cyclops.types.futurestream.SimpleReactStream; import org.junit.Test; import cyclops.futurestream.SimpleReact; public class MergeTest { @Test public void testMerge() throws InterruptedException, ExecutionException { SimpleReactStream<String> stage1 = new SimpleReact().<Integer> ofAsync(() -> 1, () -> 2, () -> 3).then(it -> "*" + it); SimpleReactStream<String> stage2 = new SimpleReact().<Integer> ofAsync(() -> 4, () -> 5, () -> 6).then(it -> "*" + it); List<String> result = stage1.merge(stage2).block(); assertThat(result.size(), is(6)); } @Test public void testMergeTypes() throws InterruptedException, ExecutionException { SimpleReactStream<Integer> stage1 = new SimpleReact().<Integer> ofAsync(() -> 1, () -> 2, () -> 3); SimpleReactStream<String> stage2 = new SimpleReact().<Integer> ofAsync(() -> 4, () -> 5, () -> 6).then(it -> "*" + it); List<Object> result = SimpleReactStream.<Object> merge(stage1, stage2).block(); assertThat(result.size(), is(6)); } @Test public void testSplitAndMerge() throws InterruptedException, ExecutionException { SimpleReactStream<String> stage = new SimpleReact().<Integer> ofAsync(() -> 1, () -> 2, () -> 3).then(it -> "*" + it); SimpleReactStream<String> stage1 = stage.filter(it -> it.startsWith("*1")); SimpleReactStream<String> stage2 = stage.filter(it -> it.startsWith("*2")); SimpleReactStream<String> stage3 = stage.filter(it -> it.startsWith("*3")); stage1 = stage1.then(it -> it + "!"); stage2 = stage2.then(it -> it + "*"); stage3 = stage3.then(it -> it + "%"); List<String> result = stage1.merge(stage2).merge(stage3).block(); assertThat(result.size(), is(3)); assertThat(result, hasItem("*1!")); assertThat(result, hasItem("*2*")); assertThat(result, hasItem("*3%")); } @Test public void mergeAndContinueProcessing() { SimpleReactStream<String> stage1 = new SimpleReact().<Integer> ofAsync(() -> 1, () -> 2, () -> 3).then(it -> "*" + it); SimpleReactStream<String> stage2 = new SimpleReact().<Integer> ofAsync(() -> 4, () -> 5, () -> 6).then(it -> "*" + it); List<String> result = stage1.merge(stage2).then(it -> it +"*").block(); result.stream().forEach( it-> assertThat(it,endsWith("*"))); } @Test public void mergeAndForkProcessing() { SimpleReactStream<String> stage1 = new SimpleReact().<Integer> ofAsync(() -> 1, () -> 2, () -> 3).then(it -> "*" + it); SimpleReactStream<String> stage2 = new SimpleReact().<Integer> ofAsync(() -> 4, () -> 5, () -> 6).then(it -> "*" + it); List<String> result1 = stage1.merge(stage2).then(it -> it +"*") .peek(it -> System.out.println(it)).block(); List<String> result2 = stage1.merge(stage2).then(it -> it +"-").block(); result1.stream().forEach( it-> assertThat(it,endsWith("*"))); result2.stream().forEach( it-> assertThat(it,endsWith("-"))); } } ======================= File: cyclops/src/main/java/cyclops/control/Validated.java ======================= <filename>cyclops/src/main/java/cyclops/control/Validated.java package cyclops.control; import com.oath.cyclops.hkt.DataWitness.validated; import com.oath.cyclops.hkt.Higher; import com.oath.cyclops.matching.Sealed2; import com.oath.cyclops.types.OrElseValue; import com.oath.cyclops.types.Value; import com.oath.cyclops.types.functor.Transformable; import cyclops.companion.Semigroups; import cyclops.data.NonEmptyList; import cyclops.data.Seq; import cyclops.function.Monoid; import cyclops.function.Semigroup; import cyclops.reactive.ReactiveSeq; import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.EqualsAndHashCode; import org.reactivestreams.Publisher; import java.io.Serializable; import java.util.Objects; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; public interface Validated<E,T> extends Sealed2<NonEmptyList<E>,T>, Transformable<T>, Iterable<T>, OrElseValue<T,Validated<E,T>>, Higher<validated,T>, Value<T>, Serializable { <R> Validated<E,R> map(Function<? super T,? extends R> f); <RE,R> Validated<RE,R> bimap(Function<? super E,? extends RE> e,Function<? super T,? extends R> f); boolean isValid(); default boolean isInvalid(){ return!isValid(); } @Override default Validated<E,T> peek(final Consumer<? super T> c) { return map(input -> { c.accept(input); return input; }); } default Validated<E,T> combine(Semigroup<T> st, Validated<E,T> b){ return fold(iv -> { return b.fold(biv -> { return Validated.<E,T>invalid(Semigroups.<E>nonEmptyListConcat().apply(iv, biv)); }, bv -> { return Validated.<E,T>invalid(iv); }); }, v -> { return b.fold(biv -> { return Validated.<E,T>invalid(biv); }, bv -> { return Validated.<E,T>valid(st.apply(v, bv)); }); }); } default Validated<E,Seq<T>> sequence(Iterable<Validated<E,T>> seq){ return ReactiveSeq.fromIterable(seq) .prepend(this) .foldLeft(Validated.<E,Seq<T>>valid(Seq.<T>empty()),(a, b)-> a.combine(Semigroups.<T>seqConcat(),b.map(Seq::of))); } default <R> Validated<E,Seq<R>> traverse(Iterable<Validated<E,T>> seq,Function<? super T,? extends R> fn){ return ReactiveSeq.fromIterable(seq) .prepend(this) .foldLeft(Validated.<E,Seq<R>>valid(Seq.<R>empty()),(a, b)-> a.combine(Semigroups.<R>seqConcat(),b.map(v->Seq.of(fn.apply(v))))); } default NonEmptyList<E> orElseInvalid(E alt){ return fold(t->t,a->NonEmptyList.of(alt)); } default Validated<E,T> orElseUseAccumulating(Supplier<Validated<E, T>> alt) { return fold( e -> { return alt.get().fold( ee -> Validated.<E,T>invalid(Semigroups.<E>nonEmptyListConcat().apply(e,ee)), it -> valid(it) ); }, it -> valid(it)); } @Override default Validated<E,T> orElseUse(Supplier<Validated<E, T>> alt) { return fold( e -> alt.get(), it -> valid(it)); } public static <E,T> Validated<E,T> valid(T t){ return new Valid<>(Either.right(t)); } public static <E,T> Validated<E,T> invalid(E e){ return new Invalid<>(Either.left(NonEmptyList.of(e))); } public static <E,T> Validated<E,T> invalid(NonEmptyList<E> nel){ return new Invalid<>(Either.left(nel)); } public static <T> Validated<Throwable,T> fromPublisher(Publisher<T> pub){ return new Async<>(LazyEither.fromPublisher(pub).mapLeft(NonEmptyList::of)); } Either<NonEmptyList<E>,T> toEither(); default <R> R foldInvalidLeft(R zero, BiFunction<R,? super E,R> fold){ return toEither().mapLeft(l->l.foldLeft(zero,fold)).swap().orElse(zero); } default E foldInvalidLeft(Monoid<E> reducer){ return toEither().mapLeft(l->l.foldLeft(reducer.zero(),reducer)).swap().orElse(reducer.zero()); } @AllArgsConstructor(access = AccessLevel.PRIVATE) public final class Async<E,T> implements Validated<E,T>{ private final LazyEither<NonEmptyList<E>,T> either; @Override public <R> Validated<E, R> map(Function<? super T,? extends R> f) { return new Async<>(either.map(f)); } @Override public <RE, R> Validated<RE, R> bimap(Function<? super E,? extends RE> e, Function<? super T,? extends R> f) { return new Async<>(either.bimap(nel->nel.map(e),f)); } @Override public boolean isValid() { return either.isRight(); } @Override public Either<NonEmptyList<E>, T> toEither() { return either; } @Override public <R> R fold(Function<? super NonEmptyList<E>,? extends R> fn1, Function<? super T,? extends R> fn2) { return either.fold(fn1,fn2); } @Override public <R> R fold(Function<? super T,? extends R> present, Supplier<? extends R> absent) { return either.fold(present,absent); } public String toString(){ return either.fold(nl->Validated.invalid(nl).toString(), i->Validated.valid(i).toString()); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null) return false; Validated<?,?> async = (Validated<?,?>) o; return Objects.equals(either, async.toEither()); } @Override public int hashCode() { return Objects.hash(either); } } @AllArgsConstructor(access = AccessLevel.PRIVATE) public final class Valid<E,T> implements Validated<E,T>{ private final Either<NonEmptyList<E>,T> either; @Override public <R> Validated<E, R> map(Function<? super T,? extends R> f) { return new Valid<>(either.map(f)); } @Override public <RE, R> Validated<RE, R> bimap(Function<? super E,? extends RE> e, Function<? super T,? extends R> f) { return new Valid<>(either.bimap(nel->nel.map(e),f)); } @Override public final boolean isValid() { return true; } @Override public Either<NonEmptyList<E>, T> toEither() { return either; } @Override public <R> R fold(Function<? super NonEmptyList<E>,? extends R> fn1, Function<? super T,? extends R> fn2) { return either.fold(fn1,fn2); } @Override public <R> R fold(Function<? super T,? extends R> present, Supplier<? extends R> absent) { return either.fold(present,absent); } public String toString(){ return "Valid["+either.orElse(null)+"]"; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null) return false; Validated<?,?> valid = (Validated<?,?>) o; return Objects.equals(either, valid.toEither()); } @Override public int hashCode() { return Objects.hash(either); } } @AllArgsConstructor(access = AccessLevel.PRIVATE) @EqualsAndHashCode public final class Invalid<E,T> implements Validated<E,T>{ private final Either<NonEmptyList<E>,T> either; @Override public <R> Validated<E, R> map(Function<? super T,? extends R> f) { return new Invalid<>(either.map(f)); } @Override public <RE, R> Validated<RE, R> bimap(Function<? super E,? extends RE> e, Function<? super T,? extends R> f) { return new Invalid<>(either.bimap(nel->nel.map(e),f)); } @Override public boolean isValid() { return false; } @Override public Either<NonEmptyList<E>, T> toEither() { return either; } @Override public <R> R fold(Function<? super NonEmptyList<E>,? extends R> fn1, Function<? super T,? extends R> fn2) { return either.fold(fn1,fn2); } @Override public <R> R fold(Function<? super T,? extends R> present, Supplier<? extends R> absent) { return either.fold(present,absent); } public String toString(){ String str = either.mapLeft(l -> l.join(",")).swap().orElse( ""); return "Invalid["+str+"]"; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null) return false; Validated<?,?> invalid = (Validated<?,?>) o; return Objects.equals(either, invalid.toEither()); } @Override public int hashCode() { return Objects.hash(either); } } } ======================= File: cyclops/src/main/java/com/oath/cyclops/types/factory/Unit.java ======================= package com.oath.cyclops.types.factory; /** * A Data type that supports instantiation of instances of the same type * * @author johnmcclean * * @param <T> Data type of element(s) stored inside this Pure instance */ @FunctionalInterface public interface Unit<T> { public <T> Unit<T> unit(T unit); } ======================= File: cyclops/src/test/java/cyclops/data/DifferenceListTest.java ======================= package cyclops.data; import org.junit.Test; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; /** * Created by johnmcclean on 02/09/2017. */ public class DifferenceListTest { @Test public void append(){ assertThat(DifferenceList.of(1,2,3).append(DifferenceList.of(4,5,6)).run(),equalTo(LazySeq.of(1,2,3,4,5,6))); } @Test public void map(){ assertThat(DifferenceList.of(1,2,3).append(DifferenceList.of(4,5,6)).map(i->i*2).run(),equalTo(LazySeq.of(2,4,6,8,10,12))); } @Test public void flatMap(){ assertThat(DifferenceList.of(1,2,3).append(DifferenceList.of(4,5,6)).flatMap(i-> DifferenceList.of(i*2)).run(),equalTo(LazySeq.of(2,4,6,8,10,12))); } } ======================= File: cyclops-anym/src/test/java/cyclops/monads/anym/value/OptionalAnyMValueTest.java ======================= package cyclops.monads.anym.value; import java.util.Optional; import cyclops.monads.Witness; import cyclops.monads.Witness.optional; import org.junit.Before; import cyclops.monads.AnyM; public class OptionalAnyMValueTest extends BaseAnyMValueTest<optional> { @Before public void setUp() throws Exception { just = AnyM.fromOptional(Optional.of(10)); none = AnyM.fromOptional(Optional.empty()); } } ======================= File: cyclops-rxjava2-integration/src/test/java/cyclops/streams/flowables/syncflux/SyncZippingTest.java ======================= <reponame>zmyer/cyclops-react package cyclops.streams.flowables.syncflux; import cyclops.companion.rx2.Flowables; import cyclops.reactive.FlowableReactiveSeq; import cyclops.reactive.ReactiveSeq; import cyclops.data.tuple.Tuple2; import cyclops.data.tuple.Tuple3; import cyclops.data.tuple.Tuple4; import org.junit.Before; import org.junit.Test; import reactor.core.publisher.Flux; import java.util.Arrays; import java.util.List; import java.util.function.Supplier; import java.util.stream.Collectors; import static java.util.Arrays.asList; import static org.hamcrest.Matchers.*; import static cyclops.data.tuple.Tuple.tuple; import static org.junit.Assert.*; public class SyncZippingTest { ReactiveSeq<Integer> empty; ReactiveSeq<Integer> nonEmpty; @Before public void setup(){ empty = of(); nonEmpty = of(1); } protected <U> ReactiveSeq<U> of(U... array){ return FlowableReactiveSeq.reactiveSeq(Flux.just(array)); } @Test public void zipInOrderNoLimit(){ List<Tuple2<Integer,Integer>> list = of(1,2,3,4,5,6) .zip( of(100,200,300,400)) .collect(Collectors.toList()); /** List<Tuple2<Integer,Integer>> list = of(1,2,3,4,5,6).limit(6) .zip( of(100,200,300,400).limit(4)) .collect(CyclopsCollectors.toList());**/ assertThat(list.get(0)._1(),is(1)); assertThat(list.get(0)._2(),is(100)); assertThat(list.get(1)._1(),is(2)); assertThat(list.get(1)._2(),is(200)); assertThat(list.get(2)._1(),is(3)); assertThat(list.get(2)._2(),is(300)); assertThat(list.get(3)._1(),is(4)); assertThat(list.get(3)._2(),is(400)); } @Test public void zipUnevenRight(){ for(int i=0;i<100;i++) { System.out.println(i); assertEquals(asList("a"), of("a").toList()); assertEquals(asList(tuple("a", 0L)), of("a").zip(of(0L, 1L, 2L)).toList()); assertEquals(asList(tuple("a", 0L), tuple("b", 1L)), of("a", "b").zip(of(0L, 1L, 2L, 3L)).toList()); assertEquals(asList(tuple("a", 0L), tuple("b", 1L)), of("a", "b").zip(of(0L, 1L, 2L, 3L, 4L)).toList()); assertEquals(asList(tuple("a", 0L), tuple("b", 1L)), of("a", "b").zip(of(0L, 1L, 2L, 3L, 4L, 5L)).toList()); assertEquals(asList(tuple(0L, "a"), tuple(1L, "b")), of(0L, 1L).zip(of("a", "b", "c", "d")).toList()); } } @Test public void unevenTest(){ assertEquals(asList(tuple("a", 0L)), of("a","b","c").zip(of(0L)).toList()); } @Test public void zipUnevenLeft(){ for(int i=0;i<100;i++) { System.out.println(i); assertEquals(asList(tuple("a", 0L)), of("a", "b").zip(of(0L)).toList()); assertEquals(asList(tuple("a", 0L), tuple("b", 1L)), of("a", "b", "c").zip(of(0L, 1L)).toList()); assertEquals(asList(tuple("a", 0L), tuple("b", 1L)), of("a", "b", "c").zip(of(0L, 1L)).collect(Collectors.toList())); assertEquals(asList(tuple("a", 0L), tuple("b", 1L)), of("a", "b", "c", "d").zip(of(0L, 1L)).toList()); } } @Test public void zip1(){ assertEquals(asList("a"), of("a").toList()); assertEquals(asList(tuple("a", 0L)), of("a").zip(of(0L)).toList()); } @Test public void zip(){ List<Tuple2<Integer,Integer>> list = of(1,2,3,4,5,6).zip(of(100,200,300,400)) .peek(it -> System.out.println(it)) .collect(Collectors.toList()); System.out.println(list); List<Integer> right = list.stream().map(t -> t._2()).collect(Collectors.toList()); assertThat(right,hasItem(100)); assertThat(right,hasItem(200)); assertThat(right,hasItem(300)); assertThat(right,hasItem(400)); List<Integer> left = list.stream().map(t -> t._1()).collect(Collectors.toList()); assertThat(Arrays.asList(1,2,3,4,5,6),hasItem(left.get(0))); } @Test public void zip3(){ List<Tuple3<Integer,Integer,Character>> list = of(1,2,3,4,5,6).zip3(of(100,200,300,400),of('a','b','c')) .peek(it -> System.out.println(it)) .collect(Collectors.toList()); System.out.println(list); List<Integer> right = list.stream().map(t -> t._2()).collect(Collectors.toList()); assertThat(right,hasItem(100)); assertThat(right,hasItem(200)); assertThat(right,hasItem(300)); assertThat(right,not(hasItem(400))); List<Integer> left = list.stream().map(t -> t._1()).collect(Collectors.toList()); assertThat(Arrays.asList(1,2,3,4,5,6),hasItem(left.get(0))); List<Character> three = list.stream().map(t -> t._3()).collect(Collectors.toList()); assertThat(Arrays.asList('a','b','c'),hasItem(three.get(0))); } @Test public void zip4(){ List<Tuple4<Integer,Integer,Character,String>> list = of(1,2,3,4,5,6).zip4(of(100,200,300,400),of('a','b','c'),of("hello","world")) .peek(it -> System.out.println(it)) .collect(Collectors.toList()); System.out.println(list); List<Integer> right = list.stream().map(t -> t._2()).collect(Collectors.toList()); assertThat(right,hasItem(100)); assertThat(right,hasItem(200)); assertThat(right,not(hasItem(300))); assertThat(right,not(hasItem(400))); List<Integer> left = list.stream().map(t -> t._1()).collect(Collectors.toList()); assertThat(Arrays.asList(1,2,3,4,5,6),hasItem(left.get(0))); List<Character> three = list.stream().map(t -> t._3()).collect(Collectors.toList()); assertThat(Arrays.asList('a','b','c'),hasItem(three.get(0))); List<String> four = list.stream().map(t -> t._4()).collect(Collectors.toList()); assertThat(Arrays.asList("hello","world"),hasItem(four.get(0))); } @Test public void zip2of(){ for(int i=0;i<1000;i++) { System.out.println("i is " + i); List<Tuple2<Integer, Integer>> list = of(1, 2, 3, 4, 5, 6) .zip(of(100, 200, 300, 400)) .peek(it -> System.out.println("Peeking " + it)) .collect(Collectors.toList()); List<Integer> right = list.stream().map(t -> t._2()).collect(Collectors.toList()); System.out.println("Right is " + right + " list is " + list); assertThat(right, hasItem(100)); assertThat(right, hasItem(200)); assertThat(right, hasItem(300)); assertThat(right, hasItem(400)); List<Integer> left = list.stream().map(t -> t._1()).collect(Collectors.toList()); assertThat(Arrays.asList(1, 2, 3, 4, 5, 6), hasItem(left.get(0))); } } @Test public void zipInOrder(){ List<Tuple2<Integer,Integer>> list = of(1,2,3,4,5,6) .zip( of(100,200,300,400)) .collect(Collectors.toList()); assertThat(asList(1,2,3,4,5,6),hasItem(list.get(0)._1())); assertThat(asList(100,200,300,400),hasItem(list.get(0)._2())); } @Test public void zipEmpty() throws Exception { final ReactiveSeq<Integer> zipped = empty.zip(ReactiveSeq.<Integer>of(), (a, b) -> a + b); assertTrue(zipped.collect(Collectors.toList()).isEmpty()); } @Test public void shouldReturnEmptySeqWhenZipEmptyWithNonEmpty() throws Exception { final ReactiveSeq<Integer> zipped = empty.zip(nonEmpty, (a, b) -> a + b); assertTrue(zipped.collect(Collectors.toList()).isEmpty()); } @Test public void shouldReturnEmptySeqWhenZipNonEmptyWithEmpty() throws Exception { final ReactiveSeq<Integer> zipped = nonEmpty.zip(empty, (a, b) -> a + b); assertTrue(zipped.collect(Collectors.toList()).isEmpty()); } @Test public void shouldZipTwoFiniteSequencesOfSameSize() throws Exception { final ReactiveSeq<String> first = of("A", "B", "C"); final ReactiveSeq<Integer> second = of(1, 2, 3); final ReactiveSeq<String> zipped = first.zip(second, (a, b) -> a + b); assertThat(zipped.collect(Collectors.toList()).size(),is(3)); } @Test public void shouldTrimSecondFixedSeqIfLonger() throws Exception { final ReactiveSeq<String> first = of("A", "B", "C"); final ReactiveSeq<Integer> second = of(1, 2, 3, 4); final ReactiveSeq<String> zipped = first.zip(second, (a, b) -> a + b); assertThat(zipped.collect(Collectors.toList()).size(),is(3)); } @Test public void shouldTrimFirstFixedSeqIfLonger() throws Exception { final ReactiveSeq<String> first = of("A", "B", "C","D"); final ReactiveSeq<Integer> second = of(1, 2, 3); final ReactiveSeq<String> zipped = first.zip(second, (a, b) -> a + b); assertThat(zipped.collect(Collectors.toList()).size(),equalTo(3)); } @Test public void testZipDifferingLength() { List<Tuple2<Integer, String>> list = of(1, 2).zip(of("a", "b", "c", "d")).toList(); assertEquals(2, list.size()); assertTrue(asList(1, 2).contains(list.get(0)._1())); assertTrue("" + list.get(1)._2(), asList(1, 2).contains(list.get(1)._1())); assertTrue(asList("a", "b", "c", "d").contains(list.get(0)._2())); assertTrue(asList("a", "b", "c", "d").contains(list.get(1)._2())); } @Test public void shouldTrimSecondFixedSeqIfLongerStream() throws Exception { final ReactiveSeq<String> first = of("A", "B", "C"); final ReactiveSeq<Integer> second = of(1, 2, 3, 4); final ReactiveSeq<String> zipped = first.zipWithStream(second, (a, b) -> a + b); assertThat(zipped.collect(Collectors.toList()).size(),is(3)); } @Test public void shouldTrimFirstFixedSeqIfLongerStream() throws Exception { final ReactiveSeq<String> first = of("A", "B", "C","D"); final ReactiveSeq<Integer> second = of(1, 2, 3); final ReactiveSeq<String> zipped = first.zipWithStream(second, (a, b) -> a + b); assertThat(zipped.collect(Collectors.toList()).size(),equalTo(3)); } @Test public void testZipDifferingLengthStream() { List<Tuple2<Integer, String>> list = of(1, 2).zip(of("a", "b", "c", "d")).toList(); assertEquals(2, list.size()); assertTrue(asList(1, 2).contains(list.get(0)._1())); assertTrue("" + list.get(1)._2(), asList(1, 2).contains(list.get(1)._1())); assertTrue(asList("a", "b", "c", "d").contains(list.get(0)._2())); assertTrue(asList("a", "b", "c", "d").contains(list.get(1)._2())); } @Test public void shouldTrimSecondFixedSeqIfLongerSequence() throws Exception { final ReactiveSeq<String> first = of("A", "B", "C"); final ReactiveSeq<Integer> second = of(1, 2, 3, 4); final ReactiveSeq<String> zipped = first.zip(second, (a, b) -> a + b); assertThat(zipped.collect(Collectors.toList()).size(),is(3)); } @Test public void shouldTrimFirstFixedSeqIfLongerSequence() throws Exception { final ReactiveSeq<String> first = of("A", "B", "C","D"); final ReactiveSeq<Integer> second = of(1, 2, 3); final ReactiveSeq<String> zipped = first.zip(second, (a, b) -> a + b); assertThat(zipped.collect(Collectors.toList()).size(),equalTo(3)); } @Test public void zipWithIndexToList(){ of("a").zipWithIndex().toList(); } @Test public void testZipWithIndex() { assertEquals(asList(), of().zipWithIndex().toList()); assertThat(of("a").zipWithIndex().map(t -> t._2()).findFirst().get(), is(0l)); assertEquals(asList(new Tuple2("a", 0L)), of("a").zipWithIndex().toList()); } @Test public void testUnzip() { Supplier<ReactiveSeq<Tuple2<Integer, String>>> s = () -> of(new Tuple2(1, "a"), new Tuple2(2, "b"), new Tuple2(3, "c")); Tuple2<ReactiveSeq<Integer>, ReactiveSeq<String>> u1 = ReactiveSeq.unzip(s.get()); assertTrue(u1._1().toList().containsAll(Arrays.asList(1, 2, 3))); assertTrue(u1._2().toList().containsAll(asList("a", "b", "c"))); } @Test public void testUnzipWithLimits() { Supplier<ReactiveSeq<Tuple2<Integer, String>>> s = () -> of(new Tuple2(1, "a"), new Tuple2(2, "b"), new Tuple2(3, "c")); Tuple2<ReactiveSeq<Integer>, ReactiveSeq<String>> u1 = ReactiveSeq.unzip(s.get()); assertTrue(u1._1().limit(2).toList().containsAll(Arrays.asList(1, 2))); assertTrue(u1._2().toList().containsAll(asList("a", "b", "c"))); } @Test public void testUnzip3WithLimits() { Supplier<ReactiveSeq<Tuple3<Integer, String, Long>>> s = () -> of(new Tuple3(1, "a", 2l), new Tuple3(2, "b", 3l), new Tuple3(3, "c", 4l)); Tuple3<ReactiveSeq<Integer>, ReactiveSeq<String>, ReactiveSeq<Long>> u1 = ReactiveSeq.unzip3(s.get()); assertTrue(u1._1().limit(1).toList().containsAll(Arrays.asList(1))); assertTrue(u1._2().limit(2).toList().containsAll(asList("a", "b"))); assertTrue(u1._3().toList().containsAll(asList(2l, 3l, 4l))); } @Test public void testUnzip3() { Supplier<ReactiveSeq<Tuple3<Integer, String, Long>>> s = () -> of(new Tuple3(1, "a", 2l), new Tuple3(2, "b", 3l), new Tuple3(3, "c", 4l)); Tuple3<ReactiveSeq<Integer>, ReactiveSeq<String>, ReactiveSeq<Long>> u1 = ReactiveSeq.unzip3(s.get()); assertTrue(u1._1().toList().containsAll(Arrays.asList(1, 2, 3))); assertTrue(u1._2().toList().containsAll(asList("a", "b", "c"))); assertTrue(u1._3().toList().containsAll(asList(2l, 3l, 4l))); } @Test public void testUnzip4() { Supplier<ReactiveSeq<Tuple4<Integer, String, Long, Character>>> s = () -> of(new Tuple4(1, "a", 2l, 'z'), new Tuple4(2, "b", 3l, 'y'), new Tuple4(3, "c", 4l, 'x')); Tuple4<ReactiveSeq<Integer>, ReactiveSeq<String>, ReactiveSeq<Long>, ReactiveSeq<Character>> u1 = ReactiveSeq.unzip4(s.get()); assertTrue(u1._1().toList().containsAll(Arrays.asList(1, 2, 3))); assertTrue(u1._2().toList().containsAll(asList("a", "b", "c"))); assertTrue(u1._3().toList().containsAll(asList(2l, 3l, 4l))); assertTrue(u1._4().toList().containsAll(asList('z', 'y', 'x'))); } @Test public void testUnzip4WithLimits() { Supplier<ReactiveSeq<Tuple4<Integer, String, Long, Character>>> s = () -> of(new Tuple4(1, "a", 2l, 'z'), new Tuple4(2, "b", 3l, 'y'), new Tuple4(3, "c", 4l, 'x')); Tuple4<ReactiveSeq<Integer>, ReactiveSeq<String>, ReactiveSeq<Long>, ReactiveSeq<Character>> u1 = ReactiveSeq.unzip4(s.get()); assertTrue(u1._1().limit(1).toList().containsAll(Arrays.asList(1))); assertTrue(u1._2().limit(2).toList().containsAll(asList("a", "b"))); assertTrue(u1._3().limit(3).toList().containsAll(asList(2l, 3l, 4l))); assertTrue(u1._4().limit(4).toList().containsAll(asList('z', 'y', 'x'))); } } ======================= File: cyclops-futurestream/src/test/java/cyclops/futurestream/react/simple/FilterTest.java ======================= <gh_stars>100-1000 package cyclops.futurestream.react.simple; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import java.util.Arrays; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.stream.Collectors; import org.junit.Test; import cyclops.futurestream.SimpleReact; public class FilterTest { @Test public void testFilterBehavesAsStreamFilter() throws InterruptedException, ExecutionException { int expected = Arrays.asList("*1","*2","*3").stream().filter(it -> it.startsWith("*")) .collect(Collectors.toList()).size(); List<String> result = new SimpleReact() .<Integer> ofAsync(() -> 1, () -> 2, () -> 3) .then(it -> "*" + it) .filter(it -> it.startsWith("*")) .block(); assertThat(result.size(), is(expected)); } @Test public void testNegativeFilterBehavesAsStreamFilter() throws InterruptedException, ExecutionException { int expected = Arrays.asList("*1","*2","*3").stream().filter(it ->!it.startsWith("*")) .collect(Collectors.toList()).size(); List<String> result = new SimpleReact() .<Integer> ofAsync(() -> 1, () -> 2, () -> 3) .then(it -> "*" + it) .filter(it ->!it.startsWith("*")) .block(); assertThat(result.size(), is(expected)); } @Test public void testFilter() throws InterruptedException, ExecutionException { List<String> result = new SimpleReact() .<Integer> ofAsync(() -> 1, () -> 2, () -> 3) .then(it -> "*" + it) .filter(it -> it.startsWith("*")) .block(); assertThat(result.size(), is(3)); } @Test public void testNegativeFilter() throws InterruptedException, ExecutionException { List<String> result = new SimpleReact() .<Integer> ofAsync(() -> 1, () -> 2, () -> 3) .then(it -> "*" + it) .filter(it ->!it.startsWith("*")) .block(); assertThat(result.size(), is(0)); } @Test public void testFilterFirst() throws InterruptedException, ExecutionException { List<String> result = new SimpleReact() .<Integer> ofAsync(() -> 1, () -> 2, () -> 3) .filter(it -> 1!=it) .peek(it -> System.out.println(it)) .<String>then(it -> "*" + it) .capture( e -> e.printStackTrace()) .block(); assertThat(result.size(), is(2)); assertThat(result, not(hasItem("*1"))); } @Test public void testFilterExceptions() throws InterruptedException, ExecutionException { List<String> result = new SimpleReact() .<Integer> ofAsync(() -> 1, () -> 2, () -> 3) .filter(it -> 1!=it) .<String>then(it -> "*" + it) .capture( e -> fail("No exception should be captured")) .block(); assertThat(result.size(), is(2)); assertThat(result, not(hasItem("*1"))); } } ======================= File: cyclops/src/main/java/cyclops/function/Lambda.java ======================= <filename>cyclops/src/main/java/cyclops/function/Lambda.java package cyclops.function; import java.util.function.Predicate; /** * Lambda type inferencing helper / curried function creation helper * * @author johnmcclean * */ public class Lambda { public static <T> Iterable<T> it(Iterable<T> it){ return it; } /** * E.g. to use a supplier to embed additional code inisde a ternary operator * * <pre> * {@code * return pos >= values.length? tuple(true, split) : Lambda.s(() -> { action.accept(values[pos++]); return tuple(true, this); }).getValue(); * * } * </pre> * * @param supplier Lambda / method to assign type of Supplier to * @return Supplier */ public static <T> Function0<T> s(final Function0<T> supplier) { return supplier; } /** * E.g. to use a supplier to embed additional code inisde a ternary operator * * <pre> * {@code * return pos >= values.length? tuple(true, split) : Lambda.s(() -> { action.accept(values[pos++]); return tuple(true, this); }).getValue(); * * } * </pre> * * @param supplier Lambda / method to assign type of Supplier to * @return Supplier */ public static <T> Function0<T> λ(final Function0<T> supplier) { return supplier; } public static <T> Predicate<T> λ(final Predicate<T> pred) { return pred; } public static <T> Predicate<T> p(final Predicate<T> p) { return p; } /** * Alias for l1 * e.g. with Lombok val * * <pre>{@code * val fn = λ((Integer i)->"hello") * }</pre> * @param func * @return supplied function */ public static <T1, R> Function1<T1, R> λ(final Function1<T1, R> func) { return func; } /** * e.g. with Lombok val * * <pre>{@code * val fn = l1((Integer i)->"hello") * }</pre> * @param func * @return supplied function */ public static <T1, R> Function1<T1, R> l1(final Function1<T1, R> func) { return func; } /** * Create a curried function with arity of 2 * * e.g. with Lombok val * * <pre>{@code * val fn = λ((Integer a)-> (Integer b)-> a+b+) * }</pre> * @param biFunc * @return supplied function */ public static <T1, T2, R> Function2<T1,T2, R> λ(final Function2<T1,T2, R> biFunc) { return biFunc; } /** * Create a curried function with arity of 3 * * e.g. with Lombok val * * <pre>{@code * val fn = λ((Integer a)-> (Integer b)-> a+b+) * }</pre> * @param triFunc * @return supplied function */ public static <T1, T2, T3,R> Function3<T1,T2,T3, R> λ(final Function3<T1,T2,T3, R> triFunc) { return triFunc; } /** * Create a curried function with arity of 4 * * e.g. with Lombok val * * <pre>{@code * val fn = λ((Integer a)-> (Integer b)-> a+b+) * }</pre> * @param quadFunc * @return supplied function */ public static <T1, T2, T3, T4,R> Function4<T1,T2,T3, T4,R> λ(final Function4<T1,T2,T3,T4, R> quadFunc) { return quadFunc; } /** * Create a curried function with arity of 5 * * e.g. with Lombok val * * <pre>{@code * val fn = λ((Integer a)-> (Integer b)-> a+b+) * }</pre> * @param quintFunc * @return supplied function */ public static <T1, T2, T3, T4, T5,R> Function5<T1,T2,T3, T4, T5,R> λ(final Function5<T1,T2,T3,T4,T5, R> quintFunc) { return quintFunc; } /** * Create a curried function with arity of 6 * * e.g. with Lombok val * * <pre>{@code * val fn = λ((Integer a)-> (Integer b)-> a+b+) * }</pre> * @param func6 * @return supplied function */ public static <T1, T2, T3, T4, T5, T6,R> Function6<T1,T2,T3, T4, T5,T6,R> λ(final Function6<T1,T2,T3,T4,T5,T6, R> func6) { return func6; } /** * Create a curried function with arity of 7 * * e.g. with Lombok val * * <pre>{@code * val fn = λ((Integer a)-> (Integer b)-> a+b+) * }</pre> * @param quadFunc * @return supplied function */ public static <T1, T2, T3, T4, T5, T6,T7,R> Function7<T1,T2,T3, T4, T5,T6,T7,R> λ(final Function7<T1,T2,T3,T4,T5,T6,T7, R> func7) { return func7; } /** * Create a curried function with arity of 8 * * e.g. with Lombok val * * <pre>{@code * val fn = λ((Integer a)-> (Integer b)-> a+b+) * }</pre> * @param quadFunc * @return supplied function */ public static <T1, T2, T3, T4, T5, T6,T7,T8,R> Function8<T1,T2,T3, T4, T5,T6,T7,T8,R> λ(final Function8<T1,T2,T3,T4,T5,T6,T7,T8, R> func8) { return func8; } /** * Create a curried function with arity of 2 * * e.g. with Lombok val * * <pre>{@code * val fn = l3((Integer a)-> (Integer b)-> a+b+) * }</pre> * @param biFunc * @return supplied function */ public static <T1, T2, R> Function1<T1, Function1<T2, R>> l2(final Function1<T1, Function1<T2, R>> biFunc) { return biFunc; } public static <T1, T2, R> Function1<? super T1,? extends Function1<? super T2,? extends R>> v2(final Function1<? super T1, Function1<? super T2,? extends R>> biFunc) { return biFunc; } /** * Create a curried function with arity of 3 * * e.g. with Lombok val * * <pre>{@code * val fn = l3((Integer a)-> (Integer b)->(Integer c) -> a+b+c) * }</pre> * @param triFunc * @return supplied function */ public static <T1, T2, T3, R> Function1<T1, Function1<T2, Function1<T3, R>>> l3(final Function1<T1, Function1<T2, Function1<T3, R>>> triFunc) { return triFunc; } /** * Create a curried function with arity of 4 * * e.g. with Lombok val * * <pre>{@code * val fn = l4((Integer a)-> (Integer b)->(Integer c) -> (Integer d) -> a+b+c+d) * }</pre> * @param quadFunc * @return supplied function */ public static <T1, T2, T3, T4, R> Function1<T1, Function1<T2, Function1<T3, Function1<T4, R>>>> l4( final Function1<T1, Function1<T2, Function1<T3, Function1<T4, R>>>> quadFunc) { return quadFunc; } /** * Create a curried function with arity of 5 * * e.g. with Lombok val * * <pre>{@code * val fn = l4((Integer a)-> (Integer b)->(Integer c) -> (Integer d) -> (Integer e) -> a+b+c+d+e) * }</pre> * @param pentFunc * @return supplied function */ public static <T1, T2, T3, T4, T5, R> Function1<T1, Function1<T2, Function1<T3, Function1<T4, Function1<T5, R>>>>> l5( final Function1<T1, Function1<T2, Function1<T3, Function1<T4, Function1<T5, R>>>>> pentFunc) { return pentFunc; } /** * Create a curried function with arity of 6 * * e.g. with Lombok val * * <pre>{@code * val fn = l4((Integer a)-> (Integer b)->(Integer c) -> (Integer d) -> (Integer e) -> (Integer f)-> a+b+c+d+e+f) * }</pre> * @param hexFunc * @return supplied function */ public static <T1, T2, T3, T4, T5, T6, R> Function1<T1, Function1<T2, Function1<T3, Function1<T4, Function1<T5, Function1<T6, R>>>>>> l6( final Function1<T1, Function1<T2, Function1<T3, Function1<T4, Function1<T5, Function1<T6, R>>>>>> hexFunc) { return hexFunc; } /** * Create a curried function with arity of 7 * * e.g. with Lombok val * * <pre>{@code * val fn = l4((Integer a)-> (Integer b)->(Integer c) -> (Integer d) -> (Integer e) -> (Integer f)->(Integer g) -> a+b+c+d+e+f+g) * }</pre> * @param heptFunc * @return supplied function */ public static <T1, T2, T3, T4, T5, T6, T7, R> Function1<T1, Function1<T2, Function1<T3, Function1<T4, Function1<T5, Function1<T6, Function1<T7, R>>>>>>> l7( final Function1<T1, Function1<T2, Function1<T3, Function1<T4, Function1<T5, Function1<T6, Function1<T7, R>>>>>>> heptFunc) { return heptFunc; } /** * Create a curried function with arity of 8 * * e.g. with Lombok val * * <pre>{@code * val fn = l4((Integer a)-> (Integer b)->(Integer c) -> (Integer d) -> (Integer e) -> (Integer f)->(Integer g) -> (Integer h) ->a+b+c+d+e+f+g+h) * }</pre> * @param octFunc * @return supplied function */ public static <T1, T2, T3, T4, T5, T6, T7, T8, R> Function1<T1, Function1<T2, Function1<T3, Function1<T4, Function1<T5, Function1<T6, Function1<T7, Function1<T8, R>>>>>>>> l8( final Function1<T1, Function1<T2, Function1<T3, Function1<T4, Function1<T5, Function1<T6, Function1<T7, Function1<T8, R>>>>>>>> octFunc) { return octFunc; } } ======================= File: cyclops-anym/src/test/java/cyclops/monads/collections/AbstractAnyMSeqOrderedDependentTest.java ======================= <filename>cyclops-anym/src/test/java/cyclops/monads/collections/AbstractAnyMSeqOrderedDependentTest.java<gh_stars>100-1000 package cyclops.monads.collections; import com.oath.cyclops.anym.AnyMSeq; import com.oath.cyclops.ReactiveConvertableSequence; import cyclops.companion.Semigroups; import cyclops.data.Seq; import cyclops.monads.WitnessType; import cyclops.reactive.ReactiveSeq; import cyclops.reactive.collections.mutable.ListX; import cyclops.reactive.Spouts; import lombok.AllArgsConstructor; import lombok.EqualsAndHashCode; import cyclops.data.tuple.Tuple3; import cyclops.data.tuple.Tuple4; import org.junit.Test; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.function.Supplier; import java.util.stream.Collectors; import static java.util.Arrays.asList; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; public abstract class AbstractAnyMSeqOrderedDependentTest<W extends WitnessType<W>> extends AbstractAnyMSeqTest<W> { @Test public void groupedT(){ assertThat(of(1,2,3,4).groupedT(2) .toListOfLists(),equalTo(ListX.of(ListX.of(1,2),ListX.of(3,4)))); } @Test public void sortedComparator() { assertThat(of(1,5,3,4,2).sorted((t1,t2) -> t2-t1).collect(Collectors.toList()),is(Arrays.asList(5,4,3,2,1))); } @Test public void testOnEmptyOrdered() throws X { assertEquals(asList(1), of().onEmpty(1).to(ReactiveConvertableSequence::converter).listX()); assertEquals(asList(1), of().onEmptyGet(() -> 1).to(ReactiveConvertableSequence::converter).listX()); assertEquals(asList(2), of(2).onEmpty(1).to(ReactiveConvertableSequence::converter).listX()); assertEquals(asList(2), of(2).onEmptyGet(() -> 1).to(ReactiveConvertableSequence::converter).listX()); assertEquals(asList(2, 3), of(2, 3).onEmpty(1).to(ReactiveConvertableSequence::converter).listX()); assertEquals(asList(2, 3), of(2, 3).onEmptyGet(() -> 1).to(ReactiveConvertableSequence::converter).listX()); } @SuppressWarnings("serial") public static class X extends Exception { } @Test public void testCycle() { assertEquals(asList(1, 2, 1, 2, 1, 2),of(1, 2).cycle(3).to(ReactiveConvertableSequence::converter).listX()); assertEquals(asList(1, 2, 3, 1, 2, 3), of(1, 2, 3).cycle(2).to(ReactiveConvertableSequence::converter).listX()); } @Test public void testCycleTimes() { System.out.println(of(1, 2).cycle(3).to(ReactiveConvertableSequence::converter).listX()); assertEquals(asList(1, 2, 1, 2, 1, 2),of(1, 2).cycle(3).to(ReactiveConvertableSequence::converter).listX()); } int count =0; @Test public void testCycleWhile() { count =0; assertEquals(asList(1, 2,3, 1, 2,3),of(1, 2, 3).cycleWhile(next->count++<6).to(ReactiveConvertableSequence::converter).listX()); } @Test public void testCycleUntil() { count =0; System.out.println("Cycle until!"); ListX<Integer> a =Spouts.of(1,2,3).cycleUntil(next->count++==6).to(ReactiveConvertableSequence::converter).listX(); System.out.println("1 " + a); count =0; ListX<Integer> b= of(1, 2, 3).cycleUntil(next->count++==6).to(ReactiveConvertableSequence::converter).listX(); System.out.println("2 " + b); count =0; ListX<Integer> c= of(1, 2, 3).cycleUntil(next->count++==6).to(ReactiveConvertableSequence::converter).listX(); System.out.println("3 " + c); count =0; System.out.println("A " + a); count =0; System.out.println("C " + c); count =0; System.out.println("Cycle" +Sp
1,523
25, 1.4187420034517249), (2830526006618762624, 346.04121016034526, 17.251035026332172, 9.322877780864099), (4955621776810839680, 25.924537017290312, -43.87212213274469, 1.8464983646504756), (4497404807061934720, 272.7022811156271, 14.371405822848407, 0.6353827762284441), (5898024806569713792, 218.01174738947074, -51.402338488676286, 1.095322739082313), (180612308332276224, 79.27057351204832, 32.063740398292836, 1.5535939612225975), (1727973851234566784, 266.84691782140754, 87.69773816372111, 1.7492706048702116), (4886255890317016704, 63.790393420732684, -28.15024968341418, 0.0334803213118694), (5487548081942479744, 112.85398361062612, -54.939297096550646, 1.2482445039311527), (6013747134082332800, 231.32641590867962, -35.77824293390352, 9.440466240806048), (4794633655094834176, 86.7889729438293, -48.456477176209084, 3.330686326974671), (5581608140601958912, 96.73970697593641, -34.79928225614848, 0.9396728525580109), (2791109854793254272, 15.580901406110412, 20.926699838315052, 1.0406613220690049), (5235860696297079168, 176.7618501190338, -67.72268171690013, 0.6138810671158766), (6327021224019767808, 222.17791947827408, -9.258752141586271, 2.916421927775579), (4502721632975998464, 269.25411304929366, 17.057374913730317, -0.35753186064756864), (3817216883707348352, 168.19505050270214, 6.407990952366207, 2.9894159012428028), (3034628212645555712, 110.99889858413458, -12.06173433161991, 1.051516468243149), (6817094412880217856, 327.41650589115807, -21.959603641538735, 0.5520604173868183), (803722384061256320, 151.00929776950724, 40.41377510392512, 5.325852714670872), (5593413493870383744, 112.40099714290082, -30.62131247652452, 1.138912779804063), (4845947141207913984, 50.97739939490007, -47.57290083101666, 4.108134507952199), (1472909727938777984, 199.94688850431893, 34.2618364832827, 4.950371733369127), (4531107449792373248, 281.71301892591845, 21.515625107406677, 3.189791882505194), (2048484342590197120, 294.3745395879135, 36.472927716545215, 1.6681300722135775), (4396946106123467008, 233.93813225840594, -7.403230574684751, 2.1265638885233273), (1755244969421691904, 310.87147797866373, 12.722628616441906, 3.5610307789586098), (5963312157759111936, 255.13295629287046, -45.48320068469501, 1.2165574990465233), (5328613229469973760, 132.762504533692, -48.62053136242687, 2.1043196477527575), (5416682324150578304, 156.36233228878052, -40.557131072726754, 2.3482299421743464), (6473689718612568832, 304.1402619405782, -52.83116749632613, 0.6486446087746072), (1974851045313661568, 329.8609559314486, 45.36651978507489, 1.6929213689993157), (5868685163416173056, 201.26617192300841, -61.447782664285185, 0.515537543867604), (5329360966099856512, 130.4442042675248, -47.43879162285399, 0.913213127699021), (4022420388066623744, 173.76978114398693, 29.42443822872424, 8.385731279595339), (5397804259255388928, 172.0081800615335, -37.02037849887927, 2.126479451814759), (472873150512242176, 70.0655458812453, 63.29804394650203, 0.16925352686641304), (1861082996639446016, 307.865677831377, 30.857580928531636, 1.3347334593659503), (776260294451362560, 161.17310874817895, 39.44386768781234, 1.8794136177011773), (5977512316074251136, 254.61617120601485, -36.19020050399335, 1.7863890427588645), (2894180445603402496, 100.00827911130908, -30.740883098112544, 0.8686746862869894), (2695225568902985344, 325.0682361358794, 3.737151903311681, 7.97320656630088), (3651393281650552448, 220.53980697901275, -0.4350431856871763, 0.6334661609576554), (5377221332865835136, 169.5901259335518, -42.45830293884771, 1.0311211123620525), (2520395248627093632, 35.52015786473975, 6.7579328558154845, 2.1701501431672376), (1935188156202697984, 346.37734953819023, 45.00572896956053, 1.5562192613990606), (5988851167175237504, 236.73337279930513, -45.00991520942991, 1.2141242106717198), (726201179306165760, 156.0307951733571, 25.720156755807015, 2.413154023841092), (5820385885355226240, 238.85974111961693, -68.7333223418782, 1.2406685321323978), (2345281391790784768, 12.524557262225507, -25.478314310793913, 2.195995400854557), (6060931404278019712, 190.33955099168185, -57.7170085766307, 0.7838352504509013), (1310120777975191680, 256.03432164395036, 31.282735469425702, 0.8662975970860324), (2863285096575624448, 4.4695512745172, 32.518811335805125, 0.580769415187628), (1294611547989265920, 221.5593833409237, 37.32146300841378, 2.1956753566527323), (2379260596056417536, 347.4859728422271, -27.267187414137986, 2.2895864429135777), (1106848497069809408, 93.67760836586487, 68.6022297023451, 3.17966998546634), (1385232368637313664, 241.06665789251943, 43.41432780798134, 6.203545956615131), (260264126101313280, 72.04872840204492, 51.06764979981026, 1.5420204801202642), (2069736424886749952, 308.9688268967132, 43.45801957668269, 9.902321556353009), (3503276764602309376, 191.72188057380146, -21.502632398081154, 3.4014588704482316), (5493983901456926336, 115.66711533614453, -50.11173302163703, 1.2552863049248186), (2006379953556035072, 337.5965553718519, 54.88998492171804, 1.3354788043596784), (1968423162894889984, 317.45200202170366, 40.48957908077302, 6.985403293955059), (5976255161967435136, 261.663398599938, -33.179813407734464, 1.4839795970745633), (5857840680232986368, 199.2135667475717, -66.29154169767754, 1.6923064736147668), (5943657425341160448, 247.89916863241825, -45.94882246273465, 1.8016513671478607), (715429023370454144, 136.6350515621518, 36.5459532423339, 5.995874677879014), (782709342465169408, 164.75203634846528, 45.197672181913845, 4.34647074085567), (5798812917460152320, 224.84939324556646, -70.68472023164023, 2.3268065073489907), (1964483440933875072, 321.62261536479275, 38.967016682926165, 1.9392164106305654), (4040573084529315584, 269.26427271697753, -35.00370875429347, -0.06946151781260534), (6193920531113963136, 197.934377714896, -24.479492386128516, 3.732435390007697), (5683669414097314944, 146.1481666125657, -18.516565658615033, 3.46631155950452), (5487133085021509504, 111.3042585603496, -56.561183666122034, 3.4015375149063694), (5928372667525641216, 246.68960187788736, -56.51605613300665, 1.1998718271055844), (2270794083214636672, 316.76724325649224, 69.97760072226232, 2.627570347628124), (6102977347400046592, 218.1624437594248, -42.891461721688295, 1.3546072202343367), (4969734558309602688, 33.94821985964025, -35.33449494468426, 4.097296502449921), (5340328903822527616, 167.58489432434, -57.48368123874291, 1.7588800551516763), (450592440729468928, 38.5837543753013, 49.721303761096934, 1.1370800298602453), (6832871648824178944, 318.8137980145531, -19.33913646617477, 0.509859012626827), (2906731920589364864, 82.04018314411799, -28.718826120669537, 1.6388961848671728), (5516490870116929792, 126.43231222128473, -47.14868215267053, 1.3616680566408181), (2169955019972118400, 312.99621791000624, 51.442949893394015, 1.3225644516412067), (5478311256555261056, 97.92514329190459, -61.68687121944899, 3.6119305480514714), (353116508677732736, 33.407382521176984, 46.024450879166466, 0.6357993218976428), (551059456721773440, 57.924646157401405, 75.83985751985566, 1.5468457870795185), (4189313127746563072, 299.0013763466935, -11.686715940832146, 1.2939637004564333), (5694923293564351104, 126.76913062427086, -26.217376521612245, 3.920675778389682), (3345241140846236928, 92.59292497539387, 14.54680381247232, 0.6118354886470332), (4377515536639347200, 253.26523228667392, -4.406159372967476, 0.653645218390491), (2703747471213326080, 336.35211170911464, 2.770211172107789, 1.269770102099908), (4315033486296512896, 293.64303976655975, 11.061469682756641, 5.4247713039011645), (315782179038729472, 22.60216399987425, 32.231453090580736, 2.629044920192704), (3243003086494696448, 55.39596187535491, -8.054227461628722, 3.802579011326157), (3795477992638346752, 176.1093422843852, -0.3787785071489299, 2.5200365621932175), (2208570933494669056, 346.81609683092734, 64.59509811364772, 1.2831172332693914), (1214360805617750528, 231.75282493562503, 21.310793946631048, 1.3933118699419553), (6279326299392232832, 219.03197590512377, -22.17733775198388, 19.555012849953876), (5956119565007079680, 269.1455246024209, -44.012478252291764, 3.1900176127589197), (317357435603938688, 21.93938475418504, 34.78665496398957, 5.577645619829107), (2070946781032118016, 306.7234028192179, 45.56775092872868, 2.007550308850342), (5092281932453792512, 65.59681665502036, -19.133990063685662, 1.63132502326708), (30494920637286656, 45.926069166584675, 13.969594236891382, 3.535193450520515), (4465669018833460608, 247.12479885710798, 15.906665841394327, 1.6406231384839902), (5234495102853623552, 173.2926581643027, -69.49854480492613, 1.5183498709660332), (1836702494523656448, 301.2599510079595, 27.197303163054535, 1.2332714316040103), (6473667625301399552, 302.99662960150334, -53.11356618529412, 0.7232471635478316), (1205482902058819072, 244.21631451728726, 22.13658496718047, 4.837472045287775), (416372787013975680, 7.946703566176018, 52.525546821257, 0.7972902235893737), (271669428936079744, 63.832142883132185, 51.23977987944259, 0.7387597336012263), (5858574879124227968, 194.12769420738368, -65.5937870139083, 0.4132590004589913), (1125113481151275904, 128.62856789295773, 75.3243006948283, 3.9556337668965282), (509888106380399104, 23.181667645162925, 60.96995510437262, 2.0383671827108714), (2572968087871786752, 23.132766773062325, 9.152843798084396, 1.4684204712444602), (556967441935106688, 89.77783778993347, 81.51444138328887, 0.8870404108000629), (6432404019063848832, 272.56022434991144, -69.60025568673456, 2.8108846630707753), (1836381093531194368, 302.8280077627017, 26.456145916803194, 0.70101317449723), (5630983428235250688, 138.07703920720468, -32.948873604016924, 4.64006654570178), (6104721378999918464, 218.91516479831026, -40.97614545207886, 1.5906321328050443), (5222986892602285696, 137.45472838932344, -68.74923895921263, 0.37181797920163007), (233377562108104064, 60.76812116226573, 44.952825913675895, 1.2206136157615424), (527117178712042752, 9.787535702533042, 64.90179816448324, 2.188358007481007), (5716385520020384384, 115.11689120150317, -19.42779122142832, 0.7287790017082457), (5253257787743429504, 152.09940818994292, -62.00119128867432, 5.121210707260384), (6758064794684880640, 289.0057732024652, -31.009188207173015, 0.6140897356415441), (4798655428110525696, 83.02145714772075, -47.015059167926296, 2.1140608071799223), (5308936472458446848, 143.96935273345636, -54.60341374079018, 0.8278967573299161), (6527318466977270528, 348.40691839282147, -47.432363963317215, 1.5909070820941826), (1403225292310635904, 237.01873352383444, 49.500500647032396, 2.931451933814655), (2016540128191459328, 351.7068697947064, 62.58771341672006, 1.8292097870130937), (5696919422567140480, 126.57501381506954, -23.141680952111994, 1.6733494822115993), (5589739785003483264, 112.21508555059832, -35.38943015369078, 1.2219342230811439), (3818749087520906624, 169.5284891353153, 8.624994549477304, 1.9934444203661064), (222747552410244608, 52.48303382233736, 37.414948483560096, 1.870294877376601), (4168822800846435712, 266.9092120281861, -7.380593288320855, 4.105518328588298), (3932848570230677504, 186.8852861777807, 13.806228867190939, 10.246030478922119), (3714890215593557120, 203.77788491339174, 5.627894099839553, 3.250931366430482), (1963183302796971520, 334.6666415825447, 46.27437354671615, 2.395858785519043), (4816710611629363200, 73.0644976527315, -40.82136404118863, 3.951275986703303), (133403024244054656, 39.12666940626046, 32.362637382803385, 3.76560932287828), (6431839488562979584, 279.62055547112305, -69.534118471139, 15.966110381026658), (1538833352764253184, 184.39780360102463, 44.49576710887269, 1.6894534876868512), (5438410013944361216, 145.4072301070161, -34.42381200080467, 0.8703042423014257), (5865378038597854336, 205.20852430658417, -63.31284658089344, 0.16580134423126824), (1019195258305145472, 141.37802969356787, 51.542269024191924, 3.202696808407265), (5270832072365322496, 118.47984854551065, -68.8988683191798, 10.109637566031621), (424416092528686848, 12.760237372022052, 58.106822259472395, 2.9162132964320957), (491118927499887488, 51.26729602560598, 64.9789083083121, 0.5463098045196305), (5348347367249563008, 170.59046657951697, -52.95963641085876, 1.2221555489393259), (604865810573298048, 134.53622272001556, 12.283050129110592, 2.062988666522427), (6279806476735227904, 219.17875528210635, -21.215739139335195, 1.043464228710801), (5367603423620013440, 157.49371988067432, -44.47990855289482, 0.25677239997147583), (1290334722634984320, 228.033065154199, 33.417415384985354, 3.531726464815959), (6749020624347223168, 299.7514198941098, -31.32866279924678, 2.7611387695097793), (4381431069343349504, 254.51087602288987, 0.9477092822938804, 4.642884272097864), (2744937375812753152, 357.27370431688195, 6.971301130387611, 1.0292650402041412), (3032465370196703104, 107.63583488591841, -14.022337751195906, 0.48728647831679983), (3367757317915678720, 106.55988287488222, 22.04919683002708, 3.465488347860541), (4834452777931868544, 53.52354494548044, -46.17390138533675, 3.7969513461735795), (3027178437249875840, 114.89414854821756, -16.96032659616763, 1.425183521655565), (5852829415470346240, 213.3070065167148, -64.57033769479136, 0.9443655743673606), (939137411505861248, 104.01281558823325, 34.00949504200221, 1.1392434007110186), (2589987325278730368, 19.044811515231686, 13.735363503756108, 1.7644075256984708), (1114905305961392384, 103.26152924355944, 74.13694910715121, 2.502417439211392), (5831881519940833280, 245.68897321271155, -59.58048134282377, 1.1127628609816684), (5854018434215451136, 213.45449820446248, -62.8012811946857, 0.5559584786596339), (3612897317977337600, 209.40107698118297, -11.619488189693984, 1.5072421895725765), (5519895954549204608, 125.12661246482025, -45.24332341070068, 1.0482022947588814), (2214059351939748992, 353.31256154535316, 69.04085636640698, 1.8908808877354946), (6855699125126375296, 307.4493419000912, -22.644788137826666, 1.9495652005617536), (2059669055911620352, 299.0922577286979, 35.988016435640844, 1.89223834923887), (5567029990807097088, 93.11341217949584, -46.32608710640933, 2.107386984542032), (6063398845813193856, 198.38123921309455, -57.22978521349384, 0.9115054973476073), (1637503113924035840, 261.046677717379, 68.28546712559243, 2.101414857818521), (2045944127132047488, 292.091273025196, 32.7174280459171, 2.591761938383263), (5379729112728338560, 179.89151406390016, -43.62067398513582, 0.18878541993990183), (4318472655583276672, 295.0443009657632, 15.028837290247445, 0.9271557638416617), (952208611895116928, 103.69020018662954, 43.80308737817197, 1.2547691344188816), (2875563033685146752, 2.82857875976512, 33.16838421731817, 1.3449509719755985), (1571953391771538944, 186.57149259545875, 52.79504265779474, 2.6590935719271904), (4233052628009846912, 309.6647747389148, 3.5995387444136235, 4.909120617640583), (3849914366652952448, 147.990970936268, 5.238270556142784, 1.5807464871946135), (2049466309556687360, 289.614049572396, 34.218886098995824, 2.5010920860729993), (5270111376851905536, 124.33133478769682, -69.46420325546399, 0.7064576787341842), (451777645544090240, 35.74988901377472, 50.78927580049973, 2.2971237812113543), (2565360017163301120, 22.34636595979645, 7.041137582704766, 3.6988610054640647), (2929112170535269376, 106.60879740900148, -21.454359138454333, 7.844578592851138), (3742701125267293440, 200.76929515953384, 13.484694408369196, 3.6336555643025386), (2406530133692368128, 347.5274900206437, -16.279976034002495, 1.650915570182242), (4051223263392565760, 275.79254957047146, -28.599541265619138, 5.264248624043519), (6605001746618421888, 346.4563897940413, -30.65954480500622, 0.8891812911488819), (5453008229826224896, 165.3258758103789, -29.53283210378577, 1.9984945759301322), (2223669255366278784, 324.5123175831121, 68.41404043134911, 1.3912184867505448), (5253286684286472320, 152.7148891918705, -61.59199602229316, 1.6928007656274384), (5720867266856428800, 123.13497410435886, -17.119423169494095, 5.523076054758523), (5288993255675928448, 114.7450244880347, -62.78221471254181, 1.6052177806897205), (3473349363764305920, 183.7168228312252, -29.385326722484518, 2.310608385490202), (5364544376112415232, 160.23787920630048, -48.24540608109143, 2.3526982076513407), (5592358890422978816, 111.2187660295076, -33.86670381409532, 2.1032220398245176), (2022749139072475520, 291.4623314634305, 24.248865235340638, 2.671450427534691), (913597680537408512, 130.3612600879451, 42.24536344646998, 2.472438611919072), (5237923895515940096, 165.7345461323568, -67.90902007932756, 2.7954174059914334), (3892250890081600000, 178.67896342276882, 1.5086581743299912, 4.92562039327512), (179687481612480256, 67.51507216293022, 39.546866776586, 4.3702373246128685), (3047132099394853888, 109.55928357691363, -10.457891564801482, 3.011281863526902), (438469259879459072, 39.66232147981243, 48.670923588117006, 2.4121445529336665), (5887286117018896768, 229.81671921995414, -53.44861615219435, 3.4160448568778863), (3322416860000846080, 91.46320569555515, 7.531033362172423, 0.40721783775833), (5058518266826196224, 48.324963238261624, -29.54691342011923, 3.0492898276636486), (5052201469445843840, 42.88968781263473, -33.24813386838141, 2.3986574031246595), (5233720531269728640, 174.7905375012427, -69.89639231535608, 1.4816387088679306), (6738985519161262080, 291.6512149610022, -37.790870184437, 1.3851382014524505), (6426319527873025408, 310.41475500710067, -64.64374889995736, 2.1635063091848363), (4181735018728542592, 295.9868295600879, -16.205920107991492, 0.7149874364602994), (6357413237239107712, 338.89104077901055, -76.4802833265323, 1.1655012701444172), (2000106208928355840, 335.18340532976566, 50.491617421218116, 2.3961411091941907), (5334208644143814016, 174.1451072059824, -61.60977131039614, 0.13981761550319782), (997015806670377600, 93.03772094530686, 54.91060753724836, 0.8926809666908175), (2900734496977219328, 83.84012066144933, -33.693820134289325, 1.4178025202617222), (5717433320242086912, 118.04955029042682, -18.600602995082653, 3.337729716157959), (4549615906979841408, 265.1573049209543, 17.440171991625338, 2.0862365741494977), (1142487998252715904, 116.42220200262057, 81.68106627334402, 2.269259432931584), (1867116738492647040, 316.5355153842309, 34.22758922457392, 0.24805026130853663), (4983077922186200192, 15.462261276757443, -42.97024124148906, 3.754098803257677), (6119782661076508032, 214.551799461727, -34.87586497465279, 1.3551842961538365), (3150288795707790720, 118.07824478243039, 9.918790736479467, 1.0451335158371817), (3439461109726183552, 96.62275276931442, 33.20300475952703, 0.7008725904448819), (6690441256161188096, 297.8156050984177, -40.128360816845586, 1.3820129324613437), (4046695989900240896, 278.8246407107933, -31.679323901655927, 0.4994582920006787), (6230923289276178560, 226.26057632722038, -23.186100629326067, 2.625253901057545), (3154571771456004608, 106.04869135906556, 8.355259699118303, 3.6598303551004765), (2030560928671658240, 300.9555919129441, 30.06203458706574, 3.561768104666807), (4674195797087268224, 54.36886334771803, -63.11526372176608, 1.9804623492477726), (5969539413667949056, 252.9469935467038, -41.51774658396955, 2.0659306896494725), (5336492845190619648, 172.95519835512323, -59.30091395091174, 0.10516740664094892), (5515321127187471872, 126.47793039533805, -48.70433843438456, 1.4719769388084898), (2150217824180666624, 271.3030827615164, 55.73465769380498, 0.6848942196360501), (4051449762784030336, 275.8810687436951, -28.17575397528474, 1.1660369339878698), (3861650759925892224, 153.52079815024186, 6.073787436501805, 1.9088348109952313), (6175165474083836288, 207.4109210331244, -30.301159913696463, 0.03465856822440827), (5526196431054920064, 127.124982606485, -42.748187772797635, 1.0154033819264716), (1290759099763399296, 228.11378961861075, 34.92607717076539, 2.059087701793132), (4486067880105883136, 264.59387025833837, 6.68465686707325, 1.7350891744803), (4608947341121174912, 266.71408840664765, 36.23992092964818, 0.9057402950718474), (2116738760266763264, 281.4009409067968, 42.61273658595563, 0.09417645098619051), (5314838616520540928, 128.6516900781199, -58.433040026183626, 0.8796305386199914), (5229111653408530176, 159.4349208799568, -73.58048068410824, 6.357299607134782), (1846196055874939648, 314.3055595025977, 28.0518705347503, 1.9302054149571979), (1268236016385270656, 225.43157196347178, 26.67857379206736, 3.268324674149956), (2076154583500455808, 300.14448696880015, 44.83925659877828, 2.9738623627479925), (2144780292505181440, 281.3625655734445, 51.98383437355378, 1.0290840190611052), (426042682545126272, 14.537680217244514, 59.51456615240768, 2.480096012653447), (5827853768330131840, 248.10252159004858, -65.0120865931764, 0.8418240823255377), (5598111810134895616, 115.1969355057555, -31.58831833147994, 0.4356700622884133), (2046983749738521472, 295.0028441206143, 33.608492880263796, 1.3883002138948601), (2234844691551130496, 299.9814543514457, 58.00254538159452, 3.3940575302720024), (4654587244163108480, 73.91199939067002, -71.30486455081903, 1.9282326154304523), (961142590546365056, 92.86419914143117, 43.34081493875276, 0.4573504970153388), (1264896524693799040, 225.93740196364644, 25.202137752013147, 2.339628838607723), (3561586649362559744, 169.20189282340607, -14.508394013054634, 3.728274855239163), (1468564045669136384, 201.86230107666194, 31.58259141747948, 3.332887952898827), (2252289233799260672, 286.0561331790548, 62.87487171560671, 1.666280285405422), (2613816319232980480, 332.142381966665, -11.613630686308335, 3.6597208578123035), (2157047646816762496, 279.6227938854845, 62.2585847502025, 0.6944984277971601), (4082807834412441088, 289.07541029627026, -21.112057000932126, 0.916157296082261), (1019092969363343104, 141.36795704617717, 50.90887300157355, 6.261407082273488), (6407364291008030848, 339.46259079530506, -60.09466740254835, 5.18376853669625), (5523767541148736384, 131.52182114967917, -43.998831465292696, 1.4412564044121359), (4892239638753721216, 67.2481824875029, -27.180661400068587, 3.676408372603621), (1227138298963564416, 214.3529251292599, 13.90182146690255, 2.4095833400493567), (5531248515190355328, 119.13291041905732, -44.68756638682895, 0.7482927375544657), (448566521833968000, 53.49696837659588, 56.3632251960956, 2.4472124251476677), (3119138325622417792, 97.73174582646561, -0.934101883974705, 2.979101511355878), (2073369039510990848, 297.9821086213974, 39.11039561069279, 0.7996665018731224), (1824200050880816000, 295.559052396417, 18.32520203988752, 1.2045896357181425), (5149823602182325376, 30.530869780330434, -12.556536830382633, 2.5346331345648743), (355904114250486912, 29.763952405308775, 46.20068141368823, 0.9761235908203448), (5512781495842733056, 118.90156395359, -52.77581380918019, 1.365173812002825), (5989729608245265152, 236.26999386598868, -42.6039914056088, 2.2675374822004852), (2086365473103992192, 297.408333058295, 47.11751510204871, 1.9512239455674765), (5240040627190138752, 166.57165790044112, -65.50979648441167, 0.4519843161290746), (969777124078648832, 90.08775065214041, 48.24147952934052, 4.088458353610215), (4652429761824447104, 71.16076163438538, -74.17644730519027, 2.1439283060943803), (3152878248669524224, 105.81333510763838, 5.851490295523451, 0.9601676521258968), (2692788226502832640, 321.48327874996335, 3.5694124158279954, 1.6273132422545307), (999031864318526592, 90.72466365046729, 57.25402542717365, 1.166218314531098), (2946144327204999808, 103.25970251841666, -16.883171561925497, 1.36702847131966), (3342293899926002944, 91.62618806481352, 11.47403140963755, 1.8320965881799152), (5159702439280493696, 47.03677768125284, -11.778886087888484, 1.9938989526030377), (4314820799507154944, 291.43653214637766, 10.802734251771431, 1.9449680139176444), (5234968580052267264, 171.41621345131665, -68.63627809266222, 1.7115113193611238), (3962144610876142464, 189.415771302667, 26.797818793620753, 1.1923675460092453), (4862283788052384384, 57.31855701274884, -33.49850861512826, 0.7204470394832402), (4082768183269985152, 290.57717055629325, -20.55625744625285, 2.320069579921449), (5426717360617923840, 143.39847061471838, -39.83639486521697, 1.391168473555723), (4253180528398675456, 280.62273974599714, -6.571049748057031, 0.5009903635691965), (2974842061724870272, 76.32972381847793, -20.90864434503295, 1.2772935361218616), (5229440957137694208, 163.37837987164167, -72.36923575870303, 3.954976311107853), (672613353390102784, 113.98758596232804, 19.90572399688591, 4.422749604100172), (2119029730182173568, 281.16732045863506, 45.83605538522691, 0.9930271739789162), (6663000538309428992, 288.17513658688836, -45.53119451917435, 2.626205026265772), (3624091823817933952, 199.9211159334714, -9.485243492621885, 1.7550738806323738), (2139439277335851904, 290.1702411587975, 52.703534407781326, 1.4896303633232508), (297121405131041280, 22.307657344428126, 29.020837485292454, 11.24589779468044), (2192664951607798912, 317.6002043712627, 61.47399285924118, 2.3175371944360794), (5249988974037573632, 147.29178807186167, -62.692257496688235, 0.7054020409133674), (6034556731670156928, 252.47485352579466, -26.26768277100491, 0.9201149155136467), (2073383023927993088, 298.615444862493, 39.267025416740665, 0.9780274974458047), (677731648737092736, 123.50616797733653, 23.896836652817885, 5.074814842697485), (5390375752541615616, 165.7697624062597, -40.56862642443146, 1.9334511123720732), (4567399854725310592, 261.38462436261483, 22.017750946554823, 0.18035334001318148), (5370926113399237376, 176.79008078659805, -49.488088399079416, 1.8144726275021599), (6117263130182717440, 213.15041404647988, -38.51289827333982, 8.533607688161156), (4231972117317300224, 311.41889256484194, 2.8049676938424555, 3.3078241822216174), (1958149120089747840, 334.40508219030005, 42.04200216537368, 11.477758073476846), (1683262245251176320, 185.7036455172627, 68.52479834574213, 3.617247688608076), (4764427424979314048, 77.82077042019226, -56.05632228379007, 19.604542258186896), (1899832947494658688, 330.28959773142583, 32.98604959944388, 3.51639507605565), (4298307749765409536, 299.3840379647007, 8.26647093153099, 1.166077294200388), (1209748972814639488, 233.34181423354445, 18.958469162856048, 0.6772293516147636), (4292180343261960448, 290.42534594117, 3.7359269431468025, 9.516169827013282), (3410640676579205120, 68.22486712847396, 19.098816438540663, 3.326735793288192), (5074201872483490048, 49.070044114316644, -24.494871611971703, 2.370060406649311), (5612044031208059648, 112.3734195604268, -27.491210795969927, 2.098112915893667), (466321332519336192, 46.396247950792194, 61.9399080971993, 0.5715061940352044), (5341285204059252608, 179.6847555887345, -59.977394771705974, 2.308595862842355), (6435688397733408896, 272.5712711096799, -68.80413204405122, 1.485782250749425), (494418802411333120, 55.89160232368322, 68.96177887428692, 4.37892346867036), (2739882371103852288, 359.95020977258923, 2.5066488568383, 1.853575090323956), (6754948881806604416, 298.1421302838173, -26.388504830552527, 1.0068992663050653), (5727374142307569536, 125.49029500250153, -11.35471823345759, 2.3481064102360487), (4194917372869681152, 294.0586434908803, -8.311671345132668, 0.6118044879313128), (5915775768964642688, 258.8687290639412, -59.18442144323557, 4.254881740298463), (2674427550549786112, 324.15650869721736, -1.9820597545190806, 1.5177425778943994), (5952172146465960448, 262.48441286799016, -45.617285879143765, 0.8264075834539781), (4080567235867854208, 285.97881517655816, -23.60225573691977, 0.8223767952271842), (911438102260752896, 129.137621751162, 38.998758913313814, 0.5004985814879435), (458912410854533632, 36.72687927842633, 58.330675952088534, 5.425982354064892), (5793864049981919360, 224.73713625634966, -72.84602821564334, 1.4276117565511115), (5385963618535764480, 174.85846329143803, -37.246860240879265, 5.147245561504561), (838681390626464000, 171.71836511153944, 51.689375021285706, 1.9611013891671079), (5319015008357691392, 124.66291751384608, -55.31067848286271, 1.8223202026986962), (3238155992562665856, 76.22595059278281, 3.1794850444765737, 1.0283765513341105), (5715252542009536128, 116.37858582191744, -20.77084712880515, 0.9174958288230867), (4700195089555797376, 37.31376980772112, -63.847051900762914, 0.5709415395372448), (5438661149270777216, 147.6470348690856, -34.12803957758969, 6.286768546895017), (5624370518631403392, 136.01821987601534, -35.04269506126681, 1.2300192437915256), (1783757573669861888, 320.4390935129516, 15.7332448427315, 2.2179840306380663), (6363209037907578624, 309.5364923317182, -76.89278292963769, 3.5182189068473395), (5336262050832688640, 174.7362362721547, -59.648182367467186, 0.21443497032207745), (2244592137009306368, 304.6304186984249, 64.38759246520878, 1.067503803119444), (1248167558356634624, 206.70613188637319, 18.953310799954224, 2.9435405600814497), (4657770124169458688, 85.80183118978645, -68.59322611769807, 10.142041743095046), (456025024602109696, 32.67424285759965, 53.25038932741075, 4.045097062525529), (2005225191468698368, 336.32348654007103, 55.72713243637295, 3.489756958352201), (421390958081345280, 4.965259961639824, 55.5119370762876, 1.298212219053817), (526633153075351040, 16.015266509713467, 68.4212965603952, 1.9684567773845427), (3381980909569514368, 103.47535842549924, 25.997916989028425, 1.0365400687012578), (6555882816994383744, 349.95458298469816, -32.797157395111135, 2.2654601469328197), (5244931323625211136, 152.68603581387902, -67.01093864310494, 0.8200290617924832), (1324800254637254400, 250.05619534602783, 32.61634872208704, 1.4262238155626163), (1303459524217229056, 244.8727775915088, 25.88554955465206, 4.351274236744004), (974238839184824192, 108.95374781553765, 44.86630259004608, 1.0463437025905407), (537828277391412096, 6.318002313964739, 74.21690721458504, 1.199671269399644), (6598723191626059776, 335.0245318206411, -35.36494511060082, 18.289773658285043), (469870556054189312, 57.52537787869584, 57.30418497924589, 1.8472622671874157), (4931528900066403840, 14.26120397488457, -50.35818827240874, 1.0119666642218024), (1253457274437897984, 212.099630926953, 22.012315289310344, 3.1147231856754187), (1996201533900536704, 352.2197429322342, 55.59347277999909, 0.7530390596962755), (6649734930518047360, 280.7745824066614, -56.060524653081, 2.5762528791795845), (668351749400446976, 117.94810978737901, 17.948464751788933, 1.1937072314154), (5862303872806033792, 195.52191796956026, -63.76957375436654, 0.7964933994156185), (2143354810039082368, 290.74472557746185, 59.066059290381276, 2.942441433790206), (5451406516261887744, 162.181634362806, -31.457759316573455, 4.487509758579495), (884801848962440320, 106.12714684353435, 28.95931596959646, 4.3715974093443055), (5248297753352758400, 138.16765832503071, -65.72777570575195, 3.839554134975745), (5264283106233402112, 113.83310074478534, -71.06565791178745, 0.6297611462876277), (5514126198562644864, 121.28770381295328, -50.69874750944429, 1.1985428271314473), (4315057400664038656, 294.41620816794125, 11.389451179552339, 1.2803605044699937), (3442300426708228736, 83.05129609347725, 27.376770436919095, 1.7182310803919887), (5958912805582097536, 263.3168434068356, -42.479391111527136, 1.7665002763283566), (5908790743392279936, 268.72443589231847, -65.45214286319023, 2.4536862076038566), (5802900661172286208, 269.5764185909855, -74.95362251990416, 2.1065641798199257), (6148420918891849344, 183.93938356618844, -41.471448277373334, 2.349609232879823), (474871890851148160, 57.3629454601881, 61.6086939311866, 3.6166134962461163), (6099711694786347264, 219.8221815398474, -43.87254755850905, 0.6041589993470976), (983119113566164992, 113.59989604570718, 51.48352747696037, 0.4694006696215718), (5331197665912895232, 133.86016732860517, -45.759594429952095, 1.586993808185308), (4500873285212516224, 266.6766553518928, 14.996089127175308, 3.567236039149206), (5354993330919743104, 155.3214201595609, -56.13977403609152, 1.0535234643912545), (2493199206471192576, 33.7022438556881, -3.0358443270270232, 15.783617014674018), (2990553876727448704, 90.48613586323825, -18.503917844359968, 3.8473493921682604), (53412178933319808, 60.20238103145424, 22.454513405293195, 2.3943684908017473), (2001292238377190016, 335.8317768538556, 51.44712888375802, 2.883592158579775), (974666686647062016, 111.12968972747758, 46.61273394816398, 2.3283281643665488), (4577916236768302592, 272.8445590702913, 22.238314360523905, 1.269312578823794), (1162407335017685376, 230.81587853127323, 6.580110452996836, 3.51816068142217), (4619601986751307008, 36.821299095373256, -82.01946320509006, 5.260788003992356), (3069909410475158912, 125.93019278099925, -2.8644409230510273, 3.343463611589913), (3859436068630269312, 159.68661460666888, 6.347365065876872, 2.672046991909328), (2023440628804793344, 289.1248707845643, 24.59897486616, 1.4009071233724262), (2586199164123625984, 21.08803479142849, 11.018880141880093, 2.8991244388139172), (2172233963980740224, 318.72698113773487, 51.256950962777616, 2.1177036559103426), (1326557342938137472, 251.05979263795786, 34.32771917521605, 0.9839971800935915), (6762692776560731264, 286.9911296634603, -27.714524175829546, 0.11512838522639489), (2295592056149529856, 290.09608361347875, 81.58889411187164, 2.5483301244099543), (5494124020469110528, 114.15278333674561, -50.08998036131952, 1.2883757815412606), (1870706300359306496, 311.8860107524578, 36.091050806755455, 2.1858542231875604), (5517659101226840192, 121.952318275754, -48.185246374049356, 2.9055517489683274), (1833027170757564800, 301.3366375857912, 22.719526894375345, 2.5154768783019086), (5608611046668394496, 102.5735801652329, -29.376998680518717, 3.162737020830801), (3205576878916518016, 66.06010732381735, -2.457687309911361, 2.793167396755438), (5854500844943412480, 213.67175905628008, -61.74922462761723, 1.132883076840709), (6006411295582517376, 231.43479020967405, -38.989091418525334, 2.1704036819165102), (5531605650305459712, 115.37891837554594, -45.757265802211776, 0.7680907298152498), (2144992326450172928, 280.15249109431045, 50.86926531153153, 0.6012371961578716), (5210227197599549056, 124.35957636239083, -77.25747767695552, 0.2921965920843669), (5259525381980632192, 148.88425935344785, -56.935611662169684, 2.0075148873740707), (486745207682119296, 52.51406337018693, 61.71355553713749, 5.354615498143564), (3103070406292321920, 97.99310875463321, -6.627631531864673, 3.072859739275313), (4477258077548054528, 277.33245882137527, 6.8514036434523815, 2.5394867803461687), (4302161297510150912, 293.6067782094795, 9.08687678558831, 0.29163666289155943), (3568898504766007296, 178.94095507910805, -15.82946053411928, 1.2199236730583967), (662893876759010944, 127.18685061270394, 19.146196368880542, 0.8538950192820673), (5371365196497574400, 178.97264462387113, -47.79629667017225, 1.5776712607685826), (4100803781738538240, 284.77957633389906, -15.251903892075122, 2.8533093961709874), (501055592035538944, 62.99115640597187, 71.48213214294125, 1.372044749535735), (264452234610990592, 88.33832581005414, 54.60230213292899, 2.4723247134868918), (5070761809837819520, 39.85903638518323, -25.569022998567664, 3.1368665542029732), (5276494832125260800, 124.73568709269517, -64.16750313011013, 1.4086980835611906), (2053664966502414848, 303.4571513825421, 30.359868666091025, 1.3912961229668614), (5423098730410685696, 143.4102469761871, -44.873604041868404, 1.6407201024171845), (725887268736206208, 156.5175451732339, 24.857208846482138, 1.9352890299633008), (5380771724630610176, 175.76642740588758, -42.499621492500864, 5.141262387364778), (6041838694102211328, 242.65224967200697, -28.33132625950039, 2.240946820636519), (4568136905473038464, 256.4270212184066, 21.905675077019836, 2.44235732607099), (2739715588933902720, 357.98949023014546, 2.6781547538838564, 7.488990145700428), (3431985495811511040, 95.9555886380729, 26.096159225969235, 0.31994560073727774), (6057244604352615808, 196.18474062085545, -58.19610653475913, 1.0941573305914156), (5630295340113468032, 142.2778002598738, -32.75315878366481, 2.9544584299611114), (1945070875950715264, 356.8932523991781, 51.97616656214928, 2.0656502300886808), (3055925065680358912, 115.61080766006515, -5.934323371690814, 3.454279762023264), (3290275661218462720, 75.40834606276245, 8.575047403848778, 1.0272302655685328), (5534523410571178240, 121.57102273684225, -40.55608336141546, 3.711231927005032), (1406555678671483648, 246.46868867178455, 44.714818594402495, 1.7082030023174468), (2148025775952330752, 278.2447422268006, 55.80949321234513, 1.4901437793908843), (3503442000584124544, 192.2934693434655, -20.608284623147, 3.526618711280623), (1266832695950844800, 221.68214048819127, 24.582348450907514, 6.521639090403135), (1108900426285068800, 111.98179049498846, 69.9618400925485, 1.345434221021636), (2076904072472088960, 297.6141631874309, 41.59285846865607, 2.357499573703043), (5190473509133893248, 167.79709449374124, -86.56799934122702, 1.2731397961024564), (612586787382143744, 145.8893224010029, 10.251941702286809, 4.808470701787907), (2772311195254793984, 359.7187826568544, 15.836945947017242, 2.450594847884151), (2950393630408075776, 98.39025231362882, -14.858910545667264, 0.16946602548195178), (5329553071400955136, 131.8295316875551, -47.315484965759545, 2.764622444435279), (3081137417060773248, 119.56686583507228, -2.8044059407750908, 1.3607252409568182), (4154497779249220608, 275.9036451858856, -10.00301151231369, 9.224761172086065), (3885494597287630336, 159.0107434383495, 13.545087546418994, 3.1506116536270397), (5353030427788558592, 161.65438820221195, -55.19912645465457, 1.8264376155350444), (4054220394648377984, 265.1662846623096, -32.18864827548507, 1.7034842541412405), (3196060502698588288, 64.16199016005208, -7.304055753360144, 3.9650763901518333), (6521408042221712256, 359.51262369555263, -52.87146836864382, 2.9879531840355686), (4699791465709481984, 32.896167448047535, -65.47907671867146, 2.6927379172556036), (1117763830034740736, 136.5630549805766, 69.10302037699267, 1.9073636413918806), (2056175770023875072, 305.90185843323195, 33.63742213174493, 1.7933607058933367), (6122544496846966400, 211.19268228747566, -33.644714606220326, 1.7895452408579908), (3104982250855229184, 97.69721505751605, -3.7131567535826657, 4.764050013283288), (384084322393512320, 2.456378573028078, 41.416107574214216, 1.8567267983909148), (6582080949268384896, 320.94541424598236, -40.68018317472791, 3.14783180627141), (5278733953195312128, 93.5508168738564, -70.19889094708108, 3.479393727549088), (5552930197290976640, 101.82653613557116, -45.29924046394433, 1.3430806634548922), (3136863380774644864, 115.37980937850931, 3.050729866958867, 6.164676109658944), (6733112134203018112, 278.5783168887964, -37.21168137947029, 1.3579440434787549), (2007010592194383872, 340.128422516412, 56.64464366613173, 2.073438146258948), (3568515840359800064, 178.8300672089475, -16.07681991036094, 2.3473769697949374), (4520994244921200896, 285.18003161301885, 22.626999151857888, 1.8910523615001185), (463224042624252288, 47.70197457409412, 61.24075326698759, 1.5771812257818254), (521596908786326144, 27.043104328006034, 69.0893940982564, 1.0745568645891401), (2222892347321151104, 324.9738557586395, 67.93215355234031, 0.9479785994057354), (5715451450532825728, 114.17754411396113, -20.585057180936282, 1.050702587206974), (386716037833316736, 0.5467623872721797, 45.923459162894, 0.9936635142715852), (5603590573496742784, 108.18126488503607, -31.668265358897695, 0.784444471483071), (5577899522241099392, 105.28583902083301, -37.14076979223129, 0.5015905637225372), (4551299946478123136, 266.2652403510608, 18.603276814068906, 0.8553829360187893), (2028006934957943936, 297.49858127333096, 27.62803576762055, 2.400630081191889), (5328420024661198976, 132.9571756704272, -48.778937931511905, 7.930354135922643), (6494595042429221248, 356.3504933249266, -58.39388617614965, 0.549761122910462), (4733553001032469248, 49.4051027301659, -55.48255804083893, 2.4868157828408104), (5444250928947516672, 158.42604791660588, -34.752900202920344, 1.243210687824913), (6131001665409846528, 182.51595380481012, -47.43261502354074, 1.3957418616039772), (4295001243422994944, 294.8287923212217, 7.412151674272096, 0.6815898347627526), (5607801290716669952, 106.34556421826534, -29.719955840893398, 1.9364454987620512), (5914540364573118336, 256.34792621158476, -60.45495756963599, 3.8480540282126836), (5380020552029367168, 178.34706704049148, -42.64814722457387, 13.814841542020044), (5590373687816618112, 108.92209625230727, -35.05448618922227, 3.2398037344294073), (6657691649493217792, 286.1448145363574, -50.974731011552294, 0.9276804270556739), (4084525065413327616, 289.2666213670468, -18.306088812115366, 0.6127375132166742), (6094575601095666048, 206.76269925637047, -49.065633746769436, 0.7746113891248068), (5537517689968574720, 117.55734142857561, -40.17254243626973, 1.1790732876108774), (5246003381823397504, 149.0190150997696, -66.12275172221123, 1.2573890494249977), (6435719596375852928, 270.33675369938624, -68.84633005143775, 5.828256586813146), (5598181010647936896, 116.45572234010167, -31.1393081158229, 1.0880157991974109), (458497035977388416, 36.06353359945872, 57.67524957283614, 2.814897812412698), (5348814934565309696, 171.92724992050034, -51.15560736233971, 4.047576382879919), (5805826805210292864, 251.61649759513776, -72.83984664985182, 1.9991267303647837), (5317598150184148608, 133.0916554669257, -53.271091194977146, 3.747584450612042), (528773764777372416, 4.618611636230403, 67.58638153696117, 1.3541265197208243), (6268081490895584768, 235.86608357439434, -12.006510204408784, 2.4074048399736077), (4813783539877151232, 74.59478519167504, -40.34208441180233, 5.559275855824612), (5443254977571878400, 161.27687391328854, -36.40055399073813, 1.8672711605091517), (5385663486222309760, 173.33099620449727, -37.861977230251235, 1.9267264244320876), (2915128719091709312, 86.50575465494455, -24.760220645286232, 1.023127634762143), (5833799995928627200, 235.31261838859712, -59.72334496855475, 0.9053629745684227), (6158571507158275968, 188.7253807404871, -33.735801789248484, 3.6905471563149748), (2940411301777661056, 98.30583044998345, -18.62565780279195, 1.084655583566424), (93954814781707264, 29.407954129387974, 20.12504010260109, 1.9639593735034402), (4582904343065274624, 270.32937596601374, 26.879642053241835, 2.2924992244563107), (5252436521276938112, 152.74394236451465, -63.907966507429755, 5.164544863947963), (4486402166002295936, 266.4478866292659, 7.375467300548371, 1.3321375500942887), (344622575194748800, 30.602661747452437, 39.52786293269187, 1.428782415914207), (2667950430629161216, 326.1124356671548, -6.206497485732822, 2.2967552064523136), (3875932763135794176, 155.79180444764353, 8.652054582870418, 2.3902561202579196), (5335233629498903040, 179.66973190147743, -60.70280815562505, -0.39299563006741794), (6620991841141589760, 338.7711428411814, -27.471936871039972, 2.576376397430812), (4800713713878201216, 79.64143144942653, -42.86024852405683, 0.9626867345254524), (5297994545055665920, 134.37328707797516, -62.89719385411427, 2.8543963312581506), (6427358566360812928, 301.7711290204492, -66.93281222265826, 3.0154841718863232), (3346332337417317760, 88.0712891809609, 13.033230651036368, 1.183524905483395), (5255449217497851008, 155.5690094120537, -59.09199465348353, -0.3029878528052834), (409884156581185280, 20.53880360376107, 52.072775690111705, 3.8085832731673204), (1309339540603287552, 257.3872808150315, 30.705582764950524, 7.375300588417374), (1965547665115773184, 319.8787142431107, 39.74170378369654, 1.2846597003608098), (3200704118259713024, 71.48626639463212, -4.692907002922351, 2.3018824204713084), (3344163688167821824, 93.24814780056458, 13.401118628587282, 1.0707022508812862), (2503752628312557440, 38.56645070373843, 3.4578075641473776, 9.112092366533705), (1247123228468449920, 212.2553509860801, 20.81587542506572, 2.4544186629389095), (247199110464070400, 61.92047574304858, 49.06758604929816, -0.314118431626485), (3153191094090847616, 108.41402421173296, 6.726199765043803, 3.2579639144738715), (1319644438456330880, 238.5633994489983, 27.896435512741988, 7.307618860002161), (2108701124110404352, 276.9857093476874, 39.22889051521394, 0.45710411911610477), (5334718920620915456, 179.37308733487487, -61.76867228333948, 1.0363207234144496), (5881168022007375232, 225.1050519393966, -56.835256069677534, 0.5768946825011869), (1178109048256859264, 218.74526132322316, 11.318194527013599, 4.082052247844917), (359890221859704064, 31.37155554475897, 52.45254820835617, 9.697168655947776), (5818243418225340288, 255.09175157659257, -62.293979444271955, 1.3306792702224544), (5438134242682884608, 146.6829491805995, -35.178516137275864, 1.3829772754718106), (963107108588979328, 91.24323359435748, 45.58248077933919, 2.4160272068542312), (760152242945926272, 170.9358895765649, 35.47063671157585, 4.603657928537548), (3116070894338908544, 107.57276226858538, 3.1265187397293484, 1.8405066839001212), (6262783459757179264, 239.06365266343815, -15.045385481273165, 1.7744242226451297), (3904588888013860224, 188.58824047805348, 11.58761460308145, 4.475294167465012), (6641741068668423296, 293.9745774989292, -55.16001889407961, 1.8094065169324869), (3368998426023943808, 94.77181121104064, 15.448866271020892, 0.7031367963419655), (1959798937285422848, 331.2862037081953, 41.60358430563149, 1.4006817448545448), (195571129666032256, 83.44373724926207, 43.53777069664211, 1.3829973910890545), (2258716910055076096, 280.7829084225301, 67.54528491512983, 2.0815533388128804), (5612534104156295936, 114.35308379881741, -26.498899953348516, 0.7321914842646122), (2067134842936731008, 311.8555914679525, 44.45391453239054, 2.4259011256080196), (1064006610609431936, 142.0824847032828, 62.47994270487483, 1.5781279418083773), (5928581299859956224, 249.77751623861732, -56.25252011811585, 1.4528543957170434), (2277716196105133696, 310.5859391838277, 74.23875893925727, 2.265278502116826), (3654139208861746048, 216.44590544329196, 0.4039714753757896, -0.03599582724942711), (5828418504985957504, 249.14821290504088, -63.41471108215592, 0.8062986170530551), (5257576978659523712, 149.88893449597265, -58.94699926982393, 0.5901175603808246), (3106960856387224832, 101.50300712013046, -1.9612750685089797, 2.4385781922295333), (5806441054254404352, 245.6037874365543, -72.46559139044565, 2.28186051929106), (5596035348070081280, 120.19337057058807, -31.592228584598885, 0.6708044306346702), (5420038995709004416, 148.73265509535182, -39.359024730662874, 1.2053929341525935), (3261268963929103616, 51.79248665149577, -2.8259638680051715, 2.6513575665494704), (2719137129308530432, 341.2049920549223, 11.337232751870449, 1.7542487829521676), (5933287003465588992, 241.57422420619542, -53.01457611710912, 1.4401759775089342), (5512610968461712768, 122.11821236829823, -52.61689532689581, 6.701674934782202), (2950075253072543488, 98.66642878260244, -15.828133536239623, 0.3064207374323079), (3167362355862487808, 109.37173087179033, 14.638402195701165, 2.445343703557502), (2925969800662418176, 102.40216791456233, -22.239690719650856, 0.7870128165810638), (3835152495336753024, 151.4708307553545, 1.2023060762164723, 4.33218955446675), (4314733319621017984, 291.8385237800332, 10.345758212243535, 2.6724649609381865), (5257192424466360832, 144.8255555071471, -60.434852922261115, 0.9705940706559832), (5281531935410843648, 109.2680165493593, -65.87637003101064, 1.6041547933444387), (4039313937552742656, 273.58390484212083, -34.691053295751466, 2.124478741082782), (1810002503912723840, 304.0282410486669, 17.93509337634336, 1.5954891479930977), (1447217886409215744, 198.3202720248622, 24.92145867583071, 8.40249802303252), (784513744125798016, 171.98707581044968, 44.878415863875354, 5.18729737111661), (2003384540286180992, 338.62359003874946, 54.76996301840174, 2.70536838184937), (5713693159641367808, 121.5786239246506, -19.589547420223358, 1.2558910965698695), (773157197759862400, 179.1101742836587, 45.04554145737943, 3.744790509776648), (6001695902526346752, 234.8791176423405, -42.521652536656354, 1.7880588694431099), (1368399292292964480, 265.17549494621187, 51.617002508166365, 2.042320414279042), (3089527790291968896, 123.82747045721648, 0.5962005355672079, 0.6235316562619191), (351294720989138176, 33.80695054101698, 42.20930730819782, 1.1857086917912165), (3003483652435747968, 99.0560158296853, -8.843990619771596, 2.950739543642389), (4427497926486399744, 233.79817285724576, 4.016614788508798, 0.7720145425853414), (1936276294757013376, 345.07074080998063, 46.05718404413914, 0.7477565256989279), (323420245799498752, 20.259068725867685, 38.06869902889195, 0.7182029770667618), (168686008781523200, 58.22930609650711, 31.367755685195064, -1.1119958929807892), (5616102981461094784, 109.69157756964232, -26.296701153781765, 0.8797337667390922), (4120778678203387392, 267.0925517266491, -17.296844349682807, 2.0464009820647635), (3667101660679634816, 212.87295415023715, 1.7357670090215431, 4.436919399880918), (6066582172494529536, 197.67220734761142, -55.90438597610975, 1.4676894449565658), (525207911128043392, 17.640790415576443, 66.01661529028448, 0.7010392670533453), (1114237077769603712, 96.85900138578539, 73.42401696319641, 2.765505644940413), (6615387527295986048, 335.3188730129529, -28.902556447663617, 2.552443986484165), (5564803101804870016, 108.66822974257876, -39.532727000839145, 0.6135383733537343), (1645837549501179648, 229.94989734248307, 67.81904520508188, 3.901478415901806), (4437687822295506560, 242.65064000331756, 5.4025993320623105, 0.4487927798862244), (4883926265695845120, 61.297395488246096, -31.49366659702945, 2.5221229676170553), (3268385381141192064, 52.43018099282658, 2.834349044424617, 1.0959783254848543), (5651579961082355840, 137.73661802470326, -23.704470477028195, 0.4627389121743859), (5598469598096144128, 115.03636135517134, -30.884132754975102, 1.8435932509970838), (5417016060287491456, 152.68780929571878, -41.986493174120646, 1.4783699529104752), (3213615374067072640, 78.25946889401054, -3.8470321171401074, 1.2565017914242824), (4116413754474760832, 264.23811360634323, -23.751214567889424, 1.168039375054994), (2279253622599531264, 332.0226851942833, 74.12422354804688, 0.9508366393523626), (2090403017240660736, 283.446971710193, 32.613921127539925, 1.9707950277814106), (1271591210477625600, 229.17002615244837, 27.726303451045982, 0.7421094860951047), (2834857292157974144, 339.7950901298992, 21.17729976646648, 5.529601314497683), (1342979201933819136, 265.427894645665, 38.7567225144679, 3.313299338621084), (239539912465533952, 48.416606247994935, 41.15769812995633, 1.8900845973414937), (5720745289783982464, 122.96776859223965, -17.56737399581486, 1.124179235208661), (5836299907417546112, 241.93048350625446, -55.81159012301556, 1.3784135273721103), (3058435182007928192, 110.08548580835004, -5.1676233317339415, 2.6200215192722958), (2967631361391540352, 86.71269584307558, -18.394582186941633, 2.030641143843028), (5318036580449160448, 128.28485720255213, -53.924099043611626, 1.5920407759119302), (3023707485200840704, 86.7417798388531, -3.9809824347119114, 3.0144094888870505), (729304997551954432, 156.8564042600417, 28.103637482962764, 1.1940066673733112), (5814843831350200960, 256.31294970084514, -66.67626397564446, 1.235736759666482), (2919925235491352448, 100.43425091463969, -26.716233583725916, 1.9583266925402232), (3365934465074556288, 104.31671187568296, 20.124123472951382, 7.2605895896262505), (2005850023312572032, 334.3155463610016, 55.19446381577342, 0.9150647821496509), (1723838313124795520, 232.94469337223205, 83.47138076430545, 2.0152906694459567), (1645223644055483008, 226.56908691597596, 65.83130335348422, 2.2031457874697162), (5437188697044475776, 142.34557744577677, -35.825916745623026, 2.2430290114901283), (6522539611485879808, 355.74718922235326, -51.1423303737491, 2.7136474308500587), (4336600338147651840, 256.8708751568244, -8.39800692087204, 1.1104720848177592), (5479170078215778688, 103.23173293096502, -60.8620140138694, 0.4186481124020752), (2156465799005485568, 279.82632300181916, 60.490780298739985, 5.423893896348414), (5854008676053132928, 212.6294674646513, -62.830008104186426, 1.006267050251651), (5792105724731309312, 225.43646429226112, -76.12780873907484, 3.2182990644906333), (5938264320814870784, 255.38719376640398, -49.24842144013439, 3.867414013168514), (5549088297504511616, 93.85887813447515, -52.0531747508186, 6.1606328657243505), (91120273805302528, 29.84824846702378, 17.678860158205904, 2.004298833030002), (5325073798461823744, 134.80253819031108, -50.021670522453164, 1.3829684947489718), (2189085525863536640, 314.29295321063216, 55.823065829245834, 1.989378771976682), (581482290627362560, 131.60142637863723, 4.234003288382743, 6.047221351810284), (1427355380652970624, 253.73410496300173, 56.40501661949992, 2.831357030510823), (1646467157346801536, 235.8301893747892, 68.30996417584761, 2.3805923435356733), (5361474814528430976, 161.06726985092814, -48.99901264527933, 1.057685977254702), (3828164789704592000, 151.52440006442993, -3.925825606707327, 4.796677805805512), (6188577763597083776, 204.3088849681911, -27.694215285554375, 2.962943903574714), (4288208563667758080, 294.29879891051274, 2.338706714884014, 0.45028436791714466), (3362950046919739520, 111.03765319229076, 19.85687612875397, 0.878162810560061), (3429359827682329344, 87.4093492146898, 26.181939527533572, 0.40805807153417595), (4248288045241208064, 300.10208693524925, 5.115802658247761, 3.050361816828533), (5309100883808619264, 144.3625440631125, -53.49440279202324, 2.1573348909164634), (5334132915280484736, 174.7644971708801, -62.08992692657401, 2.1900620991385993), (2019072921947366144, 290.58544402654496, 21.888087203000346, 2.1433133648511533), (430090191001092480, 0.22002395666404875, 63.24521759050102, 1.3101095713892639), (5460371968433891456, 151.56613247943383, -31.54423584627722, 0.9602446369579322), (4587210580356321536, 278.021669820436, 28.347398590344774, 1.5031870840413841), (5864271929904391552, 206.17619477909227, -64.6253621344803, 0.5952696133831465), (2930993984685737344, 109.06844244113033, -18.990971363611187, 0.5366141257631966), (5946572196310573696, 265.0159745766965, -49.92011989234859, 1.2538958269233835), (1764188500079793280, 316.93582020709624, 17.461742261716655, 1.3841832918224297), (1619891858224696448, 226.27916734967548, 62.85697310023784, 1.5183426989245614), (4244187794582685184, 303.7980750640263, 3.099790994923133, 3.011974482810276), (6720781764132059520, 270.27497427422827, -45.564910495255845, 1.4203310360600192), (398505379463831040, 19.467643369446858, 47.23991700165951, 3.116405522168221), (4962702288096332416, 27.538821858435796, -37.42788575111953, 5.161774880281205), (5238238733788714368, 163.13027172723625, -66.75510901983722, 2.025987912349956), (5607794075171626368, 106.21388705779043, -29.865757789130353, 0.7081521071403509), (1862920452364842880, 310.8570325713012, 32.400536200128556, 2.510095741191459), (5377329909637109376, 179.2584925539395, -47.57438172476513, 1.6339795324568134), (4162860458526640512, 262.1957246976987, -11.700349918052934, 1.9748924729118977), (1514726835202934912, 189.0678782580244, 32.90558199641274, 2.28520101312546), (3637308915655391232, 203.34760545143035, -3.0659110947650734, 3.219622033090251), (668194656676243200, 116.71919080297579, 17.835319794949758, 2.472609496201665), (303509533328812288, 25.101597525584406, 30.565813169008013, 0.40944348021655813), (6091026824239749760, 212.4971192516104, -48.941591339029046, 0.970441182124498), (1929081434262723456, 340.9487842527727, 39.171749377263296, 2.005672123509098), (3770052576519787904, 149.34333587788302, -9.885657721879964, 13.73497562337333), (1953327761598714112, 327.4977448464585, 39.24239223313435, 2.4043086957941755), (1867932885357877504, 316.79435683912516, 35.1139738576081, 1.168735261747222), (755094008422232320, 160.0517859284672, 38.403101755475475, 3.143695130300149), (2150494282635573376, 276.75137038072205, 54.82080430827566, 1.1622773359051406), (92212088851939712, 28.231283998860366, 18.662797554485543, 1.0428872683192383), (296405588701924352, 20.583612429111316, 26.944586732727476, 2.0224594892069034), (183059511976451584, 82.73912468051552, 35.17374151201293, 1.3316259720480341), (2375839431266696576, 12.34597823720762, -13.23915974297868, 1.8692797198498476), (2938727159202480768, 98.20047792662281, -21.060542187883637, 2.305355409071726), (1968493325480625408, 317.08646296422626, 40.85805326539586, 0.5099111252739439), (3360648906521504896, 107.66941732831525, 17.236258365862472, 2.1372301605000947), (5844452408177478272, 204.70487575243692, -68.70807537093448, 0.8901773886386889), (3223788811562961408, 82.55191039228575, 2.3887598121667963, 0.8170216755776663), (6343586500562651904, 348.78105608278264, -85.2951175855243, 2.0523130371634046), (1925545095629840000, 356.71672872769153, 43.679545076690154, 0.641749695436497), (6176254402912987520, 205.2155981914469, -28.882490742318236, 1.430925381026173), (5321044603744448384, 127.96714704882072, -53.70321202533942, 1.8576937991582094), (6048236992781501056, 250.66367480093942, -22.740081441731306, 1.1625898633009197), (1857461789451405824, 308.70668416555435, 28.25435665322044, 0.5188381226931598), (4266317768191651968, 281.91932932086456, -0.4998264205233949, 2.5665638884828117), (4651483322836369152, 76.61355085830597, -72.18022648373689, 1.0653653165871895), (6513885046226556032, 339.90887686557545, -49.92407192864307, 3.0017686495852667), (2978820644550302592, 70.92163806714673, -18.021162196211385, 1.688347041873559), (2103415290681390592, 284.08815373630745, 40.2044225329919, 1.1726200726678857), (1174947436931185792, 221.8343070925311, 9.963340817968822, 1.5308648670820804), (5811506092005430016, 262.79864500710096, -68.10734558779, 1.3756556363203287), (4921805953101482240, 9.297519748971032, -53.798186252471055, 2.8525682750800785), (5733613114881545216, 132.29695726934904, -14.954445365334989, 0.9499875726993042), (5433368581331439232, 145.79814809576033, -37.10310243862088, 1.7047900133437666), (3461241679158186368, 183.29706999227224, -37.13747530666425, 0.7852556231782377), (1515193131212344576, 190.66521641461316, 33.81420162666315, 3.6550889675317193), (5546859793594816128, 125.1559207743953, -33.20497211572317, 2.525774545426648), (5933875276556838144, 245.10642819845506, -52.66903905661873, 1.421608538535297), (1998370354945767680, 359.2323320664499, 57.953615258191746, -0.22709277318455445), (83180906499549824, 39.33603258775341, 18.35231690380673, 2.743660827829151), (3034573718098549248, 111.86585769441592, -11.632015401097528, 1.0556509224770638), (5255503127928327680, 154.94847509606916, -58.97320759194146, 0.905432257920146), (1964459595275459712, 321.85575955556004, 38.62586579481914, 1.3467995975932952), (1701736308340423424, 219.86816946439112, 75.93969783955951, 3.3982546821090023), (1867698345784113920, 318.4035243873685, 35.90124830029094, 0.47005393855196564), (2994206797952549248, 91.5641515557799, -14.08786153993861, 2.7683305211681772), (3466008130784971520, 180.27523076702138, -33.40630865961603, 2.4709434862821382), (5407611525017961344, 152.7012704565458, -47.42537151649047, 1.5503593986232338), (3113378052925878784, 103.21092616378812, 0.23488685957044406, 1.7166121995070895), (2938829963539825024, 98.69905007023347, -20.782440584132193, 9.210876766753852), (6311500895838363776, 222.69375208560916, -12.942806861153139, 1.8524574669733371), (1775681007928865024, 330.3811941413865, 16.786381536991144, 3.419504845469366), (5833215674217964160, 240.8001365562254, -59.40745144916267, 0.5329201232419178), (2603717064414086528, 344.3049364911152, -12.778252345131348, 3.025263712685032), (5596191856677803264, 121.57041794063238, -30.684313181114415, 1.1328560251561208), (4237849797243774080, 300.49249670223503, 1.9997083342655722, 0.1133459013887787), (1806563987453751936, 302.43983043378887, 13.834312818352988, 1.6466753343634513), (5165969586838837376, 47.20240666288, -10.7398931701869, 2.172548817210702), (1572023245119424384, 185.81187717379134, 53.18873390837291, 3.204003592619696), (1765418819230416896, 326.1874055829166, 9.801239717318536, 0.8275531819604216), (1913071308011555072, 350.8789505929576, 35.37428969453294, 4.54073620618268), (5715926542636397696, 116.15571964848417, -19.77279805291933, 2.2737595239194555), (3205279873338153984, 67.97327507680282, -2.1891886232863964, 2.1435585126562864), (2963996547748112768, 86.20970618644184, -22.506013815043175, 2.1169761851447246), (4397417693533573376, 236.51233207574276, -6.182899660631368, 1.1850786701306717), (1974008235287399680, 324.48991355314536, 44.62158730953837, 0.9347808436018903), (5959848627416194816, 260.617194248648, -41.225381411556356, 1.0605926254743787), (5890854341493724160, 217.24164965388863, -59.49721072053736, 1.2490199156630482), (5274439226417901952, 122.0469198899104, -66.83959821564142, 0.8337504034329254), (4518632390867255552, 282.1451998074585, 19.682639528915193, 1.5807098873401817), (131652842250936832, 38.30522691217921, 30.80041546528295, 0.9659147519155891), (6811510714876830976, 325.2547498389285, -25.845238758015363, 3.155731222823688), (1834792848983719040, 300.93318511601694, 25.83072489130124, 1.295913370022334), (2956696683892867840, 81.47010850269403, -26.537457231765146, 1.7333547931607078), (6374814554936924032, 308.13303693445465, -70.05384596352462, 1.5308728788572155), (451286301284273920, 38.89513226848091, 51.20840096852822, 0.3651969609144562), (6855508909612871936, 311.2802413505559, -21.485075310608597, 0.8395832709154755), (5310641437046739200, 139.91042186146868, -54.48663458161823, 1.6168292730161897), (729427386940300160, 156.69385908578943, 28.938128877451817, 1.2772946463949113), (1714202949133025664, 219.7173742158438, 77.14180591807911, 1.1922069122852392), (3142751231182597632, 110.30166438123129, 7.202689881777499, 0.8205938419489887), (3028277433483862784, 113.27746762314749, -15.9097170709557, 7.012715979529966), (6125628558244334208, 186.06223102067952, -51.445588255029264, 1.2107308156108132), (5142301052862731520, 26.011669258038452, -17.01639238564576, 1.603000819009566), (4319114804728958592, 290.12972312252356, 12.884556288840546, 2.2142194376275044), (2004714640113680384, 335.7019197395734, 53.58468622092644, 1.7868788444770916), (5223011184937300352, 137.01040277030594, -68.52858168565601, 4.066761800271691), (6220780981704500480, 216.1400132001689, -30.079528802739482, 1.0806373265362175), (5809796454503466368, 269.6854723213297, -71.29025250915933, 1.3826742865566912), (708225916538675072, 125.1701250602184, 29.283862816849037, 2.0056350972236863), (1414053592058753408, 255.02849170975816, 53.70130477079506, 2.946080283699005), (5497290717037190528, 102.12152948734777, -55.11473907622818, 1.5288064497663119), (4111528349434643840, 260.5287642321978, -23.660944356589216, 1.2909191814407794), (3899172865534537088, 179.5056805056483, 7.012293192882499, 1.417483629146796), (1364825810783090432, 259.25414072454055, 46.62658565382542, 0.4707221664878064), (3818555607833831040, 169.01325551290705, 7.885421599001586, 1.20790611013347), (5368786360691877376, 177.25892648859718, -52.233047608489585, 11.387077959160187), (1268592739189015296, 227.02321318306727, 27.591524615633904, 1.8856694943688095), (205523118646207232, 76.60137979109872, 44.147886517460456, 4.076028367450737), (4298325857347517568, 299.227026378686, 8.44743388161955, 2.4342378610249815), (2266558145948039680, 275.04187110788786, 72.0939223733377, 0.8267555042374336), (1865722214154984320, 313.5864901341322, 32.166176570747425, 0.5706499058516766), (4516539298688821376, 288.30701602713543, 20.48191745501285, 3.4580427076008897), (1113145571960937984, 103.87822491566678, 72.21608066084214, 2.229475962072439), (3513666324851070208, 186.46645081402744, -22.322176894864235, 2.573730819215837), (4531597213507104128, 281.8141042585991, 22.46979944975851, 2.037133363670591), (5235551974044208384, 178.3654840827821, -68.30696967649926, 2.5800481790974366), (6210779652139894784, 227.07266977466656, -31.478673373680664, 1.9607686290334698), (5601166837552280448, 118.29172203034172, -27.16740420481827, 3.54384750516682), (5554397220679955584, 91.54202378441127, -48.029635925411654, 1.4123906509134971), (6436599858515142528, 277.1236872782533, -66.22138640484627, 1.46574706210214), (2965610562098044160, 84.16326868620777, -19.717913536028988, 3.694999040765951), (400558305111593728, 20.920745325610145, 49.267865788598456, 2.0878560995295796), (5717817977512963584, 117.67620161410053, -17.731665502837203, -3.2333240164080577), (1297840057726145408, 249.41429217677177, 22.186690240397287, 8.730986692108248), (4835952786669568256, 55.882241839919715, -45.25926838216073, 2.776364387201861), (6516424986805406592, 343.3393347405474, -45.973783579945504, 4.366562054321495), (1982231276594292736, 339.83290679113617, 44.20675521618606, 2.4064052822871713), (5413055035290828416, 146.22162943870413, -43.890090962143134, 0.651420484343059), (6813649436792373888, 329.66289541842076, -23.057262800606743, 5.557970099809967), (5582062204545084416, 97.73500735958146, -33.857033856091434, 1.123503168462296), (4145781022858280704, 273.07672459087524, -15.823080647447211, 0.6050268321074752), (5280689228466884736, 105.73332918684842, -68.0141562489291, 2.5946919855794253), (2929396222495407744, 105.977099308787, -20.698677404957568, 3.8489253291168835), (399330391141868672, 25.061334319366537, 48.15734809183528, 0.7915373267854107), (1354945358778993792, 255.61396326038005, 42.841117024664534, 2.943799935728693), (5093456829347165696, 64.69270141595656, -17.890061132225124, 1.3715031000228333), (1818050757226610304, 310.1792086020459, 21.56352680265188, 1.9037179678753748), (1412852066367955072, 253.48744931262536, 51.68276002267881, 0.6532739396670177), (6725048315924207872, 271.3535232926992, -42.55792956972478, 0.7064718395914545), (1874966358162132480, 335.56614953007545, 22.172720920036117, 3.9580302687545283), (2173964045527956992, 327.40035375189285, 54.821445538738494, 3.680204169189384), (2046247317466885504, 291.48693439283, 33.669302669282814, 0.8512018815920681), (6649312546254582912, 274.8533875963923, -56.08320531873717, 3.544428804849391), (5831022560838227712, 248.51883606524834, -59.34765694673802, 1.1893734399570661), (5316641609427761280, 131.95564984455507, -56.525370174407904, 1.4800671818258204), (5589076985650356352, 109.79261194050588, -37.66098726760884, 1.8550577708376723), (6054468784173227648, 183.4012442665854, -62.70234861400218, 0.9939729648485452), (3043391663916983552, 116.50022690900387, -7.786555872339654, 2.1818977132926864), (1988868306735537664, 342.1980435926731, 50.57736162442072, 1.78110369028983), (5512017610138470016, 112.47366865344193, -43.50474270692899, 1.656468481796434), (4875624059553204224, 76.18634628682948, -30.743322428325037, 2.0988753614399642), (4431854500794032640, 246.71458065689626, 1.0118518970370443, 4.576036086713469), (5399123879367053824, 170.4629013474013, -35.34098544441796, 3.8809307512103968), (6438289189411960832, 282.09613454290906, -64.69291958936617, 2.156431970016938), (2929693949625925376, 109.22779060844545, -21.232500890031123, 2.2558466732956446), (4796310788283308288, 84.55928357933338, -45.40877228282192, 1.2327272788885297), (5867166703499436928, 208.16373479833297, -61.029901316412456, 0.3059170051327498), (4793814759449942272, 84.63361462553287, -50.10242891784695, 0.3494494661628859), (1798183475463926272, 322.1829437527153, 24.341555944117218, 2.780785229727652), (2123824700391183232, 273.34808354237214, 49.80020622373122, 0.6075580188499305), (1832306612679779456, 305.67461632013635, 25.194282685696106, 2.6842390837701045), (4531072471578730496, 281.34742825094696, 21.19746362194404, 6.450314288107561), (2164121492315035392, 318.78820754308913, 45.86206101916755, 2.563866710723047), (5048414751399516672, 47.727448140809045, -33.876561798899836, 1.5607989672668878), (5287150920864794240, 108.18513777681301, -60.96684654158664, 2.3657535131528817), (6252124416081087744, 229.3199574382517, -23.216531972014405, 0.4218357051910315), (1327761926646030720, 248.7227119061636, 35.57019677794224, 2.741130428378954), (4568564443696504448, 259.17307951475107, 23.31602744105993, 2.8567186751432203), (5405024374162180096, 151.68639676997492, -51.95169583736376, 1.833613779981984), (4998617801057917696, 6.866238532622511, -37.27978493382854, 0.9673072183731255), (1867667834336406272, 318.42710801637514, 35.614250023407195, 1.284941885781848), (5073083428639872512, 44.52465204587279, -25.89097079855649, 2.31019790775755), (203481188114559744, 72.68426961515385, 42.082466735582436, 0.9584122203573409), (4651599115151840640, 76.82280680408624, -71.66405315621277, 2.380050745945255), (369194220533081728, 11.520810434526554, 40.767860022263925, 0.8731739599073428), (3656466737538278784, 219.35189354459666, 3.0441411464072936, 3.888449288464291), (6275634998338928640, 211.14354167886833, -23.080991761006988, 0.896492758870046), (1982365829330269312, 340.79866265018967, 44.90685565865872, 0.5574152133795168), (4891307493411544960, 67.03686019342145, -28.341699610850345, 1.3948023676843466), (4839244346526557184, 65.35401866643733, -43.81465398181477, 1.834106453975668), (4606908640406875904, 272.0709076174453, 36.66635206102578, 2.447949278068539), (169449001131734656, 63.32582356158305, 31.50304196796639, 1.4369539474567303), (1936809557896478848, 351.057914409757, 43.825044840158746, 2.2225846596687164), (1918077453171987712, 348.69916342980423, 39.545964915910346, 1.277611376760475), (456007569855025792, 32.07734984813386, 53.07820460943473, 2.6481100916956812), (5803194127698016768, 264.0439589438205, -74.19132449120103, 2.0771922236957923), (4508645045713074432, 278.5582684246502, 14.166128339079707, 3.5077315558852975), (5791801228728873856, 227.41376257286336, -77.02226550161396, 5.560265586804967), (992640059628849280, 100.1450437485668, 52.33985670661523, 3.5042594553025532), (1859649611431427968, 312.57744692509584, 31.420881500275932, 1.7143743601071784), (2003781635779482496, 342.9479870849695, 56.054223981713555, 4.605318481692192), (1314561430560714240, 252.93647063958298, 33.334176024632356, 1.6730523585810244), (4676947290575911936, 62.97232370582371, -61.00182164341783, 1.1846081659667473), (1918210425359553920, 349.21263432103217, 40.380939486819926, 3.80771343437889), (5594074162919437056, 119.80597104200984, -33.67880927278339, 1.2543495941354117), (6776888468108242560, 316.08673130763333, -36.376618959805214, 1.9378053245334965), (3501584719286374400, 191.62061861146967, -24.223638135910587, -0.010309748264548058), (5264272489073300224, 113.6558731142275, -71.20089739470751, 7.1917849540133165), (5974225394783242368, 262.41795585454446, -37.1107198948739, 1.0145548858971989), (2287218484830017024, 335.65966473071813, 81.93945770922005, 8.115465871946617), (5694745241405206528, 123.56284023166864, -25.292701733211622, 0.37262761014036133), (4864447798734488576, 67.41369376874154, -38.865697669868446, 7.891756656675371), (1289578430433609216, 223.6152417169471, 32.86461109743802, 0.8570430229432772), (389868268950868864, 10.109450093156068, 46.26156051829578, 2.045171571057002), (3219226422422487680, 86.35331649590678, 0.4632892936794957, 3.9791566673856438), (5617935077071955712, 110.66766655022089, -23.036928957917517, 0.8525510406125939), (4864320598983486336, 67.64148462059971, -39.88953099928294, 2.6313732425268714), (1103137301728355072, 104.62854611039619, 67.67733483067359, 5.40102411005971), (4310566067464049664, 285.51822154146396, 8.964777319131885, 1.1388247697707161), (6722736661446266752, 279.53204957982103, -40.60847512013818, 0.4608270861029438), (5591465812100816256, 113.25795696818919, -34.16042682926032, 0.8827157179195084), (130784193704633216, 37.71455678774566, 28.47799926926261, 0.6996134458624039), (2988826681399430528, 80.07488469866118, -12.383788937787944, 1.504986693445473), (3234076838784240256, 79.0710608725071, 2.043781520636996, 2.0388132885948043), (1013602351892191616, 131.34976421515526, 46.170743356924454, 9.847838164962575), (3871488880733595776, 164.4998314903133, 11.40495051405037, 4.246062574695222), (1164203627779856896, 233.14933031098616, 7.461827066229961, 2.480173574926722), (2026308739251035008, 293.0662393382625, 28.775668980565975, 5.6098888699703044), (3450021987631690496, 90.58453047278594, 31.6623237583511, 1.3792693412814134), (5633484988985957760, 143.98197853142193, -29.410469138593143, 1.560461927917109), (261697408234408832, 79.42600814882229, 50.64928661726158, 0.7991897068850019), (5869064323131799424, 203.7508428308092, -60.5994577766196, 0.9322168062580446), (5438810098738130816, 148.5853992720309, -33.20934999326442, 0.8269213374084172), (1817848687607875456, 310.67750739227455, 21.414908187415485, 1.1115938848648756), (5489701887781726336, 115.50658005736058, -52.705378103102, 1.3764883100465233), (4355872131280539648, 246.06697020166513, -4.793201160587516, 2.2209771362811113), (5516637792358225536, 125.02891217741005, -47.05681074159642, 2.6143169089958915), (2793154671542397056, 5.933233712863628, 16.881355611014683, 3.878087528922676), (213513269645021952, 82.22997532697826, 49.323498747759125, 4.424104754962698), (5351003649898186368, 162.45721480291095, -57.74416857831057, 1.6519725577385893), (6565184066890436736, 326.07876680620524, -45.75696839399191, 1.0193373726552608), (3339055872542059904, 82.37610623420356, 10.842119211670436, 1.080740905542263), (4286484014035899648, 280.93914058183, 7.0826471147987515, 3.1786980016272715), (6072244416862545920, 183.3669045951306, -57.07904795974875, 0.46861992318807755), (1815279128929884160, 306.5021645741266, 18.197028583519025, 2.868580911460415), (6562728685625942144, 325.3268319168207, -47.423322452388675, 3.93086369121794), (5596686533827575808, 121.75252571581309, -29.67425042722204, 2.121334396139026), (5981659467776026112, 239.73017055933556, -51.307533583072654, 1.754060217420153), (1224116188175483392, 235.69273632982137, 27.700914237376015, 9.838544483472411), (1497539235077801088, 210.32158165248697, 39.3552695259705, 5.8102826686384645), (2440458760423641728, 353.9913389097019, -6.834587127175033, 3.5733279708676804), (2328753567361651840, 350.73929191404824, -31.228929664636123, 2.971316418178858), (5335638181060953728, 175.94462859393042, -59.01699192381218, 0.6199740451326988), (5834590029395004928, 244.01426070522078, -59.194324178249644, 0.8456439327907452), (1125981923538121600, 150.50911980540448, 73.1113689459091, 0.6416137949915509), (1997045168553812480, 351.8677387229726, 56.270283940355945, 1.040990910779534), (4599676465234074240, 258.7966693517649, 30.016308201435244, 3.0017758098743683), (5813146322839815552, 261.8201107088413, -66.86299937344084, 3.1969006775880526), (2964617187702620800, 83.16414338634371, -22.238455678123355, 2.669784285074428), (5823767089769439360, 234.46489609003484, -67.18366479938695, 1.1177729744892846), (4908265845362872320, 11.68591112138325, -56.69160688735712, 2.180798067255193), (2005979250286025984, 336.4054390988057, 55.87994513961189, 3.063967752356367), (2931636752313874944, 108.54299329675183, -18.41472830531768, 2.744764651481464), (382840018827497088, 2.865379164517825, 39.38917516619754, 11.76243040422617), (1975958219159258240, 329.14523787292813, 46.79370928926091, 2.2279238478641603), (5414548412597025024, 151.12118374343189, -45.693836220019556, 2.3223042863656835), (330307827154053888, 28.714259915493017, 36.24755342371863, 2.261776854631727), (48319996988389120, 66.7429713537181, 20.100486846528053, 1.3224865335961624), (6709404876801076096, 277.9957529776437, -45.340725309728974, 1.2452930791667915), (3033782585122672896, 114.40748326147296, -12.713712871163034, 0.45589745267667403), (1965256294530855936, 319.23336443748326, 40.0881116290108, 2.4211281444325747), (1984717787779735168, 345.02086675816446, 47.89415296879786, 1.3068374496423631), (4317591362656740864, 296.63392884616263, 14.462136721462501, 0.8637399170863141), (2002438891562372864, 342.1188846030695, 53.30121529688976, 1.4325416346665891), (2687604441494457088, 321.9458862249314, -0.6659121911533308, 4.3847962508012674), (1717951390430527872, 182.6936639781304, 79.9859084585268, 3.430278926800451), (5324386775497054592, 133.07408819668174, -52.585098714744554, 0.7902266490465036), (1764768904779146112, 313.7645650192441, 17.730827414915108, 1.7468580416499486), (2263439484295148416, 291.73810482182114, 71.06056795027372, 0.362461855769198), (2247722480972077568, 299.1566121520995, 65.18556569573053, 0.2261843666631571), (418522126086567424, 10.696506249517554, 56.10648673399661, 1.8608976456322486), (248672971444014464, 55.380823198435245, 48.60722323237799, 4.089226117923355), (1226027826579256704, 215.47711592921934, 12.749296166382862, 2.7042473713979884), (4538628968322244992, 279.7090812731203, 26.914464689303582, 5.6918147573372835), (1024435668161410688, 138.95575608194633, 56.1665536464995, 1.81416244428881), (5881419329131512192, 225.97708576920527, -55.14660518270069, 1.4738802445450214), (3009893049310993664, 82.08249508070068, -12.05841579530339, 0.9357591419238378), (5310737438151080832, 140.56266326637078, -54.01978364235204, 1.2103914119378736), (4560203654199545856, 255.1834890779684, 17.960567514886538, 0.9818037694932981), (3959448745803804416, 190.40778299823614, 24.57982645254339, 5.638030398348422), (1269005399646798592, 223.78343089993686, 26.903766298353105, 3.0749225225413506), (4219115596574374144, 304.22293974977816, -4.712027319694186, 3.7973828491887787), (5821805904623633664, 243.47317152295716, -66.41313418528779, 0.661524545097196), (6059834503992473728, 191.5275618289884, -58.7163993038811, 0.17025132453490605), (279580415096785280, 74.65627707496947, 55.70400800382078, 1.4665605956980106), (4801004534702992256, 89.57410155409002, -46.91225266539694, 0.9640983470882296), (6205243095697819136, 222.82298648641208, -32.38612612519194, 1.6771514994052623), (2135396270000127488, 296.01916490554186, 50.899365900434475, 2.2433761111285873), (2999386837749512960, 89.82016778543631, -9.838751031835603, 0.7144749261215916), (5338660704164783232, 166.54421628617214, -58.69705225478318, 1.8155540817761437), (4558315586576193280, 254.6245325627052, 16.53497722059602, 1.509565043648693), (6578533684238894336, 325.1222292997434, -41.18393008701382, 5.970603879615828), (4646872864417383296, 40.18675266030727, -70.04666540555249, 4.150400672216344), (1723248150258407424, 255.14730409934026, 83.3959191846052, 4.132619226058597), (1851632934716246528, 318.75911096787735, 29.281397163932827, -0.149383490006196), (213231107473691776, 79.17461293695239, 48.51130427820601, 1.8965275049605443), (435589604566675072, 49.84062342702654, 48.41760166841114, 2.295802484154138), (1435043578270631040, 266.3520319988739, 59.65334209324884, 2.9157623760039773), (4153501827867885696, 274.49478144094826, -12.574957640564234, 0.06047626143444418), (5384033563313536, 43.26813748838129, 4.547227871577842, 2.449650760534872), (3358689851678897408, 99.7339630333212, 16.712292330387633, 0.3984343915150709), (6194808764710059264, 202.47340399523944, -23.85685392353154, 0.9859229266128606), (2251490816559182080, 302.77052278168424, 71.22009132954267, 1.0502401378540667), (3059715941253346432, 109.54668728535026, -4.1612962488777265, 0.22234373675276323), (2462672056399954176, 29.410021258212502, -9.590013225103005, 4.332444308175918), (3610977330157581568, 201.37703595568988, -12.180485006867809, 7.712106734823177), (1927942718174101888, 342.5200974876386, 37.58789080504927, 2.9064345969251137), (4175956947684765824, 268.7376286162955, -3.72259577785477, 1.4563463098242928), (5523706312097575296, 132.3343156445247, -44.36367576253667, 1.8028112079703227), (3455382862730110592, 88.51404551427927, 36.96047688173019, 1.6722857959822237), (1960348177703136000, 328.5286599108062, 41.457526940596125, 1.6380756714875204), (192005413457258496, 89.04256685531593, 40.88231797588967, 1.182160138225874), (2293684162957213952, 277.3104037674065, 78.3143534072411, 1.1872504562243957), (1650546001888414720, 255.15555643124168, 72.03029634507476, 0.9533502165993171), (282878675102205952, 85.11217495930576, 61.00273435447867, 0.4676015263586454), (350040899777140608, 28.31138207017958, 45.44801407567939, 2.6197733501213007), (974367619484531200, 109.533243953178, 45.643047257613844, 3.123162544382498), (6355227992239053184, 332.236655856168, -78.9807059459129, -0.15594203107666366), (3042624239159884416, 118.09339317782735, -8.094101285923909, 1.466119709122119), (2179519362384267264, 322.5017899761046, 58.92079026194261, 2.3363102248314496), (1819740431720129280, 297.32061170188797, 15.204250203839067, 1.7010526631612788), (5533121498888975872, 120.69009705078341, -42.90082184821189, 1.0458956956176704), (4980764412283314688, 10.053925651191488, -43.195996359000425, 1.4460496206405007), (2469175530239300224, 15.109373927818165, -12.775679845194984, 4.952118255722575), (399651242378386560, 23.342430225056738, 49.01892945317649, 4.490785141465737), (1998039642460652032, 357.32435688533974, 57.09655445235521, 2.0074083108228016), (4742784019623327872, 32.993970860758694, -55.366433542996646, 1.5390983063229087), (4386493083437499392, 252.8803075827472, 4.45358504330564, 3.322029970749359), (2001659612699447680, 335.1564174269935, 52.79929475033596, 1.0207947279105245), (2878247491323570304, 357.03338291738436, 34.68985123780606, 3.0749457501931), (1720650313519603200, 228.70183877175063, 80.25828139573689, 2.633615701022182), (1992409455733031552, 350.33166183624195, 52.47139824549379, 1.6140964977749483), (4329233816397917312, 243.96459116161606, -14.84911086132074, 5.308634936814945), (2053553812749942656, 292.6397911641157, 40.869198300337615, 1.0546080421012756), (3229131853957740416, 70.80279025593268, -1.7489922992301905, 1.2550572692381812), (2032734491365413248, 294.19464888226554, 30.764349670753422, 0.6401388360878812), (2966226872725156352, 88.96157369647008, -20.152541216418353, 2.997682312014371), (1991197862640446336, 351.0706923602852, 50.4531337419131, 0.9804499431408036), (5346066705251566720, 169.8821267345551, -56.24856264602735, 1.2131261300649123), (393717830959921920, 2.2171613421849137, 49.451593951573045, 0.9770519233502465), (4298565172925238272, 298.0130209572546, 8.640733370724112, 2.4690149639083647), (861869369301638144, 165.57960620284348, 61.698203079993874, 4.052418605193799), (5512536957584724352, 120.24608883090771, -53.09035643269638, 1.610438866542061), (1421943481341484416, 268.1935348249529, 57.89557459896204, 4.809909286858608), (320980807454250496, 17.99328422077391, 35.1020935546071, 0.6795588451295377), (6575089223547327488, 331.35660134032963, -36.88146363292831, 5.333205384757172), (5853684320120096256, 212.15349803132258, -63.715806766809344, 1.0222805476439514), (5511760461858118912, 110.0507694828262, -44.181437506884244, 2.97854203364278), (1868330530614486528, 316.7330008266965, 36.254413654459455, 9.0890617468435), (4385118109788827264, 253.66469895030227, 2.051050605349856, 3.4980870006819234), (3267038307598827648, 48.25852705745154, 1.2815845550626994, 1.0892488101479372), (3091323086621703680, 124.18593784585092, 3.346295489439592, 2.910695508830234), (5336220819143545472, 174.93520280428177, -60.17438323331253, 2.2712759017369617), (3970473789413785216, 168.523865807647, 16.654797189950443, 3.929019046206014), (1724149268757075072, 232.85007747331764, 84.41218437530011, 2.3961968273883385), (1067717221834557952, 138.7738631630507, 64.94265011180875, 0.6319241773213546), (283849509509795968, 75.06009068737802, 58.66771459555721, 1.5912749672976607), (5838831704734777600, 194.48791646542267, -73.16224300898114, 0.4173569073114187), (1859371057034079104, 310.28625410219746, 30.55110220553703, 2.2321752307008964), (5355727495448508288, 153.95274992967316, -54.10259226599978, 1.01074281807064), (5323429238306587392, 135.97117672144103, -52.89852333658045, 1.77920182491047), (1882318517539065344, 336.33432584695794, 28.72550033855634, 3.2650926586639852), (4597601686793778816, 265.60321217788356, 31.088118487835978, 1.2523398736427205), (5810733685088827136, 264.05786284878394, -68.3970536668942, 1.5340183595047077), (4796304294292750720, 84.32281025763054, -45.573654491791025, 0.48978709058486486), (5921590192610772480, 263.7570690896691, -53.451620262201736, 1.5022996186156299), (4454195992954588928, 239.18215517792922, 8.273561847238971, 4.997608697529676), (5859622404471956096, 184.26979555748395, -67.45603571856631, 0.5470185223786622), (2944037731644847744, 95.95719451270135, -16.943459270911312, 2.54061698906032), (5244031923118930304, 149.16242703078282, -68.32424354268898, 0.7591494078367822), (2051566308041962496, 293.6086928229083, 36.893720759391954, 1.9426323362206732), (2203128041700926592, 328.9372825883551, 60.057243004471474, 1.352772513701297), (5060998833777936768, 48.89069432392797, -28.008850221299802, 5.858544554430702), (3859455894198692096, 160.62857480824889, 6.275238016505248, 3.045907825903762), (2452838608516957056, 27.180008798667888, -14.88748766181092, 6.2696385332420155), (5851641152638332032, 204.21734398693806, -66.45500640333574, 1.487716302091693), (3424376291231894144, 87.97143371553685, 22.618201574356004, 5.659487001323998), (1481306595161278336, 217.84492296498428, 37.03999317611395, 2.8958499996714067), (390726197259643520, 9.275675895610245, 47.19010619999909, 0.947808470343009), (1838415018241046400, 315.3322583311708, 22.197628447601407, 2.4526522561891215), (5852638718921288704, 216.52397616673574, -64.60067835605132, 1.4281360151033795), (136056558118908544, 45.41441713903327, 33.07463196846598, 3.713796049828186), (1830313335532603776, 304.182388582476, 22.951777828469183, 0.4560302423746715), (6789296456827144832, 320.70506629828014, -28.96736470877262, 5.427836764429369), (3116604088759446400, 95.68756145948274, -3.938161360722832, 1.6784570879251381), (5344755056601643520, 175.16354190140524, -54.94524211406557, -0.08995192583322131), (1355374271391650432, 255.7268422603663, 43.17451276357422, 2.725513435157524), (6055991092377149824, 195.05253398783987, -60.37612476324491, -0.12754664758388445), (6042369174105245056, 243.82926208897905, -27.21082452605118, 27.43368616966608), (53881945276331776, 61.198342465068464, 23.647892973443795, 0.9135128307348028), (1303486221732807424, 245.5313962543015, 26.227246887425924, 2.5009869521757704), (6697539806307823616, 302.21658760310976, -36.10489731584342, 0.6109992832876298), (5359296200958036608, 165.04118357418213, -53.94962057661516, 0.7757664119186015), (225186922035904768, 61.83329597655023, 35.914283103636095, 3.5304118737213397), (725707739103440512, 156.461085058082, 24.14039593938609, 5.91738934054883), (1856412065083805312, 309.84615845898105, 27.29163832241029, 0.43566683814809315), (6554014196982689152, 345.37492833029637, -36.15280641061608, 1.4659383862051825), (6474326164047490560, 307.00432266783696, -52.40293630575416, 1.7391748142657268), (4585514205712697344, 276.2751547518234, 26.787187822908606, 1.7149541008017872), (4968975964005597952, 28.401042822916743, -35.58724613127691, 2.158175570628498), (2004963061022596480, 334.6957251158502, 54.05725824558551, 1.0869047969615706), (3240253895108508288, 76.08643024697292, 6.533760138735461, 2.539909228718284), (4836795321814289408, 56.71763769860997, -42.251261172078884, 1.4489754976147178), (3351919059075701120, 100.08545219490489, 11.632323411639847, 1.280395097559227), (3358956002213799296, 99.37489685844871, 17.193306523420443, 1.2118389772900704), (4568619006960861696, 259.4760520712962, 23.886711945674747, 4.5164464104920965), (5856286932867511680, 184.94312697098687, -68.61587588759886, 0.8879635984192964), (4445696733711736832, 251.56622045852626, 8.939357251010788, 2.9438388194136995), (2203308911360592896, 331.7816691343499, 61.33233063699384, 0.9264357263879086), (5321523750292691584, 127.56822251651877, -51.887984885407946, 2.9912381394280665), (4899298056727579008, 65.84903483592237, -21.34669081818683, 0.4398687051736762), (3808565101586669952, 165.48851897322632, 2.576408086802944, 2.522916916178559), (1299175002280916864, 247.52860697252927, 23.72475571004985, 6.91686818868507), (2050484938359105536, 288.7754991823694, 35.60020835864981, 1.8233639202013028), (2950682870686011776, 100.71950438629541, -14.112065617621688, 0.9359226649466059), (6710254009020536960, 280.4853083829742, -42.818229563257745, 2.305233616167088), (5405488746024209280, 147.75537659300085, -52.114342023957406, 0.5564733267897679), (2030311717486816128, 298.7127174974205, 29.85665543513673, 0.8939604169277158), (1356806866324028160, 248.6294862541332, 41.11839270025836, 0.6161940093613881), (2162666048157054080, 315.0141484325738, 44.98873015136279, 1.8054886542664772), (6575477007554680960, 321.79821297840226, -46.651646941291325, 4.499408575265458), (3289497138265857536, 74.10856026282099, 8.205469693573885, 0.4760543139021791), (1856478722978367360, 310.94842585919275, 27.551575198781663, 1.4247498780126062), (6001352683101707136, 232.85615405498385, -43.71355741417475, 0.3572206056458892), (6343203217681163648, 312.5935164586698, -85.188679912735, 1.4407904299635752), (5206489717058715520, 98.54920855294476, -82.68385338623798, 1.2959691731702698), (53821747014724608, 61.384445153600815, 23.390801373500615, 1.8090332466166545), (2014699511363934848, 345.55133780131825, 61.067999962926336, 3.397698250787723), (4511868779445723904, 279.1692474652517, 17.02602613679117, 2.89418134197604), (5818187411853913600, 253.68366407536698, -62.521310402585456, 2.195782720325723), (4108911511769432192, 257.10531492012717, -26.697887447396482, 1.2635629109192605), (6352470520156000896, 359.69454861714667, -80.34611569469901, 2.5133034240663767), (5823250628542728448, 229.99874469330962, -68.54726372598627, 0.34326138655771965), (4319347591956856192, 288.9681295765693, 13.507738245671755, 3.9235592385544003), (1606058936794876032, 220.83751548654197, 53.7939039237229, 3.676040401042818), (3487074052018947840, 179.16451027065187, -27.595330148013378, 0.6884253363499142), (2153417403019216896, 284.5633812756697, 57.176016224704725, 2.0884544810149075), (1044991931395895296, 151.82885155814492, 55.57984817899976, 0.4507338259441447), (4481639734467512320, 272.8988440838855, 9.470144633985266, 5.675548763732794), (3145137892969915648, 116.35285367662243, 7.658892583186113, 1.962757987923222), (2173423704279766400, 325.9386070090783, 53.196637656319794, 1.854295919215262), (2057168732104815488, 306.02954185694136, 35.15479518476091, 1.5103027915009095), (3110823990492970752, 110.64649327289739, 0.8006384031674089, 1.037548205614603), (6515927217275889024, 341.80277100049057, -48.04630829291553, 1.2009246560411433), (5357098689531026432, 157.3269971329084, -53.36963470108476, 0.876630786529484), (669881032635806976, 122.18437251359889, 20.251334594591945, 1.8066189318254458), (1343484942922878976, 262.157915324624, 38.088348697865854, 2.0132921047867716), (6231307843467963392, 226.4492609623108, -22.970599456232918, 4.667118510782846), (251597053898148480, 57.07378627461839, 52.17325446099399, 0.7344402014121959), (5218713331425136640, 140.79160255742622, -72.71406614512885, 1.545310631369309), (3240625358240984192, 78.12926861211439, 5.553989228110485, 6.586484442488619), (4631167646484671104, 4.901678378341366, -81.15456184058365, 2.2310001070182066), (6134061949870006912, 194.24395953015787, -47.04801016548312, 1.3714533462859184), (6074581325746126336, 189.21753689480568, -54.03127980361206, 1.6351750484310426), (5002887410867158656, 12.210035241462265, -34.91543469466174, 2.0830658099187658), (5360425502475623296, 161.9539840557652, -52.33268379888203, 1.5029859546073099), (5301657808561775104, 130.9353869122934, -60.5772633334342, 0.7372325480828413), (1433612563887034240, 254.93396704293792, 57.47937683233287, 1.4601943669418112), (2373729296654281856, 8.286208727907555, -15.667363333931084, 2.852351722136228), (2253333872924772224, 280.5705101789867, 63.82853304813757, 0.9689266517477059), (4515615434036238464, 291.93615631784763, 19.35626802814801, 5.690176221234043), (2908568070648034304, 82.02286316798325, -27.208574194019075, 1.3013280150387492), (135519721565979264, 44.11921170322984, 31.822056080822403, 2.5083861643972196), (5562085418297459072, 102.98151263825486, -43.49816671575367, 0.8507192630213625), (5402871358591873536, 170.63938097022256, -32.61246251086405, 2.080081470127889), (423699932500778240, 12.57764039456837, 55.79338341237926, 0.9060219507275105), (5821882732995680768, 243.03829596075795, -65.87964795638541, 1.4810306921858711), (2129577551385867776, 290.08712428428913, 48.843678619326354, 2.3183920423160043), (5979511400015858048, 259.3587228930132, -32.20549624194684, 1.7206916087070738), (3409065213855537280, 75.441318961974, 21.131648371105637, 6.4617547874476085), (1830551242364002304, 303.21410350140377, 23.65027220593971, 1.7352425582704736), (2207381536789076096, 346.8257672647169, 62.65583052007109, 1.5527951363241164), (391744310666146688, 7.418180848245198, 50.19628886568261, 1.4290828175609762), (1208473814205116672, 228.14130481923797, 17.094652821234188, 5.04697131754289), (1020480312519626880, 144.96256174170492, 53.30603952838444, 2.6419832357709536), (6860460388431070848, 304.10584578758585, -19.74060649748972, 3.6957681601506174), (6660970358805393920, 285.2210502088451, -50.30088804729113, 2.1595747153283136), (5839258727563175424, 199.2008912698061, -73.76199066194894, 0.41934738553446343), (5628070925011299072, 137.25023632002734, -32.451972496109434, 2.419079013403698), (6036902986402256512, 241.2089221233028, -31.212409220132173, 0.9802831424607403), (2175769065661486592, 318.7954662613795, 53.73491862593716, 3.022342904949717), (1826232154529612032, 297.86047432694755, 19.7808999189945, 1.4812559025469112), (237577456008080384, 52.23581599323926, 40.64578945024541, 21.333688348797644), (5670450398113597184, 148.31718038301972, -20.282712623987035, 11.4747269954593), (4796107172474309760, 84.90998428289885, -46.643627770046926, 1.6116518106406545), (4519569827612669568, 287.85383197381344, 20.900566759959393, -0.45711409036239914), (5250989426537926272, 142.81756642894536, -62.16157728246982, 8.361544964754952), (5247699206709329664, 143.28072620199825, -66.08011056184911, 1.8320139037931422), (3090175574439494784, 125.91597853456591, 1.9069640283872946, -0.8524055572379843), (5761582388590068608, 129.80140660181834, -5.003644689572745, -0.48144661024746876), (4674809668174135680, 66.600422825051, -65.89277689627701, 0.4554499353632564), (6780688449012918016, 314.67395165777396, -33.45210949918264, 4.395062137099362), (2006988842480001536, 340.3728189804384, 56.41832735961975, 2.4468650692443856), (2163527652954486656, 314.9387156051345, 46.007415867426616, 0.6325356066864258), (5348258203725640448, 171.19675066401095, -52.83980352794961, 1.3326712869547856), (957881439058171776, 98.87593989682368, 41.342646223156805, 2.816403439141698), (1763600845474374912, 314.8425087617608, 15.979983154887687, 0.5781202143333293), (5601246655229427072, 119.9192734222392, -26.90695689281874, 1.1134839559801946), (1409189902373054336, 254.63184270583247, 49.29298503641795, 4.008601419063279), (5723831790721180928, 126.35858975206386, -13.397937501054, 18.590160330592777), (5165114957066717440, 53.935773041421065, -8.995373499274947, 2.269492672512069), (4624420149783608192, 70.986383442679, -78.06132054045024, 3.1880608606791534), (5491615072373696256, 109.74655476868053, -53.77093742484332, 1.3227866379402482), (3231179591284626688, 69.40503047894397, 1.4986591163769145, 7.709985819412537), (5822449977921880704, 237.24990874386137, -65.77424934177563, 0.7293843174699601), (6056585653293215872, 189.18978067322735, -60.558438023567525, 0.832540870339223), (5849753703489838848, 220.90153881542435, -65.68032798049636, 0.5891437360739233), (6654221659516870528, 279.80644830184815, -53.17984642463886, 1.5773113876177651), (4145190653833256448, 271.167407113028, -15.69373495248754, 1.0111889915354881), (4120449821145249536, 267.48411854339827, -18.279688039243002, 0.908508071769509), (4257096232896012672, 277.37862396502624, -5.166116597933808, 2.02729906843184), (5426505120514649600, 143.64646284200117, -40.28495500919016, 1.2472997968215), (135449799498965888, 44.51801310992955, 31.48445662789402, 8.007019331508747), (1880910799058069504, 338.3893946480654, 26.677136685555844, 5.632236663012133), (1978775992587574016, 324.68982876260685, 48.38845304238832, 1.2667391080895394), (6123646585453677824, 215.00497117440923, -32.57845056067804, 0.9711548472318489), (5511804339243606912, 109.58703844065309, -43.98827200475646, 2.020044808730364), (6002601315992135552, 232.03540341421956, -41.573510432834304, 2.3716021399775182), (1598369261708429184, 237.6856038179991, 55.45605252454001, 2.675565244091326), (3392353427387345920, 74.65922523613592, 13.658913107704729, 3.3859598490112406), (4310492090951200000, 283.9034485880758, 9.266589517897982, 0.9497581587046421), (5959558596860609152, 261.10795549321045, -41.9790534878375, 0.9931265270577672), (1281504166795021056, 222.3010014963468, 28.539008798237457, 4.450122711270762), (4018667789240967296, 172.65067911654774, 27.267353058744828, 11.13845236456865), (1936639442831984640, 348.7606274888827, 42.613427114347154, 5.437168522999435), (2173753111091413504, 329.63354497763953, 54.46184736551509, 1.5164037948511275), (1449609186760477696, 202.76613627292443, 27.66649195214998, 2.22802306366479), (1817490968372384512, 308.6839283406481, 20.315437284722847, 2.31864831015136), (5621633937265736192, 133.75111458471687, -39.78648454198572, 3.637930815000585), (4302502970741489408, 294.1107623535039, 10.01310469914073, 1.3487692097271107), (3307405193385443200, 67.2383267856651, 12.491038590594759, 1.3789749716925297), (6773377486967255936, 292.17673599990314, -19.8426723585203, 1.6900582452540869), (5981519658001935488, 241.99280715430885, -51.56626494444592, 0.23964268566765207), (6398918907834784640, 328.93853344731156, -66.15654371252953, 2.528664590511137), (5872546442094213760, 208.6285751231518, -55.33249312287577, 1.8220336645175157), (1960174970260692224, 330.64903882327695, 42.90150969933881, 0.8106202254461461), (4303641308871842560, 298.259055633263, 11.294262502405317, 3.7827531864648165), (5957770584800351616, 266.87279792414347, -41.31624761225274, 1.5791504889525427), (1639990518463550592, 237.89961765175886, 63.07625505604066, 3.8772958568025775), (4865647537719205888, 67.21859682092885, -38.20842624933467, 14.567503063946393), (3444044973705066112, 88.75631271273618, 30.693195664702774, 1.2694529047314524), (933603260244566144, 117.59581918865885, 48.15843126351835, 1.3222996764069068), (5762084693604322560, 131.6649005694347, -3.948848531031014, 3.7208714412577946), (6096802387018677760, 211.40406524972374, -45.84118408721702, 0.821403028526609), (952519533166351488, 106.64442624869854, 42.1522273844068, 3.545370726770745), (5749029711012208384, 133.40490291815806, -10.936586807041962, 1.930987987349038), (6107838803701950592, 207.81398713573986, -44.71466950713125, 1.0293404833947488), (3159273145738415488, 104.08074907836671, 11.912556487639689, 2.0057730136250225), (1598357098360472064, 237.36462274986152, 55.203843082336945, 10.634407026525627), (2035575698123934848, 297.52146077705834, 34.87049951547281, 1.0751518505162048), (512630803776158336, 21.827649701462168, 63.602239308512, -0.89023237560045), (6687459792941767808, 301.93240969194323, -40.53178895420342, 1.1261121512212182), (2016319091995003392, 356.7288056586035, 63.74630013952055, 3.2017841227107087), (6891476683736647552, 321.1703871827125, -11.779053697371038, 4.042844623196549), (2410357464949317376, 346.3979699884772, -14.398071081875901, 2.4205167090369706), (5605306979867246720, 111.14155307620202, -31.072435966839215, 1.9574699854136501), (3160218794455572352, 107.28639326897824, 12.128688395212722, 1.96185169199828), (5724234967890830592, 121.42359693556133, -16.09136186106277, 0.8346386511376993), (2056063757277519616, 307.30109073678534, 34.03491879327099, 0.7963634552276562), (5819484010942072064, 241.7480580198483, -68.99529185111606, 0.6980243142006637), (2895706670821847552, 98.35269565771759, -28.069873107853127, 1.111444513809481), (4681623376089842944, 62.06329359155006, -59.16319285859791, 0.7945080527560928), (6031595162738640896, 249.59296807706696, -30.372668252685273, 7.03555493101029), (5827696744321784320, 247.68791016015965, -65.87661345308122, 0.5296967475300857), (5866146116189327488, 212.50731868692725, -61.75357886633973, 0.849414493348728), (5198092918555965824, 165.18874752058784, -81.13421424279912, 1.2543857641653655), (5339950190792933632, 168.1176837011853, -57.520251356110336, 1.017666178125358), (298238405865913856, 29.692944909540227, 27.645737551444736, 0.9838122918522254), (1995888104363268352, 350.84846086570013, 54.28397650432519, 1.774850313285611), (3157778428397125888, 106.72648516501361, 9.664106702127908, -0.3019385221864369), (5863600815491576320, 197.57760860966175, -61.223065049381034, 0.8380324580451812), (3043230860339354112, 119.94569443417805, -6.457578824082187, 1.8534465115239123), (3347271079826674432, 88.42764677761348, 15.25101781747585, 0.437884708526415), (1357356553418520192, 250.48312535629816, 42.60200925115967, 3.4559200064097557), (1994857037334320128, 357.55340867620885, 55.85235067945313, 0.7829201151939994), (246962715466029952, 58.763240184277954, 48.338291240405226, 1.830820706428805), (5698061231030604800, 122.12149225843018, -24.322108525108256, 1.6427718141304395), (4437633087234044672, 243.71135913408844, 5.270644527568049, 2.3915761856170414), (5683128076418951680, 141.3741047336045, -16.0940114680049, 4.113127956664691), (1391537414987936640, 234.37304117894263, 44.46832704625917, 2.348500351340443), (4289673078801007360, 292.6139402034787, 4.647540829679813, 0.5642802249704864), (6863525689409202688, 298.36804540028146, -24.177887262521477, 1.8738198080231399), (5941688646692903040, 245.12646708548982, -48.27770497297111, 1.515865028922164), (5141764594267690496, 29.032075031435365, -16.843406698000965, 4.5919458101377995), (3045276879679390080, 108.9450651948244, -11.4882418194236, 1.1673031121828528), (1786528033734209024, 324.0459488748863, 19.03751356645885, 3.2605956171090176), (6233739104198284288, 238.5838457063958, -27.366706155629167, 1.500029016927533), (3342099561246852736, 89.89792332183147, 11.008403709774393, 0.8865135426754417), (963228329745438336, 92.50857393591268, 45.36325185226614, 0.16710086896783094), (5627472790686647424, 135.49020952625824, -34.22436428843799, 2.178756501540663), (5196836589084393984, 136.24446253842623, -79.46934451231884, 1.9981900932056313), (194517247771763200, 82.09430495855686, 41.29020023183206, 1.4668918023807607), (6473291695403739904, 301.6358570831209, -53.89681070712948, 4.452121322646476), (4910917867408928768, 19.918083827913748, -56.20550949912544, 2.887154526138282), (546613925052530560, 32.431520941349156, 73.5711480778221, 1.4730211377148266), (1608926806718040832, 212.495203398301, 53.25957502819311, 2.6755774575189233), (4101860652938564352, 283.6805181570442, -14.341590956602133, 5.163550072165438), (1852791235856164608, 317.9540929357317, 31.160227068984568, 2.1422193949181203), (4627677934017834368, 65.92475851267784, -76.9309414209126, 2.7236392925978254), (5084677366437907200, 53.4185968669707, -26.37433872203151, 3.4608632056449324), (437693794946569216, 42.65225776002478, 47.40719450572565, 0.16010790023378516), (3667036445895300992, 215.35203455199954, 3.3375128570643757, 19.891852737856567), (195920740003610112, 84.83625550508464, 42.23021791114751, 0.5243000889424406), (1104475373019753600, 97.26657329487291, 67.34204985192422, 2.5245029987857515), (4719336384404634880, 28.978278635769463, -56.24049085297601, 2.492208561564168), (1879309944486914816, 334.32506027052773, 24.523142210083243, 1.1717083933195227), (259500755795778304, 72.73844485103378, 50.939337839892374, 3.415400966896066), (664294104816946304, 129.64261159828806, 19.860179005899028, 2.783812726150528), (6746976219916427264, 299.42355876405963, -33.88094604016837, 3.3557713062336623), (6370144722895254400, 312.2946538823987, -73.85543945383992, 0.8758672918632926), (1987096821707239296, 339.14157183865746, 48.55328589826451, 1.839033268065), (1754855776662409728, 311.5012784180301, 11.431325618981571, 5.541673421604911), (6846846372893708032, 303.1705789125963, -27.14583014420179, 4.2742204801410475), (2187791984792486144, 305.82705177524446, 57.1295904157308, 4.9353229557340965), (1751517831159106944, 313.16735160983086, 10.613460642508537, 1.2505176078903038), (2570159076180770816, 31.88740014751519, 9.232178685509638, 4.337746856273566), (1430012659738803328, 248.41789149620658, 55.52106414157024, 1.672392259186346), (6716136293150907904, 283.0512494438695, -42.448840815202395, 1.3003293323412497), (4304953541640622976, 297.6741784640513, 12.464689781177592, 2.441387592983599), (3107514941532288768, 106.79268967685387, -4.357635703196695, 0.8789180191628921), (6002234457068832640, 232.47330888990487, -42.526216533607105, 1.2918106376342422), (1625693774925552256, 249.30424864686952, 62.66282743043136, 2.0564904775801875), (514118030696173056, 39.04988791574837, 62.91856708233721, 1.705654439133063), (856522753494113152, 171.6603600682491, 57.99819593616648, 2.6903744984478455), (4475347229423974272, 271.79693979586665, 7.55111653483504, 2.3173114545957345), (3916962516995457024, 175.49834988370563, 12.713858198687065, 1.1929690204148033), (2947485422152845056, 101.16277772151555, -15.442055050236123, 0.9375252359278489), (6551447249649073280, 352.5639800845319, -35.33719380140402, 2.1958311336682046), (5828235127069908352, 248.6866581300159, -64.5396224066724, 1.3382533356928346), (4404187283545621248, 236.37662940311378, -1.2935590826716483, 1.0313477901986543), (6662163706878839040, 284.8713785805594, -48.35150158285654, 3.0161033450404133), (4302366871820098432, 293.11520257700636, 9.34230447403519, 1.1105650769547755), (6544334165330906240, 342.46201302954375, -42.82518352228107, 0.8553283212151912), (5096445508109488128, 63.46166513572207, -17.547651378703133, 2.2582974249837484), (6059456100192004480, 186.76769420206924, -58.715949432193135, 3.3960442681158276), (3253398384820067712, 61.8283374470743, -1.6540442565317315, 2.518905656175099), (6508943806610538880, 332.32760562929286, -54.74816282610644, 2.7140023096374333), (1937380307510515456, 353.26246257405444, 45.38705776937445, 0.12037124772977187), (3907384671205795456, 185.13066459648118, 11.375302020575512, 1.2956204950076287), (5602024972018166400, 118.05615704376335, -26.50786467327983, 1.3236533103158106), (527489569554854528, 10.18827352078161, 65.17631405634343, 1.508142404674546), (1953939502381120512, 324.68324022708015, 39.393540843771305, 1.1584722182711693), (3145093019150065280, 116.57666504802434, 7.654618985156316, 1.061986126891973), (5405078284592269952, 151.78570805377763, -51.33230632571134, 4.841707844654215), (4696175618642342784, 37.60377475775054, -67.17933587601682, 5.601583094248444), (1622684274161356032, 240.8533054872423, 57.866234949800635, 1.6501074290970508), (2923173467715510016, 98.03168588224709, -25.93901182017873, 0.229734243756878), (6416201065959591936, 298.81441783634483, -72.00201311874476, 2.8099905018387608), (4087581982614096768, 288.40169054552035, -18.095114468918624, 1.4553313792680624), (2283182143284884352, 352.40139415419776, 80.33250024387303, 1.2684855794393197), (4421708997766751360, 228.38697941990904, 2.0350481719811304, 0.4018099129904865), (4312466470232658048, 287.28186147932917, 11.122598016663128, 0.8754406467419482), (5711585842530272512, 119.8289531384046, -21.645130612542516, 1.133423220677376), (505066919695316992, 30.53926881166415, 56.87618398790006, 0.7598251173359806), (3336912031025516416, 86.27029014139869, 10.62110322363072, 5.211849904983432), (266922493640452864, 75.93886654101374, 53.564472547735775, 2.2601650006396197), (2056171887372797440, 307.12521402933896, 34.795928463490405, 1.3870047982545664), (5367252129654900352, 157.59048794739746, -45.67220093162539, 1.3555766328806984), (3367189351439047168, 109.55569769657457, 21.951597308172634, 2.8151762637185542), (3068210080894687104, 119.53365892912517, -5.003764875105892, 1.3690523884005363), (2095448813538919552, 277.7296452107307, 35.262593202756264, 0.5807732509961265), (2291103849686229120, 310.98686664576553, 78.83992348157403, 3.42099953611259), (1422204477913493248, 265.7214331284348, 57.514469296089096, 2.5201482408886546), (6178530357621643136, 208.98141995602094, -26.286080801159493, 1.5515344181310078), (5816547043581122560, 258.81292839457444, -65.40396850669761, 2.024978157920707), (306408464454808832, 17.35966451269679, 25.615738316615694, 5.9584686179958855), (4198536827717723520, 285.68395924124394, -12.660255771970125, 0.37170929827755617), (2007602473049351040, 337.5529130824147, 57.16920731782719, 0.674455865415598), (1747435000888629760, 309.8590206045706, 5.243982534050392, 0.6414749903908635), (3125893759426215424, 100.52186337571597, 1.4536408834326007, 1.1979065283543626), (1583422053963912704, 185.1282726849082, 62.29908030690139, 0.8635816907991565), (6884851232825940224, 319.2334045530715, -13.582537669657118, 3.2113788153300415), (241320605906110208, 49.50653976990654, 43.554322432336804, 2.131606384726826), (6366887454058640384, 303.6219537300123, -74.44831380347043, 0.7552501119326266), (1824567390845129088, 297.3364599490322, 18.80661543921698, -0.05887056085983167), (5767668907003538048, 263.88431513565234, -84.10861471179143, 4.2375444789846215), (3047301699065552000, 111.28688005783792, -10.288663872485525, 0.737749493927558), (6710777582711398144, 283.61824633205157, -46.07854585919469, 9.558182392226554), (5615051126790430208, 115.15823154430012, -24.63200524536658, -0.1702921408834644), (2048712869209441280, 295.2261634072697, 36.99349181936747, 1.2259691426820094), (1690347292021755520, 180.5671538673043, 72.36197891752798, 1.5801156356004158), (319201797640741760, 25.473900727583523, 35.92477687351717, 1.3319930986373325), (709782790643651072, 129.7390974868831, 32.05267040668736, 1.2642850521734346), (2053560478539181184, 292.6842648664707, 41.07386316083724, 3.552374977527851), (2505761436056788608, 27.80266831786941, -2.0214347943841555, 2.484499159641729), (5811664352961612928, 260.3181115952028, -67.87141785612941, 0.35202105317853244), (910231628767426816, 129.30095844492283, 37.93492966885963, 1.7884653561003243), (2107827596481921280, 276.42671460689826, 36.53061767629788, 2.5572702339576074), (2836711446720454400, 343.1347604361662, 22.1993753189957, 3.7510822326018856), (5733741414144021504, 133.0044339254858, -14.999078467730822, 2.653422099398614), (5834565049865215744, 243.8887500717668, -59.376120039793726, 6.113109756246911), (1975080705802248064, 331.2135338583582, 46.79644852355548, 2.3649311791760046), (2001312991659139072, 335.80675592033566, 51.770599279031615, 1.2786505917742559), (5696081113668822912, 126.12288949197308, -24.916849570870724, 0.49765155454597854), (976298121385120512, 112.00382867292079, 47.549033752421124, 0.7035913774990202), (4566922632319839488, 259.2740963648293, 21.201093317843288, 3.9010974307516424), (5785781093328833920, 217.75097438643124, -78.2046345667469, 0.6130184244983373), (5827895103091399424, 246.4308213264062, -64.80686938979247, 0.8592056306156404), (1548805407831790080, 181.89812377969224, 52.46687856050902, 3.5178413359637797), (5992465742933341056, 245.28970253787838, -43.14677426684187, -0.30283551136928777), (536240513881329152, 9.111048349943216, 70.79545962416448, 3.167965046335968), (3052564683267442304, 106.22483485249663, -7.016499646065161, 0.7494491349955343), (5822072742349065728, 240.6174647277638, -67.32544068776254, 5.689622795778348), (1071343651700892160, 149.2680493858861, 70.16852165982242, 2.382301521845295), (5529876118514968064, 129.1715191425197, -38.423839872324315, 1.5443713770356993), (3016720501122356224, 83.16365055579084, -6.879663205969146, 2.9352507529627125), (2006161528703191936, 332.72516390663156, 55.77159091281669, 1.6133584829720378), (4577394140542910464, 270.63598788748425, 22.72400650754902, 2.3938824468099598), (1146071066129660800, 138.58035738703967, 83.3468253777415, 3.6788229685256537), (1919605739975504000, 355.542044751613, 39.538549678865245, 2.4630263842004902), (5411306880519669760, 147.73036573523413, -46.5468337434046, 0.9792284126254326), (6873579177057028736, 304.87167861124334, -16.134848626837165, 3.177835832941525), (533572514558050304, 17.371664271735145, 71.37789002518824, 1.5945165813313298), (4503903333107245184, 280.3021958535705, 10.477365933209187, 0.24216590034020913), (5294905913814854272, 119.42690954076205, -57.4791232511399, 2.7041724698013456), (4779013305716010752, 65.47613757691782, -54.62780501374563, 3.0188922001113783), (5644491547058907904, 124.17822264571943, -30.178597866971995, 0.4088654122531259), (6020871763275973504, 250.53548848508143, -34.46200074350077, 10.58915594186968), (4632578972739221888, 40.95958250912916, -78.91510227560197, 1.7611617552957992), (3119793428393630848, 100.28910688043891, 0.7714883829984303, 0.7286879833701705), (999949234973194624, 105.426735940372, 55.36323395852031, 0.9379888676842977), (6054456861338376576, 182.55149929005012, -63.000126184709345, 2.6695865983451434), (6695693039090797056, 307.9017222272132, -34.85529806421848, 1.6126710176878678), (3530202533056735616, 189.62226705862312, -11.446506651660467, 2.7049544946203614), (5908789059765108480, 268.83101893268656, -65.54797697235871, 0.4557780024803932), (5246008707582845952, 148.51715335434014, -66.18329096267277, 0.6188867254956375), (6870319880994945280, 297.7899941646866, -18.90272478820052, 0.8116029674596674), (1427821917180186112, 244.145575705761, 52.59880231133506, 1.4171309293290104), (3158950129835194624, 104.4328810110369, 10.865510008676608, 1.715428015704548), (6243032004674215424, 243.41754601611777, -21.399927540662343, 26.178123000784662), (1939662412613565568, 356.97577279670355, 47.65352781606989, 3.360293336261081), (467017185940744576, 47.10226270065026, 63.49459548543867, 3.705463529781382), (3829602435518075264, 149.8337648575094, -1.9483810418022665, 1.8821182512010481), (5418458619544520192, 151.0600459446952, -42.39142523962082, 1.0039146135713366), (4655871645544693248, 68.7672428124825, -68.87574326823734, 0.8873411178832271), (1708407904380188416, 228.27748356117326, 78.90631910387035, 3.6803152204079), (434117358496267520, 44.844805596968406, 45.81945646608027, 1.1992578865758032), (3055161386134558080, 112.36740551043239, -6.7322206045358435, 2.0751363324239485), (5695713155229971968, 127.56965323580191, -24.439964901362483, 2.041324427467061), (661005912214881024, 130.29315225931438, 19.004483140712065, -1.5798087022688994), (5800828906386796032, 269.0186756444506, -76.72465749919725, 4.943285835581581), (5546984313284742272, 125.52067688631912, -32.69602334617828, 0.6465002816056707), (1946333046581713024, 328.0944301248461, 32.66102512823356, 2.5594207188685827), (6631945382136880640, 280.9522067021427, -61.662123041589346, 0.28121227506894664), (1937798602966189568, 348.97141411117315, 44.52490880278933, 1.2591069559224297), (1953184687648180736, 327.0233860549047, 38.48245359349949, 5.494509404856253), (5818181227105822464, 253.08378156100574, -62.732653642162745, -1.4568839223601016), (6067961922147329792, 198.1294848693552, -53.370345032628286, 1.3871314951698446), (765721681657390848, 174.42785728077206, 36.66291012585338, 4.214077007347959), (3131439592994012416, 96.43371279486166, 4.681767844788531, 2.260028589374711), (6900734777800979328, 307.3750547916264, -12.591410294427956, 4.853641984037333), (2415993973869908224, 358.69418049007805, -15.666213504226745, 0.7977908910590072), (492678172427548928, 50.11954553604683, 67.24369042103625, 2.6205485441219296), (3143168942523212800, 112.85916108153253, 8.319449749530298, 1.5513618394047648), (4973008629058771456, 6.378151266770797, -50.518506689102544, 8.137927811314675), (3737520226477623680, 196.3660481104991, 12.719604018882745, -1.0928492025730492), (5272735773668453248, 127.49161621897785, -67.01883633222451, 4.8184276357995), (2976686698638888192, 74.73176980576491, -18.290011690991513, 0.4862959664807274), (2898824129883683200, 97.87550329229066, -27.361446135670512, 1.698794372611865), (5163245649860235136, 50.83909573235218, -10.602540693477398, 0.6204310334872114), (2404914779312480256, 343.05599806502727, -14.72033807907845, 0.6896452911552622), (5336830223463334144, 169.5926163885845, -62.502437384769806, 0.30739157857557176), (5597222820626610688, 118.25644445973637, -30.034997223778877, 3.621058496301337), (5256497223880270720, 150.90163901471675, -60.47027988617657, 1.1952794750176112), (6565889197440619264, 327.6167922937832, -43.284634415854136, 4.142925432071656), (5635689131842470784, 136.29235733185834, -28.77853554912285, 4.14166789998308), (5241882068647073024, 164.23327403323353, -61.583118342047385, -0.2827747345580186), (2548782783430658688, 4.916165897233899, 3.3420540241833057, 2.6830094826452235), (850438640260614912, 157.90411217432845, 54.55284021028917, 3.4790426793650777), (1316183210212005504, 240.41638599205882, 26.14732427977973, 2.4476460179612984), (3400943946096020736, 83.45125443309404, 19.121226651455114, 1.501268465693585), (6062250646436572800, 198.2242888320236, -58.623411301791194, 0.5099993339514602), (4368180201881219968, 259.3863045320702, -1.0537489510758153, 0.7781235987867052), (5272390149062462464, 130.71334647538674, -66.41330723064362, 0.26047197833355895), (5253460304048452736, 160.09496218865652, -63.11608002966854, 0.9504890253462819), (1365495482083869184, 261.531955427892, 48.272958866631846, 2.230373641502536), (2013142877777926784, 344.25835197904576, 58.068863344896066, 0.811072688079981), (3053189618187938560, 106.24355309377836, -6.087016723052686, 5.145416295137564), (2907772058589501184, 85.81452534747717, -27.44263097174727, 0.43943924471895884), (2242764405086703616, 292.92607171869986, 65.94216783655749, 3.4581103262235406), (5929461080961506048, 252.3128205257523, -55.08212824958407, 1.1303036061721956), (1418545200137033088, 269.7995271365738, 56.74811718224121, 2.6886671358113903), (1951124546455128960, 324.61100900828137, 36.35461023489851, 1.6187889400342321), (6056558165498028416, 190.53619266633848, -60.30693089582088, 0.17602593443594433), (3019766904247040000, 92.46436182307495, -6.41831807044384, 2.3484721132311375), (2771021571194745600, 356.6893925852304, 14.343890523035201, 2.5572176641256057), (2211906645611793792, 343.86479347873683, 65.52731701065971, 1.886732166959084), (4514284303412104960, 285.2354627465393, 17.93443265192153, 1.2553108884424424), (1821875133545986944, 301.63600360226195, 18.01167534757314, 0.5485017387975898), (1210177816709069696, 234.3707247276335, 19.755514229309863, 1.8308210136891534), (1870381600831741568, 311.69384654805384, 36.09415128113382, 0.7290184636078199), (4358918774922618368, 246.01787346388954, -1.3235128091834425, 2.7000366736484307), (6726049867939139968, 273.3186727328759, -39.254494529689595, 3.5350915360116826), (3415594732378152320, 79.73011136346793, 23.077614935477655, 2.209066267352925), (1041562142312028288, 127.68850475971374, 59.9541520315561, 3.3788283424649976), (2033938903274308224, 299.6036208704829, 31.477335104605224, 1.4180263444367025), (5588762765843148416, 114.27586464637598, -34.36925601583143, 1.8348674421823286), (4328185741299776640, 245.21262427433183, -15.703718839761635, 1.4749069547599372), (2195270484927872768, 310.1740864281893, 61.95503667247172, 3.170001217580874), (5827530614992780672, 234.55087360322253, -61.602134589259194, 1.2135122642763212), (1968118769979077120, 318.34139192222017, 39.39535124228027, 0.45067533307277907), (1836591615648030848, 303.11250417163484, 27.42316736106556, 2.81586512893342), (5869762513015412224, 200.1999716870477, -59.99057381906564, 0.6505658676573415), (3381116796510284544, 103.06366497933666, 23.84715572887585, 1.1055917700554432), (6566083742278882176, 326.0782526322966, -43.04715164120706, 1.4826079480261523), (5412318980977931136, 145.7960346671416, -45.36422113692598, 2.502973606091687), (4499684335186358016, 268.3613112363761, 13.606462507866372, 0.6071973367660994), (3360999959968095616, 106.81901403313464, 16.99726862556029, 1.4240104792654689), (218771374766863232, 58.76436087319429, 34.42689726636408, 2.954718432615947), (5299821383628518016, 138.8158069233488, -60.11168862085286, -0.05626408529409066), (5623254754846730112, 137.28601284223035, -36.53859664748668, 3.0863147588920254), (5310179848320347776, 138.9783122913065, -55.50775725520679, 3.879632660179972), (2015471231091965568, 352.01700849370997, 61.35348474418517, 1.1723980141595876), (360189289021936768, 30.791716601132862, 53.424142756496735, 10.40976748759778), (2089426891432810240, 300.4007676640838, 52.60479606705146, 1.4146203354531932), (244275990082115200, 58.2240665360797, 45.943157149837134, 1.1039375941769174), (4508059555770531328, 283.69515982279603, 16.370542071772746, 0.8532897842673677), (6425284818712412160, 311.39294222396694, -66.47055195741457, 2.1198228397888066), (2038360073881169152, 289.7947703609013, 29.35691952912854, 1.7149138527569494), (6735739829555201664, 283.02205869891037, -33.55837818521113, 1.4271978658439441), (4300163347434894336, 299.1683180364063, 9.866418241515797, 0.07508454049167157), (2619497392734477056, 332.8083587051743, -7.8113373825802475, 1.6727003289465263), (1942655729944579456, 349.61748571484395, 48.91870109452333, 0.6486818402723101), (908688326759236352, 122.15078993956095, 38.026505860627964, 1.6205205111621555), (3756086648543640576, 162.90909535295697, -13.846080285532134, 2.078497643681113), (1388781626531516160, 229.05491375558293, 39.768072984279705, 3.4072206297922323), (2424087891278916864, 4.000395544342898, -12.873394792869487, 2.3721978758173274), (511265966248788992, 26.473899652825967, 61.32057321307362, 0.42624082664330526), (5694414013522343296, 124.412056782546, -26.013438260835407, 1.408122748091392), (1764181284534741248, 316.7707469333658, 17.362708384927604, 1.3415711083487873), (6062662688415172352, 203.72566092482077, -57.07365528982863, 2.011322161633824), (923226447458337152, 119.8285618995593, 44.6227724365456, 1.4552795529939355), (6584895561596411520, 328.02927266081645, -39.13384334966808, 0.6543024117437797), (4685940471057489408, 13.276404387333157, -73.10929616754603, 1.1928934202540227), (4504783629598806528, 279.94638577546, 11.427146667950527, 0.6334616688923198), (5958338104596045440, 263.0639542132383, -44.3775956784146, 1.1388451964872983), (4718779275607102720, 26.45319316030045, -57.704216378776145, 1.8135758138607205), (238133362215163904, 53.34896797375853, 41.989470712246764, 0.4156766334016889), (1833124477533999360, 301.42808453010804, 22.88157328220119, 1.796760059471296), (5615603974981389184, 116.44339961256982, -23.54590667593914, 0.5667386037891519), (6640454502623349504, 292.4914721290115, -55.33768961194646, -0.05827746560900404), (3170826435963501440, 66.94980391635355, -18.551618263131466, 4.732507071647512), (4508966171826980096, 278.9855414943001, 14.10517062493307, 0.765131758270654), (2215698277102728320, 359.3872291866926, 71.88443287350724, 4.4473490002666995), (5518749370084428800, 120.2016582074169, -47.06574500223602, 2.284663991012841), (1529336767755478784, 195.139254897373, 43.450924457145405, 4.400698139720543), (889123994811247872, 104.48605458584157, 31.4142957391259, 1.5565401330150086), (5905767670531291136, 220.20043770944872, -48.06074259691938, 2.7585325613682943), (3328615666038632704, 92.78900568324721, 8.875105721726198, 2.277962287052079), (4672162009813796480, 51.165516718782825, -64.78225676549725, 1.1426824558963142), (127146150246484864, 40.976136256992106, 28.01931650275395, 1.8462785354811109), (3140090344324859520, 110.57095220974504, 5.474465556917307, 4.078680099719929), (2123202754767658496, 271.52959848981544, 49.46621378657492, 3.9291266599934396), (2030470803075789184, 300.0522903399013, 30.75439221061101, 1.5063613487438157), (1768282084948239616, 330.69888780818115, 13.860127058506592, 8.14466992622752), (408405176002617088, 28.754952403994363, 54.69182359119669, 1.054239296054107), (2911859905382098432, 92.10702277584049, -26.52787278488774, 2.020011165409731), (4097539709673361920, 273.6778915087229, -16.806152840653176, 1.2712240829233252), (413552539689392640, 17.79560608661978, 57.64259952300637, 1.6439842595852037), (2582925643130232576, 16.76178420745296, 10.350672430760246, 0.7105388254468297), (3219490030335532928, 85.84090394333218, 0.8839405594341206, 2.3606260818877742), (4442661841101016448, 253.094289205925, 8.478229893094017, 0.43108974727015803), (6387583630146799616, 348.24524401587735, -69.67410522258989, 1.5100484188176784), (2079243627053201920, 298.7789385003953, 45.37627850843616, 1.6475672402965942), (4812382281027738624, 76.54546355997661, -44.05681050248313, 1.54523369654281), (6300014366582724352, 216.83270711311593, -13.981788402668268, 6.515318865681108), (1055523466083677440, 163.6865737175564, 64.63634806217522, 11.385673727667765), (816946794524070400, 137.89295568566064, 42.700201362629635, 11.1368162116025), (5783457756539687168, 207.1375457640033, -80.8119713643751, 1.5875927816759827), (3142424607510419584, 111.59609564326861, 6.413239851126887, 1.1619679925247106), (3110067079815717120, 109.43092384471431, -1.1782693282636565, 1.6227355724267254), (1459731771842102784, 198.33881156616957, 26.0642023941496, 1.6935735738288058), (1006904436292893824, 96.18192939031434, 62.163938700775944, 1.6199491041285794), (6807875557636873216, 316.60508667773036, -22.284672163716102, 3.701765671555045), (6632877596199432448, 282.69024921510436, -60.35637005618916, 0.82634065102551), (5558498502130035200, 106.47851319458101, -44.46337436687433, 1.3027932717281632), (1251381327765178368, 206.5116130578582, 22.66192251675151, 2.781479957464986), (1237495732856971264, 220.57718563205938, 19.273849999684142, 0.5126088918240601), (5792943758750836352, 224.80476803214887, -75.29599976650141, 0.8492952570415929), (2155134324785248000, 286.1897881602378, 58.52646928040076, 0.5405398002074667), (5624515001327844736, 137.7697999992758, -34.957570029683744, 2.132526021492563), (2011004774341548160, 354.02505399137914, 58.39580184103589, 3.9620340972303216), (4944035741753308800, 32.66289293577877, -44.746273054006195, 2.5676286713610517), (5164024447690089472, 54.633319901462336, -10.189261045205514, 1.6073954511673043), (3008128126988365184, 94.87371119157014, -6.437711829546466, 1.170819013135819), (3050986299966448896, 103.00019789153971, -8.414800572105058, 1.1362719258475842), (2820568313921522944, 354.2756255100649, 17.00765817075942, 3.3735494644317994), (2107136897021705088, 284.769403838435, 45.45660419499806, 3.596821649098966), (5977226821006023168, 256.6639618017894, -35.64330963798951, 1.0185247008999543), (1791915228393428480, 321.1182632219579, 22.617084400920174, 1.5609679984464728), (1704950524425777024, 253.35389565720527, 76.85062906520693, 0.8111233916636073), (5787500385916696064, 180.65861254149604, -79.72468033047879, 5.186375155478564), (1947908131348338304, 328.64821075737365, 33.64032373554216, 2.502011773720228), (438473657925247872, 39.54389375883848, 48.76558925818444, 5.800262994801619), (6730514297467875712, 281.0332534518849, -36.718517288885174, 9.20653057267865), (6056278236709561600, 191.17748966760846, -61.060136285865646, 0.22559444605888904), (4924362420715177344, 5.973843665197128, -52.684215145299106, 1.736392133121908), (4838513068214537984, 60.91254142584844, -44.09229104590682, 2.3830488553977913), (687002421545091968, 138.81122087066717, 23.37954393465703, 6.413906503270961), (2049375221887602304, 289.8834301326914, 34.38615286676428, 0.9738845903401864), (5460347916617041792, 151.2558870394601, -31.720352205217388, 3.698961015209335), (3054796107759272192, 111.32196739051982, -7.246398043946898, 4.719934585109565), (242345316383197184, 50.41238125955912, 45.6334080571971, 0.7183146624593092), (5867783838760730880, 213.3056526101796, -59.25420889488407, 0.4787138604038833), (5953659854422124800, 259.7534507521879, -42.76991928722192, 0.8118320496358611), (5540582338116035456, 122.41422226078002, -39.68853067429192, 1.0413770012177488), (2094890021113833856, 280.761241791514, 35.32558559241401, 1.5697478294253693), (1898136607212745344, 329.1996054819142, 31.64705233051325, 0.9445143865344084), (5798535943606865536, 227.26359495552035, -71.31050330218997, 1.613508142549333), (6085538611950499840, 194.38901463032235, -48.9367855799492, 1.692522319496745), (1709420382789856384, 245.7285993817712, 79.38301364598959, 0.9273107036866564), (458391963897553408, 36.09844840308373, 56.901484346557325, 0.4151869487955834), (6639600697485301760, 289.2959168579609, -57.64102326033174, 0.26723335806769255), (6041147925919859712, 239.06763254211847, -28.95088335822856, 3.400246177712695), (4144896259594940800, 268.91049779091907, -16.56271482787047, 1.0853613134805242), (5303922046607265536, 135.19318583261162, -57.53480330518871, 1.9446473646057905), (6685041348397087360, 297.33027237292026, -44.64945738083494, 1.4784363709827217), (6066182328219403648, 206.53213043627713, -52.51407580012271, 6.716103465427168), (3181042410814573056, 70.37283642825648, -12.018593017038635, 21.93667773460837), (1755508439892628224, 308.15817424433584, 11.97673621876042, 0.7775947205115336), (1995702974094932992, 350.4197606936642, 53.468899054501925, 2.384420833201223), (6086307926491468416, 198.2166311847988, -46.28360344355555, 1.873144683270956), (6674846848383973248, 308.2912974357645, -45.82200224549341, 1.3033152371440972), (2000253715281776640, 336.3373235389818, 50.42646531871588, 1.9828836025370278), (3237836034679328896, 81.01277376011411, 5.829890452994216, 0.6129314884644572), (2055716930078983808, 302.7270703892669, 34.55353206323099, 0.7755229929650329), (1975659083280109184, 333.51315151111544, 48.56408504398184, 1.532607412824539), (5356920225054055424, 152.89937799688497, -52.2436538972726, 1.0118016933800327), (3342867089082328704, 88.94716166426811, 11.70119951196444, 2.090604708319788), (4100497533391778304, 281.1969059143269, -14.945381297675326, 1.2665436301561372), (6071915869037474944, 186.27724770655144, -56.733148149888024, 1.556220984524395), (4303741295710453888, 297.87582616665526, 11.777572298770416, 0.8857778114453718), (4478249871396095104, 274.08847483156114, 7.989539877725431, 1.5468919800229897), (1888892669359312000, 341.18959738086926, 31.35061406803212, 3.455830684938177), (1714779849140682240, 209.1086327226333, 77.45602808803058, 3.58011624636226), (4955746983697804416, 26.996091925737666, -44.06110540345441, 5.549713756282843), (3029311008773344768, 116.32759258626263, -15.214107092962221, 0.1485853119697902), (5237375307920444672, 172.88296349580182, -64.778577333011, 0.1276173957435658), (1633140732821283200, 264.8402821532432, 65.331051607975, 1.4177530759760297), (2733242111146102272, 340.38065449537055, 15.414096974514333, 0.8577057745350596), (4788527654709307392, 65.94309305080358, -49.145299940032224, 8.254812444730206), (5613725768602359424, 112.21126485689183, -24.908199289832826, 4.871035024400391), (2921812375399048064, 102.25338207069171, -25.108742473393676, 3.9748757323316166), (2060678029621794048, 304.43086994722245, 37.86944818779334, 0.4551470412236404), (150736653256756736, 64.69259577118667, 26.14914724135843, 8.14290811118061), (6369391694869201792, 313.8447118503095, -75.69460910863053, 0.9137803740119267), (5885200687059802240, 234.71194194510954, -54.61523165248951, 2.80751572097647), (2202588765602782208, 327.74496768848894, 58.93003074416142, 2.221155255006875), (4062774388951361792, 269.6370385943312, -27.658307905785826, 0.6292476860415365), (2340964468622028672, 358.9850148975946, -22.102425115063056, 1.5276144070204167), (6383793544846964608, 334.83036086213656, -70.18274342617035, 0.6503352801219535), (1974720821901728896, 327.6189387063451, 47.204386077726035, 1.9330364715321877), (5340852133918246656, 167.77423186973152, -56.44002014547152, 1.0551274284176904), (1712680778363586560, 206.78350863947028, 75.29213068349655, 2.112827600854583), (3049758729592384384, 106.40253461473141, -9.271748097361353, 0.16409685186777365), (1402491333939099264, 236.2061111786836, 49.58407953830531, 0.7046159474176104), (4005195473265993600, 174.54203808782353, 24.4747596875282, 4.579354988959037), (5697588887708714496, 120.9882192935645, -25.01868550497485, 0.9294490757043727), (5524785963793908224, 133.67092688800867, -40.39142068040598, 1.006060949097541), (5260747248634957568, 98.41337770993741, -75.67515807596817, 1.3411579155116615), (1669952004161536512, 217.1291104383875, 66.58759212663549, 3.4244536752429053), (427521079005638656, 12.166366848232634, 62.09415179688783, 1.3663853788060032), (741497756870248960, 155.46721268431503, 29.26827473178248, 2.636228496486356), (1352402600699629696, 252.64378902025095, 38.65471687015788, 0.7512152963170797), (4304305173376798976, 299.3731977798933, 13.003613796431111, 1.0620247071018123), (5335391753014883072, 176.8801525423946, -60.55391843223085, 0.15099062421645776), (1537785037146452224, 180.38205019611885, 43.51087431323797, 3.229671011176495), (5334118484190379008, 174.59724549612238, -62.25773210247916, 0.04938902750735402), (4290227644971260544, 295.14286629077714, 4.478862672658671, 0.24975641925447728), (4477626001633374976, 277.3638530495481, 7.847516612723427, 1.5583548933797202), (1995604602166974976, 347.91459887343154, 53.7187671092559, 1.2650314776874243), (6066748370546368128, 197.30970170630516, -55.47591688994854, 0.5646133633456256), (3053884097221231104, 112.37891982817828, -8.072587590973543, 5.024054437110714), (1927756282233216384, 343.4135573470291, 36.91874015609018, -1.3854649227924858), (4044831733580137344, 277.3549605076638, -33.802567081514376, 1.218814522941229), (2244334713849830656, 301.2362210354316, 63.97940783025732, 2.869860794323662), (1222117207317093888, 231.3919589536803, 25.27270837710308, 0.8707992291059694), (5257431843122010624, 148.7886993721187, -59.79056308434814, 1.2556980318947824), (3134267193303249664, 100.87094916996521, 8.333528092634785, 0.6532759847944019), (4102114365246315776, 283.0401311734917, -14.006967231837335, 1.7970369142424105), (342033122232192384, 38.245367559709635, 46.3750919412455, 13.090089813106646), (3115319515580217472, 107.79528575174645, 3.0535019666338545, 0.47292411031077636), (958165628454204288, 96.89323200664843, 40.69414523410923, 0.901051723254265), (1678183326164190848, 200.8324634770485, 65.52379551092235, 1.2867694786503605), (3046795683197130496, 109.64994062614441, -11.279661771168172, -0.12560620728004232), (4188997602265564288, 299.33144347784514, -12.570135226338197, 56.259002184476174), (3308058784328624256, 70.74142060191829, 13.006222748610782, 6.592233627355095), (5259049637041604480, 152.7400881495241, -56.404885118162625, 0.7972904168441391), (2890917885364962944, 90.83765810288396, -31.590924649192026, 3.5212762535836384), (4674094985615456000, 52.9995866409554, -62.62563512903896, 2.8095818726999306), (6709878766312642944, 279.10713735184856, -44.310918217163746, 9.533538624390108), (5216491252783254016, 133.58112529396257, -75.34293162143942, 2.479323495154715), (383412314629686400, 4.527777121525927, 40.95867417106836, 2.8162523651863065), (4640832525491709312, 45.37153765604483, -73.5143212372769, 4.696317819516305), (5979785040968280192, 257.18059562789784, -33.06371827092422, 2.289467752589112), (4062649353863432320, 269.45392664774727, -28.271081631955102, 1.781734707660729), (5700389756140489472, 124.8813652932042, -21.25626188272681, 2.49915421021963), (5261705850975708032, 90.36031724009075, -75.30904095678758, 1.1747837695655825), (2021465493609223552, 294.1108926456953, 25.157146206825633, 2.1334117207187377), (6066633643384918272, 196.2817902251773, -56.44566610917119, 0.7627739888137207), (3544700659020710912, 170.68819986775839, -20.673882769481537, 1.9697259081784464), (6334130631844309760, 224.00759687872548, -5.877239202415627, 3.7622707004777185), (5542897016247433728, 124.67401655251084, -36.39832460309018, 0.25903319479177844), (205790609208774528, 75.49830590588988, 44.833684864989785, 1.41318115385007), (1420235561825735808, 257.80817943427917, 55.03194445818792, 1.470467743802613), (2156804276788137216, 283.837938812671, 61.31683879274979, 0.9365808353436674), (3557967022724185856, 168.60891303771768, -18.63439818449431, 2.343017744073615), (4347532266864682624, 237.82483221826377, -9.347409309210608, 4.8916214322202025), (6465330647103246848, 320.9887792366942, -52.23391608272088, 2.210605518611175), (1749090624882307456, 309.3579904021981, 7.333497085089419, 2.6154672678160047), (5839020717659803648, 198.65483842161007, -74.35709548800659, 2.908024535312859), (521309214694645376, 29.992135575744282, 68.48492343818256, 3.1535835219805914), (1807437824318589184, 298.6304237424348, 14.544664711774043, -0.21675858588762875), (6388197501232545408, 349.0704371269249, -67.42865162721702, 2.4746788076337825), (5864658580036150912, 206.4033599740251, -63.003663386332356, 1.0467879278143766), (4095462697848263168, 272.83073854721874, -19.361209637008493, 0.4400722020424058), (211843833039640192, 79.88282451584016, 46.48541336283945, 1.0538046169830653), (5792221070372135552, 230.1050926554705, -76.29838295546232, 4.566538287333624), (1961611722721929728, 331.79910067668436, 43.05512762392738, 2.1865836856679333), (6293917127929813248, 208.03472501865795, -18.40475227016662, 0.5136958361213984), (6815897182156610944, 324.3131217660995, -22.946524181881816, 7.847377908834952), (5404323401135307264, 150.0339225690951, -54.1293075211864, 0.74380127066132), (5811918099630669440, 268.73050064181894, -69.03393260459865, 0.9400012731629591), (51539470113340160, 58.48789776369158, 20.5911450103525, 0.9478463001057296), (5677240741408782080, 143.35118656006728, -20.287353783286466, 1.818541652207927), (5813388146674531328, 259.6002808139107, -66.38450847310435, 2.5354116147997514), (1625216999196518016, 246.32422460233184, 61.61029015013231, 4.985804861171507), (5480046629502315008, 99.80329847936689, -60.88747763101423, 3.452415316421113), (1942005987289288192, 351.2251828007112, 48.28795771982447, 1.8669548156223403), (5053537754030562176, 50.14635931195658, -33.64186024487064, 2.6159184623135667), (4148685451546376448, 267.6542006749632, -14.68833525606908, 1.850490300137809), (5363272893996312320, 163.9267844591309, -47.40328544921011, 1.1417678642051008), (1887854833463057664, 341.01445289149405, 29.475114727412805, 0.9991317339632735), (4003533973757100544, 182.31563645334123, 26.221858311055687, 1.579040612808396), (4563765522118163584, 248.58773594372013, 19.84237629985432, 0.5336563752874721), (2921800830528643712, 102.2172323561006, -25.317491036427164, 0.7441469028839811), (4118779456824964736, 267.54579421785905, -20.710432598717635, 1.210223703926884), (2051862214109441536, 292.9114464731913, 37.97285261470771, 0.3887573495350394), (5007420319351560960, 9.997082008103433, -31.713001700264158, 1.9286467549707569), (991875108773568640, 100.9221920695523, 52.137289060189914, 1.8071890767819456), (1335753795632702720, 261.601794410802, 34.55814722429771, 4.04751114618354), (6275222647118768384, 210.74312004577004, -24.341897803874264, 4.062924926890417), (6715948826412188288, 284.9406918298079, -40.847503098304514, 0.5424338126969047), (2361815847648888320, 6.020797691259604, -20.606345682851003, 3.4159112041939683), (2044769127167211520, 292.6468713182319, 31.220083266912376, 0.3697061146050896), (780807221709126400, 159.46845767872034, 43.12972124197941, 1.8553169917197598), (5479751067033106048, 106.8563154932373, -59.13459843545477, 1.253038825250482), (4244731571800898432, 306.08100732312306, 2.9165187264959362, 2.4010229135492747), (514239526727700736, 38.55489351816485, 63.75877643098371, 2.3826502758856445), (5371586404490961280, 177.67919779367813, -47.34584947411728, 0.9919722686429224), (5305691229529343104, 143.56622469253045, -58.42603901707127, 1.4125180552980001), (6352570197757121664, 354.1115755177217, -79.54760919573378, 2.0010741034603803), (5856936366279305600, 193.02785271485723, -69.24638203737439, -0.0248480651038413), (6839034617656267392, 328.692123603581, -15.921045443524674, 0.7206668613073337), (1809444810996162176, 302.16639796422277, 16.56225892616167, 2.9513663536428107), (144903469194050944, 69.37922185089302, 22.045037392230583, 1.4111827980953633), (1825169545260655104, 293.7426381791492, 18.8596820688171, 2.3392003436014477), (6055695014511783808, 195.53851517652478, -61.312829730623925, 1.0968558042706302), (5320821265443260672, 123.03816261204655, -52.62216352443331, 0.9143199610786799), (4000045292081651840, 180.6141291320667, 21.470212335523193, 2.712771457981342), (5372936432972451456, 173.08121452937846, -50.371661275322445, 0.7267289750369323), (5408728182155143424, 150.87936745446277, -45.85059508160045, 1.9007042201191653), (6228630120337853568, 223.16054862702515, -26.330335628237236, 0.5386122429694504), (3157321787475015680, 103.48033343349238, 8.17597786868757, 0.8631524442129036), (4620147962993968512, 44.062566623228214, -81.00635922070279, 17.45011404698758), (6779149785568920960, 310.80207381020256, -36.330699846434676, 0.4625950779684942), (6642148472086005632, 295.2429042820772, -53.662425947818825, 3.8628944509529792), (1562399185481775744, 206.02571715683163, 55.63499516206163, 3.4550098235800606), (2879976954395122048, 357.6141303213232, 38.15195091452653, 1.5456159836260202), (1214098778253031296, 229.58689851120224, 20.80288737381246, 2.38691693860298), (5346775031259565056, 170.3648144777791, -53.838107342863786, -0.25355057836183326), (5000231884127681792, 9.761774094076412, -39.275710955737814, 1.2270269687866795), (1979857705866695552, 328.2349190443785, 50.70525118448075, 0.9299659562318152), (3234209742251380352, 80.57327869133076, 1.847473056091652, 3.2279403821669277), (1005148928540517888, 96.44863649289493, 59.81527352207677, 9.939824058098338), (4154175072584453248, 276.35343587199395, -11.065860897704068, 0.8934724945945114), (2050802972096291328, 288.53868382634687, 36.77027602676289, 3.2180246473511773), (4917568297849042432, 26.036517980648508, -49.65329728863575, 2.615987673898351), (1752150497022878464, 307.34851636196294, 8.561014777660636, 1.0375002756224183), (2949139087639982464, 101.85991338211079, -14.199393146748898, 6.008677928325195), (558340285282080000, 84.71490909809704, 83.3560978850052, 2.123488400553013), (504558704803469184, 30.526113356987956, 55.52585556455743, 1.4136209169994312), (6138063931673889280, 200.28696762895166, -40.33710438838876, 11.779645970177132), (4037589731519792512, 272.8120301046634, -37.660785504535696, 1.0761193597979688), (5323396012436387968, 135.9123516238848, -53.4875590129914, 1.219003184667209), (4015609841245603840, 186.85336198826926, 32.232697741361605, 3.524864350011763), (1905632596453246720, 336.7378283433477, 34.94158497924343, 1.41612111039749), (2829730647395447168, 341.3309304809787, 17.016729374149378, 7.370708473551929), (2142140090208489088, 293.01069904272, 56.88976624947178, 1.4130088214923524), (5315276325224967936, 129.54906109307964, -56.68424473249127, 2.3095506293827266), (3425803594762898176, 94.94460635070477, 24.835216707991222, 3.3500513331486745), (4100805396646241408, 284.7096436249701, -15.245248269138388, 1.962456390320352), (5936273139617337728, 253.19417681827468, -51.88958868220065, 0.8173056483690779), (3105128795140296576, 98.88866025675138, -3.1723295978664607, 1.1805663910198314), (166311888300640256, 65.11265797684706, 31.61027636898189, 1.6946883505910202), (3474382767256782080, 182.08453359429177, -28.110473450538823, 1.0233165577652716), (2199375786469582720, 329.1004644538899, 57.870930729293214, 1.7268611099337947), (6128173893300854528, 192.03906130280095, -47.51076278451834, 0.8643427384166149), (5835593780432956032, 239.96628014032723, -58.21611528439116, 2.5609482057427013), (554765051425761152, 66.5228219653617, 78.70946719524933, 2.960657172492275), (6799392997227129856, 307.8950242366761, -27.889952902482754, 2.3286507763463433), (5542217449344292736, 126.70483654884414, -36.13159915804269, 2.184025461376234), (3051261177873210752, 106.53051461534656, -9.16578673005903, 1.1898824644487485), (5244636001675582336, 155.11385115529555, -68.02362884215505, 0.4285336572611983), (844814603925361536, 173.46837052698706, 56.04372951390135, 3.6139197949326154), (5871901647250074752, 206.31838630006573, -57.283873994161866, 1.4436003543034255), (5952625007816343936, 261.5506763323443, -43.67884483794954, 0.032043963835554745), (5797542878448261376, 211.8081817270665, -72.96875642939374, 0.5781328999008393), (5300209030197034880, 140.0043298659502, -60.0352291369262, 1.9087854068845607), (2976974805045375616, 69.79883985661138, -21.297533234096687, 2.5394219353093703), (3207536552234191360, 79.18697669287558, -6.871295773893602, 4.121956385715596), (6402063373651091968, 327.5145302675287, -64.93491145737266, 0.9275208804358829), (1616396476403531776, 230.86317484426485, 61.5855051468262, 5.879229597748249), (426515300742998528, 14.35833231031586, 60.364297128737064, 7.389350221525991), (3093988508965694464, 121.14702609567406, 2.7299941375654946, 3.7539481404467825), (3168854221341546368, 114.10846222073273, 15.901908441447304, 0.761222339866361), (5815052291885773824, 254.66190060715087, -66.36223290449006, 0.9938950058951364), (5835690743611534720, 240.76030136150106, -57.82740951735657, 5.032307841676071), (6584748604995404672, 326.6010240413469, -39.263338932385544, 3.6387852107043424), (3336792115540170240, 88.52673654991882, 10.805575299699951, 2.97221284069588), (892384218586296576, 114.05217187846897, 32.274318930386606, 4.34145915016135), (2059762789272769664, 299.81615050857584, 36.71869514281724, 8.244723996519735), (5851275255783884928, 211.49422070166108, -65.3540697274737, 2.6997068576530037), (6595656035221248640, 340.4192844914046, -37.38773006111629, 4.076530968965266), (1037839402099261696, 134.24230987001178, 58.7557252117823, 2.5374185391451647), (5308407057609677312, 146.84232439116693, -54.69093187976363, 1.04005558452934), (2877696773437582208, 3.168408941439168, 37.72394217412003, 2.4711020534722463), (5559493628873202688, 105.09560674641865, -43.500807374218
1,524
","uid":251753,"time":"2015-12-10 13:11:30","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/pcsh-pastacode-syntaxhighlighter.zip?timestamp=1449753090"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/pcsh-pastacode-syntaxhighlighter\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/pcsh-pastacode-syntaxhighlighter\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/bu/buddypress-ajax-chat/package.json ======================= {"packages":{"wpackagist-plugin\/buddypress-ajax-chat":{"1.4.4":{"name":"wpackagist-plugin\/buddypress-ajax-chat","version":"1.4.4","version_normalized":"1.4.4.0","uid":54008,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/buddypress-ajax-chat.zip?timestamp=1306187836"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/buddypress-ajax-chat\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/buddypress-ajax-chat\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.0.0":{"name":"wpackagist-plugin\/buddypress-ajax-chat","version":"1.0.0","version_normalized":"1.0.0.0","uid":54009,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/buddypress-ajax-chat.1.0.0.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/buddypress-ajax-chat\/","reference":"tags\/1.0.0"},"homepage":"https:\/\/wordpress.org\/plugins\/buddypress-ajax-chat\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.0.1":{"name":"wpackagist-plugin\/buddypress-ajax-chat","version":"1.0.1","version_normalized":"1.0.1.0","uid":54010,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/buddypress-ajax-chat.1.0.1.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/buddypress-ajax-chat\/","reference":"tags\/1.0.1"},"homepage":"https:\/\/wordpress.org\/plugins\/buddypress-ajax-chat\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.1.2":{"name":"wpackagist-plugin\/buddypress-ajax-chat","version":"1.1.2","version_normalized":"1.1.2.0","uid":54011,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/buddypress-ajax-chat.1.1.2.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/buddypress-ajax-chat\/","reference":"tags\/1.1.2"},"homepage":"https:\/\/wordpress.org\/plugins\/buddypress-ajax-chat\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.2.6":{"name":"wpackagist-plugin\/buddypress-ajax-chat","version":"1.2.6","version_normalized":"1.2.6.0","uid":54012,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/buddypress-ajax-chat.1.2.6.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/buddypress-ajax-chat\/","reference":"tags\/1.2.6"},"homepage":"https:\/\/wordpress.org\/plugins\/buddypress-ajax-chat\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.2.8":{"name":"wpackagist-plugin\/buddypress-ajax-chat","version":"1.2.8","version_normalized":"1.2.8.0","uid":54013,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/buddypress-ajax-chat.1.2.8.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/buddypress-ajax-chat\/","reference":"tags\/1.2.8"},"homepage":"https:\/\/wordpress.org\/plugins\/buddypress-ajax-chat\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.2.9":{"name":"wpackagist-plugin\/buddypress-ajax-chat","version":"1.2.9","version_normalized":"1.2.9.0","uid":54014,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/buddypress-ajax-chat.1.2.9.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/buddypress-ajax-chat\/","reference":"tags\/1.2.9"},"homepage":"https:\/\/wordpress.org\/plugins\/buddypress-ajax-chat\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.3.9":{"name":"wpackagist-plugin\/buddypress-ajax-chat","version":"1.3.9","version_normalized":"1.3.9.0","uid":54015,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/buddypress-ajax-chat.1.3.9.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/buddypress-ajax-chat\/","reference":"tags\/1.3.9"},"homepage":"https:\/\/wordpress.org\/plugins\/buddypress-ajax-chat\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/buddypress-ajax-chat","version":"dev-trunk","version_normalized":"9999999-dev","uid":54016,"time":"2011-05-23 21:57:16","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/buddypress-ajax-chat.zip?timestamp=1306187836"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/buddypress-ajax-chat\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/buddypress-ajax-chat\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/em/empathy/package.json ======================= <gh_stars>1-10 {"packages":{"wpackagist-plugin\/empathy":{"1":{"name":"wpackagist-plugin\/empathy","version":1,"version_normalized":"1.0.0.0","uid":119019,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/empathy.1.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/empathy\/","reference":"tags\/1"},"homepage":"https:\/\/wordpress.org\/plugins\/empathy\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.0.1":{"name":"wpackagist-plugin\/empathy","version":"1.0.1","version_normalized":"1.0.1.0","uid":119020,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/empathy.1.0.1.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/empathy\/","reference":"tags\/1.0.1"},"homepage":"https:\/\/wordpress.org\/plugins\/empathy\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.0.2":{"name":"wpackagist-plugin\/empathy","version":"1.0.2","version_normalized":"1.0.2.0","uid":119021,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/empathy.1.0.2.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/empathy\/","reference":"tags\/1.0.2"},"homepage":"https:\/\/wordpress.org\/plugins\/empathy\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.0.3":{"name":"wpackagist-plugin\/empathy","version":"1.0.3","version_normalized":"1.0.3.0","uid":119022,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/empathy.1.0.3.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/empathy\/","reference":"tags\/1.0.3"},"homepage":"https:\/\/wordpress.org\/plugins\/empathy\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/empathy","version":"dev-trunk","version_normalized":"9999999-dev","uid":119023,"time":"2009-11-18 00:37:24","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/empathy.zip?timestamp=1258504644"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/empathy\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/empathy\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/go/google-analytics-link/package.json ======================= {"packages":{"wpackagist-plugin\/google-analytics-link":{"1.6":{"name":"wpackagist-plugin\/google-analytics-link","version":"1.6","version_normalized":"1.6.0.0","uid":154683,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/google-analytics-link.zip?timestamp=1418831698"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/google-analytics-link\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/google-analytics-link\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/google-analytics-link","version":"dev-trunk","version_normalized":"9999999-dev","uid":154684,"time":"2014-12-17 15:54:58","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/google-analytics-link.zip?timestamp=1418831698"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/google-analytics-link\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/google-analytics-link\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/tw/twitter-follow-button-in-comments/package.json ======================= <gh_stars>1-10 {"packages":{"wpackagist-plugin\/twitter-follow-button-in-comments":{"0.2":{"name":"wpackagist-plugin\/twitter-follow-button-in-comments","version":"0.2","version_normalized":"0.2.0.0","uid":363451,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/twitter-follow-button-in-comments.0.2.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/twitter-follow-button-in-comments\/","reference":"tags\/0.2"},"homepage":"https:\/\/wordpress.org\/plugins\/twitter-follow-button-in-comments\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.3":{"name":"wpackagist-plugin\/twitter-follow-button-in-comments","version":"0.3","version_normalized":"0.3.0.0","uid":363452,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/twitter-follow-button-in-comments.0.3.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/twitter-follow-button-in-comments\/","reference":"tags\/0.3"},"homepage":"https:\/\/wordpress.org\/plugins\/twitter-follow-button-in-comments\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.5":{"name":"wpackagist-plugin\/twitter-follow-button-in-comments","version":"0.5","version_normalized":"0.5.0.0","uid":363453,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/twitter-follow-button-in-comments.0.5.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/twitter-follow-button-in-comments\/","reference":"tags\/0.5"},"homepage":"https:\/\/wordpress.org\/plugins\/twitter-follow-button-in-comments\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/twitter-follow-button-in-comments","version":"dev-trunk","version_normalized":"9999999-dev","uid":363454,"time":"2013-02-20 23:21:50","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/twitter-follow-button-in-comments.zip?timestamp=1361402510"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/twitter-follow-button-in-comments\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/twitter-follow-button-in-comments\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-theme/sm/smile/package.json ======================= {"packages":{"wpackagist-theme\/smile":{"1.0":{"name":"wpackagist-theme\/smile","version":"1.0","version_normalized":"1.0.0.0","uid":326091,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/smile.1.0.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/smile\/","reference":"1.0"},"homepage":"https:\/\/wordpress.org\/themes\/smile\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.0.1":{"name":"wpackagist-theme\/smile","version":"1.0.1","version_normalized":"1.0.1.0","uid":326092,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/smile.1.0.1.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/smile\/","reference":"1.0.1"},"homepage":"https:\/\/wordpress.org\/themes\/smile\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.0.2":{"name":"wpackagist-theme\/smile","version":"1.0.2","version_normalized":"1.0.2.0","uid":326093,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/smile.1.0.2.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/smile\/","reference":"1.0.2"},"homepage":"https:\/\/wordpress.org\/themes\/smile\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.0.3":{"name":"wpackagist-theme\/smile","version":"1.0.3","version_normalized":"1.0.3.0","uid":326094,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/smile.1.0.3.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/smile\/","reference":"1.0.3"},"homepage":"https:\/\/wordpress.org\/themes\/smile\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.0.4":{"name":"wpackagist-theme\/smile","version":"1.0.4","version_normalized":"1.0.4.0","uid":326095,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/smile.1.0.4.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/smile\/","reference":"1.0.4"},"homepage":"https:\/\/wordpress.org\/themes\/smile\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"}}}} ======================= File: data/wpackagist-plugin/hi/hilightsticky/package.json ======================= {"packages":{"wpackagist-plugin\/hilightsticky":{"V1.05":{"name":"wpackagist-plugin\/hilightsticky","version":"V1.05","version_normalized":"1.05.0.0","uid":166073,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/hilightsticky.zip?timestamp=1282612454"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/hilightsticky\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/hilightsticky\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/hilightsticky","version":"dev-trunk","version_normalized":"9999999-dev","uid":166074,"time":"2010-08-24 01:14:14","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/hilightsticky.zip?timestamp=1282612454"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/hilightsticky\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/hilightsticky\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/wp/wp-togetherjs/package.json ======================= {"packages":{"wpackagist-plugin\/wp-togetherjs":{"1.0.1":{"name":"wpackagist-plugin\/wp-togetherjs","version":"1.0.1","version_normalized":"1.0.1.0","uid":436796,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/wp-togetherjs.1.0.1.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/wp-togetherjs\/","reference":"tags\/1.0.1"},"homepage":"https:\/\/wordpress.org\/plugins\/wp-togetherjs\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/wp-togetherjs","version":"dev-trunk","version_normalized":"9999999-dev","uid":436797,"time":"2013-09-30 14:03:02","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/wp-togetherjs.zip?timestamp=1380549782"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/wp-togetherjs\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/wp-togetherjs\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/st/statpress-dashboard-widget-lite/package.json ======================= {"packages":{"wpackagist-plugin\/statpress-dashboard-widget-lite":{"1.1.0":{"name":"wpackagist-plugin\/statpress-dashboard-widget-lite","version":"1.1.0","version_normalized":"1.1.0.0","uid":336699,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/statpress-dashboard-widget-lite.1.1.0.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/statpress-dashboard-widget-lite\/","reference":"tags\/1.1.0"},"homepage":"https:\/\/wordpress.org\/plugins\/statpress-dashboard-widget-lite\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.1.1":{"name":"wpackagist-plugin\/statpress-dashboard-widget-lite","version":"1.1.1","version_normalized":"1.1.1.0","uid":336700,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/statpress-dashboard-widget-lite.1.1.1.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/statpress-dashboard-widget-lite\/","reference":"tags\/1.1.1"},"homepage":"https:\/\/wordpress.org\/plugins\/statpress-dashboard-widget-lite\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"2.0":{"name":"wpackagist-plugin\/statpress-dashboard-widget-lite","version":"2.0","version_normalized":"2.0.0.0","uid":336701,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/statpress-dashboard-widget-lite.2.0.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/statpress-dashboard-widget-lite\/","reference":"tags\/2.0"},"homepage":"https:\/\/wordpress.org\/plugins\/statpress-dashboard-widget-lite\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/statpress-dashboard-widget-lite","version":"dev-trunk","version_normalized":"9999999-dev","uid":336702,"time":"2011-01-04 17:01:48","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/statpress-dashboard-widget-lite.zip?timestamp=1294160508"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/statpress-dashboard-widget-lite\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/statpress-dashboard-widget-lite\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/aj/ajax-yandexmetrika/package.json ======================= <filename>data/wpackagist-plugin/aj/ajax-yandexmetrika/package.json {"packages":{"wpackagist-plugin\/ajax-yandexmetrika":{"2.1.0":{"name":"wpackagist-plugin\/ajax-yandexmetrika","version":"2.1.0","version_normalized":"2.1.0.0","uid":16542,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/ajax-yandexmetrika.zip?timestamp=1333830321"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/ajax-yandexmetrika\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/ajax-yandexmetrika\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/ajax-yandexmetrika","version":"dev-trunk","version_normalized":"9999999-dev","uid":16543,"time":"2012-04-07 20:25:21","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/ajax-yandexmetrika.zip?timestamp=1333830321"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/ajax-yandexmetrika\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/ajax-yandexmetrika\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/na/naytev-integegration/package.json ======================= {"packages":{"wpackagist-plugin\/naytev-integegration":{"1.0.0":{"name":"wpackagist-plugin\/naytev-integegration","version":"1.0.0","version_normalized":"1.0.0.0","uid":229834,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/naytev-integegration.1.0.0.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/naytev-integegration\/","reference":"tags\/1.0.0"},"homepage":"https:\/\/wordpress.org\/plugins\/naytev-integegration\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.1.0":{"name":"wpackagist-plugin\/naytev-integegration","version":"1.1.0","version_normalized":"1.1.0.0","uid":229835,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/naytev-integegration.1.1.0.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/naytev-integegration\/","reference":"tags\/1.1.0"},"homepage":"https:\/\/wordpress.org\/plugins\/naytev-integegration\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"2.1.0":{"name":"wpackagist-plugin\/naytev-integegration","version":"2.1.0","version_normalized":"2.1.0.0","uid":229836,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/naytev-integegration.2.1.0.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/naytev-integegration\/","reference":"tags\/2.1.0"},"homepage":"https:\/\/wordpress.org\/plugins\/naytev-integegration\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"2.2.0":{"name":"wpackagist-plugin\/naytev-integegration","version":"2.2.0","version_normalized":"2.2.0.0","uid":229837,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/naytev-integegration.2.2.0.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/naytev-integegration\/","reference":"tags\/2.2.0"},"homepage":"https:\/\/wordpress.org\/plugins\/naytev-integegration\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"2.2.1":{"name":"wpackagist-plugin\/naytev-integegration","version":"2.2.1","version_normalized":"2.2.1.0","uid":229838,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/naytev-integegration.2.2.1.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/naytev-integegration\/","reference":"tags\/2.2.1"},"homepage":"https:\/\/wordpress.org\/plugins\/naytev-integegration\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"2.2.3":{"name":"wpackagist-plugin\/naytev-integegration","version":"2.2.3","version_normalized":"2.2.3.0","uid":229839,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/naytev-integegration.2.2.3.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/naytev-integegration\/","reference":"tags\/2.2.3"},"homepage":"https:\/\/wordpress.org\/plugins\/naytev-integegration\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"2.2.4":{"name":"wpackagist-plugin\/naytev-integegration","version":"2.2.4","version_normalized":"2.2.4.0","uid":229840,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/naytev-integegration.2.2.4.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/naytev-integegration\/","reference":"tags\/2.2.4"},"homepage":"https:\/\/wordpress.org\/plugins\/naytev-integegration\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/naytev-integegration","version":"dev-trunk","version_normalized":"9999999-dev","uid":229841,"time":"2014-09-29 22:36:28","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/naytev-integegration.zip?timestamp=1412030188"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/naytev-integegration\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/naytev-integegration\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/rs/rss-feeds-disabler/package.json ======================= <reponame>wplib/wpackagist-requestor {"packages":{"wpackagist-plugin\/rss-feeds-disabler":{"1.0":{"name":"wpackagist-plugin\/rss-feeds-disabler","version":"1.0","version_normalized":"1.0.0.0","uid":295602,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/rss-feeds-disabler.1.0.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/rss-feeds-disabler\/","reference":"tags\/1.0"},"homepage":"https:\/\/wordpress.org\/plugins\/rss-feeds-disabler\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/rss-feeds-disabler","version":"dev-trunk","version_normalized":"9999999-dev","uid":295603,"time":"2011-09-27 06:46:10","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/rss-feeds-disabler.zip?timestamp=1317105970"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/rss-feeds-disabler\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/rss-feeds-disabler\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-theme/gr/green-hope/package.json ======================= {"packages":{"wpackagist-theme\/green-hope":{"1.0":{"name":"wpackagist-theme\/green-hope","version":"1.0","version_normalized":"1.0.0.0","uid":159768,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/green-hope.1.0.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/green-hope\/","reference":"1.0"},"homepage":"https:\/\/wordpress.org\/themes\/green-hope\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.1":{"name":"wpackagist-theme\/green-hope","version":"1.1","version_normalized":"1.1.0.0","uid":159769,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/green-hope.1.1.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/green-hope\/","reference":"1.1"},"homepage":"https:\/\/wordpress.org\/themes\/green-hope\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.2":{"name":"wpackagist-theme\/green-hope","version":"1.2","version_normalized":"1.2.0.0","uid":159770,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/green-hope.1.2.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/green-hope\/","reference":"1.2"},"homepage":"https:\/\/wordpress.org\/themes\/green-hope\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.2.1":{"name":"wpackagist-theme\/green-hope","version":"1.2.1","version_normalized":"1.2.1.0","uid":159771,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/green-hope.1.2.1.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/green-hope\/","reference":"1.2.1"},"homepage":"https:\/\/wordpress.org\/themes\/green-hope\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.2.2":{"name":"wpackagist-theme\/green-hope","version":"1.2.2","version_normalized":"1.2.2.0","uid":159772,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/green-hope.1.2.2.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/green-hope\/","reference":"1.2.2"},"homepage":"https:\/\/wordpress.org\/themes\/green-hope\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.2.3":{"name":"wpackagist-theme\/green-hope","version":"1.2.3","version_normalized":"1.2.3.0","uid":159773,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/green-hope.1.2.3.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/green-hope\/","reference":"1.2.3"},"homepage":"https:\/\/wordpress.org\/themes\/green-hope\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.2.4":{"name":"wpackagist-theme\/green-hope","version":"1.2.4","version_normalized":"1.2.4.0","uid":159774,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/green-hope.1.2.4.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/green-hope\/","reference":"1.2.4"},"homepage":"https:\/\/wordpress.org\/themes\/green-hope\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.2.5":{"name":"wpackagist-theme\/green-hope","version":"1.2.5","version_normalized":"1.2.5.0","uid":159775,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/green-hope.1.2.5.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/green-hope\/","reference":"1.2.5"},"homepage":"https:\/\/wordpress.org\/themes\/green-hope\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.2.6":{"name":"wpackagist-theme\/green-hope","version":"1.2.6","version_normalized":"1.2.6.0","uid":159776,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/green-hope.1.2.6.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/green-hope\/","reference":"1.2.6"},"homepage":"https:\/\/wordpress.org\/themes\/green-hope\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.2.7":{"name":"wpackagist-theme\/green-hope","version":"1.2.7","version_normalized":"1.2.7.0","uid":159777,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/green-hope.1.2.7.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/green-hope\/","reference":"1.2.7"},"homepage":"https:\/\/wordpress.org\/themes\/green-hope\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"}}}} ======================= File: data/wpackagist-plugin/ne/neonternetics/package.json ======================= <gh_stars>1-10 {"packages":{"wpackagist-plugin\/neonternetics":{"172.16.17.328":{"name":"wpackagist-plugin\/neonternetics","version":"1.10.3.28","version_normalized":"172.16.17.328","uid":230486,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/neonternetics.1.10.3.28.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/neonternetics\/","reference":"tags\/1.10.3.28"},"homepage":"https:\/\/wordpress.org\/plugins\/neonternetics\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/neonternetics","version":"dev-trunk","version_normalized":"9999999-dev","uid":230487,"time":"2010-03-28 16:56:09","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/neonternetics.zip?timestamp=1269795369"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/neonternetics\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/neonternetics\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/sh/shieldpass-two-factor-authentication/package.json ======================= <reponame>wplib/wpackagist-requestor {"packages":{"wpackagist-plugin\/shieldpass-two-factor-authentication":{"2.2":{"name":"wpackagist-plugin\/shieldpass-two-factor-authentication","version":"2.2","version_normalized":"2.2.0.0","uid":308618,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/shieldpass-two-factor-authentication.zip?timestamp=1321934283"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/shieldpass-two-factor-authentication\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/shieldpass-two-factor-authentication\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/shieldpass-two-factor-authentication","version":"dev-trunk","version_normalized":"9999999-dev","uid":308619,"time":"2011-11-22 03:58:03","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/shieldpass-two-factor-authentication.zip?timestamp=1321934283"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/shieldpass-two-factor-authentication\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/shieldpass-two-factor-authentication\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-theme/mo/modern-blue/package.json ======================= {"packages":{"wpackagist-theme\/modern-blue":{"2.0":{"name":"wpackagist-theme\/modern-blue","version":"2.0","version_normalized":"2.0.0.0","uid":220865,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/modern-blue.2.0.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/modern-blue\/","reference":"2.0"},"homepage":"https:\/\/wordpress.org\/themes\/modern-blue\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"}}}} ======================= File: data/wpackagist-theme/ha/hamid-bakeri/package.json ======================= <reponame>wplib/wpackagist-requestor<filename>data/wpackagist-theme/ha/hamid-bakeri/package.json {"packages":{"wpackagist-theme\/hamid-bakeri":{"1.00":{"name":"wpackagist-theme\/hamid-bakeri","version":"1.00","version_normalized":"1.00.0.0","uid":162232,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/hamid-bakeri.1.00.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/hamid-bakeri\/","reference":"1.00"},"homepage":"https:\/\/wordpress.org\/themes\/hamid-bakeri\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.10":{"name":"wpackagist-theme\/hamid-bakeri","version":"1.10","version_normalized":"1.10.0.0","uid":162233,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/hamid-bakeri.1.10.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/hamid-bakeri\/","reference":"1.10"},"homepage":"https:\/\/wordpress.org\/themes\/hamid-bakeri\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.80":{"name":"wpackagist-theme\/hamid-bakeri","version":"1.80","version_normalized":"1.80.0.0","uid":162234,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/hamid-bakeri.1.80.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/hamid-bakeri\/","reference":"1.80"},"homepage":"https:\/\/wordpress.org\/themes\/hamid-bakeri\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"}}}} ======================= File: data/wpackagist-plugin/da/daumview/package.json ======================= <reponame>wplib/wpackagist-requestor<gh_stars>1-10 {"packages":{"wpackagist-plugin\/daumview":{"1.0":{"name":"wpackagist-plugin\/daumview","version":"1.0","version_normalized":"1.0.0.0","uid":95212,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/daumview.1.0.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/daumview\/","reference":"tags\/1.0"},"homepage":"https:\/\/wordpress.org\/plugins\/daumview\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.1":{"name":"wpackagist-plugin\/daumview","version":"1.1","version_normalized":"1.1.0.0","uid":95213,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/daumview.1.1.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/daumview\/","reference":"tags\/1.1"},"homepage":"https:\/\/wordpress.org\/plugins\/daumview\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.2":{"name":"wpackagist-plugin\/daumview","version":"1.2","version_normalized":"1.2.0.0","uid":95214,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/daumview.1.2.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/daumview\/","reference":"tags\/1.2"},"homepage":"https:\/\/wordpress.org\/plugins\/daumview\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.3":{"name":"wpackagist-plugin\/daumview","version":"1.3","version_normalized":"1.3.0.0","uid":95215,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/daumview.1.3.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/daumview\/","reference":"tags\/1.3"},"homepage":"https:\/\/wordpress.org\/plugins\/daumview\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.4":{"name":"wpackagist-plugin\/daumview","version":"1.4","version_normalized":"1.4.0.0","uid":95216,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/daumview.1.4.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/daumview\/","reference":"tags\/1.4"},"homepage":"https:\/\/wordpress.org\/plugins\/daumview\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.5":{"name":"wpackagist-plugin\/daumview","version":"1.5","version_normalized":"1.5.0.0","uid":95217,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/daumview.1.5.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/daumview\/","reference":"tags\/1.5"},"homepage":"https:\/\/wordpress.org\/plugins\/daumview\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.6":{"name":"wpackagist-plugin\/daumview","version":"1.6","version_normalized":"1.6.0.0","uid":95218,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/daumview.1.6.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/daumview\/","reference":"tags\/1.6"},"homepage":"https:\/\/wordpress.org\/plugins\/daumview\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.7":{"name":"wpackagist-plugin\/daumview","version":"1.7","version_normalized":"1.7.0.0","uid":95219,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/daumview.1.7.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/daumview\/","reference":"tags\/1.7"},"homepage":"https:\/\/wordpress.org\/plugins\/daumview\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.8":{"name":"wpackagist-plugin\/daumview","version":"1.8","version_normalized":"1.8.0.0","uid":95220,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/daumview.1.8.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/daumview\/","reference":"tags\/1.8"},"homepage":"https:\/\/wordpress.org\/plugins\/daumview\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/daumview","version":"dev-trunk","version_normalized":"9999999-dev","uid":95221,"time":"2014-04-26 07:30:35","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/daumview.zip?timestamp=1398497435"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/daumview\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/daumview\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/ex/excerpt-length/package.json ======================= {"packages":{"wpackagist-plugin\/excerpt-length":{"1.1":{"name":"wpackagist-plugin\/excerpt-length","version":"1.1","version_normalized":"1.1.0.0","uid":124557,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/excerpt-length.zip?timestamp=1246356385"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/excerpt-length\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/excerpt-length\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.0":{"name":"wpackagist-plugin\/excerpt-length","version":"1.0","version_normalized":"1.0.0.0","uid":124558,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/excerpt-length.1.0.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/excerpt-length\/","reference":"tags\/1.0"},"homepage":"https:\/\/wordpress.org\/plugins\/excerpt-length\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/excerpt-length","version":"dev-trunk","version_normalized":"9999999-dev","uid":124559,"time":"2009-06-30 10:06:25","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/excerpt-length.zip?timestamp=1246356385"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/excerpt-length\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/excerpt-length\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/wp/wp-widget-bundle/package.json ======================= {"packages":{"wpackagist-plugin\/wp-widget-bundle":{"1.0.0":{"name":"wpackagist-plugin\/wp-widget-bundle","version":"1.0.0","version_normalized":"1.0.0.0","uid":439041,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/wp-widget-bundle.zip?timestamp=1439442226"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/wp-widget-bundle\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/wp-widget-bundle\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/wp-widget-bundle","version":"dev-trunk","version_normalized":"9999999-dev","uid":439042,"time":"2015-08-13 05:03:46","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/wp-widget-bundle.zip?timestamp=1439442226"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/wp-widget-bundle\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/wp-widget-bundle\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/au/author-social-links/package.json ======================= {"packages":{"wpackagist-plugin\/author-social-links":{"0.0.1":{"name":"wpackagist-plugin\/author-social-links","version":"0.0.1","version_normalized":"0.0.1.0","uid":29912,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/author-social-links.zip?timestamp=1335119680"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/author-social-links\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/author-social-links\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/author-social-links","version":"dev-trunk","version_normalized":"9999999-dev","uid":29913,"time":"2012-04-22 18:34:40","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/author-social-links.zip?timestamp=1335119680"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/author-social-links\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/author-social-links\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/wp/wp-cards/package.json ======================= {"packages":{"wpackagist-plugin\/wp-cards":{"1.0":{"name":"wpackagist-plugin\/wp-cards","version":"1.0","version_normalized":"1.0.0.0","uid":409197,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/wp-cards.1.0.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/wp-cards\/","reference":"tags\/1.0"},"homepage":"https:\/\/wordpress.org\/plugins\/wp-cards\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.1":{"name":"wpackagist-plugin\/wp-cards","version":"1.1","version_normalized":"1.1.0.0","uid":409198,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/wp-cards.1.1.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/wp-cards\/","reference":"tags\/1.1"},"homepage":"https:\/\/wordpress.org\/plugins\/wp-cards\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.2":{"name":"wpackagist-plugin\/wp-cards","version":"1.2","version_normalized":"1.2.0.0","uid":409199,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/wp-cards.1.2.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/wp-cards\/","reference":"tags\/1.2"},"homepage":"https:\/\/wordpress.org\/plugins\/wp-cards\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.2.1":{"name":"wpackagist-plugin\/wp-cards","version":"1.2.1","version_normalized":"1.2.1.0","uid":409200,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/wp-cards.1.2.1.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/wp-cards\/","reference":"tags\/1.2.1"},"homepage":"https:\/\/wordpress.org\/plugins\/wp-cards\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.3":{"name":"wpackagist-plugin\/wp-cards","version":"1.3","version_normalized":"1.3.0.0","uid":409201,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/wp-cards.1.3.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/wp-cards\/","reference":"tags\/1.3"},"homepage":"https:\/\/wordpress.org\/plugins\/wp-cards\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.3.1":{"name":"wpackagist-plugin\/wp-cards","version":"1.3.1","version_normalized":"1.3.1.0","uid":409202,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/wp-cards.1.3.1.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/wp-cards\/","reference":"tags\/1.3.1"},"homepage":"https:\/\/wordpress.org\/plugins\/wp-cards\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.4":{"name":"wpackagist-plugin\/wp-cards","version":"1.4","version_normalized":"1.4.0.0","uid":409203,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/wp-cards.1.4.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/wp-cards\/","reference":"tags\/1.4"},"homepage":"https:\/\/wordpress.org\/plugins\/wp-cards\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.5":{"name":"wpackagist-plugin\/wp-cards","version":"1.5","version_normalized":"1.5.0.0","uid":409204,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/wp-cards.1.5.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/wp-cards\/","reference":"tags\/1.5"},"homepage":"https:\/\/wordpress.org\/plugins\/wp-cards\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.5.1":{"name":"wpackagist-plugin\/wp-cards","version":"1.5.1","version_normalized":"1.5.1.0","uid":409205,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/wp-cards.1.5.1.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/wp-cards\/","reference":"tags\/1.5.1"},"homepage":"https:\/\/wordpress.org\/plugins\/wp-cards\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/wp-cards","version":"dev-trunk","version_normalized":"9999999-dev","uid":409206,"time":"2015-07-27 20:52:18","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/wp-cards.zip?timestamp=1438030338"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/wp-cards\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/wp-cards\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/al/all-in-one-gallery/package.json ======================= {"packages":{"wpackagist-plugin\/all-in-one-gallery":{"0.4":{"name":"wpackagist-plugin\/all-in-one-gallery","version":"0.4","version_normalized":"0.4.0.0","uid":17914,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/all-in-one-gallery.0.4.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/all-in-one-gallery\/","reference":"tags\/0.4"},"homepage":"https:\/\/wordpress.org\/plugins\/all-in-one-gallery\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.5":{"name":"wpackagist-plugin\/all-in-one-gallery","version":"0.5","version_normalized":"0.5.0.0","uid":17915,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/all-in-one-gallery.0.5.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/all-in-one-gallery\/","reference":"tags\/0.5"},"homepage":"https:\/\/wordpress.org\/plugins\/all-in-one-gallery\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.6":{"name":"wpackagist-plugin\/all-in-one-gallery","version":"0.6","version_normalized":"0.6.0.0","uid":17916,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/all-in-one-gallery.0.6.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/all-in-one-gallery\/","reference":"tags\/0.6"},"homepage":"https:\/\/wordpress.org\/plugins\/all-in-one-gallery\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.6.1":{"name":"wpackagist-plugin\/all-in-one-gallery","version":"0.6.1","version_normalized":"0.6.1.0","uid":17917,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/all-in-one-gallery.0.6.1.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/all-in-one-gallery\/","reference":"tags\/0.6.1"},"homepage":"https:\/\/wordpress.org\/plugins\/all-in-one-gallery\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.7":{"name":"wpackagist-plugin\/all-in-one-gallery","version":"0.7","version_normalized":"0.7.0.0","uid":17918,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/all-in-one-gallery.0.7.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/all-in-one-gallery\/","reference":"tags\/0.7"},"homepage":"https:\/\/wordpress.org\/plugins\/all-in-one-gallery\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.0":{"name":"wpackagist-plugin\/all-in-one-gallery","version":"1.0","version_normalized":"1.0.0.0","uid":17919,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/all-in-one-gallery.1.0.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/all-in-one-gallery\/","reference":"tags\/1.0"},"homepage":"https:\/\/wordpress.org\/plugins\/all-in-one-gallery\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.9":{"name":"wpackagist-plugin\/all-in-one-gallery","version":"1.9","version_normalized":"1.9.0.0","uid":17920,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/all-in-one-gallery.1.9.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/all-in-one-gallery\/","reference":"tags\/1.9"},"homepage":"https:\/\/wordpress.org\/plugins\/all-in-one-gallery\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"2.0":{"name":"wpackagist-plugin\/all-in-one-gallery","version":"2.0","version_normalized":"2.0.0.0","uid":17921,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/all-in-one-gallery.2.0.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/all-in-one-gallery\/","reference":"tags\/2.0"},"homepage":"https:\/\/wordpress.org\/plugins\/all-in-one-gallery\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"2.1":{"name":"wpackagist-plugin\/all-in-one-gallery","version":"2.1","version_normalized":"2.1.0.0","uid":17922,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/all-in-one-gallery.2.1.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/all-in-one-gallery\/","reference":"tags\/2.1"},"homepage":"https:\/\/wordpress.org\/plugins\/all-in-one-gallery\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/all-in-one-gallery","version":"dev-trunk","version_normalized":"9999999-dev","uid":17923,"time":"2010-04-29 09:52:59","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/all-in-one-gallery.zip?timestamp=1272534779"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/all-in-one-gallery\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/all-in-one-gallery\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/up/update-notifications/package.json ======================= <filename>data/wpackagist-plugin/up/update-notifications/package.json {"packages":{"wpackagist-plugin\/update-notifications":{"0.2.0":{"name":"wpackagist-plugin\/update-notifications","version":"0.2.0","version_normalized":"0.2.0.0","uid":369411,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/update-notifications.0.2.0.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/update-notifications\/","reference":"tags\/0.2.0"},"homepage":"https:\/\/wordpress.org\/plugins\/update-notifications\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.2.2":{"name":"wpackagist-plugin\/update-notifications","version":"0.2.2","version_normalized":"0.2.2.0","uid":369412,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/update-notifications.0.2.2.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/update-notifications\/","reference":"tags\/0.2.2"},"homepage":"https:\/\/wordpress.org\/plugins\/update-notifications\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.2.3":{"name":"wpackagist-plugin\/update-notifications","version":"0.2.3","version_normalized":"0.2.3.0","uid":369413,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/update-notifications.0.2.3.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/update-notifications\/","reference":"tags\/0.2.3"},"homepage":"https:\/\/wordpress.org\/plugins\/update-notifications\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.2.4":{"name":"wpackagist-plugin\/update-notifications","version":"0.2.4","version_normalized":"0.2.4.0","uid":369414,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/update-notifications.0.2.4.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/update-notifications\/","reference":"tags\/0.2.4"},"homepage":"https:\/\/wordpress.org\/plugins\/update-notifications\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.3":{"name":"wpackagist-plugin\/update-notifications","version":"0.3","version_normalized":"0.3.0.0","uid":369415,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/update-notifications.0.3.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/update-notifications\/","reference":"tags\/0.3"},"homepage":"https:\/\/wordpress.org\/plugins\/update-notifications\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.3.1":{"name":"wpackagist-plugin\/update-notifications","version":"0.3.1","version_normalized":"0.3.1.0","uid":369416,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/update-notifications.0.3.1.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/update-notifications\/","reference":"tags\/0.3.1"},"homepage":"https:\/\/wordpress.org\/plugins\/update-notifications\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.3.2":{"name":"wpackagist-plugin\/update-notifications","version":"0.3.2","version_normalized":"0.3.2.0","uid":369417,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/update-notifications.0.3.2.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/update-notifications\/","reference":"tags\/0.3.2"},"homepage":"https:\/\/wordpress.org\/plugins\/update-notifications\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.3.3":{"name":"wpackagist-plugin\/update-notifications","version":"0.3.3","version_normalized":"0.3.3.0","uid":369418,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/update-notifications.0.3.3.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/update-notifications\/","reference":"tags\/0.3.3"},"homepage":"https:\/\/wordpress.org\/plugins\/update-notifications\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.3.4":{"name":"wpackagist-plugin\/update-notifications","version":"0.3.4","version_normalized":"0.3.4.0","uid":369419,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/update-notifications.0.3.4.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/update-notifications\/","reference":"tags\/0.3.4"},"homepage":"https:\/\/wordpress.org\/plugins\/update-notifications\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/update-notifications","version":"dev-trunk","version_normalized":"9999999-dev","uid":369420,"time":"2011-09-14 14:52:12","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/update-notifications.zip?timestamp=1316011932"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/update-notifications\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/update-notifications\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/po/potenza-slider/package.json ======================= {"packages":{"wpackagist-plugin\/potenza-slider":{"1.0":{"name":"wpackagist-plugin\/potenza-slider","version":"1.0","version_normalized":"1.0.0.0","uid":266673,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/potenza-slider.zip?timestamp=1388214934"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/potenza-slider\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/potenza-slider\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/potenza-slider","version":"dev-trunk","version_normalized":"9999999-dev","uid":266674,"time":"2013-12-28 07:15:34","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/potenza-slider.zip?timestamp=1388214934"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/potenza-slider\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/potenza-slider\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-theme/re/restaurant/package.json ======================= <reponame>wplib/wpackagist-requestor {"packages":{"wpackagist-theme\/restaurant":{"1.01":{"name":"wpackagist-theme\/restaurant","version":"1.01","version_normalized":"1.01.0.0","uid":290670,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/restaurant.1.01.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/restaurant\/","reference":"1.01"},"homepage":"https:\/\/wordpress.org\/themes\/restaurant\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.02":{"name":"wpackagist-theme\/restaurant","version":"1.02","version_normalized":"1.02.0.0","uid":290671,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/restaurant.1.02.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/restaurant\/","reference":"1.02"},"homepage":"https:\/\/wordpress.org\/themes\/restaurant\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.03":{"name":"wpackagist-theme\/restaurant","version":"1.03","version_normalized":"1.03.0.0","uid":290672,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/restaurant.1.03.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/restaurant\/","reference":"1.03"},"homepage":"https:\/\/wordpress.org\/themes\/restaurant\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.04":{"name":"wpackagist-theme\/restaurant","version":"1.04","version_normalized":"1.04.0.0","uid":290673,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/restaurant.1.04.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/restaurant\/","reference":"1.04"},"homepage":"https:\/\/wordpress.org\/themes\/restaurant\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.05":{"name":"wpackagist-theme\/restaurant","version":"1.05","version_normalized":"1.05.0.0","uid":290674,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/restaurant.1.05.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/restaurant\/","reference":"1.05"},"homepage":"https:\/\/wordpress.org\/themes\/restaurant\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.06":{"name":"wpackagist-theme\/restaurant","version":"1.06","version_normalized":"1.06.0.0","uid":290675,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/restaurant.1.06.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/restaurant\/","reference":"1.06"},"homepage":"https:\/\/wordpress.org\/themes\/restaurant\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.07":{"name":"wpackagist-theme\/restaurant","version":"1.07","version_normalized":"1.07.0.0","uid":290676,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/restaurant.1.07.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/restaurant\/","reference":"1.07"},"homepage":"https:\/\/wordpress.org\/themes\/restaurant\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.08":{"name":"wpackagist-theme\/restaurant","version":"1.08","version_normalized":"1.08.0.0","uid":290677,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/restaurant.1.08.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/restaurant\/","reference":"1.08"},"homepage":"https:\/\/wordpress.org\/themes\/restaurant\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.09":{"name":"wpackagist-theme\/restaurant","version":"1.09","version_normalized":"1.09.0.0","uid":290678,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/restaurant.1.09.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/restaurant\/","reference":"1.09"},"homepage":"https:\/\/wordpress.org\/themes\/restaurant\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.10":{"name":"wpackagist-theme\/restaurant","version":"1.10","version_normalized":"1.10.0.0","uid":290679,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/restaurant.1.10.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/restaurant\/","reference":"1.10"},"homepage":"https:\/\/wordpress.org\/themes\/restaurant\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"}}}} ======================= File: data/wpackagist-plugin/hu/humanized-history-for-wordpress/package.json ======================= {"packages":{"wpackagist-plugin\/humanized-history-for-wordpress":{"2007.10.08":{"name":"wpackagist-plugin\/humanized-history-for-wordpress","version":"2007.10.08","version_normalized":"2007.10.08.0","uid":169308,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/humanized-history-for-wordpress.2007.10.08.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/humanized-history-for-wordpress\/","reference":"tags\/2007.10.08"},"homepage":"https:\/\/wordpress.org\/plugins\/humanized-history-for-wordpress\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"2007.11.29":{"name":"wpackagist-plugin\/humanized-history-for-wordpress","version":"2007.11.29","version_normalized":"2007.11.29.0","uid":169309,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/humanized-history-for-wordpress.2007.11.29.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/humanized-history-for-wordpress\/","reference":"tags\/2007.11.29"},"homepage":"https:\/\/wordpress.org\/plugins\/humanized-history-for-wordpress\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"2008.02.10":{"name":"wpackagist-plugin\/humanized-history-for-wordpress","version":"2008.02.10","version_normalized":"2008.02.10.0","uid":169310,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/humanized-history-for-wordpress.2008.02.10.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/humanized-history-for-wordpress\/","reference":"tags\/2008.02.10"},"homepage":"https:\/\/wordpress.org\/plugins\/humanized-history-for-wordpress\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/humanized-history-for-wordpress","version":"dev-trunk","version_normalized":"9999999-dev","uid":169311,"time":"2008-02-26 00:03:56","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/humanized-history-for-wordpress.zip?timestamp=1203984236"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/humanized-history-for-wordpress\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/humanized-history-for-wordpress\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/dy/dynamic-registration-links/package.json ======================= <reponame>wplib/wpackagist-requestor {"packages":{"wpackagist-plugin\/dynamic-registration-links":{"1.0":{"name":"wpackagist-plugin\/dynamic-registration-links","version":"1.0","version_normalized":"1.0.0.0","uid":106799,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/dynamic-registration-links.1.0.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/dynamic-registration-links\/","reference":"tags\/1.0"},"homepage":"https:\/\/wordpress.org\/plugins\/dynamic-registration-links\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.0.1":{"name":"wpackagist-plugin\/dynamic-registration-links","version":"1.0.1","version_normalized":"1.0.1.0","uid":106800,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/dynamic-registration-links.1.0.1.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/dynamic-registration-links\/","reference":"tags\/1.0.1"},"homepage":"https:\/\/wordpress.org\/plugins\/dynamic-registration-links\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/dynamic-registration-links","version":"dev-trunk","version_normalized":"9999999-dev","uid":106801,"time":"2012-02-24 08:57:16","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/dynamic-registration-links.zip?timestamp=1330073836"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/dynamic-registration-links\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/dynamic-registration-links\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/wp/wpbizplugins-easy-admin-quick-menu/package.json ======================= <reponame>wplib/wpackagist-requestor<filename>data/wpackagist-plugin/wp/wpbizplugins-easy-admin-quick-menu/package.json {"packages":{"wpackagist-plugin\/wpbizplugins-easy-admin-quick-menu":{"1.2.5":{"name":"wpackagist-plugin\/wpbizplugins-easy-admin-quick-menu","version":"1.2.5","version_normalized":"1.2.5.0","uid":440175,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/wpbizplugins-easy-admin-quick-menu.1.2.5.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/wpbizplugins-easy-admin-quick-menu\/","reference":"tags\/1.2.5"},"homepage":"https:\/\/wordpress.org\/plugins\/wpbizplugins-easy-admin-quick-menu\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.2.6":{"name":"wpackagist-plugin\/wpbizplugins-easy-admin-quick-menu","version":"1.2.6","version_normalized":"1.2.6.0","uid":440176,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/wpbizplugins-easy-admin-quick-menu.1.2.6.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/wpbizplugins-easy-admin-quick-menu\/","reference":"tags\/1.2.6"},"homepage":"https:\/\/wordpress.org\/plugins\/wpbizplugins-easy-admin-quick-menu\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.2.7":{"name":"wpackagist-plugin\/wpbizplugins-easy-admin-quick-menu","version":"1.2.7","version_normalized":"1.2.7.0","uid":440177,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/wpbizplugins-easy-admin-quick-menu.1.2.7.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/wpbizplugins-easy-admin-quick-menu\/","reference":"tags\/1.2.7"},"homepage":"https:\/\/wordpress.org\/plugins\/wpbizplugins-easy-admin-quick-menu\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.2.8":{"name":"wpackagist-plugin\/wpbizplugins-easy-admin-quick-menu","version":"1.2.8","version_normalized":"1.2.8.0","uid":440178,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/wpbizplugins-easy-admin-quick-menu.1.2.8.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/wpbizplugins-easy-admin-quick-menu\/","reference":"tags\/1.2.8"},"homepage":"https:\/\/wordpress.org\/plugins\/wpbizplugins-easy-admin-quick-menu\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/wpbizplugins-easy-admin-quick-menu","version":"dev-trunk","version_normalized":"9999999-dev","uid":440179,"time":"2015-01-25 14:24:19","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/wpbizplugins-easy-admin-quick-menu.zip?timestamp=1422195859"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/wpbizplugins-easy-admin-quick-menu\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/wpbizplugins-easy-admin-quick-menu\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/re/recipe-snippets/package.json ======================= {"packages":{"wpackagist-plugin\/recipe-snippets":{"1.0.0":{"name":"wpackagist-plugin\/recipe-snippets","version":"1.0.0","version_normalized":"1.0.0.0","uid":284238,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/recipe-snippets.zip?timestamp=1447463912"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/recipe-snippets\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/recipe-snippets\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/recipe-snippets","version":"dev-trunk","version_normalized":"9999999-dev","uid":284239,"time":"2015-11-14 01:18:32","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/recipe-snippets.zip?timestamp=1447463912"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/recipe-snippets\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/recipe-snippets\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/cl/clickworkercom-seo/package.json ======================= {"packages":{"wpackagist-plugin\/clickworkercom-seo":{"0.93":{"name":"wpackagist-plugin\/clickworkercom-seo","version":"0.93","version_normalized":"0.93.0.0","uid":71169,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/clickworkercom-seo.0.93.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/clickworkercom-seo\/","reference":"tags\/0.93"},"homepage":"https:\/\/wordpress.org\/plugins\/clickworkercom-seo\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.94":{"name":"wpackagist-plugin\/clickworkercom-seo","version":"0.94","version_normalized":"0.94.0.0","uid":71170,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/clickworkercom-seo.0.94.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/clickworkercom-seo\/","reference":"tags\/0.94"},"homepage":"https:\/\/wordpress.org\/plugins\/clickworkercom-seo\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.95":{"name":"wpackagist-plugin\/clickworkercom-seo","version":"0.95","version_normalized":"0.95.0.0","uid":71171,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/clickworkercom-seo.0.95.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/clickworkercom-seo\/","reference":"tags\/0.95"},"homepage":"https:\/\/wordpress.org\/plugins\/clickworkercom-seo\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.96":{"name":"wpackagist-plugin\/clickworkercom-seo","version":"0.96","version_normalized":"0.96.0.0","uid":71172,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/clickworkercom-seo.0.96.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/clickworkercom-seo\/","reference":"tags\/0.96"},"homepage":"https:\/\/wordpress.org\/plugins\/clickworkercom-seo\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/clickworkercom-seo","version":"dev-trunk","version_normalized":"9999999-dev","uid":71173,"time":"2013-07-22 09:54:37","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/clickworkercom-seo.zip?timestamp=1374486877"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/clickworkercom-seo\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/clickworkercom-seo\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/sb/sb-tab-widget/package.json ======================= {"packages":{"wpackagist-plugin\/sb-tab-widget":{"1.0.6":{"name":"wpackagist-plugin\/sb-tab-widget","version":"1.0.6","version_normalized":"1.0.6.0","uid":300008,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/sb-tab-widget.zip?timestamp=1428543361"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/sb-tab-widget\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/sb-tab-widget\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.0.1":{"name":"wpackagist-plugin\/sb-tab-widget","version":"1.0.1","version_normalized":"1.0.1.0","uid":300009,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/sb-tab-widget.1.0.1.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/sb-tab-widget\/","reference":"tags\/1.0.1"},"homepage":"https:\/\/wordpress.org\/plugins\/sb-tab-widget\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.0.2":{"name":"wpackagist-plugin\/sb-tab-widget","version":"1.0.2","version_normalized":"1.0.2.0","uid":300010,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/sb-tab-widget.1.0.2.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/sb-tab-widget\/","reference":"tags\/1.0.2"},"homepage":"https:\/\/wordpress.org\/plugins\/sb-tab-widget\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/sb-tab-widget","version":"dev-trunk","version_normalized":"9999999-dev","uid":300011,"time":"2015-04-09 01:36:01","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/sb-tab-widget.zip?timestamp=1428543361"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/sb-tab-widget\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/sb-tab-widget\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-theme/so/social/package.json ======================= <filename>data/wpackagist-theme/so/social/package.json<gh_stars>1-10 {"packages":{"wpackagist-theme\/social":{"0.1":{"name":"wpackagist-theme\/social","version":"0.1","version_normalized":"0.1.0.0","uid":327588,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/social.0.1.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/social\/","reference":"0.1"},"homepage":"https:\/\/wordpress.org\/themes\/social\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"0.1.1":{"name":"wpackagist-theme\/social","version":"0.1.1","version_normalized":"0.1.1.0","uid":327589,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/social.0.1.1.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/social\/","reference":"0.1.1"},"homepage":"https:\/\/wordpress.org\/themes\/social\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"0.1.2":{"name":"wpackagist-theme\/social","version":"0.1.2","version_normalized":"0.1.2.0","uid":327590,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/social.0.1.2.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/social\/","reference":"0.1.2"},"homepage":"https:\/\/wordpress.org\/themes\/social\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"0.1.3":{"name":"wpackagist-theme\/social","version":"0.1.3","version_normalized":"0.1.3.0","uid":327591,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/social.0.1.3.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/social\/","reference":"0.1.3"},"homepage":"https:\/\/wordpress.org\/themes\/social\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"0.1.4":{"name":"wpackagist-theme\/social","version":"0.1.4","version_normalized":"0.1.4.0","uid":327592,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/social.0.1.4.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/social\/","reference":"0.1.4"},"homepage":"https:\/\/wordpress.org\/themes\/social\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"0.1.5":{"name":"wpackagist-theme\/social","version":"0.1.5","version_normalized":"0.1.5.0","uid":327593,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/social.0.1.5.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/social\/","reference":"0.1.5"},"homepage":"https:\/\/wordpress.org\/themes\/social\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"0.1.6":{"name":"wpackagist-theme\/social","version":"0.1.6","version_normalized":"0.1.6.0","uid":327594,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/social.0.1.6.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/social\/","reference":"0.1.6"},"homepage":"https:\/\/wordpress.org\/themes\/social\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"0.1.7":{"name":"wpackagist-theme\/social","version":"0.1.7","version_normalized":"0.1.7.0","uid":327595,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/social.0.1.7.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/social\/","reference":"0.1.7"},"homepage":"https:\/\/wordpress.org\/themes\/social\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"0.1.8":{"name":"wpackagist-theme\/social","version":"0.1.8","version_normalized":"0.1.8.0","uid":327596,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/social.0.1.8.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/social\/","reference":"0.1.8"},"homepage":"https:\/\/wordpress.org\/themes\/social\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"}}}} ======================= File: data/wpackagist-plugin/yo/youtube-videos-widget/package.json ======================= <filename>data/wpackagist-plugin/yo/youtube-videos-widget/package.json {"packages":{"wpackagist-plugin\/youtube-videos-widget":{"1.3":{"name":"wpackagist-plugin\/youtube-videos-widget","version":"1.3","version_normalized":"1.3.0.0","uid":451411,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/youtube-videos-widget.zip?timestamp=1324675441"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/youtube-videos-widget\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/youtube-videos-widget\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.1":{"name":"wpackagist-plugin\/youtube-videos-widget","version":"1.1","version_normalized":"1.1.0.0","uid":451412,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/youtube-videos-widget.1.1.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/youtube-videos-widget\/","reference":"tags\/1.1"},"homepage":"https:\/\/wordpress.org\/plugins\/youtube-videos-widget\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.2":{"name":"wpackagist-plugin\/youtube-videos-widget","version":"1.2","version_normalized":"1.2.0.0","uid":451413,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/youtube-videos-widget.1.2.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/youtube-videos-widget\/","reference":"tags\/1.2"},"homepage":"https:\/\/wordpress.org\/plugins\/youtube-videos-widget\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/youtube-videos-widget","version":"dev-trunk","version_normalized":"9999999-dev","uid":451414,"time":"2011-12-23 21:24:01","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/youtube-videos-widget.zip?timestamp=1324675441"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/youtube-videos-widget\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/youtube-videos-widget\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/wp/wp-markdown-syntaxhighlighter/package.json ======================= <gh_stars>1-10 {"packages":{"wpackagist-plugin\/wp-markdown-syntaxhighlighter":{"0.1":{"name":"wpackagist-plugin\/wp-markdown-syntaxhighlighter","version":"0.1","version_normalized":"0.1.0.0","uid":423633,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/wp-markdown-syntaxhighlighter.0.1.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/wp-markdown-syntaxhighlighter\/","reference":"tags\/0.1"},"homepage":"https:\/\/wordpress.org\/plugins\/wp-markdown-syntaxhighlighter\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.2":{"name":"wpackagist-plugin\/wp-markdown-syntaxhighlighter","version":"0.2","version_normalized":"0.2.0.0","uid":423634,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/wp-markdown-syntaxhighlighter.0.2.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/wp-markdown-syntaxhighlighter\/","reference":"tags\/0.2"},"homepage":"https:\/\/wordpress.org\/plugins\/wp-markdown-syntaxhighlighter\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.2.1":{"name":"wpackagist-plugin\/wp-markdown-syntaxhighlighter","version":"0.2.1","version_normalized":"0.2.1.0","uid":423635,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/wp-markdown-syntaxhighlighter.0.2.1.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/wp-markdown-syntaxhighlighter\/","reference":"tags\/0.2.1"},"homepage":"https:\/\/wordpress.org\/plugins\/wp-markdown-syntaxhighlighter\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.3":{"name":"wpackagist-plugin\/wp-markdown-syntaxhighlighter","version":"0.3","version_normalized":"0.3.0.0","uid":423636,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/wp-markdown-syntaxhighlighter.0.3.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/wp-markdown-syntaxhighlighter\/","reference":"tags\/0.3"},"homepage":"https:\/\/wordpress.org\/plugins\/wp-markdown-syntaxhighlighter\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.3.1":{"name":"wpackagist-plugin\/wp-markdown-syntaxhighlighter","version":"0.3.1","version_normalized":"0.3.1.0","uid":423637,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/wp-markdown-syntaxhighlighter.0.3.1.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/wp-markdown-syntaxhighlighter\/","reference":"tags\/0.3.1"},"homepage":"https:\/\/wordpress.org\/plugins\/wp-markdown-syntaxhighlighter\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.4":{"name":"wpackagist-plugin\/wp-markdown-syntaxhighlighter","version":"0.4","version_normalized":"0.4.0.0","uid":423638,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/wp-markdown-syntaxhighlighter.0.4.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/wp-markdown-syntaxhighlighter\/","reference":"tags\/0.4"},"homepage":"https:\/\/wordpress.org\/plugins\/wp-markdown-syntaxhighlighter\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/wp-markdown-syntaxhighlighter","version":"dev-trunk","version_normalized":"9999999-dev","uid":423639,"time":"2012-09-17 17:21:39","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/wp-markdown-syntaxhighlighter.zip?timestamp=1347902499"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/wp-markdown-syntaxhighlighter\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/wp-markdown-syntaxhighlighter\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-theme/fi/fifty-fifth-street/package.json ======================= {"packages":{"wpackagist-theme\/fifty-fifth-street":{"1.0":{"name":"wpackagist-theme\/fifty-fifth-street","version":"1.0","version_normalized":"1.0.0.0","uid":133675,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/fifty-fifth-street.1.0.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/fifty-fifth-street\/","reference":"1.0"},"homepage":"https:\/\/wordpress.org\/themes\/fifty-fifth-street\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.1":{"name":"wpackagist-theme\/fifty-fifth-street","version":"1.1","version_normalized":"1.1.0.0","uid":133676,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/fifty-fifth-street.1.1.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/fifty-fifth-street\/","reference":"1.1"},"homepage":"https:\/\/wordpress.org\/themes\/fifty-fifth-street\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.2":{"name":"wpackagist-theme\/fifty-fifth-street","version":"1.2","version_normalized":"1.2.0.0","uid":133677,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/fifty-fifth-street.1.2.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/fifty-fifth-street\/","reference":"1.2"},"homepage":"https:\/\/wordpress.org\/themes\/fifty-fifth-street\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.3":{"name":"wpackagist-theme\/fifty-fifth-street","version":"1.3","version_normalized":"1.3.0.0","uid":133678,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/fifty-fifth-street.1.3.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/fifty-fifth-street\/","reference":"1.3"},"homepage":"https:\/\/wordpress.org\/themes\/fifty-fifth-street\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.4":{"name":"wpackagist-theme\/fifty-fifth-street","version":"1.4","version_normalized":"1.4.0.0","uid":133679,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/fifty-fifth-street.1.4.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/fifty-fifth-street\/","reference":"1.4"},"homepage":"https:\/\/wordpress.org\/themes\/fifty-fifth-street\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"}}}} ======================= File: data/wpackagist-plugin/bs/bsplaces/package.json ======================= {"packages":{"wpackagist-plugin\/bsplaces":{"1.1":{"name":"wpackagist-plugin\/bsplaces","version":"1.1","version_normalized":"1.1.0.0","uid":53128,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/bsplaces.1.1.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/bsplaces\/","reference":"tags\/1.1"},"homepage":"https:\/\/wordpress.org\/plugins\/bsplaces\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.2":{"name":"wpackagist-plugin\/bsplaces","version":"1.2","version_normalized":"1.2.0.0","uid":53129,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/bsplaces.1.2.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/bsplaces\/","reference":"tags\/1.2"},"homepage":"https:\/\/wordpress.org\/plugins\/bsplaces\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.3":{"name":"wpackagist-plugin\/bsplaces","version":"1.3","version_normalized":"1.3.0.0","uid":53130,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/bsplaces.1.3.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/bsplaces\/","reference":"tags\/1.3"},"homepage":"https:\/\/wordpress.org\/plugins\/bsplaces\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.4":{"name":"wpackagist-plugin\/bsplaces","version":"1.4","version_normalized":"1.4.0.0","uid":53131,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/bsplaces.1.4.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/bsplaces\/","reference":"tags\/1.4"},"homepage":"https:\/\/wordpress.org\/plugins\/bsplaces\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.6":{"name":"wpackagist-plugin\/bsplaces","version":"1.6","version_normalized":"1.6.0.0","uid":53132,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/bsplaces.1.6.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/bsplaces\/","reference":"tags\/1.6"},"homepage":"https:\/\/wordpress.org\/plugins\/bsplaces\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/bsplaces","version":"dev-trunk","version_normalized":"9999999-dev","uid":53133,"time":"2014-09-08 17:50:09","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/bsplaces.zip?timestamp=1410198609"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/bsplaces\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/bsplaces\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/st/streamtestnet-badges/package.json ======================= {"packages":{"wpackagist-plugin\/streamtestnet-badges":{"1.0.0":{"name":"wpackagist-plugin\/streamtestnet-badges","version":"1.0.0","version_normalized":"1.0.0.0","uid":338868,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/streamtestnet-badges.zip?timestamp=1431033792"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/streamtestnet-badges\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/streamtestnet-badges\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.0":{"name":"wpackagist-plugin\/streamtestnet-badges","version":"1.0","version_normalized":"1.0.0.0","uid":338869,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/streamtestnet-badges.1.0.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/streamtestnet-badges\/","reference":"tags\/1.0"},"homepage":"https:\/\/wordpress.org\/plugins\/streamtestnet-badges\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/streamtestnet-badges","version":"dev-trunk","version_normalized":"9999999-dev","uid":338870,"time":"2015-05-07 21:23:12","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/streamtestnet-badges.zip?timestamp=1431033792"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/streamtestnet-badges\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/streamtestnet-badges\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/tw/twiogle-search/package.json ======================= <gh_stars>1-10 {"packages":{"wpackagist-plugin\/twiogle-search":{"1.48":{"name":"wpackagist-plugin\/twiogle-search","version":"1.48","version_normalized":"1.48.0.0","uid":362865,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/twiogle-search.zip?timestamp=1245093791"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/twiogle-search\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/twiogle-search\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/twiogle-search","version":"dev-trunk","version_normalized":"9999999-dev","uid":362866,"time":"2009-06-15 19:23:11","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/twiogle-search.zip?timestamp=1245093791"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/twiogle-search\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/twiogle-search\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/sl/slideshowfx/package.json ======================= {"packages":{"wpackagist-plugin\/slideshowfx":{"1.1":{"name":"wpackagist-plugin\/slideshowfx","version":"1.1","version_normalized":"1.1.0.0","uid":323951,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/slideshowfx.zip?timestamp=1364112790"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/slideshowfx\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/slideshowfx\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.00":{"name":"wpackagist-plugin\/slideshowfx","version":"1.00","version_normalized":"1.00.0.0","uid":323952,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/slideshowfx.1.00.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/slideshowfx\/","reference":"tags\/1.00"},"homepage":"https:\/\/wordpress.org\/plugins\/slideshowfx\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.01":{"name":"wpackagist-plugin\/slideshowfx","version":"1.01","version_normalized":"1.01.0.0","uid":323953,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/slideshowfx.1.01.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/slideshowfx\/","reference":"tags\/1.01"},"homepage":"https:\/\/wordpress.org\/plugins\/slideshowfx\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/slideshowfx","version":"dev-trunk","version_normalized":"9999999-dev","uid":323954,"time":"2013-03-24 08:13:10","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/slideshowfx.zip?timestamp=1364112790"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/slideshowfx\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/slideshowfx\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-theme/ha/hazom-chair/package.json ======================= {"packages":{"wpackagist-theme\/hazom-chair":{"1.0":{"name":"wpackagist-theme\/hazom-chair","version":"1.0","version_normalized":"1.0.0.0","uid":163327,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/hazom-chair.1.0.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/hazom-chair\/","reference":"1.0"},"homepage":"https:\/\/wordpress.org\/themes\/hazom-chair\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.1":{"name":"wpackagist-theme\/hazom-chair","version":"1.1","version_normalized":"1.1.0.0","uid":163328,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/hazom-chair.1.1.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/hazom-chair\/","reference":"1.1"},"homepage":"https:\/\/wordpress.org\/themes\/hazom-chair\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.1.1":{"name":"wpackagist-theme\/hazom-chair","version":"1.1.1","version_normalized":"1.1.1.0","uid":163329,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/hazom-chair.1.1.1.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/hazom-chair\/","reference":"1.1.1"},"homepage":"https:\/\/wordpress.org\/themes\/hazom-chair\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.1.2":{"name":"wpackagist-theme\/hazom-chair","version":"1.1.2","version_normalized":"1.1.2.0","uid":163330,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/hazom-chair.1.1.2.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/hazom-chair\/","reference":"1.1.2"},"homepage":"https:\/\/wordpress.org\/themes\/hazom-chair\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.1.3":{"name":"wpackagist-theme\/hazom-chair","version":"1.1.3","version_normalized":"1.1.3.0","uid":163331,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/hazom-chair.1.1.3.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/hazom-chair\/","reference":"1.1.3"},"homepage":"https:\/\/wordpress.org\/themes\/hazom-chair\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.1.4":{"name":"wpackagist-theme\/hazom-chair","version":"1.1.4","version_normalized":"1.1.4.0","uid":163332,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/hazom-chair.1.1.4.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/hazom-chair\/","reference":"1.1.4"},"homepage":"https:\/\/wordpress.org\/themes\/hazom-chair\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.1.5":{"name":"wpackagist-theme\/hazom-chair","version":"1.1.5","version_normalized":"1.1.5.0","uid":163333,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/hazom-chair.1.1.5.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/hazom-chair\/","reference":"1.1.5"},"homepage":"https:\/\/wordpress.org\/themes\/hazom-chair\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"}}}} ======================= File: data/wpackagist-theme/my/myblogstheme/package.json ======================= <filename>data/wpackagist-theme/my/myblogstheme/package.json {"packages":{"wpackagist-theme\/myblogstheme":{"1.0":{"name":"wpackagist-theme\/myblogstheme","version":"1.0","version_normalized":"1.0.0.0","uid":227972,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/myblogstheme.1.0.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/myblogstheme\/","reference":"1.0"},"homepage":"https:\/\/wordpress.org\/themes\/myblogstheme\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.5":{"name":"wpackagist-theme\/myblogstheme","version":"1.5","version_normalized":"1.5.0.0","uid":227973,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/myblogstheme.1.5.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/myblogstheme\/","reference":"1.5"},"homepage":"https:\/\/wordpress.org\/themes\/myblogstheme\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.6":{"name":"wpackagist-theme\/myblogstheme","version":"1.6","version_normalized":"1.6.0.0","uid":227974,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/myblogstheme.1.6.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/myblogstheme\/","reference":"1.6"},"homepage":"https:\/\/wordpress.org\/themes\/myblogstheme\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"}}}} ======================= File: data/wpackagist-plugin/wp/wp-social-links/package.json ======================= <filename>data/wpackagist-plugin/wp/wp-social-links/package.json {"packages":{"wpackagist-plugin\/wp-social-links":{"0.3":{"name":"wpackagist-plugin\/wp-social-links","version":"0.3","version_normalized":"0.3.0.0","uid":433441,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/wp-social-links.0.3.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/wp-social-links\/","reference":"tags\/0.3"},"homepage":"https:\/\/wordpress.org\/plugins\/wp-social-links\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.3.1":{"name":"wpackagist-plugin\/wp-social-links","version":"0.3.1","version_normalized":"0.3.1.0","uid":433442,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/wp-social-links.0.3.1.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/wp-social-links\/","reference":"tags\/0.3.1"},"homepage":"https:\/\/wordpress.org\/plugins\/wp-social-links\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/wp-social-links","version":"dev-trunk","version_normalized":"9999999-dev","uid":433443,"time":"2011-12-12 15:06:19","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/wp-social-links.zip?timestamp=1323702379"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/wp-social-links\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/wp-social-links\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/sh/show-all-html-spezial-chars-in-comments/package.json ======================= {"packages":{"wpackagist-plugin\/show-all-html-spezial-chars-in-comments":{"0.1":{"name":"wpackagist-plugin\/show-all-html-spezial-chars-in-comments","version":"0.1","version_normalized":"0.1.0.0","uid":311168,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/show-all-html-spezial-chars-in-comments.0.1.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/show-all-html-spezial-chars-in-comments\/","reference":"tags\/0.1"},"homepage":"https:\/\/wordpress.org\/plugins\/show-all-html-spezial-chars-in-comments\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.2":{"name":"wpackagist-plugin\/show-all-html-spezial-chars-in-comments","version":"0.2","version_normalized":"0.2.0.0","uid":311169,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/show-all-html-spezial-chars-in-comments.0.2.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/show-all-html-spezial-chars-in-comments\/","reference":"tags\/0.2"},"homepage":"https:\/\/wordpress.org\/plugins\/show-all-html-spezial-chars-in-comments\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.2.1":{"name":"wpackagist-plugin\/show-all-html-spezial-chars-in-comments","version":"0.2.1","version_normalized":"0.2.1.0","uid":311170,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/show-all-html-spezial-chars-in-comments.0.2.1.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/show-all-html-spezial-chars-in-comments\/","reference":"tags\/0.2.1"},"homepage":"https:\/\/wordpress.org\/plugins\/show-all-html-spezial-chars-in-comments\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.2.2":{"name":"wpackagist-plugin\/show-all-html-spezial-chars-in-comments","version":"0.2.2","version_normalized":"0.2.2.0","uid":311171,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/show-all-html-spezial-chars-in-comments.0.2.2.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/show-all-html-spezial-chars-in-comments\/","reference":"tags\/0.2.2"},"homepage":"https:\/\/wordpress.org\/plugins\/show-all-html-spezial-chars-in-comments\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/show-all-html-spezial-chars-in-comments","version":"dev-trunk","version_normalized":"9999999-dev","uid":311172,"time":"2009-02-10 12:04:51","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/show-all-html-spezial-chars-in-comments.zip?timestamp=1234267491"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/show-all-html-spezial-chars-in-comments\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/show-all-html-spezial-chars-in-comments\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/ve/vessel/package.json ======================= {"packages":{"wpackagist-plugin\/vessel":{"0.5.10":{"name":"wpackagist-plugin\/vessel","version":"0.5.10","version_normalized":"0.5.10.0","uid":374573,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/vessel.zip?timestamp=1539205019"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/vessel\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/vessel\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.6.0":{"name":"wpackagist-plugin\/vessel","version":"0.6.0","version_normalized":"0.6.0.0","uid":374574,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/vessel.0.6.0.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/vessel\/","reference":"tags\/0.6.0"},"homepage":"https:\/\/wordpress.org\/plugins\/vessel\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/vessel","version":"dev-trunk","version_normalized":"9999999-dev","uid":374575,"time":"2018-10-10 20:56:59","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/vessel.zip?timestamp=1539205019"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/vessel\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/vessel\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/gp/gplus-author-profile/package.json ======================= <reponame>wplib/wpackagist-requestor {"packages":{"wpackagist-plugin\/gplus-author-profile":{"1.2":{"name":"wpackagist-plugin\/gplus-author-profile","version":"1.2","version_normalized":"1.2.0.0","uid":157393,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/gplus-author-profile.zip?timestamp=1323688637"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/gplus-author-profile\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/gplus-author-profile\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/gplus-author-profile","version":"dev-trunk","version_normalized":"9999999-dev","uid":157394,"time":"2011-12-12 11:17:17","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/gplus-author-profile.zip?timestamp=1323688637"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/gplus-author-profile\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/gplus-author-profile\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/fi/firstlast-links/package.json ======================= {"packages":{"wpackagist-plugin\/firstlast-links":{"0.1":{"name":"wpackagist-plugin\/firstlast-links","version":"0.1","version_normalized":"0.1.0.0","uid":134865,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/firstlast-links.zip?timestamp=1243988710"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/firstlast-links\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/firstlast-links\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/firstlast-links","version":"dev-trunk","version_normalized":"9999999-dev","uid":134866,"time":"2009-06-03 00:25:10","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/firstlast-links.zip?timestamp=1243988710"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/firstlast-links\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/firstlast-links\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/s3/s3-rating/package.json ======================= {"packages":{"wpackagist-plugin\/s3-rating":{"1.0":{"name":"wpackagist-plugin\/s3-rating","version":"1.0","version_normalized":"1.0.0.0","uid":298013,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/s3-rating.1.0.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/s3-rating\/","reference":"tags\/1.0"},"homepage":"https:\/\/wordpress.org\/plugins\/s3-rating\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.1":{"name":"wpackagist-plugin\/s3-rating","version":"1.1","version_normalized":"1.1.0.0","uid":298014,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/s3-rating.1.1.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/s3-rating\/","reference":"tags\/1.1"},"homepage":"https:\/\/wordpress.org\/plugins\/s3-rating\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/s3-rating","version":"dev-trunk","version_normalized":"9999999-dev","uid":298015,"time":"2014-04-01 15:44:56","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/s3-rating.zip?timestamp=1396367096"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/s3-rating\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/s3-rating\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-theme/de/deep-silent/package.json ======================= <gh_stars>1-10 {"packages":{"wpackagist-theme\/deep-silent":{"1.2":{"name":"wpackagist-theme\/deep-silent","version":"1.2","version_normalized":"1.2.0.0","uid":96556,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/deep-silent.1.2.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/deep-silent\/","reference":"1.2"},"homepage":"https:\/\/wordpress.org\/themes\/deep-silent\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.3":{"name":"wpackagist-theme\/deep-silent","version":"1.3","version_normalized":"1.3.0.0","uid":96557,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/deep-silent.1.3.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/deep-silent\/","reference":"1.3"},"homepage":"https:\/\/wordpress.org\/themes\/deep-silent\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.4":{"name":"wpackagist-theme\/deep-silent","version":"1.4","version_normalized":"1.4.0.0","uid":96558,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/deep-silent.1.4.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/deep-silent\/","reference":"1.4"},"homepage":"https:\/\/wordpress.org\/themes\/deep-silent\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.5":{"name":"wpackagist-theme\/deep-silent","version":"1.5","version_normalized":"1.5.0.0","uid":96559,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/deep-silent.1.5.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/deep-silent\/","reference":"1.5"},"homepage":"https:\/\/wordpress.org\/themes\/deep-silent\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.6":{"name":"wpackagist-theme\/deep-silent","version":"1.6","version_normalized":"1.6.0.0","uid":96560,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/deep-silent.1.6.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/deep-silent\/","reference":"1.6"},"homepage":"https:\/\/wordpress.org\/themes\/deep-silent\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.7":{"name":"wpackagist-theme\/deep-silent","version":"1.7","version_normalized":"1.7.0.0","uid":96561,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/deep-silent.1.7.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/deep-silent\/","reference":"1.7"},"homepage":"https:\/\/wordpress.org\/themes\/deep-silent\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.8":{"name":"wpackagist-theme\/deep-silent","version":"1.8","version_normalized":"1.8.0.0","uid":96562,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/deep-silent.1.8.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/deep-silent\/","reference":"1.8"},"homepage":"https:\/\/wordpress.org\/themes\/deep-silent\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"}}}} ======================= File: data/wpackagist-plugin/se/search-statistics/package.json ======================= <reponame>wplib/wpackagist-requestor {"packages":{"wpackagist-plugin\/search-statistics":{"1.5.7":{"name":"wpackagist-plugin\/search-statistics","version":"1.5.7","version_normalized":"1.5.7.0","uid":302385,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/search-statistics.zip?timestamp=1439734924"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/search-statistics\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/search-statistics\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/search-statistics","version":"dev-trunk","version_normalized":"9999999-dev","uid":302386,"time":"2015-08-16 14:22:04","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/search-statistics.zip?timestamp=1439734924"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/search-statistics\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/search-statistics\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/li/link-icons/package.json ======================= <filename>data/wpackagist-plugin/li/link-icons/package.json {"packages":{"wpackagist-plugin\/link-icons":{"0.1":{"name":"wpackagist-plugin\/link-icons","version":"0.1","version_normalized":"0.1.0.0","uid":198691,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/link-icons.0.1.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/link-icons\/","reference":"tags\/0.1"},"homepage":"https:\/\/wordpress.org\/plugins\/link-icons\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.2":{"name":"wpackagist-plugin\/link-icons","version":"0.2","version_normalized":"0.2.0.0","uid":198692,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/link-icons.0.2.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/link-icons\/","reference":"tags\/0.2"},"homepage":"https:\/\/wordpress.org\/plugins\/link-icons\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.3":{"name":"wpackagist-plugin\/link-icons","version":"0.3","version_normalized":"0.3.0.0","uid":198693,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/link-icons.0.3.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/link-icons\/","reference":"tags\/0.3"},"homepage":"https:\/\/wordpress.org\/plugins\/link-icons\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.3.1":{"name":"wpackagist-plugin\/link-icons","version":"0.3.1","version_normalized":"0.3.1.0","uid":198694,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/link-icons.0.3.1.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/link-icons\/","reference":"tags\/0.3.1"},"homepage":"https:\/\/wordpress.org\/plugins\/link-icons\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.4":{"name":"wpackagist-plugin\/link-icons","version":"0.4","version_normalized":"0.4.0.0","uid":198695,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/link-icons.0.4.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/link-icons\/","reference":"tags\/0.4"},"homepage":"https:\/\/wordpress.org\/plugins\/link-icons\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/link-icons","version":"dev-trunk","version_normalized":"9999999-dev","uid":198696,"time":"2013-05-04 01:40:17","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/link-icons.zip?timestamp=1367631617"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/link-icons\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/link-icons\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/di/disable-parent-menu-link/package.json ======================= <gh_stars>1-10 {"packages":{"wpackagist-plugin\/disable-parent-menu-link":{"0.1.1":{"name":"wpackagist-plugin\/disable-parent-menu-link","version":"0.1.1","version_normalized":"0.1.1.0","uid":100510,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/disable-parent-menu-link.0.1.1.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/disable-parent-menu-link\/","reference":"tags\/0.1.1"},"homepage":"https:\/\/wordpress.org\/plugins\/disable-parent-menu-link\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.1.2":{"name":"wpackagist-plugin\/disable-parent-menu-link","version":"0.1.2","version_normalized":"0.1.2.0","uid":100511,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/disable-parent-menu-link.0.1.2.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/disable-parent-menu-link\/","reference":"tags\/0.1.2"},"homepage":"https:\/\/wordpress.org\/plugins\/disable-parent-menu-link\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.1.3":{"name":"wpackagist-plugin\/disable-parent-menu-link","version":"0.1.3","version_normalized":"0.1.3.0","uid":100512,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/disable-parent-menu-link.0.1.3.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/disable-parent-menu-link\/","reference":"tags\/0.1.3"},"homepage":"https:\/\/wordpress.org\/plugins\/disable-parent-menu-link\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/disable-parent-menu-link","version":"dev-trunk","version_normalized":"9999999-dev","uid":100513,"time":"2011-12-09 10:04:09","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/disable-parent-menu-link.zip?timestamp=1323425049"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/disable-parent-menu-link\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/disable-parent-menu-link\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/wp/wp-biblia-catolica-widget/package.json ======================= <filename>data/wpackagist-plugin/wp/wp-biblia-catolica-widget/package.json {"packages":{"wpackagist-plugin\/wp-biblia-catolica-widget":{"1.0.0.0":{"name":"wpackagist-plugin\/wp-biblia-catolica-widget","version":"1.0.0.0","version_normalized":"1.0.0.0","uid":408356,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/wp-biblia-catolica-widget.1.0.0.0.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/wp-biblia-catolica-widget\/","reference":"tags\/1.0.0.0"},"homepage":"https:\/\/wordpress.org\/plugins\/wp-biblia-catolica-widget\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.0.0.2":{"name":"wpackagist-plugin\/wp-biblia-catolica-widget","version":"1.0.0.2","version_normalized":"1.0.0.2","uid":408357,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/wp-biblia-catolica-widget.1.0.0.2.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/wp-biblia-catolica-widget\/","reference":"tags\/1.0.0.2"},"homepage":"https:\/\/wordpress.org\/plugins\/wp-biblia-catolica-widget\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.0.0.3":{"name":"wpackagist-plugin\/wp-biblia-catolica-widget","version":"1.0.0.3","version_normalized":"1.0.0.3","uid":408358,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/wp-biblia-catolica-widget.1.0.0.3.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/wp-biblia-catolica-widget\/","reference":"tags\/1.0.0.3"},"homepage":"https:\/\/wordpress.org\/plugins\/wp-biblia-catolica-widget\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.0.0.4":{"name":"wpackagist-plugin\/wp-biblia-catolica-widget","version":"1.0.0.4","version_normalized":"1.0.0.4","uid":408359,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/wp-biblia-catolica-widget.1.0.0.4.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/wp-biblia-catolica-widget\/","reference":"tags\/1.0.0.4"},"homepage":"https:\/\/wordpress.org\/plugins\/wp-biblia-catolica-widget\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.0.0.5":{"name":"wpackagist-plugin\/wp-biblia-catolica-widget","version":"1.0.0.5","version_normalized":"1.0.0.5","uid":408360,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/wp-biblia-catolica-widget.1.0.0.5.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/wp-biblia-catolica-widget\/","reference":"tags\/1.0.0.5"},"homepage":"https:\/\/wordpress.org\/plugins\/wp-biblia-catolica-widget\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.0.0.6":{"name":"wpackagist-plugin\/wp-biblia-catolica-widget","version":"1.0.0.6","version_normalized":"1.0.0.6","uid":408361,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/wp-biblia-catolica-widget.1.0.0.6.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/wp-biblia-catolica-widget\/","reference":"tags\/1.0.0.6"},"homepage":"https:\/\/wordpress.org\/plugins\/wp-biblia-catolica-widget\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/wp-biblia-catolica-widget","version":"dev-trunk","version_normalized":"9999999-dev","uid":408362,"time":"2011-12-03 13:41:12","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/wp-biblia-catolica-widget.zip?timestamp=1322919672"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/wp-biblia-catolica-widget\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/wp-biblia-catolica-widget\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/be/better-hipchat/package.json ======================= {"packages":{"wpackagist-plugin\/better-hipchat":{"0.1.0":{"name":"wpackagist-plugin\/better-hipchat","version":"0.1.0","version_normalized":"0.1.0.0","uid":40347,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/better-hipchat.zip?timestamp=1399433867"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/better-hipchat\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/better-hipchat\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/better-hipchat","version":"dev-trunk","version_normalized":"9999999-dev","uid":40348,"time":"2014-05-07 03:37:47","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/better-hipchat.zip?timestamp=1399433867"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/better-hipchat\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/better-hipchat\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/xk/xkcd-shortcode/package.json ======================= {"packages":{"wpackagist-plugin\/xkcd-shortcode":{"0.7":{"name":"wpackagist-plugin\/xkcd-shortcode","version":"0.7","version_normalized":"0.7.0.0","uid":446600,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/xkcd-shortcode.0.7.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/xkcd-shortcode\/","reference":"tags\/0.7"},"homepage":"https:\/\/wordpress.org\/plugins\/xkcd-shortcode\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.8.0":{"name":"wpackagist-plugin\/xkcd-shortcode","version":"0.8.0","version_normalized":"0.8.0.0","uid":446601,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/xkcd-shortcode.0.8.0.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/xkcd-shortcode\/","reference":"tags\/0.8.0"},"homepage":"https:\/\/wordpress.org\/plugins\/xkcd-shortcode\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/xkcd-shortcode","version":"dev-trunk","version_normalized":"9999999-dev","uid":446602,"time":"2014-03-17 10:22:31","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/xkcd-shortcode.zip?timestamp=1395051751"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/xkcd-shortcode\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/xkcd-shortcode\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/ac/activity-life-stream/package.json ======================= {"packages":{"wpackagist-plugin\/activity-life-stream":{"0.9.0":{"name":"wpackagist-plugin\/activity-life-stream","version":"0.9.0","version_normalized":"0.9.0.0","uid":5970,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/activity-life-stream.zip?timestamp=1265277144"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/activity-life-stream\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/activity-life-stream\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.0.0":{"name":"wpackagist-plugin\/activity-life-stream","version":"1.0.0","version_normalized":"1.0.0.0","uid":5971,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/activity-life-stream.1.0.0.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/activity-life-stream\/","reference":"tags\/1.0.0"},"homepage":"https:\/\/wordpress.org\/plugins\/activity-life-stream\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/activity-life-stream","version":"dev-trunk","version_normalized":"9999999-dev","uid":5972,"time":"2010-02-04 09:52:24","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/activity-life-stream.zip?timestamp=1265277144"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/activity-life-stream\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/activity-life-stream\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-theme/sm/smartshop/package.json ======================= {"packages":{"wpackagist-theme\/smartshop":{"1.1":{"name":"wpackagist-theme\/smartshop","version":"1.1","version_normalized":"1.1.0.0","uid":325984,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/smartshop.1.1.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/smartshop\/","reference":"1.1"},"homepage":"https:\/\/wordpress.org\/themes\/smartshop\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.2":{"name":"wpackagist-theme\/smartshop","version":"1.2","version_normalized":"1.2.0.0","uid":325985,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/smartshop.1.2.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/smartshop\/","reference":"1.2"},"homepage":"https:\/\/wordpress.org\/themes\/smartshop\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.3":{"name":"wpackagist-theme\/smartshop","version":"1.3","version_normalized":"1.3.0.0","uid":325986,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/smartshop.1.3.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/smartshop\/","reference":"1.3"},"homepage":"https:\/\/wordpress.org\/themes\/smartshop\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.4":{"name":"wpackagist-theme\/smartshop","version":"1.4","version_normalized":"1.4.0.0","uid":325987,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/smartshop.1.4.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/smartshop\/","reference":"1.4"},"homepage":"https:\/\/wordpress.org\/themes\/smartshop\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.4.1":{"name":"wpackagist-theme\/smartshop","version":"1.4.1","version_normalized":"1.4.1.0","uid":325988,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/smartshop.1.4.1.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/smartshop\/","reference":"1.4.1"},"homepage":"https:\/\/wordpress.org\/themes\/smartshop\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.4.2":{"name":"wpackagist-theme\/smartshop","version":"1.4.2","version_normalized":"1.4.2.0","uid":325989,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/smartshop.1.4.2.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/smartshop\/","reference":"1.4.2"},"homepage":"https:\/\/wordpress.org\/themes\/smartshop\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.5":{"name":"wpackagist-theme\/smartshop","version":"1.5","version_normalized":"1.5.0.0","uid":325990,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/smartshop.1.5.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/smartshop\/","reference":"1.5"},"homepage":"https:\/\/wordpress.org\/themes\/smartshop\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.5.1":{"name":"wpackagist-theme\/smartshop","version":"1.5.1","version_normalized":"1.5.1.0","uid":325991,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/smartshop.1.5.1.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/smartshop\/","reference":"1.5.1"},"homepage":"https:\/\/wordpress.org\/themes\/smartshop\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.5.3":{"name":"wpackagist-theme\/smartshop","version":"1.5.3","version_normalized":"1.5.3.0","uid":325992,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/smartshop.1.5.3.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/smartshop\/","reference":"1.5.3"},"homepage":"https:\/\/wordpress.org\/themes\/smartshop\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.5.4":{"name":"wpackagist-theme\/smartshop","version":"1.5.4","version_normalized":"1.5.4.0","uid":325993,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/smartshop.1.5.4.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/smartshop\/","reference":"1.5.4"},"homepage":"https:\/\/wordpress.org\/themes\/smartshop\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.5.5":{"name":"wpackagist-theme\/smartshop","version":"1.5.5","version_normalized":"1.5.5.0","uid":325994,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/smartshop.1.5.5.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/smartshop\/","reference":"1.5.5"},"homepage":"https:\/\/wordpress.org\/themes\/smartshop\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"}}}} ======================= File: data/wpackagist-plugin/ap/application-insights-dashboard/package.json ======================= {"packages":{"wpackagist-plugin\/application-insights-dashboard":{"1.0a":{"name":"wpackagist-plugin\/application-insights-dashboard","version":"1.0a","version_normalized":"1.0.0.0-alpha","uid":24599,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/application-insights-dashboard.1.0a.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/application-insights-dashboard\/","reference":"tags\/1.0a"},"homepage":"https:\/\/wordpress.org\/plugins\/application-insights-dashboard\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/application-insights-dashboard","version":"dev-trunk","version_normalized":"9999999-dev","uid":24600,"time":"2014-12-18 07:48:42","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/application-insights-dashboard.zip?timestamp=1418888922"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/application-insights-dashboard\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/application-insights-dashboard\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-theme/fr/fresh-ink-magazine/package.json ======================= {"packages":{"wpackagist-theme\/fresh-ink-magazine":{"1.0":{"name":"wpackagist-theme\/fresh-ink-magazine","version":"1.0","version_normalized":"1.0.0.0","uid":143004,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/fresh-ink-magazine.1.0.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/fresh-ink-magazine\/","reference":"1.0"},"homepage":"https:\/\/wordpress.org\/themes\/fresh-ink-magazine\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.01":{"name":"wpackagist-theme\/fresh-ink-magazine","version":"1.01","version_normalized":"1.01.0.0","uid":143005,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/fresh-ink-magazine.1.01.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/fresh-ink-magazine\/","reference":"1.01"},"homepage":"https:\/\/wordpress.org\/themes\/fresh-ink-magazine\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.02":{"name":"wpackagist-theme\/fresh-ink-magazine","version":"1.02","version_normalized":"1.02.0.0","uid":143006,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/fresh-ink-magazine.1.02.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/fresh-ink-magazine\/","reference":"1.02"},"homepage":"https:\/\/wordpress.org\/themes\/fresh-ink-magazine\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.03":{"name":"wpackagist-theme\/fresh-ink-magazine","version":"1.03","version_normalized":"1.03.0.0","uid":143007,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/fresh-ink-magazine.1.03.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/fresh-ink-magazine\/","reference":"1.03"},"homepage":"https:\/\/wordpress.org\/themes\/fresh-ink-magazine\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.04":{"name":"wpackagist-theme\/fresh-ink-magazine","version":"1.04","version_normalized":"1.04.0.0","uid":143008,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/fresh-ink-magazine.1.04.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/fresh-ink-magazine\/","reference":"1.04"},"homepage":"https:\/\/wordpress.org\/themes\/fresh-ink-magazine\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.05":{"name":"wpackagist-theme\/fresh-ink-magazine","version":"1.05","version_normalized":"1.05.0.0","uid":143009,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/fresh-ink-magazine.1.05.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/fresh-ink-magazine\/","reference":"1.05"},"homepage":"https:\/\/wordpress.org\/themes\/fresh-ink-magazine\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.06":{"name":"wpackagist-theme\/fresh-ink-magazine","version":"1.06","version_normalized":"1.06.0.0","uid":143010,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/fresh-ink-magazine.1.06.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/fresh-ink-magazine\/","reference":"1.06"},"homepage":"https:\/\/wordpress.org\/themes\/fresh-ink-magazine\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.07":{"name":"wpackagist-theme\/fresh-ink-magazine","version":"1.07","version_normalized":"1.07.0.0","uid":143011,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/fresh-ink-magazine.1.07.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/fresh-ink-magazine\/","reference":"1.07"},"homepage":"https:\/\/wordpress.org\/themes\/fresh-ink-magazine\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.08":{"name":"wpackagist-theme\/fresh-ink-magazine","version":"1.08","version_normalized":"1.08.0.0","uid":143012,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/fresh-ink-magazine.1.08.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/fresh-ink-magazine\/","reference":"1.08"},"homepage":"https:\/\/wordpress.org\/themes\/fresh-ink-magazine\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"}}}} ======================= File: data/wpackagist-plugin/cy/cyber-slider/package.json ======================= <reponame>wplib/wpackagist-requestor<filename>data/wpackagist-plugin/cy/cyber-slider/package.json {"packages":{"wpackagist-plugin\/cyber-slider":{"1.0":{"name":"wpackagist-plugin\/cyber-slider","version":"1.0","version_normalized":"1.0.0.0","uid":92907,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/cyber-slider.1.0.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/cyber-slider\/","reference":"tags\/1.0"},"homepage":"https:\/\/wordpress.org\/plugins\/cyber-slider\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.1":{"name":"wpackagist-plugin\/cyber-slider","version":"1.1","version_normalized":"1.1.0.0","uid":92908,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/cyber-slider.1.1.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/cyber-slider\/","reference":"tags\/1.1"},"homepage":"https:\/\/wordpress.org\/plugins\/cyber-slider\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/cyber-slider","version":"dev-trunk","version_normalized":"9999999-dev","uid":92909,"time":"2013-10-23 06:34:00","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/cyber-slider.zip?timestamp=1382510040"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/cyber-slider\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/cyber-slider\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/me/mediatext-ad-wrap/package.json ======================= {"packages":{"wpackagist-plugin\/mediatext-ad-wrap":{"1.0.0":{"name":"wpackagist-plugin\/mediatext-ad-wrap","version":"1.0.0","version_normalized":"1.0.0.0","uid":213118,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/mediatext-ad-wrap.zip?timestamp=1214288508"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/mediatext-ad-wrap\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/mediatext-ad-wrap\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/mediatext-ad-wrap","version":"dev-trunk","version_normalized":"9999999-dev","uid":213119,"time":"2008-06-24 06:21:48","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/mediatext-ad-wrap.zip?timestamp=1214288508"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/mediatext-ad-wrap\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/mediatext-ad-wrap\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/dh/dh-new-mark/package.json ======================= <reponame>wplib/wpackagist-requestor {"packages":{"wpackagist-plugin\/dh-new-mark":{"0.9.5":{"name":"wpackagist-plugin\/dh-new-mark","version":"0.9.5","version_normalized":"0.9.5.0","uid":98770,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/dh-new-mark.zip?timestamp=1311140783"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/dh-new-mark\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/dh-new-mark\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/dh-new-mark","version":"dev-trunk","version_normalized":"9999999-dev","uid":98771,"time":"2011-07-20 05:46:23","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/dh-new-mark.zip?timestamp=1311140783"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/dh-new-mark\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/dh-new-mark\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/wo/wordpress-pastebin/package.json ======================= <gh_stars>1-10 {"packages":{"wpackagist-plugin\/wordpress-pastebin":{"0.4.4":{"name":"wpackagist-plugin\/wordpress-pastebin","version":"0.4.4","version_normalized":"0.4.4.0","uid":402886,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/wordpress-pastebin.0.4.4.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/wordpress-pastebin\/","reference":"tags\/0.4.4"},"homepage":"https:\/\/wordpress.org\/plugins\/wordpress-pastebin\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.4.5.1":{"name":"wpackagist-plugin\/wordpress-pastebin","version":"0.4.5.1","version_normalized":"0.4.5.1","uid":402887,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/wordpress-pastebin.0.4.5.1.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/wordpress-pastebin\/","reference":"tags\/0.4.5.1"},"homepage":"https:\/\/wordpress.org\/plugins\/wordpress-pastebin\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.4.5.2":{"name":"wpackagist-plugin\/wordpress-pastebin","version":"0.4.5.2","version_normalized":"0.4.5.2","uid":402888,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/wordpress-pastebin.0.4.5.2.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/wordpress-pastebin\/","reference":"tags\/0.4.5.2"},"homepage":"https:\/\/wordpress.org\/plugins\/wordpress-pastebin\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.4.5.3":{"name":"wpackagist-plugin\/wordpress-pastebin","version":"0.4.5.3","version_normalized":"0.4.5.3","uid":402889,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/wordpress-pastebin.0.4.5.3.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/wordpress-pastebin\/","reference":"tags\/0.4.5.3"},"homepage":"https:\/\/wordpress.org\/plugins\/wordpress-pastebin\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.4.5.4":{"name":"wpackagist-plugin\/wordpress-pastebin","version":"0.4.5.4","version_normalized":"0.4.5.4","uid":402890,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/wordpress-pastebin.0.4.5.4.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/wordpress-pastebin\/","reference":"tags\/0.4.5.4"},"homepage":"https:\/\/wordpress.org\/plugins\/wordpress-pastebin\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/wordpress-pastebin","version":"dev-trunk","version_normalized":"9999999-dev","uid":402891,"time":"2010-10-22 08:00:50","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/wordpress-pastebin.zip?timestamp=1287734450"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/wordpress-pastebin\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/wordpress-pastebin\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/me/memory-viewer/package.json ======================= {"packages":{"wpackagist-plugin\/memory-viewer":{"1.04":{"name":"wpackagist-plugin\/memory-viewer","version":"1.04","version_normalized":"1.04.0.0","uid":214475,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/memory-viewer.1.04.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/memory-viewer\/","reference":"tags\/1.04"},"homepage":"https:\/\/wordpress.org\/plugins\/memory-viewer\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.05":{"name":"wpackagist-plugin\/memory-viewer","version":"1.05","version_normalized":"1.05.0.0","uid":214476,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/memory-viewer.1.05.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/memory-viewer\/","reference":"tags\/1.05"},"homepage":"https:\/\/wordpress.org\/plugins\/memory-viewer\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/memory-viewer","version":"dev-trunk","version_normalized":"9999999-dev","uid":214477,"time":"2011-11-28 23:21:01","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/memory-viewer.zip?timestamp=1322522461"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/memory-viewer\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/memory-viewer\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/an/any-word-search/package.json ======================= <gh_stars>1-10 {"packages":{"wpackagist-plugin\/any-word-search":{"1.0":{"name":"wpackagist-plugin\/any-word-search","version":"1.0","version_normalized":"1.0.0.0","uid":23435,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/any-word-search.1.0.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/any-word-search\/","reference":"tags\/1.0"},"homepage":"https:\/\/wordpress.org\/plugins\/any-word-search\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/any-word-search","version":"dev-trunk","version_normalized":"9999999-dev","uid":23436,"time":"2013-04-02 00:04:00","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/any-word-search.zip?timestamp=1364861040"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/any-word-search\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/any-word-search\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/si/simple-groups/package.json ======================= {"packages":{"wpackagist-plugin\/simple-groups":{"1.0":{"name":"wpackagist-plugin\/simple-groups","version":"1.0","version_normalized":"1.0.0.0","uid":315207,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/simple-groups.1.0.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/simple-groups\/","reference":"tags\/1.0"},"homepage":"https:\/\/wordpress.org\/plugins\/simple-groups\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.0.1":{"name":"wpackagist-plugin\/simple-groups","version":"1.0.1","version_normalized":"1.0.1.0","uid":315208,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/simple-groups.1.0.1.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/simple-groups\/","reference":"tags\/1.0.1"},"homepage":"https:\/\/wordpress.org\/plugins\/simple-groups\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.1":{"name":"wpackagist-plugin\/simple-groups","version":"1.1","version_normalized":"1.1.0.0","uid":315209,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/simple-groups.1.1.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/simple-groups\/","reference":"tags\/1.1"},"homepage":"https:\/\/wordpress.org\/plugins\/simple-groups\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.2":{"name":"wpackagist-plugin\/simple-groups","version":"1.2","version_normalized":"1.2.0.0","uid":315210,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/simple-groups.1.2.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/simple-groups\/","reference":"tags\/1.2"},"homepage":"https:\/\/wordpress.org\/plugins\/simple-groups\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/simple-groups","version":"dev-trunk","version_normalized":"9999999-dev","uid":315211,"time":"2012-12-26 20:22:10","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/simple-groups.zip?timestamp=1356553330"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/simple-groups\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/simple-groups\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/we/webcam-cima-grappa/package.json ======================= {"packages":{"wpackagist-plugin\/webcam-cima-grappa":{"1.0.0":{"name":"wpackagist-plugin\/webcam-cima-grappa","version":"1.0.0","version_normalized":"1.0.0.0","uid":383143,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/webcam-cima-grappa.1.0.0.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/webcam-cima-grappa\/","reference":"tags\/1.0.0"},"homepage":"https:\/\/wordpress.org\/plugins\/webcam-cima-grappa\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/webcam-cima-grappa","version":"dev-trunk","version_normalized":"9999999-dev","uid":383144,"time":"2015-01-08 12:33:19","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/webcam-cima-grappa.zip?timestamp=1420720399"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/webcam-cima-grappa\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/webcam-cima-grappa\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/co/contributors-posts/package.json ======================= <gh_stars>1-10 {"packages":{"wpackagist-plugin\/contributors-posts":{"0.7.2":{"name":"wpackagist-plugin\/contributors-posts","version":"0.7.2","version_normalized":"0.7.2.0","uid":81768,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/contributors-posts.0.7.2.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/contributors-posts\/","reference":"tags\/0.7.2"},"homepage":"https:\/\/wordpress.org\/plugins\/contributors-posts\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.7.2.1":{"name":"wpackagist-plugin\/contributors-posts","version":"0.7.2.1","version_normalized":"0.7.2.1","uid":81769,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/contributors-posts.0.7.2.1.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/contributors-posts\/","reference":"tags\/0.7.2.1"},"homepage":"https:\/\/wordpress.org\/plugins\/contributors-posts\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.8":{"name":"wpackagist-plugin\/contributors-posts","version":"0.8","version_normalized":"0.8.0.0","uid":81770,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/contributors-posts.0.8.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/contributors-posts\/","reference":"tags\/0.8"},"homepage":"https:\/\/wordpress.org\/plugins\/contributors-posts\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.8.1":{"name":"wpackagist-plugin\/contributors-posts","version":"0.8.1","version_normalized":"0.8.1.0","uid":81771,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/contributors-posts.0.8.1.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/contributors-posts\/","reference":"tags\/0.8.1"},"homepage":"https:\/\/wordpress.org\/plugins\/contributors-posts\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/contributors-posts","version":"dev-trunk","version_normalized":"9999999-dev","uid":81772,"time":"2014-05-01 10:28:03","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/contributors-posts.zip?timestamp=1398940083"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/contributors-posts\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/contributors-posts\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/ch/chronological-spam-removal/package.json ======================= {"packages":{"wpackagist-plugin\/chronological-spam-removal":{"1.0.0.0":{"name":"wpackagist-plugin\/chronological-spam-removal","version":"1.0.0.0","version_normalized":"1.0.0.0","uid":68270,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/chronological-spam-removal.1.0.0.0.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/chronological-spam-removal\/","reference":"tags\/1.0.0.0"},"homepage":"https:\/\/wordpress.org\/plugins\/chronological-spam-removal\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.0.1.0":{"name":"wpackagist-plugin\/chronological-spam-removal","version":"1.0.1.0","version_normalized":"1.0.1.0","uid":68271,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/chronological-spam-removal.1.0.1.0.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/chronological-spam-removal\/","reference":"tags\/1.0.1.0"},"homepage":"https:\/\/wordpress.org\/plugins\/chronological-spam-removal\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.0.2.0":{"name":"wpackagist-plugin\/chronological-spam-removal","version":"1.0.2.0","version_normalized":"1.0.2.0","uid":68272,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/chronological-spam-removal.1.0.2.0.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/chronological-spam-removal\/","reference":"tags\/1.0.2.0"},"homepage":"https:\/\/wordpress.org\/plugins\/chronological-spam-removal\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.0.3.0":{"name":"wpackagist-plugin\/chronological-spam-removal","version":"1.0.3.0","version_normalized":"1.0.3.0","uid":68273,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/chronological-spam-removal.1.0.3.0.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/chronological-spam-removal\/","reference":"tags\/1.0.3.0"},"homepage":"https:\/\/wordpress.org\/plugins\/chronological-spam-removal\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.0.4.0":{"name":"wpackagist-plugin\/chronological-spam-removal","version":"1.0.4.0","version_normalized":"1.0.4.0","uid":68274,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/chronological-spam-removal.1.0.4.0.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/chronological-spam-removal\/","reference":"tags\/1.0.4.0"},"homepage":"https:\/\/wordpress.org\/plugins\/chronological-spam-removal\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/chronological-spam-removal","version":"dev-trunk","version_normalized":"9999999-dev","uid":68275,"time":"2012-02-26 02:40:10","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/chronological-spam-removal.zip?timestamp=1330224010"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/chronological-spam-removal\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/chronological-spam-removal\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/my/myph3preview/package.json ======================= <gh_stars>1-10 {"packages":{"wpackagist-plugin\/myph3preview":{"1.0":{"name":"wpackagist-plugin\/myph3preview","version":"1.0","version_normalized":"1.0.0.0","uid":228469,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/myph3preview.1.0.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/myph3preview\/","reference":"tags\/1.0"},"homepage":"https:\/\/wordpress.org\/plugins\/myph3preview\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"2.0":{"name":"wpackagist-plugin\/myph3preview","version":"2.0","version_normalized":"2.0.0.0","uid":228470,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/myph3preview.2.0.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/myph3preview\/","reference":"tags\/2.0"},"homepage":"https:\/\/wordpress.org\/plugins\/myph3preview\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"2.1":{"name":"wpackagist-plugin\/myph3preview","version":"2.1","version_normalized":"2.1.0.0","uid":228471,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/myph3preview.2.1.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/myph3preview\/","reference":"tags\/2.1"},"homepage":"https:\/\/wordpress.org\/plugins\/myph3preview\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/myph3preview","version":"dev-trunk","version_normalized":"9999999-dev","uid":228472,"time":"2008-03-26 09:27:59","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/myph3preview.zip?timestamp=1206523679"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/myph3preview\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/myph3preview\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-theme/re/reference/package.json ======================= {"packages":{"wpackagist-theme\/reference":{"1.0":{"name":"wpackagist-theme\/reference","version":"1.0","version_normalized":"1.0.0.0","uid":285427,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/reference.1.0.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/reference\/","reference":"1.0"},"homepage":"https:\/\/wordpress.org\/themes\/reference\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.1":{"name":"wpackagist-theme\/reference","version":"1.1","version_normalized":"1.1.0.0","uid":285428,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/reference.1.1.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/reference\/","reference":"1.1"},"homepage":"https:\/\/wordpress.org\/themes\/reference\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.5":{"name":"wpackagist-theme\/reference","version":"1.5","version_normalized":"1.5.0.0","uid":285429,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/reference.1.5.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/reference\/","reference":"1.5"},"homepage":"https:\/\/wordpress.org\/themes\/reference\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.6":{"name":"wpackagist-theme\/reference","version":"1.6","version_normalized":"1.6.0.0","uid":285430,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/reference.1.6.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/reference\/","reference":"1.6"},"homepage":"https:\/\/wordpress.org\/themes\/reference\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"}}}} ======================= File: data/wpackagist-plugin/ne/new-twitter-button/package.json ======================= <filename>data/wpackagist-plugin/ne/new-twitter-button/package.json {"packages":{"wpackagist-plugin\/new-twitter-button":{"0.1.2b":{"name":"wpackagist-plugin\/new-twitter-button","version":"0.1.2b","version_normalized":"0.1.2.0-beta","uid":231855,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/new-twitter-button.0.1.2b.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/new-twitter-button\/","reference":"tags\/0.1.2b"},"homepage":"https:\/\/wordpress.org\/plugins\/new-twitter-button\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.2.1":{"name":"wpackagist-plugin\/new-twitter-button","version":"0.2.1","version_normalized":"0.2.1.0","uid":231856,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/new-twitter-button.0.2.1.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/new-twitter-button\/","reference":"tags\/0.2.1"},"homepage":"https:\/\/wordpress.org\/plugins\/new-twitter-button\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.2.2":{"name":"wpackagist-plugin\/new-twitter-button","version":"0.2.2","version_normalized":"0.2.2.0","uid":231857,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/new-twitter-button.0.2.2.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/new-twitter-button\/","reference":"tags\/0.2.2"},"homepage":"https:\/\/wordpress.org\/plugins\/new-twitter-button\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.2.4":{"name":"wpackagist-plugin\/new-twitter-button","version":"0.2.4","version_normalized":"0.2.4.0","uid":231858,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/new-twitter-button.0.2.4.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/new-twitter-button\/","reference":"tags\/0.2.4"},"homepage":"https:\/\/wordpress.org\/plugins\/new-twitter-button\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.2b":{"name":"wpackagist-plugin\/new-twitter-button","version":"0.2b","version_normalized":"0.2.0.0-beta","uid":231859,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/new-twitter-button.0.2b.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/new-twitter-button\/","reference":"tags\/0.2b"},"homepage":"https:\/\/wordpress.org\/plugins\/new-twitter-button\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.3.1":{"name":"wpackagist-plugin\/new-twitter-button","version":"0.3.1","version_normalized":"0.3.1.0","uid":231860,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/new-twitter-button.0.3.1.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/new-twitter-button\/","reference":"tags\/0.3.1"},"homepage":"https:\/\/wordpress.org\/plugins\/new-twitter-button\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"2.0.1":{"name":"wpackagist-plugin\/new-twitter-button","version":"2.0.1","version_normalized":"2.0.1.0","uid":231861,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/new-twitter-button.2.0.1.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/new-twitter-button\/","reference":"tags\/2.0.1"},"homepage":"https:\/\/wordpress.org\/plugins\/new-twitter-button\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"2.0.2":{"name":"wpackagist-plugin\/new-twitter-button","version":"2.0.2","version_normalized":"2.0.2.0","uid":231862,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/new-twitter-button.2.0.2.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/new-twitter-button\/","reference":"tags\/2.0.2"},"homepage":"https:\/\/wordpress.org\/plugins\/new-twitter-button\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"2.1":{"name":"wpackagist-plugin\/new-twitter-button","version":"2.1","version_normalized":"2.1.0.0","uid":231863,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/new-twitter-button.2.1.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/new-twitter-button\/","reference":"tags\/2.1"},"homepage":"https:\/\/wordpress.org\/plugins\/new-twitter-button\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/new-twitter-button","version":"dev-trunk","version_normalized":"9999999-dev","uid":231864,"time":"2014-03-04 17:42:50","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/new-twitter-button.zip?timestamp=1393954970"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/new-twitter-button\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/new-twitter-button\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/qu/quick-count/package.json ======================= <gh_stars>1-10 {"packages":{"wpackagist-plugin\/quick-count":{"3.00":{"name":"wpackagist-plugin\/quick-count","version":"3.00","version_normalized":"3.00.0.0","uid":276685,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/quick-count.zip?timestamp=1353881983"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/quick-count\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/quick-count\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/quick-count","version":"dev-trunk","version_normalized":"9999999-dev","uid":276686,"time":"2012-11-25 22:19:43","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/quick-count.zip?timestamp=1353881983"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/quick-count\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/quick-count\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/wp/wp-tidy-tinymce/package.json ======================= <reponame>wplib/wpackagist-requestor {"packages":{"wpackagist-plugin\/wp-tidy-tinymce":{"1.0":{"name":"wpackagist-plugin\/wp-tidy-tinymce","version":"1.0","version_normalized":"1.0.0.0","uid":436389,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/wp-tidy-tinymce.1.0.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/wp-tidy-tinymce\/","reference":"tags\/1.0"},"homepage":"https:\/\/wordpress.org\/plugins\/wp-tidy-tinymce\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"2.0":{"name":"wpackagist-plugin\/wp-tidy-tinymce","version":"2.0","version_normalized":"2.0.0.0","uid":436390,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/wp-tidy-tinymce.2.0.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/wp-tidy-tinymce\/","reference":"tags\/2.0"},"homepage":"https:\/\/wordpress.org\/plugins\/wp-tidy-tinymce\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/wp-tidy-tinymce","version":"dev-trunk","version_normalized":"9999999-dev","uid":436391,"time":"2014-05-15 10:15:09","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/wp-tidy-tinymce.zip?timestamp=1400148909"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/wp-tidy-tinymce\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/wp-tidy-tinymce\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/mi/minecraft-server-status-widget/package.json ======================= {"packages":{"wpackagist-plugin\/minecraft-server-status-widget":{"1.1":{"name":"wpackagist-plugin\/minecraft-server-status-widget","version":"1.1","version_normalized":"1.1.0.0","uid":217839,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/minecraft-server-status-widget.zip?timestamp=1340575014"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/minecraft-server-status-widget\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/minecraft-server-status-widget\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"2.0":{"name":"wpackagist-plugin\/minecraft-server-status-widget","version":"2.0","version_normalized":"2.0.0.0","uid":217840,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/minecraft-server-status-widget.2.0.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/minecraft-server-status-widget\/","reference":"tags\/2.0"},"homepage":"https:\/\/wordpress.org\/plugins\/minecraft-server-status-widget\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/minecraft-server-status-widget","version":"dev-trunk","version_normalized":"9999999-dev","uid":217841,"time":"2012-06-24 21:56:54","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/minecraft-server-status-widget.zip?timestamp=1340575014"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/minecraft-server-status-widget\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/minecraft-server-status-widget\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-theme/ch/chaostheory/package.json ======================= <filename>data/wpackagist-theme/ch/chaostheory/package.json {"packages":{"wpackagist-theme\/chaostheory":{"1.1":{"name":"wpackagist-theme\/chaostheory","version":"1.1","version_normalized":"1.1.0.0","uid":66027,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/chaostheory.1.1.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/chaostheory\/","reference":"1.1"},"homepage":"https:\/\/wordpress.org\/themes\/chaostheory\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.1.1":{"name":"wpackagist-theme\/chaostheory","version":"1.1.1","version_normalized":"1.1.1.0","uid":66028,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/chaostheory.1.1.1.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/chaostheory\/","reference":"1.1.1"},"homepage":"https:\/\/wordpress.org\/themes\/chaostheory\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.1.2":{"name":"wpackagist-theme\/chaostheory","version":"1.1.2","version_normalized":"1.1.2.0","uid":66029,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/chaostheory.1.1.2.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/chaostheory\/","reference":"1.1.2"},"homepage":"https:\/\/wordpress.org\/themes\/chaostheory\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.1.3":{"name":"wpackagist-theme\/chaostheory","version":"1.1.3","version_normalized":"1.1.3.0","uid":66030,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/chaostheory.1.1.3.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/chaostheory\/","reference":"1.1.3"},"homepage":"https:\/\/wordpress.org\/themes\/chaostheory\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.2":{"name":"wpackagist-theme\/chaostheory","version":"1.2","version_normalized":"1.2.0.0","uid":66031,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/chaostheory.1.2.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/chaostheory\/","reference":"1.2"},"homepage":"https:\/\/wordpress.org\/themes\/chaostheory\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.3":{"name":"wpackagist-theme\/chaostheory","version":"1.3","version_normalized":"1.3.0.0","uid":66032,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/chaostheory.1.3.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/chaostheory\/","reference":"1.3"},"homepage":"https:\/\/wordpress.org\/themes\/chaostheory\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"}}}} ======================= File: data/wpackagist-plugin/ti/tierra-billboard-manager/package.json ======================= {"packages":{"wpackagist-plugin\/tierra-billboard-manager":{"1.14":{"name":"wpackagist-plugin\/tierra-billboard-manager","version":"1.14","version_normalized":"1.14.0.0","uid":354505,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/tierra-billboard-manager.zip?timestamp=1293054717"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/tierra-billboard-manager\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/tierra-billboard-manager\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/tierra-billboard-manager","version":"dev-trunk","version_normalized":"9999999-dev","uid":354506,"time":"2010-12-22 21:51:57","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/tierra-billboard-manager.zip?timestamp=1293054717"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/tierra-billboard-manager\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/tierra-billboard-manager\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/da/daily-quote-by-quote-land/package.json ======================= <reponame>wplib/wpackagist-requestor {"packages":{"wpackagist-plugin\/daily-quote-by-quote-land":{"1.0":{"name":"wpackagist-plugin\/daily-quote-by-quote-land","version":"1.0","version_normalized":"1.0.0.0","uid":93728,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/daily-quote-by-quote-land.zip?timestamp=1393809186"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/daily-quote-by-quote-land\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/daily-quote-by-quote-land\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.0.0":{"name":"wpackagist-plugin\/daily-quote-by-quote-land","version":"1.0.0","version_normalized":"1.0.0.0","uid":93729,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/daily-quote-by-quote-land.1.0.0.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/daily-quote-by-quote-land\/","reference":"tags\/1.0.0"},"homepage":"https:\/\/wordpress.org\/plugins\/daily-quote-by-quote-land\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.0.1":{"name":"wpackagist-plugin\/daily-quote-by-quote-land","version":"1.0.1","version_normalized":"1.0.1.0","uid":93730,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/daily-quote-by-quote-land.1.0.1.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/daily-quote-by-quote-land\/","reference":"tags\/1.0.1"},"homepage":"https:\/\/wordpress.org\/plugins\/daily-quote-by-quote-land\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.1.0":{"name":"wpackagist-plugin\/daily-quote-by-quote-land","version":"1.1.0","version_normalized":"1.1.0.0","uid":93731,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/daily-quote-by-quote-land.1.1.0.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/daily-quote-by-quote-land\/","reference":"tags\/1.1.0"},"homepage":"https:\/\/wordpress.org\/plugins\/daily-quote-by-quote-land\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/daily-quote-by-quote-land","version":"dev-trunk","version_normalized":"9999999-dev","uid":93732,"time":"2014-03-03 01:13:06","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/daily-quote-by-quote-land.zip?timestamp=1393809186"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/daily-quote-by-quote-land\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/daily-quote-by-quote-land\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/sq/sqlmon/package.json ======================= <filename>data/wpackagist-plugin/sq/sqlmon/package.json {"packages":{"wpackagist-plugin\/sqlmon":{"0.5":{"name":"wpackagist-plugin\/sqlmon","version":"0.5","version_normalized":"0.5.0.0","uid":334921,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/sqlmon.0.5.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/sqlmon\/","reference":"tags\/0.5"},"homepage":"https:\/\/wordpress.org\/plugins\/sqlmon\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.5.1":{"name":"wpackagist-plugin\/sqlmon","version":"0.5.1","version_normalized":"0.5.1.0","uid":334922,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/sqlmon.0.5.1.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/sqlmon\/","reference":"tags\/0.5.1"},"homepage":"https:\/\/wordpress.org\/plugins\/sqlmon\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.5.4":{"name":"wpackagist-plugin\/sqlmon","version":"0.5.4","version_normalized":"0.5.4.0","uid":334923,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/sqlmon.0.5.4.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/sqlmon\/","reference":"tags\/0.5.4"},"homepage":"https:\/\/wordpress.org\/plugins\/sqlmon\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.5.6":{"name":"wpackagist-plugin\/sqlmon","version":"0.5.6","version_normalized":"0.5.6.0","uid":334924,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/sqlmon.0.5.6.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/sqlmon\/","reference":"tags\/0.5.6"},"homepage":"https:\/\/wordpress.org\/plugins\/sqlmon\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.5.7":{"name":"wpackagist-plugin\/sqlmon","version":"0.5.7","version_normalized":"0.5.7.0","uid":334925,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/sqlmon.0.5.7.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/sqlmon\/","reference":"tags\/0.5.7"},"homepage":"https:\/\/wordpress.org\/plugins\/sqlmon\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.5.8":{"name":"wpackagist-plugin\/sqlmon","version":"0.5.8","version_normalized":"0.5.8.0","uid":334926,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/sqlmon.0.5.8.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/sqlmon\/","reference":"tags\/0.5.8"},"homepage":"https:\/\/wordpress.org\/plugins\/sqlmon\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.5.8.1":{"name":"wpackagist-plugin\/sqlmon","version":"0.5.8.1","version_normalized":"0.5.8.1","uid":334927,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/sqlmon.0.5.8.1.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/sqlmon\/","reference":"tags\/0.5.8.1"},"homepage":"https:\/\/wordpress.org\/plugins\/sqlmon\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.5.9":{"name":"wpackagist-plugin\/sqlmon","version":"0.5.9","version_normalized":"0.5.9.0","uid":334928,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/sqlmon.0.5.9.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/sqlmon\/","reference":"tags\/0.5.9"},"homepage":"https:\/\/wordpress.org\/plugins\/sqlmon\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.6":{"name":"wpackagist-plugin\/sqlmon","version":"0.6","version_normalized":"0.6.0.0","uid":334929,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/sqlmon.0.6.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/sqlmon\/","reference":"tags\/0.6"},"homepage":"https:\/\/wordpress.org\/plugins\/sqlmon\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.6.1.1":{"name":"wpackagist-plugin\/sqlmon","version":"0.6.1.1","version_normalized":"0.6.1.1","uid":334930,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/sqlmon.0.6.1.1.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/sqlmon\/","reference":"tags\/0.6.1.1"},"homepage":"https:\/\/wordpress.org\/plugins\/sqlmon\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/sqlmon","version":"dev-trunk","version_normalized":"9999999-dev","uid":334931,"time":"2011-07-04 17:24:09","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/sqlmon.zip?timestamp=1309800249"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/sqlmon\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/sqlmon\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/su/sui-proxyme/package.json ======================= {"packages":{"wpackagist-plugin\/sui-proxyme":{"0.1":{"name":"wpackagist-plugin\/sui-proxyme","version":"0.1","version_normalized":"0.1.0.0","uid":341144,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/sui-proxyme.zip?timestamp=1250080050"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/sui-proxyme\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/sui-proxyme\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/sui-proxyme","version":"dev-trunk","version_normalized":"9999999-dev","uid":341145,"time":"2009-08-12 12:27:30","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/sui-proxyme.zip?timestamp=1250080050"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/sui-proxyme\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/sui-proxyme\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/st/st-simple-gallery-shortcode/package.json ======================= <reponame>wplib/wpackagist-requestor {"packages":{"wpackagist-plugin\/st-simple-gallery-shortcode":{"1.0":{"name":"wpackagist-plugin\/st-simple-gallery-shortcode","version":"1.0","version_normalized":"1.0.0.0","uid":335515,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/st-simple-gallery-shortcode.1.0.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/st-simple-gallery-shortcode\/","reference":"tags\/1.0"},"homepage":"https:\/\/wordpress.org\/plugins\/st-simple-gallery-shortcode\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.0.1":{"name":"wpackagist-plugin\/st-simple-gallery-shortcode","version":"1.0.1","version_normalized":"1.0.1.0","uid":335516,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/st-simple-gallery-shortcode.1.0.1.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/st-simple-gallery-shortcode\/","reference":"tags\/1.0.1"},"homepage":"https:\/\/wordpress.org\/plugins\/st-simple-gallery-shortcode\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/st-simple-gallery-shortcode","version":"dev-trunk","version_normalized":"9999999-dev","uid":335517,"time":"2015-12-04 16:26:41","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/st-simple-gallery-shortcode.zip?timestamp=1449246401"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/st-simple-gallery-shortcode\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/st-simple-gallery-shortcode\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/ic/icopaw-customizable-animal-rescue-icons/package.json ======================= {"packages":{"wpackagist-plugin\/icopaw-customizable-animal-rescue-icons":{"1.0":{"name":"wpackagist-plugin\/icopaw-customizable-animal-rescue-icons","version":"1.0","version_normalized":"1.0.0.0","uid":171261,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/icopaw-customizable-animal-rescue-icons.1.0.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/icopaw-customizable-animal-rescue-icons\/","reference":"tags\/1.0"},"homepage":"https:\/\/wordpress.org\/plugins\/icopaw-customizable-animal-rescue-icons\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/icopaw-customizable-animal-rescue-icons","version":"dev-trunk","version_normalized":"9999999-dev","uid":171262,"time":"2014-09-10 02:27:03","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/icopaw-customizable-animal-rescue-icons.zip?timestamp=1410316023"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/icopaw-customizable-animal-rescue-icons\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/icopaw-customizable-animal-rescue-icons\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/tw/twitter-sp2/package.json ======================= <reponame>wplib/wpackagist-requestor {"packages":{"wpackagist-plugin\/twitter-sp2":{"0.6.1":{"name":"wpackagist-plugin\/twitter-sp2","version":"0.6.1","version_normalized":"0.6.1.0","uid":363775,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/twitter-sp2.zip?timestamp=1252944160"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/twitter-sp2\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/twitter-sp2\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.1":{"name":"wpackagist-plugin\/twitter-sp2","version":"0.1","version_normalized":"0.1.0.0","uid":363776,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/twitter-sp2.0.1.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/twitter-sp2\/","reference":"tags\/0.1"},"homepage":"https:\/\/wordpress.org\/plugins\/twitter-sp2\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.1.1":{"name":"wpackagist-plugin\/twitter-sp2","version":"0.1.1","version_normalized":"0.1.1.0","uid":363777,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/twitter-sp2.0.1.1.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/twitter-sp2\/","reference":"tags\/0.1.1"},"homepage":"https:\/\/wordpress.org\/plugins\/twitter-sp2\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.2":{"name":"wpackagist-plugin\/twitter-sp2","version":"0.2","version_normalized":"0.2.0.0","uid":363778,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/twitter-sp2.0.2.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/twitter-sp2\/","reference":"tags\/0.2"},"homepage":"https:\/\/wordpress.org\/plugins\/twitter-sp2\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.3":{"name":"wpackagist-plugin\/twitter-sp2","version":"0.3","version_normalized":"0.3.0.0","uid":363779,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/twitter-sp2.0.3.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/twitter-sp2\/","reference":"tags\/0.3"},"homepage":"https:\/\/wordpress.org\/plugins\/twitter-sp2\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.4":{"name":"wpackagist-plugin\/twitter-sp2","version":"0.4","version_normalized":"0.4.0.0","uid":363780,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/twitter-sp2.0.4.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/twitter-sp2\/","reference":"tags\/0.4"},"homepage":"https:\/\/wordpress.org\/plugins\/twitter-sp2\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.5":{"name":"wpackagist-plugin\/twitter-sp2","version":"0.5","version_normalized":"0.5.0.0","uid":363781,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/twitter-sp2.0.5.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/twitter-sp2\/","reference":"tags\/0.5"},"homepage":"https:\/\/wordpress.org\/plugins\/twitter-sp2\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.6":{"name":"wpackagist-plugin\/twitter-sp2","version":"0.6","version_normalized":"0.6.0.0","uid":363782,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/twitter-sp2.0.6.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/twitter-sp2\/","reference":"tags\/0.6"},"homepage":"https:\/\/wordpress.org\/plugins\/twitter-sp2\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/twitter-sp2","version":"dev-trunk","version_normalized":"9999999-dev","uid":363783,"time":"2009-09-14 16:02:40","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/twitter-sp2.zip?timestamp=1252944160"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/twitter-sp2\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/twitter-sp2\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/si/sitemap-navigation/package.json ======================= {"packages":{"wpackagist-plugin\/sitemap-navigation":{"3.3":{"name":"wpackagist-plugin\/sitemap-navigation","version":"3.3","version_normalized":"3.3.0.0","uid":321073,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/sitemap-navigation.zip?timestamp=1324105790"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/sitemap-navigation\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/sitemap-navigation\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/sitemap-navigation","version":"dev-trunk","version_normalized":"9999999-dev","uid":321074,"time":"2011-12-17 07:09:50","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/sitemap-navigation.zip?timestamp=1324105790"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/sitemap-navigation\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/sitemap-navigation\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/au/author/package.json ======================= {"packages":{"wpackagist-plugin\/author":{"1.9":{"name":"wpackagist-plugin\/author","version":"1.9","version_normalized":"1.9.0.0","uid":29504,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/author.zip?timestamp=1339524674"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/author\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/author\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.8":{"name":"wpackagist-plugin\/author","version":"1.8","version_normalized":"1.8.0.0","uid":29505,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/author.1.8.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/author\/","reference":"tags\/1.8"},"homepage":"https:\/\/wordpress.org\/plugins\/author\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/author","version":"dev-trunk","version_normalized":"9999999-dev","uid":29506,"time":"2012-06-12 18:11:14","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/author.zip?timestamp=1339524674"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/author\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/author\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/fa/fashion-traffic/package.json ======================= {"packages":{"wpackagist-plugin\/fashion-traffic":{"1.0.0":{"name":"wpackagist-plugin\/fashion-traffic","version":"1.0.0","version_normalized":"1.0.0.0","uid":129673,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/fashion-traffic.1.0.0.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/fashion-traffic\/","reference":"tags\/1.0.0"},"homepage":"https:\/\/wordpress.org\/plugins\/fashion-traffic\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.0.1":{"name":"wpackagist-plugin\/fashion-traffic","version":"1.0.1","version_normalized":"1.0.1.0","uid":129674,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/fashion-traffic.1.0.1.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/fashion-traffic\/","reference":"tags\/1.0.1"},"homepage":"https:\/\/wordpress.org\/plugins\/fashion-traffic\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/fashion-traffic","version":"dev-trunk","version_normalized":"9999999-dev","uid":129675,"time":"2012-09-09 22:17:04","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/fashion-traffic.zip?timestamp=1347229024"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/fashion-traffic\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/fashion-traffic\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/ad/advanced-random-posts/package.json ======================= {"packages":{"wpackagist-plugin\/advanced-random-posts":{"2.3":{"name":"wpackagist-plugin\/advanced-random-posts","version":"2.3","version_normalized":"2.3.0.0","uid":12847,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/advanced-random-posts.zip?timestamp=1252178326"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/advanced-random-posts\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/advanced-random-posts\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.1":{"name":"wpackagist-plugin\/advanced-random-posts","version":"1.1","version_normalized":"1.1.0.0","uid":12848,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/advanced-random-posts.1.1.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/advanced-random-posts\/","reference":"tags\/1.1"},"homepage":"https:\/\/wordpress.org\/plugins\/advanced-random-posts\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/advanced-random-posts","version":"dev-trunk","version_normalized":"9999999-dev","uid":12849,"time":"2009-09-05 19:18:46","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/advanced-random-posts.zip?timestamp=1252178326"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/advanced-random-posts\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/advanced-random-posts\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/db/dbd-fire-fighter/package.json ======================= <reponame>wplib/wpackagist-requestor<gh_stars>1-10 {"packages":{"wpackagist-plugin\/dbd-fire-fighter":{"1.0":{"name":"wpackagist-plugin\/dbd-fire-fighter","version":"1.0","version_normalized":"1.0.0.0","uid":95496,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/dbd-fire-fighter.zip?timestamp=1369430064"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/dbd-fire-fighter\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/dbd-fire-fighter\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/dbd-fire-fighter","version":"dev-trunk","version_normalized":"9999999-dev","uid":95497,"time":"2013-05-24 21:14:24","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/dbd-fire-fighter.zip?timestamp=1369430064"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/dbd-fire-fighter\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/dbd-fire-fighter\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/xt/xtreme-zoom-menu/package.json ======================= <reponame>wplib/wpackagist-requestor<gh_stars>1-10 {"packages":{"wpackagist-plugin\/xtreme-zoom-menu":{"1.2":{"name":"wpackagist-plugin\/xtreme-zoom-menu","version":"1.2","version_normalized":"1.2.0.0","uid":447240,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/xtreme-zoom-menu.zip?timestamp=1292586380"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/xtreme-zoom-menu\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/xtreme-zoom-menu\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/xtreme-zoom-menu","version":"dev-trunk","version_normalized":"9999999-dev","uid":447241,"time":"2010-12-17 11:46:20","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/xtreme-zoom-menu.zip?timestamp=1292586380"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/xtreme-zoom-menu\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/xtreme-zoom-menu\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/ba/ballast-security-securing-hashing/package.json ======================= {"packages":{"wpackagist-plugin\/ballast-security-securing-hashing":{"1.2.1":{"name":"wpackagist-plugin\/ballast-security-securing-hashing","version":"1.2.1","version_normalized":"1.2.1.0","uid":35338,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/ballast-security-securing-hashing.zip?timestamp=1346969866"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/ballast-security-securing-hashing\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/ballast-security-securing-hashing\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.2b":{"name":"wpackagist-plugin\/ballast-security-securing-hashing","version":"0.2b","version_normalized":"0.2.0.0-beta","uid":35339,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/ballast-security-securing-hashing.0.2b.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/ballast-security-securing-hashing\/","reference":"tags\/0.2b"},"homepage":"https:\/\/wordpress.org\/plugins\/ballast-security-securing-hashing\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.3b":{"name":"wpackagist-plugin\/ballast-security-securing-hashing","version":"0.3b","version_normalized":"0.3.0.0-beta","uid":35340,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/ballast-security-securing-hashing.0.3b.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/ballast-security-securing-hashing\/","reference":"tags\/0.3b"},"homepage":"https:\/\/wordpress.org\/plugins\/ballast-security-securing-hashing\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.0":{"name":"wpackagist-plugin\/ballast-security-securing-hashing","version":"1.0","version_normalized":"1.0.0.0","uid":35341,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/ballast-security-securing-hashing.1.0.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/ballast-security-securing-hashing\/","reference":"tags\/1.0"},"homepage":"https:\/\/wordpress.org\/plugins\/ballast-security-securing-hashing\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.1":{"name":"wpackagist-plugin\/ballast-security-securing-hashing","version":"1.1","version_normalized":"1.1.0.0","uid":35342,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/ballast-security-securing-hashing.1.1.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/ballast-security-securing-hashing\/","reference":"tags\/1.1"},"homepage":"https:\/\/wordpress.org\/plugins\/ballast-security-securing-hashing\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.2":{"name":"wpackagist-plugin\/ballast-security-securing-hashing","version":"1.2","version_normalized":"1.2.0.0","uid":35343,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/ballast-security-securing-hashing.1.2.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/ballast-security-securing-hashing\/","reference":"tags\/1.2"},"homepage":"https:\/\/wordpress.org\/plugins\/ballast-security-securing-hashing\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/ballast-security-securing-hashing","version":"dev-trunk","version_normalized":"9999999-dev","uid":35344,"time":"2012-09-06 22:17:46","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/ballast-security-securing-hashing.zip?timestamp=1346969866"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/ballast-security-securing-hashing\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/ballast-security-securing-hashing\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/hi/hip-multifeed/package.json ======================= {"packages":{"wpackagist-plugin\/hip-multifeed":{"1.1":{"name":"wpackagist-plugin\/hip-multifeed","version":"1.1","version_normalized":"1.1.0.0","uid":166150,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/hip-multifeed.zip?timestamp=1337000127"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/hip-multifeed\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/hip-multifeed\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/hip-multifeed","version":"dev-trunk","version_normalized":"9999999-dev","uid":166151,"time":"2012-05-14 12:55:27","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/hip-multifeed.zip?timestamp=1337000127"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/hip-multifeed\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/hip-multifeed\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-theme/bi/bitlumen/package.json ======================= {"packages":{"wpackagist-theme\/bitlumen":{"0.4.0":{"name":"wpackagist-theme\/bitlumen","version":"0.4.0","version_normalized":"0.4.0.0","uid":42259,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/bitlumen.0.4.0.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/bitlumen\/","reference":"0.4.0"},"homepage":"https:\/\/wordpress.org\/themes\/bitlumen\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"0.4.1":{"name":"wpackagist-theme\/bitlumen","version":"0.4.1","version_normalized":"0.4.1.0","uid":42260,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/bitlumen.0.4.1.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/bitlumen\/","reference":"0.4.1"},"homepage":"https:\/\/wordpress.org\/themes\/bitlumen\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"0.4.2":{"name":"wpackagist-theme\/bitlumen","version":"0.4.2","version_normalized":"0.4.2.0","uid":42261,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/bitlumen.0.4.2.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/bitlumen\/","reference":"0.4.2"},"homepage":"https:\/\/wordpress.org\/themes\/bitlumen\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"0.4.3":{"name":"wpackagist-theme\/bitlumen","version":"0.4.3","version_normalized":"0.4.3.0","uid":42262,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/bitlumen.0.4.3.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/bitlumen\/","reference":"0.4.3"},"homepage":"https:\/\/wordpress.org\/themes\/bitlumen\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"0.4.5":{"name":"wpackagist-theme\/bitlumen","version":"0.4.5","version_normalized":"0.4.5.0","uid":42263,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/bitlumen.0.4.5.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/bitlumen\/","reference":"0.4.5"},"homepage":"https:\/\/wordpress.org\/themes\/bitlumen\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"0.4.6":{"name":"wpackagist-theme\/bitlumen","version":"0.4.6","version_normalized":"0.4.6.0","uid":42264,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/bitlumen.0.4.6.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/bitlumen\/","reference":"0.4.6"},"homepage":"https:\/\/wordpress.org\/themes\/bitlumen\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"0.4.7":{"name":"wpackagist-theme\/bitlumen","version":"0.4.7","version_normalized":"0.4.7.0","uid":42265,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/bitlumen.0.4.7.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/bitlumen\/","reference":"0.4.7"},"homepage":"https:\/\/wordpress.org\/themes\/bitlumen\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"0.4.7.1":{"name":"wpackagist-theme\/bitlumen","version":"0.4.7.1","version_normalized":"0.4.7.1","uid":42266,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/bitlumen.0.4.7.1.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/bitlumen\/","reference":"0.4.7.1"},"homepage":"https:\/\/wordpress.org\/themes\/bitlumen\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"0.5.0":{"name":"wpackagist-theme\/bitlumen","version":"0.5.0","version_normalized":"0.5.0.0","uid":42267,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/bitlumen.0.5.0.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/bitlumen\/","reference":"0.5.0"},"homepage":"https:\/\/wordpress.org\/themes\/bitlumen\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.0.0":{"name":"wpackagist-theme\/bitlumen","version":"1.0.0","version_normalized":"1.0.0.0","uid":42268,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/bitlumen.1.0.0.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/bitlumen\/","reference":"1.0.0"},"homepage":"https:\/\/wordpress.org\/themes\/bitlumen\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.0.1":{"name":"wpackagist-theme\/bitlumen","version":"1.0.1","version_normalized":"1.0.1.0","uid":42269,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/bitlumen.1.0.1.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/bitlumen\/","reference":"1.0.1"},"homepage":"https:\/\/wordpress.org\/themes\/bitlumen\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"}}}} ======================= File: data/wpackagist-plugin/ca/campusnet-authentication/package.json ======================= {"packages":{"wpackagist-plugin\/campusnet-authentication":{"0.2.6":{"name":"wpackagist-plugin\/campusnet-authentication","version":"0.2.6","version_normalized":"0.2.6.0","uid":59744,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/campusnet-authentication.zip?timestamp=1410436065"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/campusnet-authentication\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/campusnet-authentication\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/campusnet-authentication","version":"dev-trunk","version_normalized":"9999999-dev","uid":59745,"time":"2014-09-11 11:47:45","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/campusnet-authentication.zip?timestamp=1410436065"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/campusnet-authentication\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/campusnet-authentication\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/ze/zeemgo-expansion-pack-zep-for-rs-biz/package.json ======================= <gh_stars>1-10 {"packages":{"wpackagist-plugin\/zeemgo-expansion-pack-zep-for-rs-biz":{"1.0":{"name":"wpackagist-plugin\/zeemgo-expansion-pack-zep-for-rs-biz","version":"1.0","version_normalized":"1.0.0.0","uid":452462,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/zeemgo-expansion-pack-zep-for-rs-biz.zip?timestamp=1406240749"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/zeemgo-expansion-pack-zep-for-rs-biz\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/zeemgo-expansion-pack-zep-for-rs-biz\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/zeemgo-expansion-pack-zep-for-rs-biz","version":"dev-trunk","version_normalized":"9999999-dev","uid":452463,"time":"2014-07-24 22:25:49","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/zeemgo-expansion-pack-zep-for-rs-biz.zip?timestamp=1406240749"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/zeemgo-expansion-pack-zep-for-rs-biz\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/zeemgo-expansion-pack-zep-for-rs-biz\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/ho/horizontal-full-categories-wordpress-plugin/package.json ======================= <filename>data/wpackagist-plugin/ho/horizontal-full-categories-wordpress-plugin/package.json {"packages":{"wpackagist-plugin\/horizontal-full-categories-wordpress-plugin":{"1.2b":{"name":"wpackagist-plugin\/horizontal-full-categories-wordpress-plugin","version":"1.2b","version_normalized":"1.2.0.0-beta","uid":167379,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/horizontal-full-categories-wordpress-plugin.zip?timestamp=1362108490"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/horizontal-full-categories-wordpress-plugin\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/horizontal-full-categories-wordpress-plugin\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.2":{"name":"wpackagist-plugin\/horizontal-full-categories-wordpress-plugin","version":"1.2","version_normalized":"1.2.0.0","uid":167380,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/horizontal-full-categories-wordpress-plugin.1.2.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/horizontal-full-categories-wordpress-plugin\/","reference":"tags\/1.2"},"homepage":"https:\/\/wordpress.org\/plugins\/horizontal-full-categories-wordpress-plugin\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/horizontal-full-categories-wordpress-plugin","version":"dev-trunk","version_normalized":"9999999-dev","uid":167381,"time":"2013-03-01 03:28:10","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/horizontal-full-categories-wordpress-plugin.zip?timestamp=1362108490"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/horizontal-full-categories-wordpress-plugin\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/horizontal-full-categories-wordpress-plugin\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/cc/ccavenue-payment-gateway-woocommerce/package.json ======================= <filename>data/wpackagist-plugin/cc/ccavenue-payment-gateway-woocommerce/package.json {"packages":{"wpackagist-plugin\/ccavenue-payment-gateway-woocommerce":{"1.0":{"name":"wpackagist-plugin\/ccavenue-payment-gateway-woocommerce","version":"1.0","version_normalized":"1.0.0.0","uid":63961,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/ccavenue-payment-gateway-woocommerce.1.0.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/ccavenue-payment-gateway-woocommerce\/","reference":"tags\/1.0"},"homepage":"https:\/\/wordpress.org\/plugins\/ccavenue-payment-gateway-woocommerce\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.1":{"name":"wpackagist-plugin\/ccavenue-payment-gateway-woocommerce","version":"1.1","version_normalized":"1.1.0.0","uid":63962,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/ccavenue-payment-gateway-woocommerce.1.1.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/ccavenue-payment-gateway-woocommerce\/","reference":"tags\/1.1"},"homepage":"https:\/\/wordpress.org\/plugins\/ccavenue-payment-gateway-woocommerce\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.2":{"name":"wpackagist-plugin\/ccavenue-payment-gateway-woocommerce","version":"1.2","version_normalized":"1.2.0.0","uid":63963,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/ccavenue-payment-gateway-woocommerce.1.2.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/ccavenue-payment-gateway-woocommerce\/","reference":"tags\/1.2"},"homepage":"https:\/\/wordpress.org\/plugins\/ccavenue-payment-gateway-woocommerce\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.2.1":{"name":"wpackagist-plugin\/ccavenue-payment-gateway-woocommerce","version":"1.2.1","version_normalized":"1.2.1.0","uid":63964,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/ccavenue-payment-gateway-woocommerce.1.2.1.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/ccavenue-payment-gateway-woocommerce\/","reference":"tags\/1.2.1"},"homepage":"https:\/\/wordpress.org\/plugins\/ccavenue-payment-gateway-woocommerce\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.2.2":{"name":"wpackagist-plugin\/ccavenue-payment-gateway-woocommerce","version":"1.2.2","version_normalized":"1.2.2.0","uid":63965,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/ccavenue-payment-gateway-woocommerce.1.2.2.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/ccavenue-payment-gateway-woocommerce\/","reference":"tags\/1.2.2"},"homepage":"https:\/\/wordpress.org\/plugins\/ccavenue-payment-gateway-woocommerce\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.2.3":{"name":"wpackagist-plugin\/ccavenue-payment-gateway-woocommerce","version":"1.2.3","version_normalized":"1.2.3.0","uid":63966,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/ccavenue-payment-gateway-woocommerce.1.2.3.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/ccavenue-payment-gateway-woocommerce\/","reference":"tags\/1.2.3"},"homepage":"https:\/\/wordpress.org\/plugins\/ccavenue-payment-gateway-woocommerce\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"1.2.4":{"name":"wpackagist-plugin\/ccavenue-payment-gateway-woocommerce","version":"1.2.4","version_normalized":"1.2.4.0","uid":63967,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/ccavenue-payment-gateway-woocommerce.1.2.4.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/ccavenue-payment-gateway-woocommerce\/","reference":"tags\/1.2.4"},"homepage":"https:\/\/wordpress.org\/plugins\/ccavenue-payment-gateway-woocommerce\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/ccavenue-payment-gateway-woocommerce","version":"dev-trunk","version_normalized":"9999999-dev","uid":63968,"time":"2014-03-19 10:48:47","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/ccavenue-payment-gateway-woocommerce.zip?timestamp=1395226127"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/ccavenue-payment-gateway-woocommerce\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/ccavenue-payment-gateway-woocommerce\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/cu/custom-field-images/package.json ======================= {"packages":{"wpackagist-plugin\/custom-field-images":{"1.9.2":{"name":"wpackagist-plugin\/custom-field-images","version":"1.9.2","version_normalized":"1.9.2.0","uid":89626,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/custom-field-images.1.9.2.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/custom-field-images\/","reference":"tags\/1.9.2"},"homepage":"https:\/\/wordpress.org\/plugins\/custom-field-images\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"2.0.0.1":{"name":"wpackagist-plugin\/custom-field-images","version":"2.0.0.1","version_normalized":"2.0.0.1","uid":89627,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/custom-field-images.2.0.0.1.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/custom-field-images\/","reference":"tags\/2.0.0.1"},"homepage":"https:\/\/wordpress.org\/plugins\/custom-field-images\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"2.2.3":{"name":"wpackagist-plugin\/custom-field-images","version":"2.2.3","version_normalized":"2.2.3.0","uid":89628,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/custom-field-images.2.2.3.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/custom-field-images\/","reference":"tags\/2.2.3"},"homepage":"https:\/\/wordpress.org\/plugins\/custom-field-images\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/custom-field-images","version":"dev-trunk","version_normalized":"9999999-dev","uid":89629,"time":"2010-08-29 22:53:36","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/custom-field-images.zip?timestamp=1283122416"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/custom-field-images\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/custom-field-images\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-theme/ch/cherry-blossom/package.json ======================= <filename>data/wpackagist-theme/ch/cherry-blossom/package.json {"packages":{"wpackagist-theme\/cherry-blossom":{"1.0":{"name":"wpackagist-theme\/cherry-blossom","version":"1.0","version_normalized":"1.0.0.0","uid":67022,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/cherry-blossom.1.0.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/cherry-blossom\/","reference":"1.0"},"homepage":"https:\/\/wordpress.org\/themes\/cherry-blossom\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.0.1":{"name":"wpackagist-theme\/cherry-blossom","version":"1.0.1","version_normalized":"1.0.1.0","uid":67023,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/cherry-blossom.1.0.1.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/cherry-blossom\/","reference":"1.0.1"},"homepage":"https:\/\/wordpress.org\/themes\/cherry-blossom\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.0.2":{"name":"wpackagist-theme\/cherry-blossom","version":"1.0.2","version_normalized":"1.0.2.0","uid":67024,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/cherry-blossom.1.0.2.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/cherry-blossom\/","reference":"1.0.2"},"homepage":"https:\/\/wordpress.org\/themes\/cherry-blossom\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.1":{"name":"wpackagist-theme\/cherry-blossom","version":"1.1","version_normalized":"1.1.0.0","uid":67025,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/cherry-blossom.1.1.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/cherry-blossom\/","reference":"1.1"},"homepage":"https:\/\/wordpress.org\/themes\/cherry-blossom\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.1.1":{"name":"wpackagist-theme\/cherry-blossom","version":"1.1.1","version_normalized":"1.1.1.0","uid":67026,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/cherry-blossom.1.1.1.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/cherry-blossom\/","reference":"1.1.1"},"homepage":"https:\/\/wordpress.org\/themes\/cherry-blossom\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.2":{"name":"wpackagist-theme\/cherry-blossom","version":"1.2","version_normalized":"1.2.0.0","uid":67027,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/cherry-blossom.1.2.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/cherry-blossom\/","reference":"1.2"},"homepage":"https:\/\/wordpress.org\/themes\/cherry-blossom\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.2.1":{"name":"wpackagist-theme\/cherry-blossom","version":"1.2.1","version_normalized":"1.2.1.0","uid":67028,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/cherry-blossom.1.2.1.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/cherry-blossom\/","reference":"1.2.1"},"homepage":"https:\/\/wordpress.org\/themes\/cherry-blossom\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"1.2.2":{"name":"wpackagist-theme\/cherry-blossom","version":"1.2.2","version_normalized":"1.2.2.0","uid":67029,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/cherry-blossom.1.2.2.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/cherry-blossom\/","reference":"1.2.2"},"homepage":"https:\/\/wordpress.org\/themes\/cherry-blossom\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"}}}} ======================= File: data/wpackagist-plugin/wp/wp-author-logo-front-end/package.json ======================= {"packages":{"wpackagist-plugin\/wp-author-logo-front-end":{"0.1.0":{"name":"wpackagist-plugin\/wp-author-logo-front-end","version":"0.1.0","version_normalized":"0.1.0.0","uid":407034,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/wp-author-logo-front-end.0.1.0.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/wp-author-logo-front-end\/","reference":"tags\/0.1.0"},"homepage":"https:\/\/wordpress.org\/plugins\/wp-author-logo-front-end\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.3.0":{"name":"wpackagist-plugin\/wp-author-logo-front-end","version":"0.3.0","version_normalized":"0.3.0.0","uid":407035,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/wp-author-logo-front-end.0.3.0.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/wp-author-logo-front-end\/","reference":"tags\/0.3.0"},"homepage":"https:\/\/wordpress.org\/plugins\/wp-author-logo-front-end\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.3.5":{"name":"wpackagist-plugin\/wp-author-logo-front-end","version":"0.3.5","version_normalized":"0.3.5.0","uid":407036,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/wp-author-logo-front-end.0.3.5.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/wp-author-logo-front-end\/","reference":"tags\/0.3.5"},"homepage":"https:\/\/wordpress.org\/plugins\/wp-author-logo-front-end\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/wp-author-logo-front-end","version":"dev-trunk","version_normalized":"9999999-dev","uid":407037,"time":"2011-06-13 16:06:21","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/wp-author-logo-front-end.zip?timestamp=1307981181"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/wp-author-logo-front-end\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/wp-author-logo-front-end\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/a-/a-to-z-category-navigation-widget/package.json ======================= {"packages":{"wpackagist-plugin\/a-to-z-category-navigation-widget":{"1.0":{"name":"wpackagist-plugin\/a-to-z-category-navigation-widget","version":"1.0","version_normalized":"1.0.0.0","uid":1999,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/a-to-z-category-navigation-widget.zip?timestamp=1311145035"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/a-to-z-category-navigation-widget\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/a-to-z-category-navigation-widget\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/a-to-z-category-navigation-widget","version":"dev-trunk","version_normalized":"9999999-dev","uid":2000,"time":"2011-07-20 06:57:15","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/a-to-z-category-navigation-widget.zip?timestamp=1311145035"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/a-to-z-category-navigation-widget\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/a-to-z-category-navigation-widget\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/fu/full-comments-on-dashboard/package.json ======================= {"packages":{"wpackagist-plugin\/full-comments-on-dashboard":{"1.0.3":{"name":"wpackagist-plugin\/full-comments-on-dashboard","version":"1.0.3","version_normalized":"1.0.3.0","uid":144395,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/full-comments-on-dashboard.zip?timestamp=1347558894"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/full-comments-on-dashboard\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/full-comments-on-dashboard\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/full-comments-on-dashboard","version":"dev-trunk","version_normalized":"9999999-dev","uid":144396,"time":"2012-09-13 17:54:54","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/full-comments-on-dashboard.zip?timestamp=1347558894"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/full-comments-on-dashboard\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/full-comments-on-dashboard\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-theme/as/ascetica/package.json ======================= <reponame>wplib/wpackagist-requestor {"packages":{"wpackagist-theme\/ascetica":{"0.1.5":{"name":"wpackagist-theme\/ascetica","version":"0.1.5","version_normalized":"0.1.5.0","uid":27265,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/ascetica.0.1.5.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/ascetica\/","reference":"0.1.5"},"homepage":"https:\/\/wordpress.org\/themes\/ascetica\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"0.1.6":{"name":"wpackagist-theme\/ascetica","version":"0.1.6","version_normalized":"0.1.6.0","uid":27266,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/ascetica.0.1.6.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/ascetica\/","reference":"0.1.6"},"homepage":"https:\/\/wordpress.org\/themes\/ascetica\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"0.1.8":{"name":"wpackagist-theme\/ascetica","version":"0.1.8","version_normalized":"0.1.8.0","uid":27267,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/ascetica.0.1.8.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/ascetica\/","reference":"0.1.8"},"homepage":"https:\/\/wordpress.org\/themes\/ascetica\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"0.2.1":{"name":"wpackagist-theme\/ascetica","version":"0.2.1","version_normalized":"0.2.1.0","uid":27268,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/ascetica.0.2.1.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/ascetica\/","reference":"0.2.1"},"homepage":"https:\/\/wordpress.org\/themes\/ascetica\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"0.3":{"name":"wpackagist-theme\/ascetica","version":"0.3","version_normalized":"0.3.0.0","uid":27269,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/ascetica.0.3.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/ascetica\/","reference":"0.3"},"homepage":"https:\/\/wordpress.org\/themes\/ascetica\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"0.3.1":{"name":"wpackagist-theme\/ascetica","version":"0.3.1","version_normalized":"0.3.1.0","uid":27270,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/ascetica.0.3.1.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/ascetica\/","reference":"0.3.1"},"homepage":"https:\/\/wordpress.org\/themes\/ascetica\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"},"0.3.5":{"name":"wpackagist-theme\/ascetica","version":"0.3.5","version_normalized":"0.3.5.0","uid":27271,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/theme\/ascetica.0.3.5.zip"},"source":{"type":"svn","url":"https:\/\/themes.svn.wordpress.org\/ascetica\/","reference":"0.3.5"},"homepage":"https:\/\/wordpress.org\/themes\/ascetica\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-theme"}}}} ======================= File: data/wpackagist-plugin/pu/publishing-stats/package.json ======================= <reponame>wplib/wpackagist-requestor {"packages":{"wpackagist-plugin\/publishing-stats":{"0.1":{"name":"wpackagist-plugin\/publishing-stats","version":"0.1","version_normalized":"0.1.0.0","uid":273439,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/publishing-stats.0.1.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/publishing-stats\/","reference":"tags\/0.1"},"homepage":"https:\/\/wordpress.org\/plugins\/publishing-stats\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.2":{"name":"wpackagist-plugin\/publishing-stats","version":"0.2","version_normalized":"0.2.0.0","uid":273440,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/publishing-stats.0.2.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/publishing-stats\/","reference":"tags\/0.2"},"homepage":"https:\/\/wordpress.org\/plugins\/publishing-stats\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.3":{"name":"wpackagist-plugin\/publishing-stats","version":"0.3","version_normalized":"0.3.0.0","uid":273441,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/publishing-stats.0.3.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/publishing-stats\/","reference":"tags\/0.3"},"homepage":"https:\/\/wordpress.org\/plugins\/publishing-stats\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.4":{"name":"wpackagist-plugin\/publishing-stats","version":"0.4","version_normalized":"0.4.0.0","uid":273442,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/publishing-stats.0.4.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/publishing-stats\/","reference":"tags\/0.4"},"homepage":"https:\/\/wordpress.org\/plugins\/publishing-stats\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.5":{"name":"wpackagist-plugin\/publishing-stats","version":"0.5","version_normalized":"0.5.0.0","uid":273443,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/publishing-stats.0.5.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/publishing-stats\/","reference":"tags\/0.5"},"homepage":"https:\/\/wordpress.org\/plugins\/publishing-stats\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.6":{"name":"wpackagist-plugin\/publishing-stats","version":"0.6","version_normalized":"0.6.0.0","uid":273444,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/publishing-stats.0.6.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/publishing-stats\/","reference":"tags\/0.6"},"homepage":"https:\/\/wordpress.org\/plugins\/publishing-stats\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/publishing-stats","version":"dev-trunk","version_normalized":"9999999-dev","uid":273445,"time":"2014-11-24 14:44:54","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/publishing-stats.zip?timestamp=1416840294"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/publishing-stats\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/publishing-stats\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/ra/random-facts/package.json ======================= <gh_stars>1-10 {"packages":{"wpackagist-plugin\/random-facts":{"2":{"name":"wpackagist-plugin\/random-facts","version":2,"version_normalized":"2.0.0.0","uid":280296,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/random-facts.zip?timestamp=1255783818"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/random-facts\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/random-facts\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/random-facts","version":"dev-trunk","version_normalized":"9999999-dev","uid":280297,"time":"2009-10-17 12:50:18","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/random-facts.zip?timestamp=1255783818"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/random-facts\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/random-facts\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/si/simple-crm-buddypress-xprofile/package.json ======================= <gh_stars>1-10 {"packages":{"wpackagist-plugin\/simple-crm-buddypress-xprofile":{"0.1":{"name":"wpackagist-plugin\/simple-crm-buddypress-xprofile","version":"0.1","version_normalized":"0.1.0.0","uid":313966,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/simple-crm-buddypress-xprofile.0.1.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/simple-crm-buddypress-xprofile\/","reference":"tags\/0.1"},"homepage":"https:\/\/wordpress.org\/plugins\/simple-crm-buddypress-xprofile\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/simple-crm-buddypress-xprofile","version":"dev-trunk","version_normalized":"9999999-dev","uid":313967,"time":"2011-04-12 20:51:38","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/simple-crm-buddypress-xprofile.zip?timestamp=1302641498"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/simple-crm-buddypress-xprofile\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/simple-crm-buddypress-xprofile\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}} ======================= File: data/wpackagist-plugin/ne/network-copier/package.json ======================= {"packages":{"wpackagist-plugin\/network-copier":{"1.1":{"name":"wpackagist-plugin\/network-copier","version":"1.1","version_normalized":"1
1,525
/// </summary> [OutputType] public sealed class DetectorModelAssetPropertyTimestamp { /// <summary> /// The timestamp, in seconds, in the Unix epoch format. The valid range is between `1-31556889864403199`. You can also specify an expression. /// </summary> public readonly string? OffsetInNanos; /// <summary> /// The nanosecond offset converted from `timeInSeconds`. The valid range is between `0-999999999`. You can also specify an expression. /// </summary> public readonly string TimeInSeconds; [OutputConstructor] private DetectorModelAssetPropertyTimestamp( string? offsetInNanos, string timeInSeconds) { OffsetInNanos = offsetInNanos; TimeInSeconds = timeInSeconds; } } } ======================= File: sdk/dotnet/AppMesh/Inputs/VirtualNodeOutlierDetectionArgs.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.AppMesh.Inputs { public sealed class VirtualNodeOutlierDetectionArgs : Pulumi.ResourceArgs { [Input("baseEjectionDuration", required: true)] public Input<Inputs.VirtualNodeDurationArgs> BaseEjectionDuration { get; set; } = null!; [Input("interval", required: true)] public Input<Inputs.VirtualNodeDurationArgs> Interval { get; set; } = null!; [Input("maxEjectionPercent", required: true)] public Input<int> MaxEjectionPercent { get; set; } = null!; [Input("maxServerErrors", required: true)] public Input<int> MaxServerErrors { get; set; } = null!; public VirtualNodeOutlierDetectionArgs() { } } } ======================= File: sdk/dotnet/DataBrew/Inputs/DatasetPathParameterArgs.cs ======================= <filename>sdk/dotnet/DataBrew/Inputs/DatasetPathParameterArgs.cs // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.DataBrew.Inputs { /// <summary> /// A key-value pair to associate dataset parameter name with its definition. /// </summary> public sealed class DatasetPathParameterArgs : Pulumi.ResourceArgs { [Input("datasetParameter", required: true)] public Input<Inputs.DatasetParameterArgs> DatasetParameter { get; set; } = null!; [Input("pathParameterName", required: true)] public Input<string> PathParameterName { get; set; } = null!; public DatasetPathParameterArgs() { } } } ======================= File: sdk/dotnet/IoTWireless/Inputs/WirelessGatewayLoRaWANGatewayArgs.cs ======================= <reponame>AaronFriel/pulumi-aws-native // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.IoTWireless.Inputs { public sealed class WirelessGatewayLoRaWANGatewayArgs : Pulumi.ResourceArgs { [Input("gatewayEui", required: true)] public Input<string> GatewayEui { get; set; } = null!; [Input("rfRegion", required: true)] public Input<string> RfRegion { get; set; } = null!; public WirelessGatewayLoRaWANGatewayArgs() { } } } ======================= File: sdk/dotnet/WAFv2/Outputs/WebACLByteMatchStatement.cs ======================= <filename>sdk/dotnet/WAFv2/Outputs/WebACLByteMatchStatement.cs // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.WAFv2.Outputs { /// <summary> /// Byte Match statement. /// </summary> [OutputType] public sealed class WebACLByteMatchStatement { public readonly Outputs.WebACLFieldToMatch FieldToMatch; public readonly Pulumi.AwsNative.WAFv2.WebACLPositionalConstraint PositionalConstraint; public readonly string? SearchString; public readonly string? SearchStringBase64; public readonly ImmutableArray<Outputs.WebACLTextTransformation> TextTransformations; [OutputConstructor] private WebACLByteMatchStatement( Outputs.WebACLFieldToMatch fieldToMatch, Pulumi.AwsNative.WAFv2.WebACLPositionalConstraint positionalConstraint, string? searchString, string? searchStringBase64, ImmutableArray<Outputs.WebACLTextTransformation> textTransformations) { FieldToMatch = fieldToMatch; PositionalConstraint = positionalConstraint; SearchString = searchString; SearchStringBase64 = searchStringBase64; TextTransformations = textTransformations; } } } ======================= File: sdk/dotnet/SSMIncidents/Inputs/ResponsePlanChatChannelArgs.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.SSMIncidents.Inputs { /// <summary> /// The chat channel configuration. /// </summary> public sealed class ResponsePlanChatChannelArgs : Pulumi.ResourceArgs { [Input("chatbotSns")] private InputList<string>? _chatbotSns; public InputList<string> ChatbotSns { get => _chatbotSns?? (_chatbotSns = new InputList<string>()); set => _chatbotSns = value; } public ResponsePlanChatChannelArgs() { } } } ======================= File: sdk/dotnet/IoT/Outputs/DomainConfigurationAuthorizerConfig.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.IoT.Outputs { [OutputType] public sealed class DomainConfigurationAuthorizerConfig { public readonly bool? AllowAuthorizerOverride; public readonly string? DefaultAuthorizerName; [OutputConstructor] private DomainConfigurationAuthorizerConfig( bool? allowAuthorizerOverride, string? defaultAuthorizerName) { AllowAuthorizerOverride = allowAuthorizerOverride; DefaultAuthorizerName = defaultAuthorizerName; } } } ======================= File: sdk/dotnet/AppMesh/Outputs/VirtualGatewayListenerTlsFileCertificate.cs ======================= <reponame>AaronFriel/pulumi-aws-native // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.AppMesh.Outputs { [OutputType] public sealed class VirtualGatewayListenerTlsFileCertificate { public readonly string CertificateChain; public readonly string PrivateKey; [OutputConstructor] private VirtualGatewayListenerTlsFileCertificate( string certificateChain, string privateKey) { CertificateChain = certificateChain; PrivateKey = privateKey; } } } ======================= File: sdk/dotnet/ApplicationInsights/Inputs/ApplicationComponentMonitoringSettingArgs.cs ======================= <gh_stars>10-100 // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.ApplicationInsights.Inputs { /// <summary> /// The monitoring setting of the component. /// </summary> public sealed class ApplicationComponentMonitoringSettingArgs : Pulumi.ResourceArgs { /// <summary> /// The ARN of the compnonent. /// </summary> [Input("componentARN")] public Input<string>? ComponentARN { get; set; } /// <summary> /// The component monitoring configuration mode. /// </summary> [Input("componentConfigurationMode", required: true)] public Input<Pulumi.AwsNative.ApplicationInsights.ApplicationComponentMonitoringSettingComponentConfigurationMode> ComponentConfigurationMode { get; set; } = null!; /// <summary> /// The name of the component. /// </summary> [Input("componentName")] public Input<string>? ComponentName { get; set; } /// <summary> /// The monitoring configuration of the component. /// </summary> [Input("customComponentConfiguration")] public Input<Inputs.ApplicationComponentConfigurationArgs>? CustomComponentConfiguration { get; set; } /// <summary> /// The overwritten settings on default component monitoring configuration. /// </summary> [Input("defaultOverwriteComponentConfiguration")] public Input<Inputs.ApplicationComponentConfigurationArgs>? DefaultOverwriteComponentConfiguration { get; set; } /// <summary> /// The tier of the application component. /// </summary> [Input("tier", required: true)] public Input<string> Tier { get; set; } = null!; public ApplicationComponentMonitoringSettingArgs() { } } } ======================= File: sdk/dotnet/Connect/Inputs/QuickConnectConfigArgs.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.Connect.Inputs { /// <summary> /// Configuration settings for the quick connect. /// </summary> public sealed class QuickConnectConfigArgs : Pulumi.ResourceArgs { [Input("phoneConfig")] public Input<Inputs.QuickConnectPhoneNumberQuickConnectConfigArgs>? PhoneConfig { get; set; } [Input("queueConfig")] public Input<Inputs.QuickConnectQueueQuickConnectConfigArgs>? QueueConfig { get; set; } [Input("quickConnectType", required: true)] public Input<Pulumi.AwsNative.Connect.QuickConnectType> QuickConnectType { get; set; } = null!; [Input("userConfig")] public Input<Inputs.QuickConnectUserQuickConnectConfigArgs>? UserConfig { get; set; } public QuickConnectConfigArgs() { } } } ======================= File: sdk/dotnet/MediaPackage/Inputs/OriginEndpointMssPackageArgs.cs ======================= <gh_stars>10-100 // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.MediaPackage.Inputs { /// <summary> /// A Microsoft Smooth Streaming (MSS) packaging configuration. /// </summary> public sealed class OriginEndpointMssPackageArgs : Pulumi.ResourceArgs { [Input("encryption")] public Input<Inputs.OriginEndpointMssEncryptionArgs>? Encryption { get; set; } /// <summary> /// The time window (in seconds) contained in each manifest. /// </summary> [Input("manifestWindowSeconds")] public Input<int>? ManifestWindowSeconds { get; set; } /// <summary> /// The duration (in seconds) of each segment. /// </summary> [Input("segmentDurationSeconds")] public Input<int>? SegmentDurationSeconds { get; set; } [Input("streamSelection")] public Input<Inputs.OriginEndpointStreamSelectionArgs>? StreamSelection { get; set; } public OriginEndpointMssPackageArgs() { } } } ======================= File: sdk/dotnet/NetworkFirewall/Inputs/RuleGroupRuleVariablesArgs.cs ======================= <reponame>AaronFriel/pulumi-aws-native // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.NetworkFirewall.Inputs { public sealed class RuleGroupRuleVariablesArgs : Pulumi.ResourceArgs { [Input("iPSets")] public Input<object>? IPSets { get; set; } [Input("portSets")] public Input<object>? PortSets { get; set; } public RuleGroupRuleVariablesArgs() { } } } ======================= File: sdk/dotnet/IoTSiteWise/Outputs/AccessPolicyResource.cs ======================= <reponame>AaronFriel/pulumi-aws-native<filename>sdk/dotnet/IoTSiteWise/Outputs/AccessPolicyResource.cs // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.IoTSiteWise.Outputs { /// <summary> /// The AWS IoT SiteWise Monitor resource for this access policy. Choose either portal or project but not both. /// </summary> [OutputType] public sealed class AccessPolicyResource { public readonly Outputs.AccessPolicyPortal? Portal; public readonly Outputs.AccessPolicyProject? Project; [OutputConstructor] private AccessPolicyResource( Outputs.AccessPolicyPortal? portal, Outputs.AccessPolicyProject? project) { Portal = portal; Project = project; } } } ======================= File: sdk/dotnet/ImageBuilder/Outputs/ImageRecipeAdditionalInstanceConfiguration.cs ======================= <gh_stars>10-100 // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.ImageBuilder.Outputs { /// <summary> /// Specify additional settings and launch scripts for your build instances. /// </summary> [OutputType] public sealed class ImageRecipeAdditionalInstanceConfiguration { /// <summary> /// Contains settings for the SSM agent on your build instance. /// </summary> public readonly Outputs.ImageRecipeSystemsManagerAgent? SystemsManagerAgent; /// <summary> /// Use this property to provide commands or a command script to run when you launch your build instance. /// </summary> public readonly string? UserDataOverride; [OutputConstructor] private ImageRecipeAdditionalInstanceConfiguration( Outputs.ImageRecipeSystemsManagerAgent? systemsManagerAgent, string? userDataOverride) { SystemsManagerAgent = systemsManagerAgent; UserDataOverride = userDataOverride; } } } ======================= File: sdk/dotnet/EKS/Outputs/ClusterLogging.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.EKS.Outputs { /// <summary> /// Enable exporting the Kubernetes control plane logs for your cluster to CloudWatch Logs based on log types. By default, cluster control plane logs aren't exported to CloudWatch Logs. /// </summary> [OutputType] public sealed class ClusterLogging { /// <summary> /// The cluster control plane logging configuration for your cluster. /// </summary> public readonly Outputs.ClusterLogging? ClusterLoggingValue; [OutputConstructor] private ClusterLogging(Outputs.ClusterLogging? clusterLogging) { ClusterLoggingValue = clusterLogging; } } } ======================= File: sdk/dotnet/AppMesh/Inputs/RouteGrpcRouteMatchArgs.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.AppMesh.Inputs { public sealed class RouteGrpcRouteMatchArgs : Pulumi.ResourceArgs { [Input("metadata")] private InputList<Inputs.RouteGrpcRouteMetadataArgs>? _metadata; public InputList<Inputs.RouteGrpcRouteMetadataArgs> Metadata { get => _metadata?? (_metadata = new InputList<Inputs.RouteGrpcRouteMetadataArgs>()); set => _metadata = value; } [Input("methodName")] public Input<string>? MethodName { get; set; } [Input("serviceName")] public Input<string>? ServiceName { get; set; } public RouteGrpcRouteMatchArgs() { } } } ======================= File: sdk/dotnet/AppMesh/Outputs/GatewayRouteGrpcGatewayRouteMatch.cs ======================= <reponame>AaronFriel/pulumi-aws-native<gh_stars>10-100 // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.AppMesh.Outputs { [OutputType] public sealed class GatewayRouteGrpcGatewayRouteMatch { public readonly Outputs.GatewayRouteHostnameMatch? Hostname; public readonly ImmutableArray<Outputs.GatewayRouteGrpcGatewayRouteMetadata> Metadata; public readonly string? ServiceName; [OutputConstructor] private GatewayRouteGrpcGatewayRouteMatch( Outputs.GatewayRouteHostnameMatch? hostname, ImmutableArray<Outputs.GatewayRouteGrpcGatewayRouteMetadata> metadata, string? serviceName) { Hostname = hostname; Metadata = metadata; ServiceName = serviceName; } } } ======================= File: sdk/dotnet/Lambda/Outputs/FunctionCode.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.Lambda.Outputs { [OutputType] public sealed class FunctionCode { /// <summary> /// ImageUri. /// </summary> public readonly string? ImageUri; /// <summary> /// An Amazon S3 bucket in the same AWS Region as your function. The bucket can be in a different AWS account. /// </summary> public readonly string? S3Bucket; /// <summary> /// The Amazon S3 key of the deployment package. /// </summary> public readonly string? S3Key; /// <summary> /// For versioned objects, the version of the deployment package object to use. /// </summary> public readonly string? S3ObjectVersion; /// <summary> /// The source code of your Lambda function. If you include your function source inline with this parameter, AWS CloudFormation places it in a file named index and zips it to create a deployment package.. /// </summary> public readonly string? ZipFile; [OutputConstructor] private FunctionCode( string? imageUri, string? s3Bucket, string? s3Key, string? s3ObjectVersion, string? zipFile) { ImageUri = imageUri; S3Bucket = s3Bucket; S3Key = s3Key; S3ObjectVersion = s3ObjectVersion; ZipFile = zipFile; } } } ======================= File: sdk/dotnet/AppFlow/Outputs/ConnectorProfileProperties.cs ======================= <reponame>AaronFriel/pulumi-aws-native // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.AppFlow.Outputs { /// <summary> /// Connector specific properties needed to create connector profile - currently not needed for Amplitude, Trendmicro, Googleanalytics and Singular /// </summary> [OutputType] public sealed class ConnectorProfileProperties { public readonly Outputs.ConnectorProfileDatadogConnectorProfileProperties? Datadog; public readonly Outputs.ConnectorProfileDynatraceConnectorProfileProperties? Dynatrace; public readonly Outputs.ConnectorProfileInforNexusConnectorProfileProperties? InforNexus; public readonly Outputs.ConnectorProfileMarketoConnectorProfileProperties? Marketo; public readonly Outputs.ConnectorProfileRedshiftConnectorProfileProperties? Redshift; public readonly Outputs.ConnectorProfileSAPODataConnectorProfileProperties? SAPOData; public readonly Outputs.ConnectorProfileSalesforceConnectorProfileProperties? Salesforce; public readonly Outputs.ConnectorProfileServiceNowConnectorProfileProperties? ServiceNow; public readonly Outputs.ConnectorProfileSlackConnectorProfileProperties? Slack; public readonly Outputs.ConnectorProfileSnowflakeConnectorProfileProperties? Snowflake; public readonly Outputs.ConnectorProfileVeevaConnectorProfileProperties? Veeva; public readonly Outputs.ConnectorProfileZendeskConnectorProfileProperties? Zendesk; [OutputConstructor] private ConnectorProfileProperties( Outputs.ConnectorProfileDatadogConnectorProfileProperties? datadog, Outputs.ConnectorProfileDynatraceConnectorProfileProperties? dynatrace, Outputs.ConnectorProfileInforNexusConnectorProfileProperties? inforNexus, Outputs.ConnectorProfileMarketoConnectorProfileProperties? marketo, Outputs.ConnectorProfileRedshiftConnectorProfileProperties? redshift, Outputs.ConnectorProfileSAPODataConnectorProfileProperties? sAPOData, Outputs.ConnectorProfileSalesforceConnectorProfileProperties? salesforce, Outputs.ConnectorProfileServiceNowConnectorProfileProperties? serviceNow, Outputs.ConnectorProfileSlackConnectorProfileProperties? slack, Outputs.ConnectorProfileSnowflakeConnectorProfileProperties? snowflake, Outputs.ConnectorProfileVeevaConnectorProfileProperties? veeva, Outputs.ConnectorProfileZendeskConnectorProfileProperties? zendesk) { Datadog = datadog; Dynatrace = dynatrace; InforNexus = inforNexus; Marketo = marketo; Redshift = redshift; SAPOData = sAPOData; Salesforce = salesforce; ServiceNow = serviceNow; Slack = slack; Snowflake = snowflake; Veeva = veeva; Zendesk = zendesk; } } } ======================= File: sdk/dotnet/IoT/Outputs/TopicRuleSigV4Authorization.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.IoT.Outputs { [OutputType] public sealed class TopicRuleSigV4Authorization { public readonly string RoleArn; public readonly string ServiceName; public readonly string SigningRegion; [OutputConstructor] private TopicRuleSigV4Authorization( string roleArn, string serviceName, string signingRegion) { RoleArn = roleArn; ServiceName = serviceName; SigningRegion = signingRegion; } } } ======================= File: sdk/dotnet/CodePipeline/Inputs/PipelineActionTypeIdArgs.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.CodePipeline.Inputs { public sealed class PipelineActionTypeIdArgs : Pulumi.ResourceArgs { [Input("category", required: true)] public Input<string> Category { get; set; } = null!; [Input("owner", required: true)] public Input<string> Owner { get; set; } = null!; [Input("provider", required: true)] public Input<string> Provider { get; set; } = null!; [Input("version", required: true)] public Input<string> Version { get; set; } = null!; public PipelineActionTypeIdArgs() { } } } ======================= File: sdk/dotnet/AppMesh/Outputs/VirtualGatewayHealthCheckPolicy.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.AppMesh.Outputs { [OutputType] public sealed class VirtualGatewayHealthCheckPolicy { public readonly int HealthyThreshold; public readonly int IntervalMillis; public readonly string? Path; public readonly int? Port; public readonly string Protocol; public readonly int TimeoutMillis; public readonly int UnhealthyThreshold; [OutputConstructor] private VirtualGatewayHealthCheckPolicy( int healthyThreshold, int intervalMillis, string? path, int? port, string protocol, int timeoutMillis, int unhealthyThreshold) { HealthyThreshold = healthyThreshold; IntervalMillis = intervalMillis; Path = path; Port = port; Protocol = protocol; TimeoutMillis = timeoutMillis; UnhealthyThreshold = unhealthyThreshold; } } } ======================= File: sdk/dotnet/MediaConnect/Outputs/FlowSourceEncryption.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.MediaConnect.Outputs { /// <summary> /// Information about the encryption of the flow. /// </summary> [OutputType] public sealed class FlowSourceEncryption { /// <summary> /// The type of algorithm that is used for the encryption (such as aes128, aes192, or aes256). /// </summary> public readonly Pulumi.AwsNative.MediaConnect.FlowSourceEncryptionAlgorithm Algorithm; /// <summary> /// A 128-bit, 16-byte hex value represented by a 32-character string, to be used with the key for encrypting content. This parameter is not valid for static key encryption. /// </summary> public readonly string? ConstantInitializationVector; /// <summary> /// The value of one of the devices that you configured with your digital rights management (DRM) platform key provider. This parameter is required for SPEKE encryption and is not valid for static key encryption. /// </summary> public readonly string? DeviceId; /// <summary> /// The type of key that is used for the encryption. If no keyType is provided, the service will use the default setting (static-key). /// </summary> public readonly Pulumi.AwsNative.MediaConnect.FlowSourceEncryptionKeyType? KeyType; /// <summary> /// The AWS Region that the API Gateway proxy endpoint was created in. This parameter is required for SPEKE encryption and is not valid for static key encryption. /// </summary> public readonly string? Region; /// <summary> /// An identifier for the content. The service sends this value to the key server to identify the current endpoint. The resource ID is also known as the content ID. This parameter is required for SPEKE encryption and is not valid for static key encryption. /// </summary> public readonly string? ResourceId; /// <summary> /// The ARN of the role that you created during setup (when you set up AWS Elemental MediaConnect as a trusted entity). /// </summary> public readonly string RoleArn; /// <summary> /// The ARN of the secret that you created in AWS Secrets Manager to store the encryption key. This parameter is required for static key encryption and is not valid for SPEKE encryption. /// </summary> public readonly string? SecretArn; /// <summary> /// The URL from the API Gateway proxy that you set up to talk to your key server. This parameter is required for SPEKE encryption and is not valid for static key encryption. /// </summary> public readonly string? Url; [OutputConstructor] private FlowSourceEncryption( Pulumi.AwsNative.MediaConnect.FlowSourceEncryptionAlgorithm algorithm, string? constantInitializationVector, string? deviceId, Pulumi.AwsNative.MediaConnect.FlowSourceEncryptionKeyType? keyType, string? region, string? resourceId, string roleArn, string? secretArn, string? url) { Algorithm = algorithm; ConstantInitializationVector = constantInitializationVector; DeviceId = deviceId; KeyType = keyType; Region = region; ResourceId = resourceId; RoleArn = roleArn; SecretArn = secretArn; Url = url; } } } ======================= File: sdk/dotnet/IoT/Inputs/JobTemplateExponentialRolloutRateArgs.cs ======================= <reponame>AaronFriel/pulumi-aws-native<gh_stars>10-100 // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.IoT.Inputs { /// <summary> /// Allows you to create an exponential rate of rollout for a job. /// </summary> public sealed class JobTemplateExponentialRolloutRateArgs : Pulumi.ResourceArgs { /// <summary> /// The minimum number of things that will be notified of a pending job, per minute at the start of job rollout. This parameter allows you to define the initial rate of rollout. /// </summary> [Input("baseRatePerMinute", required: true)] public Input<int> BaseRatePerMinute { get; set; } = null!; /// <summary> /// The exponential factor to increase the rate of rollout for a job. /// </summary> [Input("incrementFactor", required: true)] public Input<double> IncrementFactor { get; set; } = null!; /// <summary> /// The criteria to initiate the increase in rate of rollout for a job. /// </summary> [Input("rateIncreaseCriteria", required: true)] public Input<Inputs.JobTemplateRateIncreaseCriteriaArgs> RateIncreaseCriteria { get; set; } = null!; public JobTemplateExponentialRolloutRateArgs() { } } } ======================= File: sdk/dotnet/WAFv2/Outputs/LoggingConfigurationFieldToMatch.cs ======================= <filename>sdk/dotnet/WAFv2/Outputs/LoggingConfigurationFieldToMatch.cs // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.WAFv2.Outputs { /// <summary> /// A key-value pair to associate with a resource. /// </summary> [OutputType] public sealed class LoggingConfigurationFieldToMatch { /// <summary> /// Inspect the request body as JSON. The request body immediately follows the request headers. This is the part of a request that contains any additional data that you want to send to your web server as the HTTP request body, such as data from a form. /// </summary> public readonly Outputs.LoggingConfigurationFieldToMatchJsonBodyProperties? JsonBody; /// <summary> /// Inspect the HTTP method. The method indicates the type of operation that the request is asking the origin to perform. /// </summary> public readonly object? Method; /// <summary> /// Inspect the query string. This is the part of a URL that appears after a? character, if any. /// </summary> public readonly object? QueryString; /// <summary> /// Inspect a single header. Provide the name of the header to inspect, for example, User-Agent or Referer. This setting isn't case sensitive. /// </summary> public readonly Outputs.LoggingConfigurationFieldToMatchSingleHeaderProperties? SingleHeader; /// <summary> /// Inspect the request URI path. This is the part of a web request that identifies a resource, for example, /images/daily-ad.jpg. /// </summary> public readonly object? UriPath; [OutputConstructor] private LoggingConfigurationFieldToMatch( Outputs.LoggingConfigurationFieldToMatchJsonBodyProperties? jsonBody, object? method, object? queryString, Outputs.LoggingConfigurationFieldToMatchSingleHeaderProperties? singleHeader, object? uriPath) { JsonBody = jsonBody; Method = method; QueryString = queryString; SingleHeader = singleHeader; UriPath = uriPath; } } } ======================= File: sdk/dotnet/GameLift/Inputs/FleetServerProcessArgs.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.GameLift.Inputs { /// <summary> /// A set of instructions for launching server processes on each instance in a fleet. Each instruction set identifies the location of the server executable, optional launch parameters, and the number of server processes with this configuration to maintain concurrently on the instance. Server process configurations make up a fleet's RuntimeConfiguration. /// </summary> public sealed class FleetServerProcessArgs : Pulumi.ResourceArgs { /// <summary> /// The number of server processes that use this configuration to run concurrently on an instance. /// </summary> [Input("concurrentExecutions", required: true)] public Input<int> ConcurrentExecutions { get; set; } = null!; /// <summary> /// The location of the server executable in a custom game build or the name of the Realtime script file that contains the Init() function. Game builds and Realtime scripts are installed on instances at the root: /// /// Windows (for custom game builds only): C:\game. Example: "C:\game\MyGame\server.exe" /// /// Linux: /local/game. Examples: "/local/game/MyGame/server.exe" or "/local/game/MyRealtimeScript.js" /// </summary> [Input("launchPath", required: true)] public Input<string> LaunchPath { get; set; } = null!; /// <summary> /// An optional list of parameters to pass to the server executable or Realtime script on launch. /// </summary> [Input("parameters")] public Input<string>? Parameters { get; set; } public FleetServerProcessArgs() { } } } ======================= File: sdk/dotnet/HealthLake/Inputs/FHIRDatastoreKmsEncryptionConfigArgs.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.HealthLake.Inputs { /// <summary> /// The customer-managed-key (CMK) used when creating a Data Store. If a customer owned key is not specified, an AWS owned key will be used for encryption. /// </summary> public sealed class FHIRDatastoreKmsEncryptionConfigArgs : Pulumi.ResourceArgs { /// <summary> /// The type of customer-managed-key (CMK) used for encryption. The two types of supported CMKs are customer owned CMKs and AWS owned CMKs. /// </summary> [Input("cmkType", required: true)] public Input<Pulumi.AwsNative.HealthLake.FHIRDatastoreKmsEncryptionConfigCmkType> CmkType { get; set; } = null!; /// <summary> /// The KMS encryption key id/alias used to encrypt the Data Store contents at rest. /// </summary> [Input("kmsKeyId")] public Input<string>? KmsKeyId { get; set; } public FHIRDatastoreKmsEncryptionConfigArgs() { } } } ======================= File: sdk/dotnet/WAFv2/Inputs/RuleGroupRateBasedStatementArgs.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.WAFv2.Inputs { public sealed class RuleGroupRateBasedStatementArgs : Pulumi.ResourceArgs { [Input("aggregateKeyType", required: true)] public Input<Pulumi.AwsNative.WAFv2.RuleGroupRateBasedStatementAggregateKeyType> AggregateKeyType { get; set; } = null!; [Input("forwardedIPConfig")] public Input<Inputs.RuleGroupForwardedIPConfigurationArgs>? ForwardedIPConfig { get; set; } [Input("limit", required: true)] public Input<int> Limit { get; set; } = null!; [Input("scopeDownStatement")] public Input<Inputs.RuleGroupStatementArgs>? ScopeDownStatement { get; set; } public RuleGroupRateBasedStatementArgs() { } } } ======================= File: sdk/dotnet/NetworkManager/Outputs/LinkBandwidth.cs ======================= <filename>sdk/dotnet/NetworkManager/Outputs/LinkBandwidth.cs // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.NetworkManager.Outputs { /// <summary> /// The bandwidth for the link. /// </summary> [OutputType] public sealed class LinkBandwidth { /// <summary> /// Download speed in Mbps. /// </summary> public readonly int? DownloadSpeed; /// <summary> /// Upload speed in Mbps. /// </summary> public readonly int? UploadSpeed; [OutputConstructor] private LinkBandwidth( int? downloadSpeed, int? uploadSpeed) { DownloadSpeed = downloadSpeed; UploadSpeed = uploadSpeed; } } } ======================= File: sdk/dotnet/AppSync/Outputs/DataSourceAuthorizationConfig.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.AppSync.Outputs { [OutputType] public sealed class DataSourceAuthorizationConfig { public readonly string AuthorizationType; public readonly Outputs.DataSourceAwsIamConfig? AwsIamConfig; [OutputConstructor] private DataSourceAuthorizationConfig( string authorizationType, Outputs.DataSourceAwsIamConfig? awsIamConfig) { AuthorizationType = authorizationType; AwsIamConfig = awsIamConfig; } } } ======================= File: sdk/dotnet/EC2/Inputs/SpotFleetTagSpecificationArgs.cs ======================= <reponame>AaronFriel/pulumi-aws-native // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.EC2.Inputs { public sealed class SpotFleetTagSpecificationArgs : Pulumi.ResourceArgs { [Input("resourceType")] public Input<Pulumi.AwsNative.EC2.SpotFleetTagSpecificationResourceType>? ResourceType { get; set; } [Input("tags")] private InputList<Inputs.SpotFleetTagArgs>? _tags; public InputList<Inputs.SpotFleetTagArgs> Tags { get => _tags?? (_tags = new InputList<Inputs.SpotFleetTagArgs>()); set => _tags = value; } public SpotFleetTagSpecificationArgs() { } } } ======================= File: sdk/dotnet/Timestream/Outputs/ScheduledQueryTimestreamConfiguration.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.Timestream.Outputs { /// <summary> /// Configuration needed to write data into the Timestream database and table. /// </summary> [OutputType] public sealed class ScheduledQueryTimestreamConfiguration { public readonly string DatabaseName; public readonly ImmutableArray<Outputs.ScheduledQueryDimensionMapping> DimensionMappings; public readonly string? MeasureNameColumn; public readonly ImmutableArray<Outputs.ScheduledQueryMixedMeasureMapping> MixedMeasureMappings; public readonly Outputs.ScheduledQueryMultiMeasureMappings? MultiMeasureMappings; public readonly string TableName; public readonly string TimeColumn; [OutputConstructor] private ScheduledQueryTimestreamConfiguration( string databaseName, ImmutableArray<Outputs.ScheduledQueryDimensionMapping> dimensionMappings, string? measureNameColumn, ImmutableArray<Outputs.ScheduledQueryMixedMeasureMapping> mixedMeasureMappings, Outputs.ScheduledQueryMultiMeasureMappings? multiMeasureMappings, string tableName, string timeColumn) { DatabaseName = databaseName; DimensionMappings = dimensionMappings; MeasureNameColumn = measureNameColumn; MixedMeasureMappings = mixedMeasureMappings; MultiMeasureMappings = multiMeasureMappings; TableName = tableName; TimeColumn = timeColumn; } } } ======================= File: sdk/dotnet/EFS/Inputs/AccessPointPosixUserArgs.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.EFS.Inputs { public sealed class AccessPointPosixUserArgs : Pulumi.ResourceArgs { /// <summary> /// The POSIX group ID used for all file system operations using this access point. /// </summary> [Input("gid", required: true)] public Input<string> Gid { get; set; } = null!; [Input("secondaryGids")] private InputList<string>? _secondaryGids; /// <summary> /// Secondary POSIX group IDs used for all file system operations using this access point. /// </summary> public InputList<string> SecondaryGids { get => _secondaryGids?? (_secondaryGids = new InputList<string>()); set => _secondaryGids = value; } /// <summary> /// The POSIX user ID used for all file system operations using this access point. /// </summary> [Input("uid", required: true)] public Input<string> Uid { get; set; } = null!; public AccessPointPosixUserArgs() { } } } ======================= File: sdk/dotnet/S3/Inputs/BucketDefaultRetentionArgs.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.S3.Inputs { /// <summary> /// The default retention period that you want to apply to new objects placed in the specified bucket. /// </summary> public sealed class BucketDefaultRetentionArgs : Pulumi.ResourceArgs { [Input("days")] public Input<int>? Days { get; set; } [Input("mode")] public Input<Pulumi.AwsNative.S3.BucketDefaultRetentionMode>? Mode { get; set; } [Input("years")] public Input<int>? Years { get; set; } public BucketDefaultRetentionArgs() { } } } ======================= File: sdk/dotnet/NimbleStudio/Outputs/StudioComponentConfiguration.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.NimbleStudio.Outputs { /// <summary> /// &lt;p&gt;The configuration of the studio component, based on component type.&lt;/p&gt; /// </summary> [OutputType] public sealed class StudioComponentConfiguration { public readonly Outputs.StudioComponentActiveDirectoryConfiguration? ActiveDirectoryConfiguration; public readonly Outputs.StudioComponentComputeFarmConfiguration? ComputeFarmConfiguration; public readonly Outputs.StudioComponentLicenseServiceConfiguration? LicenseServiceConfiguration; public readonly Outputs.StudioComponentSharedFileSystemConfiguration? SharedFileSystemConfiguration; [OutputConstructor] private StudioComponentConfiguration( Outputs.StudioComponentActiveDirectoryConfiguration? activeDirectoryConfiguration, Outputs.StudioComponentComputeFarmConfiguration? computeFarmConfiguration, Outputs.StudioComponentLicenseServiceConfiguration? licenseServiceConfiguration, Outputs.StudioComponentSharedFileSystemConfiguration? sharedFileSystemConfiguration) { ActiveDirectoryConfiguration = activeDirectoryConfiguration; ComputeFarmConfiguration = computeFarmConfiguration; LicenseServiceConfiguration = licenseServiceConfiguration; SharedFileSystemConfiguration = sharedFileSystemConfiguration; } } } ======================= File: sdk/dotnet/EFS/Inputs/AccessPointCreationInfoArgs.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.EFS.Inputs { public sealed class AccessPointCreationInfoArgs : Pulumi.ResourceArgs { /// <summary> /// Specifies the POSIX group ID to apply to the RootDirectory. Accepts values from 0 to 2^32 (4294967295). /// </summary> [Input("ownerGid", required: true)] public Input<string> OwnerGid { get; set; } = null!; /// <summary> /// Specifies the POSIX user ID to apply to the RootDirectory. Accepts values from 0 to 2^32 (4294967295). /// </summary> [Input("ownerUid", required: true)] public Input<string> OwnerUid { get; set; } = null!; /// <summary> /// Specifies the POSIX permissions to apply to the RootDirectory, in the format of an octal number representing the file's mode bits. /// </summary> [Input("permissions", required: true)] public Input<string> Permissions { get; set; } = null!; public AccessPointCreationInfoArgs() { } } } ======================= File: sdk/dotnet/Lex/Inputs/BotVoiceSettingsArgs.cs ======================= <filename>sdk/dotnet/Lex/Inputs/BotVoiceSettingsArgs.cs // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.Lex.Inputs { /// <summary> /// Settings for using an Amazon Polly voice to communicate with a user. /// </summary> public sealed class BotVoiceSettingsArgs : Pulumi.ResourceArgs { /// <summary> /// The Amazon Polly voice ID that Amazon Lex uses for voice interaction with the user. /// </summary> [Input("voiceId", required: true)] public Input<string> VoiceId { get; set; } = null!; public BotVoiceSettingsArgs() { } } } ======================= File: sdk/dotnet/SageMaker/Outputs/MonitoringScheduleMonitoringExecutionSummary.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.SageMaker.Outputs { /// <summary> /// Summary of information about monitoring job /// </summary> [OutputType] public sealed class MonitoringScheduleMonitoringExecutionSummary { /// <summary> /// The time at which the monitoring job was created. /// </summary> public readonly string CreationTime; public readonly string? EndpointName; /// <summary> /// Contains the reason a monitoring job failed, if it failed. /// </summary> public readonly string? FailureReason; /// <summary> /// A timestamp that indicates the last time the monitoring job was modified. /// </summary> public readonly string LastModifiedTime; /// <summary> /// The status of the monitoring job. /// </summary> public readonly Pulumi.AwsNative.SageMaker.MonitoringScheduleMonitoringExecutionSummaryMonitoringExecutionStatus MonitoringExecutionStatus; public readonly string MonitoringScheduleName; /// <summary> /// The Amazon Resource Name (ARN) of the monitoring job. /// </summary> public readonly string? ProcessingJobArn; /// <summary> /// The time the monitoring job was scheduled. /// </summary> public readonly string ScheduledTime; [OutputConstructor] private MonitoringScheduleMonitoringExecutionSummary( string creationTime, string? endpointName, string? failureReason, string lastModifiedTime, Pulumi.AwsNative.SageMaker.MonitoringScheduleMonitoringExecutionSummaryMonitoringExecutionStatus monitoringExecutionStatus, string monitoringScheduleName, string? processingJobArn, string scheduledTime) { CreationTime = creationTime; EndpointName = endpointName; FailureReason = failureReason; LastModifiedTime = lastModifiedTime; MonitoringExecutionStatus = monitoringExecutionStatus; MonitoringScheduleName = monitoringScheduleName; ProcessingJobArn = processingJobArn; ScheduledTime = scheduledTime; } } } ======================= File: sdk/dotnet/NetworkFirewall/Outputs/RuleGroupPortRange.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.NetworkFirewall.Outputs { [OutputType] public sealed class RuleGroupPortRange { public readonly int FromPort; public readonly int ToPort; [OutputConstructor] private RuleGroupPortRange( int fromPort, int toPort) { FromPort = fromPort; ToPort = toPort; } } } ======================= File: sdk/dotnet/SSM/Inputs/ResourceDataSyncS3DestinationArgs.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.SSM.Inputs { public sealed class ResourceDataSyncS3DestinationArgs : Pulumi.ResourceArgs { [Input("bucketName", required: true)] public Input<string> BucketName { get; set; } = null!; [Input("bucketPrefix")] public Input<string>? BucketPrefix { get; set; } [Input("bucketRegion", required: true)] public Input<string> BucketRegion { get; set; } = null!; [Input("kMSKeyArn")] public Input<string>? KMSKeyArn { get; set; } [Input("syncFormat", required: true)] public Input<string> SyncFormat { get; set; } = null!; public ResourceDataSyncS3DestinationArgs() { } } } ======================= File: sdk/dotnet/Lex/Enums.cs ======================= <gh_stars>0 // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.ComponentModel; using Pulumi; namespace Pulumi.AwsNative.Lex { [EnumType] public readonly struct BotAliasStatus : IEquatable<BotAliasStatus> { private readonly string _value; private BotAliasStatus(string value) { _value = value?? throw new ArgumentNullException(nameof(value)); } public static BotAliasStatus Creating { get; } = new BotAliasStatus("Creating"); public static BotAliasStatus Available { get; } = new BotAliasStatus("Available"); public static BotAliasStatus Deleting { get; } = new BotAliasStatus("Deleting"); public static BotAliasStatus Failed { get; } = new BotAliasStatus("Failed"); public static bool operator ==(BotAliasStatus left, BotAliasStatus right) => left.Equals(right); public static bool operator!=(BotAliasStatus left, BotAliasStatus right) =>!left.Equals(right); public static explicit operator string(BotAliasStatus value) => value._value; [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) => obj is BotAliasStatus other && Equals(other); public bool Equals(BotAliasStatus other) => string.Equals(_value, other._value, StringComparison.Ordinal); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value?.GetHashCode()?? 0; public override string ToString() => _value; } /// <summary> /// Value that determines whether Amazon Lex obscures slot values in conversation logs. The default is to obscure the values. /// </summary> [EnumType] public readonly struct BotObfuscationSettingObfuscationSettingType : IEquatable<BotObfuscationSettingObfuscationSettingType> { private readonly string _value; private BotObfuscationSettingObfuscationSettingType(string value) { _value = value?? throw new ArgumentNullException(nameof(value)); } public static BotObfuscationSettingObfuscationSettingType None { get; } = new BotObfuscationSettingObfuscationSettingType("None"); public static BotObfuscationSettingObfuscationSettingType DefaultObfuscation { get; } = new BotObfuscationSettingObfuscationSettingType("DefaultObfuscation"); public static bool operator ==(BotObfuscationSettingObfuscationSettingType left, BotObfuscationSettingObfuscationSettingType right) => left.Equals(right); public static bool operator!=(BotObfuscationSettingObfuscationSettingType left, BotObfuscationSettingObfuscationSettingType right) =>!left.Equals(right); public static explicit operator string(BotObfuscationSettingObfuscationSettingType value) => value._value; [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) => obj is BotObfuscationSettingObfuscationSettingType other && Equals(other); public bool Equals(BotObfuscationSettingObfuscationSettingType other) => string.Equals(_value, other._value, StringComparison.Ordinal); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value?.GetHashCode()?? 0; public override string ToString() => _value; } [EnumType] public readonly struct BotSlotConstraint : IEquatable<BotSlotConstraint> { private readonly string _value; private BotSlotConstraint(string value) { _value = value?? throw new ArgumentNullException(nameof(value)); } public static BotSlotConstraint Required { get; } = new BotSlotConstraint("Required"); public static BotSlotConstraint Optional { get; } = new BotSlotConstraint("Optional"); public static bool operator ==(BotSlotConstraint left, BotSlotConstraint right) => left.Equals(right); public static bool operator!=(BotSlotConstraint left, BotSlotConstraint right) =>!left.Equals(right); public static explicit operator string(BotSlotConstraint value) => value._value; [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) => obj is BotSlotConstraint other && Equals(other); public bool Equals(BotSlotConstraint other) => string.Equals(_value, other._value, StringComparison.Ordinal); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value?.GetHashCode()?? 0; public override string ToString() => _value; } [EnumType] public readonly struct BotSlotValueResolutionStrategy : IEquatable<BotSlotValueResolutionStrategy> { private readonly string _value; private BotSlotValueResolutionStrategy(string value) { _value = value?? throw new ArgumentNullException(nameof(value)); } public static BotSlotValueResolutionStrategy OriginalValue { get; } = new BotSlotValueResolutionStrategy("ORIGINAL_VALUE"); public static BotSlotValueResolutionStrategy TopResolution { get; } = new BotSlotValueResolutionStrategy("TOP_RESOLUTION"); public static bool operator ==(BotSlotValueResolutionStrategy left, BotSlotValueResolutionStrategy right) => left.Equals(right); public static bool operator!=(BotSlotValueResolutionStrategy left, BotSlotValueResolutionStrategy right) =>!left.Equals(right); public static explicit operator string(BotSlotValueResolutionStrategy value) => value._value; [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) => obj is BotSlotValueResolutionStrategy other && Equals(other); public bool Equals(BotSlotValueResolutionStrategy other) => string.Equals(_value, other._value, StringComparison.Ordinal); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value?.GetHashCode()?? 0; public override string ToString() => _value; } } ======================= File: sdk/dotnet/WAFv2/Outputs/LoggingConfigurationCondition.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.WAFv2.Outputs { [OutputType] public sealed class LoggingConfigurationCondition { /// <summary> /// A single action condition. /// </summary> public readonly Outputs.LoggingConfigurationConditionActionConditionProperties? ActionCondition; /// <summary> /// A single label name condition. /// </summary> public readonly Outputs.LoggingConfigurationConditionLabelNameConditionProperties? LabelNameCondition; [OutputConstructor] private LoggingConfigurationCondition( Outputs.LoggingConfigurationConditionActionConditionProperties? actionCondition, Outputs.LoggingConfigurationConditionLabelNameConditionProperties? labelNameCondition) { ActionCondition = actionCondition; LabelNameCondition = labelNameCondition; } } } ======================= File: sdk/dotnet/LookoutEquipment/Inputs/InferenceSchedulerTagArgs.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.LookoutEquipment.Inputs { /// <summary> /// A tag is a key-value pair that can be added to a resource as metadata. /// </summary> public sealed class InferenceSchedulerTagArgs : Pulumi.ResourceArgs { /// <summary> /// The key for the specified tag. /// </summary> [Input("key", required: true)] public Input<string> Key { get; set; } = null!; /// <summary> /// The value for the specified tag. /// </summary> [Input("value", required: true)] public Input<string> Value { get; set; } = null!; public InferenceSchedulerTagArgs() { } } } ======================= File: sdk/dotnet/Budgets/Outputs/BudgetsActionSubscriber.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.Budgets.Outputs { [OutputType] public sealed class BudgetsActionSubscriber { public readonly string Address; public readonly Pulumi.AwsNative.Budgets.BudgetsActionSubscriberType Type; [OutputConstructor] private BudgetsActionSubscriber( string address, Pulumi.AwsNative.Budgets.BudgetsActionSubscriberType type) { Address = address; Type = type; } } } ======================= File: sdk/dotnet/Kendra/Outputs/DataSourceWebCrawlerConfiguration.cs ======================= <reponame>AaronFriel/pulumi-aws-native // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.Kendra.Outputs { [OutputType] public sealed class DataSourceWebCrawlerConfiguration { public readonly Outputs.DataSourceWebCrawlerAuthenticationConfiguration? AuthenticationConfiguration; public readonly int? CrawlDepth; public readonly double? MaxContentSizePerPageInMegaBytes; public readonly int? MaxLinksPerPage; public readonly int? MaxUrlsPerMinuteCrawlRate; public readonly Outputs.DataSourceProxyConfiguration? ProxyConfiguration; public readonly ImmutableArray<string> UrlExclusionPatterns; public readonly ImmutableArray<string> UrlInclusionPatterns; public readonly Outputs.DataSourceWebCrawlerUrls Urls; [OutputConstructor] private DataSourceWebCrawlerConfiguration( Outputs.DataSourceWebCrawlerAuthenticationConfiguration? authenticationConfiguration, int? crawlDepth, double? maxContentSizePerPageInMegaBytes, int? maxLinksPerPage, int? maxUrlsPerMinuteCrawlRate, Outputs.DataSourceProxyConfiguration? proxyConfiguration, ImmutableArray<string> urlExclusionPatterns, ImmutableArray<string> urlInclusionPatterns, Outputs.DataSourceWebCrawlerUrls urls) { AuthenticationConfiguration = authenticationConfiguration; CrawlDepth = crawlDepth; MaxContentSizePerPageInMegaBytes = maxContentSizePerPageInMegaBytes; MaxLinksPerPage = maxLinksPerPage; MaxUrlsPerMinuteCrawlRate = maxUrlsPerMinuteCrawlRate; ProxyConfiguration = proxyConfiguration; UrlExclusionPatterns = urlExclusionPatterns; UrlInclusionPatterns = urlInclusionPatterns; Urls = urls; } } } ======================= File: sdk/dotnet/S3/Outputs/StorageLensConfiguration.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.S3.Outputs { /// <summary> /// Specifies the details of Amazon S3 Storage Lens configuration. /// </summary> [OutputType] public sealed class StorageLensConfiguration { public readonly Outputs.StorageLensAccountLevel AccountLevel; public readonly Outputs.StorageLensAwsOrg? AwsOrg; public readonly Outputs.StorageLensDataExport? DataExport; public readonly Outputs.StorageLensBucketsAndRegions? Exclude; public readonly string Id; public readonly Outputs.StorageLensBucketsAndRegions? Include; /// <summary> /// Specifies whether the Amazon S3 Storage Lens configuration is enabled or disabled. /// </summary> public readonly bool IsEnabled; /// <summary> /// The ARN for the Amazon S3 Storage Lens configuration. /// </summary> public readonly string? StorageLensArn; [OutputConstructor] private StorageLensConfiguration( Outputs.StorageLensAccountLevel accountLevel, Outputs.StorageLensAwsOrg? awsOrg, Outputs.StorageLensDataExport? dataExport, Outputs.StorageLensBucketsAndRegions? exclude, string id, Outputs.StorageLensBucketsAndRegions? include, bool isEnabled, string? storageLensArn) { AccountLevel = accountLevel; AwsOrg = awsOrg; DataExport = dataExport; Exclude = exclude; Id = id; Include = include; IsEnabled = isEnabled; StorageLensArn = storageLensArn; } } } ======================= File: sdk/dotnet/Kendra/Outputs/IndexUserTokenConfiguration.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.Kendra.Outputs { [OutputType] public sealed class IndexUserTokenConfiguration { public readonly Outputs.IndexJsonTokenTypeConfiguration? JsonTokenTypeConfiguration; public readonly Outputs.IndexJwtTokenTypeConfiguration? JwtTokenTypeConfiguration; [OutputConstructor] private IndexUserTokenConfiguration( Outputs.IndexJsonTokenTypeConfiguration? jsonTokenTypeConfiguration, Outputs.IndexJwtTokenTypeConfiguration? jwtTokenTypeConfiguration) { JsonTokenTypeConfiguration = jsonTokenTypeConfiguration; JwtTokenTypeConfiguration = jwtTokenTypeConfiguration; } } } ======================= File: sdk/dotnet/LicenseManager/Outputs/LicenseEntitlement.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.LicenseManager.Outputs { [OutputType] public sealed class LicenseEntitlement { public readonly bool? AllowCheckIn; public readonly int? MaxCount; public readonly string Name; public readonly bool? Overage; public readonly string Unit; public readonly string? Value; [OutputConstructor] private LicenseEntitlement( bool? allowCheckIn, int? maxCount, string name, bool? overage, string unit, string? value) { AllowCheckIn = allowCheckIn; MaxCount = maxCount; Name = name; Overage = overage; Unit = unit; Value = value; } } } ======================= File: sdk/dotnet/GreengrassV2/Outputs/ComponentVersionLambdaVolumeMount.cs ======================= <filename>sdk/dotnet/GreengrassV2/Outputs/ComponentVersionLambdaVolumeMount.cs<gh_stars>10-100 // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.GreengrassV2.Outputs { [OutputType] public sealed class ComponentVersionLambdaVolumeMount { public readonly bool? AddGroupOwner; public readonly string? DestinationPath; public readonly Pulumi.AwsNative.GreengrassV2.ComponentVersionLambdaFilesystemPermission? Permission; public readonly string? SourcePath; [OutputConstructor] private ComponentVersionLambdaVolumeMount( bool? addGroupOwner, string? destinationPath, Pulumi.AwsNative.GreengrassV2.ComponentVersionLambdaFilesystemPermission? permission, string? sourcePath) { AddGroupOwner = addGroupOwner; DestinationPath = destinationPath; Permission = permission; SourcePath = sourcePath; } } } ======================= File: sdk/dotnet/EC2/NetworkAclEntry.cs ======================= <reponame>AaronFriel/pulumi-aws-native<filename>sdk/dotnet/EC2/NetworkAclEntry.cs // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.EC2 { /// <summary> /// Resource Type definition for AWS::EC2::NetworkAclEntry /// </summary> [Obsolete(@"NetworkAclEntry is not yet supported by AWS Native, so its creation will currently fail. Please use the classic AWS provider, if possible.")] [AwsNativeResourceType("aws-native:ec2:NetworkAclEntry")] public partial class NetworkAclEntry : Pulumi.CustomResource { /// <summary> /// The IPv4 CIDR range to allow or deny, in CIDR notation (for example, 172.16.0.0/24). Requirement is conditional: You must specify the CidrBlock or Ipv6CidrBlock property /// </summary> [Output("cidrBlock")] public Output<string?> CidrBlock { get; private set; } = null!; /// <summary> /// Indicates whether this is an egress rule (rule is applied to traffic leaving the subnet) /// </summary> [Output("egress")] public Output<bool?> Egress { get; private set; } = null!; /// <summary> /// The Internet Control Message Protocol (ICMP) code and type. Requirement is conditional: Required if specifying 1 (ICMP) for the protocol parameter /// </summary> [Output("icmp")] public Output<Outputs.NetworkAclEntryIcmp?> Icmp { get; private set; } = null!; /// <summary> /// The IPv6 network range to allow or deny, in CIDR notation (for example 2001:db8:1234:1a00::/64) /// </summary> [Output("ipv6CidrBlock")] public Output<string?> Ipv6CidrBlock { get; private set; } = null!; /// <summary> /// The ID of the network ACL /// </summary> [Output("networkAclId")] public Output<string> NetworkAclId { get; private set; } = null!; /// <summary> /// The IPv4 network range to allow or deny, in CIDR notation (for example 172.16.0.0/24). We modify the specified CIDR block to its canonical form; for example, if you specify 172.16.58.3/18, we modify it to 172.16.58.3/18 /// </summary> [Output("portRange")] public Output<Outputs.NetworkAclEntryPortRange?> PortRange { get; private set; } = null!; /// <summary> /// The protocol number. A value of "-1" means all protocols. If you specify "-1" or a protocol number other than "6" (TCP), "17" (UDP), or "1" (ICMP), traffic on all ports is allowed, regardless of any ports or ICMP types or codes that you specify. If you specify protocol "58" (ICMPv6) and specify an IPv4 CIDR block, traffic for all ICMP types and codes allowed, regardless of any that you specify. If you specify protocol "58" (ICMPv6) and specify an IPv6 CIDR block, you must specify an ICMP type and code /// </summary> [Output("protocol")] public Output<int> Protocol { get; private set; } = null!; /// <summary> /// Indicates whether to allow or deny the traffic that matches the rule /// </summary> [Output("ruleAction")] public Output<string> RuleAction { get; private set; } = null!; /// <summary> /// Rule number to assign to the entry, such as 100. ACL entries are processed in ascending order by rule number. Entries can't use the same rule number unless one is an egress rule and the other is an ingress rule /// </summary> [Output("ruleNumber")] public Output<int> RuleNumber { get; private set; } = null!; /// <summary> /// Create a NetworkAclEntry resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public NetworkAclEntry(string name, NetworkAclEntryArgs args, CustomResourceOptions? options = null) : base("aws-native:ec2:NetworkAclEntry", name, args?? new NetworkAclEntryArgs(), MakeResourceOptions(options, "")) { } private NetworkAclEntry(string name, Input<string> id, CustomResourceOptions? options = null) : base("aws-native:ec2:NetworkAclEntry", name, null, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id?? merged.Id; return merged; } /// <summary> /// Get an existing NetworkAclEntry resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static NetworkAclEntry Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new NetworkAclEntry(name, id, options); } } public sealed class NetworkAclEntryArgs : Pulumi.ResourceArgs { /// <summary> /// The IPv4 CIDR range to allow or deny, in CIDR notation (for example, 172.16.0.0/24). Requirement is conditional: You must specify the CidrBlock or Ipv6CidrBlock property /// </summary> [Input("cidrBlock")] public Input<string>? CidrBlock { get; set; } /// <summary> /// Indicates whether this is an egress rule (rule is applied to traffic leaving the subnet) /// </summary> [Input("egress")] public Input<bool>? Egress { get; set; } /// <summary> /// The Internet Control Message Protocol (ICMP) code and type. Requirement is conditional: Required if specifying 1 (ICMP) for the protocol parameter /// </summary> [Input("icmp")] public Input<Inputs.NetworkAclEntryIcmpArgs>? Icmp { get; set; } /// <summary> /// The IPv6 network range to allow or deny, in CIDR notation (for example 2001:db8:1234:1a00::/64) /// </summary> [Input("ipv6CidrBlock")] public Input<string>? Ipv6CidrBlock { get; set; } /// <summary> /// The ID of the network ACL /// </summary> [Input("networkAclId", required: true)] public Input<string> NetworkAclId { get; set; } = null!; /// <summary> /// The IPv4 network range to allow or deny, in CIDR notation (for example 172.16.0.0/24). We modify the specified CIDR block to its canonical form; for example, if you specify 172.16.58.3/18, we modify it to 172.16.58.3/18 /// </summary> [Input("portRange")] public Input<Inputs.NetworkAclEntryPortRangeArgs>? PortRange { get; set; } /// <summary> /// The protocol number. A value of "-1" means all protocols. If you specify "-1" or a protocol number other than "6" (TCP), "17" (UDP), or "1" (ICMP), traffic on all ports is allowed, regardless of any ports or ICMP types or codes that you specify. If you specify protocol "58" (ICMPv6) and specify an IPv4 CIDR block, traffic for all ICMP types and codes allowed, regardless of any that you specify. If you specify protocol "58" (ICMPv6) and specify an IPv6 CIDR block, you must specify an ICMP type and code /// </summary> [Input("protocol", required: true)] public Input<int> Protocol { get; set; } = null!; /// <summary> /// Indicates whether to allow or deny the traffic that matches the rule /// </summary> [Input("ruleAction", required: true)] public Input<string> RuleAction { get; set; } = null!; /// <summary> /// Rule number to assign to the entry, such as 100. ACL entries are processed in ascending order by rule number. Entries can't use the same rule number unless one is an egress rule and the other is an ingress rule /// </summary> [Input("ruleNumber", required: true)] public Input<int> RuleNumber { get; set; } = null!; public NetworkAclEntryArgs() { } } } ======================= File: sdk/dotnet/SSM/Inputs/MaintenanceWindowTaskMaintenanceWindowRunCommandParametersArgs.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.SSM.Inputs { public sealed class MaintenanceWindowTaskMaintenanceWindowRunCommandParametersArgs : Pulumi.ResourceArgs { [Input("comment")] public Input<string>? Comment { get; set; } [Input("documentHash")] public Input<string>? DocumentHash { get; set; } [Input("documentHashType")] public Input<string>? DocumentHashType { get; set; } [Input("notificationConfig")] public Input<Inputs.MaintenanceWindowTaskNotificationConfigArgs>? NotificationConfig { get; set; } [Input("outputS3BucketName")] public Input<string>? OutputS3BucketName { get; set; } [Input("outputS3KeyPrefix")] public Input<string>? OutputS3KeyPrefix { get; set; } [Input("parameters")] public Input<object>? Parameters { get; set; } [Input("serviceRoleArn")] public Input<string>? ServiceRoleArn { get; set; } [Input("timeoutSeconds")] public Input<int>? TimeoutSeconds { get; set; } public MaintenanceWindowTaskMaintenanceWindowRunCommandParametersArgs() { } } } ======================= File: sdk/dotnet/Cognito/Outputs/UserPoolVerificationMessageTemplate.cs ======================= <reponame>AaronFriel/pulumi-aws-native // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.Cognito.Outputs { [OutputType] public sealed class UserPoolVerificationMessageTemplate { public readonly string? DefaultEmailOption; public readonly string? EmailMessage; public readonly string? EmailMessageByLink; public readonly string? EmailSubject; public readonly string? EmailSubjectByLink; public readonly string? SmsMessage; [OutputConstructor] private UserPoolVerificationMessageTemplate( string? defaultEmailOption, string? emailMessage, string? emailMessageByLink, string? emailSubject, string? emailSubjectByLink, string? smsMessage) { DefaultEmailOption = defaultEmailOption; EmailMessage = emailMessage; EmailMessageByLink = emailMessageByLink; EmailSubject = emailSubject; EmailSubjectByLink = emailSubjectByLink; SmsMessage = smsMessage; } } } ======================= File: sdk/dotnet/AppFlow/Inputs/FlowPrefixConfigArgs.cs ======================= <gh_stars>10-100 // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.AppFlow.Inputs { public sealed class FlowPrefixConfigArgs : Pulumi.ResourceArgs { [Input("prefixFormat")] public Input<Pulumi.AwsNative.AppFlow.FlowPrefixFormat>? PrefixFormat { get; set; } [Input("prefixType")] public Input<Pulumi.AwsNative.AppFlow.FlowPrefixType>? PrefixType { get; set; } public FlowPrefixConfigArgs() { } } } ======================= File: sdk/dotnet/DocDB/DBCluster.cs ======================= <gh_stars>0 // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.DocDB { /// <summary> /// Resource Type definition for AWS::DocDB::DBCluster /// </summary> [Obsolete(@"DBCluster is not yet supported by AWS Native, so its creation will currently fail. Please use the classic AWS provider, if possible.")] [AwsNativeResourceType("aws-native:docdb:DBCluster")] public partial class DBCluster : Pulumi.CustomResource { [Output("availabilityZones")] public Output<ImmutableArray<string>> AvailabilityZones { get; private set; } = null!; [Output("backupRetentionPeriod")] public Output<int?> BackupRetentionPeriod { get; private set; } = null!; [Output("clusterResourceId")] public Output<string> ClusterResourceId { get; private set; } = null!; [Output("dBClusterIdentifier")] public Output<string?> DBClusterIdentifier { get; private set; } = null!; [Output("dBClusterParameterGroupName")] public Output<string?> DBClusterParameterGroupName { get; private set; } = null!; [Output("dBSubnetGroupName")] public Output<string?> DBSubnetGroupName { get; private set; } = null!; [Output("deletionProtection")] public Output<bool?> DeletionProtection { get; private set; } = null!; [Output("enableCloudwatchLogsExports")] public Output<ImmutableArray<string>> EnableCloudwatchLogsExports { get; private set; } = null!; [Output("endpoint")] public Output<string> Endpoint { get; private set; } = null!; [Output("engineVersion")] public Output<string?> EngineVersion { get; private set; } = null!; [Output("kmsKeyId")] public Output<string?> KmsKeyId { get; private set; } = null!; [Output("masterUserPassword")] public Output<string> MasterUserPassword { get; private set; } = null!; [Output("masterUsername")] public Output<string> MasterUsername { get; private set; } = null!; [Output("port")] public Output<int?> Port { get; private set; } = null!; [Output("preferredBackupWindow")] public Output<string?> PreferredBackupWindow { get; private set; } = null!; [Output("preferredMaintenanceWindow")] public Output<string?> PreferredMaintenanceWindow { get; private set; } = null!; [Output("readEndpoint")] public Output<string> ReadEndpoint { get; private set; } = null!; [Output("snapshotIdentifier")] public Output<string?> SnapshotIdentifier { get; private set; } = null!; [Output("storageEncrypted")] public Output<bool?> StorageEncrypted { get; private set; } = null!; [Output("tags")] public Output<ImmutableArray<Outputs.DBClusterTag>> Tags { get; private set; } = null!; [Output("vpcSecurityGroupIds")] public Output<ImmutableArray<string>> VpcSecurityGroupIds { get; private set; } = null!; /// <summary> /// Create a DBCluster resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public DBCluster(string name, DBClusterArgs args, CustomResourceOptions? options = null) : base("aws-native:docdb:DBCluster", name, args?? new DBClusterArgs(), MakeResourceOptions(options, "")) { } private DBCluster(string name, Input<string> id, CustomResourceOptions? options = null) : base("aws-native:docdb:DBCluster", name, null, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id?? merged.Id; return merged; } /// <summary> /// Get an existing DBCluster resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static DBCluster Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new DBCluster(name, id, options); } } public sealed class DBClusterArgs : Pulumi.ResourceArgs { [Input("availabilityZones")] private InputList<string>? _availabilityZones; public InputList<string> AvailabilityZones { get => _availabilityZones?? (_availabilityZones = new InputList<string>()); set => _availabilityZones = value; } [Input("backupRetentionPeriod")] public Input<int>? BackupRetentionPeriod { get; set; } [Input("dBClusterIdentifier")] public Input<string>? DBClusterIdentifier { get; set; } [Input("dBClusterParameterGroupName")] public Input<string>? DBClusterParameterGroupName { get; set; } [Input("dBSubnetGroupName")] public Input<string>? DBSubnetGroupName { get; set; } [Input("deletionProtection")] public Input<bool>? DeletionProtection { get; set; } [Input("enableCloudwatchLogsExports")] private InputList<string>? _enableCloudwatchLogsExports; public InputList<string> EnableCloudwatchLogsExports { get => _enableCloudwatchLogsExports?? (_enableCloudwatchLogsExports = new InputList<string>()); set => _enableCloudwatchLogsExports = value; } [Input("engineVersion")] public Input<string>? EngineVersion { get; set; } [Input("kmsKeyId")] public Input<string>? KmsKeyId { get; set; } [Input("masterUserPassword", required: true)] public Input<string> MasterUserPassword { get; set; } = null!; [Input("masterUsername", required: true)] public Input<string> MasterUsername { get; set; } = null!; [Input("port")] public Input<int>? Port { get; set; } [Input("preferredBackupWindow")] public Input<string>? PreferredBackupWindow { get; set; } [Input("preferredMaintenanceWindow")] public Input<string>? PreferredMaintenanceWindow { get; set; } [Input("snapshotIdentifier")] public Input<string>? SnapshotIdentifier { get; set; } [Input("storageEncrypted")] public Input<bool>? StorageEncrypted { get; set; } [Input("tags")] private InputList<Inputs.DBClusterTagArgs>? _tags; public InputList<Inputs.DBClusterTagArgs> Tags { get => _tags?? (_tags = new InputList<Inputs.DBClusterTagArgs>()); set => _tags = value; } [Input("vpcSecurityGroupIds")] private InputList<string>? _vpcSecurityGroupIds; public InputList<string> VpcSecurityGroupIds { get => _vpcSecurityGroupIds?? (_vpcSecurityGroupIds = new InputList<string>()); set => _vpcSecurityGroupIds = value; } public DBClusterArgs() { } } } ======================= File: sdk/dotnet/Glue/Outputs/SecurityConfigurationEncryptionConfiguration.cs ======================= <gh_stars>10-100 // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.Glue.Outputs { [OutputType] public sealed class SecurityConfigurationEncryptionConfiguration { public readonly Outputs.SecurityConfigurationCloudWatchEncryption? CloudWatchEncryption; public readonly Outputs.SecurityConfigurationJobBookmarksEncryption? JobBookmarksEncryption; public readonly Outputs.SecurityConfigurationS3Encryptions? S3Encryptions; [OutputConstructor] private SecurityConfigurationEncryptionConfiguration( Outputs.SecurityConfigurationCloudWatchEncryption? cloudWatchEncryption, Outputs.SecurityConfigurationJobBookmarksEncryption? jobBookmarksEncryption, Outputs.SecurityConfigurationS3Encryptions? s3Encryptions) { CloudWatchEncryption = cloudWatchEncryption; JobBookmarksEncryption = jobBookmarksEncryption; S3Encryptions = s3Encryptions; } } } ======================= File: sdk/dotnet/MemoryDB/ParameterGroup.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.MemoryDB { /// <summary> /// The AWS::MemoryDB::ParameterGroup resource creates an Amazon MemoryDB ParameterGroup. /// </summary> [AwsNativeResourceType("aws-native:memorydb:ParameterGroup")] public partial class ParameterGroup : Pulumi.CustomResource { /// <summary> /// The Amazon Resource Name (ARN) of the parameter group. /// </summary> [Output("aRN")] public Output<string> ARN { get; private set; } = null!; /// <summary> /// A description of the parameter group. /// </summary> [Output("description")] public Output<string?> Description { get; private set; } = null!; /// <summary> /// The name of the parameter group family that this parameter group is compatible with. /// </summary> [Output("family")] public Output<string> Family { get; private set; } = null!; /// <summary> /// The name of the parameter group. /// </summary> [Output("parameterGroupName")] public Output<string> ParameterGroupName { get; private set; } = null!; /// <summary> /// An map of parameter names and values for the parameter update. You must supply at least one parameter name and value; subsequent arguments are optional. /// </summary> [Output("parameters")] public Output<object?> Parameters { get; private set; } = null!; /// <summary> /// An array of key-value pairs to apply to this parameter group. /// </summary> [Output("tags")] public Output<ImmutableArray<Outputs.ParameterGroupTag>> Tags { get; private set; } = null!; /// <summary> /// Create a ParameterGroup resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public ParameterGroup(string name, ParameterGroupArgs args, CustomResourceOptions? options = null) : base("aws-native:memorydb:ParameterGroup", name, args?? new ParameterGroupArgs(), MakeResourceOptions(options, "")) { } private ParameterGroup(string name, Input<string> id, CustomResourceOptions? options = null) : base("aws-native:memorydb:ParameterGroup", name, null, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id?? merged.Id; return merged; } /// <summary> /// Get an existing ParameterGroup resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static ParameterGroup Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new ParameterGroup(name, id, options); } } public sealed class ParameterGroupArgs : Pulumi.ResourceArgs { /// <summary> /// A description of the parameter group. /// </summary> [Input("description")] public Input<string>? Description { get; set; } /// <summary> /// The name of the parameter group family that this parameter group is compatible with. /// </summary> [Input("family", required: true)] public Input<string> Family { get; set; } = null!; /// <summary> /// The name of the parameter group. /// </summary> [Input("parameterGroupName")] public Input<string>? ParameterGroupName { get; set; } /// <summary> /// An map of parameter names and values for the parameter update. You must supply at least one parameter name and value; subsequent arguments are optional. /// </summary> [Input("parameters")] public Input<object>? Parameters { get; set; } [Input("tags")] private InputList<Inputs.ParameterGroupTagArgs>? _tags; /// <summary> /// An array of key-value pairs to apply to this parameter group. /// </summary> public InputList<Inputs.ParameterGroupTagArgs> Tags { get => _tags?? (_tags = new InputList<Inputs.ParameterGroupTagArgs>()); set => _tags = value; } public ParameterGroupArgs() { } } } ======================= File: sdk/dotnet/Cognito/UserPoolUser.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.Cognito { /// <summary> /// Resource Type definition for AWS::Cognito::UserPoolUser /// </summary> [Obsolete(@"UserPoolUser is not yet supported by AWS Native, so its creation will currently fail. Please use the classic AWS provider, if possible.")] [AwsNativeResourceType("aws-native:cognito:UserPoolUser")] public partial class UserPoolUser : Pulumi.CustomResource { [Output("clientMetadata")] public Output<object?> ClientMetadata { get; private set; } = null!; [Output("desiredDeliveryMediums")] public Output<ImmutableArray<string>> DesiredDeliveryMediums { get; private set; } = null!; [Output("forceAliasCreation")] public Output<bool?> ForceAliasCreation { get; private set; } = null!; [Output("messageAction")] public Output<string?> MessageAction { get; private set; } = null!; [Output("userAttributes")] public Output<ImmutableArray<Outputs.UserPoolUserAttributeType>> UserAttributes { get; private set; } = null!; [Output("userPoolId")] public Output<string> UserPoolId { get; private set; } = null!; [Output("username")] public Output<string?> Username { get; private set; } = null!; [Output("validationData")] public Output<ImmutableArray<Outputs.UserPoolUserAttributeType>> ValidationData { get; private set; } = null!; /// <summary> /// Create a UserPoolUser resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public UserPoolUser(string name, UserPoolUserArgs args, CustomResourceOptions? options = null) : base("aws-native:cognito:UserPoolUser", name, args?? new UserPoolUserArgs(), MakeResourceOptions(options, "")) { } private UserPoolUser(string name, Input<string> id, CustomResourceOptions? options = null) : base("aws-native:cognito:UserPoolUser", name, null, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id?? merged.Id; return merged; } /// <summary> /// Get an existing UserPoolUser resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static UserPoolUser Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new UserPoolUser(name, id, options); } } public sealed class UserPoolUserArgs : Pulumi.ResourceArgs { [Input("clientMetadata")] public Input<object>? ClientMetadata { get; set; } [Input("desiredDeliveryMediums")] private InputList<string>? _desiredDeliveryMediums; public InputList<string> DesiredDeliveryMediums { get => _desiredDeliveryMediums?? (_desiredDeliveryMediums = new InputList<string>()); set => _desiredDeliveryMediums = value; } [Input("forceAliasCreation")] public Input<bool>? ForceAliasCreation { get; set; } [Input("messageAction")] public Input<string>? MessageAction { get; set; } [Input("userAttributes")] private InputList<Inputs.UserPoolUserAttributeTypeArgs>? _userAttributes; public InputList<Inputs.UserPoolUserAttributeTypeArgs> UserAttributes { get => _userAttributes?? (_userAttributes = new InputList<Inputs.UserPoolUserAttributeTypeArgs>()); set => _userAttributes = value; } [Input("userPoolId", required: true)] public Input<string> UserPoolId { get; set; } = null!; [Input("username")] public Input<string>? Username { get; set; } [Input("validationData")] private InputList<Inputs.UserPoolUserAttributeTypeArgs>? _validationData; public InputList<Inputs.UserPoolUserAttributeTypeArgs> ValidationData { get => _validationData?? (_validationData = new InputList<Inputs.UserPoolUserAttributeTypeArgs>()); set => _validationData = value; } public UserPoolUserArgs() { } } } ======================= File: sdk/dotnet/IoT/Outputs/SecurityProfileStatisticalThreshold.cs ======================= <filename>sdk/dotnet/IoT/Outputs/SecurityProfileStatisticalThreshold.cs<gh_stars>10-100 // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.IoT.Outputs { /// <summary> /// A statistical ranking (percentile) which indicates a threshold value by which a behavior is determined to be in compliance or in violation of the behavior. /// </summary> [OutputType] public sealed class SecurityProfileStatisticalThreshold { /// <summary> /// The percentile which resolves to a threshold value by which compliance with a behavior is determined /// </summary> public readonly Pulumi.AwsNative.IoT.SecurityProfileStatisticalThresholdStatistic? Statistic; [OutputConstructor] private SecurityProfileStatisticalThreshold(Pulumi.AwsNative.IoT.SecurityProfileStatisticalThresholdStatistic? statistic) { Statistic = statistic; } } } ======================= File: sdk/dotnet/ApiGatewayV2/Route.cs ======================= <reponame>AaronFriel/pulumi-aws-native // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.ApiGatewayV2 { /// <summary> /// Resource Type definition for AWS::ApiGatewayV2::Route /// </summary> [Obsolete(@"Route is not yet supported by AWS Native, so its creation will currently fail. Please use the classic AWS provider, if possible.")] [AwsNativeResourceType("aws-native:apigatewayv2:Route")] public partial class Route : Pulumi.CustomResource { [Output("apiId")] public Output<string> ApiId { get; private set; } = null!; [Output("apiKeyRequired")] public Output<bool?> ApiKeyRequired { get; private set; } = null!; [Output("authorizationScopes")] public Output<ImmutableArray<string>> AuthorizationScopes { get; private set; } = null!; [Output("authorizationType")] public Output<string?> AuthorizationType { get; private set; } = null!; [Output("authorizerId")] public Output<string?> AuthorizerId { get; private set; } = null!; [Output("modelSelectionExpression")] public Output<string?> ModelSelectionExpression { get; private set; } = null!; [Output("operationName")] public Output<string?> OperationName { get; private set; } = null!; [Output("requestModels")] public Output<object?> RequestModels { get; private set; } = null!; [Output("requestParameters")] public Output<object?> RequestParameters { get; private set; } = null!; [Output("routeKey")] public Output<string> RouteKey { get; private set; } = null!; [Output("routeResponseSelectionExpression")] public Output<string?> RouteResponseSelectionExpression { get; private set; } = null!; [Output("target")] public Output<string?> Target { get; private set; } = null!; /// <summary> /// Create a Route resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public Route(string name, RouteArgs args, CustomResourceOptions? options = null) : base("aws-native:apigatewayv2:Route", name, args?? new RouteArgs(), MakeResourceOptions(options, "")) { } private Route(string name, Input<string> id, CustomResourceOptions? options = null) : base("aws-native:apigatewayv2:Route", name, null, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id?? merged.Id; return merged; } /// <summary> /// Get an existing Route resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static Route Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new Route(name, id, options); } } public sealed class RouteArgs : Pulumi.ResourceArgs { [Input("apiId", required: true)] public Input<string> ApiId { get; set; } = null!; [Input("apiKeyRequired")] public Input<bool>? ApiKeyRequired { get; set; } [Input("authorizationScopes")] private InputList<string>? _authorizationScopes; public InputList<string> AuthorizationScopes { get => _authorizationScopes?? (_authorizationScopes = new InputList<string>()); set => _authorizationScopes = value; } [Input("authorizationType")] public Input<string>? AuthorizationType { get; set; } [Input("authorizerId")] public Input<string>? AuthorizerId { get; set; } [Input("modelSelectionExpression")] public Input<string>? ModelSelectionExpression { get; set; } [Input("operationName")] public Input<string>? OperationName { get; set; } [Input("requestModels")] public Input<object>? RequestModels { get; set; } [Input("requestParameters")] public Input<object>? RequestParameters { get; set; } [Input("routeKey", required: true)] public Input<string> RouteKey { get; set; } = null!; [Input("routeResponseSelectionExpression")] public Input<string>? RouteResponseSelectionExpression { get; set; } [Input("target")] public Input<string>? Target { get; set; } public RouteArgs() { } } } ======================= File: sdk/dotnet/Backup/Outputs/FrameworkControl.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.Backup.Outputs { [OutputType] public sealed class FrameworkControl { /// <summary> /// A list of ParameterName and ParameterValue pairs. /// </summary> public readonly ImmutableArray<Outputs.FrameworkControlInputParameter> ControlInputParameters; /// <summary> /// The name of a control. This name is between 1 and 256 characters. /// </summary> public readonly string ControlName; /// <summary> /// The scope of a control. The control scope defines what the control will evaluate. Three examples of control scopes are: a specific backup plan, all backup plans with a specific tag, or all backup plans. /// </summary> public readonly Outputs.FrameworkControlControlScopeProperties? ControlScope; [OutputConstructor] private FrameworkControl( ImmutableArray<Outputs.FrameworkControlInputParameter> controlInputParameters, string controlName, Outputs.FrameworkControlControlScopeProperties? controlScope) { ControlInputParameters = controlInputParameters; ControlName = controlName; ControlScope = controlScope; } } } ======================= File: sdk/dotnet/IoT/Outputs/TopicRuleCloudwatchMetricAction.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.IoT.Outputs { [OutputType] public sealed class TopicRuleCloudwatchMetricAction { public readonly string MetricName; public readonly string MetricNamespace; public readonly string? MetricTimestamp; public readonly string MetricUnit; public readonly string MetricValue; public readonly string RoleArn; [OutputConstructor] private TopicRuleCloudwatchMetricAction( string metricName, string metricNamespace, string? metricTimestamp, string metricUnit, string metricValue, string roleArn) { MetricName = metricName; MetricNamespace = metricNamespace; MetricTimestamp = metricTimestamp; MetricUnit = metricUnit; MetricValue = metricValue; RoleArn = roleArn; } } } ======================= File: sdk/dotnet/MediaLive/Outputs/ChannelVideoDescription.cs ======================= <gh_stars>10-100 // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.MediaLive.Outputs { [OutputType] public sealed class ChannelVideoDescription { public readonly Outputs.ChannelVideoCodecSettings? CodecSettings; public readonly int? Height; public readonly string? Name; public readonly string? RespondToAfd; public readonly string? ScalingBehavior; public readonly int? Sharpness; public readonly int? Width; [OutputConstructor] private ChannelVideoDescription( Outputs.ChannelVideoCodecSettings? codecSettings, int? height, string? name, string? respondToAfd, string? scalingBehavior, int? sharpness, int? width) { CodecSettings = codecSettings; Height = height; Name = name; RespondToAfd = respondToAfd; ScalingBehavior = scalingBehavior; Sharpness = sharpness; Width = width; } } } ======================= File: sdk/dotnet/ACMPCA/Inputs/CertificateAuthorityOcspConfigurationArgs.cs ======================= <filename>sdk/dotnet/ACMPCA/Inputs/CertificateAuthorityOcspConfigurationArgs.cs // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.ACMPCA.Inputs { /// <summary> /// Helps to configure online certificate status protocol (OCSP) responder for your certificate authority /// </summary> public sealed class CertificateAuthorityOcspConfigurationArgs : Pulumi.ResourceArgs { [Input("enabled")] public Input<bool>? Enabled { get; set; } [Input("ocspCustomCname")] public Input<string>? OcspCustomCname { get; set; } public CertificateAuthorityOcspConfigurationArgs() { } } } ======================= File: sdk/dotnet/IoT/AccountAuditConfiguration.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.IoT { /// <summary> /// Configures the Device Defender audit settings for this account. Settings include how audit notifications are sent and which audit checks are enabled or disabled. /// </summary> [AwsNativeResourceType("aws-native:iot:AccountAuditConfiguration")] public partial class AccountAuditConfiguration : Pulumi.CustomResource { /// <summary> /// Your 12-digit account ID (used as the primary identifier for the CloudFormation resource). /// </summary> [Output("accountId")] public Output<string> AccountId { get; private set; } = null!; [Output("auditCheckConfigurations")] public Output<Outputs.AccountAuditConfigurationAuditCheckConfigurations> AuditCheckConfigurations { get; private set; } = null!; [Output("auditNotificationTargetConfigurations")] public Output<Outputs.AccountAuditConfigurationAuditNotificationTargetConfigurations?> AuditNotificationTargetConfigurations { get; private set; } = null!; /// <summary> /// The ARN of the role that grants permission to AWS IoT to access information about your devices, policies, certificates and other items as required when performing an audit. /// </summary> [Output("roleArn")] public Output<string> RoleArn { get; private set; } = null!; /// <summary> /// Create a AccountAuditConfiguration resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public AccountAuditConfiguration(string name, AccountAuditConfigurationArgs args, CustomResourceOptions? options = null) : base("aws-native:iot:AccountAuditConfiguration", name, args?? new AccountAuditConfigurationArgs(), MakeResourceOptions(options, "")) { } private AccountAuditConfiguration(string name, Input<string> id, CustomResourceOptions? options = null) : base("aws-native:iot:AccountAuditConfiguration", name, null, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id?? merged.Id; return merged; } /// <summary> /// Get an existing AccountAuditConfiguration resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static AccountAuditConfiguration Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new AccountAuditConfiguration(name, id, options); } } public sealed class AccountAuditConfigurationArgs : Pulumi.ResourceArgs { /// <summary> /// Your 12-digit account ID (used as the primary identifier for the CloudFormation resource). /// </summary> [Input("accountId", required: true)] public Input<string> AccountId { get; set; } = null!; [Input("auditCheckConfigurations", required: true)] public Input<Inputs.AccountAuditConfigurationAuditCheckConfigurationsArgs> AuditCheckConfigurations { get; set; } = null!; [Input("auditNotificationTargetConfigurations")] public Input<Inputs.AccountAuditConfigurationAuditNotificationTargetConfigurationsArgs>? AuditNotificationTargetConfigurations { get; set; } /// <summary> /// The ARN of the role that grants permission to AWS IoT to access information about your devices, policies, certificates and other items as required when performing an audit. /// </summary> [Input("roleArn", required: true)] public Input<string> RoleArn { get; set; } = null!; public AccountAuditConfigurationArgs() { } } } ======================= File: sdk/dotnet/NetworkFirewall/Inputs/RuleGroupStatelessRulesAndCustomActionsArgs.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.NetworkFirewall.Inputs { public sealed class RuleGroupStatelessRulesAndCustomActionsArgs : Pulumi.ResourceArgs { [Input("customActions")] private InputList<Inputs.RuleGroupCustomActionArgs>? _customActions; public InputList<Inputs.RuleGroupCustomActionArgs> CustomActions { get => _customActions?? (_customActions = new InputList<Inputs.RuleGroupCustomActionArgs>()); set => _customActions = value; } [Input("statelessRules", required: true)] private InputList<Inputs.RuleGroupStatelessRuleArgs>? _statelessRules; public InputList<Inputs.RuleGroupStatelessRuleArgs> StatelessRules { get => _statelessRules?? (_statelessRules = new InputList<Inputs.RuleGroupStatelessRuleArgs>()); set => _statelessRules = value; } public RuleGroupStatelessRulesAndCustomActionsArgs() { } } } ======================= File: sdk/dotnet/ElasticLoadBalancingV2/Outputs/ListenerRedirectConfig.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.ElasticLoadBalancingV2.Outputs { [OutputType] public sealed class ListenerRedirectConfig { public readonly string? Host; public readonly string? Path; public readonly string? Port; public readonly string? Protocol; public readonly string? Query; public readonly string StatusCode; [OutputConstructor] private ListenerRedirectConfig( string? host, string? path, string? port, string? protocol, string? query, string statusCode) { Host = host; Path = path; Port = port; Protocol = protocol; Query = query; StatusCode = statusCode; } } } ======================= File: sdk/dotnet/GameLift/Inputs/GameSessionQueuePriorityConfigurationArgs.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.GameLift.Inputs { public sealed class GameSessionQueuePriorityConfigurationArgs : Pulumi.ResourceArgs { [Input("locationOrder")] private InputList<string>? _locationOrder; public InputList<string> LocationOrder { get => _locationOrder?? (_locationOrder = new InputList<string>()); set => _locationOrder = value; } [Input("priorityOrder")] private InputList<string>? _priorityOrder; public InputList<string> PriorityOrder { get => _priorityOrder?? (_priorityOrder = new InputList<string>()); set => _priorityOrder = value; } public GameSessionQueuePriorityConfigurationArgs() { } } } ======================= File: sdk/dotnet/GreengrassV2/Outputs/ComponentVersionLambdaContainerParams.cs ======================= <gh_stars>10-100 // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.GreengrassV2.Outputs { [OutputType] public sealed class ComponentVersionLambdaContainerParams { public readonly ImmutableArray<Outputs.ComponentVersionLambdaDeviceMount> Devices; public readonly int? MemorySizeInKB; public readonly bool? MountROSysfs; public readonly ImmutableArray<Outputs.ComponentVersionLambdaVolumeMount> Volumes; [OutputConstructor] private ComponentVersionLambdaContainerParams( ImmutableArray<Outputs.ComponentVersionLambdaDeviceMount> devices, int? memorySizeInKB, bool? mountROSysfs, ImmutableArray<Outputs.ComponentVersionLambdaVolumeMount> volumes) { Devices = devices; MemorySizeInKB = memorySizeInKB; MountROSysfs = mountROSysfs; Volumes = volumes; } } } ======================= File: sdk/dotnet/EC2/Outputs/InstanceNetworkInterface.cs ======================= <gh_stars>10-100 // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.EC2.Outputs { [OutputType] public sealed class InstanceNetworkInterface { public readonly bool? AssociatePublicIpAddress; public readonly bool? DeleteOnTermination; public readonly string? Description; public readonly string DeviceIndex; public readonly ImmutableArray<string> GroupSet; public readonly int? Ipv6AddressCount; public readonly ImmutableArray<Outputs.InstanceIpv6Address> Ipv6Addresses; public readonly string? NetworkInterfaceId; public readonly string? PrivateIpAddress; public readonly ImmutableArray<Outputs.InstancePrivateIpAddressSpecification> PrivateIpAddresses; public readonly int? SecondaryPrivateIpAddressCount; public readonly string? SubnetId; [OutputConstructor] private InstanceNetworkInterface( bool? associatePublicIpAddress, bool? deleteOnTermination, string? description, string deviceIndex, ImmutableArray<string> groupSet, int? ipv6AddressCount, ImmutableArray<Outputs.InstanceIpv6Address> ipv6Addresses, string? networkInterfaceId, string? privateIpAddress, ImmutableArray<Outputs.InstancePrivateIpAddressSpecification> privateIpAddresses, int? secondaryPrivateIpAddressCount, string? subnetId) { AssociatePublicIpAddress = associatePublicIpAddress; DeleteOnTermination = deleteOnTermination; Description = description; DeviceIndex = deviceIndex; GroupSet = groupSet; Ipv6AddressCount = ipv6AddressCount; Ipv6Addresses = ipv6Addresses; NetworkInterfaceId = networkInterfaceId; PrivateIpAddress = privateIpAddress; PrivateIpAddresses = privateIpAddresses; SecondaryPrivateIpAddressCount = secondaryPrivateIpAddressCount; SubnetId = subnetId; } } } ======================= File: sdk/dotnet/Pinpoint/Outputs/CampaignInAppMessageContent.cs ======================= <gh_stars>10-100 // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.Pinpoint.Outputs { [OutputType] public sealed class CampaignInAppMessageContent { public readonly string? BackgroundColor; public readonly Outputs.CampaignInAppMessageBodyConfig? BodyConfig; public readonly Outputs.CampaignInAppMessageHeaderConfig? HeaderConfig; public readonly string? ImageUrl; public readonly Outputs.CampaignInAppMessageButton? PrimaryBtn; public readonly Outputs.CampaignInAppMessageButton? SecondaryBtn; [OutputConstructor] private CampaignInAppMessageContent( string? backgroundColor, Outputs.CampaignInAppMessageBodyConfig? bodyConfig, Outputs.CampaignInAppMessageHeaderConfig? headerConfig, string? imageUrl, Outputs.CampaignInAppMessageButton? primaryBtn, Outputs.CampaignInAppMessageButton? secondaryBtn) { BackgroundColor = backgroundColor; BodyConfig = bodyConfig; HeaderConfig = headerConfig; ImageUrl = imageUrl; PrimaryBtn = primaryBtn; SecondaryBtn = secondaryBtn; } } } ======================= File: sdk/dotnet/Batch/Inputs/SchedulingPolicyShareAttributesArgs.cs ======================= <filename>sdk/dotnet/Batch/Inputs/SchedulingPolicyShareAttributesArgs.cs // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.Batch.Inputs { public sealed class SchedulingPolicyShareAttributesArgs : Pulumi.ResourceArgs { [Input("shareIdentifier")] public Input<string>? ShareIdentifier { get; set; } [Input("weightFactor")] public Input<double>? WeightFactor { get; set; } public SchedulingPolicyShareAttributesArgs() { } } } ======================= File: sdk/dotnet/Lightsail/LoadBalancer.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.Lightsail { /// <summary> /// Resource Type definition for AWS::Lightsail::LoadBalancer /// </summary> [AwsNativeResourceType("aws-native:lightsail:LoadBalancer")] public partial class LoadBalancer : Pulumi.CustomResource { /// <summary> /// The names of the instances attached to the load balancer. /// </summary> [Output("attachedInstances")] public Output<ImmutableArray<string>> AttachedInstances { get; private set; } = null!; /// <summary> /// The path you provided to perform the load balancer health check. If you didn't specify a health check path, Lightsail uses the root path of your website (e.g., "/"). /// </summary> [Output("healthCheckPath")] public Output<string?> HealthCheckPath { get; private set; } = null!; /// <summary> /// The instance port where you're creating your load balancer. /// </summary> [Output("instancePort")] public Output<int> InstancePort { get; private set; } = null!; /// <summary> /// The IP address type for the load balancer. The possible values are ipv4 for IPv4 only, and dualstack for IPv4 and IPv6. The default value is dualstack. /// </summary> [Output("ipAddressType")] public Output<string?> IpAddressType { get; private set; } = null!; [Output("loadBalancerArn")] public Output<string> LoadBalancerArn { get; private set; } = null!; /// <summary> /// The name of your load balancer. /// </summary> [Output("loadBalancerName")] public Output<string> LoadBalancerName { get; private set; } = null!; /// <summary> /// Configuration option to enable session stickiness. /// </summary> [Output("sessionStickinessEnabled")] public Output<bool?> SessionStickinessEnabled { get; private set; } = null!; /// <summary> /// Configuration option to adjust session stickiness cookie duration parameter. /// </summary> [Output("sessionStickinessLBCookieDurationSeconds")] public Output<string?> SessionStickinessLBCookieDurationSeconds { get; private set; } = null!; /// <summary> /// An array of key-value pairs to apply to this resource. /// </summary> [Output("tags")] public Output<ImmutableArray<Outputs.LoadBalancerTag>> Tags { get; private set; } = null!; /// <summary> /// Create a LoadBalancer resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public LoadBalancer(string name, LoadBalancerArgs args, CustomResourceOptions? options = null) : base("aws-native:lightsail:LoadBalancer", name, args?? new LoadBalancerArgs(), MakeResourceOptions(options, "")) { } private LoadBalancer(string name, Input<string> id, CustomResourceOptions? options = null) : base("aws-native:lightsail:LoadBalancer", name, null, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id?? merged.Id; return merged; } /// <summary> /// Get an existing LoadBalancer resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static LoadBalancer Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new LoadBalancer(name, id, options); } } public sealed class LoadBalancerArgs : Pulumi.ResourceArgs { [Input("attachedInstances")] private InputList<string>? _attachedInstances; /// <summary> /// The names of the instances attached to the load balancer. /// </summary> public InputList<string> AttachedInstances { get => _attachedInstances?? (_attachedInstances = new InputList<string>()); set => _attachedInstances = value; } /// <summary> /// The path you provided to perform the load balancer health check. If you didn't specify a health check path, Lightsail uses the root path of your website (e.g., "/"). /// </summary> [Input("healthCheckPath")] public Input<string>? HealthCheckPath { get; set; } /// <summary> /// The instance port where you're creating your load balancer. /// </summary> [Input("instancePort", required: true)] public Input<int> InstancePort { get; set; } = null!; /// <summary> /// The IP address type for the load balancer. The possible values are ipv4 for IPv4 only, and dualstack for IPv4 and IPv6. The default value is dualstack. /// </summary> [Input("ipAddressType")] public Input<string>? IpAddressType { get; set; } /// <summary> /// The name of your load balancer. /// </summary> [Input("loadBalancerName")] public Input<string>? LoadBalancerName { get; set; } /// <summary> /// Configuration option to enable session stickiness. /// </summary> [Input("sessionStickinessEnabled")] public Input<bool>? SessionStickinessEnabled { get; set; } /// <summary> /// Configuration option to adjust session stickiness cookie duration parameter. /// </summary> [Input("sessionStickinessLBCookieDurationSeconds")] public Input<string>? SessionStickinessLBCookieDurationSeconds { get; set; } [Input("tags")] private InputList<Inputs.LoadBalancerTagArgs>? _tags; /// <summary> /// An array of key-value pairs to apply to this resource. /// </summary> public InputList<Inputs.LoadBalancerTagArgs> Tags { get => _tags?? (_tags = new InputList<Inputs.LoadBalancerTagArgs>()); set => _tags = value; } public LoadBalancerArgs() { } } } ======================= File: sdk/dotnet/Route53Resolver/Enums.cs ======================= <reponame>AaronFriel/pulumi-aws-native<filename>sdk/dotnet/Route53Resolver/Enums.cs // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.ComponentModel; using Pulumi; namespace Pulumi.AwsNative.Route53Resolver { /// <summary> /// ResolverFirewallDomainList, possible values are COMPLETE, DELETING, UPDATING, COMPLETE_IMPORT_FAILED, IMPORTING, and INACTIVE_OWNER_ACCOUNT_CLOSED. /// </summary> [EnumType] public readonly struct FirewallDomainListStatus : IEquatable<FirewallDomainListStatus> { private readonly string _value; private FirewallDomainListStatus(string value) { _value = value?? throw new ArgumentNullException(nameof(value)); } public static FirewallDomainListStatus Complete { get; } = new FirewallDomainListStatus("COMPLETE"); public static FirewallDomainListStatus Deleting { get; } = new FirewallDomainListStatus("DELETING"); public static FirewallDomainListStatus Updating { get; } = new FirewallDomainListStatus("UPDATING"); public static FirewallDomainListStatus CompleteImportFailed { get; } = new FirewallDomainListStatus("COMPLETE_IMPORT_FAILED"); public static FirewallDomainListStatus Importing { get; } = new FirewallDomainListStatus("IMPORTING"); public static FirewallDomainListStatus InactiveOwnerAccountClosed { get; } = new FirewallDomainListStatus("INACTIVE_OWNER_ACCOUNT_CLOSED"); public static bool operator ==(FirewallDomainListStatus left, FirewallDomainListStatus right) => left.Equals(right); public static bool operator!=(FirewallDomainListStatus left, FirewallDomainListStatus right) =>!left.Equals(right); public static explicit operator string(FirewallDomainListStatus value) => value._value; [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) => obj is FirewallDomainListStatus other && Equals(other); public bool Equals(FirewallDomainListStatus other) => string.Equals(_value, other._value, StringComparison.Ordinal); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value?.GetHashCode()?? 0; public override string ToString() => _value; } /// <summary> /// MutationProtectionStatus /// </summary> [EnumType] public readonly struct FirewallRuleGroupAssociationMutationProtection : IEquatable<FirewallRuleGroupAssociationMutationProtection> { private readonly string _value; private FirewallRuleGroupAssociationMutationProtection(string value) { _value = value?? throw new ArgumentNullException(nameof(value)); } public static FirewallRuleGroupAssociationMutationProtection Enabled { get; } = new FirewallRuleGroupAssociationMutationProtection("ENABLED"); public static FirewallRuleGroupAssociationMutationProtection Disabled { get; } = new FirewallRuleGroupAssociationMutationProtection("DISABLED"); public static bool operator ==(FirewallRuleGroupAssociationMutationProtection left, FirewallRuleGroupAssociationMutationProtection right) => left.Equals(right); public static bool operator!=(FirewallRuleGroupAssociationMutationProtection left, FirewallRuleGroupAssociationMutationProtection right) =>!left.Equals(right); public static explicit operator string(FirewallRuleGroupAssociationMutationProtection value) => value._value; [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) => obj is FirewallRuleGroupAssociationMutationProtection other && Equals(other); public bool Equals(FirewallRuleGroupAssociationMutationProtection other) => string.Equals(_value, other._value, StringComparison.Ordinal); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value?.GetHashCode()?? 0; public override string ToString() => _value; } /// <summary> /// ResolverFirewallRuleGroupAssociation, possible values are COMPLETE, DELETING, UPDATING, and INACTIVE_OWNER_ACCOUNT_CLOSED. /// </summary> [EnumType] public readonly struct FirewallRuleGroupAssociationStatus : IEquatable<FirewallRuleGroupAssociationStatus> { private readonly string _value; private FirewallRuleGroupAssociationStatus(string value) { _value = value?? throw new ArgumentNullException(nameof(value)); } public static FirewallRuleGroupAssociationStatus Complete { get; } = new FirewallRuleGroupAssociationStatus("COMPLETE"); public static FirewallRuleGroupAssociationStatus Deleting { get; } = new FirewallRuleGroupAssociationStatus("DELETING"); public static FirewallRuleGroupAssociationStatus Updating { get; } = new FirewallRuleGroupAssociationStatus("UPDATING"); public static FirewallRuleGroupAssociationStatus InactiveOwnerAccountClosed { get; } = new FirewallRuleGroupAssociationStatus("INACTIVE_OWNER_ACCOUNT_CLOSED"); public static bool operator ==(FirewallRuleGroupAssociationStatus left, FirewallRuleGroupAssociationStatus right) => left.Equals(right); public static bool operator!=(FirewallRuleGroupAssociationStatus left, FirewallRuleGroupAssociationStatus right) =>!left.Equals(right); public static explicit operator string(FirewallRuleGroupAssociationStatus value) => value._value; [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) => obj is FirewallRuleGroupAssociationStatus other && Equals(other); public bool Equals(FirewallRuleGroupAssociationStatus other) => string.Equals(_value, other._value, StringComparison.Ordinal); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value?.GetHashCode()?? 0; public override string ToString() => _value; } /// <summary> /// Rule Action /// </summary> [EnumType] public readonly struct FirewallRuleGroupFirewallRuleAction : IEquatable<FirewallRuleGroupFirewallRuleAction> { private readonly string _value; private FirewallRuleGroupFirewallRuleAction(string value) { _value = value?? throw new ArgumentNullException(nameof(value)); } public static FirewallRuleGroupFirewallRuleAction Allow { get; } = new FirewallRuleGroupFirewallRuleAction("ALLOW"); public static FirewallRuleGroupFirewallRuleAction Block { get; } = new FirewallRuleGroupFirewallRuleAction("BLOCK"); public static FirewallRuleGroupFirewallRuleAction Alert { get; } = new FirewallRuleGroupFirewallRuleAction("ALERT"); public static bool operator ==(FirewallRuleGroupFirewallRuleAction left, FirewallRuleGroupFirewallRuleAction right) => left.Equals(right); public static bool operator!=(FirewallRuleGroupFirewallRuleAction left, FirewallRuleGroupFirewallRuleAction right) =>!left.Equals(right); public static explicit operator string(FirewallRuleGroupFirewallRuleAction value) => value._value; [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) => obj is FirewallRuleGroupFirewallRuleAction other && Equals(other); public bool Equals(FirewallRuleGroupFirewallRuleAction other) => string.Equals(_value, other._value, StringComparison.Ordinal); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value?.GetHashCode()?? 0; public override string ToString() => _value; } /// <summary> /// BlockOverrideDnsType /// </summary> [EnumType] public readonly struct FirewallRuleGroupFirewallRuleBlockOverrideDnsType : IEquatable<FirewallRuleGroupFirewallRuleBlockOverrideDnsType> { private readonly string _value; private FirewallRuleGroupFirewallRuleBlockOverrideDnsType(string value) { _value = value?? throw new ArgumentNullException(nameof(value)); } public static FirewallRuleGroupFirewallRuleBlockOverrideDnsType Cname { get; } = new FirewallRuleGroupFirewallRuleBlockOverrideDnsType("CNAME"); public static bool operator ==(FirewallRuleGroupFirewallRuleBlockOverrideDnsType left, FirewallRuleGroupFirewallRuleBlockOverrideDnsType right) => left.Equals(right); public static bool operator!=(FirewallRuleGroupFirewallRuleBlockOverrideDnsType left, FirewallRuleGroupFirewallRuleBlockOverrideDnsType right) =>!left.Equals(right); public static explicit operator string(FirewallRuleGroupFirewallRuleBlockOverrideDnsType value) => value._value; [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) => obj is FirewallRuleGroupFirewallRuleBlockOverrideDnsType other && Equals(other); public bool Equals(FirewallRuleGroupFirewallRuleBlockOverrideDnsType other) => string.Equals(_value, other._value, StringComparison.Ordinal); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value?.GetHashCode()?? 0; public override string ToString() => _value; } /// <summary> /// BlockResponse /// </summary> [EnumType] public readonly struct FirewallRuleGroupFirewallRuleBlockResponse : IEquatable<FirewallRuleGroupFirewallRuleBlockResponse> { private readonly string _value; private FirewallRuleGroupFirewallRuleBlockResponse(string value) { _value = value?? throw new ArgumentNullException(nameof(value)); } public static FirewallRuleGroupFirewallRuleBlockResponse Nodata { get; } = new FirewallRuleGroupFirewallRuleBlockResponse("NODATA"); public static FirewallRuleGroupFirewallRuleBlockResponse Nxdomain { get; } = new FirewallRuleGroupFirewallRuleBlockResponse("NXDOMAIN"); public static FirewallRuleGroupFirewallRuleBlockResponse Override { get; } = new FirewallRuleGroupFirewallRuleBlockResponse("OVERRIDE"); public static bool operator ==(FirewallRuleGroupFirewallRuleBlockResponse left, FirewallRuleGroupFirewallRuleBlockResponse right) => left.Equals(right); public static bool operator!=(FirewallRuleGroupFirewallRuleBlockResponse left, FirewallRuleGroupFirewallRuleBlockResponse right) =>!left.Equals(right); public static explicit operator string(FirewallRuleGroupFirewallRuleBlockResponse value) => value._value; [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) => obj is FirewallRuleGroupFirewallRuleBlockResponse other && Equals(other); public bool Equals(FirewallRuleGroupFirewallRuleBlockResponse other) => string.Equals(_value, other._value, StringComparison.Ordinal); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value?.GetHashCode()?? 0; public override string ToString() => _value; } /// <summary> /// ShareStatus, possible values are NOT_SHARED, SHARED_WITH_ME, SHARED_BY_ME. /// </summary> [EnumType] public readonly struct FirewallRuleGroupShareStatus : IEquatable<FirewallRuleGroupShareStatus> { private readonly string _value; private FirewallRuleGroupShareStatus(string value) { _value = value?? throw new ArgumentNullException(nameof(value)); } public static FirewallRuleGroupShareStatus NotShared { get; } = new FirewallRuleGroupShareStatus("NOT_SHARED"); public static FirewallRuleGroupShareStatus SharedWithMe { get; } = new FirewallRuleGroupShareStatus("SHARED_WITH_ME"); public static FirewallRuleGroupShareStatus SharedByMe { get; } = new FirewallRuleGroupShareStatus("SHARED_BY_ME"); public static bool operator ==(FirewallRuleGroupShareStatus left, FirewallRuleGroupShareStatus right) => left.Equals(right); public static bool operator!=(FirewallRuleGroupShareStatus left, FirewallRuleGroupShareStatus right) =>!left.Equals(right); public static explicit operator string(FirewallRuleGroupShareStatus value) => value._value; [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) => obj is FirewallRuleGroupShareStatus other && Equals(other); public bool Equals(FirewallRuleGroupShareStatus other) => string.Equals(_value, other._value, StringComparison.Ordinal); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value?.GetHashCode()?? 0; public override string ToString() => _value; } /// <summary> /// ResolverFirewallRuleGroupAssociation, possible values are COMPLETE, DELETING, UPDATING, and INACTIVE_OWNER_ACCOUNT_CLOSED. /// </summary> [EnumType] public readonly struct FirewallRuleGroupStatus : IEquatable<FirewallRuleGroupStatus> { private readonly string _value; private FirewallRuleGroupStatus(string value) { _value = value?? throw new ArgumentNullException(nameof(value)); } public static FirewallRuleGroupStatus Complete { get; } = new FirewallRuleGroupStatus("COMPLETE"); public static FirewallRuleGroupStatus Deleting { get; } = new FirewallRuleGroupStatus("DELETING"); public static FirewallRuleGroupStatus Updating { get; } = new FirewallRuleGroupStatus("UPDATING"); public static FirewallRuleGroupStatus InactiveOwnerAccountClosed { get; } = new FirewallRuleGroupStatus("INACTIVE_OWNER_ACCOUNT_CLOSED"); public static bool operator ==(FirewallRuleGroupStatus left, FirewallRuleGroupStatus right) => left.Equals(right); public static bool operator!=(FirewallRuleGroupStatus left, FirewallRuleGroupStatus right) =>!left.Equals(right); public static explicit operator string(FirewallRuleGroupStatus value) => value._value; [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) => obj is FirewallRuleGroupStatus other && Equals(other); public bool Equals(FirewallRuleGroupStatus other) => string.Equals(_value, other._value, StringComparison.Ordinal); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value?.GetHashCode()?? 0; public override string ToString() => _value; } /// <summary> /// ResolverAutodefinedReverseStatus, possible values are ENABLING, ENABLED, DISABLING AND DISABLED. /// </summary> [EnumType] public readonly struct ResolverConfigAutodefinedReverse : IEquatable<ResolverConfigAutodefinedReverse> { private readonly string _value; private ResolverConfigAutodefinedReverse(string value) { _value = value?? throw new ArgumentNullException(nameof(value)); } public static ResolverConfigAutodefinedReverse Enabling { get; } = new ResolverConfigAutodefinedReverse("ENABLING"); public static ResolverConfigAutodefinedReverse Enabled { get; } = new ResolverConfigAutodefinedReverse("ENABLED"); public static ResolverConfigAutodefinedReverse Disabling { get; } = new ResolverConfigAutodefinedReverse("DISABLING"); public static ResolverConfigAutodefinedReverse Disabled { get; } = new ResolverConfigAutodefinedReverse("DISABLED"); public static bool operator ==(ResolverConfigAutodefinedReverse left, ResolverConfigAutodefinedReverse right) => left.Equals(right); public static bool operator!=(ResolverConfigAutodefinedReverse left, ResolverConfigAutodefinedReverse right) =>!left.Equals(right); public static explicit operator string(ResolverConfigAutodefinedReverse value) => value._value; [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) => obj is ResolverConfigAutodefinedReverse other && Equals(other); public bool Equals(ResolverConfigAutodefinedReverse other) => string.Equals(_value, other._value, StringComparison.Ordinal); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value?.GetHashCode()?? 0; public override string ToString() => _value; } /// <summary> /// Represents the desired status of AutodefinedReverse. The only supported value on creation is DISABLE. Deletion of this resource will return AutodefinedReverse to its default value (ENABLED). /// </summary> [EnumType] public readonly struct ResolverConfigAutodefinedReverseFlag : IEquatable<ResolverConfigAutodefinedReverseFlag> { private readonly string _value; private ResolverConfigAutodefinedReverseFlag(string value) { _value = value?? throw new ArgumentNullException(nameof(value)); } public static ResolverConfigAutodefinedReverseFlag Disable { get; } = new ResolverConfigAutodefinedReverseFlag("DISABLE"); public static bool operator ==(ResolverConfigAutodefinedReverseFlag left, ResolverConfigAutodefinedReverseFlag right) => left.Equals(right); public static bool operator!=(ResolverConfigAutodefinedReverseFlag left, ResolverConfigAutodefinedReverseFlag right) =>!left.Equals(right); public static explicit operator string(ResolverConfigAutodefinedReverseFlag value) => value._value; [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) => obj is ResolverConfigAutodefinedReverseFlag other && Equals(other); public bool Equals(ResolverConfigAutodefinedReverseFlag other) => string.Equals(_value, other._value, StringComparison.Ordinal); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value?.GetHashCode()?? 0; public override string ToString() => _value; } /// <summary> /// ResolverDNSSECValidationStatus, possible values are ENABLING, ENABLED, DISABLING AND DISABLED. /// </summary> [EnumType] public readonly struct ResolverDNSSECConfigValidationStatus : IEquatable<ResolverDNSSECConfigValidationStatus> { private readonly string _value; private ResolverDNSSECConfigValidationStatus(string value) { _value = value?? throw new ArgumentNullException(nameof(value)); } public static ResolverDNSSECConfigValidationStatus Enabling { get; } = new ResolverDNSSECConfigValidationStatus("ENABLING"); public static ResolverDNSSECConfigValidationStatus Enabled { get; } = new ResolverDNSSECConfigValidationStatus("ENABLED"); public static ResolverDNSSECConfigValidationStatus Disabling { get; } = new ResolverDNSSECConfigValidationStatus("DISABLING"); public static ResolverDNSSECConfigValidationStatus Disabled { get; } = new ResolverDNSSECConfigValidationStatus("DISABLED"); public static bool operator ==(ResolverDNSSECConfigValidationStatus left, ResolverDNSSECConfigValidationStatus right) => left.Equals(right); public static bool operator!=(ResolverDNSSECConfigValidationStatus left, ResolverDNSSECConfigValidationStatus right) =>!left.Equals(right); public static explicit operator string(ResolverDNSSECConfigValidationStatus value) => value._value; [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) => obj is ResolverDNSSECConfigValidationStatus other && Equals(other); public bool Equals(ResolverDNSSECConfigValidationStatus other) => string.Equals(_value, other._value, StringComparison.Ordinal); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value?.GetHashCode()?? 0; public override string ToString() => _value; } /// <summary> /// ResolverQueryLogConfigAssociationError /// </summary> [EnumType] public readonly struct ResolverQueryLoggingConfigAssociationError : IEquatable<ResolverQueryLoggingConfigAssociationError> { private readonly string _value; private ResolverQueryLoggingConfigAssociationError(string value) { _value = value?? throw new ArgumentNullException(nameof(value)); } public static ResolverQueryLoggingConfigAssociationError None { get; } = new ResolverQueryLoggingConfigAssociationError("NONE"); public static ResolverQueryLoggingConfigAssociationError DestinationNotFound { get; } = new ResolverQueryLoggingConfigAssociationError("DESTINATION_NOT_FOUND"); public static ResolverQueryLoggingConfigAssociationError AccessDenied { get; } = new ResolverQueryLoggingConfigAssociationError("ACCESS_DENIED"); public static bool operator ==(ResolverQueryLoggingConfigAssociationError left, ResolverQueryLoggingConfigAssociationError right) => left.Equals(right); public static bool operator!=(ResolverQueryLoggingConfigAssociationError left, ResolverQueryLoggingConfigAssociationError right) =>!left.Equals(right); public static explicit operator string(ResolverQueryLoggingConfigAssociationError value) => value._value; [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) => obj is ResolverQueryLoggingConfigAssociationError other && Equals(other); public bool Equals(ResolverQueryLoggingConfigAssociationError other) => string.Equals(_value, other._value, StringComparison.Ordinal); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value?.GetHashCode()?? 0; public override string ToString() => _value; } /// <summary> /// ResolverQueryLogConfigAssociationStatus /// </summary> [EnumType] public readonly struct ResolverQueryLoggingConfigAssociationStatus : IEquatable<ResolverQueryLoggingConfigAssociationStatus> { private readonly string _value; private ResolverQueryLoggingConfigAssociationStatus(string value) { _value = value?? throw new ArgumentNullException(nameof(value)); } public static ResolverQueryLoggingConfigAssociationStatus Creating { get; } = new ResolverQueryLoggingConfigAssociationStatus("CREATING"); public static ResolverQueryLoggingConfigAssociationStatus Active { get; } = new ResolverQueryLoggingConfigAssociationStatus("ACTIVE"); public static ResolverQueryLoggingConfigAssociationStatus ActionNeeded { get; } = new ResolverQueryLoggingConfigAssociationStatus("ACTION_NEEDED"); public static ResolverQueryLoggingConfigAssociationStatus Deleting { get; } = new ResolverQueryLoggingConfigAssociationStatus("DELETING"); public static ResolverQueryLoggingConfigAssociationStatus Failed { get; } = new ResolverQueryLoggingConfigAssociationStatus("FAILED"); public static ResolverQueryLoggingConfigAssociationStatus Overridden { get; } = new ResolverQueryLoggingConfigAssociationStatus("OVERRIDDEN"); public static bool operator ==(ResolverQueryLoggingConfigAssociationStatus left, ResolverQueryLoggingConfigAssociationStatus right) => left.Equals(right); public static bool operator!=(ResolverQueryLoggingConfigAssociationStatus left, ResolverQueryLoggingConfigAssociationStatus right) =>!left.Equals(right); public static explicit operator string(ResolverQueryLoggingConfigAssociationStatus value) => value._value; [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) => obj is ResolverQueryLoggingConfigAssociationStatus other && Equals(other); public bool Equals(ResolverQueryLoggingConfigAssociationStatus other) => string.Equals(_value, other._value, StringComparison.Ordinal); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value?.GetHashCode()?? 0; public override string ToString() => _value; } /// <summary> /// ShareStatus, possible values are NOT_SHARED, SHARED_WITH_ME, SHARED_BY_ME. /// </summary> [EnumType] public readonly struct ResolverQueryLoggingConfigShareStatus : IEquatable<ResolverQueryLoggingConfigShareStatus> { private readonly string _value; private ResolverQueryLoggingConfigShareStatus(string value) { _value = value?? throw new ArgumentNullException(nameof(value)); } public static ResolverQueryLoggingConfigShareStatus NotShared { get; } = new ResolverQueryLoggingConfigShareStatus("NOT_SHARED"); public static ResolverQueryLoggingConfigShareStatus SharedWithMe { get; } = new ResolverQueryLoggingConfigShareStatus("SHARED_WITH_ME"); public static ResolverQueryLoggingConfigShareStatus SharedByMe { get; } = new ResolverQueryLoggingConfigShareStatus("SHARED_BY_ME"); public static bool operator ==(ResolverQueryLoggingConfigShareStatus left, ResolverQueryLoggingConfigShareStatus right) => left.Equals(right); public static bool operator!=(ResolverQueryLoggingConfigShareStatus left, ResolverQueryLoggingConfigShareStatus right) =>!left.Equals(right); public static explicit operator string(ResolverQueryLoggingConfigShareStatus value) => value._value; [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) => obj is ResolverQueryLoggingConfigShareStatus other && Equals(other); public bool Equals(ResolverQueryLoggingConfigShareStatus other) => string.Equals(_value, other._value, StringComparison.Ordinal); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value?.GetHashCode()?? 0; public override string ToString() => _value; } /// <summary> /// ResolverQueryLogConfigStatus, possible values are CREATING, CREATED, DELETED AND FAILED. /// </summary> [EnumType] public readonly struct ResolverQueryLoggingConfigStatus : IEquatable<ResolverQueryLoggingConfigStatus> { private readonly string _value; private ResolverQueryLoggingConfigStatus(string value) { _value = value?? throw new ArgumentNullException(nameof(value)); } public static ResolverQueryLoggingConfigStatus Creating { get; } = new ResolverQueryLoggingConfigStatus("CREATING"); public static ResolverQueryLoggingConfigStatus Created { get; } = new ResolverQueryLoggingConfigStatus("CREATED"); public static ResolverQueryLoggingConfigStatus Deleting { get; } = new ResolverQueryLoggingConfigStatus("DELETING"); public static ResolverQueryLoggingConfigStatus Failed { get; } = new ResolverQueryLoggingConfigStatus("FAILED"); public static bool operator ==(ResolverQueryLoggingConfigStatus left, ResolverQueryLoggingConfigStatus right) => left.Equals(right); public static bool operator!=(ResolverQueryLoggingConfigStatus left, ResolverQueryLoggingConfigStatus right) =>!left.Equals(right); public static explicit operator string(ResolverQueryLoggingConfigStatus value) => value._value; [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) => obj is ResolverQueryLoggingConfigStatus other && Equals(other); public bool Equals(ResolverQueryLoggingConfigStatus other) => string.Equals(_value, other._value, StringComparison.Ordinal); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value?.GetHashCode()?? 0; public override string ToString() => _value; } /// <summary> /// When you want to forward DNS queries for specified domain name to resolvers on your network, specify FORWARD. When you have a forwarding rule to forward DNS queries for a domain to your network and you want Resolver to process queries for a subdomain of that domain, specify SYSTEM. /// </summary> [EnumType] public readonly struct ResolverRuleRuleType : IEquatable<ResolverRuleRuleType> { private readonly string _value; private ResolverRuleRuleType(string value) { _value = value?? throw new ArgumentNullException(nameof(value)); } public static ResolverRuleRuleType Forward { get; } = new ResolverRuleRuleType("FORWARD"); public static ResolverRuleRuleType System { get; } = new ResolverRuleRuleType("SYSTEM"); public static ResolverRuleRuleType Recursive { get; } = new ResolverRuleRuleType("RECURSIVE"); public static bool operator ==(ResolverRuleRuleType left, ResolverRuleRuleType right) => left.Equals(right); public static bool operator!=(ResolverRuleRuleType left, ResolverRuleRuleType right) =>!left.Equals(right); public static explicit operator string(ResolverRuleRuleType value) => value._value; [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) => obj is ResolverRuleRuleType other && Equals(other); public bool Equals(ResolverRuleRuleType other) => string.Equals(_value, other._value, StringComparison.Ordinal); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value?.GetHashCode()?? 0; public override string ToString() => _value; } } ======================= File: sdk/dotnet/QuickSight/Inputs/ThemeTileLayoutStyleArgs.cs ======================= <filename>sdk/dotnet/QuickSight/Inputs/ThemeTileLayoutStyleArgs.cs // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.QuickSight.Inputs { /// <summary> /// &lt;p&gt;The display options for the layout of tiles on a sheet.&lt;/p&gt; /// </summary> public sealed class ThemeTileLayoutStyleArgs : Pulumi.ResourceArgs { [Input("gutter")] public Input<Inputs.ThemeGutterStyleArgs>? Gutter { get; set; } [Input("margin")] public Input<Inputs.ThemeMarginStyleArgs>? Margin { get; set; } public ThemeTileLayoutStyleArgs() { } } } ======================= File: sdk/dotnet/QuickSight/Outputs/TemplateDataSetConfiguration.cs ======================= <reponame>AaronFriel/pulumi-aws-native // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.QuickSight.Outputs { /// <summary> /// &lt;p&gt;Dataset configuration.&lt;/p&gt; /// </summary> [OutputType] public sealed class TemplateDataSetConfiguration { /// <summary> /// &lt;p&gt;A structure containing the list of column group schemas.&lt;/p&gt; /// </summary> public readonly ImmutableArray<Outputs.TemplateColumnGroupSchema> ColumnGroupSchemaList; public readonly Outputs.TemplateDataSetSchema? DataSetSchema; /// <summary> /// &lt;p&gt;Placeholder.&lt;/p&gt; /// </summary> public readonly string? Placeholder; [OutputConstructor] private TemplateDataSetConfiguration( ImmutableArray<Outputs.TemplateColumnGroupSchema> columnGroupSchemaList, Outputs.TemplateDataSetSchema? dataSetSchema, string? placeholder) { ColumnGroupSchemaList = columnGroupSchemaList; DataSetSchema = dataSetSchema; Placeholder = placeholder; } } } ======================= File: sdk/dotnet/AppMesh/Outputs/VirtualGatewayClientPolicyTls.cs ======================= <filename>sdk/dotnet/AppMesh/Outputs/VirtualGatewayClientPolicyTls.cs<gh_stars>10-100 // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.AppMesh.Outputs { [OutputType] public sealed class VirtualGatewayClientPolicyTls { public readonly Outputs.VirtualGatewayClientTlsCertificate? Certificate; public readonly bool? Enforce; public readonly ImmutableArray<int> Ports; public readonly Outputs.VirtualGatewayTlsValidationContext Validation; [OutputConstructor] private VirtualGatewayClientPolicyTls( Outputs.VirtualGatewayClientTlsCertificate? certificate, bool? enforce, ImmutableArray<int> ports, Outputs.VirtualGatewayTlsValidationContext validation) { Certificate = certificate; Enforce = enforce; Ports = ports; Validation = validation; } } } ======================= File: sdk/dotnet/EMR/Inputs/ClusterHadoopJarStepConfigArgs.cs ======================= <filename>sdk/dotnet/EMR/Inputs/ClusterHadoopJarStepConfigArgs.cs // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.EMR.Inputs { public sealed class ClusterHadoopJarStepConfigArgs : Pulumi.ResourceArgs { [Input("args")] private InputList<string>? _args; public InputList<string> Args { get => _args?? (_args = new InputList<string>()); set => _args = value; } [Input("jar", required: true)] public Input<string> Jar { get; set; } = null!; [Input("mainClass")] public Input<string>? MainClass { get; set; } [Input("stepProperties")] private InputList<Inputs.ClusterKeyValueArgs>? _stepProperties; public InputList<Inputs.ClusterKeyValueArgs> StepProperties { get => _stepProperties?? (_stepProperties = new InputList<Inputs.ClusterKeyValueArgs>()); set => _stepProperties = value; } public ClusterHadoopJarStepConfigArgs() { } } } ======================= File: sdk/dotnet/MediaLive/Outputs/ChannelNielsenWatermarksSettings.cs ======================= <gh_stars>10-100 // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.MediaLive.Outputs { [OutputType] public sealed class ChannelNielsenWatermarksSettings { public readonly Outputs.ChannelNielsenCBET? NielsenCbetSettings; public readonly string? NielsenDistributionType; public readonly Outputs.ChannelNielsenNaesIiNw? NielsenNaesIiNwSettings; [OutputConstructor] private ChannelNielsenWatermarksSettings( Outputs.ChannelNielsenCBET? nielsenCbetSettings, string? nielsenDistributionType, Outputs.ChannelNielsenNaesIiNw? nielsenNaesIiNwSettings) { NielsenCbetSettings = nielsenCbetSettings; NielsenDistributionType = nielsenDistributionType; NielsenNaesIiNwSettings = nielsenNaesIiNwSettings; } } } ======================= File: sdk/dotnet/S3/Outputs/BucketObjectLockRule.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.S3.Outputs { /// <summary> /// The Object Lock rule in place for the specified object. /// </summary> [OutputType] public sealed class BucketObjectLockRule { public readonly Outputs.BucketDefaultRetention? DefaultRetention; [OutputConstructor] private BucketObjectLockRule(Outputs.BucketDefaultRetention? defaultRetention) { DefaultRetention = defaultRetention; } } } ======================= File: sdk/dotnet/EC2/Inputs/LaunchTemplateCpuOptionsArgs.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.EC2.Inputs { public sealed class LaunchTemplateCpuOptionsArgs : Pulumi.ResourceArgs { [Input("coreCount")] public Input<int>? CoreCount { get; set; } [Input("threadsPerCore")] public Input<int>? ThreadsPerCore { get; set; } public LaunchTemplateCpuOptionsArgs() { } } } ======================= File: sdk/dotnet/ImageBuilder/Outputs/DistributionConfigurationDistributionAmiDistributionConfigurationPropertiesLaunchPermissionConfigurationProperties.cs ======================= <reponame>AaronFriel/pulumi-aws-native // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.ImageBuilder.Outputs { /// <summary> /// Launch permissions can be used to configure which AWS accounts can use the AMI to launch instances. /// </summary> [OutputType] public sealed class DistributionConfigurationDistributionAmiDistributionConfigurationPropertiesLaunchPermissionConfigurationProperties { /// <summary> /// The ARN for an Amazon Web Services Organization that you want to share your AMI with. /// </summary> public readonly ImmutableArray<string> OrganizationArns; /// <summary> /// The ARN for an Organizations organizational unit (OU) that you want to share your AMI with. /// </summary> public readonly ImmutableArray<string> OrganizationalUnitArns; /// <summary> /// The name of the group. /// </summary> public readonly ImmutableArray<string> UserGroups; /// <summary> /// The AWS account ID. /// </summary> public readonly ImmutableArray<string> UserIds; [OutputConstructor] private DistributionConfigurationDistributionAmiDistributionConfigurationPropertiesLaunchPermissionConfigurationProperties( ImmutableArray<string> organizationArns, ImmutableArray<string> organizationalUnitArns, ImmutableArray<string> userGroups, ImmutableArray<string> userIds) { OrganizationArns = organizationArns; OrganizationalUnitArns = organizationalUnitArns; UserGroups = userGroups; UserIds = userIds; } } } ======================= File: sdk/dotnet/Timestream/Inputs/ScheduledQueryMultiMeasureAttributeMappingArgs.cs ======================= <reponame>AaronFriel/pulumi-aws-native // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.Timestream.Inputs { /// <summary> /// An attribute mapping to be used for mapping query results to ingest data for multi-measure attributes. /// </summary> public sealed class ScheduledQueryMultiMeasureAttributeMappingArgs : Pulumi.ResourceArgs { [Input("measureValueType", required: true)] public Input<Pulumi.AwsNative.Timestream.ScheduledQueryMultiMeasureAttributeMappingMeasureValueType> MeasureValueType { get; set; } = null!; [Input("sourceColumn", required: true)] public Input<string> SourceColumn { get; set; } = null!; [Input("targetMultiMeasureAttributeName")] public Input<string>? TargetMultiMeasureAttributeName { get; set; } public ScheduledQueryMultiMeasureAttributeMappingArgs() { } } } ======================= File: sdk/dotnet/Lex/Outputs/BotMessage.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.Lex.Outputs { /// <summary> /// The primary message that Amazon Lex should send to the user. /// </summary> [OutputType] public sealed class BotMessage { public readonly Outputs.BotCustomPayload? CustomPayload; public readonly Outputs.BotImageResponseCard? ImageResponseCard; public readonly Outputs.BotPlainTextMessage? PlainTextMessage; public readonly Outputs.BotSSMLMessage? SSMLMessage; [OutputConstructor] private BotMessage( Outputs.BotCustomPayload? customPayload, Outputs.BotImageResponseCard? imageResponseCard, Outputs.BotPlainTextMessage? plainTextMessage, Outputs.BotSSMLMessage? sSMLMessage) { CustomPayload = customPayload; ImageResponseCard = imageResponseCard; PlainTextMessage = plainTextMessage; SSMLMessage = sSMLMessage; } } } ======================= File: sdk/dotnet/CloudFront/Outputs/DistributionStatusCodes.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.CloudFront.Outputs { [OutputType] public sealed class DistributionStatusCodes { public readonly ImmutableArray<int> Items; public readonly int Quantity; [OutputConstructor] private DistributionStatusCodes( ImmutableArray<int> items, int quantity) { Items = items; Quantity = quantity; } } } ======================= File: sdk/dotnet/IoTWireless/Inputs/WirelessDeviceSessionKeysAbpV11Args.cs ======================= <gh_stars>10-100 // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.IoTWireless.Inputs { public sealed class WirelessDeviceSessionKeysAbpV11Args : Pulumi.ResourceArgs { [Input("appSKey", required: true)] public Input<string> AppSKey { get; set; } = null!; [Input("fNwkSIntKey", required: true)] public Input<string> FNwkSIntKey { get; set; } = null!; [Input("nwkSEncKey", required: true)] public Input<string> NwkSEncKey { get; set; } = null!; [Input("sNwkSIntKey", required: true)] public Input<string> SNwkSIntKey { get; set; } = null!; public WirelessDeviceSessionKeysAbpV11Args() { } } } ======================= File: sdk/dotnet/MSK/Outputs/ClusterTls.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.MSK.Outputs { [OutputType] public sealed class ClusterTls { public readonly ImmutableArray<string> CertificateAuthorityArnList; public readonly bool? Enabled; [OutputConstructor] private ClusterTls( ImmutableArray<string> certificateAuthorityArnList, bool? enabled) { CertificateAuthorityArnList = certificateAuthorityArnList; Enabled = enabled; } } } ======================= File: sdk/dotnet/Backup/Inputs/ReportDeliveryChannelPropertiesArgs.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.Backup.Inputs { /// <summary> /// A structure that contains information about where and how to deliver your reports, specifically your Amazon S3 bucket name, S3 key prefix, and the formats of your reports. /// </summary> public sealed class ReportDeliveryChannelPropertiesArgs : Pulumi.ResourceArgs { [Input("formats")] private InputList<string>? _formats; /// <summary> /// A list of the format of your reports: CSV, JSON, or both. If not specified, the default format is CSV. /// </summary> public InputList<string> Formats { get => _formats?? (_formats = new InputList<string>()); set => _formats = value; } /// <summary> /// The unique name of the S3 bucket that receives your reports. /// </summary> [Input("s3BucketName", required: true)] public Input<string> S3BucketName { get; set; } = null!; /// <summary> /// The prefix for where AWS Backup Audit Manager delivers your reports to Amazon S3. The prefix is this part of the following path: s3://your-bucket-name/prefix/Backup/us-west-2/year/month/day/report-name. If not specified, there is no prefix. /// </summary> [Input("s3KeyPrefix")] public Input<string>? S3KeyPrefix { get; set; } public ReportDeliveryChannelPropertiesArgs() { } } } ======================= File: sdk/dotnet/SageMaker/Outputs/FeatureGroupDataCatalogConfig.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.SageMaker.Outputs { [OutputType] public sealed class FeatureGroupDataCatalogConfig { public readonly string Catalog; public readonly string Database; public readonly string TableName; [OutputConstructor] private FeatureGroupDataCatalogConfig( string catalog, string database, string tableName) { Catalog = catalog; Database = database; TableName = tableName; } } } ======================= File: sdk/dotnet/OpsWorks/Inputs/InstanceTimeBasedAutoScalingArgs.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.OpsWorks.Inputs { public sealed class InstanceTimeBasedAutoScalingArgs : Pulumi.ResourceArgs { [Input("friday")] public Input<object>? Friday { get; set; } [Input("monday")] public Input<object>? Monday { get; set; } [Input("saturday")] public Input<object>? Saturday { get; set; } [Input("sunday")] public Input<object>? Sunday { get; set; } [Input("thursday")] public Input<object>? Thursday { get; set; } [Input("tuesday")] public Input<object>? Tuesday { get; set; } [Input("wednesday")] public Input<object>? Wednesday { get; set; } public InstanceTimeBasedAutoScalingArgs() { } } } ======================= File: sdk/dotnet/SES/Inputs/ConfigurationSetEventDestinationDimensionConfigurationArgs.cs ======================= <filename>sdk/dotnet/SES/Inputs/ConfigurationSetEventDestinationDimensionConfigurationArgs.cs // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.SES.Inputs { public sealed class ConfigurationSetEventDestinationDimensionConfigurationArgs : Pulumi.ResourceArgs { [Input("defaultDimensionValue", required: true)] public Input<string> DefaultDimensionValue { get; set; } = null!; [Input("dimensionName", required: true)] public Input<string> DimensionName { get; set; } = null!; [Input("dimensionValueSource", required: true)] public Input<string> DimensionValueSource { get; set; } = null!; public ConfigurationSetEventDestinationDimensionConfigurationArgs() { } } } ======================= File: sdk/dotnet/MediaLive/Outputs/ChannelBlackoutSlate.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.MediaLive.Outputs { [OutputType] public sealed class ChannelBlackoutSlate { public readonly Outputs.ChannelInputLocation? BlackoutSlateImage; public readonly string? NetworkEndBlackout; public readonly Outputs.ChannelInputLocation? NetworkEndBlackoutImage; public readonly string? NetworkId; public readonly string? State; [OutputConstructor] private ChannelBlackoutSlate( Outputs.ChannelInputLocation? blackoutSlateImage, string? networkEndBlackout, Outputs.ChannelInputLocation? networkEndBlackoutImage, string? networkId, string? state) { BlackoutSlateImage = blackoutSlateImage; NetworkEndBlackout = networkEndBlackout; NetworkEndBlackoutImage = networkEndBlackoutImage; NetworkId = networkId; State = state; } } } ======================= File: sdk/dotnet/KinesisAnalytics/Inputs/ApplicationOutputResourceOutputArgs.cs ======================= <reponame>AaronFriel/pulumi-aws-native // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.KinesisAnalytics.Inputs { public sealed class ApplicationOutputResourceOutputArgs : Pulumi.ResourceArgs { [Input("destinationSchema", required: true)] public Input<Inputs.ApplicationOutputResourceDestinationSchemaArgs> DestinationSchema { get; set; } = null!; [Input("kinesisFirehoseOutput")] public Input<Inputs.ApplicationOutputResourceKinesisFirehoseOutputArgs>? KinesisFirehoseOutput { get; set; } [Input("kinesisStreamsOutput")] public Input<Inputs.ApplicationOutputResourceKinesisStreamsOutputArgs>? KinesisStreamsOutput { get; set; } [Input("lambdaOutput")] public Input<Inputs.ApplicationOutputResourceLambdaOutputArgs>? LambdaOutput { get; set; } [Input("name")] public Input<string>? Name { get; set; } public ApplicationOutputResourceOutputArgs() { } } } ======================= File: sdk/dotnet/Lambda/Inputs/EventInvokeConfigDestinationConfigArgs.cs ======================= <reponame>AaronFriel/pulumi-aws-native<gh_stars>10-100 // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.Lambda.Inputs { public sealed class EventInvokeConfigDestinationConfigArgs : Pulumi.ResourceArgs { [Input("onFailure")] public Input<Inputs.EventInvokeConfigOnFailureArgs>? OnFailure { get; set; } [Input("onSuccess")] public Input<Inputs.EventInvokeConfigOnSuccessArgs>? OnSuccess { get; set; } public EventInvokeConfigDestinationConfigArgs() { } } } ======================= File: sdk/dotnet/Kendra/Inputs/DataSourceConfluenceBlogConfigurationArgs.cs ======================= <filename>sdk/dotnet/Kendra/Inputs/DataSourceConfluenceBlogConfigurationArgs.cs // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.Kendra.Inputs { public sealed class DataSourceConfluenceBlogConfigurationArgs : Pulumi.ResourceArgs { [Input("blogFieldMappings")] private InputList<Inputs.DataSourceConfluenceBlogToIndexFieldMappingArgs>? _blogFieldMappings; public InputList<Inputs.DataSourceConfluenceBlogToIndexFieldMappingArgs> BlogFieldMappings { get => _blogFieldMappings?? (_blogFieldMappings = new InputList<Inputs.DataSourceConfluenceBlogToIndexFieldMappingArgs>()); set => _blogFieldMappings = value; } public DataSourceConfluenceBlogConfigurationArgs() { } } } ======================= File: sdk/dotnet/CloudWatch/Outputs/AnomalyDetectorConfiguration.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.CloudWatch.Outputs { [OutputType] public sealed class AnomalyDetectorConfiguration { public readonly ImmutableArray<Outputs.AnomalyDetectorRange> ExcludedTimeRanges; public readonly string? MetricTimeZone; [OutputConstructor] private AnomalyDetectorConfiguration( ImmutableArray<Outputs.AnomalyDetectorRange> excludedTimeRanges, string? metricTimeZone) { ExcludedTimeRanges = excludedTimeRanges; MetricTimeZone = metricTimeZone; } } } ======================= File: sdk/dotnet/IoT/Inputs/MitigationActionActionParamsArgs.cs ======================= <filename>sdk/dotnet/IoT/Inputs/MitigationActionActionParamsArgs.cs<gh_stars>10-100 // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.IoT.Inputs { /// <summary> /// The set of parameters for this mitigation action. You can specify only one type of parameter (in other words, you can apply only one action for each defined mitigation action). /// </summary> public sealed class MitigationActionActionParamsArgs : Pulumi.ResourceArgs { [Input("addThingsToThingGroupParams")] public Input<Inputs.MitigationActionAddThingsToThingGroupParamsArgs>? AddThingsToThingGroupParams { get; set; } [Input("enableIoTLoggingParams")] public Input<Inputs.MitigationActionEnableIoTLoggingParamsArgs>? EnableIoTLoggingParams { get; set; } [Input("publishFindingToSnsParams")] public Input<Inputs.MitigationActionPublishFindingToSnsParamsArgs>? PublishFindingToSnsParams { get; set; } [Input("replaceDefaultPolicyVersionParams")] public Input<Inputs.MitigationActionReplaceDefaultPolicyVersionParamsArgs>? ReplaceDefaultPolicyVersionParams { get; set; } [Input("updateCACertificateParams")] public Input<Inputs.MitigationActionUpdateCACertificateParamsArgs>? UpdateCACertificateParams { get; set; } [Input("updateDeviceCertificateParams")] public Input<Inputs.MitigationActionUpdateDeviceCertificateParamsArgs>? UpdateDeviceCertificateParams { get; set; } public MitigationActionActionParamsArgs() { } } } ======================= File: sdk/dotnet/AuditManager/Inputs/AssessmentScopeArgs.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.AuditManager.Inputs { /// <summary> /// The wrapper that contains the AWS accounts and AWS services in scope for the assessment. /// </summary> public sealed class AssessmentScopeArgs : Pulumi.ResourceArgs { [Input("awsAccounts")] private InputList<Inputs.AssessmentAWSAccountArgs>? _awsAccounts; /// <summary> /// The AWS accounts included in scope. /// </summary> public InputList<Inputs.AssessmentAWSAccountArgs> AwsAccounts { get => _awsAccounts?? (_awsAccounts = new InputList<Inputs.AssessmentAWSAccountArgs>()); set => _awsAccounts = value; } [Input("awsServices")] private InputList<Inputs.AssessmentAWSServiceArgs>? _awsServices; /// <summary> /// The AWS services included in scope. /// </summary> public InputList<Inputs.AssessmentAWSServiceArgs> AwsServices { get => _awsServices?? (_awsServices = new InputList<Inputs.AssessmentAWSServiceArgs>()); set => _awsServices = value; } public AssessmentScopeArgs() { } } } ======================= File: sdk/dotnet/KinesisAnalyticsV2/Outputs/ApplicationZeppelinApplicationConfiguration.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.KinesisAnalyticsV2.Outputs { [OutputType] public sealed class ApplicationZeppelinApplicationConfiguration { public readonly Outputs.ApplicationCatalogConfiguration? CatalogConfiguration; public readonly ImmutableArray<Outputs.ApplicationCustomArtifactConfiguration> CustomArtifactsConfiguration; public readonly Outputs.ApplicationDeployAsApplicationConfiguration? DeployAsApplicationConfiguration; public readonly Outputs.ApplicationZeppelinMonitoringConfiguration? MonitoringConfiguration; [OutputConstructor] private ApplicationZeppelinApplicationConfiguration( Outputs.ApplicationCatalogConfiguration? catalogConfiguration, ImmutableArray<Outputs.ApplicationCustomArtifactConfiguration> customArtifactsConfiguration, Outputs.ApplicationDeployAsApplicationConfiguration? deployAsApplicationConfiguration, Outputs.ApplicationZeppelinMonitoringConfiguration? monitoringConfiguration) { CatalogConfiguration = catalogConfiguration; CustomArtifactsConfiguration = customArtifactsConfiguration; DeployAsApplicationConfiguration = deployAsApplicationConfiguration; MonitoringConfiguration = monitoringConfiguration; } } } ======================= File: sdk/dotnet/NetworkFirewall/Outputs/RuleGroupRuleOption.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.NetworkFirewall.Outputs { [OutputType] public sealed class RuleGroupRuleOption { public readonly string Keyword; public readonly ImmutableArray<string> Settings; [OutputConstructor] private RuleGroupRuleOption( string keyword, ImmutableArray<string> settings) { Keyword = keyword; Settings = settings; } } } ======================= File: sdk/dotnet/CloudFront/Outputs/DistributionLogging.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.CloudFront.Outputs { [OutputType] public sealed class DistributionLogging { public readonly string Bucket; public readonly bool? IncludeCookies; public readonly string? Prefix; [OutputConstructor] private DistributionLogging( string bucket, bool? includeCookies, string? prefix) { Bucket = bucket; IncludeCookies = includeCookies; Prefix = prefix; } } } ======================= File: sdk/dotnet/AppFlow/Inputs/FlowTriggerConfigArgs.cs ======================= <gh_stars>10-100 // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.AppFlow.Inputs { /// <summary> /// Trigger settings of the flow. /// </summary> public sealed class FlowTriggerConfigArgs : Pulumi.ResourceArgs { /// <summary> /// Details required based on the type of trigger /// </summary> [Input("triggerProperties")] public Input<Inputs.FlowScheduledTriggerPropertiesArgs>? TriggerProperties { get; set; } /// <summary> /// Trigger type of the flow /// </summary> [Input("triggerType", required: true)] public Input<Pulumi.AwsNative.AppFlow.FlowTriggerType> TriggerType { get; set; } = null!; public FlowTriggerConfigArgs() { } } } ======================= File: sdk/dotnet/MediaLive/Outputs/ChannelFmp4HlsSettings.cs ======================= <filename>sdk/dotnet/MediaLive/Outputs/ChannelFmp4HlsSettings.cs // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.MediaLive.Outputs { [OutputType] public sealed class ChannelFmp4HlsSettings { public readonly string? AudioRenditionSets; public readonly string? NielsenId3Behavior; public readonly string? TimedMetadataBehavior; [OutputConstructor] private ChannelFmp4HlsSettings( string? audioRenditionSets, string? nielsenId3Behavior, string? timedMetadataBehavior) { AudioRenditionSets = audioRenditionSets; NielsenId3Behavior = nielsenId3Behavior; TimedMetadataBehavior = timedMetadataBehavior; } } } ======================= File: sdk/dotnet/MediaStore/Inputs/ContainerCorsRuleArgs.cs ======================= <gh_stars>10-100 // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.MediaStore.Inputs { public sealed class ContainerCorsRuleArgs : Pulumi.ResourceArgs { [Input("allowedHeaders")] private InputList<string>? _allowedHeaders; public InputList<string> AllowedHeaders { get => _allowedHeaders?? (_allowedHeaders = new InputList<string>()); set => _allowedHeaders = value; } [Input("allowedMethods")] private InputList<string>? _allowedMethods; public InputList<string> AllowedMethods { get => _allowedMethods?? (_allowedMethods = new InputList<string>()); set => _allowedMethods = value; } [Input("allowedOrigins")] private InputList<string>? _allowedOrigins; public InputList<string> AllowedOrigins { get => _allowedOrigins?? (_allowedOrigins = new InputList<string>()); set => _allowedOrigins = value; } [Input("exposeHeaders")] private InputList<string>? _exposeHeaders; public InputList<string> ExposeHeaders { get => _exposeHeaders?? (_exposeHeaders = new InputList<string>()); set => _exposeHeaders = value; } [Input("maxAgeSeconds")] public Input<int>? MaxAgeSeconds { get; set; } public ContainerCorsRuleArgs() { } } } ======================= File: sdk/dotnet/Synthetics/Outputs/CanaryVisualReference.cs ======================= <filename>sdk/dotnet/Synthetics/Outputs/CanaryVisualReference.cs // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.Synthetics.Outputs { [OutputType] public sealed class CanaryVisualReference { /// <summary> /// Canary run id to be used as base reference for visual testing /// </summary> public readonly string BaseCanaryRunId; /// <summary> /// List of screenshots used as base reference for visual testing /// </summary> public readonly ImmutableArray<Outputs.CanaryBaseScreenshot> BaseScreenshots; [OutputConstructor] private CanaryVisualReference( string baseCanaryRunId, ImmutableArray<Outputs.CanaryBaseScreenshot> baseScreenshots) { BaseCanaryRunId = baseCanaryRunId; BaseScreenshots = baseScreenshots; } } } ======================= File: sdk/dotnet/S3ObjectLambda/Outputs/PolicyStatusProperties.cs ======================= <gh_stars>10-100 // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.S3ObjectLambda.Outputs { [OutputType] public sealed class PolicyStatusProperties { /// <summary> /// Specifies whether the Object lambda Access Point Policy is Public or not. Object lambda Access Points are private by default. /// </summary> public readonly bool? IsPublic; [OutputConstructor] private PolicyStatusProperties(bool? isPublic) { IsPublic = isPublic; } } } ======================= File: sdk/dotnet/Lightsail/LoadBalancerTlsCertificate.cs ======================= <filename>sdk/dotnet/Lightsail/LoadBalancerTlsCertificate.cs // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.Lightsail { /// <summary> /// Resource Type definition for AWS::Lightsail::LoadBalancerTlsCertificate /// </summary> [AwsNativeResourceType("aws-native:lightsail:LoadBalancerTlsCertificate")] public partial class LoadBalancerTlsCertificate : Pulumi.CustomResource { /// <summary> /// An array of strings listing alternative domains and subdomains for your SSL/TLS certificate. /// </summary> [Output("certificateAlternativeNames")] public Output<ImmutableArray<string>> CertificateAlternativeNames { get; private set; } = null!; /// <summary> /// The domain name (e.g., example.com ) for your SSL/TLS certificate. /// </summary> [Output("certificateDomainName")] public Output<string> CertificateDomainName { get; private set; } = null!; /// <summary> /// The SSL/TLS certificate name. /// </summary> [Output("certificateName")] public Output<string> CertificateName { get; private set; } = null!; /// <summary> /// When true, the SSL/TLS certificate is attached to the Lightsail load balancer. /// </summary> [Output("isAttached")] public Output<bool?> IsAttached { get; private set; } = null!; /// <summary> /// The name of your load balancer. /// </summary> [Output("loadBalancerName")] public Output<string> LoadBalancerName { get; private set; } = null!; [Output("loadBalancerTlsCertificateArn")] public Output<string> LoadBalancerTlsCertificateArn { get; private set; } = null!; /// <summary> /// The validation status of the SSL/TLS certificate. /// </summary> [Output("status")] public Output<string> Status { get; private set; } = null!; /// <summary> /// Create a LoadBalancerTlsCertificate resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public LoadBalancerTlsCertificate(string name, LoadBalancerTlsCertificateArgs args, CustomResourceOptions? options = null) : base("aws-native:lightsail:LoadBalancerTlsCertificate", name, args?? new LoadBalancerTlsCertificateArgs(), MakeResourceOptions(options, "")) { } private LoadBalancerTlsCertificate(string name, Input<string> id, CustomResourceOptions? options = null) : base("aws-native:lightsail:LoadBalancerTlsCertificate", name, null, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id?? merged.Id; return merged; } /// <summary> /// Get an existing LoadBalancerTlsCertificate resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static LoadBalancerTlsCertificate Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new LoadBalancerTlsCertificate(name, id, options); } } public sealed class LoadBalancerTlsCertificateArgs : Pulumi.ResourceArgs { [Input("certificateAlternativeNames")] private InputList<string>? _certificateAlternativeNames; /// <summary> /// An array of strings listing alternative domains and subdomains for your SSL/TLS certificate. /// </summary> public InputList<string> CertificateAlternativeNames { get => _certificateAlternativeNames?? (_certificateAlternativeNames = new InputList<string>()); set => _certificateAlternativeNames = value; } /// <summary> /// The domain name (e.g., example.com ) for your SSL/TLS certificate. /// </summary> [Input("certificateDomainName", required: true)] public Input<string> CertificateDomainName { get; set; } = null!; /// <summary> /// The SSL/TLS certificate name. /// </summary> [Input("certificateName", required: true)] public Input<string> CertificateName { get; set; } = null!; /// <summary> /// When true, the SSL/TLS certificate is attached to the Lightsail load balancer. /// </summary> [Input("isAttached")] public Input<bool>? IsAttached { get; set; } /// <summary> /// The name of your load balancer. /// </summary> [Input("loadBalancerName", required: true)] public Input<string> LoadBalancerName { get; set; } = null!; public LoadBalancerTlsCertificateArgs() { } } } ======================= File: sdk/dotnet/Configuration/ConformancePack.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.Configuration { /// <summary> /// A conformance pack is a collection of AWS Config rules and remediation actions that can be easily deployed as a single entity in an account and a region or across an entire AWS Organization. /// </summary> [AwsNativeResourceType("aws-native:configuration:ConformancePack")] public partial class ConformancePack : Pulumi.CustomResource { /// <summary> /// A list of ConformancePackInputParameter objects. /// </summary> [Output("conformancePackInputParameters")] public Output<ImmutableArray<Outputs.ConformancePackInputParameter>> ConformancePackInputParameters { get; private set; } = null!; /// <summary> /// Name of the conformance pack which will be assigned as the unique identifier. /// </summary> [Output("conformancePackName")] public Output<string> ConformancePackName { get; private set; } = null!; /// <summary> /// AWS Config stores intermediate files while processing conformance pack template. /// </summary> [Output("deliveryS3Bucket")] public Output<string?> DeliveryS3Bucket { get; private set; } = null!; /// <summary> /// The prefix for delivery S3 bucket. /// </summary> [Output("deliveryS3KeyPrefix")] public Output<string?> DeliveryS3KeyPrefix { get; private set; } = null!; /// <summary> /// A string containing full conformance pack template body. You can only specify one of the template body or template S3Uri fields. /// </summary> [Output("templateBody")] public Output<string?> TemplateBody { get; private set; } = null!; /// <summary> /// Location of file containing the template body which points to the conformance pack template that is located in an Amazon S3 bucket. You can only specify one of the template body or template S3Uri fields. /// </summary> [Output("templateS3Uri")] public Output<string?> TemplateS3Uri { get; private set; } = null!; /// <summary> /// Create a ConformancePack resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public ConformancePack(string name, ConformancePackArgs? args = null, CustomResourceOptions? options = null) : base("aws-native:configuration:ConformancePack", name, args?? new ConformancePackArgs(), MakeResourceOptions(options, "")) { } private ConformancePack(string name, Input<string> id, CustomResourceOptions? options = null) : base("aws-native:configuration:ConformancePack", name, null, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id?? merged.Id; return merged; } /// <summary> /// Get an existing ConformancePack resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static ConformancePack Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new ConformancePack(name, id, options); } } public sealed class ConformancePackArgs : Pulumi.ResourceArgs { [Input("conformancePackInputParameters")] private InputList<Inputs.ConformancePackInputParameterArgs>? _conformancePackInputParameters; /// <summary> /// A list of ConformancePackInputParameter objects. /// </summary> public InputList<Inputs.ConformancePackInputParameterArgs> ConformancePackInputParameters { get => _conformancePackInputParameters?? (_conformancePackInputParameters = new InputList<Inputs.ConformancePackInputParameterArgs>()); set => _conformancePackInputParameters = value; } /// <summary> /// Name of the conformance pack which will be assigned as the unique identifier. /// </summary> [Input("conformancePackName")] public Input<string>? ConformancePackName { get; set; } /// <summary> /// AWS Config stores intermediate files while processing conformance pack template. /// </summary> [Input("deliveryS3Bucket")] public Input<string>? DeliveryS3Bucket { get; set; } /// <summary> /// The prefix for delivery S3 bucket. /// </summary> [Input("deliveryS3KeyPrefix")] public Input<string>? DeliveryS3KeyPrefix { get; set; } /// <summary> /// A string containing full conformance pack template body. You can only specify one of the template body or template S3Uri fields. /// </summary> [Input("templateBody")] public Input<string>? TemplateBody { get; set; } /// <summary> /// Location of file containing the template body which points to the conformance pack template that is located in an Amazon S3 bucket. You can only specify one of the template body or template S3Uri fields. /// </summary> [Input("templateS3Uri")] public Input<string>? TemplateS3Uri { get; set; } public ConformancePackArgs() { } } } ======================= File: sdk/dotnet/IoT/Outputs/TopicRuleIotEventsAction.cs ======================= <filename>sdk/dotnet/IoT/Outputs/TopicRuleIotEventsAction.cs<gh_stars>10-100 // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.IoT.Outputs { [OutputType] public sealed class TopicRuleIotEventsAction { public readonly bool? BatchMode; public readonly string InputName; public readonly string? MessageId; public readonly string RoleArn; [OutputConstructor] private TopicRuleIotEventsAction( bool? batchMode, string inputName, string? messageId, string roleArn) { BatchMode = batchMode; InputName = inputName; MessageId = messageId; RoleArn = roleArn; } } } ======================= File: sdk/dotnet/DataBrew/Outputs/DatasetFormatOptions.cs ======================= <reponame>AaronFriel/pulumi-aws-native<gh_stars>10-100 // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.DataBrew.Outputs { /// <summary> /// Format options for dataset /// </summary> [OutputType] public sealed class DatasetFormatOptions { public readonly Outputs.DatasetCsvOptions? Csv; public readonly Outputs.DatasetExcelOptions? Excel; public readonly Outputs.DatasetJsonOptions? Json; [OutputConstructor] private DatasetFormatOptions( Outputs.DatasetCsvOptions? csv, Outputs.DatasetExcelOptions? excel, Outputs.DatasetJsonOptions? json) { Csv = csv; Excel = excel; Json = json; } } } ======================= File: sdk/dotnet/CodeBuild/Outputs/ProjectEnvironment.cs ======================= <gh_stars>10-100 // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.CodeBuild.Outputs { [OutputType] public sealed class ProjectEnvironment { public readonly string? Certificate; public readonly string ComputeType; public readonly ImmutableArray<Outputs.ProjectEnvironmentVariable> EnvironmentVariables; public readonly string Image; public readonly string? ImagePullCredentialsType; public readonly bool? PrivilegedMode; public readonly Outputs.ProjectRegistryCredential? RegistryCredential; public readonly string Type; [OutputConstructor] private ProjectEnvironment( string? certificate, string computeType, ImmutableArray<Outputs.ProjectEnvironmentVariable> environmentVariables, string image, string? imagePullCredentialsType, bool? privilegedMode, Outputs.ProjectRegistryCredential? registryCredential, string type) { Certificate = certificate; ComputeType = computeType; EnvironmentVariables = environmentVariables; Image = image; ImagePullCredentialsType = imagePullCredentialsType; PrivilegedMode = privilegedMode; RegistryCredential = registryCredential; Type = type; } } } ======================= File: sdk/dotnet/Lightsail/Inputs/InstanceLocationArgs.cs ======================= <reponame>AaronFriel/pulumi-aws-native // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.Lightsail.Inputs { /// <summary> /// Location of a resource. /// </summary> public sealed class InstanceLocationArgs : Pulumi.ResourceArgs { /// <summary> /// The Availability Zone in which to create your instance. Use the following format: us-east-2a (case sensitive). Be sure to add the include Availability Zones parameter to your request. /// </summary> [Input("availabilityZone")] public Input<string>? AvailabilityZone { get; set; } /// <summary> /// The Region Name in which to create your instance. /// </summary> [Input("regionName")] public Input<string>? RegionName { get; set; } public InstanceLocationArgs() { } } } ======================= File: sdk/dotnet/GreengrassV2/Inputs/ComponentVersionLambdaExecutionParametersArgs.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.GreengrassV2.Inputs { public sealed class ComponentVersionLambdaExecutionParametersArgs : Pulumi.ResourceArgs { [Input("environmentVariables")] public Input<object>? EnvironmentVariables { get; set; } [Input("eventSources")] private InputList<Inputs.ComponentVersionLambdaEventSourceArgs>? _eventSources; public InputList<Inputs.ComponentVersionLambdaEventSourceArgs> EventSources { get => _eventSources?? (_eventSources = new InputList<Inputs.ComponentVersionLambdaEventSourceArgs>()); set => _eventSources = value; } [Input("execArgs")] private InputList<string>? _execArgs; public InputList<string> ExecArgs { get => _execArgs?? (_execArgs = new InputList<string>()); set => _execArgs = value; } [Input("inputPayloadEncodingType")] public Input<Pulumi.AwsNative.GreengrassV2.ComponentVersionLambdaExecutionParametersInputPayloadEncodingType>? InputPayloadEncodingType { get; set; } [Input("linuxProcessParams")] public Input<Inputs.ComponentVersionLambdaLinuxProcessParamsArgs>? LinuxProcessParams { get; set; } [Input("maxIdleTimeInSeconds")] public Input<int>? MaxIdleTimeInSeconds { get; set; } [Input("maxInstancesCount")] public Input<int>? MaxInstancesCount { get; set; } [Input("maxQueueSize")] public Input<int>? MaxQueueSize { get; set; } [Input("pinned")] public Input<bool>? Pinned { get; set; } [Input("statusTimeoutInSeconds")] public Input<int>? StatusTimeoutInSeconds { get; set; } [Input("timeoutInSeconds")] public Input<int>? TimeoutInSeconds { get; set; } public ComponentVersionLambdaExecutionParametersArgs() { } } } ======================= File: sdk/dotnet/SageMaker/Inputs/AppResourceSpecArgs.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.SageMaker.Inputs { public sealed class AppResourceSpecArgs : Pulumi.ResourceArgs { /// <summary> /// The instance type that the image version runs on. /// </summary> [Input("instanceType")] public Input<Pulumi.AwsNative.SageMaker.AppResourceSpecInstanceType>? InstanceType { get; set; } /// <summary> /// The ARN of the SageMaker image that the image version belongs to. /// </summary> [Input("sageMakerImageArn")] public Input<string>? SageMakerImageArn { get; set; } /// <summary> /// The ARN of the image version created on the instance. /// </summary> [Input("sageMakerImageVersionArn")] public Input<string>? SageMakerImageVersionArn { get; set; } public AppResourceSpecArgs() { } } } ======================= File: sdk/dotnet/DataBrew/Inputs/ProjectSampleArgs.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.DataBrew.Inputs { public sealed class ProjectSampleArgs : Pulumi.ResourceArgs { /// <summary> /// Sample size /// </summary> [Input("size")] public Input<int>? Size { get; set; } /// <summary> /// Sample type /// </summary> [Input("type", required: true)] public Input<Pulumi.AwsNative.DataBrew.ProjectSampleType> Type { get; set; } = null!; public ProjectSampleArgs() { } } } ======================= File: sdk/dotnet/DynamoDB/Outputs/GlobalTableReplicaGlobalSecondaryIndexSpecification.cs ======================= <filename>sdk/dotnet/DynamoDB/Outputs/GlobalTableReplicaGlobalSecondaryIndexSpecification.cs<gh_stars>10-100 // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.DynamoDB.Outputs { [OutputType] public sealed class GlobalTableReplicaGlobalSecondaryIndexSpecification { public readonly Outputs.GlobalTableContributorInsightsSpecification? ContributorInsightsSpecification; public readonly string IndexName; public readonly Outputs.GlobalTableReadProvisionedThroughputSettings? ReadProvisionedThroughputSettings; [OutputConstructor] private GlobalTableReplicaGlobalSecondaryIndexSpecification( Outputs.GlobalTableContributorInsightsSpecification? contributorInsightsSpecification, string indexName, Outputs.GlobalTableReadProvisionedThroughputSettings? readProvisionedThroughputSettings) { ContributorInsightsSpecification = contributorInsightsSpecification; IndexName = indexName; ReadProvisionedThroughputSettings = readProvisionedThroughputSettings; } } } ======================= File: sdk/dotnet/MediaPackage/Outputs/PackagingConfigurationMssPackage.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.MediaPackage.Outputs { /// <summary> /// A Microsoft Smooth Streaming (MSS) PackagingConfiguration. /// </summary> [OutputType] public sealed class PackagingConfigurationMssPackage { public readonly Outputs.PackagingConfigurationMssEncryption? Encryption; /// <summary> /// A list of MSS manifest configurations. /// </summary> public readonly ImmutableArray<Outputs.PackagingConfigurationMssManifest> MssManifests; public readonly int? SegmentDurationSeconds; [OutputConstructor] private PackagingConfigurationMssPackage( Outputs.PackagingConfigurationMssEncryption? encryption, ImmutableArray<Outputs.PackagingConfigurationMssManifest> mssManifests, int? segmentDurationSeconds) { Encryption = encryption; MssManifests = mssManifests; SegmentDurationSeconds = segmentDurationSeconds; } } } ======================= File: sdk/dotnet/KinesisFirehose/Outputs/DeliveryStreamOpenXJsonSerDe.cs ======================= <reponame>AaronFriel/pulumi-aws-native // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.KinesisFirehose.Outputs { [OutputType] public sealed class DeliveryStreamOpenXJsonSerDe { public readonly bool? CaseInsensitive; public readonly object? ColumnToJsonKeyMappings; public readonly bool? ConvertDotsInJsonKeysToUnderscores; [OutputConstructor] private DeliveryStreamOpenXJsonSerDe( bool? caseInsensitive, object? columnToJsonKeyMappings, bool? convertDotsInJsonKeysToUnderscores) { CaseInsensitive = caseInsensitive; ColumnToJsonKeyMappings = columnToJsonKeyMappings; ConvertDotsInJsonKeysToUnderscores = convertDotsInJsonKeysToUnderscores; } } } ======================= File: sdk/dotnet/MediaLive/Inputs/ChannelAc3SettingsArgs.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.MediaLive.Inputs { public sealed class ChannelAc3SettingsArgs : Pulumi.ResourceArgs { [Input("bitrate")] public Input<double>? Bitrate { get; set; } [Input("bitstreamMode")] public Input<string>? BitstreamMode { get; set; } [Input("codingMode")] public Input<string>? CodingMode { get; set; } [Input("dialnorm")] public Input<int>? Dialnorm { get; set; } [Input("drcProfile")] public Input<string>? DrcProfile { get; set; } [Input("lfeFilter")] public Input<string>? LfeFilter { get; set; } [Input("metadataControl")] public Input<string>? MetadataControl { get; set; } public ChannelAc3SettingsArgs() { } } } ======================= File: sdk/dotnet/AppMesh/Outputs/VirtualNodeListener.cs ======================= <gh_stars>10-100 // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.AppMesh.Outputs { [OutputType] public sealed class VirtualNodeListener { public readonly Outputs.VirtualNodeConnectionPool? ConnectionPool; public readonly Outputs.VirtualNodeHealthCheck? HealthCheck; public readonly Outputs.VirtualNodeOutlierDetection? OutlierDetection; public readonly Outputs.VirtualNodePortMapping PortMapping; public readonly Outputs.VirtualNodeListenerTls? TLS; public readonly Outputs.VirtualNodeListenerTimeout? Timeout; [OutputConstructor] private VirtualNodeListener( Outputs.VirtualNodeConnectionPool? connectionPool, Outputs.VirtualNodeHealthCheck? healthCheck, Outputs.VirtualNodeOutlierDetection? outlierDetection, Outputs.VirtualNodePortMapping portMapping, Outputs.VirtualNodeListenerTls? tLS, Outputs.VirtualNodeListenerTimeout? timeout) { ConnectionPool = connectionPool; HealthCheck = healthCheck; OutlierDetection = outlierDetection; PortMapping = portMapping; TLS = tLS; Timeout = timeout; } } } ======================= File: sdk/dotnet/Glue/Inputs/TriggerPredicateArgs.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.Glue.Inputs { public sealed class TriggerPredicateArgs : Pulumi.ResourceArgs { [Input("conditions")] private InputList<Inputs.TriggerConditionArgs>? _conditions; public InputList<Inputs.TriggerConditionArgs> Conditions { get => _conditions?? (_conditions = new InputList<Inputs.TriggerConditionArgs>()); set => _conditions = value; } [Input("logical")] public Input<string>? Logical { get; set; } public TriggerPredicateArgs() { } } } ======================= File: sdk/dotnet/DLM/Inputs/LifecyclePolicyPolicyDetailsArgs.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.DLM.Inputs { public sealed class LifecyclePolicyPolicyDetailsArgs : Pulumi.ResourceArgs { [Input("actions")] private InputList<Inputs.LifecyclePolicyActionArgs>? _actions; public InputList<Inputs.LifecyclePolicyActionArgs> Actions { get => _actions?? (_actions = new InputList<Inputs.LifecyclePolicyActionArgs>()); set => _actions = value; } [Input("eventSource")] public Input<Inputs.LifecyclePolicyEventSourceArgs>? EventSource { get; set; } [Input("parameters")] public Input<Inputs.LifecyclePolicyParametersArgs>? Parameters { get; set; } [Input("policyType")] public Input<string>? PolicyType { get; set; } [Input("resourceLocations")] private InputList<string>? _resourceLocations; public InputList<string> ResourceLocations { get => _resourceLocations?? (_resourceLocations = new InputList<string>()); set => _resourceLocations = value; } [Input("resourceTypes")] private InputList<string>? _resourceTypes; public InputList<string> ResourceTypes { get => _resourceTypes?? (_resourceTypes = new InputList<string>()); set => _resourceTypes = value; } [Input("schedules")] private InputList<Inputs.LifecyclePolicyScheduleArgs>? _schedules; public InputList<Inputs.LifecyclePolicyScheduleArgs> Schedules { get => _schedules?? (_schedules = new InputList<Inputs.LifecyclePolicyScheduleArgs>()); set => _schedules = value; } [Input("targetTags")] private InputList<Inputs.LifecyclePolicyTagArgs>? _targetTags; public InputList<Inputs.LifecyclePolicyTagArgs> TargetTags { get => _targetTags?? (_targetTags = new InputList<Inputs.LifecyclePolicyTagArgs>()); set => _targetTags = value; } public LifecyclePolicyPolicyDetailsArgs() { } } } ======================= File: sdk/dotnet/Synthetics/Outputs/CanaryArtifactConfig.cs ======================= <reponame>AaronFriel/pulumi-aws-native // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.Synthetics.Outputs { [OutputType] public sealed class CanaryArtifactConfig { /// <summary> /// Encryption configuration for uploading artifacts to S3 /// </summary> public readonly Outputs.CanaryS3Encryption? S3Encryption; [OutputConstructor] private CanaryArtifactConfig(Outputs.CanaryS3Encryption? s3Encryption) { S3Encryption = s3Encryption; } } } ======================= File: sdk/dotnet/S3/Inputs/BucketSseKmsEncryptedObjectsArgs.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.S3.Inputs { /// <summary> /// A container for filter information for the selection of S3 objects encrypted with AWS KMS. /// </summary> public sealed class BucketSseKmsEncryptedObjectsArgs : Pulumi.ResourceArgs { /// <summary> /// Specifies whether Amazon S3 replicates objects created with server-side encryption using a customer master key (CMK) stored in AWS Key Management Service. /// </summary> [Input("status", required: true)] public Input<Pulumi.AwsNative.S3.BucketSseKmsEncryptedObjectsStatus> Status { get; set; } = null!; public BucketSseKmsEncryptedObjectsArgs() { } } } ======================= File: sdk/dotnet/NimbleStudio/Outputs/StudioComponentActiveDirectoryComputerAttribute.cs ======================= <gh_stars>10-100 // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.NimbleStudio.Outputs { /// <summary> /// &lt;p&gt;An LDAP attribute of an Active Directory computer account, in the form of a name:value pair.&lt;/p&gt; /// </summary> [OutputType] public sealed class StudioComponentActiveDirectoryComputerAttribute { /// <summary> /// &lt;p&gt;The name for the LDAP attribute.&lt;/p&gt; /// </summary> public readonly string? Name; /// <summary> /// &lt;p&gt;The value for the LDAP attribute.&lt;/p&gt; /// </summary> public readonly string? Value; [OutputConstructor] private StudioComponentActiveDirectoryComputerAttribute( string? name, string? value) { Name = name; Value = value; } } } ======================= File: sdk/dotnet/EC2/Outputs/LaunchTemplateInstanceRequirements.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.EC2.Outputs { [OutputType] public sealed class LaunchTemplateInstanceRequirements { public readonly Outputs.LaunchTemplateAcceleratorCount? AcceleratorCount; public readonly ImmutableArray<string> AcceleratorManufacturers; public readonly ImmutableArray<string> AcceleratorNames; public readonly Outputs.LaunchTemplateAcceleratorTotalMemoryMiB? AcceleratorTotalMemoryMiB; public readonly ImmutableArray<string> AcceleratorTypes; public readonly string? BareMetal; public readonly Outputs.LaunchTemplateBaselineEbsBandwidthMbps? BaselineEbsBandwidthMbps; public readonly string? BurstablePerformance; public readonly ImmutableArray<string> CpuManufacturers; public readonly ImmutableArray<string> ExcludedInstanceTypes; public readonly ImmutableArray<string> InstanceGenerations; public readonly string? LocalStorage; public readonly ImmutableArray<string> LocalStorageTypes; public readonly Outputs.LaunchTemplateMemoryGiBPerVCpu? MemoryGiBPerVCpu; public readonly Outputs.LaunchTemplateMemoryMiB? MemoryMiB; public readonly Outputs.LaunchTemplateNetworkInterfaceCount? NetworkInterfaceCount; public readonly int? OnDemandMaxPricePercentageOverLowestPrice; public readonly bool? RequireHibernateSupport; public readonly int? SpotMaxPricePercentageOverLowestPrice; public readonly Outputs.LaunchTemplateTotalLocalStorageGB? TotalLocalStorageGB; public readonly Outputs.LaunchTemplateVCpuCount? VCpuCount; [OutputConstructor] private LaunchTemplateInstanceRequirements( Outputs.LaunchTemplateAcceleratorCount? acceleratorCount, ImmutableArray<string> acceleratorManufacturers, ImmutableArray<string> acceleratorNames, Outputs.LaunchTemplateAcceleratorTotalMemoryMiB? acceleratorTotalMemoryMiB, ImmutableArray<string> acceleratorTypes, string? bareMetal, Outputs.LaunchTemplateBaselineEbsBandwidthMbps? baselineEbsBandwidthMbps, string? burstablePerformance, ImmutableArray<string> cpuManufacturers, ImmutableArray<string> excludedInstanceTypes, ImmutableArray<string> instanceGenerations, string? localStorage, ImmutableArray<string> localStorageTypes, Outputs.LaunchTemplateMemoryGiBPerVCpu? memoryGiBPerVCpu, Outputs.LaunchTemplateMemoryMiB? memoryMiB, Outputs.LaunchTemplateNetworkInterfaceCount? networkInterfaceCount, int? onDemandMaxPricePercentageOverLowestPrice, bool? requireHibernateSupport, int? spotMaxPricePercentageOverLowestPrice, Outputs.LaunchTemplateTotalLocalStorageGB? totalLocalStorageGB, Outputs.LaunchTemplateVCpuCount? vCpuCount) { AcceleratorCount = acceleratorCount; AcceleratorManufacturers = acceleratorManufacturers; AcceleratorNames = acceleratorNames; AcceleratorTotalMemoryMiB = acceleratorTotalMemoryMiB; AcceleratorTypes = acceleratorTypes; BareMetal = bareMetal; BaselineEbsBandwidthMbps = baselineEbsBandwidthMbps; BurstablePerformance = burstablePerformance; CpuManufacturers = cpuManufacturers; ExcludedInstanceTypes = excludedInstanceTypes; InstanceGenerations = instanceGenerations; LocalStorage = localStorage; LocalStorageTypes = localStorageTypes; MemoryGiBPerVCpu = memoryGiBPerVCpu; MemoryMiB = memoryMiB; NetworkInterfaceCount = networkInterfaceCount; OnDemandMaxPricePercentageOverLowestPrice = onDemandMaxPricePercentageOverLowestPrice; RequireHibernateSupport = requireHibernateSupport; SpotMaxPricePercentageOverLowestPrice = spotMaxPricePercentageOverLowestPrice; TotalLocalStorageGB = totalLocalStorageGB; VCpuCount = vCpuCount; } } } ======================= File: sdk/dotnet/Redshift/Outputs/ScheduledActionPauseClusterMessage.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.Redshift.Outputs { /// <summary> /// Describes a pause cluster operation. For example, a scheduled action to run the `PauseCluster` API operation. /// </summary> [OutputType] public sealed class ScheduledActionPauseClusterMessage { public readonly string ClusterIdentifier; [OutputConstructor] private ScheduledActionPauseClusterMessage(string clusterIdentifier) { ClusterIdentifier = clusterIdentifier; } } } ======================= File: sdk/dotnet/MediaPackage/Outputs/OriginEndpointHlsPackage.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.MediaPackage.Outputs { /// <summary> /// An HTTP Live Streaming (HLS) packaging configuration. /// </summary> [OutputType] public sealed class OriginEndpointHlsPackage { /// <summary> /// This setting controls how ad markers are included in the packaged OriginEndpoint. "NONE" will omit all SCTE-35 ad markers from the output. "PASSTHROUGH" causes the manifest to contain a copy of the SCTE-35 ad markers (comments) taken directly from the input HTTP Live Streaming (HLS) manifest. "SCTE35_ENHANCED" generates ad markers and blackout tags based on SCTE-35 messages in the input source. "DATERANGE" inserts EXT-X-DATERANGE tags to signal ad and program transition events in HLS and CMAF manifests. For this option, you must set a programDateTimeIntervalSeconds value that is greater than 0. /// </summary> public readonly Pulumi.AwsNative.MediaPackage.OriginEndpointHlsPackageAdMarkers? AdMarkers; /// <summary> /// A list of SCTE-35 message types that are treated as ad markers in the output. If empty, no ad markers are output. Specify multiple items to create ad markers for all of the included message types. /// </summary> public readonly ImmutableArray<Pulumi.AwsNative.MediaPackage.OriginEndpointHlsPackageAdTriggersItem> AdTriggers; public readonly Pulumi.AwsNative.MediaPackage.OriginEndpointAdsOnDeliveryRestrictions? AdsOnDeliveryRestrictions; public readonly Outputs.OriginEndpointHlsEncryption? Encryption; /// <summary> /// When enabled, an I-Frame only stream will be included in the output. /// </summary> public readonly bool? IncludeIframeOnlyStream; /// <summary> /// The HTTP Live Streaming (HLS) playlist type. When either "EVENT" or "VOD" is specified, a corresponding EXT-X-PLAYLIST-TYPE entry will be included in the media playlist. /// </summary> public readonly Pulumi.AwsNative.MediaPackage.OriginEndpointHlsPackagePlaylistType? PlaylistType; /// <summary> /// Time window (in seconds) contained in each parent manifest. /// </summary> public readonly int? PlaylistWindowSeconds; /// <summary> /// The interval (in seconds) between each EXT-X-PROGRAM-DATE-TIME tag inserted into manifests. Additionally, when an interval is specified ID3Timed Metadata messages will be generated every 5 seconds using the ingest time of the content. If the interval is not specified, or set to 0, then no EXT-X-PROGRAM-DATE-TIME tags will be inserted into manifests and no ID3Timed Metadata messages will be generated. Note that irrespective of this parameter, if any ID3 Timed Metadata is found in HTTP Live Streaming (HLS) input, it will be passed through to HLS output. /// </summary> public readonly int? ProgramDateTimeIntervalSeconds; /// <summary> /// Duration (in seconds) of each fragment. Actual fragments will be rounded to the nearest multiple of the source fragment duration. /// </summary> public readonly int? SegmentDurationSeconds; public readonly Outputs.OriginEndpointStreamSelection? StreamSelection; /// <summary> /// When enabled, audio streams will be placed in rendition groups in the output. /// </summary> public readonly bool? UseAudioRenditionGroup; [OutputConstructor] private OriginEndpointHlsPackage( Pulumi.AwsNative.MediaPackage.OriginEndpointHlsPackageAdMarkers? adMarkers, ImmutableArray<Pulumi.AwsNative.MediaPackage.OriginEndpointHlsPackageAdTriggersItem> adTriggers, Pulumi.AwsNative.MediaPackage.OriginEndpointAdsOnDeliveryRestrictions? adsOnDeliveryRestrictions, Outputs.OriginEndpointHlsEncryption? encryption, bool? includeIframeOnlyStream, Pulumi.AwsNative.MediaPackage.OriginEndpointHlsPackagePlaylistType? playlistType, int? playlistWindowSeconds, int? programDateTimeIntervalSeconds, int? segmentDurationSeconds, Outputs.OriginEndpointStreamSelection? streamSelection, bool? useAudioRenditionGroup) { AdMarkers = adMarkers; AdTriggers = adTriggers; AdsOnDeliveryRestrictions = adsOnDeliveryRestrictions; Encryption = encryption; IncludeIframeOnlyStream = includeIframeOnlyStream; PlaylistType = playlistType; PlaylistWindowSeconds = playlistWindowSeconds; ProgramDateTimeIntervalSeconds = programDateTimeIntervalSeconds; SegmentDurationSeconds = segmentDurationSeconds; StreamSelection = streamSelection; UseAudioRenditionGroup = useAudioRenditionGroup; } } } ======================= File: sdk/dotnet/EKS/Outputs/NodegroupUpdateConfig.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.EKS.Outputs { [OutputType] public sealed class NodegroupUpdateConfig { public readonly double? MaxUnavailable; public readonly double? MaxUnavailablePercentage; [OutputConstructor] private NodegroupUpdateConfig( double? maxUnavailable, double? maxUnavailablePercentage) { MaxUnavailable = maxUnavailable; MaxUnavailablePercentage = maxUnavailablePercentage; } } } ======================= File: sdk/dotnet/FSx/Inputs/FileSystemAuditLogConfigurationArgs.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.FSx.Inputs { public sealed class FileSystemAuditLogConfigurationArgs : Pulumi.ResourceArgs { [Input("auditLogDestination")] public Input<string>? AuditLogDestination { get; set; } [Input("fileAccessAuditLogLevel", required: true)] public Input<string> FileAccessAuditLogLevel { get; set; } = null!; [Input("fileShareAccessAuditLogLevel", required: true)] public Input<string> FileShareAccessAuditLogLevel { get; set; } = null!; public FileSystemAuditLogConfigurationArgs() { } } } ======================= File: sdk/dotnet/S3/Inputs/BucketS3KeyFilterArgs.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.S3.Inputs { /// <summary> /// A container for object key name prefix and suffix filtering rules. /// </summary> public sealed class BucketS3KeyFilterArgs : Pulumi.ResourceArgs { [Input("rules", required: true)] private InputList<Inputs.BucketFilterRuleArgs>? _rules; public InputList<Inputs.BucketFilterRuleArgs> Rules { get => _rules?? (_rules = new InputList<Inputs.BucketFilterRuleArgs>()); set => _rules = value; } public BucketS3KeyFilterArgs() { } } } ======================= File: sdk/dotnet/Route53/KeySigningKey.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.Route53 { /// <summary> /// Represents a key signing key (KSK) associated with a hosted zone. You can only have two KSKs per hosted zone. /// </summary> [AwsNativeResourceType("aws-native:route53:KeySigningKey")] public partial class KeySigningKey : Pulumi.CustomResource { /// <summary> /// The unique string (ID) used to identify a hosted zone. /// </summary> [Output("hostedZoneId")] public Output<string> HostedZoneId { get; private set; } = null!; /// <summary> /// The Amazon resource name (ARN) for a customer managed key (CMK) in AWS Key Management Service (KMS). The KeyManagementServiceArn must be unique for each key signing key (KSK) in a single hosted zone. /// </summary> [Output("keyManagementServiceArn")] public Output<string> KeyManagementServiceArn { get; private set; } = null!; /// <summary> /// An alphanumeric string used to identify a key signing key (KSK). Name must be unique for each key signing key in the same hosted zone. /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; /// <summary> /// A string specifying the initial status of the key signing key (KSK). You can set the value to ACTIVE or INACTIVE. /// </summary> [Output("status")] public Output<Pulumi.AwsNative.Route53.KeySigningKeyStatus> Status { get; private set; } = null!; /// <summary> /// Create a KeySigningKey resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public KeySigningKey(string name, KeySigningKeyArgs args, CustomResourceOptions? options = null) : base("aws-native:route53:KeySigningKey", name, args?? new KeySigningKeyArgs(), MakeResourceOptions(options, "")) { } private KeySigningKey(string name, Input<string> id, CustomResourceOptions? options = null) : base("aws-native:route53:KeySigningKey", name, null, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id?? merged.Id; return merged; } /// <summary> /// Get an existing KeySigningKey resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static KeySigningKey Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new KeySigningKey(name, id, options); } } public sealed class KeySigningKeyArgs : Pulumi.ResourceArgs { /// <summary> /// The unique string (ID) used to identify a hosted zone. /// </summary> [Input("hostedZoneId", required: true)] public Input<string> HostedZoneId { get; set; } = null!; /// <summary> /// The Amazon resource name (ARN) for a customer managed key (CMK) in AWS Key Management Service (KMS). The KeyManagementServiceArn must be unique for each key signing key (KSK) in a single hosted zone. /// </summary> [Input("keyManagementServiceArn", required: true)] public Input<string> KeyManagementServiceArn { get; set; } = null!; /// <summary> /// An alphanumeric string used to identify a key signing key (KSK). Name must be unique for each key signing key in the same hosted zone. /// </summary> [Input("name")] public Input<string>? Name { get; set; } /// <summary> /// A string specifying the initial status of the key signing key (KSK). You can set the value to ACTIVE or INACTIVE. /// </summary> [Input("status", required: true)] public Input<Pulumi.AwsNative.Route53.KeySigningKeyStatus> Status { get; set; } = null!; public KeySigningKeyArgs() { } } } ======================= File: sdk/dotnet/Route53RecoveryReadiness/Inputs/ResourceSetResourceArgs.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.Route53RecoveryReadiness.Inputs { /// <summary> /// The resource element of a ResourceSet /// </summary> public sealed class ResourceSetResourceArgs : Pulumi.ResourceArgs { /// <summary> /// The component identifier of the resource, generated when DNS target resource is used. /// </summary> [Input("componentId")] public Input<string>? ComponentId { get; set; } [Input("dnsTargetResource")] public Input<Inputs.ResourceSetDNSTargetResourceArgs>? DnsTargetResource { get; set; } [Input("readinessScopes")] private InputList<string>? _readinessScopes; /// <summary> /// A list of recovery group Amazon Resource Names (ARNs) and cell ARNs that this resource is contained within. /// </summary> public InputList<string> ReadinessScopes { get => _readinessScopes?? (_readinessScopes = new InputList<string>()); set => _readinessScopes = value; } /// <summary> /// The Amazon Resource Name (ARN) of the AWS resource. /// </summary> [Input("resourceArn")] public Input<string>? ResourceArn { get; set; } public ResourceSetResourceArgs() { } } } ======================= File: sdk/dotnet/Events/Outputs/ConnectionApiKeyAuthParameters.cs ======================= <reponame>AaronFriel/pulumi-aws-native // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.Events.Outputs { [OutputType] public sealed class ConnectionApiKeyAuthParameters { public readonly string ApiKeyName; public readonly string ApiKeyValue; [OutputConstructor] private ConnectionApiKeyAuthParameters( string apiKeyName, string apiKeyValue) { ApiKeyName = apiKeyName; ApiKeyValue = apiKeyValue; } } } ======================= File: sdk/dotnet/CodePipeline/Outputs/PipelineStageTransition.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.CodePipeline.Outputs { [OutputType] public sealed class PipelineStageTransition { public readonly string Reason; public readonly string StageName; [OutputConstructor] private PipelineStageTransition( string reason, string stageName) { Reason = reason; StageName = stageName; } } } ======================= File: sdk/dotnet/MediaLive/Inputs/ChannelVideoSelectorArgs.cs ======================= <reponame>AaronFriel/pulumi-aws-native // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.MediaLive.Inputs { public sealed class ChannelVideoSelectorArgs : Pulumi.ResourceArgs { [Input("colorSpace")] public Input<string>? ColorSpace { get; set; } [Input("colorSpaceSettings")] public Input<Inputs.ChannelVideoSelectorColorSpaceSettingsArgs>? ColorSpaceSettings { get; set; } [Input("colorSpaceUsage")] public Input<string>? ColorSpaceUsage { get; set; } [Input("selectorSettings")] public Input<Inputs.ChannelVideoSelectorSettingsArgs>? SelectorSettings { get; set; } public ChannelVideoSelectorArgs() { } } } ======================= File: sdk/dotnet/OpsWorks/Instance.cs ======================= <reponame>AaronFriel/pulumi-aws-native // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.OpsWorks { /// <summary> /// Resource Type definition for AWS::OpsWorks::Instance /// </summary> [Obsolete(@"Instance is not yet supported by AWS Native, so its creation will currently fail. Please use the classic AWS provider, if possible.")] [AwsNativeResourceType("aws-native:opsworks:Instance")] public partial class Instance : Pulumi.CustomResource { [Output("agentVersion")] public Output<string?> AgentVersion { get; private set; } = null!; [Output("amiId")] public Output<string?> AmiId { get; private set; } = null!; [Output("architecture")] public Output<string?> Architecture { get; private set; } = null!; [Output("autoScalingType")] public Output<string?> AutoScalingType { get; private set; } = null!; [Output("availabilityZone")] public Output<string?> AvailabilityZone { get; private set; } = null!; [Output("blockDeviceMappings")] public Output<ImmutableArray<Outputs.InstanceBlockDeviceMapping>> BlockDeviceMappings { get; private set; } = null!; [Output("ebsOptimized")] public Output<bool?> EbsOptimized { get; private set; } = null!; [Output("elasticIps")] public Output<ImmutableArray<string>> ElasticIps { get; private set; } = null!; [Output("hostname")] public Output<string?> Hostname { get; private set; } = null!; [Output("installUpdatesOnBoot")] public Output<bool?> InstallUpdatesOnBoot { get; private set; } = null!; [Output("instanceType")] public Output<string> InstanceType { get; private set; } = null!; [Output("layerIds")] public Output<ImmutableArray<string>> LayerIds { get; private set; } = null!; [Output("os")] public Output<string?> Os { get; private set; } = null!; [Output("privateDnsName")] public Output<string> PrivateDnsName { get; private set; } = null!; [Output("privateIp")] public Output<string> PrivateIp { get; private set; } = null!; [Output("publicDnsName")] public Output<string> PublicDnsName { get; private set; } = null!; [Output("publicIp")] public Output<string> PublicIp { get; private set; } = null!; [Output("rootDeviceType")] public Output<string?> RootDeviceType { get; private set; } = null!; [Output("sshKeyName")] public Output<string?> SshKeyName { get; private set; } = null!; [Output("stackId")] public Output<string> StackId { get; private set; } = null!; [Output("subnetId")] public Output<string?> SubnetId { get; private set; } = null!; [Output("tenancy")] public Output<string?> Tenancy { get; private set; } = null!; [Output("timeBasedAutoScaling")] public Output<Outputs.InstanceTimeBasedAutoScaling?> TimeBasedAutoScaling { get; private set; } = null!; [Output("virtualizationType")] public Output<string?> VirtualizationType { get; private set; } = null!; [Output("volumes")] public Output<ImmutableArray<string>> Volumes { get; private set; } = null!; /// <summary> /// Create a Instance resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public Instance(string name, InstanceArgs args, CustomResourceOptions? options = null) : base("aws-native:opsworks:Instance", name, args?? new InstanceArgs(), MakeResourceOptions(options, "")) { } private Instance(string name, Input<string> id, CustomResourceOptions? options = null) : base("aws-native:opsworks:Instance", name, null, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id?? merged.Id; return merged; } /// <summary> /// Get an existing Instance resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static Instance Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new Instance(name, id, options); } } public sealed class InstanceArgs : Pulumi.ResourceArgs { [Input("agentVersion")] public Input<string>? AgentVersion { get; set; } [Input("amiId")] public Input<string>? AmiId { get; set; } [Input("architecture")] public Input<string>? Architecture { get; set; } [Input("autoScalingType")] public Input<string>? AutoScalingType { get; set; } [Input("availabilityZone")] public Input<string>? AvailabilityZone { get; set; } [Input("blockDeviceMappings")] private InputList<Inputs.InstanceBlockDeviceMappingArgs>? _blockDeviceMappings; public InputList<Inputs.InstanceBlockDeviceMappingArgs> BlockDeviceMappings { get => _blockDeviceMappings?? (_blockDeviceMappings = new InputList<Inputs.InstanceBlockDeviceMappingArgs>()); set => _blockDeviceMappings = value; } [Input("ebsOptimized")] public Input<bool>? EbsOptimized { get; set; } [Input("elasticIps")] private InputList<string>? _elasticIps; public InputList<string> ElasticIps { get => _elasticIps?? (_elasticIps = new InputList<string>()); set => _elasticIps = value; } [Input("hostname")] public Input<string>? Hostname { get; set; } [Input("installUpdatesOnBoot")] public Input<bool>? InstallUpdatesOnBoot { get; set; } [Input("instanceType", required: true)] public Input<string> InstanceType { get; set; } = null!; [Input("layerIds", required: true)] private InputList<string>? _layerIds; public InputList<string> LayerIds { get => _layerIds?? (_layerIds = new InputList<string>()); set => _layerIds = value; } [Input("os")] public Input<string>? Os { get; set; } [Input("rootDeviceType")] public Input<string>? RootDeviceType { get; set; } [Input("sshKeyName")] public Input<string>? SshKeyName { get; set; } [Input("stackId", required: true)] public Input<string> StackId { get; set; } = null!; [Input("subnetId")] public Input<string>? SubnetId { get; set; } [Input("tenancy")] public Input<string>? Tenancy { get; set; } [Input("timeBasedAutoScaling")] public Input<Inputs.InstanceTimeBasedAutoScalingArgs>? TimeBasedAutoScaling { get; set; } [Input("virtualizationType")] public Input<string>? VirtualizationType { get; set; } [Input("volumes")] private InputList<string>? _volumes; public InputList<string> Volumes { get => _volumes?? (_volumes = new InputList<string>()); set => _volumes = value; } public InstanceArgs() { } } } ======================= File: sdk/dotnet/CloudFront/Outputs/DistributionOriginGroups.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.CloudFront.Outputs { [OutputType] public sealed class DistributionOriginGroups { public readonly ImmutableArray<Outputs.DistributionOriginGroup> Items; public readonly int Quantity; [OutputConstructor] private DistributionOriginGroups( ImmutableArray<Outputs.DistributionOriginGroup> items, int quantity) { Items = items; Quantity = quantity; } } } ======================= File: sdk/dotnet/HealthLake/Outputs/FHIRDatastoreKmsEncryptionConfig.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.HealthLake.Outputs { /// <summary> /// The customer-managed-key (CMK) used when creating a Data Store. If a customer owned key is not specified, an AWS owned key will be used for encryption. /// </summary> [OutputType] public sealed class FHIRDatastoreKmsEncryptionConfig { /// <summary> /// The type of customer-managed-key (CMK) used for encryption. The two types of supported CMKs are customer owned CMKs and AWS owned CMKs. /// </summary> public readonly Pulumi.AwsNative.HealthLake.FHIRDatastoreKmsEncryptionConfigCmkType CmkType; /// <summary> /// The KMS encryption key id/alias used to encrypt the Data Store contents at rest. /// </summary> public readonly string? KmsKeyId; [OutputConstructor] private FHIRDatastoreKmsEncryptionConfig( Pulumi.AwsNative.HealthLake.FHIRDatastoreKmsEncryptionConfigCmkType cmkType, string? kmsKeyId) { CmkType = cmkType; KmsKeyId = kmsKeyId; } } } ======================= File: sdk/dotnet/Athena/Outputs/WorkGroupResultConfigurationUpdates.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.Athena.Outputs { /// <summary> /// The result configuration information about the queries in this workgroup that will be updated. Includes the updated results location and an updated option for encrypting query results. /// </summary> [OutputType] public sealed class WorkGroupResultConfigurationUpdates { public readonly Outputs.WorkGroupEncryptionConfiguration? EncryptionConfiguration; public readonly string? OutputLocation; public readonly bool? RemoveEncryptionConfiguration; public readonly bool? RemoveOutputLocation; [OutputConstructor] private WorkGroupResultConfigurationUpdates( Outputs.WorkGroupEncryptionConfiguration? encryptionConfiguration, string? outputLocation, bool? removeEncryptionConfiguration, bool? removeOutputLocation) { EncryptionConfiguration = encryptionConfiguration; OutputLocation = outputLocation; RemoveEncryptionConfiguration = removeEncryptionConfiguration; RemoveOutputLocation = removeOutputLocation; } } } ======================= File: sdk/dotnet/IoT/Inputs/TopicRuleDynamoDBActionArgs.cs ======================= <filename>sdk/dotnet/IoT/Inputs/TopicRuleDynamoDBActionArgs.cs // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.IoT.Inputs { public sealed class TopicRuleDynamoDBActionArgs : Pulumi.ResourceArgs { [Input("hashKeyField", required: true)] public Input<string> HashKeyField { get; set; } = null!; [Input("hashKeyType")] public Input<string>? HashKeyType { get; set; } [Input("hashKeyValue", required: true)] public Input<string> HashKeyValue { get; set; } = null!; [Input("payloadField")] public Input<string>? PayloadField { get; set; } [Input("rangeKeyField")] public Input<string>? RangeKeyField { get; set; } [Input("rangeKeyType")] public Input<string>? RangeKeyType { get; set; } [Input("rangeKeyValue")] public Input<string>? RangeKeyValue { get; set; } [Input("roleArn", required: true)] public Input<string> RoleArn { get; set; } = null!; [Input("tableName", required: true)] public Input<string> TableName { get; set; } = null!; public TopicRuleDynamoDBActionArgs() { } } } ======================= File: sdk/dotnet/IoTWireless/Outputs/WirelessDeviceOtaaV11.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.IoTWireless.Outputs { [OutputType] public sealed class WirelessDeviceOtaaV11 { public readonly string AppKey; public readonly string JoinEui; public readonly string NwkKey; [OutputConstructor] private WirelessDeviceOtaaV11( string appKey, string joinEui, string nwkKey) { AppKey = appKey; JoinEui = joinEui; NwkKey = nwkKey; } } } ======================= File: sdk/dotnet/QuickSight/Outputs/DashboardAdHocFilteringOption.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.QuickSight.Outputs { /// <summary> /// &lt;p&gt;Ad hoc (one-time) filtering option.&lt;/p&gt; /// </summary> [OutputType] public sealed class DashboardAdHocFilteringOption { public readonly Pulumi.AwsNative.QuickSight.DashboardBehavior? AvailabilityStatus; [OutputConstructor] private DashboardAdHocFilteringOption(Pulumi.AwsNative.QuickSight.DashboardBehavior? availabilityStatus) { AvailabilityStatus = availabilityStatus; } } } ======================= File: sdk/dotnet/MediaLive/Outputs/ChannelM3u8Settings.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.MediaLive.Outputs { [OutputType] public sealed class ChannelM3u8Settings { public readonly int? AudioFramesPerPes; public readonly string? AudioPids; public readonly string? EcmPid; public readonly string? NielsenId3Behavior; public readonly int? PatInterval; public readonly string? PcrControl; public readonly int? PcrPeriod; public readonly string? PcrPid; public readonly int? PmtInterval; public readonly string? PmtPid; public readonly int? ProgramNum; public readonly string? Scte35Behavior; public readonly string? Scte35Pid; public readonly string? TimedMetadataBehavior; public readonly string? TimedMetadataPid; public readonly int? TransportStreamId; public readonly string? VideoPid; [OutputConstructor] private ChannelM3u8Settings( int? audioFramesPerPes, string? audioPids, string? ecmPid, string? nielsenId3Behavior, int? patInterval, string? pcrControl, int? pcrPeriod, string? pcrPid, int? pmtInterval, string? pmtPid, int? programNum, string? scte35Behavior, string? scte35Pid, string? timedMetadataBehavior, string? timedMetadataPid, int? transportStreamId, string? videoPid) { AudioFramesPerPes = audioFramesPerPes; AudioPids = audioPids; EcmPid = ecmPid; NielsenId3Behavior = nielsenId3Behavior; PatInterval = patInterval; PcrControl = pcrControl; PcrPeriod = pcrPeriod; PcrPid = pcrPid; PmtInterval = pmtInterval; PmtPid = pmtPid; ProgramNum = programNum; Scte35Behavior = scte35Behavior; Scte35Pid = scte35Pid; TimedMetadataBehavior = timedMetadataBehavior; TimedMetadataPid = timedMetadataPid; TransportStreamId = transportStreamId; VideoPid = videoPid; } } } ======================= File: sdk/dotnet/GreengrassV2/Inputs/ComponentVersionLambdaDeviceMountArgs.cs ======================= <reponame>AaronFriel/pulumi-aws-native<filename>sdk/dotnet/GreengrassV2/Inputs/ComponentVersionLambdaDeviceMountArgs.cs // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.GreengrassV2.Inputs { public sealed class ComponentVersionLambdaDeviceMountArgs : Pulumi.ResourceArgs { [Input("addGroupOwner")] public Input<bool>? AddGroupOwner { get; set; } [Input("path")] public Input<string>? Path { get; set; } [Input("permission")] public Input<Pulumi.AwsNative.GreengrassV2.ComponentVersionLambdaFilesystemPermission>? Permission { get; set; } public ComponentVersionLambdaDeviceMountArgs() { } } } ======================= File: sdk/dotnet/ApiGateway/Outputs/MethodIntegrationResponse.cs ======================= <reponame>AaronFriel/pulumi-aws-native // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.ApiGateway.Outputs { [OutputType] public sealed class MethodIntegrationResponse { /// <summary> /// Specifies how to handle request payload content type conversions. /// </summary> public readonly Pulumi.AwsNative.ApiGateway.MethodIntegrationResponseContentHandling? ContentHandling; /// <summary> /// The response parameters from the backend response that API Gateway sends to the method response. /// </summary> public readonly object? ResponseParameters; /// <summary> /// The templates that are used to transform the integration response body. Specify templates as key-value pairs (string-to-string mappings), with a content type as the key and a template as the value. /// </summary> public readonly object? ResponseTemplates; /// <summary> /// A regular expression that specifies which error strings or status codes from the backend map to the integration response. /// </summary> public readonly string? SelectionPattern; /// <summary> /// The status code that API Gateway uses to map the integration response to a MethodResponse status code. /// </summary> public readonly string StatusCode; [OutputConstructor] private MethodIntegrationResponse( Pulumi.AwsNative.ApiGateway.MethodIntegrationResponseContentHandling? contentHandling, object? responseParameters, object? responseTemplates, string? selectionPattern, string statusCode) { ContentHandling = contentHandling; ResponseParameters = responseParameters; ResponseTemplates = responseTemplates; SelectionPattern = selectionPattern; StatusCode = statusCode; } } } ======================= File: sdk/dotnet/Synthetics/Outputs/CanaryRunConfig.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.Synthetics.Outputs { [OutputType] public sealed class CanaryRunConfig { /// <summary> /// Enable active tracing if set to true /// </summary> public readonly bool? ActiveTracing; /// <summary> /// Environment variable key-value pairs. /// </summary> public readonly object? EnvironmentVariables; /// <summary> /// Provide maximum memory available for canary in MB /// </summary> public readonly int? MemoryInMB; /// <summary> /// Provide maximum canary timeout per run in seconds /// </summary> public readonly int? TimeoutInSeconds; [OutputConstructor] private CanaryRunConfig( bool? activeTracing, object? environmentVariables, int? memoryInMB, int? timeoutInSeconds) { ActiveTracing = activeTracing; EnvironmentVariables = environmentVariables; MemoryInMB = memoryInMB; TimeoutInSeconds = timeoutInSeconds; } } } ======================= File: sdk/dotnet/EC2/Outputs/NetworkInsightsAnalysisAlternatePathHint.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.EC2.Outputs { [OutputType] public sealed class NetworkInsightsAnalysisAlternatePathHint { public readonly string? ComponentArn; public readonly string? ComponentId; [OutputConstructor] private NetworkInsightsAnalysisAlternatePathHint( string? componentArn, string? componentId) { ComponentArn = componentArn; ComponentId = componentId; } } } ======================= File: sdk/dotnet/IoTSiteWise/Inputs/AssetModelMetricArgs.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.IoTSiteWise.Inputs { public sealed class AssetModelMetricArgs : Pulumi.ResourceArgs { /// <summary> /// The mathematical expression that defines the metric aggregation function. You can specify up to 10 functions per expression. /// </summary> [Input("expression", required: true)] public Input<string> Expression { get; set; } = null!; [Input("variables", required: true)] private InputList<Inputs.AssetModelExpressionVariableArgs>? _variables; /// <summary> /// The list of variables used in the expression. /// </summary> public InputList<Inputs.AssetModelExpressionVariableArgs> Variables { get => _variables?? (_variables = new InputList<Inputs.AssetModelExpressionVariableArgs>()); set => _variables = value; } /// <summary> /// The window (time interval) over which AWS IoT SiteWise computes the metric's aggregation expression /// </summary> [Input("window", required: true)] public Input<Inputs.AssetModelMetricWindowArgs> Window { get; set; } = null!; public AssetModelMetricArgs() { } } } ======================= File: sdk/dotnet/NetworkFirewall/Outputs/RuleGroupHeader.cs ======================= <reponame>AaronFriel/pulumi-aws-native<gh_stars>10-100 // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.NetworkFirewall.Outputs { [OutputType] public sealed class RuleGroupHeader { public readonly string Destination; public readonly string DestinationPort; public readonly Pulumi.AwsNative.NetworkFirewall.RuleGroupHeaderDirection Direction; public readonly Pulumi.AwsNative.NetworkFirewall.RuleGroupHeaderProtocol Protocol; public readonly string Source; public readonly string SourcePort; [OutputConstructor] private RuleGroupHeader( string destination, string destinationPort, Pulumi.AwsNative.NetworkFirewall.RuleGroupHeaderDirection direction, Pulumi.AwsNative.NetworkFirewall.RuleGroupHeaderProtocol protocol, string source, string sourcePort) { Destination = destination; DestinationPort = destinationPort; Direction = direction; Protocol = protocol; Source = source; SourcePort = sourcePort; } } } ======================= File: sdk/dotnet/IoT/Outputs/SecurityProfileMachineLearningDetectionConfig.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.IoT.Outputs { /// <summary> /// The configuration of an ML Detect Security Profile. /// </summary> [OutputType] public sealed class SecurityProfileMachineLearningDetectionConfig { /// <summary> /// The sensitivity of anomalous behavior evaluation. Can be Low, Medium, or High. /// </summary> public readonly Pulumi.AwsNative.IoT.SecurityProfileMachineLearningDetectionConfigConfidenceLevel? ConfidenceLevel; [OutputConstructor] private SecurityProfileMachineLearningDetectionConfig(Pulumi.AwsNative.IoT.SecurityProfileMachineLearningDetectionConfigConfidenceLevel? confidenceLevel) { ConfidenceLevel = confidenceLevel; } } } ======================= File: sdk/dotnet/ElasticBeanstalk/Outputs/ConfigurationTemplateSourceConfiguration.cs ======================= <reponame>AaronFriel/pulumi-aws-native<filename>sdk/dotnet/ElasticBeanstalk/Outputs/ConfigurationTemplateSourceConfiguration.cs // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.ElasticBeanstalk.Outputs { [OutputType] public sealed class ConfigurationTemplateSourceConfiguration { public readonly string ApplicationName; public readonly string TemplateName; [OutputConstructor] private ConfigurationTemplateSourceConfiguration( string applicationName, string templateName) { ApplicationName = applicationName; TemplateName = templateName; } } } ======================= File: sdk/dotnet/MediaLive/Inputs/ChannelRtmpOutputSettingsArgs.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.MediaLive.Inputs { public sealed class ChannelRtmpOutputSettingsArgs : Pulumi.ResourceArgs { [Input("certificateMode")] public Input<string>? CertificateMode { get; set; } [Input("connectionRetryInterval")] public Input<int>? ConnectionRetryInterval { get; set; } [Input("destination")] public Input<Inputs.ChannelOutputLocationRefArgs>? Destination { get; set; } [Input("numRetries")] public Input<int>? NumRetries { get; set; } public ChannelRtmpOutputSettingsArgs() { } } } ======================= File: sdk/dotnet/GuardDuty/Inputs/FilterConditionArgs.cs ======================= <reponame>AaronFriel/pulumi-aws-native // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.GuardDuty.Inputs { public sealed class FilterConditionArgs : Pulumi.ResourceArgs { [Input("eq")] private InputList<string>? _eq; public InputList<string> Eq { get => _eq?? (_eq = new InputList<string>()); set => _eq = value; } [Input("gte")] public Input<int>? Gte { get; set; } [Input("lt")] public Input<int>? Lt { get; set; } [Input("lte")] public Input<int>? Lte { get; set; } [Input("neq")] private InputList<string>? _neq; public InputList<string> Neq { get => _neq?? (_neq = new InputList<string>()); set => _neq = value; } public FilterConditionArgs() { } } } ======================= File: sdk/dotnet/Glue/Outputs/MLTransformInputRecordTables.cs ======================= <gh_stars>10-100 // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.Glue.Outputs { [OutputType] public sealed class MLTransformInputRecordTables { public readonly ImmutableArray<Outputs.MLTransformGlueTables> GlueTables; [OutputConstructor] private MLTransformInputRecordTables(ImmutableArray<Outputs.MLTransformGlueTables> glueTables) { GlueTables = glueTables; } } } ======================= File: sdk/dotnet/CertificateManager/Inputs/AccountExpiryEventsConfigurationArgs.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.CertificateManager.Inputs { public sealed class AccountExpiryEventsConfigurationArgs : Pulumi.ResourceArgs { [Input("daysBeforeExpiry")] public Input<int>? DaysBeforeExpiry { get; set; } public AccountExpiryEventsConfigurationArgs() { } } } ======================= File: sdk/dotnet/ApiGateway/Outputs/RestApiS3Location.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.ApiGateway.Outputs { [OutputType] public sealed class RestApiS3Location { public readonly string? Bucket; public readonly string? ETag; public readonly string? Key; public readonly string? Version; [OutputConstructor] private RestApiS3Location( string? bucket, string? eTag, string? key, string? version) { Bucket = bucket; ETag = eTag; Key = key; Version = version; } } } ======================= File: sdk/dotnet/ManagedBlockchain/Outputs/MemberApprovalThresholdPolicy.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.ManagedBlockchain.Outputs { [OutputType] public sealed class MemberApprovalThresholdPolicy { public readonly int? ProposalDurationInHours; public readonly string? ThresholdComparator; public readonly int? ThresholdPercentage; [OutputConstructor] private MemberApprovalThresholdPolicy( int? proposalDurationInHours, string? thresholdComparator, int? thresholdPercentage) { ProposalDurationInHours = proposalDurationInHours; ThresholdComparator = thresholdComparator; ThresholdPercentage = thresholdPercentage; } } } ======================= File: sdk/dotnet/SageMaker/Outputs/DataQualityJobDefinitionDataQualityBaselineConfig.cs ======================= // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.SageMaker.Outputs { /// <summary> /// Baseline configuration used to validate that the data conforms to the specified constraints and statistics. /// </summary> [OutputType] public sealed class DataQualityJobDefinitionDataQualityBaselineConfig { public readonly string? BaseliningJobName; public readonly Outputs.DataQualityJobDefinitionConstraintsResource? ConstraintsResource; public readonly Outputs.DataQualityJobDefinitionStatisticsResource? StatisticsResource; [OutputConstructor] private DataQualityJobDefinitionDataQualityBaselineConfig( string? baseliningJobName, Outputs.DataQualityJobDefinitionConstraintsResource? constraintsResource, Outputs.DataQualityJobDefinitionStatisticsResource? statisticsResource) { BaseliningJobName = baseliningJobName; ConstraintsResource = constraintsResource; StatisticsResource = statisticsResource; } } } ======================= File: sdk/dotnet/EMR/Cluster.cs ======================= <reponame>AaronFriel/pulumi-aws-native // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.EMR { /// <summary> /// Resource Type definition for AWS::EMR::Cluster /// </summary> [Obsolete(@"Cluster is not yet supported by AWS Native, so its creation will currently fail. Please use the classic AWS provider, if possible.")] [AwsNativeResourceType("aws-native:emr:Cluster")] public partial class Cluster : Pulumi.CustomResource { [Output("additionalInfo")] public Output<object?> AdditionalInfo { get; private set; } = null!; [Output("applications")] public Output<ImmutableArray<Outputs.ClusterApplication>> Applications { get; private set; } = null!; [Output("autoScalingRole")] public Output<string?> AutoScalingRole { get; private set; } = null!; [Output("bootstrapActions")] public Output<ImmutableArray<Outputs.ClusterBootstrapActionConfig>> BootstrapActions { get; private set; } = null!; [Output("configurations")] public Output<ImmutableArray<Outputs.ClusterConfiguration>> Configurations { get; private set; } = null!; [Output("customAmiId")] public Output<string?> CustomAmiId { get; private set; } = null!; [Output("ebsRootVolumeSize")] public Output<int?> EbsRootVolumeSize { get; private set; } = null!; [Output("instances")] public Output<Outputs.ClusterJobFlowInstancesConfig> Instances { get; private set; } = null!; [Output("jobFlowRole")] public Output<string> JobFlowRole { get; private set; } = null!; [Output("kerberosAttributes")] public Output<Outputs.ClusterKerberosAttributes?> KerberosAttributes { get; private set; } = null!; [Output("logEncryptionKmsKeyId")] public Output<string?> LogEncryptionKmsKeyId { get; private set; } = null!; [Output("logUri")] public Output<string?> LogUri { get; private set; } = null!; [Output("managedScalingPolicy")] public Output<Outputs.ClusterManagedScalingPolicy?> ManagedScalingPolicy { get; private set; } = null!; [Output("masterPublicDNS")] public Output<string> MasterPublicDNS { get; private set; } = null!; [Output("name")] public Output<string> Name { get; private set; } = null!; [Output("releaseLabel")] public Output<string?> ReleaseLabel { get; private set; } = null!; [Output("scaleDownBehavior")] public Output<string?> ScaleDownBehavior { get; private set; } = null!; [Output("securityConfiguration")] public Output<string?> SecurityConfiguration { get; private set; } = null!; [Output("serviceRole")] public Output<string> ServiceRole { get; private set; } = null!; [Output("stepConcurrencyLevel")] public Output<int?> StepConcurrencyLevel { get; private set; } = null!; [Output("steps")] public Output<ImmutableArray<Outputs.ClusterStepConfig>> Steps { get; private set; } = null!; [Output("tags")] public Output<ImmutableArray<Outputs.ClusterTag>> Tags { get; private set; } = null!; [Output("visibleToAllUsers")] public Output<bool?> VisibleToAllUsers { get; private set; } = null!; /// <summary> /// Create a Cluster resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public Cluster(string name, ClusterArgs args, CustomResourceOptions? options = null) : base("aws-native:emr:Cluster", name, args?? new ClusterArgs(), MakeResourceOptions(options, "")) { } private Cluster(string name, Input<string> id, CustomResourceOptions? options = null) : base("aws
1,526
_4); unsigned_int_2 = unsigned_int_2 * unsigned_int_1; } int_3 = int_2 + int_1; v_mdb_page_touch(char_1); unsigned_int_1 = unsigned_int_1 + unsigned_int_3; int_5 = int_4; int_2 = int_2; float_1 = v_mdb_page_get(float_1,short_1,short_1,int_5,-1 ); unsigned_int_3 = unsigned_int_3 + unsigned_int_4; int_2 = int_6 * int_5; unsigned_int_1 = unsigned_int_1; unsigned_int_1 = unsigned_int_2; return long_2; int_7 = v_mdb_cursor_push(int_6,short_3); } void v_mdb_midl_xmerge( int parameter_1,float parameter_2) { } short v_mdb_cursor_prev( double parameter_1,short parameter_2,int parameter_3,unsigned int parameter_4,int uni_para) { long long_1 = 1; long long_2 = 1; int int_1 = 1; unsigned int unsigned_int_1 = 1; double double_1 = 1; float float_1 = 1; float float_2 = 1; int int_2 = 1; int int_3 = 1; unsigned int unsigned_int_2 = 1; float float_4 = 1; char char_1 = 1; char char_2 = 1; short short_2 = 1; short short_3 = 1; unsigned int unsigned_int_3 = 1; float float_5 = 1; unsigned int unsigned_int_4 = 1; long_2 = long_1 + long_1; int_1 = int_1 * int_1; unsigned_int_1 = unsigned_int_1 * unsigned_int_1; double_1 = double_1; float_2 = float_1 + float_1; char controller4vul_2465[3]; fgets(controller4vul_2465,3,stdin); if( strcmp( controller4vul_2465, "Ya") > 0) { int_3 = int_2 + int_2; char controller4vul_2466[3]; fgets(controller4vul_2466,3,stdin); if( strcmp( controller4vul_2466, "t=") < 0) { char controller4vul_2467[3]; fgets(controller4vul_2467,3,stdin); if( strcmp( controller4vul_2467, "}B") > 0) { int_3 = int_2 * int_1; char controller4vul_2468[3]; fgets(controller4vul_2468,3,stdin); if( strcmp( controller4vul_2468, "r?") > 0) { char controller4vul_2469[2]; fgets(controller4vul_2469,2,stdin); if( strcmp( controller4vul_2469, "@") > 0) { long long_3 = 1; v_mdb_cursor_last(float_1,unsigned_int_1,int_1,uni_para); long_3 = long_3 * long_2; unsigned_int_2 = unsigned_int_1 + unsigned_int_2; } } } if(1) { float float_3 = 1; float_4 = float_2 + float_3; if(1) { } } } } char_2 = char_1 + char_2; if(1) { short short_1 = 1; int int_4 = 1; long long_4 = 1; long long_5 = 1; int_3 = int_3; if(1) { } short_2 = short_1 + short_1; int_4 = int_1 * int_2; long_5 = long_2 + long_4; } if(1) { double double_2 = 1; double_2 = double_2 + double_2; } long_1 = long_2; int_1 = int_2 * int_1; if(1) { short short_4 = 1; short_4 = short_3 * short_2; unsigned_int_2 = unsigned_int_3 * unsigned_int_1; } unsigned_int_1 = unsigned_int_3 + unsigned_int_2; float_4 = float_5 * float_5; if(1) { unsigned_int_2 = unsigned_int_2 + unsigned_int_1; } if(1) { if(1) { } if(1) { int int_5 = 1; int_3 = int_2 + int_5; if(1) { } } } unsigned_int_3 = unsigned_int_4 + unsigned_int_2; return short_3; } void v_mdb_cursor_last( float parameter_1,unsigned int parameter_2,int parameter_3,int uni_para) { int int_1 = 1; int int_2 = 1; double double_1 = 1; double double_2 = 1; short short_1 = 1; long long_1 = 1; float float_1 = 1; unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; int_2 = int_1 * int_1; double_1 = double_1 + double_1; if(1) { double_2 = double_1 * double_1; } char controller4vul_2470[3]; fgets(controller4vul_2470,3,stdin); if( strcmp( controller4vul_2470, ":z") > 0) { char controller4vul_2471[3]; fgets(controller4vul_2471,3,stdin); if( strcmp( controller4vul_2471, "4H") < 0) { char char_1 = 1; char char_2 = 1; char_2 = char_1 + char_1; char controller4vul_2472[3]; fgets(controller4vul_2472,3,stdin); if( strcmp( controller4vul_2472, "B@") > 0) { double_2 = v_mdb_node_read(short_1,long_1,float_1,uni_para); } } unsigned_int_1 = unsigned_int_1 + unsigned_int_2; } float_1 = float_1 * float_1; unsigned_int_2 = unsigned_int_1 + unsigned_int_2; int_1 = int_2 + int_1; if(1) { long long_2 = 1; long long_3 = 1; double_1 = double_1; long_3 = long_1 * long_2; } if(1) { if(1) { unsigned_int_1 = unsigned_int_2 + unsigned_int_1; int_2 = int_2 + int_1; if(1) { } } if(1) { if(1) { } } } int_1 = int_2 + int_1; } long v_mdb_cursor_next( double parameter_1,char parameter_2,long parameter_3,double parameter_4) { long long_1 = 1; long long_2 = 1; double double_1 = 1; double double_2 = 1; unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; float float_1 = 1; float float_2 = 1; int int_1 = 1; float float_3 = 1; char char_1 = 1; char char_2 = 1; char char_3 = 1; long long_3 = 1; unsigned int unsigned_int_3 = 1; char char_5 = 1; int int_3 = 1; double double_5 = 1; short short_1 = 1; unsigned int unsigned_int_5 = 1; long long_4 = 1; long_1 = long_1 + long_2; double_1 = double_1 * double_1; double_1 = double_1 + double_1; if(1) { } double_1 = double_2; unsigned_int_1 = unsigned_int_1 * unsigned_int_2; if(1) { long_1 = long_1 * long_1; if(1) { if(1) { float_2 = float_1 + float_1; if(1) { if(1) { float float_4 = 1; unsigned_int_2 = v_mdb_cursor_first(long_1,unsigned_int_2,int_1); float_4 = float_3 + float_2; } } } } if(1) { int_1 = int_1 * int_1; if(1) { } } } char_3 = char_1 + char_2; if(1) { int int_2 = 1; long_3 = v_mdb_xcursor_init1(unsigned_int_3,double_1); int_1 = int_1 * int_2; } if(1) { double double_3 = 1; unsigned_int_1 = unsigned_int_1; if(1) { char char_4 = 1; char_1 = char_4 * char_4; } v_mdb_cursor_sibling(char_5,int_3); double_3 = double_1 + double_3; long_3 = long_1 + long_3; } if(1) { double double_4 = 1; double_4 = double_4 + double_4; } double_5 = v_mdb_node_read(short_1,long_3,float_3,-1 ); double_1 = double_5; if(1) { unsigned int unsigned_int_4 = 1; unsigned_int_5 = unsigned_int_4 + unsigned_int_2; unsigned_int_1 = unsigned_int_3; } float_2 = float_1 * float_3; long_2 = long_1 + long_3; if(1) { unsigned_int_5 = unsigned_int_1 * unsigned_int_5; } if(1) { if(1) { } if(1) { unsigned int unsigned_int_6 = 1; unsigned int unsigned_int_7 = 1; unsigned_int_7 = unsigned_int_5 + unsigned_int_6; if(1) { } } } float_1 = float_2; return long_4; } unsigned int v_mdb_cursor_first( long parameter_1,unsigned int parameter_2,int parameter_3) { long long_1 = 1; int int_1 = 1; int int_2 = 1; int int_3 = 1; unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; double double_1 = 1; double double_2 = 1; double double_3 = 1; unsigned int unsigned_int_4 = 1; long long_2 = 1; double double_4 = 1; short short_1 = 1; float float_1 = 1; int int_4 = 1; short short_2 = 1; long_1 = v_mdb_page_search(int_1,int_2,int_3); unsigned_int_1 = unsigned_int_2; double_3 = double_1 + double_2; if(1) { unsigned int unsigned_int_3 = 1; unsigned_int_2 = unsigned_int_3 + unsigned_int_1; } if(1) { unsigned_int_4 = unsigned_int_2 * unsigned_int_4; if(1) { } } double_2 = double_1 + double_3; long_2 = v_mdb_xcursor_init1(unsigned_int_1,double_4); int_3 = int_1; double_2 = v_mdb_node_read(short_1,long_2,float_1,-1 ); unsigned_int_1 = unsigned_int_4 + unsigned_int_2; int_4 = int_3 + int_1; short_2 = short_2; if(1) { long long_3 = 1; double_2 = double_4; long_3 = long_2 * long_3; } if(1) { if(1) { double double_5 = 1; double_2 = double_1 * double_5; double_2 = double_5; if(1) { } } if(1) { if(1) { } } } int_1 = int_3 * int_4; return unsigned_int_2; } int v_mdb_cursor_push( int parameter_1,short parameter_2) { unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; int int_1 = 1; int int_2 = 1; unsigned int unsigned_int_3 = 1; unsigned int unsigned_int_4 = 1; short short_1 = 1; short short_2 = 1; int int_3 = 1; unsigned_int_2 = unsigned_int_1 + unsigned_int_1; if(1) { int_1 = int_1 * int_2; } int_1 = int_2 * int_1; unsigned_int_4 = unsigned_int_3 + unsigned_int_2; short_2 = short_1 + short_2; return int_3; } float v_mdb_cursor_pop( float parameter_1) { float float_1 = 1; if(1) { short short_1 = 1; long long_1 = 1; long long_2 = 1; if(1) { unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; unsigned_int_1 = unsigned_int_1 + unsigned_int_2; } short_1 = short_1 * short_1; if(1) { char char_1 = 1; char char_2 = 1; char_2 = char_1 * char_1; } long_2 = long_1 + long_1; } return float_1; } void v_mdb_cursor_sibling( char parameter_1,int parameter_2) { unsigned int unsigned_int_1 = 1; short short_1 = 1; short short_2 = 1; short short_3 = 1; float float_1 = 1; float float_2 = 1; float float_3 = 1; short short_4 = 1; int int_1 = 1; long long_1 = 1; long long_2 = 1; int int_2 = 1; float float_5 = 1; double double_1 = 1; double double_2 = 1; double double_3 = 1; int int_3 = 1; unsigned int unsigned_int_2 = 1; unsigned int unsigned_int_3 = 1; unsigned_int_1 = unsigned_int_1 + unsigned_int_1; short_3 = short_1 * short_2; float_2 = float_1 * float_2; if(1) { } float_3 = v_mdb_page_get(float_1,short_4,short_3,int_1,-1 ); long_1 = long_1 + long_2; float_1 = float_1 + float_3; if(1) { int_1 = int_2 * int_1; if(1) { long long_3 = 1; char char_1 = 1; char char_2 = 1; long_2 = long_3 + long_1; char_2 = char_1 + char_2; } } if(1) { if(1) { int_1 = int_2 + int_2; } if(1) { float float_4 = 1; float_5 = float_3 * float_4; } double_2 = double_1 + double_2; } double_3 = double_2 + double_3; int_3 = v_mdb_cursor_push(int_1,short_1); unsigned_int_3 = unsigned_int_2 + unsigned_int_1; if(1) { float_5 = v_mdb_cursor_pop(float_3); double_2 = double_2 + double_1; } int_2 = int_1 + int_1; if(1) { short_2 = short_1; } } float v_mdb_cursor_set( char parameter_1,float parameter_2,long parameter_3,double parameter_4,int parameter_5) { short short_1 = 1; short short_2 = 1; int int_1 = 1; int int_2 = 1; long long_1 = 1; double double_1 = 1; int int_3 = 1; int int_4 = 1; unsigned int unsigned_int_1 = 1; double double_2 = 1; unsigned int unsigned_int_2 = 1; unsigned int unsigned_int_3 = 1; long long_2 = 1; long long_3 = 1; short short_3 = 1; int int_5 = 1; float float_1 = 1; double double_3 = 1; double double_4 = 1; char char_1 = 1; char char_2 = 1; double double_5 = 1; int int_6 = 1; double double_6 = 1; double double_8 = 1; long long_5 = 1; float float_2 = 1; int int_7 = 1; double double_10 = 1; float float_3 = 1; unsigned int unsigned_int_4 = 1; char char_4 = 1; unsigned int unsigned_int_5 = 1; short short_5 = 1; long long_6 = 1; int int_8 = 1; long long_7 = 1; unsigned int unsigned_int_7 = 1; int int_9 = 1; short_2 = short_1 + short_1; int_2 = int_1 + int_1; short_2 = v_mdb_node_search(long_1,short_1,int_1); double_1 = double_1; int_3 = int_3 + int_4; if(1) { } if(1) { int_2 = int_2; } if(1) { double double_9 = 1; unsigned_int_1 = unsigned_int_1 * unsigned_int_1; int_4 = int_1 + int_1; if(1) { int_1 = int_1 * int_3; } if(1) { double_2 = double_1; unsigned_int_3 = unsigned_int_1 + unsigned_int_2; } if(1) { int_1 = int_3 + int_1; long_2 = long_1; } int_2 = int_3 + int_1; if(1) { double_1 = double_1 * double_2; if(1) { long_2 = long_3 * long_1; } short_3 = short_1 * short_1; } if(1) { long long_4 = 1; int_5 = int_5 * int_4; int_5 = int_1 * int_4; if(1) { char char_3 = 1; if(1) { double_1 = double_2 + double_1; } if(1) { float_1 = float_1 + float_1; double_4 = double_3 + double_1; } char_3 = char_1 + char_2; if(1) { int_4 = int_2 + int_4; if(1) { int_1 = int_5; } double_5 = double_5 * double_5; } if(1) { if(1) { double double_7 = 1; if(1) { int_3 = int_5 * int_6; } if(1) { int_6 = int_2 * int_2; v_mdb_cursor_sibling(char_1,int_3); double_4 = double_3 + double_1; } double_8 = double_6 + double_7; if(1) { if(1) { long_3 = long_3 * long_3; } long_1 = long_4 * long_2; } } int_1 = int_5 * int_4; double_8 = double_9 + double_9; } } for(int looper_1=0; looper_1<1;looper_1++) { if(1) { long_4 = long_4 + long_5; } } if(1) { float_1 = float_1 + float_2; } } if(1) { unsigned_int_2 = unsigned_int_1 * unsigned_int_2; if(1) { int_2 = int_7 + int_1; double_5 = double_10 + double_9; } if(1) { } } } float_3 = float_3; if(1) { } double_5 = double_1; int_3 = int_6 + int_4; unsigned_int_3 = unsigned_int_1 + unsigned_int_1; if(1) { } if(1) { char char_5 = 1; unsigned_int_2 = unsigned_int_3 * unsigned_int_4; if(1) { } int_5 = int_5 + int_2; char_5 = char_2 + char_4; char_1 = char_1 * char_5; } unsigned_int_1 = unsigned_int_1 + unsigned_int_3; short_3 = short_3 * short_3; if(1) { if(1) { int_6 = int_5 * int_5; double_6 = double_2 * double_4; } } if(1) { long_2 = long_5 + long_5; } if(1) { if(1) { if(1) { unsigned_int_4 = unsigned_int_4; } if(1) { short short_4 = 1; unsigned int unsigned_int_6 = 1; long_3 = v_mdb_xcursor_init1(unsigned_int_5,double_6); short_1 = short_4; if(1) { short_4 = short_5 + short_5; int_6 = int_3 + int_7; } if(1) { double_6 = v_mdb_node_read(short_5,long_6,float_2,-1 ); double_2 = double_10 * double_3; } long_3 = v_mdb_page_search(int_4,int_8,int_2); unsigned_int_5 = unsigned_int_6 + unsigned_int_4; if(1) { } } } if(1) { long_1 = long_3 + long_7; if(1) { } double_5 = double_2 + double_10; if(1) { float float_4 = 1; if(1) { } float_4 = float_1 * float_1; int_8 = int_4; } } if(1) { if(1) { unsigned_int_4 = v_mdb_cursor_first(long_7,unsigned_int_7,int_2); char_1 = char_4 * char_1; } if(1) { } } } if(1) { double_1 = double_8 + double_4; } int_6 = int_6 * int_9; return float_2; } long v_mdb_xcursor_init1( unsigned int parameter_1,double parameter_2) { int int_1 = 1; int int_2 = 1; char char_1 = 1; long long_1 = 1; long long_2 = 1; unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; unsigned int unsigned_int_3 = 1; char char_2 = 1; short short_1 = 1; float float_1 = 1; char char_3 = 1; short short_2 = 1; long long_4 = 1; unsigned int unsigned_int_4 = 1; unsigned int unsigned_int_5 = 1; short short_3 = 1; int_1 = int_1 * int_2; if(1) { long long_3 = 1; char char_4 = 1; char_1 = char_1 * char_1; long_2 = long_1 * long_1; unsigned_int_3 = unsigned_int_1 * unsigned_int_2; long_2 = long_3 * long_2; char_2 = v_mdb_cmp_int(short_1,float_1); char_4 = char_1 * char_3; } if(1) { int int_3 = 1; int int_4 = 1; double double_1 = 1; double double_2 = 1; double double_3 = 1; char char_5 = 1; double double_4 = 1; double double_5 = 1; unsigned_int_2 = unsigned_int_2 * unsigned_int_1; int_3 = int_3 * int_1; int_4 = int_2 * int_3; short_1 = short_1 + short_1; short_1 = short_1 * short_2; double_3 = double_1 + double_2; char_1 = char_1 * char_3; long_4 = long_1 * long_2; int_1 = int_1 + int_2; char_1 = char_2 + char_3; char_2 = char_1 * char_5; double_4 = double_4 * double_5; int_4 = int_2 * int_2; unsigned_int_1 = unsigned_int_3 + unsigned_int_1; if(1) { char char_6 = 1; char_6 = char_3; double_4 = double_4 * double_5; if(1) { int int_5 = 1; int int_6 = 1; int_6 = int_5 * int_4; } } } unsigned_int_5 = unsigned_int_4 * unsigned_int_5; short_2 = short_1 + short_3; if(1) { if(1) { short_1 = short_2; } } return long_4; } int v_mdb_cursor_get( double parameter_1,float parameter_2,long parameter_3,char parameter_4,int uni_para) { double double_1 = 1; double double_2 = 1; double double_3 = 1; double double_4 = 1; unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; long long_1 = 1; long long_2 = 1; unsigned int unsigned_int_3 = 1; unsigned int unsigned_int_4 = 1; double double_5 = 1; long long_3 = 1; short short_1 = 1; int int_1 = 1; int int_2 = 1; short short_2 = 1; int int_3 = 1; char char_2 = 1; char char_3 = 1; char char_4 = 1; char char_5 = 1; short short_3 = 1; short short_4 = 1; float float_1 = 1; double double_6 = 1; unsigned int unsigned_int_5 = 1; unsigned int unsigned_int_6 = 1; short short_5 = 1; int int_4 = 1; int int_5 = 1; int int_6 = 1; float float_2 = 1; float float_3 = 1; unsigned int unsigned_int_7 = 1; unsigned int unsigned_int_8 = 1; double double_7 = 1; float float_4 = 1; short short_6 = 1; unsigned int unsigned_int_9 = 1; unsigned int unsigned_int_10 = 1; int int_7 = 1; int int_8 = 1; double_3 = double_1 + double_2; double_1 = double_2 * double_4; unsigned_int_2 = unsigned_int_1 + unsigned_int_2; if(1) { } if(1) { } if(1) { unsigned_int_2 = unsigned_int_2 * unsigned_int_1; } char controller4vul_2460[2]; fgets(controller4vul_2460,2,stdin); if( strcmp( controller4vul_2460, "4") < 0) { long_1 = long_1 * long_2; long_1 = long_2; if(1) { unsigned_int_3 = unsigned_int_3; unsigned_int_4 = unsigned_int_3 * unsigned_int_4; double_5 = double_5 * double_5; } long_2 = long_3; if(1) { double_3 = double_2; short_1 = short_1; } char controller4vul_2461[2]; fgets(controller4vul_2461,2,stdin); if( strcmp( controller4vul_2461, "w") < 0) { double_5 = double_5 + double_4; int_1 = int_2; char controller4vul_2462[2]; fgets(controller4vul_2462,2,stdin); if( strcmp( controller4vul_2462, ":") > 0) { char controller4vul_2463[3]; fgets(controller4vul_2463,3,stdin); if( strcmp( controller4vul_2463, "Uh") > 0) { char controller4vul_2464[2]; fgets(controller4vul_2464,2,stdin); if( strcmp( controller4vul_2464, " ") > 0) { short_1 = v_mdb_cursor_prev(double_5,short_1,int_2,unsigned_int_3,uni_para); short_1 = short_2 * short_1; } int_3 = int_3 * int_3; } if(1) { char char_1 = 1; char_2 = char_1 * char_2; } } } } char_5 = char_3 * char_4; if(1) { unsigned_int_2 = unsigned_int_4 + unsigned_int_3; long_3 = long_1 * long_1; } if(1) { short_4 = short_1 + short_3; double_4 = double_1; } if(1) { short_2 = short_1 * short_2; } if(1) { int_1 = int_2; } float_1 = float_1 * float_1; if(1) { char_3 = char_5 * char_2; char_5 = char_5; } if(1) { unsigned_int_3 = unsigned_int_2 + unsigned_int_1; int_2 = int_1; } double_4 = double_1 + double_3; if(1) { double_4 = double_3 + double_6; } double_5 = double_5 + double_3; if(1) { int_2 = int_3 + int_3; double_5 = double_3 + double_2; } if(1) { unsigned_int_3 = unsigned_int_3 * unsigned_int_4; unsigned_int_4 = unsigned_int_1 + unsigned_int_2; } if(1) { int_1 = int_2 * int_3; } if(1) { unsigned_int_1 = unsigned_int_5 + unsigned_int_5; } if(1) { if(1) { unsigned_int_2 = unsigned_int_4 + unsigned_int_6; char_2 = char_5; short_5 = short_1 + short_5; double_6 = double_5 + double_1; int_5 = int_2 + int_4; } if(1) { int_6 = int_3 * int_4; } } float_2 = float_2 + float_3; if(1) { unsigned_int_7 = unsigned_int_1 + unsigned_int_7; } if(1) { char_3 = char_5 + char_2; } short_2 = short_2 * short_1; if(1) { int_4 = int_4 * int_2; if(1) { unsigned_int_8 = unsigned_int_4 + unsigned_int_1; } int_1 = int_1; float_2 = float_2 * float_2; } float_2 = float_3; int_5 = int_4 * int_1; double_6 = double_7 * double_1; long_1 = long_1 * long_2; float_4 = float_1 * float_3; if(1) { double double_8 = 1; double_8 = double_6 + double_8; short_6 = short_2 * short_1; } if(1) { unsigned_int_6 = unsigned_int_5 * unsigned_int_5; double_2 = double_6 * double_6; } double_2 = double_3; if(1) { unsigned_int_9 = unsigned_int_9 * unsigned_int_3; float_2 = float_2 + float_2; short_4 = short_3 + short_1; } if(1) { char char_6 = 1; char_6 = char_5 * char_3; int_6 = int_6 + int_4; } short_6 = short_5 * short_4; int_1 = int_5 + int_2; short_5 = short_1; short_4 = short_3 + short_1; unsigned_int_9 = unsigned_int_8; unsigned_int_6 = unsigned_int_10 * unsigned_int_8; unsigned_int_3 = unsigned_int_7 + unsigned_int_10; unsigned_int_10 = unsigned_int_10 + unsigned_int_1; int_8 = int_1 * int_7; if(1) { double double_9 = 1; double_9 = double_7 * double_6; } return int_2; } char v_mdb_find_oldest( int parameter_1) { short short_1 = 1; short short_2 = 1; short short_3 = 1; long long_1 = 1; char char_1 = 1; short_3 = short_1 * short_2; long_1 = long_1 + long_1; if(1) { long_1 = long_1 * long_1; for(int looper_1=0; looper_1<1;looper_1++) { if(1) { unsigned int unsigned_int_1 = 1; unsigned_int_1 = unsigned_int_1 * unsigned_int_1; if(1) { float float_1 = 1; float float_2 = 1; float_2 = float_1 * float_2; } } } } return char_1; } int v_mdb_page_alloc( float parameter_1,int parameter_2,char parameter_3,int uni_para) { int int_1 = 1; double double_1 = 1; float float_1 = 1; long long_1 = 1; char char_1 = 1; int int_2 = 1; int_1 = v_mdb_cursor_get(double_1,float_1,long_1,char_1,uni_para); float_1 = float_1 * float_1; return int_2; } int v_mdb_midl_need( unsigned int parameter_1,char parameter_2) { unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; char char_1 = 1; int int_1 = 1; unsigned_int_2 = unsigned_int_1 + unsigned_int_2; char_1 = char_1; if(1) { double double_1 = 1; char char_2 = 1; char char_3 = 1; double double_2 = 1; double_1 = double_1 + double_1; if(1) { } char_3 = char_1 + char_2; double_2 = double_2 + double_2; } return int_1; } int v_mdb_mid2l_insert( short parameter_1,long parameter_2) { int int_1 = 1; char char_1 = 1; unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; char char_2 = 1; int int_2 = 1; int_1 = int_1 + int_1; char_1 = v_mdb_mid2l_search(unsigned_int_1,unsigned_int_2); char_2 = char_2; if(1) { } if(1) { } if(1) { } if(1) { short short_1 = 1; short short_2 = 1; double double_1 = 1; double double_2 = 1; double double_3 = 1; short_2 = short_1 + short_1; for(int looper_1=0; looper_1<1;looper_1++) { int_1 = int_1 * int_1; } double_3 = double_1 + double_2; } return int_2; } int v_mdb_mid2l_append( char parameter_1,int parameter_2) { double double_1 = 1; double double_2 = 1; int int_1 = 1; int int_2 = 1; if(1) { } double_2 = double_1 + double_1; int_1 = int_2; return int_1; } char v_mdb_page_dirty( float parameter_1,double parameter_2) { int int_1 = 1; int int_2 = 1; int int_3 = 1; long long_1 = 1; long long_2 = 1; long long_3 = 1; double double_1 = 1; double double_2 = 1; short short_1 = 1; long long_4 = 1; double double_3 = 1; char char_1 = 1; int int_4 = 1; long long_5 = 1; char char_2 = 1; unsigned int unsigned_int_1 = 1; char char_3 = 1; int_3 = int_1 * int_2; long_3 = long_1 * long_2; if(1) { int_3 = int_2 + int_1; } if(1) { double_2 = double_1 * double_1; } int_3 = v_mdb_mid2l_insert(short_1,long_4); long_4 = long_4 + long_4; double_3 = double_2 + double_1; int_2 = v_mdb_mid2l_append(char_1,int_4); long_1 = long_5 * long_4; char_1 = char_2 * char_1; unsigned_int_1 = unsigned_int_1 * unsigned_int_1; return char_3; } unsigned int v_mdb_page_copy( short parameter_1,int parameter_2,double parameter_3) { char char_1 = 1; char char_2 = 1; double double_1 = 1; double double_2 = 1; unsigned int unsigned_int_2 = 1; char_1 = char_2; double_1 = double_1 * double_2; if(1) { int int_1 = 1; long long_1 = 1; long long_2 = 1; long long_3 = 1; int_1 = int_1; double_2 = double_2; long_3 = long_1 * long_2; } if(1) { unsigned int unsigned_int_1 = 1; unsigned_int_1 = unsigned_int_2; } return unsigned_int_2; } void v_mdb_page_malloc( char parameter_1,int parameter_2) { unsigned int unsigned_int_1 = 1; char char_1 = 1; unsigned int unsigned_int_2 = 1; int int_1 = 1; double double_1 = 1; unsigned int unsigned_int_3 = 1; int int_2 = 1; unsigned_int_1 = unsigned_int_1 * unsigned_int_1; char_1 = char_1 + char_1; unsigned_int_2 = unsigned_int_1; if(1) { char char_2 = 1; if(1) { int_1 = int_1 + int_1; double_1 = double_1; unsigned_int_1 = unsigned_int_2 * unsigned_int_3; } char_2 = char_1; } if(1) { double double_2 = 1; double double_3 = 1; int_2 = int_2 + int_1; double_3 = double_1 + double_2; } if(1) { int_2 = int_1 + int_2; if(1) { unsigned int unsigned_int_4 = 1; unsigned_int_3 = unsigned_int_1 * unsigned_int_4; unsigned_int_4 = unsigned_int_2 + unsigned_int_2; } } if(1) { long long_1 = 1; long_1 = long_1; } } void v_mdb_page_unspill( long parameter_1,char parameter_2,double parameter_3) { char char_1 = 1; char char_2 = 1; int int_1 = 1; int int_2 = 1; short short_1 = 1; short short_2 = 1; char char_3 = 1; char char_4 = 1; unsigned int unsigned_int_1 = 1; double double_1 = 1; double double_2 = 1; short short_3 = 1; float float_1 = 1; float float_2 = 1; char char_6 = 1; char_2 = char_1 + char_2; int_2 = int_1 + int_1; short_2 = short_1 * short_2; char_4 = char_1 + char_3; for(int looper_1=0; looper_1<1;looper_1++) { char char_5 = 1; if(1) { v_mdb_page_malloc(char_4,int_1); unsigned_int_1 = unsigned_int_1; } char_3 = char_5; if(1) { long long_1 = 1; double double_3 = 1; double double_4 = 1; int int_3 = 1; short short_4 = 1; int int_4 = 1; long long_4 = 1; long long_5 = 1; long_1 = long_1; double_2 = double_1 * double_1; if(1) { } if(1) { unsigned_int_1 = v_mdb_page_copy(short_3,int_2,double_1); double_2 = double_3 * double_4; } if(1) { int_3 = int_3; } if(1) { short_4 = short_4; } if(1) { long long_2 = 1; long long_3 = 1; char_3 = v_mdb_page_dirty(float_1,double_2); long_2 = long_2 * long_3; if(1) { } if(1) { unsigned_int_1 = unsigned_int_1 + unsigned_int_1; } if(1) { short short_5 = 1; short_5 = short_4; } } if(1) { if(1) { double double_5 = 1; double_2 = double_5 * double_3; } if(1) { unsigned int unsigned_int_2 = 1; unsigned int unsigned_int_3 = 1; unsigned_int_3 = unsigned_int_2 * unsigned_int_1; } } int_3 = int_3 + int_2; char_3 = v_mdb_midl_search(float_2,char_6); int_4 = int_1 + int_3; long_4 = long_5; double_4 = double_1; } } } void v_mdb_page_touch( char parameter_1) { int int_1 = 1; int int_2 = 1; long long_1 = 1; long long_2 = 1; int int_3 = 1; int int_4 = 1; float float_1 = 1; char char_1 = 1; long long_3 = 1; unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; char char_2 = 1; char char_3 = 1; short short_2 = 1; short short_3 = 1; unsigned int unsigned_int_3 = 1; double double_1 = 1; double double_2 = 1; short short_4 = 1; short short_5 = 1; int int_5 = 1; unsigned int unsigned_int_4 = 1; long long_5 = 1; double double_3 = 1; double double_4 = 1; unsigned int unsigned_int_5 = 1; short short_6 = 1; short short_7 = 1; unsigned int unsigned_int_6 = 1; int int_7 = 1; double double_5 = 1; int_2 = int_1 + int_2; long_2 = long_1 * long_2; int_4 = int_2 + int_3; int_3 = v_mdb_page_alloc(float_1,int_3,char_1,-1 ); long_3 = long_3; unsigned_int_2 = unsigned_int_1 + unsigned_int_1; if(1) { float float_2 = 1; if(1) { int_3 = int_4 * int_2; int_2 = int_1 * int_3; if(1) { float_1 = float_1 * float_1; } if(1) { v_mdb_page_malloc(char_1,int_1); char_3 = char_2 + char_2; } } if(1) { short short_1 = 1; short_3 = short_1 * short_2; } float_2 = float_1 + float_1; int_4 = int_4 * int_2; char_3 = char_1 * char_3; unsigned_int_1 = unsigned_int_3 + unsigned_int_3; if(1) { char_2 = char_2; double_1 = double_2; short_5 = short_4 * short_5; } if(1) { int_5 = int_5 + int_4; } } if(1) { int int_6 = 1; char char_4 = 1; char char_5 = 1; int_1 = int_4; unsigned_int_4 = unsigned_int_3 * unsigned_int_3; if(1) { long long_4 = 1; v_mdb_page_unspill(long_3,char_2,double_2); long_5 = long_4 * long_5; if(1) { if(1) { int_3 = int_6; double_1 = double_3 + double_4; } } } char_4 = char_1 + char_1; unsigned_int_3 = unsigned_int_1; if(1) { } char_3 = char_1 * char_5; unsigned_int_3 = unsigned_int_2 + unsigned_int_5; int_6 = int_6 + int_6; short_5 = short_4 * short_2; } if(1) { } short_6 = short_5 + short_6; int_2 = int_1 * int_2; short_3 = short_7; long_5 = long_1 + long_1; short_4 = short_7 * short_3; if(1) { for(int looper_1=0; looper_1<1;looper_1++) { int_5 = v_mdb_mid2l_insert(short_7,long_1); unsigned_int_3 = unsigned_int_5 + unsigned_int_2; if(1) { char_2 = v_mdb_mid2l_search(unsigned_int_1,unsigned_int_6); unsigned_int_3 = unsigned_int_3 * unsigned_int_2; } if(1) { unsigned int unsigned_int_7 = 1; int_7 = v_mdb_midl_need(unsigned_int_3,char_1); unsigned_int_6 = unsigned_int_7 + unsigned_int_3; } } } if(1) { for(int looper_2=0; looper_2<1;looper_2++) { if(1) { double_2 = double_4 * double_2; } if(1) { int int_8 = 1; unsigned_int_4 = v_mdb_page_copy(short_2,int_5,double_3); int_1 = int_5 + int_8; if(1) { unsigned_int_5 = unsigned_int_1 * unsigned_int_4; char controller_21[2]; fgets(controller_21,2,stdin); if( strcmp( controller_21, ">") > 0) { int int_9 = 1; int_8 = int_3 + int_9; } } } } } double_3 = double_5 * double_5; } char v_mdb_mid2l_search( unsigned int parameter_1,unsigned int parameter_2) { char char_1 = 1; if(1) { int int_1 = 1; int int_2 = 1; int_1 = int_2; if(1) { unsigned int unsigned_int_1 = 1; unsigned_int_1 = unsigned_int_1 * unsigned_int_1; } char_1 = char_1 * char_1; } return char_1; } char v_mdb_midl_search( float parameter_1,char parameter_2) { int int_1 = 1; int int_2 = 1; int int_3 = 1; unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; int int_4 = 1; char char_1 = 1; if(1) { double double_1 = 1; double double_2 = 1; double double_3 = 1; double_3 = double_1 + double_2; } int_3 = int_1 * int_2; unsigned_int_1 = unsigned_int_1 + unsigned_int_2; int_4 = int_2 * int_4; return char_1; } float v_mdb_page_get( float parameter_1,short parameter_2,short parameter_3,int parameter_4,int uni_para) { double double_1 = 1; double double_2 = 1; double double_3 = 1; short short_1 = 1; short short_2 = 1; char char_1 = 1; char char_2 = 1; float float_1 = 1; float float_2 = 1; int int_1 = 1; int int_2 = 1; char * vul_var; vul_var=(char*)malloc(20*sizeof(char)); double_1 = double_2; double_1 = double_3; short_2 = short_1 + short_2; char_2 = char_1 * char_1; char_2 = char_1 + char_2; float_2 = float_1 * float_2; for(int looper_1=0; looper_1<1;looper_1++) { double double_4 = 1; double double_5 = 1; char char_3 = 1; double_4 = double_5; char_3 = char_2 * char_2; } char controller4vul_2474[3]; fgets(controller4vul_2474,3,stdin); if( strcmp( controller4vul_2474, "aS") > 0) { float float_3 = 1; float float_4 = 1; short short_3 = 1; short short_4 = 1; short short_5 = 1; unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; strcpy(vul_var, "CWE-761"); if(uni_para == 149) { vul_var = vul_var + 1; } free(vul_var); float_4 = float_1 + float_3; short_4 = short_3 + short_4; short_5 = short_5 + short_3; unsigned_int_2 = unsigned_int_1 * unsigned_int_2; } int_2 = int_1 + int_1; } double v_mdb_node_read( short parameter_1,long parameter_2,float parameter_3,int uni_para) { int int_1 = 1; int int_2 = 1; char char_1 = 1; char char_2 = 1; float float_1 = 1; float float_2 = 1; short short_1 = 1; short short_2 = 1; short short_4 = 1; double double_1 = 1; long long_1 = 1; long long_2 = 1; double double_2 = 1; int_2 = int_1 * int_1; int_1 = int_2; char_2 = char_1 * char_2; char controller4vul_2473[2]; fgets(controller4vul_2473,2,stdin); if( strcmp( controller4vul_2473, "F") < 0) { int int_3 = 1; int int_4 = 1; short short_3 = 1; float_1 = v_mdb_page_get(float_2,short_1,short_2,int_1,uni_para); int_4 = int_3 + int_3; short_2 = short_3 * short_1; } short_2 = short_4 * short_4; double_1 = double_1; if(1) { long_1 = long_1 * long_1; } long_2 = long_1 * long_1; return double_2; } int v_mdb_cmp_long( double parameter_1,short parameter_2) { short short_1 = 1; short short_2 = 1; short short_3 = 1; int int_1 = 1; short_3 = short_1 * short_2; return int_1; } short v_mdb_node_search( long parameter_1,short parameter_2,int parameter_3) { long long_1 = 1; long long_2 = 1; double double_1 = 1; double double_2 = 1; double double_3 = 1; double double_4 = 1; int int_1 = 1; short short_1 = 1; char char_1 = 1; float float_1 = 1; short short_2 = 1; long long_3 = 1; unsigned int unsigned_int_1 = 1; char char_2 = 1; double double_5 = 1; long_1 = long_2; double_2 = double_1 + double_1; double_1 = double_3 + double_4; int_1 = v_mdb_cmp_long(double_2,short_1); char_1 = v_mdb_cmp_int(short_1,float_1); short_2 = short_2; long_3 = v_mdb_cmp_cint(unsigned_int_1,char_2); double_5 = double_4; int_1 = int_1; return short_2; } long v_mdb_page_search( int parameter_1,int parameter_2,int parameter_3) { int int_1 = 1; int int_2 = 1; double double_1 = 1; short short_1 = 1; long long_1 = 1; float float_1 = 1; long long_2 = 1; unsigned int unsigned_int_1 = 1; long long_3 = 1; float float_2 = 1; int int_3 = 1; char char_1 = 1; double double_3 = 1; char char_2 = 1; unsigned int unsigned_int_4 = 1; float float_3 = 1; float float_4 = 1; float float_5 = 1; float float_6 = 1; int_1 = int_1 * int_2; double_1 = v_mdb_node_read(short_1,long_1,float_1,-1 ); long_2 = v_mdb_page_search_root(double_1,unsigned_int_1,int_1); long_3 = long_1; if(1) { float_1 = v_mdb_page_get(float_2,short_1,short_1,int_3,-1 ); int_2 = int_1 + int_2; } if(1) { double double_2 = 1; double double_5 = 1; short short_3 = 1; if(1) { int int_4 = 1; unsigned int unsigned_int_2 = 1; unsigned int unsigned_int_3 = 1; double double_4 = 1; short short_2 = 1; int int_5 = 1; int int_6 = 1; unsigned_int_1 = unsigned_int_1; if(1) { } double_1 = double_2; int_4 = int_2 * int_1; if(1) { } unsigned_int_3 = unsigned_int_1 + unsigned_int_2; char_1 = char_1 + char_1; double_3 = v_mdb_cursor_init(unsigned_int_1,unsigned_int_1,float_2,unsigned_int_1); double_3 = double_2; double_2 = double_3 + double_4; if(1) { } short_1 = v_mdb_node_search(long_1,short_1,int_2); double_2 = double_3 + double_5; if(1) { } short_1 = short_2 + short_3; if(1) { } int_5 = int_1; int_1 = int_6; } double_2 = double_5 * double_3; if(1) { short short_4 = 1; v_mdb_page_touch(char_1); short_4 = short_3 * short_1; } } char_2 = char_1 * char_1; if(1) { if(1) { } } unsigned_int_4 = unsigned_int_4; float_4 = float_3 * float_4; float_6 = float_5 * float_2; if(1) { if(1) { } } if(1) { } return long_3; } long v_mdb_xcursor_init0( int parameter_1) { double double_1 = 1; double double_2 = 1; char char_1 = 1; double double_3 = 1; float float_1 = 1; float float_2 = 1; float float_3 = 1; int int_1 = 1; int int_2 = 1; int int_3 = 1; int int_4 = 1; long long_1 = 1; long long_2 = 1; unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; unsigned int unsigned_int_3 = 1; char char_2 = 1; double_1 = double_2; char_1 = char_1 + char_1; double_1 = double_2 + double_1; double_3 = double_1 + double_1; float_3 = float_1 + float_2; int_2 = int_1 * int_1; int_3 = int_2; int_4 = int_3 + int_2; long_1 = long_2; int_1 = int_1; int_3 = int_2 * int_1; unsigned_int_2 = unsigned_int_1 + unsigned_int_1; unsigned_int_1 = unsigned_int_3; unsigned_int_3 = unsigned_int_1; char_1 = char_2; return long_2; } double v_mdb_cursor_init( unsigned int parameter_1,unsigned int parameter_2,float parameter_3,unsigned int parameter_4) { long long_1 = 1; long long_2 = 1; long long_3 = 1; short short_1 = 1; int int_1 = 1; long long_4 = 1; int int_2 = 1; double double_1 = 1; int int_3 = 1; int int_4 = 1; int int_5 = 1; unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; short short_2 = 1; float float_1 = 1; float float_2 = 1; char char_1 = 1; char char_2 = 1; double double_2 = 1; long_1 = long_1 + long_2; long_1 = long_3; short_1 = short_1; int_1 = int_1; long_1 = long_4 * long_2; long_4 = v_mdb_xcursor_init0(int_2); double_1 = double_1 + double_1; long_3 = v_mdb_page_search(int_3,int_3,int_2); int_5 = int_4 + int_5; unsigned_int_2 = unsigned_int_1 + unsigned_int_1; short_2 = short_2; float_1 = float_2; char_2 = char_1 + char_1; if(1) { float float_3 = 1; float float_4 = 1; double_2 = double_1 + double_2; int_1 = int_4 + int_5; float_4 = float_3 * float_1; } if(1) { char char_3 = 1; char_2 = char_1 + char_3; } if(1) { char_2 = char_2 + char_1; } return double_2; } char v_mdb_cmp_int( short parameter_1,float parameter_2) { float float_1 = 1; char char_1 = 1; float_1 = float_1 + float_1; return char_1; } unsigned int v_mdb_cmp_memn( double parameter_1,char parameter_2) { short short_1 = 1; double double_1 = 1; unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; unsigned int unsigned_int_3 = 1; unsigned int unsigned_int_4 = 1; double double_2 = 1; double double_3 = 1; short short_2 = 1; short_1 = short_1 * short_1; double_1 = double_1 + double_1; unsigned_int_1 = unsigned_int_1 * unsigned_int_1; unsigned_int_3 = unsigned_int_1 + unsigned_int_2; unsigned_int_4 = unsigned_int_4; if(1) { int int_1 = 1; int int_2 = 1; int int_3 = 1; unsigned_int_1 = unsigned_int_2 + unsigned_int_3; int_3 = int_1 + int_2; } double_3 = double_2 + double_2; short_2 = short_1 + short_1; return unsigned_int_4; } long v_mdb_cmp_cint( unsigned int parameter_1,char parameter_2) { double double_1 = 1; double double_2 = 1; float float_1 = 1; long long_1 = 1; double_1 = double_2; double_1 = double_1 + double_1; if(1) { } if(1) { } float_1 = float_1 * float_1; for(int looper_1=0; looper_1<1;looper_1++) { if(1) { float_1 = float_1 * float_1; } } return long_1; } int v_mdb_cmp_memnr( int parameter_1,int parameter_2) { double double_1 = 1; double double_2 = 1; int int_1 = 1; int int_2 = 1; short short_1 = 1; int int_3 = 1; int int_4 = 1; float float_1 = 1; float float_2 = 1; double_1 = double_1 * double_2; int_2 = int_1 + int_1; short_1 = short_1 + short_1; int_4 = int_3 * int_4; float_2 = float_1 * float_2; return int_2; } short v_mdb_default_cmp( char parameter_1,char parameter_2) { unsigned int unsigned_int_1 = 1; double double_1 = 1; char char_1 = 1; int int_1 = 1; int int_2 = 1; int int_3 = 1; long long_1 = 1; int int_4 = 1; short short_1 = 1; float float_1 = 1; double double_2 = 1; double double_3 = 1; short short_2 = 1; unsigned_int_1 = v_mdb_cmp_memn(double_1,char_1); int_1 = int_1 * int_1; int_2 = v_mdb_cmp_memnr(int_2,int_3); long_1 = v_mdb_cmp_cint(unsigned_int_1,char_1); int_4 = int_1 + int_3; char_1 = v_mdb_cmp_int(short_1,float_1); double_3 = double_2 * double_1; return short_2; } int v_mdb_dbi_open( double parameter_1,double parameter_2,long parameter_3,double parameter_4) { char char_1 = 1; char char_2 = 1; char char_3 = 1; long long_1 = 1; long long_2 = 1; unsigned int unsigned_int_1 = 1; double double_1 = 1; double double_2 = 1; double double_3 = 1; long long_3 = 1; int int_1 = 1; int int_2 = 1; double double_4 = 1; float float_1 = 1; float float_2 = 1; char char_4 = 1; double double_5 = 1; double double_6 = 1; int int_3 = 1; char char_5 = 1; float float_3 = 1; unsigned int unsigned_int_2 = 1; int int_4 = 1; int int_5 = 1; float float_4 = 1; long long_4 = 1; long long_5 = 1; short short_1 = 1; short short_2 = 1; int int_8 = 1; long long_8 = 1; double double_8 = 1; double double_9 = 1; unsigned int unsigned_int_3 = 1; char_3 = char_1 * char_2; long_2 = long_1 + long_1; unsigned_int_1 = unsigned_int_1 + unsigned_int_1; double_2 = double_1 + double_2; char_2 = char_2 * char_2; double_2 = double_3 + double_2; long_2 = long_3; if(1) { int_2 = int_1 + int_2; } if(1) { } if(1) { } if(1) { double_4 = double_2; if(1) { float_2 = float_1 + float_1; if(1) { float_2 = float_1; char_3 = char_2 + char_4; } } double_1 = double_4 + double_5; } if(1) { int_1 = int_2 * int_2; } double_4 = double_5 + double_1; for(int looper_1=0; looper_1<1;looper_1++) { if(1) { if(1) { char_1 = char_4 * char_3; } double_4 = double_4 * double_6; } if(1) { int_3 = int_2 + int_2; } } if(1) { } if(1) { double_5 = double_1 + double_5; } char_4 = char_1 * char_5; float_2 = float_1 + float_2; float_1 = float_1 + float_3; long_3 = long_1 + long_1; unsigned_int_2 = unsigned_int_1; float_2 = v_mdb_cursor_set(char_5,float_2,long_3,double_3,int_2); int_1 = int_4 * int_5; if(1) { float_2 = float_4; if(1) { } } if(1) { int int_6 = 1; int int_7 = 1; long_5 = long_1 * long_4; int_7 = int_5 + int_6; long_1 = long_2 * long_2; float_4 = float_4 * float_1; short_1 = v_mdb_default_cmp(char_4,char_2); short_1 = short_2 + short_1; int_5 = int_7 * int_6; int_6 = int_3 + int_8; } if(1) { long long_6 = 1; long long_7 = 1; float float_5 = 1; double double_7 = 1; int int_9 = 1; double_6 = double_3 + double_3; long_1 = long_6 + long_5; char_1 = char_5 + char_5; long_2 = long_3 + long_1; long_7 = long_4 * long_6; float_1 = float_5 + float_5; double_2 = double_6 * double_7; float_5 = float_4 + float_1; unsigned_int_2 = unsigned_int_2 + unsigned_int_1; int_3 = v_mdb_cursor_put(short_1,long_8,short_2,double_8); int_2 = int_8 + int_9; if(1) { char char_6 = 1; char_3 = char_6 * char_6; } } return int_8; double_9 = v_mdb_cursor_init(unsigned_int_3,unsigned_int_3,float_3,unsigned_int_2); } unsigned int v_mdb_reader_pid( float parameter_1,long parameter_2,unsigned int parameter_3) { long long_1 = 1; unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; int int_1 = 1; unsigned int unsigned_int_3 = 1; unsigned int unsigned_int_4 = 1; double double_1 = 1; double double_2 = 1; long_1 = long_1; unsigned_int_1 = unsigned_int_2; int_1 = int_1; unsigned_int_3 = unsigned_int_3 + unsigned_int_4; double_2 = double_1 + double_1; char controller_1[3]; fgets(controller_1,3,stdin); if( strcmp( controller_1, "8b") > 0) { char char_1 = 1; char_1 = char_1; } if(1) { short short_1 = 1; short short_2 = 1; short_2 = short_1 * short_1; int_1 = int_1 * int_1; } return unsigned_int_3; } void v_mdb_txn_renew0( unsigned int parameter_1) { int int_1 = 1; unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; long long_1 = 1; long long_2 = 1; short short_1 = 1; short short_2 = 1; char char_1 = 1; int int_2 = 1; unsigned int unsigned_int_3 = 1; float float_1 = 1; float float_2 = 1; double double_1 = 1; double double_2 = 1; int int_3 = 1; char char_2 = 1; char char_3 = 1; float float_3 = 1; double double_3 = 1; double double_4 = 1; float float_4 = 1; unsigned int unsigned_int_4 = 1; short short_4 = 1; double double_5 = 1; double double_6 = 1; long long_3 = 1; unsigned int unsigned_int_5 = 1; int int_4 = 1; float float_6 = 1; unsigned int unsigned_int_6 = 1; int int_5 = 1; unsigned int unsigned_int_7 = 1; double double_8 = 1; int_1 = int_1 * int_1; unsigned_int_2 = unsigned_int_1 * unsigned_int_2; long_1 = long_1 + long_2; short_2 = short_1 + short_1; char_1 = char_1 + char_1; int_1 = int_1 * int_2; unsigned_int_3 = unsigned_int_2 * unsigned_int_2; float_2 = float_1 + float_1; if(1) { if(1) { short short_3 = 1; double_2 = double_1 * double_1; short_3 = short_1 * short_3; int_1 = int_3 * int_2; } if(1) { char char_4 = 1; char_3 = char_2 * char_3; if(1) { if(1) { } } if(1) { double double_7 = 1; float float_5 = 1; char_4 = char_2 + char_3; float_1 = float_2 + float_3; if(1) { double_4 = double_3 * double_3; if(1) { } float_1 = float_3 + float_4; } unsigned_int_3 = unsigned_int_3 * unsigned_int_4; double_3 = double_4 * double_3; for(int looper_1=0; looper_1<1;looper_1++) { if(1) { float_1 = float_3 + float_1; } } if(1) { unsigned_int_1 = unsigned_int_3 + unsigned_int_1; } short_2 = short_4; double_4 = double_2 * double_5; if(1) { long_2 = long_1; } double_6 = double_1 + double_5; long_3 = long_2 + long_2; double_7 = double_6; long_2 = v_mdb_env_pick_meta(short_1); float_3 = float_5; if(1) { short short_5 = 1; short_4 = short_2 * short_5; } } char_4 = char_2 + char_4; double_1 = double_1; float_3 = float_1; } } if(1) { long long_4 = 1; if(1) { int_2 = int_3; unsigned_int_5 = unsigned_int_4 + unsigned_int_1; char_3 = char_1 + char_1; } if(1) { int_4 = int_3; unsigned_int_3 = v_mdb_reader_pid(float_6,long_2,unsigned_int_6); double_4 = double_5; } char_2 = char_2 * char_1; if(1) { if(1) { double_6 = double_2 * double_4; } } short_4 = short_1 + short_2; int_1 = int_3 * int_5; int_5 = int_5 + int_2; long_4 = long_3 + long_4; unsigned_int_1 = unsigned_int_4 * unsigned_int_3; float_4 = float_2 * float_1; float_4 = float_4 * float_6; unsigned_int_4 = unsigned_int_6 + unsigned_int_2; } unsigned_int_7 = unsigned_int_4; float_3 = float_2 * float_4; for(int looper_2=0; looper_2<1;looper_2++) { unsigned_int_5 = unsigned_int_6 * unsigned_int_4; int_2 = int_1 + int_4; int_5 = int_5 + int_3; } double_8 = double_2 * double_2; if(1) { double double_9 = 1; double_9 = double_3 * double_4; if(1) { short short_6 = 1; short short_7 = 1; double_1 = double_3 + double_2; short_7 = short_4 + short_6; } } } float v_mdb_cursor_shadow( char parameter_1,long parameter_2) { int int_1 = 1; int int_2 = 1; int int_3 = 1; float float_1 = 1; float float_2 = 1; int_2 = int_1 + int_2; int_2 = int_3; float_1 = float_1 + float_1; float_2 = float_2; for(int looper_1=0; looper_1<1;looper_1++) { if(1) { short short_1 = 1; int_1 = int_2 * int_3; if(1) { short_1 = short_1 + short_1; } for(int looper_2=0; looper_2<1;looper_2++) { unsigned int unsigned_int_1 = 1; int int_4 = 1; int int_5 = 1; unsigned int unsigned_int_2 = 1; long long_1 = 1; unsigned_int_1 = unsigned_int_1 * unsigned_int_1; if(1) { } int_3 = int_1 + int_2; short_1 = short_1 + short_1; int_2 = int_1 * int_3; int_2 = int_4 + int_2; int_5 = int_2 * int_2; if(1) { short short_2 = 1; unsigned int unsigned_int_3 = 1; short_1 = short_2 * short_2; unsigned_int_3 = unsigned_int_2 * unsigned_int_3; } long_1 = long_1; unsigned_int_2 = unsigned_int_2; } } } return float_1; } int v_mdb_txn_begin( int parameter_1,long parameter_2,unsigned int parameter_3,unsigned int parameter_4) { int int_1 = 1; unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; short short_1 = 1; short short_2 = 1; int int_2 = 1; int int_3 = 1; short short_4 = 1; short short_5 = 1; double double_1 = 1; double double_2 = 1; double double_3 = 1; double double_4 = 1; unsigned int unsigned_int_3 = 1; unsigned int unsigned_int_4 = 1; int int_4 = 1; int int_5 = 1; char char_1 = 1; float float_1 = 1; float float_2 = 1; float float_3 = 1; long long_1 = 1; double double_5 = 1; long long_2 = 1; long long_3 = 1; double double_6 = 1; unsigned int unsigned_int_6 = 1; int int_6 = 1; int_1 = int_1; unsigned_int_2 = unsigned_int_1 * unsigned_int_1; short_1 = short_1 + short_2; if(1) { int_3 = int_2 * int_1; } if(1) { } if(1) { short short_3 = 1; if(1) { short_2 = short_3 * short_4; } v_mdb_txn_renew0(unsigned_int_1); short_3 = short_5; } int_2 = int_2 + int_2; if(1) { if(1) { double_3 = double_1 + double_2; double_4 = double_1 + double_3; } double_3 = double_3 + double_1; } unsigned_int_4 = unsigned_int_3 + unsigned_int_2; if(1) { int_5 = int_4 + int_1; } unsigned_int_2 = unsigned_int_3 + unsigned_int_3; if(1) { char_1 = char_1; float_3 = float_1 + float_2; double_2 = double_2 * double_4; } if(1) { float float_4 = 1; float_1 = v_mdb_cursor_shadow(char_1,long_1); float_4 = float_3 * float_1; if(1) { double_5 = double_1; unsigned_int_1 = unsigned_int_2 * unsigned_int_4; } if(1) { double_4 = double_1; long_2 = long_1 * long_2; } } long_3 = long_3 + long_3; if(1) { long long_4 = 1; long long_5 = 1; char char_2 = 1; unsigned int unsigned_int_5 = 1; unsigned_int_4 = unsigned_int_4; unsigned_int_4 = unsigned_int_2 + unsigned_int_4; if(1) { int_4 = int_2; long_4 = long_4 + long_4; } long_5 = long_3 * long_2; double_2 = double_4; char_1 = char_1 * char_1; double_6 = double_1 * double_5; unsigned_int_2 = unsigned_int_4; char_2 = char_2; float_1 = float_2 + float_1; double_3 = double_6 * double_4; double_6 = double_6 + double_6; unsigned_int_5 = unsigned_int_2; short_1 = short_1; for(int looper_1=0; looper_1<1;looper_1++) { long_4 = long_1 + long_3; } unsigned_int_5 = unsigned_int_4 + unsigned_int_6; double_2 = double_4 * double_5; int_5 = int_2 * int_6; if(1) { long_5 = long_3 * long_5; int_6 = v_mdb_midl_alloc(int_5); int_5 = int_3 + int_1; if(1) { float float_5 = 1; float_1 = float_5 * float_1; } if(1) { double double_7 = 1; double_5 = double_7 * double_7; } } if(1) { int_6 = int_4 * int_1; } if(1) { short_2 = short_4; } } if(1) { short short_6 = 1; short_4 = short_5 + short_6; } if(1) { if(1) { double_1 = double_1 + double_5; } } if(1) { unsigned_int_6 = unsigned_int_6 + unsigned_int_2; double_2 = double_1 * double_6; } return int_3; } void v_mdb_db_create( int parameter_1,unsigned int parameter_2,char parameter_3) { unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; double double_1 = 1; double double_2 = 1; int int_1 = 1; int int_2 = 1; int int_3 = 1; int int_4 = 1; long long_1 = 1; char char_1 = 1; char char_2 = 1; double double_3 = 1; long long_2 = 1; unsigned_int_1 = unsigned_int_1 * unsigned_int_2; double_1 = double_2; int_1 = int_1; if(1) { int_2 = int_2 * int_2; } int_3 = int_1 + int_2; if(1) { unsigned int unsigned_int_3 = 1; int_2 = v_mdb_txn_begin(int_4,long_1,unsigned_int_2,unsigned_int_2); unsigned_int_3 = unsigned_int_1 * unsigned_int_2; } char_1 = char_1 + char_2; if(1) { double double_4 = 1; double double_5 = 1; int_2 = v_mdb_dbi_open(double_1,double_3,long_2,double_1); double_5 = double_2 + double_4; } int_4 = v_mdb_txn_commit(int_2,-1 ); } short v_mdb_env_share_locks( char parameter_1,int parameter_2) { int int_1 = 1; short short_1 = 1; long long_1 = 1; short short_2 = 1; int_1 = int_1 * int_1; return short_1; long_1 = v_mdb_env_pick_meta(short_2); } void v_mdb_env_init_meta0( char parameter_1,char parameter_2) { int int_1 = 1; char char_1 = 1; char char_2 = 1; unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; long long_1 = 1; long long_2 = 1; int int_2 = 1; int int_3 = 1; unsigned int unsigned_int_3 = 1; float float_1 = 1; float float_2 = 1; long long_3 = 1; int_1 = int_1 + int_1; char_2 = char_1 + char_2; unsigned_int_2 = unsigned_int_1 + unsigned_int_1; long_2 = long_1 * long_1; int_3 = int_2 + int_3; unsigned_int_2 = unsigned_int_3 * unsigned_int_2; unsigned_int_1 = unsigned_int_3 * unsigned_int_3; float_1 = float_1 * float_2; long_2 = long_1 * long_3; } unsigned int v_mdb_env_init_meta( long parameter_1,char parameter_2) { int int_1 = 1; int int_2 = 1; int int_3 = 1; long long_1 = 1; char char_1 = 1; int int_4 = 1; int int_5 = 1; unsigned int unsigned_int_1 = 1; int_3 = int_1 * int_2; long_1 = long_1; v_mdb_env_init_meta0(char_1,char_1); int_4 = int_5; return unsigned_int_1; } char v_mdb_strerror( int parameter_1) { unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; unsigned int unsigned_int_3 = 1; char char_4 = 1; unsigned_int_3 = unsigned_int_1 * unsigned_int_2; for(int looper_1=0; looper_1<1;looper_1++) { long long_1 = 1; if(1) { long long_2 = 1; long_1 = long_1 * long_2; for(int looper_2=0; looper_2<1;looper_2++) { float float_1 = 1; float_1 = float_1; } } if(1) { unsigned int unsigned_int_4 = 1; unsigned int unsigned_int_5 = 1; unsigned_int_4 = unsigned_int_5; } if(1) { char char_1 = 1; char_1 = char_1 * char_1; for(int looper_3=0; looper_3<1;looper_3++) { double double_1 = 1; double_1 = double_1 + double_1; } } if(1) { long long_3 = 1; long_3 = long_1; } if(1) { char char_2 = 1; char char_3 = 1; char_2 = char_2 + char_3; } char controller_6[3]; fgets(controller_6,3,stdin); if( strcmp( controller_6, "bD") > 0) { int int_1 = 1; int int_2 = 1; int_2 = int_1 * int_1; } } return char_4; } int v_mdb_env_read_header( int parameter_1,long parameter_2) { long long_1 = 1; long long_2 = 1; char char_1 = 1; char char_2 = 1; char char_3 = 1; float float_1 = 1; float float_2 = 1; short short_1 = 1; short short_2 = 1; unsigned int unsigned_int_1 = 1; char char_4 = 1; int int_4 = 1; int int_5 = 1; long_1 = long_1 + long_2; char_3 = char_1 * char_2; float_2 = float_1 * float_1; short_1 = short_2; unsigned_int_1 = unsigned_int_1; for(int looper_1=0; looper_1<1;looper_1++) { unsigned int unsigned_int_2 = 1; short short_3 = 1; short short_4 = 1; short short_5 = 1; double double_1 = 1; double double_2 = 1; int int_1 = 1; int int_2 = 1; double double_3 = 1; double double_4 = 1; short short_6 = 1; int int_6 = 1; unsigned_int_2 = unsigned_int_1 + unsigned_int_1; short_5 = short_3 + short_4; double_2 = double_1 * double_2; int_1 = int_1; int_2 = int_1; if(1) { int int_3 = 1; int_3 = int_1 + int_1; } if(1) { char_4 = v_mdb_strerror(int_4); double_1 = double_3 + double_4; } if(1) { if(1) { } int_1 = int_5; double_2 = double_4 + double_3; } short_2 = short_6 * short_2; if(1) { short_3 = short_1 + short_6; } int_5 = int_4 * int_1; if(1) { int_2 = int_6 + int_2; } if(1) { int_4 = int_2 + int_6; } if(1) { int_2 = int_2; } } return int_5; } long v_mdb_env_open2( float parameter_1) { double double_1 = 1; short short_1 = 1; short short_2 = 1; int int_1 = 1; int int_2 = 1; int int_3 = 1; char char_1 = 1; char char_2 = 1; long long_1 = 1; int int_4 = 1; int int_5 = 1; long long_2 = 1; char char_3 = 1; char char_4 = 1; float float_1 = 1; float float_2 = 1; char char_5 = 1; char char_6 = 1; float float_3 = 1; double double_2 = 1; unsigned int unsigned_int_1 = 1; double double_3 = 1; short short_3 = 1; double double_4 = 1; long long_3 = 1; double_1 = double_1 + double_1; short_1 = short_1 + short_1; short_2 = short_2 * short_2; int_3 = int_1 * int_2; if(1) { char_1 = char_2; } if(1) { long_1 = v_mdb_env_pick_meta(short_1); int_4 = int_5; } long_2 = v_mdb_env_map(double_1); int_2 = int_4 + int_3; if(1) { if(1) { } char_3 = char_3 + char_4; float_2 = float_1 * float_2; char_3 = char_5; if(1) { char_3 = char_6 + char_6; } } if(1) { float_2 = float_3; } if(1) { double_2 = double_1 + double_1; } if(1) { short_2 = short_1 * short_2; if(1) { unsigned_int_1 = v_mdb_env_init_meta(long_1,char_6); double_1 = double_1 + double_1; } } short_1 = short_1; if(1) { } if(1) { if(1) { short_1 = short_2; } double_3 = double_1 + double_3; if(1) { } } double_3 = double_3; char_3 = char_4 + char_4; if(1) { short_1 = short_1 + short_3; } double_4 = double_4 + double_2; if(1) { float float_4 = 1; int int_6 = 1; int int_7 = 1; char_1 = char_5 + char_5; int_3 = int_4 * int_2; float_4 = float_3 + float_4; char_6 = char_6 * char_2; float_4 = float_2; int_3 = v_mdb_env_read_header(int_5,long_3); int_3 = int_5 * int_6; int_6 = int_3 * int_3; int_7 = int_2 * int_3; short_1 = short_2 + short_3; float_4 = float_1 + float_1; } return long_3; } double v_mdb_env_excl_lock( int parameter_1,int parameter_2) { int int_1 = 1; int int_2 = 1; double double_1 = 1; int_2 = int_1 * int_1; double_1 = double_1 + double_1; return double_1; } long v_mdb_env_reader_dest() { double double_1 = 1; double double_2 = 1; double double_3 = 1; long long_1 = 1; long long_2 = 1; long long_3 = 1; double_3 = double_1 + double_2; long_2 = long_1 * long_2; return long_3; } int v_mdb_env_setup_locks( float parameter_1,char parameter_2,int parameter_3,int parameter_4) { int int_1 = 1; long long_1 = 1; int int_2 = 1; short short_1 = 1; double double_1 = 1; double double_2 = 1; int int_3 = 1; char char_1 = 1; char char_2 = 1; unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; unsigned int unsigned_int_3 = 1; float float_1 = 1; float float_2 = 1; long long_2 = 1; int int_4 = 1; unsigned int unsigned_int_4 = 1; int_1 = int_1 * int_1; long_1 = v_mdb_env_reader_dest(); int_1 = int_1 * int_1; int_1 = int_2 * int_2; short_1 = short_1 * short_1; double_2 = double_1 + double_1; int_2 = int_2 + int_2; double_1 = v_mdb_env_excl_lock(int_2,int_3); char_2 = char_1 + char_1; unsigned_int_1 = unsigned_int_1 + unsigned_int_2; unsigned_int_2 = unsigned_int_3 * unsigned_int_1; float_2 = float_1 + float_1; long_2 = long_1 + long_1; int_3 = int_1 * int_4; unsigned_int_3 = unsigned_int_1 * unsigned_int_4; return int_2; } int v_mdb_midl_alloc( int parameter_1) { double double_1 = 1; double double_2 = 1; double double_3 = 1; int int_1 = 1; double_3 = double_1 + double_2; char controller_1[2]; fgets(controller_1,2,stdin); if( strcmp( controller_1, "d") > 0) { char char_1 = 1; char char_2 = 1; unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; char_1 = char_2; unsigned_int_2 = unsigned_int_1 + unsigned_int_2; } return int_1; } void v_mdb_env_open( double parameter_1,int parameter_2,unsigned int parameter_3,short parameter_4) { char char_1 = 1; char char_2 = 1; int int_1 = 1; float float_1 = 1; char char_3 = 1; int int_2 = 1; long long_1 = 1; float float_2 = 1; short short_1 = 1; char char_4 = 1; int int_3 = 1; char_2 = char_1 + char_1; if(1) { double double_1 = 1; double double_2 = 1; int_1 = v_mdb_env_setup_locks(float_1,char_3,int_1,int_2); long_1 = v_mdb_env_open2(float_2); short_1 = v_mdb_env_share_locks(char_4,int_2); double_2 = double_1 * double_1; } int_1 = v_mdb_midl_alloc(int_3); } void v_mdb_env_set_maxdbs( char parameter_1,float parameter_2) { int int_1 = 1; int int_2 = 1; if(1) { } int_2 = int_1 * int_1; } long v_mdb_env_map( double parameter_1) { double double_1 = 1; double double_2 = 1; double double_3 = 1; unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; unsigned int unsigned_int_3 = 1; unsigned int unsigned_int_4 = 1; int int_1 = 1; short short_1 = 1; short short_2 = 1; short short_3 = 1; double double_4 = 1; float float_1 = 1; float float_2 = 1; char char_2 = 1; long long_1 = 1; double double_5 = 1; double double_6 = 1; double double_7 = 1; unsigned int unsigned_int_6 = 1; unsigned int unsigned_int_7 = 1; int int_3 = 1; double_3 = double_1 + double_2; unsigned_int_1 = unsigned_int_1 * unsigned_int_2; unsigned_int_4 = unsigned_int_3 + unsigned_int_4; if(1) { int int_2 = 1; int_2 = int_1 + int_2; } double_2 = double_1 * double_2; if(1) { unsigned_int_1 = unsigned_int_2 + unsigned_int_2; } short_3 = short_1 + short_2; double_4 = double_4; if(1) { float_1 = float_2; } double_4 = double_3 + double_1; if(1) { char char_1 = 1; char_2 = char_1 + char_2; } if(1) { double_1 = double_3; } if(1) { long_1 = long_1 * long_1; } double_6 = double_4 + double_5; if(1) { unsigned int unsigned_int_5 = 1; unsigned_int_1 = unsigned_int_5 + unsigned_int_3; } if(1) { float_1 = float_1 + float_2; } if(1) { char_2 = char_2 + char_2; } if(1) { float float_3 = 1; float float_4 = 1; float_3 = float_3 + float_4; } double_7 = double_3 * double_7; if(1) { unsigned_int_7 = unsigned_int_4 + unsigned_int_6; } int_1 = int_1 + int_1; if(1) { short_1 = short_1 + short_1; } unsigned_int_4 = unsigned_int_7 + unsigned_int_6; int_3 = int_1; unsigned_int_4 = unsigned_int_2 + unsigned_int_4; return long_1; } long v_mdb_env_pick_meta( short parameter_1) { long long_1 = 1; return long_1; } float v_mdb_env_set_mapsize( long parameter_1,int parameter_2) { long long_1 = 1; double double_3 = 1; float float_2 = 1; double double_6 = 1; long long_3 = 1; short short_1 = 1; double double_8 = 1; if(1) { long long_2 = 1; double double_1 = 1; double double_2 = 1; double double_4 = 1; double double_7 = 1; float float_4 = 1; float float_5 = 1; int int_1 = 1; unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; unsigned int unsigned_int_3 = 1; long_2 = long_1 * long_2; double_3 = double_1 * double_2; if(1) { } char controller_3[2]; fgets(controller_3,2,stdin); if( strcmp( controller_3, "N") > 0) { double_4 = double_1 + double_4; } if(1) { double double_5 = 1; double_4 = double_5 * double_5; if(1) { float float_1 = 1; float float_3 = 1; float_3 = float_1 * float_2; } } long_1 = v_mdb_env_map(double_6); double_7 = double_7 + double_7; float_5 = float_4 + float_2; int_1 = int_1 + int_1; unsigned_int_3 = unsigned_int_1 * unsigned_int_2; if(1) { } } long_3 = v_mdb_env_pick_meta(short_1); double_8 = double_3; if(1) { short short_2 = 1; short_1 = short_2 + short_2; } return float_2; } unsigned int v_mdb_env_create( float parameter_1) { short short_1 = 1; short short_2 = 1; unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; double double_1 = 1; double double_2 = 1; unsigned int unsigned_int_3 = 1; int int_1 = 1; int int_2 = 1; int int_3 = 1; char char_1 = 1; char char_2 = 1; long long_1 = 1; long long_2 = 1; long long_3 = 1; long long_4 = 1; double double_3 = 1; int int_4 = 1; float float_1 = 1; float float_2 = 1; float float_3 = 1; short_2 = short_1 + short_2; unsigned_int_2 = unsigned_int_1 * unsigned_int_1; if(1) { } double_1 = double_2; unsigned_int_3 = unsigned_int_3 + unsigned_int_3; int_3 = int_1 + int_2; char_1 = char_1 * char_2; long_3 = long_1 * long_2; long_4 = long_2 * long_1; double_3 = double_1; int_4 = int_3; float_1 = float_1 * float_1; float_3 = float_1 + float_2; short_1 = short_2; return unsigned_int_3; } void v_mdb_db_env_create( double parameter_1,int parameter_2,unsigned int parameter_3,int parameter_4) { double double_1 = 1; double double_2 = 1; long long_1 = 1; double double_3 = 1; char char_1 = 1; char char_2 = 1; int int_1 = 1; unsigned int unsigned_int_1 = 1; short short_1 = 1; float float_1 = 1; double double_4 = 1; double double_5 = 1; unsigned int unsigned_int_2 = 1; float float_2 = 1; long long_2 = 1; unsigned int unsigned_int_3 = 1; double_2 = double_1 * double_1; long_1 = long_1 * long_1; double_2 = double_2 + double_3; if(1) { double_1 = double_3 * double_3; } char_2 = char_1 + char_1; if(1) { int int_2 = 1; v_mdb_env_open(double_3,int_1,unsigned_int_1,short_1); int_2 = int_1 * int_1; } v_mdb_env_set_maxdbs(char_1,float_1); double_2 = double_4 + double_5; if(1) { double double_6 = 1; unsigned_int_2 = v_mdb_env_create(float_2); double_3 = double_6; } float_2 = v_mdb_env_set_mapsize(long_2,int_1); unsigned_int_1 = unsigned_int_3 + unsigned_int_2; if(1) { char char_3 = 1; short short_2 = 1; char_2 = char_1 + char_3; short_2 = short_1 + short_1; } if(1) { char char_4 = 1; char_2 = char_4 * char_1; } } unsigned int v___new_db() { double double_1 = 1; double double_2 = 1; int int_1 = 1; unsigned int unsigned_int_1 = 1; int int_2 = 1; unsigned int unsigned_int_2 = 1; char char_1 = 1; char char_2 = 1; unsigned int unsigned_int_3 = 1; unsigned int unsigned_int_4 = 1; float float_1 = 1; float float_2 = 1; double_2 = double_1 * double_2; v_mdb_db_env_create(double_2,int_1,unsigned_int_1,int_1); v_mdb_db_create(int_2,unsigned_int_2,char_1); char_2 = char_1 * char_2; unsigned_int_1 = unsigned_int_3 + unsigned_int_4; float_2 = float_1 * float_2; return unsigned_int_4; } void v_log_set_callbacks( double parameter_1,short parameter_2) { unsigned int unsigned_int_1 = 1; double double_1 = 1; double double_2 = 1; double double_3 = 1; unsigned_int_1 = unsigned_int_1 * unsigned_int_1; double_1 = double_1 * double_1; double_3 = double_2 + double_2; } void v_raft_set_callbacks( float parameter_1,char parameter_2) { unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; int int_1 = 1; float float_1 = 1; float float_2 = 1; double double_1 = 1; short short_1 = 1; int int_2 = 1; int int_3 = 1; unsigned_int_2 = unsigned_int_1 * unsigned_int_1; int_1 = int_1; float_2 = float_1 * float_1; v_log_set_callbacks(double_1,short_1); int_2 = int_2 + int_3; } void v_raft_set_state( unsigned int parameter_1,int parameter_2) { float float_1 = 1; float float_2 = 1; short short_1 = 1; short short_2 = 1; float_1 = float_1 * float_2; if(1) { unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; unsigned_int_1 = unsigned_int_2; } short_1 = short_2; } float v_log_new() { double double_1 = 1; double double_2 = 1; long long_1 = 1; long long_2 = 1; long long_3 = 1; int int_1 = 1; int int_2 = 1; char char_1 = 1; char char_2 = 1; float float_1 = 1; double_1 = double_1 * double_2; long_3 = long_1 * long_2; double_1 = double_1; int_1 = int_1 * int_2; char_2 = char_1 + char_2; return float_1; } short v_raft_new() { int int_1 = 1; unsigned int unsigned_int_1 = 1; short short_1 = 1; short short_2 = 1; float float_1 = 1; double double_1 = 1; double double_2 = 1; int int_2 = 1; int int_3 = 1; unsigned int unsigned_int_2 = 1; unsigned int unsigned_int_3 = 1; long long_1 = 1; long long_2 = 1; int int_4 = 1; int int_5 = 1; int_1 = int_1; if(1) { } v_raft_set_state(unsigned_int_1,int_1); short_2 = short_1 + short_2; float_1 = v_log_new(); double_1 = double_2; int_3 = int_2 + int_2; unsigned_int_2 = unsigned_int_2 + unsigned_int_3; double_2 = double_1 * double_2; unsigned_int_1 = unsigned_int_1 + unsigned_int_3; long_2 = long_1 + long_1; int_1 = int_4 * int_1; int_5 = int_3 + int_5; return short_1; } short v_calc_field_addr( double parameter_1,int parameter_2,char parameter_3,int parameter_4) { unsigned int unsigned_int_1 = 1; char char_1 = 1; char char_2 = 1; short short_1 = 1; short short_2 = 1; unsigned int unsigned_int_2 = 1; unsigned int unsigned_int_3 = 1; int int_1 = 1; int int_2 = 1; double double_1 = 1; double double_2 = 1; int int_3 = 1; int int_4 = 1; char char_3 = 1; double double_3 = 1; int int_5 = 1; unsigned_int_1 = unsigned_int_1; char_2 = char_1 * char_2; short_2 = short_1 + short_2; if(1) { } unsigned_int_3 = unsigned_int_1 + unsigned_int_2; int_1 = int_1 + int_2; double_2 = double_1 + double_2; int_4 = int_3 + int_2; unsigned_int_1 = unsigned_int_3 + unsigned_int_1; char_3 = char_2; double_3 = double_1 * double_2; int_3 = int_3 * int_4; int_5 = int_1 * int_5; return short_2; } char v_tpl_node_new( long parameter_1) { char char_1 = 1; char char_2 = 1; char char_3 = 1; char char_4 = 1; unsigned int unsigned_int_3 = 1; unsigned int unsigned_int_4 = 1; int int_1 = 1; int int_2 = 1; int int_3 = 1; double double_1 = 1; double double_2 = 1; int int_4 = 1; char char_5 = 1; char char_6 = 1; char_3 = char_1 + char_2; if(1) { unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; unsigned_int_2 = unsigned_int_1 * unsigned_int_1; } char_4 = char_4 * char_2; unsigned_int_3 = unsigned_int_4; int_1 = int_1 + int_2; int_3 = int_1 + int_3; double_2 = double_1 + double_2; int_1 = int_4 * int_3; char_3 = char_5 * char_2; return char_6; } short v_tpl_map_va( char parameter_1,int parameter_2) { short short_1 = 1; char char_1 = 1; long long_1 = 1; double double_1 = 1; int int_1 = 1; short short_2 = 1; return short_1; char_1 = v_tpl_node_new(long_1); short_1 = v_calc_field_addr(double_1,int_1,char_1,int_1); short_2 = v_tpl_free(short_2); } void v_tpl_map( char parameter_1,int parameter_2) { char char_1 = 1; char char_2 = 1; unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; long long_1 = 1; short short_1 = 1; int int_1 = 1; long long_2 = 1; unsigned int unsigned_int_3 = 1; char_1 = char_2; unsigned_int_2 = unsigned_int_1 + unsigned_int_1; long_1 = long_1; short_1 = v_tpl_map_va(char_1,int_1); long_1 = long_1 * long_2; unsigned_int_3 = unsigned_int_2 + unsigned_int_2; } short v_tpl_free( short parameter_1) { long long_1 = 1; int int_1 = 1; float float_1 = 1; short short_1 = 1; float float_2 = 1; unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; unsigned int unsigned_int_3 = 1; unsigned int unsigned_int_4 = 1; short short_2 = 1; if(1) { double double_1 = 1; long_1 = v_tpl_unmap_file(int_1); float_1 = v_tpl_free_atyp(short_1,float_2); unsigned_int_2 = unsigned_int_1 + unsigned_int_1; double_1 = double_1 + double_1; } unsigned_int_3 = unsigned_int_1 + unsigned_int_2; unsigned_int_1 = unsigned_int_4 * unsigned_int_4; short_1 = short_1 * short_1; unsigned_int_3 = unsigned_int_3 + unsigned_int_4; return short_2; } double v_tpl_dump_atyp( unsigned int parameter_1,int parameter_2) { double double_1 = 1; int int_1 = 1; char char_1 = 1; long long_1 = 1; return double_1; int_1 = v_tpl_cpv(char_1,long_1); } double v_tpl_fxlens( long parameter_1,int parameter_2) { short short_1 = 1; short short_2 = 1; double double_1 = 1; short_2 = short_1 * short_2; return double_1; } float v_tpl_cpu_bigendian() { long long_1 = 1; long long_2 = 1; double double_1 = 1; double double_2 = 1; unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; unsigned int unsigned_int_3 = 1; float float_1 = 1; long_1 = long_2; double_2 = double_1 + double_1; unsigned_int_2 = unsigned_int_1 + unsigned_int_2; unsigned_int_1 = unsigned_int_3; return float_1; } double v_tpl_fmt( unsigned int parameter_1) { double double_1 = 1; return double_1; } float v_tpl_dump_to_mem( unsigned int parameter_1,long parameter_3) { double double_1 = 1; unsigned int unsigned_int_1 = 1; int int_1 = 1; char char_1 = 1; long long_1 = 1; double double_2 = 1; long long_2 = 1; int int_2 = 1; double double_3 = 1; int int_3 = 1; float float_1 = 1; double_1 = v_tpl_fmt(unsigned_int_1); int_1 = v_tpl_cpv(char_1,long_1); double_2 = v_tpl_fxlens(long_2,int_2); int_2 = int_2; if(1) { } double_3 = v_tpl_dump_atyp(unsigned_int_1,int_1); int_2 = int_3 + int_3; return float_1; float_1 = v_tpl_cpu_bigendian(); } char v_tpl_mmap_output_file( char parameter_1,char parameter_2) { char char_1 = 1; return char_1; } double v_tpl_ser_osz( long parameter_1) { unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; double double_1 = 1; unsigned_int_2 = unsigned_int_1 * unsigned_int_2; return double_1; } int v_tpl_dump( float parameter_1,int parameter_2,unsigned int parameter_3) { char char_1 = 1; char char_2 = 1; int int_1 = 1; double double_1 = 1; long long_1 = 1; float float_1 = 1; unsigned int unsigned_int_1 = 1; char controller_1[2]; fgets(controller_1,2,stdin); if( strcmp( controller_1, "m") > 0) { char char_3 = 1; char_3 = char_1 * char_2; } return int_1; double_1 = v_tpl_ser_osz(long_1); char_1 = v_tpl_mmap_output_file(char_2,char_1); float_1 = v_tpl_dump_to_mem(unsigned_int_1,long_1); } int v_tpl_cpv(char parameter_2,long parameter_3) { int int_1 = 1; if(1) { int int_2 = 1; int_2 = int_1 * int_2; } return int_1; } char v_tpl_extend_backbone() { double double_1 = 1; char char_1 = 1; char char_2 = 1; char char_3 = 1; long long_1 = 1; long long_2 = 1; long long_3 = 1; double_1 = double_1; char_3 = char_1 * char_2; if(1) { float float_1 = 1; float float_2 = 1; float_1 = float_2; } char controller_2[2]; fgets(controller_2,2,stdin); if( strcmp( controller_2, "l") > 0) { long_1 = long_1; } char_1 = char_1 + char_3; long_1 = long_2 * long_3; if(1) { int int_1 = 1; float float_3 = 1; float float_4 = 1; int_1 = int_1; float_4 = float_3 * float_4; } char controller_4[2]; fgets(controller_4,2,stdin); if( strcmp( controller_4, "/") > 0) { unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; short short_1 = 1; unsigned_int_2 = unsigned_int_1 * unsigned_int_1; short_1 = short_1 + short_1; } long_1 = long_1; return char_2; } float v_tpl_free_atyp( short parameter_1,float parameter_2) { float float_1 = 1; if(1) { } return float_1; } long v_tpl_unmap_file( int parameter_1) { int int_1 = 1; int int_2 = 1; int int_3 = 1; double double_1 = 1; double double_2 = 1; long long_1 = 1; if(1) { unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; unsigned_int_1 = unsigned_int_2; } int_1 = int_1 * int_2; int_3 = int_2 + int_2; double_2 = double_1 * double_1; return long_1; } int v_tpl_free_keep_map() { long long_1 = 1; long long_2 = 1; long long_3 = 1; float float_1 = 1; int int_1 = 1; float float_3 = 1; int int_2 = 1; short short_2 = 1; long_3 = long_1 * long_2; if(1) { double double_1 = 1; double double_2 = 1; short short_1 = 1; char char_1 = 1; double double_3 = 1; char char_2 = 1; double double_4 = 1; double double_5 = 1; unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; float float_2 = 1; float float_4 = 1; double_1 = double_2; short_1 = short_1; char_1 = char_1 * char_1; double_3 = double_3 * double_1; char_2 = char_1 + char_1; double_4 = double_5; unsigned_int_2 = unsigned_int_1 * unsigned_int_1; float_1 = float_1 + float_2; long_2 = v_tpl_unmap_file(int_1); float_3 = float_1 * float_3; double_4 = double_4 + double_2; float_4 = float_3 * float_2; short_1 = short_1 + short_1; int_2 = int_2 + int_2; double_5 = double_2; } return int_2; float_3 = v_tpl_free_atyp(short_2,float_1); } long v_tpl_find_i( unsigned int parameter_1,int parameter_2) { double double_1 = 1; short short_1 = 1; short short_2 = 1; long long_1 = 1; double_1 = double_1 + double_1; short_2 = short_1 + short_1; if(1) { } if(1) { } for(int looper_1=0; looper_1<1;looper_1++) { if(1) { } } return long_1; } long v_tpl_pack( double parameter_1,int parameter_2) { double double_1 = 1; double double_2 = 1; double double_3 = 1; unsigned int unsigned_int_1 = 1; int int_2 = 1; unsigned int unsigned_int_2 = 1; int int_3 = 1; int int_4 = 1; char char_1 = 1; char char_2 = 1; long long_1 = 1; long long_2 = 1; int int_5 = 1; int int_6 = 1; double_3 = double_1 * double_2; if(1) { unsigned_int_1 = unsigned_int_1 * unsigned_int_1; } if(1) { float float_1 = 1; float float_2 = 1; float float_3 = 1; float_3 = float_1 * float_2; } if(1) { int int_1 = 1; int_1 = int_1 * int_2; } if(1) { unsigned_int_1 = unsigned_int_1 + unsigned_int_2; } if(1) { int_4 = int_2 + int_3; if(1) { double double_4 = 1; double_3 = double_4; } } if(1) { int_2 = int_3; if(1) { short short_1 = 1; short short_2 = 1; short short_3 = 1; char_1 = v_tpl_extend_backbone(); short_3 = short_1 + short_2; } } if(1) { int_3 = v_tpl_cpv(char_2,long_1); int_4 = int_4; if(1) { long_2 = long_1; } } if(1) { if(1) { char char_3 = 1; char_1 = char_3 * char_2; } if(1) { int int_7 = 1; int_2 = int_4 + int_5; int_6 = v_tpl_free_keep_map(); int_7 = int_5 * int_2; } } if(1) { if(1) { long long_3 = 1; long_1 = long_1 * long_3; } if(1) { unsigned int unsigned_int_3 = 1; long_1 = v_tpl_find_i(unsigned_int_1,int_5); unsigned_int_2 = unsigned_int_2 + unsigned_int_3; } } return long_2; } short v___peer_msg_serialize( char parameter_1,long parameter_2,char parameter_3) { double double_1 = 1; double double_2 = 1; double double_3 = 1; double double_4 = 1; long long_1 = 1; int int_1 = 1; int int_2 = 1; long long_2 = 1; float float_1 = 1; unsigned int unsigned_int_1 = 1; short short_1 = 1; short short_2 = 1; unsigned int unsigned_int_2 = 1; unsigned int unsigned_int_3 = 1; double_2 = double_1 * double_2; double_1 = double_3 * double_4; long_1 = v_tpl_pack(double_4,int_1); double_4 = double_2; int_1 = int_2; long_2 = long_1 * long_2; int_1 = v_tpl_dump(float_1,int_1,unsigned_int_1); short_2 = short_1 * short_2; unsigned_int_2 = unsigned_int_3; return short_1; short_2 = v_tpl_free(short_2); } float v___peer_msg_send( short parameter_1,long parameter_2,long parameter_3,char parameter_4) { double double_1 = 1; double double_2 = 1; char char_1 = 1; char char_2 = 1; float float_1 = 1; short short_1 = 1; long long_1 = 1; double_1 = double_1 + double_2; char_2 = char_1 * char_1; if(1) { unsigned int unsigned_int_1 = 1; unsigned_int_1 = unsigned_int_1 + unsigned_int_1; } return float_1; short_1 = v___peer_msg_serialize(char_1,long_1,char_2); } void v___send_leave() { char char_1 = 1; char char_2 = 1; short short_1 = 1; int int_1 = 1; float float_1 = 1; long long_1 = 1; int int_2 = 1; char_1 = char_2; short_1 = short_1; v_tpl_map(char_1,int_1); short_1 = short_1 * short_1; float_1 = v___peer_msg_send(short_1,long_1,long_1,char_2); int_2 = int_1 + int_1; int_1 = int_2; } char v_raft_node_get_udata( short parameter_1) { float float_1 = 1; float float_2 = 1; float float_3 = 1; char char_1 = 1; float_3 = float_1 + float_2; return char_1; } int v_raft_node_get_id( float parameter_1) { float float_1 = 1; int int_1 = 1; float_1 = float_1; return int_1; } float v_raft_get_current_leader_node( int parameter_1) { double double_1 = 1; float float_1 = 1; double_1 = double_1 * double_1; return float_1; } float v___int_handler( int parameter_1) { double double_1 = 1; double double_2 = 1; float float_1 = 1; float float_2 = 1; char char_4 = 1; short short_1 = 1; unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; float float_3 = 1; int int_1 = 1; unsigned int unsigned_int_3 = 1; v___send_leave(); double_1 = double_2; float_1 = float_1 + float_2; if(1) { char char_2 = 1; char char_3 = 1; if(1) { char char_1 = 1; long long_1 = 1; long long_2 = 1; char_1 = char_1; long_1 = long_1 + long_2; } char_4 = char_2 * char_3; if(1) { short short_2 = 1; char_4 = v_raft_node_get_udata(short_1); unsigned_int_2 = unsigned_int_1 * unsigned_int_1; float_2 = float_2 * float_3; short_2 = short_2 * short_1; } } int_1 = v_raft_node_get_id(float_3); unsigned_int_2 = unsigned_int_1 * unsigned_int_3; float_3 = v_raft_get_current_leader_node(int_1); int_1 = int_1 + int_1; return float_2; } double v_show_usage() { unsigned int unsigned_int_1 = 1; double double_1 = 1; double double_2 = 1; unsigned int unsigned_int_2 = 1; unsigned int unsigned_int_3 = 1; short short_1 = 1; int int_1 = 1; int int_2 = 1; int int_3 = 1; long long_1 = 1; char char_1 = 1; char char_2 = 1; unsigned int unsigned_int_4 = 1; short short_2 = 1; long long_2 = 1; long long_3 = 1; long long_4 = 1; double double_3 = 1; int int_4 = 1; unsigned int unsigned_int_5 = 1; unsigned int unsigned_int_6 = 1; unsigned int unsigned_int_7 = 1; char char_3 = 1; char char_4 = 1; float float_1 = 1; float float_2 = 1; double double_4 = 1; unsigned int unsigned_int_8 = 1; unsigned_int_1 = unsigned_int_1; double_1 = double_1 + double_1; double_1 = double_2; unsigned_int_3 = unsigned_int_2 * unsigned_int_2; short_1 = short_1 + short_1; int_1 = int_1 * int_1; unsigned_int_1 = unsigned_int_1; int_3 = int_2 + int_3; long_1 = long_1 + long_1; char_1 = char_1 + char_2; unsigned_int_4 = unsigned_int_1 + unsigned_int_3; unsigned_int_3 = unsigned_int_3 + unsigned_int_1; short_2 = short_1 + short_2; long_4 = long_2 + long_3; int_3 = int_2 + int_1; long_1 = long_3; long_3 = long_1 + long_1; unsigned_int_2 = unsigned_int_4; double_3 = double_1 * double_3; double_1 = double_2 + double_3; int_4 = int_1 + int_4; unsigned_int_6 = unsigned_int_1 * unsigned_int_5; long_3 = long_4 + long_2; unsigned_int_7 = unsigned_int_7 * unsigned_int_6; char_4 = char_3 + char_3; float_1 = float_2; float_1 = float_2 * float_2; unsigned_int_4 = unsigned_int_6 + unsigned_int_1; double_4 = double_3 * double_2; short_1 = short_2; unsigned_int_2 = unsigned_int_2 * unsigned_int_4; unsigned_int_7 = unsigned_int_7 + unsigned_int_8; return double_3; } int v_params_finish( long parameter_1) { int int_1 = 1; if(1) { } if(1) { } return int_1; } unsigned int v_params_execute( short parameter_1,unsigned int parameter_2,int parameter_3) { long long_1 = 1; int int_1 = 1; int int_2 = 1; unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; long_1 = long_1; int_2 = int_1 * int_1; if(1) { long long_2 = 1; long long_3 = 1; long_3 = long_2 + long_3; } if(1) { int int_3 = 1; int_3 = int_2 + int_1; } unsigned_int_1 = unsigned_int_1 + unsigned_int_1; int_1 = int_1 * int_1; return unsigned_int_2; } double v_params_init( long parameter_1,int parameter_2) { int int_1 = 1; unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; unsigned int unsigned_int_3 = 1; short short_1 = 1; short short_2 = 1; long long_1 = 1; float float_1 = 1; float float_2 = 1; int int_2 = 1; double double_1 = 1; double double_2 = 1; short short_3 = 1; short short_4 = 1; int_1 = int_1; unsigned_int_1 = unsigned_int_1 + unsigned_int_2; unsigned_int_1 = unsigned_int_2 + unsigned_int_3; short_2 = short_1 + short_1; long_1 = long_1 * long_1; float_2 = float_1 + float_1; int_2 = int_1 + int_1; double_1 = double_1 + double_2; short_4 = short_3 + short_1; unsigned_int_1 = unsigned_int_3; return double_1; } float v_parse_options( int parameter_1,char parameter_2,unsigned int parameter_3) { float float_1 = 1; float float_2 = 1; double double_1 = 1; long long_1 = 1; int int_1 = 1; int int_2 = 1; double double_2 = 1; short short_1 = 1; short short_2 = 1; int int_3 = 1; float float_3 = 1; unsigned int unsigned_int_1 = 1; float_2 = float_1 + float_1; double_1 = v_params_init(long_1,int_1); int_1 = int_2 * int_2; double_2 = v_show_usage(); short_1 = short_2; for(int looper_1=0; looper_1<1;looper_1++) { int_3 = int_3; } if(1) { short short_3 = 1; int int_4 = 1; int int_5 = 1; int_3 = v_params_finish(long_1); short_1 = short_3 + short_3; int_5 = int_4 + int_1; } return float_3; unsigned_int_1 = v_params_execute(short_1,unsigned_int_1,int_2); } int main() { int uni_para =149; long long_1 = 1; char char_1 = 1; char char_2 = 1; unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; int int_1 = 1; char char_3 = 1; float float_1 = 1; float float_2 = 1; long long_2 = 1; unsigned int unsigned_int_3 = 1; unsigned int unsigned_int_4 = 1; int int_2 = 1; float float_4 = 1; double double_1 = 1; double double_2 = 1; double double_3 = 1; short short_1 = 1; int int_3 = 1; char char_4 = 1; float float_5 = 1; long long_3 = 1; unsigned int unsigned_int_7 = 1; int int_4 = 1; short short_3 = 1; int int_5 = 1; double double_5 = 1; int int_6 = 1; long_1 = long_1 * long_1; long_1 = long_1; if(1) { char_2 = char_1 * char_2; } if(1) { unsigned_int_1 = unsigned_int_1 + unsigned_int_2; int_1 = int_1 * int_1; } if(1) { int_1 = int_1; char_3 = char_2 + char_2; } unsigned_int_1 = unsigned_int_2; float_1 = float_1; float_1 = float_2 + float_2; long_1 = long_1 * long_2; unsigned_int_3 = unsigned_int_2 * unsigned_int_3; unsigned_int_3 = unsigned_int_4 * unsigned_int_4; if(1) { float float_3 = 1; float_3 = float_3 + float_3; int_2 = int_2 * int_2; } unsigned_int_1 = unsigned_int_2 * unsigned_int_2; float_2 = float_4 * float_2; double_1 = double_1; double_2 = double_1 + double_1; double_3 = double_2 + double_3; double_1 = double_1; short_1 = short_1; int_1 = int_3 * int_1; unsigned_int_3 = unsigned_int_4 + unsigned_int_2; double_3 = double_2 + double_1; float_4 = float_1 * float_4; char_4 = char_3 * char_1; float_2 = float_1 + float_5; if(1) { if(1) { short_1 = short_1 + short_1; } } if(1) { char char_5 = 1; char char_6 = 1; char_6 = char_5 * char_5; if(1) { double_3 = double_2 * double_3; long_1 = long_3 + long_1; } } float_2 = float_2 * float_4; if(1) { long long_4 = 1; unsigned int unsigned_int_5 = 1; unsigned_int_4 = unsigned_int_3 * unsigned_int_2; unsigned_int_2 = unsigned_int_1; double_3 = double_2; long_3 = long_3 * long_4; unsigned_int_5 = unsigned_int_5 * unsigned_int_1; if(1) { unsigned int unsigned_int_6 = 1; long long_5 = 1; unsigned_int_5 = unsigned_int_6 * unsigned_int_7; long_3 = long_5 * long_1; } if(1) { short short_2 = 1; int_4 = int_4 + int_1; short_2 = short_1 + short_2; double_1 = double_2; unsigned_int_7 = unsigned_int_2 * unsigned_int_2; short_1 = short_2 * short_1; } } char controller4vul_2430[3]; fgets(controller4vul_2430,3,stdin); if( strcmp( controller4vul_2430, "1?") < 0) { long long_6 = 1; unsigned int unsigned_int_8 = 1; unsigned int unsigned_int_9 = 1; float_4 = float_2 * float_2; long_2 = long_3 + long_6; unsigned_int_8 = unsigned_int_9; unsigned_int_2 = unsigned_int_4 * unsigned_int_4; if(1) { double double_4 = 1; double_4 = double_1 * double_4; } char controller4vul_2431[2]; fgets(controller4vul_2431,2,stdin); if( strcmp( controller4vul_2431, "5") < 0) { for(int looper_1=0; looper_1<1;looper_1++) { unsigned int unsigned_int_10 = 1; unsigned_int_1 = unsigned_int_1 * unsigned_int_10; char controller4vul_2432[3]; fgets(controller4vul_2432,3,stdin); if( strcmp( controller4vul_2432, " A") > 0) { v___load_opts(int_1,short_3,uni_para); int_4 = int_4 + int_5; } unsigned_int_7 = unsigned_int_2 + unsigned_int_9; } } } double_1 = double_5 * double_1; int_5 = int_2 * int_6; return int_4; } ======================= File: experiments/node10/c_source/terminology_0_45_node10.c ======================= <gh_stars>1-10 #include<stdio.h> #include<stdlib.h> #include<string.h> int remainder_check(char* parameter_1,int checksum_div,int length); int remainder_check(char* parameter_1,int checksum_div,int length) { if(strlen(parameter_1)!=length) return 0; int sum = 0; for(int i=0;i<length;i++) sum = sum + parameter_1[i]; if((sum % checksum_div==0)) return 1; else return 0; } void v__termpty_shutdown( long parameter_1); void v_termpty_text_scroll_rev_test( long parameter_1,long parameter_2); float v__handle_esc_dcs( int parameter_1,unsigned int parameter_2,long parameter_3); short v__handle_op_a( double parameter_1,float parameter_2,unsigned int parameter_3); void v__termpty_ext_handle( long parameter_1,double parameter_2,char parameter_3); long v__handle_esc_terminology( float parameter_1,float parameter_2,unsigned int parameter_3); unsigned int v__handle_xterm_777_command( short parameter_1,char parameter_2,int parameter_3); double v__smart_calculate_226( long parameter_1); float v__smart_size( short parameter_1,int parameter_2,int parameter_3,char parameter_4); void v_colors_term_init( long parameter_1,char parameter_2,long parameter_3); void v_termio_config_update( long parameter_1); float v__font_size_set( int parameter_1,int parameter_2); void v_termio_font_size_set( float parameter_1,int parameter_2); long v__handle_xterm_50_command( float parameter_1,char parameter_2,int parameter_3); float v__eina_unicode_to_hex( short parameter_1); int v__xterm_parse_color( long parameter_1,double parameter_2,float parameter_3,char parameter_4,int parameter_5); unsigned int v__xterm_arg_get( short parameter_1); void v__handle_esc_xterm( short parameter_1,short parameter_2,long parameter_3); void v_termpty_cells_set_content( short parameter_1,int parameter_2,double parameter_3,int parameter_4); long v__handle_esc_csi_decera( float parameter_1,double parameter_2); void v_termpty_cells_att_fill_preserve_colors( short parameter_1,long parameter_2,short parameter_3,int parameter_4); void v__clean_up_rect_coordinates( long parameter_1,int parameter_2,int parameter_3,int parameter_4,int parameter_5); short v__handle_esc_csi_decfra( short parameter_1,short parameter_2); void v__handle_esc_csi_decslrm( int parameter_1,double parameter_2); short v__handle_esc_csi_decstbm( double parameter_1,int parameter_2); long v__handle_esc_csi_decscusr( short parameter_1,unsigned int parameter_2); double v__handle_esc_csi_dsr( char parameter_1,short parameter_2); unsigned int v__handle_esc_csi_truecolor_cmyk( unsigned int parameter_1,char parameter_2); unsigned int v__handle_esc_csi_truecolor_cmy( int parameter_1,int parameter_2); float v__approximate_truecolor_rgb( short parameter_1,int parameter_2,int parameter_3,int parameter_4); long v__csi_truecolor_arg_get( double parameter_1); float v__handle_esc_csi_truecolor_rgb( float parameter_1,unsigned int parameter_2); double v__handle_esc_csi_color_set( float parameter_1,char parameter_2); void v_termpty_cursor_copy( unsigned int parameter_1,float parameter_2); char v__switch_to_alternative_screen( short parameter_1,int parameter_2); char v__move_cursor_to_origin( unsigned int parameter_1); short v__pty_size( long parameter_1); float v__limit_coord(); double v__check_screen_info( unsigned int parameter_1,long parameter_2); int v__termpty_line_rewrap( short parameter_1,unsigned int parameter_2,int parameter_3,short parameter_4,float parameter_5); float v__backlog_remove_latest_nolock( unsigned int parameter_1); void v_termpty_save_extract( long parameter_1); int v__termpty_line_is_empty( int parameter_1,unsigned int parameter_2); void v_termpty_screen_swap( char parameter_1); void v_termpty_resize( float parameter_1,int parameter_2,int parameter_3); double v_termio_win_get( char parameter_1); long v__handle_esc_csi_reset_mode( unsigned int parameter_1,short parameter_2,short parameter_3); char v__handle_esc_csi_cursor_pos_set( double parameter_1,unsigned int parameter_2,long parameter_3); void v_termpty_text_scroll_rev( unsigned int parameter_1,short parameter_2); void v_termpty_clear_line( int parameter_1,double parameter_2,int parameter_3); void v_termpty_clear_screen( int parameter_1,char parameter_2); void v_termpty_cell_codepoint_att_fill( unsigned int parameter_1,short parameter_2,short parameter_3,long parameter_4,int parameter_5); short v__termpty_charset_trans( short parameter_1,float parameter_2); void v_termio_content_change( short parameter_1,char parameter_2,short parameter_3,int parameter_4); void v_termpty_text_append( double parameter_1,short parameter_2,int parameter_3,int uni_para); float v__csi_arg_get( float parameter_1); float v__handle_esc_csi( long parameter_1,double parameter_2,float parameter_3); void v__safechar( float parameter_1); float v__handle_esc( short parameter_1,long parameter_2,char parameter_3); void v_termpty_cell_fill( float parameter_1,float parameter_2,short parameter_3,int parameter_4); void v_termpty_cells_fill( long parameter_1,float parameter_2,int parameter_3,int parameter_4); void v_termpty_cells_clear( int parameter_1,long parameter_2,int parameter_3); float v__tooltip_del(short parameter_2); short v__tooltip_content(int parameter_2,int parameter_3); void v_MD5Final( int parameter_1,double parameter_2); void v_MD5Transform( double parameter_1,char parameter_2); void v_byteReverse( long parameter_1,unsigned int parameter_2); void v_MD5Update( double parameter_1,unsigned int parameter_2,char parameter_3); void v_MD5Init( int parameter_1); void v_gravatar_tooltip( unsigned int parameter_1,long parameter_2,char parameter_3); unsigned int v__cb_link_drag_done(double parameter_2); unsigned int v__cb_link_drag_accept(int parameter_2,short parameter_3); float v__cb_link_drag_move(double parameter_2,int parameter_3,double parameter_4,float parameter_5); float v__cb_link_icon_new(float parameter_2,long parameter_3,int parameter_4); int v__cb_link_move(float parameter_2,int parameter_3); long v__cb_link_up_delay(); float v__cb_link_up(unsigned int parameter_2,char parameter_3); void v_term_focus( char parameter_1); unsigned int v__term_is_focused( long parameter_1); void v_term_unfocus( double parameter_1); short v__cb_ctxp_del(char parameter_2,long parameter_3); long v__cb_ctxp_dismissed(int parameter_2); long v__cb_ctxp_link_copy(unsigned int parameter_2); unsigned int v__screen_visual_bounds( float parameter_1); void v__draw_cell( short parameter_1,long parameter_2,unsigned int parameter_3,char parameter_4); short v__draw_line( unsigned int parameter_1,char parameter_2,char parameter_3,int parameter_4,short parameter_5); double v_termpty_backlog_length( long parameter_1); void v_termio_pty_get(); double v_termio_textgrid_get( char parameter_1); int v_miniview_colors_get( char parameter_1,float parameter_2); double v__deferred_renderer(); int v__queue_render( int parameter_1); void v_miniview_redraw( double parameter_1); long v__block_obj_del( long parameter_1); long v__termpty_is_dblwidth_slow_get( long parameter_1,int parameter_2); unsigned int v__termpty_is_dblwidth_get( float parameter_1,int parameter_2); void v_term_preedit_str_get( double parameter_1); int v_media_get( double parameter_1); long v__smart_media_clicked(long parameter_2); double v_media_control_get(); short v__smart_media_stop(double parameter_2); unsigned int v__smart_media_pause(char parameter_2); char v__smart_media_play(char parameter_2); char v__smart_media_del(long parameter_2,unsigned int parameter_3); void v_media_visualize_set( float parameter_1,float parameter_2); void v_media_mute_set( double parameter_1,char parameter_2); void v_media_volume_set( int parameter_1,double parameter_2); double v__cb_media_vol(int parameter_2,double parameter_3,float parameter_4); char v__cb_media_pos(short parameter_2,short parameter_3,char parameter_4); double v__cb_media_pos_drag_stop(double parameter_2,long parameter_3,char parameter_4); short v__cb_media_pos_drag_start(short parameter_2,unsigned int parameter_3,int parameter_4); void v_media_stop( double parameter_1); long v__cb_media_stop(double parameter_2,short parameter_3,char parameter_4); double v__cb_media_pause(unsigned int parameter_2,int parameter_3,char parameter_4); void v_media_play_set( float parameter_1,char parameter_2); unsigned int v__cb_media_play(double parameter_2,long parameter_3,long parameter_4); void v_media_position_set( unsigned int parameter_1,double parameter_2); char v__cb_mov_ref(int parameter_2); float v__cb_mov_progress(int parameter_2); float v__cb_mov_restart(); short v__cb_mov_decode_stop(int parameter_2); void v__cb_mov_len_change(long parameter_2); int v__cb_mov_frame_resize(short parameter_2); long v__cb_mov_frame_decode(int parameter_2); double v__type_mov_init( double parameter_1); void v__cb_edje_preloaded(char parameter_2,double parameter_3,int parameter_4); int v__type_edje_init( float parameter_1); long v__type_scale_init(); unsigned int v__cb_img_frame(); float v__type_img_anim_handle( long parameter_1); unsigned int v__cb_img_preloaded(double parameter_2,double parameter_3); double v__type_img_init( short parameter_1); void v__url_compl_cb(int parameter_2,int uni_para); short v__url_prog_cb(int parameter_2); unsigned int v__type_thumb_calc( float parameter_1,double parameter_2,double parameter_3,unsigned int parameter_4,long parameter_5); void v__type_mov_calc( short parameter_1,int parameter_2,short parameter_3,char parameter_4,short parameter_5); void v__type_edje_calc( unsigned int parameter_1,long parameter_2,char parameter_3,long parameter_4,int parameter_5); char v__type_img_calc( int parameter_1,short parameter_2,char parameter_3,unsigned int parameter_4,float parameter_5); float v__cb_scale_preloaded(long parameter_2,short parameter_3,int uni_para); void v__type_scale_calc( double parameter_1,char parameter_2,short parameter_3,char parameter_4,char parameter_5,int uni_para); short v__unsmooth_timeout(); void v__smooth_handler( double parameter_1); double v__smart_calculate( unsigned int parameter_1,int uni_para); long v__smart_move( int parameter_1,long parameter_2,unsigned int parameter_3); long v__smart_resize( long parameter_1,char parameter_2,short parameter_3); char v__smart_del(); float v__smart_add( unsigned int parameter_1); void v__smart_init(); short v_media_add( int parameter_1,float parameter_2,int parameter_3,int parameter_4,int parameter_5,int uni_para); unsigned int v__block_media_activate( long parameter_1,int parameter_2,int uni_para); int v__block_edje_message_cb(int parameter_2,float parameter_3,int parameter_4); void v_termpty_write( double parameter_1,long parameter_2,int parameter_3); short v__block_edje_signal_cb(long parameter_2,long parameter_3,char parameter_4); void v_termpty_block_chid_update( char parameter_1,float parameter_2); unsigned int v__block_edje_cmds( double parameter_1,unsigned int parameter_2,int parameter_3,float parameter_4); int v_homedir_get( char parameter_1,int parameter_2); float v__block_edje_activate( char parameter_1,long parameter_2); char v__block_activate( char parameter_1,long parameter_2,int uni_para); void v_termpty_block_get( short parameter_1,int parameter_2); int v_termpty_block_id_get( unsigned int parameter_1,int parameter_2,int parameter_3); void v_termpty_backscroll_adjust( short parameter_1,int parameter_2); short v__smart_apply( double parameter_1,int uni_para); int v__smart_cb_change(int uni_para); int v__smart_update_queue( double parameter_1,char parameter_2,int uni_para); long v__lost_selection_reset_job(); char v__lost_selection(short parameter_2,int uni_para); double v__take_selection_text( short parameter_1,double parameter_2,int parameter_3,int uni_para); char v__cb_ctxp_link_content_copy(short parameter_2,int uni_para); void v_ty_sb_free( float parameter_1); short v_ty_sb_steal_buf( int parameter_1); int v_codepoint_to_utf8( double parameter_1,char parameter_2); void v_ty_sb_spaces_rtrim( unsigned int parameter_1); int v_ty_sb_add( float parameter_1,float parameter_2,double parameter_3); long v__termpty_cellrow_from_beacon_get( int parameter_1,int parameter_2,short parameter_3); void v_termpty_cellrow_get( int parameter_1,int parameter_2,double parameter_3); int v_termio_selection_get( float parameter_1,int parameter_2,int parameter_3,int parameter_4,int parameter_5,double parameter_6,long parameter_7); double v__cb_ctxp_link_open(char parameter_2); float v__should_inline( unsigned int parameter_1); short v_link_is_email( int parameter_1); float v_link_is_protocol( int parameter_1); void v_link_is_url( int parameter_1); short v__activate_link( short parameter_1,float parameter_2); int v__cb_ctxp_link_preview(long parameter_2); void v__is_fmt( int parameter_1,double parameter_2); double v_media_src_type_get( float parameter_1); int v__mouse_in_selection( double parameter_1,int parameter_2,int parameter_3); float v__smart_xy_to_cursor( int parameter_1,float parameter_2,char parameter_3,int parameter_4,int parameter_5); double v__cb_link_down(long parameter_2,char parameter_3,int uni_para); short v_main_term_popup_exists( char parameter_1); float v__update_link( long parameter_1,float parameter_2,long parameter_3,char parameter_4,int uni_para); short v__remove_links( int parameter_1,double parameter_2,int uni_para); short v__sel_set( long parameter_1,char parameter_2); int v_termio_scroll_get( short parameter_1); void v_miniview_position_offset( unsigned int parameter_1,int parameter_2,unsigned int parameter_3); char v_term_miniview_get( unsigned int parameter_1); void v_termio_scroll( float parameter_1,int parameter_2,int parameter_3,int parameter_4,int uni_para); int v_termpty_save_new( float parameter_1,int parameter_2); int v_termpty_save_expand( float parameter_1,int parameter_2,int parameter_3); double v__termpty_cell_is_empty(); double v_termpty_line_length( short parameter_1,unsigned int parameter_2); long v_verify_beacon( int parameter_1,int parameter_2); void v_termpty_text_save_top( float parameter_1,unsigned int parameter_2,short parameter_3); void v_termpty_text_scroll( int parameter_1,int parameter_2,int uni_para); void v_termpty_text_scroll_test( long parameter_1,long parameter_2,int uni_para); float v__cursor_to_start_of_line( long parameter_1); void v__tab_forward( char parameter_1,int parameter_2); char v__handle_cursor_control( double parameter_1,float parameter_2); int v_termpty_handle_seq( int parameter_1,int parameter_2,short parameter_3,int uni_para); void v_termpty_handle_buf( int parameter_1,short parameter_2,int parameter_3,int uni_para); void v_theme_reload( float parameter_1); double v_theme_reload_cb(float parameter_2,double parameter_3,double parameter_4); void v_theme_auto_reload_enable( short parameter_1); void v__cursor_shape_to_group_name( unsigned int parameter_1); double v_config_theme_path_default_get( int parameter_1); long v_theme_path_get(); int v_config_theme_path_get(); double v_theme_apply( float parameter_1,unsigned int parameter_2,float parameter_3); void v_termio_set_cursor_shape( unsigned int parameter_1,char parameter_2); void v_termpty_clear_tabs_on_screen( double parameter_1); void v_termpty_backlog_unlock(); void v_termpty_backlog_size_set( int parameter_1,unsigned int parameter_2); unsigned int v__ts_free(); void v_termpty_save_free( long parameter_1); void v_termpty_backlog_lock(); void v_termpty_clear_backlog( unsigned int parameter_1); void v_termpty_reset_att(); float v_termio_config_get(); void v_termpty_reset_state( short parameter_1); void v_termpty_resize_tabs( float parameter_1,int parameter_2,int parameter_3); double v__termpty_init( short parameter_1); char v__add_default_keys( long parameter_1); void v_colors_standard_get( int parameter_1,int parameter_2,long parameter_3,char parameter_4,char parameter_5,double parameter_6); double v_config_new(); void v__termpty_shutdown( long parameter_1) { double double_1 = 1; double double_2 = 1; double_1 = double_1 * double_2; } void v_termpty_text_scroll_rev_test( long parameter_1,long parameter_2) { unsigned int unsigned_int_1 = 1; short short_1 = 1; unsigned int unsigned_int_2 = 1; unsigned int unsigned_int_3 = 1; v_termpty_text_scroll_rev(unsigned_int_1,short_1); unsigned_int_3 = unsigned_int_1 + unsigned_int_2; if(1) { int int_1 = 1; int_1 = int_1; } if(1) { char char_1 = 1; char char_2 = 1; char_1 = char_1 + char_1; char_2 = char_1 + char_1; unsigned_int_2 = unsigned_int_1; } } float v__handle_esc_dcs( int parameter_1,unsigned int parameter_2,long parameter_3) { int int_1 = 1; int int_2 = 1; int int_3 = 1; double double_1 = 1; long long_1 = 1; float float_1 = 1; int_3 = int_1 + int_2; if(1) { unsigned int unsigned_int_2 = 1; unsigned int unsigned_int_3 = 1; if(1) { if(1) { if(1) { char char_1 = 1; char_1 = char_1 + char_1; } if(1) { unsigned int unsigned_int_1 = 1; unsigned_int_3 = unsigned_int_1 + unsigned_int_2; } } } if(1) { float float_2 = 1; v_termpty_write(double_1,long_1,int_2); float_2 = float_1 * float_2; } if(1) { unsigned int unsigned_int_4 = 1; unsigned_int_3 = unsigned_int_2 * unsigned_int_4; } if(1) { } if(1) { int_1 = int_1 + int_3; } if(1) { short short_1 = 1; short short_2 = 1; short short_3 = 1; v__safechar(float_1); short_3 = short_1 + short_2; } } if(1) { if(1) { int int_4 = 1; int int_5 = 1; int_3 = int_4 + int_5; } } return float_1; } short v__handle_op_a( double parameter_1,float parameter_2,unsigned int parameter_3) { float float_1 = 1; unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; unsigned int unsigned_int_3 = 1; short short_1 = 1; float_1 = float_1 * float_1; unsigned_int_3 = unsigned_int_1 * unsigned_int_2; return short_1; } void v__termpty_ext_handle( long parameter_1,double parameter_2,char parameter_3) { short short_1 = 1; double double_1 = 1; float float_1 = 1; unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; unsigned int unsigned_int_3 = 1; short_1 = v__handle_op_a(double_1,float_1,unsigned_int_1); unsigned_int_1 = unsigned_int_1 + unsigned_int_1; unsigned_int_2 = unsigned_int_3; } long v__handle_esc_terminology( float parameter_1,float parameter_2,unsigned int parameter_3) { float float_1 = 1; long long_1 = 1; double double_1 = 1; char char_1 = 1; double double_2 = 1; float_1 = v_termio_config_get(); v__termpty_ext_handle(long_1,double_1,char_1); double_2 = double_1 * double_2; return long_1; } unsigned int v__handle_xterm_777_command( short parameter_1,char parameter_2,int parameter_3) { short short_1 = 1; double double_1 = 1; double double_2 = 1; short short_2 = 1; double double_4 = 1; int int_1 = 1; char char_1 = 1; unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; int int_2 = 1; unsigned int unsigned_int_3 = 1; short short_3 = 1; short_1 = short_1 * short_1; if(1) { double_1 = double_1 * double_2; } if(1) { double double_3 = 1; double_2 = double_2 + double_3; } short_2 = short_1; if(1) { } double_4 = double_1 + double_4; int_1 = int_1; char_1 = char_1 + char_1; if(1) { unsigned_int_1 = unsigned_int_2; } int_1 = int_1 + int_2; double_2 = double_4 + double_1; int_2 = int_1 * int_2; unsigned_int_3 = unsigned_int_1 * unsigned_int_2; short_3 = short_1 + short_2; return unsigned_int_1; } double v__smart_calculate_226( long parameter_1) { double double_1 = 1; double double_2 = 1; long long_1 = 1; long long_2 = 1; char char_1 = 1; unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; unsigned int unsigned_int_3 = 1; short short_1 = 1; short short_2 = 1; double double_3 = 1; unsigned int unsigned_int_4 = 1; double_2 = double_1 + double_2; long_2 = long_1 * long_1; char_1 = char_1 * char_1; unsigned_int_1 = unsigned_int_2; unsigned_int_2 = unsigned_int_3 + unsigned_int_2; short_2 = short_1 * short_1; double_3 = double_1 * double_2; double_2 = double_1; unsigned_int_1 = unsigned_int_4 + unsigned_int_3; return double_1; } float v__smart_size( short parameter_1,int parameter_2,int parameter_3,char parameter_4) { char char_1 = 1; double double_1 = 1; double double_2 = 1; double double_3 = 1; unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_3 = 1; long long_1 = 1; double double_4 = 1; double double_5 = 1; short short_1 = 1; short short_2 = 1; short short_3 = 1; long long_2 = 1; int int_1 = 1; int int_2 = 1; float float_1 = 1; float float_2 = 1; double double_6 = 1; int int_3 = 1; int int_4 = 1; float float_3 = 1; int int_5 = 1; char_1 = char_1 * char_1; double_3 = double_1 + double_2; if(1) { char char_2 = 1; unsigned int unsigned_int_2 = 1; char_2 = char_2; unsigned_int_3 = unsigned_int_1 * unsigned_int_2; } if(1) { if(1) { } } long_1 = long_1 + long_1; double_1 = double_4 * double_5; short_1 = short_1 * short_2; unsigned_int_1 = unsigned_int_3 * unsigned_int_1; short_3 = v__sel_set(long_1,char_1); short_2 = short_1 * short_2; double_5 = v__smart_calculate_226(long_2); int_2 = int_1 * int_1; if(1) { float_1 = float_2; } double_4 = double_6 * double_4; v_termpty_resize(float_2,int_3,int_4); float_3 = float_1 + float_1; short_2 = short_2 * short_3; short_1 = v__smart_apply(double_6,-1 ); int_3 = int_5 * int_5; double_5 = double_4 + double_3; int_2 = int_1 + int_2; return float_2; } void v_colors_term_init( long parameter_1,char parameter_2,long parameter_3) { int int_1 = 1; long long_1 = 1; long long_2 = 1; int int_2 = 1; char char_1 = 1; char char_2 = 1; int int_3 = 1; int int_4 = 1; double double_2 = 1; double double_3 = 1; double double_4 = 1; int int_5 = 1; double double_6 = 1; int_1 = int_1 * int_1; long_1 = long_2; int_1 = int_1 * int_2; char_2 = char_1 * char_1; for(int looper_1=0; looper_1<1;looper_1++) { char char_3 = 1; char char_4 = 1; long long_3 = 1; char char_6 = 1; int_3 = int_3; if(1) { short short_1 = 1; short short_2 = 1; short short_3 = 1; char_1 = char_2 * char_3; int_1 = int_1 + int_4; int_1 = int_3 + int_3; short_3 = short_1 + short_2; } if(1) { double double_1 = 1; double_1 = double_1 * double_2; if(1) { double double_5 = 1; char char_5 = 1; double_3 = double_2 * double_2; double_4 = double_4 * double_5; char_3 = char_4 + char_5; int_3 = int_3; int_5 = int_2 + int_2; } } long_2 = long_3; char_6 = char_6 * char_4; } for(int looper_2=0; looper_2<1;looper_2++) { if(1) { unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; unsigned_int_2 = unsigned_int_1 + unsigned_int_2; if(1) { unsigned_int_2 = unsigned_int_2 + unsigned_int_1; } } } for(int looper_3=0; looper_3<1;looper_3++) { if(1) { double_3 = double_6 * double_2; if(1) { int_3 = int_1; } } } for(int looper_4=0; looper_4<1;looper_4++) { int int_6 = 1; double_3 = double_3 * double_3; if(1) { float float_1 = 1; float float_2 = 1; long long_4 = 1; long_1 = long_2; float_2 = float_1 + float_2; int_1 = int_5 + int_4; double_4 = double_4 + double_6; long_2 = long_4 + long_2; } int_6 = int_1; } } void v_termio_config_update( long parameter_1) { char char_1 = 1; char char_2 = 1; char char_3 = 1; long long_1 = 1; char char_4 = 1; long long_2 = 1; unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; unsigned int unsigned_int_3 = 1; int int_1 = 1; int int_2 = 1; long long_3 = 1; float float_1 = 1; short short_1 = 1; float float_3 = 1; float float_4 = 1; double double_1 = 1; float float_5 = 1; float float_6 = 1; long long_4 = 1; double double_2 = 1; short short_2 = 1; short short_3 = 1; double double_3 = 1; int int_3 = 1; char_3 = char_1 + char_2; v_colors_term_init(long_1,char_4,long_2); unsigned_int_2 = unsigned_int_1 + unsigned_int_1; unsigned_int_2 = unsigned_int_3; int_1 = int_1 * int_2; if(1) { unsigned_int_2 = unsigned_int_3 + unsigned_int_2; } v_termpty_backlog_size_set(int_2,unsigned_int_3); int_2 = int_2 + int_2; if(1) { float float_2 = 1; long_2 = long_3 * long_2; float_1 = v__smart_size(short_1,int_1,int_1,char_3); float_1 = float_1 * float_2; } if(1) { long_2 = long_3 + long_2; } float_4 = float_3 * float_3; double_1 = double_1 + double_1; float_6 = float_4 + float_5; long_3 = long_2 * long_4; v_termio_set_cursor_shape(unsigned_int_3,char_1); unsigned_int_2 = unsigned_int_1; double_2 = double_2; double_1 = double_1; short_2 = short_2 * short_3; unsigned_int_1 = unsigned_int_2 * unsigned_int_3; if(1) { float_4 = float_5 + float_4; } if(1) { long_1 = long_3 * long_1; } unsigned_int_3 = unsigned_int_2 * unsigned_int_1; double_1 = double_3; int_2 = int_3 + int_3; double_2 = double_3; float_5 = float_5; } float v__font_size_set( int parameter_1,int parameter_2) { long long_1 = 1; float float_1 = 1; float float_2 = 1; double double_1 = 1; double double_2 = 1; double double_3 = 1; unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; char char_1 = 1; v_termio_config_update(long_1); float_1 = float_2; double_1 = double_1 * double_2; double_3 = double_2 + double_3; unsigned_int_2 = unsigned_int_1 + unsigned_int_2; if(1) { double_1 = double_1; } if(1) { char_1 = char_1 + char_1; } if(1) { int int_1 = 1; double double_4 = 1; long long_2 = 1; int int_2 = 1; int int_3 = 1; char char_2 = 1; char char_3 = 1; int_1 = int_1; double_4 = double_4 + double_3; long_1 = long_1 + long_2; unsigned_int_2 = unsigned_int_2 + unsigned_int_2; int_3 = int_2 + int_2; char_3 = char_1 + char_2; } return float_1; } void v_termio_font_size_set( float parameter_1,int parameter_2) { long long_1 = 1; long long_2 = 1; float float_1 = 1; int int_1 = 1; int int_2 = 1; long_2 = long_1 * long_2; float_1 = v__font_size_set(int_1,int_2); } long v__handle_xterm_50_command( float parameter_1,char parameter_2,int parameter_3) { unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; long long_1 = 1; float float_1 = 1; int int_1 = 1; unsigned_int_1 = unsigned_int_2; return long_1; v_termio_font_size_set(float_1,int_1); } float v__eina_unicode_to_hex( short parameter_1) { float float_1 = 1; if(1) { } if(1) { } if(1) { } return float_1; } int v__xterm_parse_color( long parameter_1,double parameter_2,float parameter_3,char parameter_4,int parameter_5) { char char_1 = 1; char char_2 = 1; int int_1 = 1; int int_2 = 1; int int_3 = 1; int int_4 = 1; double double_1 = 1; double double_2 = 1; int int_5 = 1; int int_6 = 1; double double_3 = 1; float float_1 = 1; unsigned int unsigned_int_2 = 1; unsigned int unsigned_int_3 = 1; float float_3 = 1; char char_4 = 1; int int_7 = 1; int int_8 = 1; char char_5 = 1; float float_6 = 1; short short_1 = 1; int int_9 = 1; char_2 = char_1 + char_2; int_1 = int_1 + int_2; if(1) { int_2 = int_3 + int_2; } int_2 = int_4 + int_3; double_1 = double_2; if(1) { float float_2 = 1; unsigned int unsigned_int_1 = 1; char char_3 = 1; long long_1 = 1; double double_4 = 1; double double_5 = 1; long long_2 = 1; int_4 = int_3 + int_2; if(1) { int_6 = int_5 * int_5; } double_1 = double_1 * double_3; float_2 = float_1 + float_1; if(1) { unsigned_int_2 = unsigned_int_1 * unsigned_int_1; } int_5 = int_5 + int_4; unsigned_int_1 = unsigned_int_2 + unsigned_int_3; if(1) { unsigned_int_3 = unsigned_int_1 * unsigned_int_1; } float_3 = float_2 + float_1; char_3 = char_4; if(1) { int_4 = int_7 * int_8; } double_1 = double_2; long_1 = long_1 * long_1; if(1) { float float_4 = 1; float float_5 = 1; float_3 = float_4 + float_5; } double_5 = double_4 * double_4; char_1 = char_5; if(1) { long long_3 = 1; long_3 = long_2 * long_1; } long_2 = long_2 + long_2; } if(1) { long long_4 = 1; long long_5 = 1; unsigned int unsigned_int_4 = 1; unsigned int unsigned_int_5 = 1; int_5 = int_2; if(1) { double_3 = double_2; } int_2 = int_8 + int_7; char_5 = char_5 * char_4; if(1) { float float_7 = 1; float_6 = v__eina_unicode_to_hex(short_1); float_3 = float_7 * float_1; } long_5 = long_4 * long_4; unsigned_int_5 = unsigned_int_4 + unsigned_int_3; if(1) { unsigned_int_2 = unsigned_int_5; } int_8 = int_3 * int_6; } if(1) { float float_8 = 1; float_8 = float_1 * float_6; } int_9 = int_9 * int_1; return int_6; } unsigned int v__xterm_arg_get( short parameter_1) { short short_1 = 1; short short_2 = 1; short short_3 = 1; char char_1 = 1; char char_2 = 1; float float_1 = 1; float float_2 = 1; float float_3 = 1; int int_1 = 1; int int_2 = 1; unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; int int_3 = 1; unsigned int unsigned_int_3 = 1; long long_1 = 1; long long_2 = 1; int int_4 = 1; int int_5 = 1; unsigned int unsigned_int_4 = 1; long long_3 = 1; float float_4 = 1; unsigned int unsigned_int_5 = 1; char char_3 = 1; char char_4 = 1; double double_1 = 1; double double_2 = 1; char char_5 = 1; double double_3 = 1; long long_4 = 1; long long_5 = 1; long long_6 = 1; short_3 = short_1 + short_2; char_2 = char_1 * char_2; float_3 = float_1 * float_2; int_2 = int_1 + int_1; int_2 = int_2 + int_1; unsigned_int_1 = unsigned_int_1 + unsigned_int_2; int_1 = int_2 + int_3; unsigned_int_1 = unsigned_int_3 + unsigned_int_3; long_1 = long_1 * long_2; int_2 = int_1 + int_4; int_5 = int_3; unsigned_int_3 = unsigned_int_2 * unsigned_int_4; short_2 = short_2 + short_2; unsigned_int_3 = unsigned_int_1 + unsigned_int_4; long_3 = long_3; float_2 = float_3 * float_4; unsigned_int_5 = unsigned_int_4 + unsigned_int_4; char_4 = char_3 + char_2; double_2 = double_1 * double_2; char_5 = char_3 * char_2; double_2 = double_3 * double_2; long_6 = long_4 * long_5; return unsigned_int_2; } void v__handle_esc_xterm( short parameter_1,short parameter_2,long parameter_3) { char char_1 = 1; double double_1 = 1; long long_1 = 1; int int_1 = 1; int int_2 = 1; int int_3 = 1; double double_2 = 1; short short_1 = 1; short short_2 = 1; unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; float float_1 = 1; float float_2 = 1; unsigned int unsigned_int_3 = 1; unsigned int unsigned_int_4 = 1; short short_3 = 1; int int_4 = 1; double double_3 = 1; char char_2 = 1; float float_3 = 1; float float_4 = 1; double double_4 = 1; char char_3 = 1; unsigned int unsigned_int_5 = 1; unsigned int unsigned_int_6 = 1; float float_5 = 1; double double_5 = 1; unsigned int unsigned_int_7 = 1; int int_5 = 1; float float_6 = 1; double double_7 = 1; char_1 = char_1; v_termpty_write(double_1,long_1,int_1); int_3 = int_2 + int_3; double_1 = double_2; short_2 = short_1 * short_1; unsigned_int_1 = unsigned_int_1 + unsigned_int_2; int_1 = int_2; if(1) { float_2 = float_1 + float_2; } int_1 = int_3 + int_2; float_2 = float_2 + float_1; unsigned_int_4 = unsigned_int_2 + unsigned_int_3; if(1) { short_3 = short_2 * short_2; } int_1 = int_3 * int_4; if(1) { double_3 = v_termio_textgrid_get(char_2); unsigned_int_3 = v__handle_xterm_777_command(short_2,char_1,int_3); float_1 = float_3 + float_4; } double_4 = double_2 * double_1; unsigned_int_4 = unsigned_int_2; unsigned_int_4 = v__xterm_arg_get(short_3); char_1 = char_1 + char_3; unsigned_int_3 = unsigned_int_5 * unsigned_int_1; unsigned_int_6 = unsigned_int_1 + unsigned_int_4; if(1) { char_1 = char_3 * char_2; } if(1) { float_4 = float_2 + float_5; double_2 = double_5 + double_2; unsigned_int_7 = unsigned_int_6; } char controller_6[2]; fgets(controller_6,2,stdin); if( strcmp( controller_6, "L") > 0) { int_2 = int_2; } if(1) { long long_2 = 1; long_2 = long_1 * long_2; } int_5 = int_1 * int_1; int_5 = int_3; if(1) { double_3 = double_4 * double_4; } if(1) { float_5 = v_termio_config_get(); unsigned_int_4 = unsigned_int_7 * unsigned_int_2; } if(1) { int_4 = int_4 + int_1; int_5 = v__xterm_parse_color(long_1,double_4,float_3,char_1,int_2); long_1 = v__handle_xterm_50_command(float_3,char_1,int_5); float_5 = float_6 + float_4; } if(1) { double double_6 = 1; double_5 = double_6; } if(1) { int_5 = int_2 * int_1; } double_7 = double_4 * double_4; float_6 = float_3 * float_1; } void v_termpty_cells_set_content( short parameter_1,int parameter_2,double parameter_3,int parameter_4) { short short_1 = 1; short short_2 = 1; short_1 = short_2; for(int looper_1=0; looper_1<1;looper_1++) { int int_1 = 1; int int_2 = 1; double double_1 = 1; double double_2 = 1; int_2 = int_1 + int_1; double_2 = double_1 + double_2; } } long v__handle_esc_csi_decera( float parameter_1,double parameter_2) { float float_1 = 1; double double_1 = 1; double double_2 = 1; double double_3 = 1; short short_1 = 1; int int_1 = 1; double double_4 = 1; double double_5 = 1; int int_2 = 1; long long_1 = 1; long long_2 = 1; long long_3 = 1; long long_4 = 1; int int_3 = 1; float_1 = v__csi_arg_get(float_1); double_2 = double_1 * double_1; double_3 = double_3 + double_1; v_termpty_cells_set_content(short_1,int_1,double_4,int_1); float_1 = float_1; double_2 = double_1 + double_5; int_2 = int_2 + int_2; long_3 = long_1 + long_2; char controller_1[3]; fgets(controller_1,3,stdin); if( strcmp( controller_1, "g6") > 0) { } double_4 = double_1 * double_2; for(int looper_1=0; looper_1<1;looper_1++) { float float_2 = 1; double double_6 = 1; float_1 = float_1 + float_2; double_6 = double_6 * double_1; } return long_4; v__clean_up_rect_coordinates(long_1,int_1,int_3,int_2,int_1); } void v_termpty_cells_att_fill_preserve_colors( short parameter_1,long parameter_2,short parameter_3,int parameter_4) { int int_1 = 1; int int_2 = 1; short short_1 = 1; short short_2 = 1; int_2 = int_1 + int_2; short_2 = short_1 * short_1; for(int looper_1=0; looper_1<1;looper_1++) { unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; unsigned int unsigned_int_3 = 1; double double_1 = 1; double double_2 = 1; short short_3 = 1; unsigned_int_3 = unsigned_int_1 * unsigned_int_2; double_1 = double_2; short_2 = short_3 + short_1; if(1) { long long_1 = 1; long long_2 = 1; double double_3 = 1; double double_4 = 1; float float_1 = 1; unsigned int unsigned_int_4 = 1; long_2 = long_1 * long_1; double_4 = double_3 * double_3; double_4 = double_1; float_1 = float_1 * float_1; unsigned_int_2 = unsigned_int_2 + unsigned_int_4; short_2 = short_3 * short_2; } } } void v__clean_up_rect_coordinates( long parameter_1,int parameter_2,int parameter_3,int parameter_4,int parameter_5) { unsigned int unsigned_int_1 = 1; int int_1 = 1; long long_1 = 1; double double_1 = 1; double double_2 = 1; unsigned int unsigned_int_2 = 1; unsigned int unsigned_int_3 = 1; int int_2 = 1; int int_3 = 1; long long_3 = 1; long long_4 = 1; long long_5 = 1; unsigned int unsigned_int_4 = 1; short short_1 = 1; float float_1 = 1; float float_2 = 1; char char_1 = 1; char char_2 = 1; unsigned int unsigned_int_6 = 1; float float_3 = 1; float float_4 = 1; unsigned_int_1 = unsigned_int_1 * unsigned_int_1; int_1 = int_1 * int_1; long_1 = long_1 + long_1; int_1 = int_1 * int_1; double_2 = double_1 * double_1; unsigned_int_3 = unsigned_int_2 * unsigned_int_3; if(1) { long long_2 = 1; long_2 = long_1 + long_1; } int_2 = int_3; long_5 = long_3 + long_4; if(1) { unsigned_int_4 = unsigned_int_3 * unsigned_int_4; } if(1) { short_1 = short_1 * short_1; } if(1) { double_2 = double_2; if(1) { int_2 = int_1; } } if(1) { short short_2 = 1; short_1 = short_2; } if(1) { unsigned int unsigned_int_5 = 1; unsigned_int_1 = unsigned_int_3 + unsigned_int_5; } if(1) { int_1 = int_2 * int_1; if(1) { int int_4 = 1; int_4 = int_2; } } unsigned_int_1 = unsigned_int_1 + unsigned_int_4; if(1) { int int_5 = 1; int_1 = int_1 * int_5; } if(1) { } float_2 = float_1 * float_1; char_2 = char_1 * char_2; unsigned_int_6 = unsigned_int_2 * unsigned_int_3; float_4 = float_1 * float_3; } short v__handle_esc_csi_decfra( short parameter_1,short parameter_2) { unsigned int unsigned_int_1 = 1; float float_1 = 1; float float_2 = 1; float float_3 = 1; int int_1 = 1; int int_2 = 1; unsigned int unsigned_int_2 = 1; unsigned int unsigned_int_3 = 1; short short_1 = 1; long long_1 = 1; short short_2 = 1; int int_3 = 1; short short_3 = 1; int int_4 = 1; double double_1 = 1; double double_2 = 1; short short_4 = 1; int int_5 = 1; unsigned_int_1 = unsigned_int_1; float_2 = float_1 + float_1; float_2 = v__csi_arg_get(float_3); unsigned_int_1 = unsigned_int_1 * unsigned_int_1; int_1 = int_1 + int_2; unsigned_int_3 = unsigned_int_1 + unsigned_int_2; v_termpty_cells_att_fill_preserve_colors(short_1,long_1,short_2,int_3); short_3 = short_2 + short_1; int_4 = int_4 + int_2; if(1) { } if(1) { } double_2 = double_1 + double_1; for(int looper_1=0; looper_1<1;looper_1++) { unsigned int unsigned_int_4 = 1; unsigned_int_1 = unsigned_int_3 + unsigned_int_2; unsigned_int_3 = unsigned_int_4; } return short_4; v__clean_up_rect_coordinates(long_1,int_2,int_2,int_3,int_5); } void v__handle_esc_csi_decslrm( int parameter_1,double parameter_2) { unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; int int_1 = 1; int int_2 = 1; float float_1 = 1; char char_1 = 1; unsigned int unsigned_int_3 = 1; float float_2 = 1; float float_3 = 1; long long_1 = 1; long long_2 = 1; unsigned int unsigned_int_4 = 1; unsigned int unsigned_int_5 = 1; unsigned int unsigned_int_6 = 1; short short_1 = 1; short short_2 = 1; int int_3 = 1; int int_4 = 1; unsigned_int_1 = unsigned_int_1 * unsigned_int_2; int_1 = int_2; float_1 = v__csi_arg_get(float_1); char_1 = v__move_cursor_to_origin(unsigned_int_3); float_1 = float_2 * float_3; long_1 = long_1 + long_2; if(1) { char char_2 = 1; char_2 = char_1 * char_2; } unsigned_int_4 = unsigned_int_4 * unsigned_int_1; if(1) { int_2 = int_2 + int_2; } if(1) { double double_1 = 1; double double_2 = 1; double_1 = double_2; } if(1) { float float_4 = 1; float_2 = float_4 + float_2; } unsigned_int_6 = unsigned_int_5 * unsigned_int_3; float_1 = float_1 * float_3; short_2 = short_1 * short_1; int_4 = int_3 * int_4; char_1 = char_1; } short v__handle_esc_csi_decstbm( double parameter_1,int parameter_2) { int int_1 = 1; long long_1 = 1; long long_2 = 1; long long_3 = 1; long long_4 = 1; char char_1 = 1; unsigned int unsigned_int_1 = 1; float float_1 = 1; double double_1 = 1; long long_5 = 1; double double_2 = 1; float float_2 = 1; float float_3 = 1; char char_2 = 1; short short_1 = 1; int_1 = int_1 + int_1; int_1 = int_1 + int_1; long_2 = long_1 * long_2; long_1 = long_3 + long_4; char_1 = v__move_cursor_to_origin(unsigned_int_1); float_1 = float_1; if(1) { long_3 = long_2 * long_2; } if(1) { unsigned_int_1 = unsigned_int_1 * unsigned_int_1; } long_3 = long_1 * long_4; double_1 = double_1; long_5 = long_3 * long_2; double_2 = double_1 + double_1; float_2 = v__csi_arg_get(float_3); char_1 = char_1 + char_2; return short_1; } long v__handle_esc_csi_decscusr( short parameter_1,unsigned int parameter_2) { int int_1 = 1; int int_2 = 1; int int_3 = 1; unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; double double_1 = 1; double double_2 = 1; float float_1 = 1; int int_4 = 1; int int_5 = 1; int int_6 = 1; float float_2 = 1; int int_7 = 1; char char_1 = 1; unsigned int unsigned_int_3 = 1; unsigned int unsigned_int_4 = 1; long long_1 = 1; long long_2 = 1; long long_3 = 1; double double_3 = 1; int_3 = int_1 * int_2; unsigned_int_2 = unsigned_int_1 * unsigned_int_2; double_2 = double_1 + double_2; float_1 = float_1 + float_1; int_2 = int_4 + int_3; int_6 = int_3 * int_5; float_1 = float_1 * float_2; float_2 = v__csi_arg_get(float_1); int_4 = int_2 + int_7; v_termio_set_cursor_shape(unsigned_int_2,char_1); char_1 = char_1 + char_1; unsigned_int_4 = unsigned_int_3 * unsigned_int_3; float_1 = float_2 + float_2; long_1 = long_1; long_3 = long_2 * long_2; double_3 = double_1; unsigned_int_1 = unsigned_int_3 + unsigned_int_2; return long_1; } double v__handle_esc_csi_dsr( char parameter_1,short parameter_2) { long long_1 = 1; double double_1 = 1; double double_2 = 1; float float_1 = 1; int int_1 = 1; int int_2 = 1; int int_3 = 1; double double_3 = 1; long long_2 = 1; long_1 = long_1 * long_1; double_1 = double_2; char controller_1[2]; fgets(controller_1,2,stdin); if( strcmp( controller_1, "Q") < 0) { float_1 = float_1 * float_1; } if(1) { char char_1 = 1; char char_2 = 1; unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; unsigned int unsigned_int_3 = 1; unsigned int unsigned_int_4 = 1; char_1 = char_2; int_2 = int_1 * int_1; unsigned_int_1 = unsigned_int_1; int_3 = int_3 * int_1; float_1 = v__csi_arg_get(float_1); unsigned_int_3 = unsigned_int_2 + unsigned_int_2; double_3 = double_1 * double_2; unsigned_int_3 = unsigned_int_2 + unsigned_int_4; } if(1) { short short_1 = 1; double double_4 = 1; double_3 = double_3 * double_1; long_1 = long_2 * long_1; int_1 = int_3 * int_1; short_1 = short_1 + short_1; v_termpty_write(double_3,long_2,int_3); double_4 = double_4; int_2 = int_1 * int_3; } return double_2; } unsigned int v__handle_esc_csi_truecolor_cmyk( unsigned int parameter_1,char parameter_2) { unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; int int_1 = 1; double double_1 = 1; double double_2 = 1; double double_3 = 1; int int_2 = 1; float float_1 = 1; short short_1 = 1; char char_1 = 1; char char_2 = 1; unsigned int unsigned_int_3 = 1; unsigned int unsigned_int_4 = 1; unsigned int unsigned_int_5 = 1; long long_1 = 1; long long_2 = 1; short short_2 = 1; int int_3 = 1; float float_2 = 1; float float_3 = 1; unsigned_int_2 = unsigned_int_1 * unsigned_int_1; int_1 = int_1 + int_1; double_2 = double_1 + double_1; double_2 = double_1 * double_3; int_2 = int_2; if(1) { } float_1 = v__approximate_truecolor_rgb(short_1,int_1,int_2,int_2); char_1 = char_1 * char_2; unsigned_int_5 = unsigned_int_3 + unsigned_int_4; long_2 = long_1 * long_1; short_2 = short_1 * short_2; int_3 = int_2 + int_1; long_2 = v__csi_truecolor_arg_get(double_1); float_2 = float_2 * float_3; return unsigned_int_3; } unsigned int v__handle_esc_csi_truecolor_cmy( int parameter_1,int parameter_2) { float float_1 = 1; short short_1 = 1; int int_1 = 1; int int_2 = 1; short short_2 = 1; long long_1 = 1; double double_1 = 1; double double_2 = 1; double double_3 = 1; int int_3 = 1; unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; float_1 = v__approximate_truecolor_rgb(short_1,int_1,int_1,int_2); short_2 = short_1 * short_1; short_2 = short_2 + short_2; long_1 = v__csi_truecolor_arg_get(double_1); double_3 = double_2 + double_1; int_3 = int_2 * int_1; if(1) { } int_2 = int_1 + int_3; double_1 = double_1 + double_3; unsigned_int_1 = unsigned_int_1 * unsigned_int_1; return unsigned_int_2; } float v__approximate_truecolor_rgb( short parameter_1,int parameter_2,int parameter_3,int parameter_4) { float float_1 = 1; double double_1 = 1; char char_1 = 1; int int_1 = 1; int int_2 = 1; int int_3 = 1; float float_2 = 1; float_1 = float_1 * float_1; double_1 = v_termio_textgrid_get(char_1); int_3 = int_1 + int_2; for(int looper_1=0; looper_1<1;looper_1++) { if(1) { char char_2 = 1; char_1 = char_2 + char_1; } if(1) { unsigned int unsigned_int_1 = 1; unsigned_int_1 = unsigned_int_1 * unsigned_int_1; if(1) { float_2 = float_2; } } } return float_2; } long v__csi_truecolor_arg_get( double parameter_1) { long long_1 = 1; return long_1; } float v__handle_esc_csi_truecolor_rgb( float parameter_1,unsigned int parameter_2) { float float_1 = 1; float float_2 = 1; double double_1 = 1; double double_2 = 1; float float_3 = 1; short short_1 = 1; int int_1 = 1; int int_2 = 1; int int_3 = 1; unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; double double_3 = 1; double double_4 = 1; long long_1 = 1; float float_4 = 1; float float_5 = 1; float_2 = float_1 + float_2; double_1 = double_1 * double_2; float_3 = v__approximate_truecolor_rgb(short_1,int_1,int_2,int_3); unsigned_int_2 = unsigned_int_1 + unsigned_int_1; double_4 = double_3 + double_2; long_1 = v__csi_truecolor_arg_get(double_3); float_3 = float_4 + float_4; char controller_1[3]; fgets(controller_1,3,stdin); if( strcmp( controller_1, "CQ") > 0) { int int_4 = 1; int int_5 = 1; unsigned int unsigned_int_3 = 1; unsigned_int_1 = unsigned_int_2; int_5 = int_4 + int_4; unsigned_int_3 = unsigned_int_1 + unsigned_int_2; } if(1) { } return float_5; } double v__handle_esc_csi_color_set( float parameter_1,char parameter_2) { unsigned int unsigned_int_1 = 1; int int_1 = 1; int int_2 = 1; int int_3 = 1; int int_4 = 1; float float_1 = 1; unsigned int unsigned_int_2 = 1; double double_1 = 1; char char_1 = 1; v_termpty_reset_att(); unsigned_int_1 = v__handle_esc_csi_truecolor_cmy(int_1,int_2); int_4 = int_3 * int_2; float_1 = v__handle_esc_csi_truecolor_rgb(float_1,unsigned_int_1); unsigned_int_2 = unsigned_int_1 + unsigned_int_2; return double_1; float_1 = v__csi_arg_get(float_1); unsigned_int_1 = v__handle_esc_csi_truecolor_cmyk(unsigned_int_2,char_1); } void v_termpty_cursor_copy( unsigned int parameter_1,float parameter_2) { if(1) { unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; short short_1 = 1; short short_2 = 1; unsigned_int_2 = unsigned_int_1 + unsigned_int_2; short_2 = short_1 * short_2; } if(1) { int int_1 = 1; int int_2 = 1; int int_3 = 1; double double_1 = 1; double double_2 = 1; char char_1 = 1; char char_2 = 1; int_3 = int_1 * int_2; double_2 = double_1 * double_1; char_2 = char_1 * char_1; int_3 = int_3 * int_3; } } char v__switch_to_alternative_screen( short parameter_1,int parameter_2) { char char_1 = 1; if(1) { short short_1 = 1; short short_2 = 1; short_1 = short_1 + short_2; } return char_1; v_termpty_screen_swap(char_1); } char v__move_cursor_to_origin( unsigned int parameter_1) { short short_1 = 1; char char_3 = 1; if(1) { long long_1 = 1; long long_2 = 1; float float_1 = 1; char char_1 = 1; char char_2 = 1; long_2 = long_1 * long_1; float_1 = float_1; char_1 = char_1 * char_2; short_1 = short_1; } if(1) { int int_1 = 1; short short_2 = 1; int_1 = int_1 * int_1; short_1 = short_2; } return char_3; } short v__pty_size( long parameter_1) { long long_1 = 1; long long_2 = 1; long long_3 = 1; unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; int int_1 = 1; unsigned int unsigned_int_3 = 1; unsigned int unsigned_int_4 = 1; short short_1 = 1; long_3 = long_1 * long_2; unsigned_int_2 = unsigned_int_1 + unsigned_int_1; int_1 = int_1 * int_1; unsigned_int_4 = unsigned_int_2 + unsigned_int_3; unsigned_int_4 = unsigned_int_1 * unsigned_int_2; if(1) { short_1 = short_1; } return short_1; } float v__limit_coord() { unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; int int_1 = 1; int int_2 = 1; char char_1 = 1; long long_1 = 1; long long_2 = 1; char char_2 = 1; char char_3 = 1; char char_4 = 1; float float_1 = 1; float float_2 = 1; char char_5 = 1; char char_6 = 1; int int_3 = 1; int int_4 = 1; unsigned_int_1 = unsigned_int_2; int_1 = int_1 + int_2; char_1 = char_1 * char_1; long_2 = long_1 + long_1; char_4 = char_2 * char_3; float_2 = float_1 + float_1; char_6 = char_5 * char_4; int_2 = int_3 * int_4; return float_2; } double v__check_screen_info( unsigned int parameter_1,long parameter_2) { double double_1 = 1; int int_1 = 1; short short_1 = 1; int int_4 = 1; long long_1 = 1; unsigned int unsigned_int_2 = 1; float float_1 = 1; if(1) { double double_2 = 1; double double_3 = 1; int int_2 = 1; int int_3 = 1; short short_2 = 1; char char_1 = 1; char char_2 = 1; double_3 = double_1 * double_2; int_3 = int_1 * int_2; short_1 = short_1 + short_2; char_2 = char_1 * char_1; int_1 = int_2 + int_4; if(1) { unsigned int unsigned_int_1 = 1; v_termpty_cells_clear(int_1,long_1,int_4); unsigned_int_2 = unsigned_int_1 * unsigned_int_1; } v_termpty_text_save_top(float_1,unsigned_int_2,short_1); int_1 = int_1 * int_1; } return double_1; } int v__termpty_line_rewrap( short parameter_1,unsigned int parameter_2,int parameter_3,short parameter_4,float parameter_5) { double double_1 = 1; unsigned int unsigned_int_1 = 1; long long_1 = 1; int int_1 = 1; float float_1 = 1; float float_2 = 1; double_1 = v__check_screen_info(unsigned_int_1,long_1); int_1 = int_1 + int_1; double_1 = double_1 * double_1; float_2 = float_1 * float_1; return int_1; } float v__backlog_remove_latest_nolock( unsigned int parameter_1) { unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; unsigned int unsigned_int_3 = 1; unsigned int unsigned_int_4 = 1; double double_1 = 1; float float_1 = 1; float float_2 = 1; double double_3 = 1; long long_1 = 1; char char_1 = 1; char char_2 = 1; long long_2 = 1; int int_1 = 1; int int_2 = 1; unsigned_int_3 = unsigned_int_1 * unsigned_int_2; if(1) { } unsigned_int_3 = unsigned_int_4; if(1) { unsigned int unsigned_int_5 = 1; unsigned int unsigned_int_6 = 1; unsigned_int_6 = unsigned_int_3 * unsigned_int_5; } if(1) { double double_2 = 1; double_2 = double_1 * double_1; } float_2 = float_1 * float_1; double_1 = double_1 + double_3; v_termpty_save_free(long_1); char_2 = char_1 * char_2; float_1 = float_1; return float_2; long_2 = v_verify_beacon(int_1,int_2); } void v_termpty_save_extract( long parameter_1) { if(1) { } if(1) { if(1) { char char_1 = 1; char char_2 = 1; char char_3 = 1; unsigned int unsigned_int_1 = 1; long long_1 = 1; long long_2 = 1; long long_3 = 1; long long_4 = 1; float float_1 = 1; float float_2 = 1; float float_3 = 1; unsigned int unsigned_int_2 = 1; long long_5 = 1; long long_6 = 1; unsigned int unsigned_int_3 = 1; char_3 = char_1 + char_2; unsigned_int_1 = unsigned_int_1; long_1 = long_1 * long_2; long_4 = long_2 * long_3; float_3 = float_1 * float_2; if(1) { } unsigned_int_2 = unsigned_int_1 * unsigned_int_1; long_5 = long_6; unsigned_int_2 = unsigned_int_3 + unsigned_int_3; if(1) { float float_4 = 1; float float_5 = 1; float_4 = float_5; } } } } int v__termpty_line_is_empty( int parameter_1,unsigned int parameter_2) { float float_1 = 1; float float_2 = 1; double double_1 = 1; int int_1 = 1; float_1 = float_1 + float_2; for(int looper_1=0; looper_1<1;looper_1++) { double double_2 = 1; double double_3 = 1; double double_4 = 1; double_1 = v__termpty_cell_is_empty(); double_4 = double_2 * double_3; char controller_1[3]; fgets(controller_1,3,stdin); if( strcmp( controller_1, "J]") < 0) { } } return int_1; } void v_termpty_screen_swap( char parameter_1) { double double_1 = 1; double double_2 = 1; double double_3 = 1; int int_1 = 1; int int_2 = 1; int int_3 = 1; long long_1 = 1; short short_1 = 1; unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; unsigned int unsigned_int_3 = 1; float float_1 = 1; double_1 = double_1 * double_2; double_3 = double_2 + double_1; int_3 = int_1 + int_2; long_1 = long_1 + long_1; double_3 = double_2 * double_3; short_1 = short_1 * short_1; int_2 = int_1 * int_3; unsigned_int_3 = unsigned_int_1 + unsigned_int_2; float_1 = float_1 * float_1; if(1) { float float_2 = 1; float_1 = float_2 * float_2; } } void v_termpty_resize( float parameter_1,int parameter_2,int parameter_3) { long long_1 = 1; int int_1 = 1; short short_1 = 1; int int_2 = 1; double double_1 = 1; double double_2 = 1; double double_3 = 1; long long_2 = 1; long long_3 = 1; int int_3 = 1; unsigned int unsigned_int_1 = 1; float float_1 = 1; float float_2 = 1; double double_4 = 1; char char_1 = 1; unsigned int unsigned_int_2 = 1; unsigned int unsigned_int_3 = 1; double double_5 = 1; long long_4 = 1; long long_5 = 1; int int_4 = 1; int int_5 = 1; double double_6 = 1; short short_2 = 1; double double_7 = 1; short short_3 = 1; int int_6 = 1; char char_3 = 1; float float_3 = 1; float float_4 = 1; short short_4 = 1; float float_5 = 1; int int_8 = 1; unsigned int unsigned_int_4 = 1; float float_6 = 1; unsigned int unsigned_int_5 = 1; int int_9 = 1; short short_5 = 1; double double_8 = 1; long_1 = v_verify_beacon(int_1,int_1); short_1 = short_1; short_1 = short_1; int_1 = int_1 + int_2; double_3 = double_1 * double_2; if(1) { } long_2 = long_2 + long_3; if(1) { int_1 = v__termpty_line_is_empty(int_3,unsigned_int_1); float_1 = float_2; short_1 = short_1 + short_1; } double_4 = double_1; if(1) { float_1 = v__backlog_remove_latest_nolock(unsigned_int_1); char_1 = char_1; } unsigned_int_3 = unsigned_int_2 * unsigned_int_1; v_termpty_backlog_lock(); double_5 = double_3; if(1) { double_2 = double_4; } unsigned_int_2 = unsigned_int_3 + unsigned_int_1; unsigned_int_3 = unsigned_int_1 * unsigned_int_1; long_2 = long_2 + long_1; long_5 = long_3 + long_4; for(int looper_1=0; looper_1<1;looper_1++) { int_4 = int_2 + int_3; if(1) { double_1 = double_2 + double_5; int_2 = int_5 * int_2; } } double_1 = double_3 + double_6; if(1) { short_2 = short_1 * short_1; } double_7 = double_2 * double_5; if(1) { short_2 = short_1 + short_2; unsigned_int_2 = unsigned_int_2 + unsigned_int_3; int_4 = int_1 + int_3; if(1) { char char_2 = 1; int int_7 = 1; short_3 = short_1 + short_1; double_4 = double_3 + double_5; int_6 = int_6 + int_4; long_5 = long_2 * long_3; if(1) { double_5 = double_6 + double_4; } char_2 = char_1 * char_2; double_7 = double_1 * double_6; int_7 = int_2 * int_1; v_termpty_screen_swap(char_3); double_2 = double_1 * double_3; double_4 = double_1 * double_4; float_4 = float_3 + float_3; float_2 = float_2 * float_2; } } for(int looper_2=0; looper_2<1;looper_2++) { float_2 = float_2 + float_4; double_6 = v_termpty_line_length(short_3,unsigned_int_3); short_2 = short_4 * short_3; double_4 = double_3 * double_3; short_4 = v__pty_size(long_5); float_5 = float_1 * float_2; } int_2 = int_8 * int_3; unsigned_int_4 = unsigned_int_2 + unsigned_int_3; int_4 = int_4 + int_8; float_1 = float_6 * float_6; int_1 = v__termpty_line_rewrap(short_4,unsigned_int_2,int_4,short_3,float_3); unsigned_int_5 = unsigned_int_5 + unsigned_int_2; float_6 = v__limit_coord(); int_5 = int_2 + int_9; unsigned_int_2 = unsigned_int_5; v_termpty_resize_tabs(float_5,int_1,int_6); short_1 = short_2 * short_1; if(1) { unsigned_int_4 = unsigned_int_4 * unsigned_int_4; } short_2 = short_3; v_termpty_save_extract(long_3); short_4 = short_3 + short_5; unsigned_int_1 = unsigned_int_3 * unsigned_int_2; v_termpty_backlog_unlock(); int_8 = int_5; double_3 = double_5 + double_6; double_6 = double_5; unsigned_int_4 = unsigned_int_5 + unsigned_int_2; double_6 = double_2 + double_8; } double v_termio_win_get( char parameter_1) { double double_1 = 1; double double_2 = 1; short short_1 = 1; short short_2 = 1; double_2 = double_1 * double_2; short_1 = short_2; return double_2; } long v__handle_esc_csi_reset_mode( unsigned int parameter_1,short parameter_2,short parameter_3) { char char_1 = 1; char char_2 = 1; short short_1 = 1; int int_1 = 1; char char_3 = 1; float float_1 = 1; int int_2 = 1; unsigned int unsigned_int_1 = 1; int int_3 = 1; int int_4 = 1; long long_1 = 1; double double_1 = 1; char char_4 = 1; unsigned int unsigned_int_2 = 1; char_1 = char_1; char_2 = v__switch_to_alternative_screen(short_1,int_1); char_1 = char_3 + char_2; float_1 = v__csi_arg_get(float_1); v_termpty_clear_screen(int_2,char_2); v_termpty_cursor_copy(unsigned_int_1,float_1); int_4 = int_1 * int_3; return long_1; double_1 = v_termio_win_get(char_4); v_termpty_resize(float_1,int_4,int_4); v_termpty_reset_state(short_1); char_4 = v__move_cursor_to_origin(unsigned_int_2); } char v__handle_esc_csi_cursor_pos_set( double parameter_1,unsigned int parameter_2,long parameter_3) { double double_1 = 1; double double_2 = 1; int int_1 = 1; int int_2 = 1; unsigned int unsigned_int_1 = 1; char char_1 = 1; float float_1 = 1; unsigned int unsigned_int_2 = 1; int int_3 = 1; int int_4 = 1; short short_2 = 1; char char_2 = 1; int int_6 = 1; int int_7 = 1; double double_3 = 1; double double_4 = 1; double double_5 = 1; double_2 = double_1 * double_1; int_2 = int_1 * int_1; unsigned_int_1 = unsigned_int_1 + unsigned_int_1; char_1 = char_1 * char_1; float_1 = v__csi_arg_get(float_1); unsigned_int_1 = unsigned_int_2; int_2 = int_3 * int_2; if(1) { int int_5 = 1; int_5 = int_4 + int_1; } if(1) { short short_1 = 1; short_2 = short_1 + short_1; if(1) { unsigned_int_2 = unsigned_int_1 * unsigned_int_2; } } char controller_4[3]; fgets(controller_4,3,stdin); if( strcmp( controller_4, "&u") > 0) { char_1 = char_2; } int_7 = int_6 * int_6; float_1 = float_1 * float_1; if(1) { short short_3 = 1; short_3 = short_3 + short_2; } if(1) { int_4 = int_1; if(1) { int_6 = int_3; } } if(1) { float float_2 = 1; float_2 = float_1 * float_2; } double_5 = double_3 + double_4; return char_2; } void v_termpty_text_scroll_rev( unsigned int parameter_1,short parameter_2) { float float_1 = 1; int int_1 = 1; int int_2 = 1; float float_2 = 1; float float_3 = 1; float float_4 = 1; double double_1 = 1; double double_2 = 1; int int_3 = 1; int int_4 = 1; unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; unsigned int unsigned_int_3 = 1; unsigned int unsigned_int_4 = 1; int int_7 = 1; long long_1 = 1; v_termio_scroll(float_1,int_1,int_2,int_1,-1 ); float_2 = float_1 * float_1; float_2 = float_3 + float_4; if(1) { double double_3 = 1; double_1 = double_1 + double_1; double_2 = double_3; } int_4 = int_1 * int_3; unsigned_int_3 = unsigned_int_1 + unsigned_int_2; if(1) { int int_5 = 1; unsigned_int_2 = unsigned_int_4; if(1) { int_1 = int_2; } int_2 = int_3 * int_5; if(1) { double_2 = double_2 * double_2; } } if(1) { unsigned_int_4 = unsigned_int_3 * unsigned_int_3; for(int looper_1=0; looper_1<1;looper_1++) { int int_6 = 1; double_2 = double_1 + double_2; int_1 = int_6 + int_2; int_6 = int_4 + int_6; } if(1) { v_termpty_cells_clear(int_7,long_1,int_7); unsigned_int_4 = unsigned_int_2; } } } void v_termpty_clear_line( int parameter_1,double parameter_2,int parameter_3) { unsigned int unsigned_int_1 = 1; int int_1 = 1; long long_1 = 1; int int_2 = 1; double double_1 = 1; double double_2 = 1; short short_1 = 1; short short_2 = 1; unsigned int unsigned_int_2 = 1; int int_3 = 1; unsigned int unsigned_int_3 = 1; double double_3 = 1; double double_4 = 1; short short_3 = 1; unsigned int unsigned_int_4 = 1; double double_5 = 1; double double_6 = 1; double double_7 = 1; char char_1 = 1; unsigned_int_1 = unsigned_int_1 + unsigned_int_1; int_1 = int_1; v_termpty_cells_clear(int_1,long_1,int_1); int_2 = int_1 + int_1; double_1 = double_1 + double_2; short_2 = short_1 + short_2; unsigned_int_1 = unsigned_int_1 * unsigned_int_2; int_1 = int_2 + int_3; unsigned_int_2 = unsigned_int_3 * unsigned_int_3; double_4 = double_1 * double_3; short_3 = short_2 * short_3; unsigned_int_1 = unsigned_int_4 * unsigned_int_4; double_6 = double_1 + double_5; if(1) { unsigned_int_1 = unsigned_int_1 * unsigned_int_3; } double_7 = double_2 + double_3; v_termio_content_change(short_3,char_1,short_1,int_3); int_3 = int_1 * int_3; } void v_termpty_clear_screen( int parameter_1,char parameter_2) { int int_1 = 1; double double_1 = 1; int int_2 = 1; long long_1 = 1; int int_3 = 1; unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; short short_1 = 1; short short_2 = 1; char char_1 = 1; short short_3 = 1; unsigned int unsigned_int_3 = 1; if(1) { float float_1 = 1; float float_2 = 1; v_termpty_clear_line(int_1,double_1,int_1); v_termpty_cells_clear(int_2,long_1,int_3); float_1 = float_2; } char controller_2[3]; fgets(controller_2,3,stdin); if( strcmp( controller_2, "-;") > 0) { double double_2 = 1; double_2 = double_1; } unsigned_int_2 = unsigned_int_1 * unsigned_int_1; short_1 = short_1 + short_2; unsigned_int_1 = unsigned_int_1 * unsigned_int_1; v_termio_content_change(short_2,char_1,short_3,int_3); unsigned_int_3 = unsigned_int_1 * unsigned_int_2; } void v_termpty_cell_codepoint_att_fill( unsigned int parameter_1,short parameter_2,short parameter_3,long parameter_4,int parameter_5) { float float_1 = 1; int int_1 = 1; int int_2 = 1; float_1 = float_1; int_2 = int_1 + int_2; for(int looper_1=0; looper_1<1;looper_1++) { long long_1 = 1; long long_2 = 1; int int_3 = 1; int int_4 = 1; long_2 = long_1 * long_2; int_3 = int_3 + int_4; } } short v__termpty_charset_trans( short parameter_1,float parameter_2) { short short_1 = 1; short short_2 = 1; unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; char char_1 = 1; char char_2 = 1; unsigned int unsigned_int_3 = 1; short short_4 = 1; if(1) { } short_1 = short_2; if(1) { } unsigned_int_1 = unsigned_int_2; char_2 = char_1 * char_2; if(1) { if(1) { float float_1 = 1; float_1 = float_1 + float_1; } if(1) { unsigned_int_3 = unsigned_int_1 + unsigned_int_3; } } if(1) { if(1) { short short_3 = 1; short_4 = short_1 + short_3; } if(1) { double double_1 = 1; double_1 = double_1 * double_1; } if(1) { unsigned int unsigned_int_4 = 1; unsigned_int_1 = unsigned_int_4 + unsigned_int_3; } if(1) { short_2 = short_4 * short_1; } } return short_4; } void v_termio_content_change( short parameter_1,char parameter_2,short parameter_3,int parameter_4) { int int_1 = 1; int int_2 = 1; int int_3 = 1; short short_1 = 1; short short_2 = 1; char char_1 = 1; char char_2 = 1; double double_1 = 1; float float_1 = 1; short short_3 = 1; float float_2 = 1; float float_3 = 1; double double_2 = 1; char char_3 = 1; char char_4 = 1; char char_5 = 1; double double_3 = 1; long long_1 = 1; long long_2 = 1; long long_3 = 1; long long_4 = 1; int int_4 = 1; unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; double double_4 = 1; float float_5 = 1; unsigned int unsigned_int_4 = 1; int_1 = int_1 * int_2; int_2 = int_2 + int_3; short_2 = short_1 + short_1; char_2 = char_1 + char_2; double_1 = double_1; if(1) { short_1 = short_1 + short_1; short_1 = short_2; float_1 = float_1; short_2 = short_3 + short_1; float_3 = float_2 + float_3; double_1 = double_2 * double_1; for(int looper_1=0; looper_1<1;looper_1++) { short short_4 = 1; char_2 = char_1; if(1) { char_3 = char_1 + char_2; char_5 = char_4 + char_4; } short_4 = short_3 + short_1; double_3 = double_2 + double_3; } } if(1) { } long_1 = long_2; long_4 = long_3 + long_4; int_4 = int_2 + int_1; unsigned_int_1 = unsigned_int_2; if(1) { char char_6 = 1; char_4 = char_6 + char_5; char_1 = char_4 + char_3; } if(1) { int int_5 = 1; unsigned int unsigned_int_3 = 1; int_2 = int_5 + int_1; short_3 = v__remove_links(int_1,double_4,-1 ); unsigned_int_1 = unsigned_int_1 + unsigned_int_3; for(int looper_2=0; looper_2<1;looper_2++) { float float_4 = 1; float float_6 = 1; short_2 = v__sel_set(long_1,char_2); float_4 = float_1 + float_1; if(1) { float_4 = float_5 + float_1; unsigned_int_4 = unsigned_int_3 * unsigned_int_2; } float_6 = float_6 + float_1; float_3 = float_2 * float_6; } } if(1) { unsigned int unsigned_int_5 = 1; unsigned int unsigned_int_6 = 1; unsigned int unsigned_int_7 = 1; unsigned_int_5 = unsigned_int_1 + unsigned_int_2; unsigned_int_1 = unsigned_int_5 + unsigned_int_6; float_5 = float_5 * float_5; unsigned_int_2 = unsigned_int_7 + unsigned_int_4; double_3 = double_2 * double_4; if(1) { unsigned_int_7 = unsigned_int_7 * unsigned_int_6; } } } void v_termpty_text_append( double parameter_1,short parameter_2,int parameter_3,int uni_para) { int int_1 = 1; int int_2 = 1; int int_3 = 1; unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; int int_4 = 1; int int_5 = 1; double double_1 = 1; long long_1 = 1; int_1 = int_1 * int_2; int_3 = int_1 * int_1; unsigned_int_2 = unsigned_int_1 + unsigned_int_1; unsigned_int_2 = unsigned_int_1 * unsigned_int_2; if(1) { int_2 = int_4 + int_4; } int_2 = int_5 * int_4; double_1 = double_1; for(int looper_1=0; looper_1<1;looper_1++) { short short_1 = 1; short short_2 = 1; short short_4 = 1; char char_2 = 1; char char_3 = 1; float float_1 = 1; float float_2 = 1; double double_2 = 1; double double_3 = 1; long long_2 = 1; double double_4 = 1; unsigned int unsigned_int_3 = 1; unsigned int unsigned_int_4 = 1; long long_3 = 1; unsigned int unsigned_int_5 = 1; float float_3 = 1; int int_7 = 1; short_1 = short_2; if(1) { short short_3 = 1; char char_1 = 1; short_4 = short_3 * short_3; char_3 = char_1 + char_2; float_2 = float_1 * float_2; double_2 = double_1 + double_2; double_2 = double_3; long_1 = long_2; } if(1) { for(int looper_2=0; looper_2<1;looper_2++) { unsigned_int_1 = unsigned_int_2 * unsigned_int_2; } } int_4 = int_3 + int_3; if(1) { double_1 = double_3 * double_2; } char controller4vul_2706[2]; fgets(controller4vul_2706,2,stdin); if( strcmp( controller4vul_2706, "*") > 0) { char controller4vul_2707[3]; fgets(controller4vul_2707,3,stdin); if( strcmp( controller4vul_2707, "3&") > 0) { v_termpty_text_scroll_test(long_1,long_1,uni_para); double_4 = double_2 * double_1; } unsigned_int_1 = unsigned_int_1; } short_1 = short_1 * short_1; if(1) { double_4 = double_2 * double_1; unsigned_int_3 = unsigned_int_1 + unsigned_int_3; } unsigned_int_3 = unsigned_int_4; if(1) { char char_4 = 1; char_2 = char_4 + char_3; long_3 = long_2 + long_1; } if(1) { unsigned_int_5 = unsigned_int_1 + unsigned_int_1; float_1 = float_3 + float_2; if(1) { int int_6 = 1; int_4 = int_4 + int_6; } if(1) { int_2 = int_4 + int_7; } if(1) { unsigned int unsigned_int_6 = 1; short_1 = short_4 + short_4; unsigned_int_5 = unsigned_int_5 + unsigned_int_6; } } if(1) { float float_4 = 1; int int_8 = 1; int int_9 = 1; int int_10 = 1; double double_5 = 1; float_3 = float_4 * float_1; int_10 = int_8 + int_9; if(1) { long_1 = long_2 + long_3; } unsigned_int_4 = unsigned_int_4 * unsigned_int_1; if(1) { unsigned int unsigned_int_7 = 1; unsigned_int_2 = unsigned_int_7 + unsigned_int_5; int_7 = int_8 + int_7; } double_4 = double_5 + double_1; } } } float v__csi_arg_get( float parameter_1) { unsigned int unsigned_int_1 = 1; char char_1 = 1; double double_1 = 1; double double_2 = 1; double double_3 = 1; char char_2 = 1; float float_1 = 1; unsigned_int_1 = unsigned_int_1; char_1 = char_1 * char_1; double_1 = double_1 * double_2; double_1 = double_3 + double_3; char_2 = char_1 + char_1; if(1) { double double_4 = 1; double double_5 = 1; double_1 = double_4 + double_5; } return float_1; } float v__handle_esc_csi( long parameter_1,double parameter_2,float parameter_3) { char char_1 = 1; int int_1 = 1; double double_1 = 1; unsigned int unsigned_int_1 = 1; long long_1 = 1; float float_1 = 1; double double_2 = 1; short short_1 = 1; char char_2 = 1; double double_3 = 1; float float_2 = 1; int int_2 = 1; int int_3 = 1; long long_2 = 1; int int_4 = 1; short short_2 = 1; int int_5 = 1; unsigned int unsigned_int_2 = 1; unsigned int unsigned_int_3 = 1; float float_3 = 1; int int_6 = 1; long long_3 = 1; float float_4 = 1; v__tab_forward(char_1,int_1); char_1 = v__handle_esc_csi_cursor_pos_set(double_1,unsigned_int_1,long_1); double_1 = v__handle_esc_csi_color_set(float_1,char_1); double_2 = v__handle_esc_csi_dsr(char_1,short_1); v_termpty_reset_state(short_1); char_2 = char_2 * char_2; char_2 = v__handle_cursor_control(double_3,float_2); v__safechar(float_2); v_termpty_clear_screen(int_2,char_2); v_termpty_clear_backlog(unsigned_int_1); v_termpty_clear_line(int_2,double_1,int_3); v_termpty_write(double_1,long_2,int_4); v_termpty_clear_tabs_on_screen(double_1); short_2 = v__handle_esc_csi_decstbm(double_3,int_5); v_termpty_cursor_copy(unsigned_int_2,float_2); short_2 = v__handle_esc_csi_decfra(short_1,short_1); unsigned_int_3 = unsigned_int_2 * unsigned_int_2; return float_1; float_2 = v__csi_arg_get(float_3); v_termpty_text_append(double_3,short_1,int_5,-1 ); v_termpty_text_scroll(int_1,int_4,-1 ); v_termpty_text_scroll_rev(unsigned_int_3,short_1); long_1 = v__handle_esc_csi_reset_mode(unsigned_int_1,short_2,short_2); long_1 = v__handle_esc_csi_decscusr(short_1,unsigned_int_2); v__handle_esc_csi_decslrm(int_6,double_3); long_3 = v__handle_esc_csi_decera(float_4,double_2); } void v__safechar( float parameter_1) { unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; float float_1 = 1; float float_2 = 1; double double_1 = 1; unsigned_int_2 = unsigned_int_1 * unsigned_int_2; if(1) { } if(1) { } float_1 = float_1 * float_2; double_1 = double_1 * double_1; } float v__handle_esc( short parameter_1,long parameter_2,char parameter_3) { float float_1 = 1; int int_1 = 1; unsigned int unsigned_int_1 = 1; long long_1 = 1; unsigned int unsigned_int_2 = 1; unsigned int unsigned_int_3 = 1; int int_2 = 1; int int_3 = 1; int int_4 = 1; float float_2 = 1; unsigned int unsigned_int_4 = 1; unsigned int unsigned_int_5 = 1; double double_1 = 1; double double_2 = 1; float float_3 = 1; float float_4 = 1; float float_5 = 1; int int_5 = 1; unsigned int unsigned_int_6 = 1; double double_3 = 1; double double_4 = 1; int int_6 = 1; char char_1 = 1; long long_2 = 1; float float_6 = 1; unsigned int unsigned_int_7 = 1; unsigned int unsigned_int_8 = 1; unsigned int unsigned_int_9 = 1; int int_7 = 1; float float_7 = 1; float float_8 = 1; float float_9 = 1; int int_8 = 1; long long_3 = 1; char char_2 = 1; double double_5 = 1; short short_1 = 1; short short_2 = 1; double double_6 = 1; long long_4 = 1; short short_3 = 1; short short_4 = 1; double double_7 = 1; float float_10 = 1; double double_8 = 1; float float_11 = 1; short short_5 = 1; float_1 = v__handle_esc_dcs(int_1,unsigned_int_1,long_1); unsigned_int_1 = unsigned_int_2 * unsigned_int_3; if(1) { } int_4 = int_2 * int_3; float_2 = float_1 + float_1; if(1) { } unsigned_int_5 = unsigned_int_4 * unsigned_int_2; if(1) { } double_1 = double_1; if(1) { } double_2 = double_1 * double_1; if(1) { } float_3 = float_3 * float_2; float_3 = float_4 * float_5; int_2 = int_3 + int_4; double_1 = double_2 + double_2; int_1 = int_5 + int_5; v_termpty_cursor_copy(unsigned_int_6,float_4); double_3 = double_1 * double_1; int_4 = int_1 + int_4; double_1 = double_4; v_termpty_clear_screen(int_6,char_1); int_3 = int_5 + int_3; float_1 = float_2; long_2 = long_1 + long_1; double_1 = double_3 * double_1; long_2 = v__handle_esc_terminology(float_2,float_6,unsigned_int_7); unsigned_int_9 = unsigned_int_6 * unsigned_int_8; int_7 = int_4; float_5 = float_5 * float_7; v__safechar(float_5); float_9 = float_8 + float_7; double_4 = double_3 + double_1; int_8 = int_1 * int_2; long_1 = long_3 + long_2; if(1) { char_1 = char_2; } if(1) { } double_5 = double_4 + double_5; v_termpty_text_scroll_test(long_2,long_3,-1 ); double_2 = double_3 * double_1; float_7 = float_5 + float_6; if(1) { } v_termpty_cell_codepoint_att_fill(unsigned_int_7,short_1,short_2,long_3,int_8); double_6 = double_1 * double_5; float_3 = float_1 * float_5; if(1) { } long_4 = long_3; short_2 = short_3 + short_3; if(1) { } int_1 = int_8 + int_1; int_6 = int_6 * int_6; if(1) { } v_termpty_text_scroll_rev_test(long_4,long_2); short_3 = short_2 * short_2; float_7 = float_7; if(1) { } if(1) { unsigned int unsigned_int_10 = 1; char char_3 = 1; unsigned_int_10 = unsigned_int_2; short_4 = short_1 * short_3; short_2 = short_4 + short_4; char_3 = char_2 * char_2; int_1 = int_4 + int_2; if(1) { short_4 = short_3 + short_4; } double_7 = double_5 + double_6; char_1 = char_3 * char_3; if(1) { int_6 = int_8 * int_4; float_4 = v__handle_esc_csi(long_1,double_5,float_10); float_7 = float_7 + float_4; int_3 = int_1 * int_8; } } if(1) { } double_1 = double_6; double_8 = double_7 * double_8; v_termpty_reset_state(short_4); long_1 = long_1 + long_3; unsigned_int_4 = unsigned_int_1; short_1 = short_1 * short_1; return float_11; v__handle_esc_xterm(short_5,short_3,long_1); } void v_termpty_cell_fill( float parameter_1,float parameter_2,short parameter_3,int parameter_4) { double double_1 = 1; double double_2 = 1; double_1 = double_1 + double_2; if(1) { for(int looper_1=0; looper_1<1;looper_1++) { char char_1 = 1; char char_2 = 1; int int_1 = 1; int int_2 = 1; char_2 = char_1 * char_1; int_1 = int_1 + int_2; } } if(1) { for(int looper_2=0; looper_2<1;looper_2++) { float float_1 = 1; char char_3 = 1; char char_4 = 1; float_1 = float_1; char_4 = char_3 * char_3; } } } void v_termpty_cells_fill( long parameter_1,float parameter_2,int parameter_3,int parameter_4) { double double_1 = 1; double double_2 = 1; float float_1 = 1; float float_2 = 1; short short_1 = 1; int int_1 = 1; unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; char char_1 = 1; char char_2 = 1; int int_2 = 1; int int_3 = 1; double_1 = double_2; v_termpty_cell_fill(float_1,float_2,short_1,int_1); unsigned_int_1 = unsigned_int_2; char_2 = char_1 + char_1; int_1 = int_2 + int_3; char_1 = char_1 * char_1; } void v_termpty_cells_clear( int parameter_1,long parameter_2,int parameter_3) { int int_1 = 1; int int_2 = 1; long long_1 = 1; float float_1 = 1; int int_3 = 1; int_1 = int_1 + int_2; v_termpty_cells_fill(long_1,float_1,int_1,int_3); } float v__tooltip_del(short parameter_2) { int int_1 = 1; double double_1 = 1; double double_2 = 1; double double_3 = 1; double double_4 = 1; float float_1 = 1; int_1 = int_1 * int_1; double_2 = double_1 + double_2; double_1 = double_3 * double_4; return float_1; } short v__tooltip_content(int parameter_2,int parameter_3) { char char_1 = 1; short short_1 = 1; int int_1 = 1; float float_1 = 1; int int_2 = 1; double double_1 = 1; double double_2 = 1; long long_1 = 1; long long_2 = 1; int int_3 = 1; char_1 = char_1 + char_1; short_1 = v_media_add(int_1,float_1,int_2,int_1,int_2,-1 ); double_2 = double_1 + double_1; long_2 = long_1 + long_2; int_3 = int_2 + int_1; return short_1; } void v_MD5Final( int parameter_1,double parameter_2) { double double_1 = 1; double double_2 = 1; long long_1 = 1; long long_2 = 1; long long_3 = 1; unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; unsigned int unsigned_int_3 = 1; int int_1 = 1; short short_1 = 1; int int_2 = 1; int int_3 = 1; char char_2 = 1; float float_1 = 1; float float_2 = 1; double double_5 = 1; long long_4 = 1; double_1 = double_1 + double_2; long_3 = long_1 + long_2; unsigned_int_1 = unsigned_int_2; unsigned_int_3 = unsigned_int_1; int_1 = int_1; short_1 = short_1 * short_1; if(1) { double double_3 = 1; char char_1 = 1; double_2 = double_3; int_3 = int_2 * int_1; char_2 = char_1 * char_1; float_2 = float_1 + float_2; } if(1) { double double_4 = 1; double_4 = double_1; } int_1 = int_2; v_MD5Transform(double_5,char_2); int_2 = int_1 + int_3; float_1 = float_1 + float_2; int_3 = int_2; v_byteReverse(long_1,unsigned_int_2); long_1 = long_1 + long_2; long_4 = long_3 + long_3; long_4 = long_3 * long_4; } void v_MD5Transform( double parameter_1,char parameter_2) { int int_1 = 1; int int_2 = 1; float float_1 = 1; double double_1 = 1; double double_2 = 1; double double_3 = 1; float float_2 = 1; char char_1 = 1; float float_3 = 1; int int_3 = 1; int int_4 = 1; double double_4 = 1; short short_1 = 1; short short_2 = 1; unsigned int unsigned_int_1 = 1; char char_2 = 1; unsigned int unsigned_int_2 = 1; long long_1 = 1; long long_2 = 1; short short_3 = 1; double double_5 = 1; int int_5 = 1; int int_6 = 1; unsigned int unsigned_int_3 = 1; short short_4 = 1; short short_5 = 1; unsigned int unsigned_int_4 = 1; unsigned int unsigned_int_5 = 1; unsigned int unsigned_int_6 = 1; unsigned int unsigned_int_7 = 1; int int_7 = 1; int int_8 = 1; double double_6 = 1; double double_7 = 1; float float_4 = 1; long long_3 = 1; long long_4 = 1; unsigned int unsigned_int_8 = 1; double double_8 = 1; double double_9 = 1; double double_10 = 1; double double_11 = 1; float float_5 = 1; short short_6 = 1; float float_6 = 1; float float_7 = 1; int_1 = int_1 + int_2; float_1 = float_1 + float_1; double_3 = double_1 * double_2; int_1 = int_2; float_2 = float_1 * float_1; char_1 = char_1 + char_1; float_2 = float_3; int_4 = int_2 * int_3; double_3 = double_4 + double_4; int_2 = int_3; short_2 = short_1 * short_1; unsigned_int_1 = unsigned_int_1 * unsigned_int_1; char_2 = char_1 + char_1; unsigned_int_2 = unsigned_int_2 + unsigned_int_2; double_3 = double_3 * double_1; short_2 = short_1; unsigned_int_2 = unsigned_int_1; long_2 = long_1 + long_1; char_1 = char_2; short_3 = short_2 + short_3; unsigned_int_2 = unsigned_int_2 + unsigned_int_2; double_2 = double_2 + double_5; int_6 = int_4 + int_5; unsigned_int_3 = unsigned_int_1 * unsigned_int_3; short_4 = short_3 * short_1; unsigned_int_1 = unsigned_int_3 * unsigned_int_3; double_5 = double_1 + double_5; long_1 = long_1 * long_1; long_2 = long_2 * long_2; short_5 = short_5 + short_1; unsigned_int_2 = unsigned_int_3 * unsigned_int_3; unsigned_int_5 = unsigned_int_4 * unsigned_int_2; unsigned_int_7 = unsigned_int_1 * unsigned_int_6; int_5 = int_4 * int_5; char_1 = char_1; unsigned_int_1 = unsigned_int_2 + unsigned_int_2; int_3 = int_7 + int_8; unsigned_int_3 = unsigned_int_3 * unsigned_int_2; double_3 = double_3 * double_5; double_5 = double_4 + double_4; double_2 = double_6; double_5 = double_1 * double_6; double_7 = double_5; double_3 = double_6; float_4 = float_3 + float_3; long_3 = long_4; float_1 = float_2 + float_4; int_7 = int_3 + int_8; unsigned_int_1 = unsigned_int_8 + unsigned_int_2; double_3 = double_8 * double_6; long_1 = long_4 * long_4; double_9 = double_7 + double_4; double_5 = double_9 * double_8; double_4 = double_9; int_5 = int_4 * int_8; double_1 = double_10 * double_5; unsigned_int_6 = unsigned_int_3 + unsigned_int_4; double_4 = double_3 + double_5; double_11 = double_6; float_5 = float_4; long_1 = long_4 + long_3; unsigned_int_6 = unsigned_int_5 + unsigned_int_6; unsigned_int_7 = unsigned_int_7 + unsigned_int_3; float_4 = float_5 + float_2; short_6 = short_2; double_6 = double_4 * double_10; float_3 = float_5 * float_2; double_8 = double_2; int_8 = int_5 + int_5; unsigned_int_6 = unsigned_int_1; float_3 = float_2; float_6 = float_2 + float_5; float_4 = float_6 + float_7; } void v_byteReverse( long parameter_1,unsigned int parameter_2) { long long_1 = 1; long long_2 = 1; long long_3 = 1; long_3 = long_1 * long_2; } void v_MD5Update( double parameter_1,unsigned int parameter_2,char parameter_3) { int int_1 = 1; int int_2 = 1; double double_1 = 1; double double_2 = 1; unsigned int unsigned_int_1 = 1; float float_1 = 1; float float_2 = 1; long long_1 = 1; unsigned int unsigned_int_2 = 1; unsigned int unsigned_int_3 = 1; double double_3 = 1; double double_4 = 1; short short_1 = 1; short short_2 = 1; long long_2 = 1; long long_3 = 1; long long_4 = 1; float float_3 = 1; float float_4 = 1; char char_1 = 1; unsigned int unsigned_int_4 = 1; unsigned int unsigned_int_5 = 1; unsigned int unsigned_int_6 = 1; int int_3 = 1; char char_2 = 1; short short_3 = 1; int_2 = int_1 + int_1; double_1 = double_1; double_2 = double_2 + double_2; unsigned_int_1 = unsigned_int_1; float_2 = float_1 * float_2; v_byteReverse(long_1,unsigned_int_2); unsigned_int_3 = unsigned_int_2 + unsigned_int_3; double_4 = double_2 * double_3; short_2 = short_1 * short_1; long_4 = long_2 * long_3; float_1 = float_3 + float_4; unsigned_int_1 = unsigned_int_1; v_MD5Transform(double_3,char_1); unsigned_int_3 = unsigned_int_4 * unsigned_int_5; unsigned_int_6 = unsigned_int_5 * unsigned_int_1; int_3 = int_2; int_3 = int_2 + int_3; char_1 = char_2 + char_1; double_3 = double_3; unsigned_int_4 = unsigned_int_4 + unsigned_int_4; char_1 = char_1 * char_2; double_1 = double_2 * double_3; short_1 = short_1 * short_3; } void v_MD5Init( int parameter_1) { unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; unsigned int unsigned_int_3 = 1; unsigned int unsigned_int_4 = 1; float float_1 = 1; float float_2 = 1; float float_3 = 1; double double_1 = 1; double double_2 = 1; unsigned_int_2 = unsigned_int_1 * unsigned_int_1; unsigned_int_4 = unsigned_int_2 * unsigned_int_3; unsigned_int_4 = unsigned_int_1; float_3 = float_1 + float_2; unsigned_int_4 = unsigned_int_1 * unsigned_int_4; double_2 = double_1 + double_1; } void v_gravatar_tooltip( unsigned int parameter_1,long parameter_2,char parameter_3) { double double_1 = 1; unsigned int unsigned_int_1 = 1; unsigned int unsigned_int_2 = 1; long long_1 = 1; short short_1 = 1; int int_1 = 1; double double_2 = 1; double double_3 = 1; unsigned int unsigned_int_3 = 1; char char_1 = 1; unsigned int unsigned_int_4 = 1; float float_1 = 1; float float_2 = 1; char char_2 = 1; double double_4 = 1; int int_2 = 1; int int_3 = 1; float float_3 = 1; short short_2 = 1; unsigned int unsigned_int_5 = 1; char char_3 = 1; int int_4 = 1; float float_4 = 1; double double_5 = 1; char char_4 = 1; long long_2 = 1; char char_5 = 1; int int_5 = 1; double_1 = double_1 * double_1; unsigned_int_2 = unsigned_int_1 + unsigned_int_2; long_1 = long_1; short_1 = v__tooltip_content(int_1,int_1); double_3 = double_2 * double_3; unsigned_int_1 = unsigned_int_3 + unsigned_int_3; char_1 = char_1 * char_1; unsigned_int_4 = unsigned_int_3 + unsigned_int_4; if(1) { } float_2 = float_1 + float_1; if(1) { } char_1 = char_2; double_4 = double_3; int_3 = int_2 * int_3; float_3 = v__tooltip_del(short_2); unsigned_int_1 = unsigned_int_4 + unsigned_int_5; char_3 = char_3 * char_1; for(int looper_1=0; looper_1<1;looper_1++) { double_1 = double_3 * double_2; char_3 = char_1 + char_3; } int_4 = int_2; float_4 = float_1 * float_4; v_MD5Update(double_5,unsigned_int_5,char_4); v_MD5Final(int_2,double_3); long_2 = long_1 * long_1; char_4 = char_2 + char_5; v_MD5Init(int_5); } unsigned int v__cb_link_drag_done(double parameter_2) { long long_1 = 1; long long_2 = 1; double double_1 = 1; double double_2 = 1; char char_1 = 1; char char_2 = 1; char char_3 = 1; unsigned int unsigned_int_1 = 1; long_1 = long_1 + long_1; long_2 = long_2 + long_2; double_1 = double_2; char_3 = char_1 + char_2; if(1) { float float_1 = 1; float float_2 = 1; float_2 = float_1 + float_2; } char_2 = char_3 * char_1; return unsigned_int_1; } unsigned int v__cb_link_drag_accept(int parameter_2,short parameter_3) { int int_1 = 1; double double_1 = 1; double double_2 = 1; int int_2 = 1; int int_3 = 1; unsigned int unsigned_int_1 = 1; int_1 = int_1 * int_1; double_1 = double_1 + double_2; int_3 = int_2 * int_2; return unsigned_int_1; } float v__cb_link_drag_move(double parameter_2,int parameter_3,double parameter_4,float parameter_5)
1,527
/// path='docs/doc[@name="T:URIUtility.ParseMode"]/*'/> internal enum ParseMode { /// <include file='../../docs.xml' /// path='docs/doc[@name="F:URIUtility.ParseMode.IRIStrict"]/*'/> IRIStrict, /// <include file='../../docs.xml' /// path='docs/doc[@name="F:URIUtility.ParseMode.URIStrict"]/*'/> URIStrict, /// <include file='../../docs.xml' /// path='docs/doc[@name="F:URIUtility.ParseMode.IRILenient"]/*'/> IRILenient, /// <include file='../../docs.xml' /// path='docs/doc[@name="F:URIUtility.ParseMode.URILenient"]/*'/> URILenient, /// <include file='../../docs.xml' /// path='docs/doc[@name="F:URIUtility.ParseMode.IRISurrogateLenient"]/*'/> IRISurrogateLenient } private const string HexChars = "0123456789ABCDEF"; private static void AppendAuthority( StringBuilder builder, string refValue, int[] segments) { if (segments[2] >= 0) { builder.Append("//"); builder.Append( refValue.Substring( segments[2], segments[3] - segments[2])); } } private static void AppendFragment( StringBuilder builder, string refValue, int[] segments) { if (segments[8] >= 0) { builder.Append('#'); builder.Append( refValue.Substring( segments[8], segments[9] - segments[8])); } } private static void AppendNormalizedPath( StringBuilder builder, string refValue, int[] segments) { builder.Append( NormalizePath( refValue.Substring( segments[4], segments[5] - segments[4]))); } private static void AppendPath( StringBuilder builder, string refValue, int[] segments) { builder.Append( refValue.Substring( segments[4], segments[5] - segments[4])); } private static void AppendQuery( StringBuilder builder, string refValue, int[] segments) { if (segments[6] >= 0) { builder.Append('?'); builder.Append( refValue.Substring( segments[6], segments[7] - segments[6])); } } private static void AppendScheme( StringBuilder builder, string refValue, int[] segments) { if (segments[0] >= 0) { builder.Append( refValue.Substring( segments[0], segments[1] - segments[0])); builder.Append(':'); } } /// <include file='../../docs.xml' /// path='docs/doc[@name="M:URIUtility.escapeURI(System.String,System.Int32)"]/*'/> public static string EscapeURI(string s, int mode) { if (s == null) { return null; } int[] components = null; if (mode == 1) { components = ( s == null)? null : SplitIRI( s, 0, s.Length, ParseMode.IRIStrict); if (components == null) { return null; } } else { components = (s == null)? null : SplitIRI( s, 0, s.Length, ParseMode.IRISurrogateLenient); } int index = 0; int valueSLength = s.Length; StringBuilder builder = new StringBuilder(); while (index < valueSLength) { int c = s[index]; if ((c & 0xfc00) == 0xd800 && index + 1 < valueSLength && (s[index + 1] & 0xfc00) == 0xdc00) { // Get the Unicode code point for the surrogate pair c = 0x10000 + ((c - 0xd800) << 10) + (s[index + 1] - 0xdc00); ++index; } else if ((c & 0xf800) == 0xd800) { c = 0xfffd; } if (mode == 0 || mode == 3) { if (c == '%' && mode == 3) { // Check for illegal percent encoding if (index + 2 >= valueSLength ||!IsHexChar(s[index + 1]) || !IsHexChar(s[index + 2])) { PercentEncodeUtf8(builder, c); } else { if (c <= 0xffff) { builder.Append((char)c); } else if (c <= 0x10ffff) { builder.Append((char)((((c - 0x10000) >> 10) & 0x3ff) + 0xd800)); builder.Append((char)(((c - 0x10000) & 0x3ff) + 0xdc00)); } } ++index; continue; } if (c >= 0x7f || c <= 0x20 || ((c & 0x7f) == c && "{}|^\\`<>\"".IndexOf((char)c) >= 0)) { PercentEncodeUtf8(builder, c); } else if (c == '[' || c == ']') { if (components!= null && index >= components[2] && index < components[3]) { // within the authority component, so don't percent-encode if (c <= 0xffff) { builder.Append((char)c); } else if (c <= 0x10ffff) { builder.Append((char)((((c - 0x10000) >> 10) & 0x3ff) + 0xd800)); builder.Append((char)(((c - 0x10000) & 0x3ff) + 0xdc00)); } } else { // percent encode PercentEncodeUtf8(builder, c); } } else { if (c <= 0xffff) { builder.Append((char)c); } else if (c <= 0x10ffff) { builder.Append((char)((((c - 0x10000) >> 10) & 0x3ff) + 0xd800)); builder.Append((char)(((c - 0x10000) & 0x3ff) + 0xdc00)); } } } else if (mode == 1 || mode == 2) { if (c >= 0x80) { PercentEncodeUtf8(builder, c); } else if (c == '[' || c == ']') { if (components!= null && index >= components[2] && index < components[3]) { // within the authority component, so don't percent-encode if (c <= 0xffff) { builder.Append((char)c); } else if (c <= 0x10ffff) { builder.Append((char)((((c - 0x10000) >> 10) & 0x3ff) + 0xd800)); builder.Append((char)(((c - 0x10000) & 0x3ff) + 0xdc00)); } } else { // percent encode PercentEncodeUtf8(builder, c); } } else { if (c <= 0xffff) { builder.Append((char)c); } else if (c <= 0x10ffff) { builder.Append((char)((((c - 0x10000) >> 10) & 0x3ff) + 0xd800)); builder.Append((char)(((c - 0x10000) & 0x3ff) + 0xdc00)); } } } ++index; } return builder.ToString(); } /// <include file='../../docs.xml' /// path='docs/doc[@name="M:URIUtility.hasScheme(System.String)"]/*'/> public static bool HasScheme(string refValue) { int[] segments = (refValue == null)? null : SplitIRI( refValue, 0, refValue.Length, ParseMode.IRIStrict); return segments!= null && segments[0] >= 0; } /// <include file='../../docs.xml' /// path='docs/doc[@name="M:URIUtility.hasSchemeForURI(System.String)"]/*'/> public static bool HasSchemeForURI(string refValue) { int[] segments = (refValue == null)? null : SplitIRI( refValue, 0, refValue.Length, ParseMode.URIStrict); return segments!= null && segments[0] >= 0; } private static bool IsHexChar(char c) { return (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F') || (c >= '0' && c <= '9'); } private static bool IsIfragmentChar(int c) { // '%' omitted return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || ((c & 0x7F) == c && "/?-._~:@!$&'()*+,;=".IndexOf((char)c) >= 0) || (c >= 0xa0 && c <= 0xd7ff) || (c >= 0xf900 && c <= 0xfdcf) || (c >= 0xfdf0 && c <= 0xffef) || (c >= 0x10000 && c <= 0xefffd && (c & 0xfffe)!= 0xfffe); } private static bool IsIpchar(int c) { // '%' omitted return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || ((c & 0x7F) == c && "/-._~:@!$&'()*+,;=".IndexOf((char)c) >= 0) || (c >= 0xa0 && c <= 0xd7ff) || (c >= 0xf900 && c <= 0xfdcf) || (c >= 0xfdf0 && c <= 0xffef) || (c >= 0x10000 && c <= 0xefffd && (c & 0xfffe)!= 0xfffe); } private static bool IsIqueryChar(int c) { // '%' omitted return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || ((c & 0x7F) == c && "/?-._~:@!$&'()*+,;=".IndexOf((char)c) >= 0) || (c >= 0xa0 && c <= 0xd7ff) || (c >= 0xe000 && c <= 0xfdcf) || (c >= 0xfdf0 && c <= 0xffef) || (c >= 0x10000 && c <= 0x10fffd && (c & 0xfffe)!= 0xfffe); } private static bool IsIRegNameChar(int c) { // '%' omitted return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || ((c & 0x7F) == c && "-._~!$&'()*+,;=".IndexOf((char)c) >= 0) || (c >= 0xa0 && c <= 0xd7ff) || (c >= 0xf900 && c <= 0xfdcf) || (c >= 0xfdf0 && c <= 0xffef) || (c >= 0x10000 && c <= 0xefffd && (c & 0xfffe)!= 0xfffe); } private static bool IsIUserInfoChar(int c) { // '%' omitted return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || ((c & 0x7F) == c && "-._~:!$&'()*+,;=".IndexOf((char)c) >= 0) || (c >= 0xa0 && c <= 0xd7ff) || (c >= 0xf900 && c <= 0xfdcf) || (c >= 0xfdf0 && c <= 0xffef) || (c >= 0x10000 && c <= 0xefffd && (c & 0xfffe)!= 0xfffe); } /// <include file='../../docs.xml' /// path='docs/doc[@name="M:URIUtility.isValidCurieReference(System.String,System.Int32,System.Int32)"]/*'/> public static bool IsValidCurieReference(string s, int offset, int length) { if (s == null) { return false; } if (offset < 0) { throw new ArgumentException("offset (" + offset + ") is less than " + "0 "); } if (offset > s.Length) { throw new ArgumentException("offset (" + offset + ") is more than " + s.Length); } if (length < 0) { throw new ArgumentException( "length (" + length + ") is less than " + "0 "); } if (length > s.Length) { throw new ArgumentException( "length (" + length + ") is more than " + s.Length); } if (s.Length - offset < length) { throw new ArgumentException( "s's length minus " + offset + " (" + (s.Length - offset) + ") is less than " + length); } if (length == 0) { return true; } int index = offset; int valueSLength = offset + length; int state = 0; if (index + 2 <= valueSLength && s[index] == '/' && s[index + 1] == '/') { // has an authority, which is not allowed return false; } state = 0; // IRI Path while (index < valueSLength) { // Get the next Unicode character int c = s[index]; if ((c & 0xfc00) == 0xd800 && index + 1 < valueSLength && (s[index + 1] & 0xfc00) == 0xdc00) { // Get the Unicode code point for the surrogate pair c = 0x10000 + ((c - 0xd800) << 10) + (s[index + 1] - 0xdc00); ++index; } else if ((c & 0xf800) == 0xd800) { // error return false; } if (c == '%') { // Percent encoded character if (index + 2 < valueSLength && IsHexChar(s[index + 1]) && IsHexChar(s[index + 2])) { index += 3; continue; } return false; } if (state == 0) { // Path if (c == '?') { state = 1; // move to query state } else if (c == '#') { state = 2; // move to fragment state } else if (!IsIpchar(c)) { return false; } ++index; } else if (state == 1) { // Query if (c == '#') { state = 2; // move to fragment state } else if (!IsIqueryChar(c)) { return false; } ++index; } else if (state == 2) { // Fragment if (!IsIfragmentChar(c)) { return false; } ++index; } } return true; } public static bool IsValidIRI(string s) { return ((s == null)? null : SplitIRI( s, 0, s.Length, ParseMode.IRIStrict))!= null; } private const string ValueDotSlash = "." + "/"; private const string ValueSlashDot = "/" + "."; private static string NormalizePath(string path) { int len = path.Length; if (len == 0 || path.Equals("..") || path.Equals(".")) { return String.Empty; } if (path.IndexOf(ValueSlashDot, StringComparison.Ordinal) < 0 && path.IndexOf( ValueDotSlash, StringComparison.Ordinal) < 0) { return path; } StringBuilder builder = new StringBuilder(); int index = 0; while (index < len) { char c = path[index]; if ((index + 3 <= len && c == '/' && path[index + 1] == '.' && path[index + 2] == '/') || (index + 2 == len && c == '.' && path[index + 1] == '.')) { // begins with "/./" or is ".."; // move index by 2 index += 2; continue; } if (index + 3 <= len && c == '.' && path[index + 1] == '.' && path[index + 2] == '/') { // begins with "../"; // move index by 3 index += 3; continue; } if ((index + 2 <= len && c == '.' && path[index + 1] == '/') || (index + 1 == len && c == '.')) { // begins with "./" or is "."; // move index by 1 ++index; continue; } if (index + 2 == len && c == '/' && path[index + 1] == '.') { // is "/."; append '/' and break builder.Append('/'); break; } if (index + 3 == len && c == '/' && path[index + 1] == '.' && path[index + 2] == '.') { // is "/.."; remove last segment, // append "/" and return int index2 = builder.Length - 1; string builderString = builder.ToString(); while (index2 >= 0) { if (builderString[index2] == '/') { break; } --index2; } if (index2 < 0) { index2 = 0; } builder.Length = index2; builder.Append('/'); break; } if (index + 4 <= len && c == '/' && path[index + 1] == '.' && path[index + 2] == '.' && path[index + 3] == '/') { // begins with "/../"; remove last segment int index2 = builder.Length - 1; string builderString = builder.ToString(); while (index2 >= 0) { if (builderString[index2] == '/') { break; } --index2; } if (index2 < 0) { index2 = 0; } builder.Length = index2; index += 3; continue; } builder.Append(c); ++index; while (index < len) { // Move the rest of the // path segment until the next '/' c = path[index]; if (c == '/') { break; } builder.Append(c); ++index; } } return builder.ToString(); } private static int ParseDecOctet( string s, int index, int endOffset, int c, int delim) { if (c >= '1' && c <= '9' && index + 2 < endOffset && s[index + 1] >= '0' && s[index + 1] <= '9' && s[index + 2] == delim) { return ((c - '0') * 10) + (s[index + 1] - '0'); } if (c == '2' && index + 3 < endOffset && (s[index + 1] == '5') && (s[index + 2] >= '0' && s[index + 2] <= '5') && s[index + 3] == delim) { return 250 + (s[index + 2] - '0'); } if (c == '2' && index + 3 < endOffset && s[index + 1] >= '0' && s[index + 1] <= '4' && s[index + 2] >= '0' && s[index + 2] <= '9' && s[index + 3] == delim) { return 200 + ((s[index + 1] - '0') * 10) + (s[index + 2] - '0'); } if (c == '1' && index + 3 < endOffset && s[index + 1] >= '0' && s[index + 1] <= '9' && s[index + 2] >= '0' && s[index + 2] <= '9' && s[index + 3] == delim) { return 100 + ((s[index + 1] - '0') * 10) + (s[index + 2] - '0'); } return (c >= '0' && c <= '9' && index + 1 < endOffset && s[index + 1] == delim)? (c - '0') : (-1); } private static int ParseIPLiteral(string s, int offset, int endOffset) { int index = offset; if (offset == endOffset) { return -1; } // Assumes that the character before offset // is a '[' if (s[index] == 'v') { // IPvFuture ++index; bool hex = false; while (index < endOffset) { char c = s[index]; if (IsHexChar(c)) { hex = true; } else { break; } ++index; } if (!hex) { return -1; } if (index >= endOffset || s[index]!= '.') { return -1; } ++index; hex = false; while (index < endOffset) { char c = s[index]; if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || ((c & 0x7F) == c && ":-._~!$&'()*+,;=".IndexOf(c) >= 0)) { hex = true; } else { break; } ++index; } if (!hex) { return -1; } if (index >= endOffset || s[index]!= ']') { return -1; } ++index; return index; } if (s[index] == ':' || IsHexChar(s[index])) { // IPv6 Address int phase1 = 0; int phase2 = 0; bool phased = false; bool expectHex = false; bool expectColon = false; while (index < endOffset) { char c = s[index]; if (c == ':' &&!expectHex) { if ((phase1 + (phased? 1 : 0) + phase2) >= 8) { return -1; } ++index; if (index < endOffset && s[index] == ':') { if (phased) { return -1; } phased = true; ++index; } expectHex = true; expectColon = false; continue; } if ((c >= '0' && c <= '9') &&!expectColon && (phased || (phase1 + (phased? 1 : 0) + phase2) == 6)) { // Check for IPv4 address int decOctet = ParseDecOctet(s, index, endOffset, c, '.'); if (decOctet >= 0) { if ((phase1 + (phased? 1 : 0) + phase2) > 6) { // IPv4 address illegal at this point return -1; } else { // Parse the rest of the IPv4 address phase2 += 2; if (decOctet >= 100) { index += 4; } else if (decOctet >= 10) { index += 3; } else { index += 2; } char tmpc = (index < endOffset)? s[index] : '\0'; decOctet = ParseDecOctet( s, index, endOffset, tmpc, '.'); if (decOctet >= 100) { index += 4; } else if (decOctet >= 10) { index += 3; } else if (decOctet >= 0) { index += 2; } else { return -1; } tmpc = (index < endOffset)? s[index] : '\0'; decOctet = ParseDecOctet(s, index, endOffset, tmpc, '.'); if (decOctet >= 100) { index += 4; } else if (decOctet >= 10) { index += 3; } else if (decOctet >= 0) { index += 2; } else { return -1; } tmpc = (index < endOffset)? s[index] : '\0'; decOctet = ParseDecOctet(s, index, endOffset, tmpc, ']'); if (decOctet < 0) { tmpc = (index < endOffset)? s[index] : '\0'; decOctet = ParseDecOctet(s, index, endOffset, tmpc, '%'); } if (decOctet >= 100) { index += 3; } else if (decOctet >= 10) { index += 2; } else if (decOctet >= 0) { ++index; } else { return -1; } break; } } } if (IsHexChar(c) &&!expectColon) { if (phased) { ++phase2; } else { ++phase1; } ++index; for (int i = 0; i < 3; ++i) { if (index < endOffset && IsHexChar(s[index])) { ++index; } else { break; } } expectHex = false; expectColon = true; } else { break; } } if ((phase1 + phase2)!= 8 &&!phased) { return -1; } if (phase1 + 1 + phase2 > 8 && phased) { return -1; } if (index >= endOffset) { return -1; } if (s[index]!= ']' && s[index]!= '%') { return -1; } if (s[index] == '%') { if (index + 2 < endOffset && s[index + 1] == '2' && s[index + 2] == '5') { // Zone identifier in an IPv6 address // (see RFC6874) index += 3; bool haveChar = false; while (index < endOffset) { char c = s[index]; if (c == ']') { return haveChar? index + 1 : -1; } if (c == '%') { if (index + 2 < endOffset && IsHexChar(s[index + 1]) && IsHexChar(s[index + 2])) { index += 3; haveChar = true; continue; } return -1; } if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '.' || c == '_' || c == '-' || c == '~') { // unreserved character under RFC3986 ++index; haveChar = true; continue; } return -1; } return -1; } return -1; } ++index; return index; } return -1; } private static string PathParent( string refValue, int startIndex, int endIndex) { if (startIndex > endIndex) { return String.Empty; } --endIndex; while (endIndex >= startIndex) { if (refValue[endIndex] == '/') { return refValue.Substring(startIndex, (endIndex + 1) - startIndex); } --endIndex; } return String.Empty; } private static void PercentEncode(StringBuilder buffer, int b) { buffer.Append('%'); buffer.Append(HexChars[(b >> 4) & 0x0f]); buffer.Append(HexChars[b & 0x0f]); } private static void PercentEncodeUtf8(StringBuilder buffer, int cp) { if (cp <= 0x7f) { buffer.Append('%'); buffer.Append(HexChars[(cp >> 4) & 0x0f]); buffer.Append(HexChars[cp & 0x0f]); } else if (cp <= 0x7ff) { PercentEncode(buffer, 0xc0 | ((cp >> 6) & 0x1f)); PercentEncode(buffer, 0x80 | (cp & 0x3f)); } else if (cp <= 0xffff) { PercentEncode(buffer, 0xe0 | ((cp >> 12) & 0x0f)); PercentEncode(buffer, 0x80 | ((cp >> 6) & 0x3f)); PercentEncode(buffer, 0x80 | (cp & 0x3f)); } else { PercentEncode(buffer, 0xf0 | ((cp >> 18) & 0x07)); PercentEncode(buffer, 0x80 | ((cp >> 12) & 0x3f)); PercentEncode(buffer, 0x80 | ((cp >> 6) & 0x3f)); PercentEncode(buffer, 0x80 | (cp & 0x3f)); } } /// <include file='../../docs.xml' /// path='docs/doc[@name="M:URIUtility.relativeResolve(System.String,System.String)"]/*'/> public static string RelativeResolve(string refValue, string baseURI) { return RelativeResolve(refValue, baseURI, ParseMode.IRIStrict); } /// <include file='../../docs.xml' /// path='docs/doc[@name="M:URIUtility.relativeResolve(System.String,System.String,URIUtility.ParseMode)"]/*'/> public static string RelativeResolve( string refValue, string baseURI, ParseMode parseMode) { int[] segments = (refValue == null)? null : SplitIRI( refValue, 0, refValue.Length, parseMode); if (segments == null) { return null; } int[] segmentsBase = ( baseURI == null)? null : SplitIRI( baseURI, 0, baseURI.Length, parseMode); if (segmentsBase == null) { return refValue; } StringBuilder builder = new StringBuilder(); if (segments[0] >= 0) { // scheme present AppendScheme(builder, refValue, segments); AppendAuthority(builder, refValue, segments); AppendNormalizedPath(builder, refValue, segments); AppendQuery(builder, refValue, segments); AppendFragment(builder, refValue, segments); } else if (segments[2] >= 0) { // authority present AppendScheme(builder, baseURI, segmentsBase); AppendAuthority(builder, refValue, segments); AppendNormalizedPath(builder, refValue, segments); AppendQuery(builder, refValue, segments); AppendFragment(builder, refValue, segments); } else if (segments[4] == segments[5]) { AppendScheme(builder, baseURI, segmentsBase); AppendAuthority(builder, baseURI, segmentsBase); AppendPath(builder, baseURI, segmentsBase); if (segments[6] >= 0) { AppendQuery(builder, refValue, segments); } else { AppendQuery(builder, baseURI, segmentsBase); } AppendFragment(builder, refValue, segments); } else { AppendScheme(builder, baseURI, segmentsBase); AppendAuthority(builder, baseURI, segmentsBase); if (segments[4] < segments[5] && refValue[segments[4]] == '/') { AppendNormalizedPath(builder, refValue, segments); } else { StringBuilder merged = new StringBuilder(); if (segmentsBase[2] >= 0 && segmentsBase[4] == segmentsBase[5]) { merged.Append('/'); AppendPath(merged, refValue, segments); builder.Append(NormalizePath(merged.ToString())); } else { merged.Append( PathParent( baseURI, segmentsBase[4], segmentsBase[5])); AppendPath(merged, refValue, segments); builder.Append(NormalizePath(merged.ToString())); } } AppendQuery(builder, refValue, segments); AppendFragment(builder, refValue, segments); } return builder.ToString(); } /// <include file='../../docs.xml' /// path='docs/doc[@name="M:URIUtility.splitIRI(System.String)"]/*'/> public static int[] SplitIRI(string s) { return (s == null)? null : SplitIRI(s, 0, s.Length, ParseMode.IRIStrict); } /// <include file='../../docs.xml' /// path='docs/doc[@name="M:URIUtility.splitIRI(System.String,System.Int32,System.Int32,URIUtility.ParseMode)"]/*'/> public static int[] SplitIRI( string s, int offset, int length, ParseMode parseMode) { if (s == null) { return null; } if (s == null) { throw new ArgumentNullException(nameof(s)); } if (offset < 0) { throw new ArgumentException("offset (" + offset + ") is less than 0"); } if (offset > s.Length) { throw new ArgumentException("offset (" + offset + ") is more than " + s.Length); } if (length < 0) { throw new ArgumentException("length (" + length + ") is less than 0"); } if (length > s.Length) { throw new ArgumentException("length (" + length + ") is more than " + s.Length); } if (s.Length - offset < length) { throw new ArgumentException("s's length minus " + offset + " (" + (s.Length - offset) + ") is less than " + length); } int[] retval = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }; if (length == 0) { retval[4] = 0; retval[5] = 0; return retval; } bool asciiOnly = parseMode == ParseMode.URILenient || parseMode == ParseMode.URIStrict; bool strict = parseMode == ParseMode.URIStrict || parseMode == ParseMode.IRIStrict; int index = offset; int valueSLength = offset + length; bool scheme = false; // scheme while (index < valueSLength) { int c = s[index]; if (index > offset && c == ':') { scheme = true; retval[0] = offset; retval[1] = index; ++index; break; } if (strict && index == offset &&!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))) { break; } if (strict && index > offset && !((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '+' || c == '-' || c == '.')) { break; } if (!strict && (c == '#' || c == ':' || c == '?' || c == '/')) { break; } ++index; } if (!scheme) { index = offset; } int state = 0; if (index + 2 <= valueSLength && s[index] == '/' && s[index + 1] == '/') { // authority // (index + 2, valueSLength) index += 2; int authorityStart = index; retval[2] = authorityStart; retval[3] = valueSLength; state = 0; // userinfo // Check for userinfo while (index < valueSLength) { int c = s[index]; if (asciiOnly && c >= 0x80) { return null; } if ((c & 0xfc00) == 0xd800 && index + 1 < valueSLength && (s[index + 1] & 0xfc00) == 0xdc00) { // Get the Unicode code point for the surrogate pair c = 0x10000 + ((c - 0xd800) << 10) + (s[index + 1] - 0xdc00); ++index; } else if ((c & 0xf800) == 0xd800) { if (parseMode == ParseMode.IRISurrogateLenient) { c = 0xfffd; } else { return null; } } if (c == '%' && (state == 0 || state == 1) && strict) { // Percent encoded character (except in port) if (index + 2 < valueSLength && IsHexChar(s[index + 1]) && IsHexChar(s[index + 2])) { index += 3; continue; } return null; } if (state == 0) { // User info if (c == '/' || c == '?' || c == '#') { // not user info state = 1; index = authorityStart; continue; } if (strict && c == '@') { // is user info ++index; state = 1; continue; } if (strict && IsIUserInfoChar(c)) { ++index; if (index == valueSLength) { // not user info state = 1; index = authorityStart; continue; } } else { // not user info state = 1; index = authorityStart; continue; } } else if (state == 1) { // host if (c == '/' || c == '?' || c == '#') { // end of authority retval[3] = index; break; } if (!strict) { ++index; } else if (c == '[') { ++index; index = ParseIPLiteral(s, index, valueSLength); if (index < 0) { return null; } continue; } else if (c == ':') { // port state = 2; ++index; } else if (IsIRegNameChar(c)) { // is valid host name char // (note: IPv4 addresses included // in ireg-name) ++index; } else { return null; } } else if (state == 2) { // Port if (c == '/' || c == '?' || c == '#') { // end of authority retval[3] = index; break; } if (c >= '0' && c <= '9') { ++index; } else { return null; } } } } bool colon = false; bool segment = false; bool fullyRelative = index == offset; retval[4] = index; // path offsets retval[5] = valueSLength; state = 0; // IRI Path while (index < valueSLength) { // Get the next Unicode character int c = s[index]; if (asciiOnly && c >= 0x80) { return null; } if ((c & 0xfc00) == 0xd800 && index + 1 < valueSLength && (s[index + 1] & 0xfc00) == 0xdc00) { // Get the Unicode code point for the surrogate pair c = 0x10000 + ((c - 0xd800) << 10) + (s[index + 1] - 0xdc00); ++index; } else if ((c & 0xf800) == 0xd800) { // error return null; } if (c == '%' && strict) { // Percent encoded character if (index + 2 < valueSLength && IsHexChar(s[index + 1]) && IsHexChar(s[index + 2])) { index += 3; continue; } return null; } if (state == 0) { // Path if (c == ':' && fullyRelative) { colon = true; } else if (c == '/' && fullyRelative &&!segment) { // noscheme path can't have colon before slash if (strict && colon) { return null; } segment = true; } if (c == '?') { retval[5] = index; retval[6] = index + 1; retval[7] = valueSLength; state = 1; // move to query state } else if (c == '#') { retval[5] = index; retval[8] = index + 1; retval[9] = valueSLength; state = 2; // move to fragment state } else if (strict &&!IsIpchar(c)) { return null; } ++index; } else if (state == 1) { // Query if (c == '#') { retval[7] = index; retval[8] = index + 1; retval[9] = valueSLength; state = 2; // move to fragment state } else if (strict &&!IsIqueryChar(c)) { return null; } ++index; } else if (state == 2) { // Fragment if (strict &&!IsIfragmentChar(c)) { return null; } ++index; } } if (strict && fullyRelative && colon &&!segment) { return null; // ex. "x@y:z" } return retval; } /// <include file='../../docs.xml' /// path='docs/doc[@name="M:URIUtility.splitIRI(System.String,URIUtility.ParseMode)"]/*'/> public static int[] SplitIRI(string s, ParseMode parseMode) { return (s == null)? null : SplitIRI(s, 0, s.Length, parseMode); } } #endregion } ======================= File: Neos.IdentityServer 3.0/Neos.IdentityServer.MultiFactor.WebAuthN.Common/Library/PeterO.Cbor.Interfaces.cs ======================= //******************************************************************************************************************************************************************************************// // // // Written by <NAME>. // // // // Any copyright is dedicated to the Public Domain. // // http://creativecommons.org/publicdomain/zero/1.0/ // // If you like this, you should donate to Peter O. at: http://peteroupc.github.io/ // // // //******************************************************************************************************************************************************************************************// using System; namespace Neos.IdentityServer.MultiFactor.WebAuthN.Library.Cbor { #region ICBORConverter /// <include file='../../docs.xml' /// path='docs/doc[@name="T:ICBORConverter`1"]/*'/> public interface ICBORConverter<T> { /// <include file='../../docs.xml' /// path='docs/doc[@name="M:ICBORConverter`1.ToCBORObject(`0)"]/*'/> CBORObject ToCBORObject(T obj); } #endregion #region ICBORNumber internal interface ICBORNumber { bool IsPositiveInfinity(Object obj); bool IsInfinity(Object obj); bool IsNegativeInfinity(Object obj); bool IsNaN(Object obj); bool IsNegative(Object obj); double AsDouble(Object obj); object Negate(Object obj); object Abs(Object obj); EDecimal AsExtendedDecimal(Object obj); EFloat AsExtendedFloat(Object obj); ERational AsExtendedRational(Object obj); float AsSingle(Object obj); EInteger AsEInteger(Object obj); long AsInt64(Object obj); bool CanFitInSingle(Object obj); bool CanFitInDouble(Object obj); bool CanFitInInt32(Object obj); bool CanFitInInt64(Object obj); bool CanTruncatedIntFitInInt64(Object obj); bool CanTruncatedIntFitInInt32(Object obj); int AsInt32(Object obj, int minValue, int maxValue); bool IsZero(Object obj); int Sign(Object obj); bool IsIntegral(Object obj); } #endregion #region ICBORTag /// <include file='../../docs.xml' /// path='docs/doc[@name="T:ICBORTag"]/*'/> public interface ICBORTag { /// <include file='../../docs.xml' /// path='docs/doc[@name="M:ICBORTag.GetTypeFilter"]/*'/> CBORTypeFilter GetTypeFilter(); /// <include file='../../docs.xml' /// path='docs/doc[@name="M:ICBORTag.ValidateObject(CBORObject)"]/*'/> CBORObject ValidateObject(CBORObject obj); } #endregion #region ICBORToFromConverter /// <include file='../../docs.xml' /// path='docs/doc[@name="T:ICBORObjectConverter`1"]/*'/> public interface ICBORToFromConverter<T> : ICBORConverter<T> { /// <include file='../../docs.xml' /// path='docs/doc[@name="M:ICBORObjectConverter`1.FromCBORObject(CBORObject)"]/*'/> T FromCBORObject(CBORObject cbor); } #endregion #region ICharacterInput /// <include file='../../docs.xml' /// path='docs/doc[@name="T:ICharacterInput"]/*'/> internal interface ICharacterInput { /// <include file='../../docs.xml' /// path='docs/doc[@name="M:ICharacterInput.ReadChar"]/*'/> int ReadChar(); /// <include file='../../docs.xml' /// path='docs/doc[@name="M:ICharacterInput.Read(System.Int32[],System.Int32,System.Int32)"]/*'/> int Read(int[] chars, int index, int length); } #endregion } ======================= File: Neos.IdentityServer 3.0/Neos.IdentityServer.MultiFactor.WebAuthN.Common/Library/CBOR/PeterO/Numbers/FastIntegerFixed.cs ======================= <gh_stars>1-10 /* Written by <NAME>. in 2013. Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ If you like this, you should donate to Peter O. at: http://peteroupc.github.io/ */ using System; namespace PeterO.Numbers { internal sealed class FastIntegerFixed : IComparable<FastIntegerFixed> { private int smallValue; // if integerMode is 0 private EInteger largeValue; // if integerMode is 2 private int integerMode; public static readonly FastIntegerFixed Zero = new FastIntegerFixed(0); public static readonly FastIntegerFixed One = new FastIntegerFixed(1); private static readonly EInteger ValueInt32MinValue = (EInteger)Int32.MinValue; private static readonly EInteger ValueNegativeInt32MinValue = -(EInteger)ValueInt32MinValue; internal FastIntegerFixed(int value) { this.smallValue = value; } public override bool Equals(object obj) { var fi = obj as FastIntegerFixed; if (fi == null) { return false; } if (this.integerMode!= fi.integerMode) { return false; } if (this.integerMode == 0) { if (this.smallValue!= fi.smallValue) { return false; } } else if (this.integerMode == 1) { if (!this.largeValue.Equals(fi.largeValue)) { return false; } } return true; } public override int GetHashCode() { int hash = unchecked(31 + this.integerMode); if (this.integerMode == 0) { hash = unchecked((hash * 31) + this.smallValue); } else if (this.integerMode == 1) { hash = unchecked((hash * 31) + this.largeValue.GetHashCode()); } return hash; } internal static FastIntegerFixed FromLong(long longVal) { if (longVal >= Int32.MinValue && longVal <= Int32.MaxValue) { return new FastIntegerFixed((int)longVal); } var fi = new FastIntegerFixed(0); fi.integerMode = 2; fi.largeValue = EInteger.FromInt64(longVal); return fi; } internal static FastIntegerFixed FromBig(EInteger bigintVal) { if (bigintVal.CanFitInInt32()) { return new FastIntegerFixed(bigintVal.ToInt32Unchecked()); } var fi = new FastIntegerFixed(0); fi.integerMode = 2; fi.largeValue = bigintVal; return fi; } internal int AsInt32() { return (this.integerMode == 0)? this.smallValue : this.largeValue.ToInt32Unchecked(); } public static FastIntegerFixed FromFastInteger(FastInteger fi) { if (fi.CanFitInInt32()) { return new FastIntegerFixed(fi.AsInt32()); } else { return FastIntegerFixed.FromBig(fi.AsEInteger()); } } public FastInteger ToFastInteger() { if (this.integerMode == 0) { return new FastInteger(this.smallValue); } else { return FastInteger.FromBig(this.largeValue); } } public FastIntegerFixed Increment() { if (this.integerMode == 0 && this.smallValue!= Int32.MaxValue) { return new FastIntegerFixed(this.smallValue + 1); } else { return Add(this, FastIntegerFixed.One); } } public int Mod(int value) { if (value < 0) { throw new NotSupportedException(); } if (this.integerMode == 0 && this.smallValue >= 0) { return this.smallValue % value; } else { EInteger retval = this.ToEInteger().Remainder(EInteger.FromInt32(value)); return retval.ToInt32Checked(); } } public static FastIntegerFixed Add(FastIntegerFixed a, FastIntegerFixed b) { if (a.integerMode == 0 && b.integerMode == 0) { if (a.smallValue == 0) { return b; } if (b.smallValue == 0) { return a; } if ((a.smallValue < 0 && b.smallValue >= Int32.MinValue - a.smallValue) || (a.smallValue > 0 && b.smallValue <= Int32.MaxValue - a.smallValue)) { return new FastIntegerFixed(a.smallValue + b.smallValue); } } EInteger bigA = a.ToEInteger(); EInteger bigB = b.ToEInteger(); return FastIntegerFixed.FromBig(bigA.Add(bigB)); } public static FastIntegerFixed Subtract( FastIntegerFixed a, FastIntegerFixed b) { if (a.integerMode == 0 && b.integerMode == 0) { if (b.smallValue == 0) { return a; } if ((b.smallValue < 0 && Int32.MaxValue + b.smallValue >= a.smallValue) || (b.smallValue > 0 && Int32.MinValue + b.smallValue <= a.smallValue)) { return new FastIntegerFixed(a.smallValue - b.smallValue); } } EInteger bigA = a.ToEInteger(); EInteger bigB = b.ToEInteger(); return FastIntegerFixed.FromBig(bigA.Subtract(bigB)); } public int CompareTo(FastIntegerFixed val) { switch ((this.integerMode << 2) | val.integerMode) { case (0 << 2) | 0: { int vsv = val.smallValue; return (this.smallValue == vsv)? 0 : (this.smallValue < vsv? -1 : 1); } case (0 << 2) | 2: return this.ToEInteger().CompareTo(val.largeValue); case (2 << 2) | 0: case (2 << 2) | 2: return this.largeValue.CompareTo(val.ToEInteger()); default: throw new InvalidOperationException(); } } /// <include file='../../docs.xml' /// path='docs/doc[@name="M:PeterO.Numbers.FastIntegerFixed.Negate"]/*'/> internal FastIntegerFixed Negate() { switch (this.integerMode) { case 0: if (this.smallValue == Int32.MinValue) { return FastIntegerFixed.FromBig(ValueNegativeInt32MinValue); } else { return new FastIntegerFixed(-smallValue); } case 2: return FastIntegerFixed.FromBig(-(EInteger)this.largeValue); default: throw new InvalidOperationException(); } } internal bool IsEvenNumber { get { switch (this.integerMode) { case 0: return (this.smallValue & 1) == 0; case 2: return this.largeValue.IsEven; default: throw new InvalidOperationException(); } } } internal bool CanFitInInt32() { return this.integerMode == 0 || this.largeValue.CanFitInInt32(); } /// <include file='../../docs.xml' /// path='docs/doc[@name="M:PeterO.Numbers.FastIntegerFixed.ToString"]/*'/> public override string ToString() { switch (this.integerMode) { case 0: return FastInteger.IntToString(this.smallValue); case 2: return this.largeValue.ToString(); default: return String.Empty; } } internal int Sign { get { switch (this.integerMode) { case 0: return (this.smallValue == 0)? 0 : ((this.smallValue < 0)? -1 : 1); case 2: return this.largeValue.Sign; default: return 0; } } } internal bool IsValueZero { get { switch (this.integerMode) { case 0: return this.smallValue == 0; case 2: return this.largeValue.IsZero; default: return false; } } } internal bool CanFitInInt64() { switch (this.integerMode) { case 0: return true; case 2: { return this.largeValue.CanFitInInt64(); } default: throw new InvalidOperationException(); } } internal long AsInt64() { switch (this.integerMode) { case 0: return (long)this.smallValue; case 2: { return this.largeValue.ToInt64Unchecked(); } default: throw new InvalidOperationException(); } } internal int CompareToInt(int val) { switch (this.integerMode) { case 0: return (val == this.smallValue)? 0 : (this.smallValue < val? -1 : 1); case 2: return this.largeValue.CompareTo((EInteger)val); default: return 0; } } internal EInteger ToEInteger() { switch (this.integerMode) { case 0: return EInteger.FromInt32(this.smallValue); case 2: return this.largeValue; default: throw new InvalidOperationException(); } } } } ======================= File: Neos.IdentityServer 3.0/Neos.IdentityServer.Console/Views/Neos.IdentityServer.Console.UsersFormView.cs ======================= //******************************************************************************************************************************************************************************************// // Copyright (c) 2020 @redhook62 (<EMAIL>) // // // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), // // to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, // // and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // // // https://adfsmfa.codeplex.com // // https://github.com/neos-sdi/adfsmfa // // // //******************************************************************************************************************************************************************************************// using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.ManagementConsole; using Neos.IdentityServer.MultiFactor; using Neos.IdentityServer.MultiFactor.Administration; using System.Diagnostics; using Microsoft.ManagementConsole.Advanced; using System.Windows.Forms; using System.Threading; using res = Neos.IdentityServer.Console.Resources.Neos_IdentityServer_Console_UsersFormView; namespace Neos.IdentityServer.Console { /// <summary> /// UsersFormView Class /// </summary> public class UsersFormView : FormView { private UsersListView usersControl = null; private UsersScopeNode usersScopeNode = null; private WritableSharedData _sharedUserData = null; /// <summary> /// UsersFormView Constructor /// </summary> public UsersFormView() { _sharedUserData = new WritableSharedData(); } /// <summary> /// SharedUserData property /// </summary> public WritableSharedData SharedUserData { get { return _sharedUserData; } } /// <summary> /// Initialize method override /// </summary> protected override void OnInitialize(AsyncStatus status) { usersControl = (UsersListView)this.Control; usersScopeNode = (UsersScopeNode)this.ScopeNode; usersScopeNode.usersFormView = this; base.OnInitialize(status); } /// <summary> /// PlugEvents method implementation /// </summary> internal void PlugEvents(UsersListView lst) { lst.DataSelectionChanged += OnDataSelectionChanged; lst.DataEditionActivated += OnDataEditionActivated; ActionsPaneItems.Clear(); SelectionData.ActionsPaneItems.Clear(); SelectionData.ActionsPaneHelpItems.Clear(); SelectionData.EnabledStandardVerbs = (StandardVerbs.Delete); SelectionData.ActionsPaneItems.Add(new Microsoft.ManagementConsole.Action(res.USERSFRMPROPERTIES, res.USERSFRMPROPERTIESDESC, -1, "PropertyUser")); ModeActionsPaneItems.Clear(); } /// <summary> /// UsersListControl property implementation /// </summary> public UsersListView UsersListControl { get { return usersControl; } } /// <summary> /// OnDataSelectionChanged method implementation /// </summary> private void OnDataSelectionChanged(object sender, SelectionDataEventArgs e) { if (e.Action!= MMCListAction.SelectionChanged) return; this.SelectionData.BeginUpdates(); try { if (e.Selection.Count == 0) { this.SelectionData.Clear(); } else { if (e.Selection.Count > 0) { SelectionData.Update(e.Selection, e.Selection.Count > 1, null, null); if (e.Selection.Count == 1) { UpdateActionPanelItems(e.Selection); SelectionData.DisplayName = e.Selection[0].UPN; } else { UpdateActionPanelItems(e.Selection); SelectionData.DisplayName = res.USERSFRMSLECTMULTIPLE; } } } } finally { this.SelectionData.EndUpdates(); } } /// <summary> /// OnDataEditionActivated method implmentation /// </summary> private void OnDataEditionActivated(object sender, SelectionDataEventArgs e) { this.SelectionData.ShowPropertySheet(res.USERSFRMPROPERTIES+" : "+SelectionData.DisplayName); } /// <summary> /// UpdateActionPanelItems method implmentation /// </summary> internal void UpdateActionPanelItems(MFAUserList lst) { Nullable<bool> enb = null; SelectionData.ActionsPaneItems.Clear(); foreach (MFAUser reg in lst) { if (!enb.HasValue) enb = reg.Enabled; else if (enb.Value!= reg.Enabled) enb = null; } if (enb.HasValue) { if (!enb.Value) SelectionData.ActionsPaneItems.Add(new Microsoft.ManagementConsole.Action(res.USERSFRMACTIVATE, res.USERSFRMACTIVATEDESC, -1, "EnableUser")); else SelectionData.ActionsPaneItems.Add(new Microsoft.ManagementConsole.Action(res.USERSFRMDEACTIVATE, res.USERSFRMDEACTIVATEDESC, -1, "DisableUser")); SelectionData.ActionsPaneItems.Add(new Microsoft.ManagementConsole.ActionSeparator()); } SelectionData.ActionsPaneItems.Add(new Microsoft.ManagementConsole.Action(res.USERSFRMPROPERTIES, res.USERSFRMPROPERTIESDESC, -1, "PropertyUser")); } /// <summary> /// EnableDisableAction method implmentation /// </summary> internal void EnableDisableAction(bool value) { SelectionData.ActionsPaneItems.Clear(); if (!value) SelectionData.ActionsPaneItems.Add(new Microsoft.ManagementConsole.Action(res.USERSFRMACTIVATE, res.USERSFRMACTIVATEDESC, -1, "EnableUser")); else SelectionData.ActionsPaneItems.Add(new Microsoft.ManagementConsole.Action(res.USERSFRMDEACTIVATE, res.USERSFRMDEACTIVATEDESC, -1, "DisableUser")); SelectionData.ActionsPaneItems.Add(new Microsoft.ManagementConsole.ActionSeparator()); SelectionData.ActionsPaneItems.Add(new Microsoft.ManagementConsole.Action(res.USERSFRMPROPERTIES, res.USERSFRMPROPERTIESDESC, -1, "PropertyUser")); } /// <summary> /// Refresh method implmentation /// </summary> public void Refresh(bool refreshgrid = false, bool clearselection = false) { if (UsersListControl!= null) { this.SelectionData.BeginUpdates(); try { UsersListControl.RefreshData(refreshgrid, clearselection); foreach (ActionsPaneItem itm in this.SelectionData.ActionsPaneItems) { if (itm is Microsoft.ManagementConsole.Action) { if ((string)((Microsoft.ManagementConsole.Action)itm).Tag == "EnableUser") { ((Microsoft.ManagementConsole.Action)itm).DisplayName = res.USERSFRMACTIVATE; ((Microsoft.ManagementConsole.Action)itm).Description = res.USERSFRMACTIVATEDESC; } else if ((string)((Microsoft.ManagementConsole.Action)itm).Tag == "DisableUser") { ((Microsoft.ManagementConsole.Action)itm).DisplayName = res.USERSFRMDEACTIVATE; ((Microsoft.ManagementConsole.Action)itm).Description = res.USERSFRMDEACTIVATEDESC; } else if ((string)((Microsoft.ManagementConsole.Action)itm).Tag == "PropertyUser") { ((Microsoft.ManagementConsole.Action)itm).DisplayName = res.USERSFRMPROPERTIES; ((Microsoft.ManagementConsole.Action)itm).Description = res.USERSFRMPROPERTIESDESC; } } } } finally { this.SelectionData.EndUpdates(); } } } /// <summary> /// SetUserStoreData method implmentation /// </summary> internal void SetUserStoreData(object obj) { MFAUserList reg = null; if (obj is MFAUserList) { reg = (MFAUserList)obj; if (UsersListControl!= null) { this.SelectionData.BeginUpdates(); try { UsersListControl.SetUserData(reg); } finally { this.SelectionData.EndUpdates(); } } } } /// <summary> /// AddUserStoreData method implementation /// </summary> internal void AddUserStoreData(object obj) { MFAUserList reg = null; if (obj is MFAUserList) { reg = (MFAUserList)obj; if (UsersListControl!= null) { this.SelectionData.BeginUpdates(); try { UsersListControl.AddUserData(reg); } finally { this.SelectionData.EndUpdates(); } } } } /// <summary> /// DeleteUserStoreData method implementation /// </summary> internal bool DeleteUserStoreData(object obj) { bool ret = false; MFAUserList reg = null; if (obj is MFAUserList) { reg = (MFAUserList)obj; if (UsersListControl!= null) { this.SelectionData.BeginUpdates(); try { ret = UsersListControl.DeleteUserData(reg); } finally { this.SelectionData.EndUpdates(); } } } return ret; } /// <summary> /// EnableUserStoreData method implementation /// </summary> private void EnableUserStoreData(object obj, bool enabled) { MFAUserList reg = null; if (obj is MFAUserList) { reg = (MFAUserList)obj; if (UsersListControl!= null) { this.SelectionData.BeginUpdates(); try { if (enabled) UsersListControl.EnableUserData(reg); else UsersListControl.DisableUserData(reg); } finally { this.SelectionData.EndUpdates(); } } } } /// <summary> /// Handle the selected action. /// </summary> protected override void OnSelectionAction(Microsoft.ManagementConsole.Action action, AsyncStatus status) { this.SelectionData.BeginUpdates(); try { switch ((string)action.Tag) { case "EnableUser": { MFAUserList reg = (MFAUserList)SelectionData.SelectionObject; EnableUserStoreData(reg, true); break; } case "DisableUser": { MFAUserList reg = (MFAUserList)SelectionData.SelectionObject; EnableUserStoreData(reg, false); break; } case "PropertyUser": { this.SelectionData.ShowPropertySheet(res.USERSFRMPROPERTIES + " : " + SelectionData.DisplayName); break; } } } finally { this.SelectionData.EndUpdates(); } } /// <summary> /// OnDelete method implmentation /// </summary> protected override void OnDelete(SyncStatus status) { MessageBoxParameters messageBoxParameters = new MessageBoxParameters(); messageBoxParameters.Caption = "Multi-Factor Authentication"; messageBoxParameters.Buttons = MessageBoxButtons.YesNo; messageBoxParameters.DefaultButton = MessageBoxDefaultButton.Button1; messageBoxParameters.Icon = MessageBoxIcon.Question; messageBoxParameters.Text = res.USERSFRMCONFIRMDELETE; if (this.SnapIn.Console.ShowDialog(messageBoxParameters) == DialogResult.Yes) { MFAUserList reg = (MFAUserList)SelectionData.SelectionObject; bool xres = DeleteUserStoreData(reg); if (xres) { status.Complete("ok", true); } else { status.CanCancel = true; status.Complete("error", false); } } else { status.CanCancel = true; base.OnDelete(status); } } /// <summary> /// OnAddPropertyPages method implementation /// </summary> protected override void OnAddPropertyPages(PropertyPageCollection propertyPageCollection) { Random rand = new Random(); int i = rand.Next(); MFAUserList registrations = (MFAUserList)SelectionData.SelectionObject; if (registrations.Count > 1) propertyPageCollection.Add(new UserPropertyPage(this, typeof(UserCommonPropertiesControl), i)); else { propertyPageCollection.Add(new UserPropertyPage(this, typeof(UserPropertiesControl), i)); propertyPageCollection.Add(new UserPropertyPage(this, typeof(UserPropertiesKeysControl), i)); } } } } ======================= File: Neos.IdentityServer 3.0/Neos.IdentityServer.MultiFactor.WebAuthN.Core/Model/Metdadata/DisplayPNGCharacteristicsDescriptor.cs ======================= <reponame>klpo-mt/adfsmfa //******************************************************************************************************************************************************************************************// // Copyright (c) 2020 abergs (https://github.com/abergs/fido2-net-lib) // // // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), // // to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, // // and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // // //******************************************************************************************************************************************************************************************// using Newtonsoft.Json; namespace Neos.IdentityServer.MultiFactor.WebAuthN { /// <summary> /// The DisplayPNGCharacteristicsDescriptor describes a PNG image characteristics as defined in the PNG [PNG] spec for IHDR (image header) and PLTE (palette table) /// </summary> /// <remarks> /// <see href="https://fidoalliance.org/specs/fido-v2.0-rd-20180702/fido-metadata-statement-v2.0-rd-20180702.html#displaypngcharacteristicsdescriptor-dictionary"/> /// </remarks> public class DisplayPNGCharacteristicsDescriptor { /// <summary> /// Gets or sets the image width. /// </summary> [JsonProperty("width", Required = Required.Always)] public ulong Width { get; set; } /// <summary> /// Gets or sets the image height. /// </summary> [JsonProperty("height", Required = Required.Always)] public ulong Height { get; set; } /// <summary> /// Gets or sets the bit depth - bits per sample or per palette index. /// </summary> [JsonProperty("bitDepth", Required = Required.Always)] public byte BitDepth { get; set; } /// <summary> /// Gets or sets the color type defines the PNG image type. /// </summary> [JsonProperty("colorType", Required = Required.Always)] public byte ColorType { get; set; } /// <summary> /// Gets or sets the compression method used to compress the image data. /// </summary> [JsonProperty("compression", Required = Required.Always)] public byte Compression { get; set; } /// <summary> /// Gets or sets the filter method is the preprocessing method applied to the image data before compression. /// </summary> [JsonProperty("filter", Required = Required.Always)] public byte Filter { get; set; } /// <summary> /// Gets or sets the interlace method is the transmission order of the image data. /// </summary> [JsonProperty("interlace", Required = Required.Always)] public byte Interlace { get; set; } /// <summary> /// Gets or sets the palette (1 to 256 palette entries). /// </summary> [JsonProperty("plte")] public RgbPaletteEntry[] Plte { get; set; } } } ======================= File: Neos.IdentityServer 3.0/Neos.IdentityServer.Console/Forms/Neos.IdentityServer.Console.SecurityAESViewControl.Designer.cs ======================= <filename>Neos.IdentityServer 3.0/Neos.IdentityServer.Console/Forms/Neos.IdentityServer.Console.SecurityAESViewControl.Designer.cs namespace Neos.IdentityServer.Console { partial class ServiceSecurityAESViewControl { /// <summary> /// Variable nécessaire au concepteur. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Nettoyage des ressources utilisées. /// </summary> /// <param name="disposing">true si les ressources managées doivent être supprimées ; sinon, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components!= null)) { components.Dispose(); } base.Dispose(disposing); } #region Code généré par le Concepteur de composants /// <summary> /// Méthode requise pour la prise en charge du concepteur - ne modifiez pas /// le contenu de cette méthode avec l'éditeur de code. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ServiceSecurityAESViewControl)); this.tableLayoutPanel = new System.Windows.Forms.TableLayoutPanel(); this.panel1 = new System.Windows.Forms.Panel(); this.ProviderTitle = new System.Windows.Forms.Label(); this.tableLayoutPanel.SuspendLayout(); this.panel1.SuspendLayout(); this.SuspendLayout(); // // tableLayoutPanel // resources.ApplyResources(this.tableLayoutPanel, "tableLayoutPanel"); this.tableLayoutPanel.Controls.Add(this.panel1, 0, 0); this.tableLayoutPanel.Name = "tableLayoutPanel"; // // panel1 // this.panel1.Controls.Add(this.ProviderTitle); resources.ApplyResources(this.panel1, "panel1"); this.panel1.Name = "panel1"; // // ProviderTitle // resources.ApplyResources(this.ProviderTitle, "ProviderTitle"); this.ProviderTitle.Name = "ProviderTitle"; // // ServiceSecurityViewControl // resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.SystemColors.Window; this.Controls.Add(this.tableLayoutPanel); this.Name = "ServiceSecurityAESViewControl"; this.tableLayoutPanel.ResumeLayout(false); this.panel1.ResumeLayout(false); this.panel1.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.TableLayoutPanel tableLayoutPanel; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.Label ProviderTitle; } } ======================= File: Neos.IdentityServer 3.0/Neos.IdentityServer.MultiFactor/Resources/SHtml.Designer.cs ======================= //------------------------------------------------------------------------------ // <auto-generated> // Ce code a été généré par un outil. // Version du runtime :4.0.30319.42000 // // Les modifications apportées à ce fichier peuvent provoquer un comportement incorrect et seront perdues si // le code est régénéré. // </auto-generated> //------------------------------------------------------------------------------ namespace Neos.IdentityServer.MultiFactor.Resources { using System; /// <summary> /// Une classe de ressource fortement typée destinée, entre autres, à la consultation des chaînes localisées. /// </summary> // Cette classe a été générée automatiquement par la classe StronglyTypedResourceBuilder // à l'aide d'un outil, tel que ResGen ou Visual Studio. // Pour ajouter ou supprimer un membre, modifiez votre fichier.ResX, puis réexécutez ResGen // avec l'option /str ou régénérez votre projet VS. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class SHtml { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal SHtml() { } /// <summary> /// Retourne l'instance ResourceManager mise en cache utilisée par cette classe. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Neos.IdentityServer.MultiFactor.Resources.SHtml", typeof(SHtml).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Remplace la propriété CurrentUICulture du thread actuel pour toutes /// les recherches de ressources à l'aide de cette classe de ressource fortement typée. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Recherche une chaîne localisée semblable à Use default option. /// </summary> internal static string GLOBALListChoiceDefaultLabel { get { return ResourceManager.GetString("GLOBALListChoiceDefaultLabel", resourceCulture); } } /// <summary> /// Recherche une chaîne localisée semblable à Change my configuration options. /// </summary> internal static string HtmlChangeConfiguration { get { return ResourceManager.GetString("HtmlChangeConfiguration", resourceCulture); } } /// <summary> /// Recherche une chaîne localisée semblable à Change my password. /// </summary> internal static string HtmlChangePassword { get { return ResourceManager.GetString("HtmlChangePassword", resourceCulture); } } /// <summary> /// Recherche une chaîne localisée semblable à Remember my selection. /// </summary> internal static string HtmlCHOOSEOptionRemember { get { return ResourceManager.GetString("HtmlCHOOSEOptionRemember", resourceCulture); } } /// <summary> /// Recherche une chaîne localisée semblable à Default authentication mode. /// </summary> internal static string HtmlCHOOSEOptionRemember2 { get { return ResourceManager.GetString("HtmlCHOOSEOptionRemember2", resourceCulture); } } /// <summary> /// Recherche une chaîne localisée semblable à Send Code. /// </summary> internal static string HtmlCHOOSEOptionSendCode { get { return ResourceManager.GetString("HtmlCHOOSEOptionSendCode", resourceCulture); } } /// <summary> /// Recherche une chaîne localisée semblable à Enroll my biometric device. /// </summary> internal static string HtmlEnrollBiometric { get { return ResourceManager.GetString("HtmlEnrollBiometric", resourceCulture); } } /// <summary> /// Recherche une chaîne localisée semblable à Enroll my biometric device. /// </summary> internal static string HtmlEnrollBiometrics { get { return ResourceManager.GetString("HtmlEnrollBiometrics", resourceCulture); } } /// <summary> /// Recherche une chaîne localisée semblable à Enroll my personal email address. /// </summary> internal static string HtmlEnrollEmail { get { return ResourceManager.GetString("HtmlEnrollEmail", resourceCulture); } } /// <summary> /// Recherche une chaîne localisée semblable à Enroll my authentication application. /// </summary> internal static string HtmlEnrollOTP { get { return ResourceManager.GetString("HtmlEnrollOTP", resourceCulture); } } /// <summary> /// Recherche une chaîne localisée semblable à Enroll my phone. /// </summary> internal static string HtmlEnrollPhone { get { return ResourceManager.GetString("HtmlEnrollPhone", resourceCulture); } } /// <summary> /// Recherche une chaîne localisée semblable à Set my PIN code. /// </summary> internal static string HtmlEnrollPinCode { get { return ResourceManager.GetString("HtmlEnrollPinCode", resourceCulture); } } /// <summary> /// Recherche une chaîne localisée semblable à Set up a PIN. /// </summary> internal static string HtmlEnrollPinTaskLabel { get { return ResourceManager.GetString("HtmlEnrollPinTaskLabel", resourceCulture); } } /// <summary> /// Recherche une chaîne localisée semblable à wrong Identification, please restart your session. /// </summary> internal static string HtmlErrorRestartSession { get { return ResourceManager.GetString("HtmlErrorRestartSession", resourceCulture); } } /// <summary> /// Recherche une chaîne localisée semblable à Send request. /// </summary> internal static string HtmlINSRequest { get { return ResourceManager.GetString("HtmlINSRequest", resourceCulture); } } /// <summary> /// Recherche une chaîne localisée semblable à Sending your inscription request via email to administrators. /// </summary> internal static string HtmlINSWaitRequest { get { return ResourceManager.GetString("HtmlINSWaitRequest", resourceCulture); } } /// <summary> /// Recherche une chaîne localisée semblable à Your account is not validated!&lt;br&gt; ///You can try the operation again by selecting &quot;Previous&quot;.. /// </summary> internal static string HtmlLabelVERIFYOTPError { get { return ResourceManager.GetString("HtmlLabelVERIFYOTPError", resourceCulture); } } /// <summary> /// Recherche une chaîne localisée semblable à Finish. /// </summary> internal static string HtmlLabelVERIFYOTPOK { get { return ResourceManager.GetString("HtmlLabelVERIFYOTPOK", resourceCulture); } } /// <summary> /// Recherche une chaîne localisée semblable à Previous. /// </summary> internal static string HtmlLabelVERIFYOTPPRIOR { get { return ResourceManager.GetString("HtmlLabelVERIFYOTPPRIOR", resourceCulture); } } /// <summary> /// Recherche une chaîne localisée semblable à Your account is validated!&lt;br&gt; ///You will be able to use MFA validation in the future.. /// </summary> internal static string HtmlLabelVERIFYOTPSuccess { get { return ResourceManager.GetString("HtmlLabelVERIFYOTPSuccess", resourceCulture); } } /// <summary> /// Recherche une chaîne localisée semblable à Add a biometric device. /// </summary> internal static string HtmlLabelWRAddBiometrics { get { return ResourceManager.GetString("HtmlLabelWRAddBiometrics", resourceCulture); } } /// <summary> /// Recherche une chaîne localisée semblable à You must activate your biometric device (fingerprint, facial recognition, NFC, etc.) to confirm your identity.. /// </summary> internal static string HtmlLabelWRBiometrics { get { return ResourceManager.GetString("HtmlLabelWRBiometrics", resourceCulture); } } /// <summary> /// Recherche une chaîne localisée semblable à You must have an authentication application such as Microsoft Authenticator, Google Authenticator installed on your device before you can continue and register your account. /// </summary> internal static string HtmlLabelWREGOTP { get { return ResourceManager.GetString("HtmlLabelWREGOTP", resourceCulture); } } /// <summary> /// Recherche une chaîne localisée semblable à By continuing, your current key will be invalidated and reset. /// </summary> internal static string HtmlLabelWREGOTPWarning { get { return ResourceManager.GetString("HtmlLabelWREGOTPWarning", resourceCulture); } } /// <summary> /// Recherche une chaîne localisée semblable à You must enter an email address to confirm your identiy. This email must be reachable without needing enterprise verification (personal email address). /// </summary> internal static string HtmlLabelWREmail { get { return ResourceManager.GetString("HtmlLabelWREmail", resourceCulture); } } /// <summary> /// Recherche une chaîne localisée semblable à Manage your biometrics devices. Select add, replace or delete individual devices.. /// </summary> internal static string HtmlLabelWRManageBiometrics { get { return ResourceManager.GetString("HtmlLabelWRManageBiometrics", resourceCulture); } } /// <summary> /// Recherche une chaîne localisée semblable à You must enter your phone number in order to confirm your identity. This phone must be reachable.. /// </summary> internal static string HtmlLabelWRPhone { get { return ResourceManager.GetString("HtmlLabelWRPhone", resourceCulture); } } /// <summary> /// Recherche une chaîne localisée semblable à You must enter a secret code (4 digits) in order to validate your identity. Be sure not to use the codes of your bank card or telephone as well as details concerning your date of birth.. /// </summary> internal static string HtmlLabelWRPinCode { get { return ResourceManager.GetString("HtmlLabelWRPinCode", resourceCulture); } } /// <summary> /// Recherche une chaîne localisée semblable à Scan the QR Code with a TOTP application like Microsoft Authenticator, Google Authenticator for registering your account. /// </summary> internal static string HtmlLabelWRQRCode { get { return ResourceManager.GetString("HtmlLabelWRQRCode", resourceCulture); } } /// <summary> /// Recherche une chaîne localisée semblable à Continue. /// </summary> internal static string HtmlLabelWVERIFYOTP { get { return ResourceManager.GetString("HtmlLabelWVERIFYOTP", resourceCulture); } } /// <summary> /// Recherche une chaîne localisée semblable à Cancel. /// </summary> internal static string HtmlPWDCancel { get { return ResourceManager.GetString("HtmlPWDCancel", resourceCulture); } } /// <summary> /// Recherche une chaîne localisée semblable à Current password. /// </summary> internal static string HtmlPWDLabelActual { get { return ResourceManager.GetString("HtmlPWDLabelActual", resourceCulture); } } /// <summary> /// Recherche une chaîne localisée semblable à New password. /// </summary> internal static string HtmlPWDLabelNew { get { return ResourceManager.GetString("HtmlPWDLabelNew", resourceCulture); } } /// <summary> /// Recherche une chaîne localisée semblable à Password confirmation. /// </summary> internal static string HtmlPWDLabelNewConfirmation { get { return ResourceManager.GetString("HtmlPWDLabelNewConfirmation", resourceCulture); } } /// <summary> /// Recherche une chaîne localisée semblable à Save. /// </summary> internal static string HtmlPWDSave { get { return ResourceManager.GetString("HtmlPWDSave", resourceCulture); } } /// <summary> /// Recherche une chaîne localisée semblable à Default access method. /// </summary> internal static string HtmlREGAccessMethod { get { return ResourceManager.GetString("HtmlREGAccessMethod", resourceCulture); } } /// <summary> /// Recherche une chaîne localisée semblable à Configuration options. /// </summary> internal static string HtmlREGAccessPageMethods { get { return ResourceManager.GetString("HtmlREGAccessPageMethods", resourceCulture); } } /// <summary> /// Recherche une chaîne localisée semblable à Secret Key. /// </summary> internal static string HtmlREGLabelAppKey { get { return ResourceManager.GetString("HtmlREGLabelAppKey", resourceCulture); } } /// <summary> /// Recherche une chaîne localisée semblable à Choose the default option. /// </summary> internal static string HtmlREGOptionChooseBest { get { return ResourceManager.GetString("HtmlREGOptionChooseBest", resourceCulture); } } /// <summary> /// Recherche une chaîne localisée semblable à Activate. /// </summary> internal static string HtmlUIActivate { get { return ResourceManager.GetString("HtmlUIActivate", resourceCulture); } } /// <summary> /// Recherche une chaîne localisée semblable à &lt;br/&gt; ///Click &quot;Continue&quot;. /// </summary> internal static string HtmlUIEnrollContinue { get { return ResourceManager.GetString("HtmlUIEnrollContinue", resourceCulture); } } /// <summary> /// Recherche une chaîne localisée semblable à Access my options after authentication. /// </summary> internal static string HtmlUIMAccessOptions { get { return ResourceManager.GetString("HtmlUIMAccessOptions", resourceCulture); } } /// <summary> /// Recherche une chaîne localisée semblable à Verify. /// </summary> internal static string HtmlUIMCheck { get { return ResourceManager.GetString("HtmlUIMCheck", resourceCulture); } } /// <summary> /// Recherche une chaîne localisée semblable à Sign In. /// </summary> internal static string HtmlUIMConnexion { get { return ResourceManager.GetString("HtmlUIMConnexion", resourceCulture); } } /// <summary> /// Recherche une chaîne localisée semblable à Disable Multi-Factor authentication. /// </summary> internal static string HtmlUIMDisableMFA { get { return ResourceManager.GetString("HtmlUIMDisableMFA", resourceCulture); } } /// <summary> /// Recherche une chaîne localisée semblable à Inscription request. /// </summary> internal static string HtmlUIMGotoInscription { get { return ResourceManager.GetString("HtmlUIMGotoInscription", resourceCulture); } } /// <summary> /// Recherche une chaîne localisée semblable à Registration. /// </summary> internal static string HtmlUIMGoToRegistration { get { return ResourceManager.GetString("HtmlUIMGoToRegistration", resourceCulture); } } /// <summary> /// Recherche une chaîne localisée semblable à I do not have the code. /// </summary> internal static string HtmlUIMNoCode { get { return ResourceManager.GetString("HtmlUIMNoCode", resourceCulture); } } /// <summary> /// Recherche une chaîne localisée semblable à Ok. /// </summary> internal static string HtmlUIMOk { get { return ResourceManager.GetString("HtmlUIMOk", resourceCulture); } } /// <summary> /// Recherche une chaîne localisée semblable à Quit. /// </summary> internal static string HtmlUIMQuit { get { return ResourceManager.GetString("HtmlUIMQuit", resourceCulture); } } /// <summary> /// Recherche une chaîne localisée semblable à Get a new key. /// </summary> internal static string HtmlUIMRecordNewKey { get { return ResourceManager.GetString("HtmlUIMRecordNewKey", resourceCulture); } } /// <summary> /// Recherche une chaîne localisée semblable à You must :. /// </summary> internal static string HtmlUIMustPrepareLabel { get { return ResourceManager.GetString("HtmlUIMustPrepareLabel", resourceCulture); } } /// <summary> /// Recherche une chaîne localisée semblable à Next. /// </summary> internal static string HtmlUINext { get { return ResourceManager.GetString("HtmlUINext", resourceCulture); } } /// <summary> /// Recherche une chaîne localisée semblable à Pin code. /// </summary> internal static string HtmlUIPinOptionLabel { get { return ResourceManager.GetString("HtmlUIPinOptionLabel", resourceCulture); } } /// <summary> /// Recherche une chaîne localisée semblable à Informations provided :. /// </summary> internal static string HtmlUIResultLabel { get { return ResourceManager.GetString("HtmlUIResultLabel", resourceCulture); } } } } ======================= File: Neos.IdentityServer 3.0/Neos.IdentityServer.MultiFactor.DataTypes/Neos.IdentityServer.Utils.cs ======================= <reponame>klpo-mt/adfsmfa<gh_stars>0 //******************************************************************************************************************************************************************************************// // Copyright (c) 2020 @redhook62 (<EMAIL>) // // // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), // // to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, // // and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // // // https://adfsmfa.codeplex.com // // https://github.com/neos-sdi/adfsmfa // // // //******************************************************************************************************************************************************************************************// using CERTENROLLLib; using Microsoft.Win32; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.DirectoryServices.AccountManagement; using System.IO; using System.Management.Automation; using System.Management.Automation.Runspaces; using System.Runtime.InteropServices; using System.Security; using System.Security.AccessControl; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.Text; namespace Neos.IdentityServer.MultiFactor.Data { /// <summary> /// Certs class implmentation /// </summary> public static class Certs { public static string ADFSAccountSID = string.Empty; public static string ADFSServiceSID = string.Empty; public static string ADFSAdminGroupSID = string.Empty; private static RegistryVersion _RegistryVersion; static Certs() { _RegistryVersion = new RegistryVersion(); } /// <summary> /// GetCertificate method implementation /// </summary> public static X509Certificate2 GetCertificate(string value, StoreLocation location) { X509Certificate2 data = null; X509Store store = new X509Store(location); store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly); try { X509Certificate2Collection collection = (X509Certificate2Collection)store.Certificates; X509Certificate2Collection findCollection = (X509Certificate2Collection)collection.Find(X509FindType.FindByThumbprint, value, false); foreach (X509Certificate2 x509 in findCollection) { data = x509; break; } } catch { data = null; } finally { store.Close(); } return data; } /// <summary> /// RemoveSelfSignedCertificate method implmentation /// </summary> private static bool RemoveSelfSignedCertificate(X509Certificate2 cert, StoreLocation location = StoreLocation.LocalMachine) { if (cert!= null) { X509Store store1 = new X509Store(StoreName.My, location); X509Store store2 = new X509Store(StoreName.CertificateAuthority, location); store1.Open(OpenFlags.MaxAllowed); store2.Open(OpenFlags.MaxAllowed); try { X509Certificate2Collection collection1 = (X509Certificate2Collection)store1.Certificates; X509Certificate2Collection findCollection1 = (X509Certificate2Collection)collection1.Find(X509FindType.FindByThumbprint, cert.Thumbprint, false); foreach (X509Certificate2 x509 in findCollection1) { store1.Remove(x509); x509.Reset(); } X509Certificate2Collection collection2 = (X509Certificate2Collection)store2.Certificates; X509Certificate2Collection findCollection2 = (X509Certificate2Collection)collection2.Find(X509FindType.FindByThumbprint, cert.Thumbprint, false); foreach (X509Certificate2 x509 in findCollection2) { store2.Remove(x509); x509.Reset(); } return true; } catch { return false; } finally { store1.Close(); store2.Close(); } } else return false; } /// <summary> /// CleanSelfSignedCertificate method implmentation /// </summary> private static bool CleanSelfSignedCertificate(X509Certificate2 cert, StoreLocation location = StoreLocation.LocalMachine) { if (cert!= null) { X509Store store = new X509Store(StoreName.CertificateAuthority, location); store.Open(OpenFlags.MaxAllowed); try { X509Certificate2Collection collection2 = (X509Certificate2Collection)store.Certificates; X509Certificate2Collection findCollection2 = (X509Certificate2Collection)collection2.Find(X509FindType.FindByThumbprint, cert.Thumbprint, false); foreach (X509Certificate2 x509 in findCollection2) { store.Remove(x509); x509.Reset(); } return true; } catch { return false; } finally { store.Close(); } } else return false; } /// <summary> /// CreateADFSCertificate method implementation /// </summary> public static bool CreateADFSCertificate(string subjectName, bool issigning, int years) { string strcert = string.Empty; X509Certificate2 x509 = null; try { if (_RegistryVersion.IsWindows2012R2) strcert = InternalCreateADFSCertificate2012R2(subjectName, issigning, years); else strcert = InternalCreateADFSCertificate(subjectName, issigning, years); x509 = new X509Certificate2(Convert.FromBase64String(strcert), "", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.EphemeralKeySet); CleanSelfSignedCertificate(x509, StoreLocation.LocalMachine); return true; } catch (Exception) { return false; } finally { x509.Reset(); } } /// <summary> /// CreateRSACertificate method implementation /// </summary> public static X509Certificate2 CreateRSACertificate(string subjectName, int years) { string strcert = string.Empty; if (_RegistryVersion.IsWindows2012R2) strcert = InternalCreateRSACertificate2012R2(subjectName, years); else strcert = InternalCreateRSACertificate(subjectName, years); X509Certificate2 x509 = new X509Certificate2(Convert.FromBase64String(strcert), "", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.EphemeralKeySet); if (CleanSelfSignedCertificate(x509, StoreLocation.LocalMachine)) return x509; else return null; } /// <summary> /// CreateRSACertificateForSQLEncryption method implementation /// </summary> public static X509Certificate2 CreateRSACertificateForSQLEncryption(string subjectName, int years) { string strcert = string.Empty; if (_RegistryVersion.IsWindows2012R2) strcert = InternalCreateSQLCertificate2012R2(subjectName, years); else strcert = InternalCreateSQLCertificate(subjectName, years); X509Certificate2 x509 = new X509Certificate2(Convert.FromBase64String(strcert), "", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.EphemeralKeySet); if (CleanSelfSignedCertificate(x509, StoreLocation.LocalMachine)) return x509; else return null; } /// <summary> /// CreateRSAEncryptionCertificateForUser method implementation /// </summary> public static X509Certificate2 CreateRSAEncryptionCertificateForUser(string subjectName, int years, string pwd = "") { string strcert = string.Empty; if (_RegistryVersion.IsWindows2012R2) strcert = InternalCreateUserRSACertificate2012R2(subjectName, years, pwd); else strcert = InternalCreateUserRSACertificate(subjectName, years, pwd); X509Certificate2 cert = new X509Certificate2(Convert.FromBase64String(strcert), pwd, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.EphemeralKeySet); if (Certs.RemoveSelfSignedCertificate(cert, StoreLocation.CurrentUser)) return cert; else return null; } #region Windows 2016 & 2019 /// <summary> /// InternalCreateRSACertificate method implementation /// </summary> [SuppressUnmanagedCodeSecurity] private static string InternalCreateRSACertificate(string subjectName, int years) { string base64encoded = string.Empty; CX500DistinguishedName dn = new CX500DistinguishedName(); CX500DistinguishedName neos = new CX500DistinguishedName(); dn.Encode("CN=" + subjectName + " " + DateTime.UtcNow.ToString("G") + " GMT", X500NameFlags.XCN_CERT_NAME_STR_NONE); neos.Encode("CN=MFA RSA Keys Certificate", X500NameFlags.XCN_CERT_NAME_STR_NONE); CX509PrivateKey privateKey = new CX509PrivateKey { ProviderName = "Microsoft RSA SChannel Cryptographic Provider", MachineContext = true, Length = 2048, KeySpec = X509KeySpec.XCN_AT_KEYEXCHANGE, // use is not limited ExportPolicy = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_EXPORT_FLAG, KeyUsage = X509PrivateKeyUsageFlags.XCN_NCRYPT_ALLOW_DECRYPT_FLAG, SecurityDescriptor = "D:(A;;FA;;;SY)(A;;FA;;;BA)" }; if (!string.IsNullOrEmpty(ADFSServiceSID)) privateKey.SecurityDescriptor += "(A;;FA;;;" + ADFSServiceSID + ")"; if (!string.IsNullOrEmpty(ADFSAccountSID)) privateKey.SecurityDescriptor += "(A;;FA;;;" + ADFSAccountSID + ")"; if (!string.IsNullOrEmpty(ADFSAdminGroupSID)) privateKey.SecurityDescriptor += "(A;;FA;;;" + ADFSAdminGroupSID + ")"; try { privateKey.Create(); CObjectId hashobj = new CObjectId(); hashobj.InitializeFromAlgorithmName(ObjectIdGroupId.XCN_CRYPT_HASH_ALG_OID_GROUP_ID, ObjectIdPublicKeyFlags.XCN_CRYPT_OID_INFO_PUBKEY_ANY, AlgorithmFlags.AlgorithmFlagsNone, "SHA256"); CObjectId oid = new CObjectId(); // oid.InitializeFromValue("1.3.6.1.5.172.16.58.3"); // SSL server oid.InitializeFromValue("1.3.6.1.4.1.311.80.1"); // Encryption CObjectIds oidlist = new CObjectIds { oid }; CObjectId coid = new CObjectId(); // coid.InitializeFromValue("1.3.6.1.5.5.7.3.2"); // Client auth coid.InitializeFromValue("1.3.6.1.5.5.7.3.3"); // Signature oidlist.Add(coid); CX509ExtensionEnhancedKeyUsage eku = new CX509ExtensionEnhancedKeyUsage(); eku.InitializeEncode(oidlist); // Create the self signing request CX509CertificateRequestCertificate certreq = new CX509CertificateRequestCertificate(); certreq.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextMachine, privateKey, ""); certreq.Subject = dn; certreq.Issuer = neos; certreq.NotBefore = DateTime.Now.AddDays(-10); certreq.NotAfter = DateTime.Now.AddYears(years); certreq.X509Extensions.Add((CX509Extension)eku); // add the EKU certreq.HashAlgorithm = hashobj; // Specify the hashing algorithm certreq.Encode(); // encode the certificate // Do the final enrollment process CX509Enrollment enroll = new CX509Enrollment(); enroll.InitializeFromRequest(certreq); // load the certificate enroll.CertificateFriendlyName = subjectName; // Optional: add a friendly name string csr = enroll.CreateRequest(); // Output the request in base64 // and install it back as the response enroll.InstallResponse(InstallResponseRestrictionFlags.AllowUntrustedCertificate, csr, EncodingType.XCN_CRYPT_STRING_BASE64, ""); // output a base64 encoded PKCS#12 so we can import it back to the.Net security classes base64encoded = enroll.CreatePFX("", PFXExportOptions.PFXExportChainWithRoot); } catch (Exception ex) { if (privateKey!= null) privateKey.Delete(); throw ex; } finally { // DO nothing, certificate Key is stored in the system } return base64encoded; } /// <summary> /// InternalCreateUserRSACertificate method implementation /// </summary> [SuppressUnmanagedCodeSecurity] private static string InternalCreateUserRSACertificate(string subjectName, int years, string pwd = "") { string base64encoded = string.Empty; CX500DistinguishedName dn = new CX500DistinguishedName(); CX500DistinguishedName neos = new CX500DistinguishedName(); dn.Encode("CN=" + subjectName, X500NameFlags.XCN_CERT_NAME_STR_NONE); neos.Encode("CN=MFA RSA Keys Certificate", X500NameFlags.XCN_CERT_NAME_STR_NONE); CX509PrivateKey privateKey = new CX509PrivateKey { ProviderName = "Microsoft RSA SChannel Cryptographic Provider", MachineContext = false, Length = 2048, KeySpec = X509KeySpec.XCN_AT_KEYEXCHANGE, // use is not limited ExportPolicy = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_EXPORT_FLAG, SecurityDescriptor = "D:(A;;FA;;;SY)(A;;FA;;;BA)" }; if (!string.IsNullOrEmpty(ADFSServiceSID)) privateKey.SecurityDescriptor += "(A;;FA;;;" + ADFSServiceSID + ")"; if (!string.IsNullOrEmpty(ADFSAccountSID)) privateKey.SecurityDescriptor += "(A;;FA;;;" + ADFSAccountSID + ")"; if (!string.IsNullOrEmpty(ADFSAdminGroupSID)) privateKey.SecurityDescriptor += "(A;;FA;;;" + ADFSAdminGroupSID + ")"; try { privateKey.Create(); CObjectId hashobj = new CObjectId(); hashobj.InitializeFromAlgorithmName(ObjectIdGroupId.XCN_CRYPT_HASH_ALG_OID_GROUP_ID, ObjectIdPublicKeyFlags.XCN_CRYPT_OID_INFO_PUBKEY_ANY, AlgorithmFlags.AlgorithmFlagsNone, "SHA256"); CObjectId oid = new CObjectId(); // oid.InitializeFromValue("1.3.6.1.5.5.7.3.1"); // SSL server oid.InitializeFromValue("1.3.6.1.4.1.311.80.1"); // Encryption CObjectIds oidlist = new CObjectIds { oid }; CObjectId coid = new CObjectId(); // coid.InitializeFromValue("1.3.6.1.5.5.7.3.2"); // Client auth coid.InitializeFromValue("1.3.6.1.5.5.7.3.3"); // Signature oidlist.Add(coid); CX509ExtensionEnhancedKeyUsage eku = new CX509ExtensionEnhancedKeyUsage(); eku.InitializeEncode(oidlist); // Create the self signing request CX509CertificateRequestCertificate certreq = new CX509CertificateRequestCertificate(); certreq.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextUser, privateKey, ""); certreq.Subject = dn; certreq.Issuer = neos; certreq.NotBefore = DateTime.Now.AddDays(-10); certreq.NotAfter = DateTime.Now.AddYears(years); certreq.X509Extensions.Add((CX509Extension)eku); // add the EKU certreq.HashAlgorithm = hashobj; // Specify the hashing algorithm certreq.Encode(); // encode the certificate // Do the final enrollment process CX509Enrollment enroll = new CX509Enrollment(); enroll.InitializeFromRequest(certreq); // load the certificate enroll.CertificateFriendlyName = subjectName; // Optional: add a friendly name string csr = enroll.CreateRequest(); // Output the request in base64 // and install it back as the response enroll.InstallResponse(InstallResponseRestrictionFlags.AllowUntrustedCertificate, csr, EncodingType.XCN_CRYPT_STRING_BASE64, ""); // output a base64 encoded PKCS#12 so we can import it back to the.Net security classes base64encoded = enroll.CreatePFX(pwd, PFXExportOptions.PFXExportChainWithRoot); } catch (Exception ex) { if (privateKey!=null) privateKey.Delete(); throw ex; } finally { if (privateKey!= null) privateKey.Delete(); // Remove Stored elsewhere } return base64encoded; } /// <summary> /// InternalCreateSQLCertificate method implementation /// </summary> [SuppressUnmanagedCodeSecurity] private static string InternalCreateSQLCertificate(string subjectName, int years, string pwd = "") { string base64encoded = string.Empty; CX500DistinguishedName dn = new CX500DistinguishedName(); CX500DistinguishedName neos = new CX500DistinguishedName(); dn.Encode("CN=" + subjectName + " " + DateTime.UtcNow.ToString("G") + " GMT", X500NameFlags.XCN_CERT_NAME_STR_NONE); neos.Encode("CN=Always Encrypted Certificate", X500NameFlags.XCN_CERT_NAME_STR_NONE); CX509PrivateKey privateKey = new CX509PrivateKey { ProviderName = "Microsoft RSA SChannel Cryptographic Provider", MachineContext = true, Length = 2048, KeySpec = X509KeySpec.XCN_AT_KEYEXCHANGE, // use is not limited ExportPolicy = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_EXPORT_FLAG, SecurityDescriptor = "D:PAI(A;;0xd01f01ff;;;SY)(A;;0xd01f01ff;;;BA)(A;;0xd01f01ff;;;CO)" }; if (!string.IsNullOrEmpty(ADFSServiceSID)) privateKey.SecurityDescriptor += "(A;;FA;;;" + ADFSServiceSID + ")"; if (!string.IsNullOrEmpty(ADFSAccountSID)) privateKey.SecurityDescriptor += "(A;;FA;;;" + ADFSAccountSID + ")"; if (!string.IsNullOrEmpty(ADFSAdminGroupSID)) privateKey.SecurityDescriptor += "(A;;FA;;;" + ADFSAdminGroupSID + ")"; try { privateKey.Create(); CObjectId hashobj = new CObjectId(); hashobj.InitializeFromAlgorithmName(ObjectIdGroupId.XCN_CRYPT_HASH_ALG_OID_GROUP_ID, ObjectIdPublicKeyFlags.XCN_CRYPT_OID_INFO_PUBKEY_ANY, AlgorithmFlags.AlgorithmFlagsNone, "SHA256"); // 172.16.17.32 – Enhanced Key Usage includes CObjectId oid = new CObjectId(); oid.InitializeFromValue("1.3.6.1.5.5.8.2.2"); // IP security IKE intermediate var oidlist = new CObjectIds { oid }; CObjectId coid = new CObjectId(); coid.InitializeFromValue("1.3.6.1.4.1.311.10.3.11"); // Key Recovery oidlist.Add(coid); CX509ExtensionEnhancedKeyUsage eku = new CX509ExtensionEnhancedKeyUsage(); eku.InitializeEncode(oidlist); // Create the self signing request CX509CertificateRequestCertificate certreq = new CX509CertificateRequestCertificate(); certreq.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextMachine, privateKey, ""); certreq.Subject = dn; certreq.Issuer = neos; certreq.NotBefore = DateTime.Now.AddDays(-10); certreq.NotAfter = DateTime.Now.AddYears(years); certreq.X509Extensions.Add((CX509Extension)eku); // add the EKU certreq.HashAlgorithm = hashobj; // Specify the hashing algorithm certreq.Encode(); // encode the certificate // Do the final enrollment process CX509Enrollment enroll = new CX509Enrollment(); enroll.InitializeFromRequest(certreq); // load the certificate enroll.CertificateFriendlyName = subjectName; // Optional: add a friendly name string csr = enroll.CreateRequest(); // Output the request in base64 // and install it back as the response enroll.InstallResponse(InstallResponseRestrictionFlags.AllowUntrustedCertificate, csr, EncodingType.XCN_CRYPT_STRING_BASE64, ""); // output a base64 encoded PKCS#12 so we can import it back to the.Net security classes base64encoded = enroll.CreatePFX("", PFXExportOptions.PFXExportChainWithRoot); } catch (Exception ex) { if (privateKey!=null) privateKey.Delete(); throw ex; } finally { // DO nothing, certificate Key is stored in the system } return base64encoded; } /// <summary> /// InternalCreateADFSCertificate method implementation /// </summary> [SuppressUnmanagedCodeSecurity] private static string InternalCreateADFSCertificate(string subjectName, bool issigning, int years) { string base64encoded = string.Empty; CX500DistinguishedName dn = new CX500DistinguishedName(); CX500DistinguishedName neos = new CX500DistinguishedName(); CX509PrivateKey privateKey = new CX509PrivateKey { ProviderName = "Microsoft Enhanced Cryptographic Provider v1.0", MachineContext = true, Length = 2048, KeySpec = X509KeySpec.XCN_AT_KEYEXCHANGE, // use is not limited ExportPolicy = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_EXPORT_FLAG, SecurityDescriptor = "D:(A;;FA;;;SY)(A;;FA;;;BA)" }; if (issigning) privateKey.KeyUsage = X509PrivateKeyUsageFlags.XCN_NCRYPT_ALLOW_SIGNING_FLAG; else privateKey.KeyUsage = X509PrivateKeyUsageFlags.XCN_NCRYPT_ALLOW_DECRYPT_FLAG; if (!string.IsNullOrEmpty(ADFSServiceSID)) privateKey.SecurityDescriptor += "(A;;FA;;;" + ADFSServiceSID + ")"; if (!string.IsNullOrEmpty(ADFSAccountSID)) privateKey.SecurityDescriptor += "(A;;FA;;;" + ADFSAccountSID + ")"; if (!string.IsNullOrEmpty(ADFSAdminGroupSID)) privateKey.SecurityDescriptor += "(A;;FA;;;" + ADFSAdminGroupSID + ")"; try { privateKey.Create(); CObjectId hashobj = new CObjectId(); hashobj.InitializeFromAlgorithmName(ObjectIdGroupId.XCN_CRYPT_HASH_ALG_OID_GROUP_ID, ObjectIdPublicKeyFlags.XCN_CRYPT_OID_INFO_PUBKEY_ANY, AlgorithmFlags.AlgorithmFlagsNone, "SHA256"); CObjectIds oidlist = new CObjectIds(); if (!issigning) { CObjectId oid = new CObjectId(); oid.InitializeFromValue("1.3.6.1.4.1.311.80.1"); // Encryption oidlist.Add(oid); dn.Encode("CN=ADFS Encrypt - " + subjectName, X500NameFlags.XCN_CERT_NAME_STR_NONE); neos.Encode("CN=ADFS Encrypt - " + subjectName, X500NameFlags.XCN_CERT_NAME_STR_NONE); } else { CObjectId coid = new CObjectId(); coid.InitializeFromValue("1.3.6.1.5.5.7.3.3"); // Signature oidlist.Add(coid); dn.Encode("CN=ADFS Sign - " + subjectName, X500NameFlags.XCN_CERT_NAME_STR_NONE); neos.Encode("CN=ADFS Sign - " + subjectName, X500NameFlags.XCN_CERT_NAME_STR_NONE); } CX509ExtensionEnhancedKeyUsage eku = new CX509ExtensionEnhancedKeyUsage(); eku.InitializeEncode(oidlist); // Create the self signing request CX509CertificateRequestCertificate certreq = new CX509CertificateRequestCertificate(); certreq.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextMachine, privateKey, ""); certreq.Subject = dn; certreq.Issuer = neos; certreq.NotBefore = DateTime.Now.AddDays(-10); certreq.NotAfter = DateTime.Now.AddYears(years); certreq.X509Extensions.Add((CX509Extension)eku); // add the EKU certreq.HashAlgorithm = hashobj; // Specify the hashing algorithm certreq.Encode(); // encode the certificate // Do the final enrollment process CX509Enrollment enroll = new CX509Enrollment(); enroll.InitializeFromRequest(certreq); // load the certificate enroll.CertificateFriendlyName = subjectName; // Optional: add a friendly name string csr = enroll.CreateRequest(); // Output the request in base64 // and install it back as the response enroll.InstallResponse(InstallResponseRestrictionFlags.AllowUntrustedCertificate, csr, EncodingType.XCN_CRYPT_STRING_BASE64, ""); // output a base64 encoded PKCS#12 so we can import it back to the.Net security classes base64encoded = enroll.CreatePFX("", PFXExportOptions.PFXExportEEOnly); } catch (Exception ex) { if (privateKey!=null) privateKey.Delete(); throw ex; } finally { // DO nothing, certificate Key is stored in the system } return base64encoded; } #endregion #region Windows 2012R2 /// <summary> /// InternalCreateRSACertificate2012R2 method implementation /// </summary> [SuppressUnmanagedCodeSecurity] private static string InternalCreateRSACertificate2012R2(string subjectName, int years) { string base64encoded = string.Empty; CX500DistinguishedName dn = new CX500DistinguishedName(); CX500DistinguishedName neos = new CX500DistinguishedName(); dn.Encode("CN=" + subjectName + " " + DateTime.UtcNow.ToString("G") + " GMT", X500NameFlags.XCN_CERT_NAME_STR_NONE); neos.Encode("CN=MFA RSA Keys Certificate", X500NameFlags.XCN_CERT_NAME_STR_NONE); IX509PrivateKey privateKey = (IX509PrivateKey)Activator.CreateInstance(Type.GetTypeFromProgID("X509Enrollment.CX509PrivateKey")); privateKey.ProviderName = "Microsoft RSA SChannel Cryptographic Provider"; privateKey.MachineContext = true; privateKey.Length = 2048; privateKey.KeySpec = X509KeySpec.XCN_AT_KEYEXCHANGE; // use is not limited privateKey.ExportPolicy = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_EXPORT_FLAG; privateKey.SecurityDescriptor = "D:(A;;FA;;;SY)(A;;FA;;;BA)"; if (!string.IsNullOrEmpty(ADFSServiceSID)) privateKey.SecurityDescriptor += "(A;;FA;;;" + ADFSServiceSID + ")"; if (!string.IsNullOrEmpty(ADFSAccountSID)) privateKey.SecurityDescriptor += "(A;;FA;;;" + ADFSAccountSID + ")"; if (!string.IsNullOrEmpty(ADFSAdminGroupSID)) privateKey.SecurityDescriptor += "(A;;FA;;;" + ADFSAdminGroupSID + ")"; try { privateKey.Create(); CObjectId hashobj = new CObjectId(); hashobj.InitializeFromAlgorithmName(ObjectIdGroupId.XCN_CRYPT_HASH_ALG_OID_GROUP_ID, ObjectIdPublicKeyFlags.XCN_CRYPT_OID_INFO_PUBKEY_ANY, AlgorithmFlags.AlgorithmFlagsNone, "SHA256"); CObjectId oid = new CObjectId(); // oid.InitializeFromValue("1.3.6.1.5.5.7.3.1"); // SSL server oid.InitializeFromValue("1.3.6.1.4.1.311.80.1"); // Encryption CObjectIds oidlist = new CObjectIds { oid }; CObjectId coid = new CObjectId(); // coid.InitializeFromValue("1.3.6.1.5.5.7.3.2"); // Client auth coid.InitializeFromValue("1.3.6.1.5.5.7.3.3"); // Signature oidlist.Add(coid); CX509ExtensionEnhancedKeyUsage eku = new CX509ExtensionEnhancedKeyUsage(); eku.InitializeEncode(oidlist); // Create the self signing request CX509CertificateRequestCertificate certreq = new CX509CertificateRequestCertificate(); certreq.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextMachine, privateKey, ""); certreq.Subject = dn; certreq.Issuer = neos; certreq.NotBefore = DateTime.Now.AddDays(-10); certreq.NotAfter = DateTime.Now.AddYears(years); certreq.X509Extensions.Add((CX509Extension)eku); // add the EKU certreq.HashAlgorithm = hashobj; // Specify the hashing algorithm certreq.Encode(); // encode the certificate // Do the final enrollment process CX509Enrollment enroll = new CX509Enrollment(); enroll.InitializeFromRequest(certreq); // load the certificate enroll.CertificateFriendlyName = subjectName; // Optional: add a friendly name string csr = enroll.CreateRequest(); // Output the request in base64 // and install it back as the response enroll.InstallResponse(InstallResponseRestrictionFlags.AllowUntrustedCertificate, csr, EncodingType.XCN_CRYPT_STRING_BASE64, ""); // output a base64 encoded PKCS#12 so we can import it back to the.Net security classes base64encoded = enroll.CreatePFX("", PFXExportOptions.PFXExportChainWithRoot); } catch (Exception ex) { if (privateKey!=null) privateKey.Delete(); throw ex; } finally { // DO nothing, certificate Key is stored in the system } return base64encoded; } /// <summary> /// InternalCreateUserRSACertificate2012R2 method implementation /// </summary> [SuppressUnmanagedCodeSecurity] private static string InternalCreateUserRSACertificate2012R2(string subjectName, int years, string pwd = "") { string base64encoded = string.Empty; CX500DistinguishedName dn = new CX500DistinguishedName(); CX500DistinguishedName neos = new CX500DistinguishedName(); dn.Encode("CN=" + subjectName, X500NameFlags.XCN_CERT_NAME_STR_NONE); neos.Encode("CN=MFA RSA Keys Certificate", X500NameFlags.XCN_CERT_NAME_STR_NONE); IX509PrivateKey privateKey = (IX509PrivateKey)Activator.CreateInstance(Type.GetTypeFromProgID("X509Enrollment.CX509PrivateKey")); privateKey.ProviderName = "Microsoft RSA SChannel Cryptographic Provider"; privateKey.MachineContext = false; privateKey.Length = 2048; privateKey.KeySpec = X509KeySpec.XCN_AT_KEYEXCHANGE; // use is not limited privateKey.ExportPolicy = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_EXPORT_FLAG; privateKey.SecurityDescriptor = "D:(A;;FA;;;SY)(A;;FA;;;BA)"; if (!string.IsNullOrEmpty(ADFSServiceSID)) privateKey.SecurityDescriptor += "(A;;FA;;;" + ADFSServiceSID + ")"; if (!string.IsNullOrEmpty(ADFSAccountSID)) privateKey.SecurityDescriptor += "(A;;FA;;;" + ADFSAccountSID + ")"; if (!string.IsNullOrEmpty(ADFSAdminGroupSID)) privateKey.SecurityDescriptor += "(A;;FA;;;" + ADFSAdminGroupSID + ")"; try { privateKey.Create(); CObjectId hashobj = new CObjectId(); hashobj.InitializeFromAlgorithmName(ObjectIdGroupId.XCN_CRYPT_HASH_ALG_OID_GROUP_ID, ObjectIdPublicKeyFlags.XCN_CRYPT_OID_INFO_PUBKEY_ANY, AlgorithmFlags.AlgorithmFlagsNone, "SHA256"); CObjectId oid = new CObjectId(); // oid.InitializeFromValue("1.3.6.1.5.172.16.58.3"); // SSL server oid.InitializeFromValue("1.3.6.1.4.1.311.80.1"); // Encryption CObjectIds oidlist = new CObjectIds { oid }; CObjectId coid = new CObjectId(); // coid.InitializeFromValue("1.3.6.1.5.5.7.3.2"); // Client auth coid.InitializeFromValue("1.3.6.1.5.5.7.3.3"); // Signature oidlist.Add(coid); CX509ExtensionEnhancedKeyUsage eku = new CX509ExtensionEnhancedKeyUsage(); eku.InitializeEncode(oidlist); // Create the self signing request CX509CertificateRequestCertificate certreq = new CX509CertificateRequestCertificate(); certreq.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextUser, privateKey, ""); certreq.Subject = dn; certreq.Issuer = neos; certreq.NotBefore = DateTime.Now.AddDays(-10); certreq.NotAfter = DateTime.Now.AddYears(years); certreq.X509Extensions.Add((CX509Extension)eku); // add the EKU certreq.HashAlgorithm = hashobj; // Specify the hashing algorithm certreq.Encode(); // encode the certificate // Do the final enrollment process CX509Enrollment enroll = new CX509Enrollment(); enroll.InitializeFromRequest(certreq); // load the certificate enroll.CertificateFriendlyName = subjectName; // Optional: add a friendly name string csr = enroll.CreateRequest(); // Output the request in base64 // and install it back as the response enroll.InstallResponse(InstallResponseRestrictionFlags.AllowUntrustedCertificate, csr, EncodingType.XCN_CRYPT_STRING_BASE64, ""); // output a base64 encoded PKCS#12 so we can import it back to the.Net security classes base64encoded = enroll.CreatePFX(pwd, PFXExportOptions.PFXExportChainWithRoot); } catch (Exception ex) { if (privateKey!=null) privateKey.Delete(); throw ex; } finally { if (privateKey!= null) privateKey.Delete(); // Remove Stored elsewhere } return base64encoded; } /// <summary> /// InternalCreateSQLCertificate method implementation /// </summary> [SuppressUnmanagedCodeSecurity] private static string InternalCreateSQLCertificate2012R2(string subjectName, int years, string pwd = "") { string base64encoded = string.Empty; CX500DistinguishedName dn = new CX500DistinguishedName(); CX500DistinguishedName neos = new CX500DistinguishedName(); dn.Encode("CN=" + subjectName + " " + DateTime.UtcNow.ToString("G") + " GMT", X500NameFlags.XCN_CERT_NAME_STR_NONE); neos.Encode("CN=Always Encrypted Certificate", X500NameFlags.XCN_CERT_NAME_STR_NONE); IX509PrivateKey privateKey = (IX509PrivateKey)Activator.CreateInstance(Type.GetTypeFromProgID("X509Enrollment.CX509PrivateKey")); privateKey.ProviderName = "Microsoft RSA SChannel Cryptographic Provider"; privateKey.MachineContext = true; privateKey.Length = 2048; privateKey.KeySpec = X509KeySpec.XCN_AT_KEYEXCHANGE; // use is not limited privateKey.ExportPolicy = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_EXPORT_FLAG; privateKey.SecurityDescriptor = "D:(A;;FA;;;SY)(A;;FA;;;BA)"; if (!string.IsNullOrEmpty(ADFSServiceSID)) privateKey.SecurityDescriptor += "(A;;FA;;;" + ADFSServiceSID + ")"; if (!string.IsNullOrEmpty(ADFSAccountSID)) privateKey.SecurityDescriptor += "(A;;FA;;;" + ADFSAccountSID + ")"; if (!string.IsNullOrEmpty(ADFSAdminGroupSID)) privateKey.SecurityDescriptor += "(A;;FA;;;" + ADFSAdminGroupSID + ")"; try { privateKey.Create(); CObjectId hashobj = new CObjectId(); hashobj.InitializeFromAlgorithmName(ObjectIdGroupId.XCN_CRYPT_HASH_ALG_OID_GROUP_ID, ObjectIdPublicKeyFlags.XCN_CRYPT_OID_INFO_PUBKEY_ANY, AlgorithmFlags.AlgorithmFlagsNone, "SHA256"); // 172.16.17.32 – Enhanced Key Usage includes CObjectId oid = new CObjectId(); oid.InitializeFromValue("1.3.6.1.5.5.8.2.2"); // IP security IKE intermediate var oidlist = new CObjectIds { oid }; CObjectId coid = new CObjectId(); coid.InitializeFromValue("1.3.6.1.4.1.311.10.3.11"); // Key Recovery oidlist.Add(coid); CX509ExtensionEnhancedKeyUsage eku = new CX509ExtensionEnhancedKeyUsage(); eku.InitializeEncode(oidlist); // Create the self signing request CX509CertificateRequestCertificate certreq = new CX509CertificateRequestCertificate(); certreq.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextMachine, privateKey, ""); certreq.Subject = dn; certreq.Issuer = neos; certreq.NotBefore = DateTime.Now.AddDays(-10); certreq.NotAfter = DateTime.Now.AddYears(years); certreq.X509Extensions.Add((CX509Extension)eku); // add the EKU certreq.HashAlgorithm = hashobj; // Specify the hashing algorithm certreq.Encode(); // encode the certificate // Do the final enrollment process CX509Enrollment enroll = new CX509Enrollment(); enroll.InitializeFromRequest(certreq); // load the certificate enroll.CertificateFriendlyName = subjectName; // Optional: add a friendly name string csr = enroll.CreateRequest(); // Output the request in base64 // and install it back as the response enroll.InstallResponse(InstallResponseRestrictionFlags.AllowUntrustedCertificate, csr, EncodingType.XCN_CRYPT_STRING_BASE64, ""); // output a base64 encoded PKCS#12 so we can import it back to the.Net security classes base64encoded = enroll.CreatePFX("", PFXExportOptions.PFXExportChainWithRoot); } catch (Exception ex) { if (privateKey!=null) privateKey.Delete(); throw ex; } finally { // DO nothing, certificate Key is stored in the system } return base64encoded; } /// <summary> /// InternalCreateADFSCertificate method implementation /// </summary> [SuppressUnmanagedCodeSecurity] private static string InternalCreateADFSCertificate2012R2(string subjectName, bool issigning, int years) { string base64encoded = string.Empty; CX500DistinguishedName dn = new CX500DistinguishedName(); CX500DistinguishedName neos = new CX500DistinguishedName(); IX509PrivateKey privateKey = (IX509PrivateKey)Activator.CreateInstance(Type.GetTypeFromProgID("X509Enrollment.CX509PrivateKey")); privateKey.ProviderName = "Microsoft Enhanced Cryptographic Provider v1.0"; privateKey.MachineContext = true; privateKey.Length = 2048; privateKey.KeySpec = X509KeySpec.XCN_AT_KEYEXCHANGE; // use is not limited privateKey.ExportPolicy = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_EXPORT_FLAG; privateKey.SecurityDescriptor = "D:(A;;FA;;;SY)(A;;FA;;;BA)"; if (issigning) privateKey.KeyUsage = X509PrivateKeyUsageFlags.XCN_NCRYPT_ALLOW_SIGNING_FLAG; else privateKey.KeyUsage = X509PrivateKeyUsageFlags.XCN_NCRYPT_ALLOW_DECRYPT_FLAG; if (!string.IsNullOrEmpty(ADFSServiceSID)) privateKey.SecurityDescriptor += "(A;;FA;;;" + ADFSServiceSID + ")"; if (!string.IsNullOrEmpty(ADFSAccountSID)) privateKey.SecurityDescriptor += "(A;;FA;;;" + ADFSAccountSID + ")"; if (!string.IsNullOrEmpty(ADFSAdminGroupSID)) privateKey.SecurityDescriptor += "(A;;FA;;;" + ADFSAdminGroupSID + ")"; try { privateKey.Create(); CObjectId hashobj = new CObjectId(); hashobj.InitializeFromAlgorithmName(ObjectIdGroupId.XCN_CRYPT_HASH_ALG_OID_GROUP_ID, ObjectIdPublicKeyFlags.XCN_CRYPT_OID_INFO_PUBKEY_ANY, AlgorithmFlags.AlgorithmFlagsNone, "SHA256"); CObjectIds oidlist = new CObjectIds(); if (!issigning) { CObjectId oid = new CObjectId(); oid.InitializeFromValue("1.3.6.1.4.1.311.80.1"); // Encryption oidlist.Add(oid); dn.Encode("CN=ADFS Encrypt - " + subjectName, X500NameFlags.XCN_CERT_NAME_STR_NONE); neos.Encode("CN=ADFS Encrypt - " + subjectName, X500NameFlags.XCN_CERT_NAME_STR_NONE); } else { CObjectId coid = new CObjectId(); coid.InitializeFromValue("1.3.6.1.5.5.7.3.3"); // Signature oidlist.Add(coid); dn.Encode("CN=ADFS Sign - " + subjectName, X500NameFlags.XCN_CERT_NAME_STR_NONE); neos.Encode("CN=ADFS Sign - " + subjectName, X500NameFlags.XCN_CERT_NAME_STR_NONE); } CX509ExtensionEnhancedKeyUsage eku = new CX509ExtensionEnhancedKeyUsage(); eku.InitializeEncode(oidlist); // Create the self signing request CX509CertificateRequestCertificate certreq = new CX509CertificateRequestCertificate(); certreq.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextMachine, privateKey, ""); certreq.Subject = dn; certreq.Issuer = neos; certreq.NotBefore = DateTime.Now.AddDays(-10); certreq.NotAfter = DateTime.Now.AddYears(years); certreq.X509Extensions.Add((CX509Extension)eku); // add the EKU certreq.HashAlgorithm = hashobj; // Specify the hashing algorithm certreq.Encode(); // encode the certificate // Do the final enrollment process CX509Enrollment enroll = new CX509Enrollment(); enroll.InitializeFromRequest(certreq); // load the certificate enroll.CertificateFriendlyName = subjectName; // Optional: add a friendly name string csr = enroll.CreateRequest(); // Output the request in base64 // and install it back as the response enroll.InstallResponse(InstallResponseRestrictionFlags.AllowUntrustedCertificate, csr, EncodingType.XCN_CRYPT_STRING_BASE64, ""); // output a base64 encoded PKCS#12 so we can import it back to the.Net security classes base64encoded = enroll.CreatePFX("", PFXExportOptions.PFXExportEEOnly); } catch (Exception ex) { if (privateKey!=null) privateKey.Delete(); throw ex; } finally { // DO nothing, certificate Key is stored in the system } return base64encoded; } #endregion /// <summary> /// KeyMgtOptions /// </summary> [Flags] public enum KeyMgtOptions { AllCerts = 0x0, MFACerts = 0x1, ADFSCerts = 0x2, SSLCerts = 0x4 } #region Orphaned Keys /// <summary> /// HasAssociatedCertificate method implementation /// </summary> private static bool HasAssociatedCertificate(string filename) { X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine); store.Open(OpenFlags.MaxAllowed); try { X509Certificate2Collection collection2 = (X509Certificate2Collection)store.Certificates; foreach (X509Certificate2 x509 in collection2) { try { string cntName = string.Empty; var rsakey = x509.GetRSAPrivateKey(); if (rsakey is RSACng) cntName = ((RSACng)rsakey).Key.UniqueName; else if (rsakey is RSACryptoServiceProvider) cntName = ((RSACryptoServiceProvider)rsakey).CspKeyContainerInfo.UniqueKeyContainerName; if (filename.ToLower().Equals(cntName.ToLower())) return true; } catch (Exception) { continue; } } return false; } catch (Exception ex) { throw ex; } finally { store.Close(); } } /// <summary> /// CleanOrphanedPrivateKeys method implementation /// </summary> public static int CleanOrphanedPrivateKeys() { int result = 0; List<string> paths = new List<string>() { Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + @"\Microsoft\Crypto\RSA\MachineKeys\", // Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + @"\Microsoft\Crypto\Keys\" }; foreach (string pth in paths) { DirectoryInfo dir = new DirectoryInfo(pth); foreach (FileInfo fi in dir.GetFiles()) { try { if (fi.Name.ToLower().StartsWith("f686aace6942fb7f7ceb231212eef4a4_")) // RDP Key do not drop anyway continue; if (!HasAssociatedCertificate(fi.Name)) { fi.Delete(); result++; } } catch { } } } return result; } /// <summary> /// CleanOrphanedPrivateKeysRegistry method implementation /// </summary> public static void CleanOrphanedPrivateKeysRegistry(byte option, int delay) { if (option == 0x00) // None return; if (option == 0x01) // Enable { RegistryKey ek = Registry.LocalMachine.OpenSubKey("Software\\MFA", true); if (ek == null) { ek = Registry.LocalMachine.CreateSubKey("Software\\MFA", true); } ek.SetValue("PrivateKeysCleanUpEnabled", 1, RegistryValueKind.DWord); ek.SetValue("PrivateKeysCleanUpDelay", delay, RegistryValueKind.DWord); } if (option == 0x02) // Disable { RegistryKey dk = Registry.LocalMachine.OpenSubKey("Software\\MFA", true); if (dk == null) { dk = Registry.LocalMachine.CreateSubKey("Software\\MFA", true); } dk.SetValue("PrivateKeysCleanUpEnabled", 0, RegistryValueKind.DWord); } } #endregion #region ACLs /// <summary> /// UpdateCertificatesACL method implementation /// </summary> public static bool UpdateCertificatesACL(KeyMgtOptions options = KeyMgtOptions.AllCerts) { X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine); store.Open(OpenFlags.MaxAllowed); try { X509Certificate2Collection collection2 = (X509Certificate2Collection)store.Certificates; foreach (X509Certificate2 x509 in collection2) { string fileName = string.Empty; try { bool doit = options.Equals(KeyMgtOptions.AllCerts); if (options.HasFlag(KeyMgtOptions.MFACerts)) { if (x509.Subject.ToLower().StartsWith("cn=mfa rsa keys") || x509.Subject.ToLower().StartsWith("cn=mfa sql key")) doit = true; } if (options.HasFlag(KeyMgtOptions.ADFSCerts)) { if (x509.Subject.ToLower().StartsWith("cn=adfs")) doit = true; } if (options.HasFlag(KeyMgtOptions.SSLCerts)) { if (x509.Subject.ToLower().StartsWith("cn=*.")) doit = true; } if (doit) { var rsakey = x509.GetRSAPrivateKey(); if (rsakey is RSACng) { fileName = ((RSACng)rsakey).Key.UniqueName; } else if (rsakey is RSACryptoServiceProvider) { fileName = ((RSACryptoServiceProvider)rsakey).CspKeyContainerInfo.UniqueKeyContainerName; } if (!string.IsNullOrEmpty(fileName)) { // string keysfullpath = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + @"\Microsoft\Crypto\Keys\" + fileName; string machinefullpath = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + @"\Microsoft\Crypto\RSA\MachineKeys\" + fileName; // if (File.Exists(keysfullpath)) // InternalUpdateACLs(keysfullpath); if (File.Exists(machinefullpath)) InternalUpdateACLs(machinefullpath); } } } catch { } } } catch (Exception ex) { throw ex; } finally { store.Close(); } return true; } /// <summary> /// InternalUpdateACLs method implementation /// </summary> private static void InternalUpdateACLs(string fullpath) { FileSecurity fSecurity = File.GetAccessControl(fullpath, AccessControlSections.Access); SecurityIdentifier localsys = new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null); fSecurity.AddAccessRule(new FileSystemAccessRule(localsys, FileSystemRights.FullControl, AccessControlType.Allow)); SecurityIdentifier localacc = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null); fSecurity.AddAccessRule(new FileSystemAccessRule(localacc, FileSystemRights.FullControl, AccessControlType.Allow)); if (!string.IsNullOrEmpty(ADFSAccountSID)) { SecurityIdentifier adfsacc = new SecurityIdentifier(ADFSAccountSID); fSecurity.AddAccessRule(new FileSystemAccessRule(adfsacc, FileSystemRights.FullControl, AccessControlType.Allow)); } if (!string.IsNullOrEmpty(ADFSServiceSID)) { SecurityIdentifier adfsserv = new SecurityIdentifier(ADFSServiceSID); fSecurity.AddAccessRule(new FileSystemAccessRule(adfsserv, FileSystemRights.FullControl, AccessControlType.Allow)); } if (!string.IsNullOrEmpty(ADFSAdminGroupSID)) { SecurityIdentifier adfsgroup = new SecurityIdentifier(ADFSAdminGroupSID); fSecurity.AddAccessRule(new FileSystemAccessRule(adfsgroup, FileSystemRights.FullControl, AccessControlType.Allow)); } File.SetAccessControl(fullpath, fSecurity); } #endregion #region SIDs /// <summary> /// InitializeAccountsSID method implementation /// </summary> public static void InitializeAccountsSID(string domain, string account, string password) { ADFSAccountSID = GetADFSAccountSID(domain, account, password); ADFSServiceSID = GetADFSServiceSID(); ADFSAdminGroupSID = GetADFSAdminsGroupSID(domain, account, password); } /// <summary> /// GetADFSServiceSID method implmentation /// </summary> private static string GetADFSServiceSID() { try { IntPtr ptr = GetServiceSidPtr("adfssrv"); return new SecurityIdentifier(ptr).Value; } catch (Exception) { return string.Empty; } } /// <summary> /// GetADFSAccountSID() method implmentation /// </summary> private static string GetADFSAccountSID(string domain, string account, string password) { RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Services\adfssrv"); try { if (key!= null) { string username = key.GetValue("ObjectName").ToString(); SecurityIdentifier sid; NTAccount ntaccount; try { ntaccount = new NTAccount(domain, username); sid = (SecurityIdentifier)ntaccount.Translate(typeof(SecurityIdentifier)); return sid.Value; } catch (Exception) { ntaccount = new NTAccount(username); sid = (SecurityIdentifier)ntaccount.Translate(typeof(SecurityIdentifier)); return sid.Value; } } else return string.Empty; } catch (Exception) { return string.Empty; } finally { key.Close(); } } /// <summary> /// GetADFSAdminsGroupSID() method implmentation /// </summary> private static string GetADFSAdminsGroupSID(string domain, string account, string password) { try { string admingroupname = GetADFSDelegateServiceAdministration(); if (!string.IsNullOrEmpty(admingroupname)) { PrincipalContext ctx; if (!string.IsNullOrEmpty(account)) ctx = new PrincipalContext(ContextType.Domain, domain, account, password); else ctx = new PrincipalContext(ContextType.Domain, domain); GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, admingroupname); if (group!= null) { SecurityIdentifier sid = group.Sid; ADFSAdminGroupSID = sid.Value; return sid.Value; } else return string.Empty; } else return string.Empty; } catch (Exception) { return string.Empty; } } /// <summary> /// GetServiceSidPtr method implementation /// </summary> private static IntPtr GetServiceSidPtr(string service) { NativeMethods.LSA_UNICODE_STRING lSA_UNICODE_STRING = default(NativeMethods.LSA_UNICODE_STRING); lSA_UNICODE_STRING.SetTo(service); int cb = 0; IntPtr intPtr = IntPtr.Zero; IntPtr result; try { uint num = NativeMethods.RtlCreateServiceSid(ref lSA_UNICODE_STRING, IntPtr.Zero, ref cb); if (num == 3221225507u) { intPtr = Marshal.AllocHGlobal(cb); num = NativeMethods.RtlCreateServiceSid(ref lSA_UNICODE_STRING, intPtr, ref cb); } if (num!= 0u) { throw new Win32Exception(Convert.ToInt32(num)); } result = intPtr; } finally { lSA_UNICODE_STRING.Dispose(); } return result; } /// <summary> /// IsWIDConfiguration method implmentation /// </summary> private static string GetADFSDelegateServiceAdministration() { Runspace SPRunSpace = null; PowerShell SPPowerShell = null; string grpname = string.Empty; try { RunspaceConfiguration SPRunConfig = RunspaceConfiguration.Create(); SPRunSpace = RunspaceFactory.CreateRunspace(SPRunConfig); SPPowerShell = PowerShell.Create(); SPPowerShell.Runspace = SPRunSpace; SPRunSpace.Open(); Pipeline pipeline = SPRunSpace.CreatePipeline(); Command exportcmd = new Command("(Get-AdfsProperties).DelegateServiceAdministration", true); pipeline.Commands.Add(exportcmd); Collection<PSObject> PSOutput = pipeline.Invoke(); foreach (var result in PSOutput) { grpname = result.BaseObject.ToString(); return grpname.ToLower(); } } catch (Exception) { grpname = string.Empty; } finally { if (SPRunSpace!= null) SPRunSpace.Close(); if (SPPowerShell!= null) SPPowerShell.Dispose(); } return grpname; } /// <summary> /// NativeMethod implementation /// The class exposes Windows APIs. /// </summary> [SuppressUnmanagedCodeSecurity] internal class NativeMethods { [DllImport("ntdll.dll")] internal static extern uint RtlCreateServiceSid(ref NativeMethods.LSA_UNICODE_STRING serviceName, IntPtr serviceSid, ref int serviceSidLength); internal struct LSA_UNICODE_STRING : IDisposable { public ushort Length; public ushort MaximumLength; public IntPtr Buffer; public void SetTo(string str) { this.Buffer = Marshal.StringToHGlobalUni(str); this.Length = (ushort)(str.Length * 2); this.MaximumLength = Convert.ToUInt16(this.Length + 2); } public override string ToString() { return Marshal.PtrToStringUni(this.Buffer); } public void Reset() { if (this.Buffer!= IntPtr.Zero) { Marshal.FreeHGlobal(this.Buffer); } this.Buffer = IntPtr.Zero; this.Length = 0; this.MaximumLength = 0; } public void Dispose() { this.Reset(); } } } #endregion } #region Encoding /// <summary> /// CheckSumEncoding class implementation /// </summary> public static class CheckSumEncoding { /// <summary> /// EncodeUserID /// </summary> public static byte[] EncodeUserID(int challengesize, string username) { switch (challengesize) { case 16: return CheckSum128(username); case 20: return CheckSum160(username); case 32: return CheckSum256(username); case 48: return CheckSum384(username); case 64: return CheckSum512(username); default: return CheckSum128(username); } } /// <summary> /// EncodeByteArray /// </summary> public static byte[] EncodeByteArray(int challengesize, byte[] data) { switch (challengesize) { case 16: return CheckSum128(data); case 20: return CheckSum160(data); case 32: return CheckSum256(data); case 48: return CheckSum384(data); case 64: return CheckSum512(data); default: return CheckSum128(data); } } /// <summary> /// CheckSum128 method implementation /// </summary> public static byte[] CheckSum128(byte[] value) { byte[] hash = null; using (MD5 md5 = MD5Cng.Create()) { hash = md5.ComputeHash(value); } return hash; } /// <summary> /// CheckSum128 method implementation /// </summary> public static byte[] CheckSum128(string value) { byte[] hash = null; using (MD5 md5 = MD5.Create()) { hash = md5.ComputeHash(Encoding.UTF8.GetBytes(value)); } return hash; } /// <summary> /// CheckSum160 method implementation /// </summary> public static byte[] CheckSum160(byte[] value) { byte[] hash = null; using (SHA1 sha1 = SHA1Cng.Create()) { hash = sha1.ComputeHash(value); } return hash; } /// <summary> /// CheckSum160 method implementation /// </summary> public static byte[] CheckSum160(string value) { byte[] hash = null; using (SHA1 sha1 = SHA1Cng.Create()) { hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(value)); } return hash; } /// <summary> /// CheckSum256 method implementation /// </summary> public static byte[] CheckSum256(byte[] value) { byte[] hash = null; using (SHA256 sha256 = SHA256Cng.Create()) { hash = sha256.ComputeHash(value); } return hash; } /// <summary> /// CheckSum256 method implementation /// </summary> public static byte[] CheckSum256(string value) { byte[] hash = null; using (SHA256 sha256 = SHA256.Create()) { hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(value)); } return hash; } /// <summary> /// CheckSum384 method implementation /// </summary> public static byte[] CheckSum384(byte[] value) { byte[] hash = null; using (SHA384 sha384 = SHA384Cng.Create()) { hash = sha384.ComputeHash(value); } return hash; } /// <summary> /// CheckSum384 method implementation /// </summary> public static byte[] CheckSum384(string value) { byte[] hash = null; using (SHA384 sha384 = SHA384Managed.Create()) { hash = sha384.ComputeHash(Encoding.UTF8.GetBytes(value)); } return hash; } /// <summary> /// CheckSum512 method implementation /// </summary> public static byte[] CheckSum512(byte[] value) { byte[] hash = null; using (SHA512 sha512 = SHA512Cng.Create()) { hash = sha512.ComputeHash(value); } return hash; } /// <summary> /// CheckSum512 method implementation /// </summary> public static byte[] CheckSum512(string value) { byte[] hash = null; using (SHA512 sha512 = SHA512Managed.Create()) { hash = sha512.ComputeHash(Encoding.UTF8.GetBytes(value)); } return hash; } /// <summary> /// CheckSum method implementation /// </summary> public static byte[] CheckSum(string value) { byte[] hash = null; using (MD5 md5 = MD5.Create()) { hash = md5.ComputeHash(Encoding.UTF8.GetBytes(value)); } return hash; } /// <summary> /// CheckSum method implementation /// </summary> public static string CheckSumAsString(string value) { string hash = null; using (MD5 md5 = MD5.Create()) { hash = BitConverter.ToString(md5.ComputeHash(Encoding.UTF8.GetBytes(value))); } return hash.Replace("-", String.Empty); } } /// <summary> /// HexaEncoding static class /// </summary> public static class HexaEncoding { /// <summary> /// GetByteArrayFromHexString method /// </summary> public static byte[] GetByteArrayFromHexString(String value) { int len = value.Length; byte[] bytes = new byte[len / 2]; for (int i = 0; i < len; i += 2) bytes[i / 2] = Convert.ToByte(value.Substring(i, 2), 16); return bytes; } /// <summary> /// GetHexStringFromByteArray method /// </summary> public static string GetHexStringFromByteArray(byte[] data) { int len = data.Length; StringBuilder builder = new StringBuilder(len * 2); foreach (byte b in data) { builder.AppendFormat("{0:x2}", b); } return builder.ToString().ToUpper(); } } #endregion #region ADFS Version internal class RegistryVersion { /// <summary> /// RegistryVersion constructor /// </summary> public RegistryVersion(bool loadlocal = true) { if (loadlocal) { RegistryKey rk = Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\Windows NT\\CurrentVersion"); CurrentVersion = Convert.ToString(rk.GetValue("CurrentVersion")); ProductName = Convert.ToString(rk.GetValue("ProductName")); InstallationType = Convert.ToString(rk.GetValue("InstallationType")); CurrentBuild = Convert.ToInt32(rk.GetValue("CurrentBuild")); CurrentMajorVersionNumber = Convert.ToInt32(rk.GetValue("CurrentMajorVersionNumber")); CurrentMinorVersionNumber = Convert.ToInt32(rk.GetValue("CurrentMinorVersionNumber")); } } /// <summary> /// CurrentVersion property implementation /// </summary> public string CurrentVersion { get; set; } /// <summary> /// ProductName property implementation /// </summary> public string ProductName { get; set; } /// <summary> /// InstallationType property implementation /// </summary> public string InstallationType { get; set; } /// <summary> /// CurrentBuild property implementation /// </summary> public int CurrentBuild { get; set; } /// <summary> /// CurrentMajorVersionNumber property implementation /// </summary> public int CurrentMajorVersionNumber { get; set; } /// <summary> /// CurrentMinorVersionNumber property implementation /// </summary> public int CurrentMinorVersionNumber { get; set; } /// <summary> /// IsWindows2019 property implementation /// </summary> public bool IsWindows2019 { get { return ((this.CurrentMajorVersionNumber == 10) && (this.CurrentBuild >= 17763)); } } /// <summary> /// IsWindows2016 property implementation /// </summary> public bool IsWindows2016 { get { return ((this.CurrentMajorVersionNumber == 10) && ((this.CurrentBuild >= 14393) && (this.CurrentBuild < 17763))); } } /// <summary> /// IsWindows2012R2 property implementation /// </summary> public bool IsWindows2012R2 { get { return ((this.CurrentMajorVersionNumber == 0) && ((this.CurrentBuild >= 9600) && (this.CurrentBuild < 14393))); } } } #endregion } ======================= File: Neos.IdentityServer 3.0/Neos.IdentityServer.Console/Forms/Neos.IdentityServer.Comsole.ServiceViewControl.cs ======================= //******************************************************************************************************************************************************************************************// // Copyright (c) 2020 @redhook62 (<EMAIL>) // // // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), // // to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, // // and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // // // https://adfsmfa.codeplex.com // // https://github.com/neos-sdi/adfsmfa // // // //******************************************************************************************************************************************************************************************// using Microsoft.ManagementConsole; using Neos.IdentityServer.Console.Controls; using Neos.IdentityServer.MultiFactor; using Neos.IdentityServer.MultiFactor.Administration; using System; using System.Collections.Generic; using System.ComponentModel; using System.Windows.Forms; namespace Neos.IdentityServer.Console { public partial class ServiceViewControl : UserControl, IFormViewControl, IMMCNotificationData { private Control oldParent; private ServiceFormView _frm = null; private ConfigurationControl _ctrl = null; private List<ADFSServerControl> _lst = new List<ADFSServerControl>(); private bool _notifenabled; /// <summary> /// Constructor /// </summary> public ServiceViewControl() { InitializeComponent(); } /// <summary> /// Initialize method /// </summary> public void Initialize(FormView view) { FormView = (ServiceFormView)view; ManagementService.ADFSManager.ConfigurationStatusChanged += ConfigurationStatusChanged; OnInitialize(); } private void ConfigurationStatusChanged(ADFSServiceManager mgr, ConfigOperationStatus status, Exception ex = null) { if (IsNotifsEnabled()) { if (this.InvokeRequired) ReloadData(); } } #region Properties /// <summary> /// FormView property implementation /// </summary> protected ServiceFormView FormView { get { return _frm; } private set { _frm = value; } } /// <summary> /// ControlInstance property implmentation /// </summary> protected ConfigurationControl ControlInstance { get { return _ctrl; } private set { _ctrl = value; } } /// <summary> /// SnapIn method implementation /// </summary> protected NamespaceSnapInBase SnapIn { get { return this.FormView.ScopeNode.SnapIn; } } /// <summary> /// ScopeNode method implementation /// </summary> protected ServiceScopeNode ScopeNode { get { return this.FormView.ScopeNode as ServiceScopeNode; } } #endregion /// <summary> /// OnInitialize method /// </summary> protected virtual void OnInitialize() { this.Cursor = Cursors.WaitCursor; this.SuspendLayout(); try { ComponentResourceManager resources = new ComponentResourceManager(typeof(ServiceViewControl)); this.label1.Text = resources.GetString("label1.Text"); this.label2.Text = resources.GetString("label2.Text"); this.label3.Text = resources.GetString("label3.Text"); this.label4.Text = resources.GetString("label4.Text"); ControlInstance = new ConfigurationControl(this, this.SnapIn); this.tableLayoutPanel.Controls.Add(ControlInstance, 0, 1); bool isconfigured = ManagementService.ADFSManager.IsFarmConfigured(); _lst.Clear(); if (isconfigured) { int i = 3; foreach (ADFSServerHost srv in ManagementService.ADFSManager.ADFSFarm.Servers) { bool isok = ManagementService.ADFSManager.IsRunning(srv.FQDN); ADFSServerControl crt = new ADFSServerControl(this, srv, isok); _lst.Add(crt); this.tableLayoutPanel.Controls.Add(crt, 0, i); i++; } } } finally { this.ResumeLayout(true); this.Cursor = Cursors.Default; } } /// <summary> /// RefreshData method implementation /// </summary> internal void RefreshData() { this.SuspendLayout(); this.Cursor = Cursors.WaitCursor; _notifenabled = false; try { ComponentResourceManager resources = new ComponentResourceManager(typeof(ServiceViewControl)); this.label1.Text = resources.GetString("label1.Text"); this.label2.Text = resources.GetString("label2.Text"); this.label3.Text = resources.GetString("label3.Text"); this.label4.Text = resources.GetString("label4.Text"); ManagementService.ADFSManager.ReadConfiguration(null); ((IMMCRefreshData)ControlInstance).DoRefreshData(); bool isconfigured = ManagementService.ADFSManager.IsFarmConfigured(); if (isconfigured) { foreach (ADFSServerControl srv in _lst) { ((IMMCRefreshData)srv).DoRefreshData(); } } } finally { _notifenabled = true; this.Cursor = Cursors.Default; this.ResumeLayout(); } } /// <summary> /// ReloadData method implementation /// </summary> internal void ReloadData() { this.SuspendLayout(); this.Cursor = Cursors.WaitCursor; _notifenabled = false; try { ComponentResourceManager resources = new ComponentResourceManager(typeof(ServiceViewControl)); this.label1.Text = resources.GetString("label1.Text"); this.label2.Text = resources.GetString("label2.Text"); this.label3.Text = resources.GetString("label3.Text"); this.label4.Text = resources.GetString("label4.Text"); ((IMMCRefreshData)ControlInstance).DoRefreshData(); bool isconfigured = ManagementService.ADFSManager.IsFarmConfigured(); if (isconfigured) { foreach (ADFSServerControl srv in _lst) { this.tableLayoutPanel.Controls.Remove(srv); } _lst.Clear(); int i = 3; MFAConfig cfg = CFGUtilities.ReadConfiguration(null); foreach (ADFSServerHost srv in cfg.Hosts.ADFSFarm.Servers) { bool isok = ManagementService.ADFSManager.IsRunning(srv.FQDN); ADFSServerControl crt = new ADFSServerControl(this, srv, isok); _lst.Add(crt); this.tableLayoutPanel.Invoke((MethodInvoker)delegate { this.tableLayoutPanel.Controls.Add(crt, 0, i); }); i++; } } } finally { _notifenabled = true; this.Cursor = Cursors.Default; this.ResumeLayout(); } } /// <summary> /// OnParentChanged method override /// </summary> protected override void OnParentChanged(EventArgs e) { if (Parent!= null) { if (!DesignMode) { Size = Parent.ClientSize; tableLayoutPanel.Size = Size; } Parent.SizeChanged += Parent_SizeChanged; } if (oldParent!= null) { oldParent.SizeChanged -= Parent_SizeChanged; } oldParent = Parent; base.OnParentChanged(e); } /// <summary> /// Parent_SizeChanged event /// </summary> private void Parent_SizeChanged(object sender, EventArgs e) { if (!DesignMode) Size = Parent.ClientSize; } /// <summary> /// IsNotifsEnabled method implementation /// </summary> public bool IsNotifsEnabled() { return _notifenabled; } } } ======================= File: Neos.IdentityServer 3.0/Neos.IdentityServer.MultiFactor/Neos.IdentityServer.MultiFactor.Provider.cs ======================= //******************************************************************************************************************************************************************************************// // Copyright (c) 2020 @redhook62 (<EMAIL>) // // // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), // // to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, // // and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // // // https://adfsmfa.codeplex.com // // https://github.com/neos-sdi/adfsmfa // // // //******************************************************************************************************************************************************************************************// // #define softemail using Microsoft.IdentityServer.Web.Authentication.External; using Neos.IdentityServer.MultiFactor.Common; using Neos.IdentityServer.MultiFactor.Data; using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Net; using System.Security.Claims; using System.Security.Cryptography; namespace Neos.IdentityServer.MultiFactor { /// <summary> /// AuthenticationProvider class /// </summary> public class AuthenticationProvider : IAuthenticationAdapter { private static MFAConfig _config; private static readonly object __notificationobject = 0; private static readonly string _rootdir = string.Empty; /// <summary> /// Constructor override /// </summary> static AuthenticationProvider() { Trace.AutoFlush = true; Trace.TraceInformation("AuthenticationProvider:Contructor"); } #region properties /// <summary> /// Config property /// </summary> public MFAConfig Config { get { return _config; } set { _config = value; } } #endregion #region IAuthenticationAdapter implementation /// <summary> /// BeginAuthentication method implmentation /// </summary> public IAdapterPresentation BeginAuthentication(Claim identityClaim, HttpListenerRequest request, IAuthenticationContext context) { DateTime st = DateTime.Now; AuthenticationContext usercontext = new AuthenticationContext(context); if (this.Config.UseOfUserLanguages) Utilities.PatchUserLcid(usercontext, request.UserLanguages); ResourcesLocale Resources = new ResourcesLocale(usercontext.Lcid); IAdapterPresentation result = null; try { if (Config.IsPrimaryAuhentication) { if ((!usercontext.Enabled) || (!usercontext.IsRegistered)) usercontext.UIMode = ProviderPageMode.Locking; } switch (usercontext.UIMode) { case ProviderPageMode.PreSet: usercontext.UIMode = GetAuthenticationContextRequest(usercontext); GetAuthenticationData(usercontext); result = new AdapterPresentation(this, context); break; case ProviderPageMode.Locking: result = new AdapterPresentation(this, context, Resources.GetString(ResourcesLocaleKind.Errors, "ErrorAccountNoAccess"), ProviderPageMode.DefinitiveError); break; default: // Do not Select method if only one provider if ((usercontext.UIMode == ProviderPageMode.ChooseMethod) && (usercontext.PreferredMethod==PreferredMethod.Choose)) { if (RuntimeAuthProvider.GetActiveProvidersCount()<=1) { IExternalProvider pp = RuntimeAuthProvider.GetFirstActiveProvider(); usercontext.UIMode = ProviderPageMode.SendAuthRequest; if (pp == null) { if (Config.DefaultProviderMethod!= PreferredMethod.Choose) usercontext.PreferredMethod = Config.DefaultProviderMethod; else usercontext.PreferredMethod = PreferredMethod.Code; } else usercontext.PreferredMethod = pp.Kind; } else { if (Config.DefaultProviderMethod!= PreferredMethod.Choose) { usercontext.UIMode = ProviderPageMode.SendAuthRequest; usercontext.PreferredMethod = Config.DefaultProviderMethod; } } PatchUserContextWithSelectedMethod(usercontext); GetAuthenticationData(usercontext); } else if ((HookOptionParameter(request)) && (Config.UserFeatures.CanAccessOptions())) usercontext.UIMode = ProviderPageMode.SelectOptions; result = new AdapterPresentation(this, context); break; } Trace.TraceInformation(String.Format("AuthenticationProvider:BeginAuthentication Duration : {0}", (DateTime.Now - st).ToString())); return result; } catch (Exception ex) { Trace.TraceError(String.Format("AuthenticationProvider:BeginAuthentication Duration : {0}", (DateTime.Now - st).ToString())); Log. WriteEntry(string.Format(Resources.GetString(ResourcesLocaleKind.Errors, "ErrorAuthenticating"), ex.Message), EventLogEntryType.Error, 802); throw new ExternalAuthenticationException(ex.Message, context); } } /// <summary> /// IsAvailableForUser method implementation /// </summary> public bool IsAvailableForUser(Claim identityClaim, IAuthenticationContext context) { DateTime st = DateTime.Now; ResourcesLocale Resources = new ResourcesLocale(context.Lcid); try { string upn = identityClaim.Value; MFAUser reg = RuntimeRepository.GetMFAUser(Config, upn); if (reg!= null) // User Is Registered { AuthenticationContext usercontext = new AuthenticationContext(context, reg); if (usercontext.Enabled) // Enabled { usercontext.LogonDate = DateTime.Now; usercontext.CurrentRetries = 0; usercontext.NotificationSent = false; if (usercontext.KeyStatus == SecretKeyStatus.NoKey) { if (Config.UserFeatures.CanManageOptions()) usercontext.UIMode = ProviderPageMode.PreSet; } else if (usercontext.PreferredMethod == PreferredMethod.Choose) usercontext.UIMode = ProviderPageMode.ChooseMethod; else usercontext.UIMode = ProviderPageMode.PreSet; Trace.TraceInformation(String.Format("AuthenticationProvider:IsAvailableForUser (Standard) Duration : {0}", (DateTime.Now - st).ToString())); return true; } else // Not enabled { usercontext.LogonDate = DateTime.Now; usercontext.CurrentRetries = 0; usercontext.NotificationSent = false; usercontext.UPN = upn; usercontext.Enabled = false; usercontext.PreferredMethod = Config.DefaultProviderMethod; if (Config.UserFeatures.IsMFANotRequired()) { usercontext.UIMode = ProviderPageMode.Bypass; usercontext.TargetUIMode = ProviderPageMode.None; } else if (Config.UserFeatures.IsMFAAllowed()) { if (Config.AdvertisingDays.OnFire) { usercontext.UIMode = ProviderPageMode.Activation; usercontext.TargetUIMode = ProviderPageMode.None; } else { usercontext.UIMode = ProviderPageMode.Bypass; usercontext.TargetUIMode = ProviderPageMode.None; } } else if (Config.UserFeatures.IsMFARequired()) { usercontext.TargetUIMode = ProviderPageMode.DefinitiveError; usercontext.UIMode = ProviderPageMode.Locking; } else { usercontext.TargetUIMode = ProviderPageMode.DefinitiveError; usercontext.UIMode = ProviderPageMode.Locking; } Trace.TraceInformation(String.Format("AuthenticationProvider:IsAvailableForUser (Not Enabled) Duration : {0}", (DateTime.Now - st).ToString())); return true; } } else //Not registered { AuthenticationContext usercontext = new AuthenticationContext(context) { LogonDate = DateTime.Now, CurrentRetries = 0, NotificationSent = false, UPN = upn, Enabled = false, PreferredMethod = Config.DefaultProviderMethod }; if (Config.UserFeatures.IsAdministrative()) // Error : administrative Only Registration { usercontext.UIMode = ProviderPageMode.Locking; usercontext.TargetUIMode = ProviderPageMode.DefinitiveError; } else if (Config.UserFeatures.IsStrict()) // Provide Information : Invitation { usercontext.UIMode = ProviderPageMode.Invitation; usercontext.TargetUIMode = ProviderPageMode.None; } else if (Config.UserFeatures.IsManaged()) // Provide Information : Invitation { if (Config.UserFeatures.IsAdvertisable() && (Config.AdvertisingDays.OnFire)) { usercontext.UIMode = ProviderPageMode.Invitation; usercontext.TargetUIMode = ProviderPageMode.None; } else { usercontext.UIMode = ProviderPageMode.Bypass; usercontext.TargetUIMode = ProviderPageMode.None; } } else if (Config.UserFeatures.IsRegistrationRequired()) // Provide Information : Invitation { usercontext.UIMode = ProviderPageMode.Invitation; usercontext.TargetUIMode = ProviderPageMode.None; } else if (Config.UserFeatures.IsRegistrationMixed()) // Provide Registration { usercontext.UIMode = ProviderPageMode.Registration; usercontext.TargetUIMode = ProviderPageMode.None; } else if (Config.UserFeatures.IsRegistrationAllowed()) // Provide Registration { if (Config.UserFeatures.IsAdvertisable() && (Config.AdvertisingDays.OnFire)) { usercontext.UIMode = ProviderPageMode.Registration; usercontext.TargetUIMode = ProviderPageMode.None; } else { usercontext.UIMode = ProviderPageMode.Bypass; usercontext.TargetUIMode = ProviderPageMode.None; } } else if (Config.UserFeatures.IsRegistrationNotRequired()) // Bypass { usercontext.UIMode = ProviderPageMode.Bypass; usercontext.TargetUIMode = ProviderPageMode.None; } else // Error { usercontext.UIMode = ProviderPageMode.Locking; usercontext.TargetUIMode = ProviderPageMode.DefinitiveError; } Trace.TraceInformation(String.Format("AuthenticationProvider:IsAvailableForUser (Not Registered) Duration : {0}", (DateTime.Now - st).ToString())); return true; } } catch (Exception ex) { Trace.TraceError(String.Format("AuthenticationProvider:IsAvailableForUser Error : {0}", ex.Message)); Log.WriteEntry(string.Format(Resources.GetString(ResourcesLocaleKind.Errors, "ErrorLoadingUserRegistration"), ex.Message), EventLogEntryType.Error, 801); throw new ExternalAuthenticationException(ex.Message, context); } } /// <summary> /// Metadata property implementation /// </summary> public IAuthenticationAdapterMetadata Metadata { get { return new AuthenticationAdapterMetadata(); } } /// <summary> /// OnAuthenticationPipelineLoad method implmentation /// </summary> public void OnAuthenticationPipelineLoad(IAuthenticationMethodConfigData configData) { DateTime st = DateTime.Now; ResourcesLocale Resources = new ResourcesLocale(CultureInfo.InstalledUICulture.LCID); if (configData.Data!= null) { if (_config == null) { try { Stream stm = configData.Data; XmlConfigSerializer xmlserializer = new XmlConfigSerializer(typeof(MFAConfig)); using (StreamReader reader = new StreamReader(stm)) { _config = (MFAConfig)xmlserializer.Deserialize(stm); if ((!_config.OTPProvider.Enabled) && (!_config.MailProvider.Enabled) && (!_config.ExternalProvider.Enabled) && (!_config.AzureProvider.Enabled)) _config.OTPProvider.Enabled = true; // always let an active option eg : aplication in this case using (AESSystemEncryption MSIS = new AESSystemEncryption()) { _config.KeysConfig.XORSecret = MSIS.Decrypt(_config.KeysConfig.XORSecret); _config.Hosts.ActiveDirectoryHost.Password = <PASSWORD>(_config.Hosts.ActiveDirectoryHost.Password); _config.MailProvider.Password = <PASSWORD>(_config.MailProvider.Password); }; Certs.InitializeAccountsSID(_config.Hosts.ActiveDirectoryHost.DomainName, _config.Hosts.ActiveDirectoryHost.Account, _config.Hosts.ActiveDirectoryHost.Password); KeysManager.Initialize(_config); // Always Bind KeysManager Otherwise this is made in CFGUtilities.ReadConfiguration RuntimeAuthProvider.LoadProviders(_config); // Load Available providers } RuntimeRepository.MailslotServer.MailSlotMessageArrived += this.OnMessageArrived; RuntimeRepository.MailslotServer.Start(); Trace.TraceInformation(String.Format("AuthenticationProvider:OnAuthenticationPipelineLoad Duration : {0}", (DateTime.Now - st).ToString())); } catch (Exception ex) { Trace.TraceError(String.Format("AuthenticationProvider:OnAuthenticationPipelineLoad Error : {0}", ex.Message)); Log.WriteEntry(string.Format(Resources.GetString(ResourcesLocaleKind.Errors, "ErrorLoadingConfigurationFile"), ex.Message), EventLogEntryType.Error, 900); throw new ExternalAuthenticationException(); } } } else { Trace.TraceError(String.Format("AuthenticationProvider:OnAuthenticationPipelineLoad Error : 900")); Log. WriteEntry(Resources.GetString(ResourcesLocaleKind.Errors, "ErrorLoadingConfigurationFileNotFound"), EventLogEntryType.Error, 900); throw new ExternalAuthenticationException(); } } /// <summary> /// OnAuthenticationPipelineUnload method implementation /// </summary> public void OnAuthenticationPipelineUnload() { _config = null; } /// <summary> /// OnError method implementation /// </summary> public IAdapterPresentation OnError(HttpListenerRequest request, ExternalAuthenticationException ex) { return null; // Do not present an adapter let default adfs error handling } /// <summary> /// TryEndAuthentication method implementation /// </summary> public IAdapterPresentation TryEndAuthentication(IAuthenticationContext context, IProofData proofData, HttpListenerRequest request, out Claim[] claims) { claims = null; IAdapterPresentation result = null; AuthenticationContext usercontext = new AuthenticationContext(context) { UIMessage = string.Empty }; ProviderPageMode ui = usercontext.UIMode; switch (ui) { case ProviderPageMode.Identification: result = TryIdentification(usercontext, context, proofData, request, out claims); break; case ProviderPageMode.Registration: // User self registration and enable usercontext.WizContext = WizardContextMode.Registration; result = TryRegistration(usercontext, context, proofData, request, out claims); break; case ProviderPageMode.Invitation: // admministrative user registration and let disabled usercontext.WizContext = WizardContextMode.Invitation; result = TryInvitation(usercontext, context, proofData, request, out claims); break; case ProviderPageMode.Activation: // Ask to enable result = TryActivation(usercontext, context, proofData, request, out claims); break; case ProviderPageMode.ManageOptions: // Manage Options usercontext.WizContext = WizardContextMode.ManageOptions; result = TryManageOptions(usercontext, context, proofData, request, out claims); break; case ProviderPageMode.SelectOptions: result = TrySelectOptions(usercontext, context, proofData, request, out claims); break; case ProviderPageMode.ChooseMethod: result = TryChooseMethod(usercontext, context, proofData, request, out claims); break; case ProviderPageMode.ChangePassword: result = TryChangePassword(usercontext, context, proofData, request, out claims); break; case ProviderPageMode.Bypass: result = TryBypass(usercontext, context, proofData, request, out claims); break; case ProviderPageMode.Locking: result = TryLocking(usercontext, context, proofData, request, out claims); break; case ProviderPageMode.ShowQRCode: result = TryShowQRCode(usercontext, context, proofData, request, out claims); break; case ProviderPageMode.SendAuthRequest: result = TrySendCodeRequest(usercontext, context, proofData, request, out claims); break; case ProviderPageMode.SendAdministrativeRequest: result = TrySendAdministrativeRequest(usercontext, context, proofData, request, out claims); break; case ProviderPageMode.SendKeyRequest: result = TrySendKeyRequest(usercontext, context, proofData, request, out claims); break; case ProviderPageMode.EnrollOTP: result = TryEnrollOTP(usercontext, context, proofData, request, out claims); break; case ProviderPageMode.EnrollEmail: result = TryEnrollEmail(usercontext, context, proofData, request, out claims); break; case ProviderPageMode.EnrollPhone: result = TryEnrollPhone(usercontext, context, proofData, request, out claims); break; case ProviderPageMode.EnrollBiometrics: result = TryEnrollBio(usercontext, context, proofData, request, out claims); break; case ProviderPageMode.EnrollPin: result = TryEnrollPinCode(usercontext, context, proofData, request, out claims); break; } return result; } #endregion #region IAuthenticationAdapter custom implementation /// <summary> /// TryIdentification method implementation /// </summary> private IAdapterPresentation TryIdentification(AuthenticationContext usercontext, IAuthenticationContext context, IProofData proofData, HttpListenerRequest request, out Claim[] claims) { ResourcesLocale Resources = new ResourcesLocale(usercontext.Lcid); claims = null; IAdapterPresentation result = null; usercontext.KeyChanged = false; try { string totp = proofData.Properties["totp"].ToString(); bool options = proofData.Properties.TryGetValue("options", out object opt); bool pincode = proofData.Properties.TryGetValue("pincode", out object pin); int lnk = Convert.ToInt32(proofData.Properties["lnk"].ToString()); if (lnk == 0) { if (usercontext.CurrentRetries >= Config.MaxRetries) { usercontext.UIMode = ProviderPageMode.Locking; return new AdapterPresentation(this, context, Resources.GetString(ResourcesLocaleKind.Errors, "ErrorInvalidIdentificationRestart"), ProviderPageMode.DefinitiveError); } if(DateTime.Now.ToUniversalTime() > usercontext.LogonDate.AddSeconds(Convert.ToDouble(Config.DeliveryWindow)).ToUniversalTime()) { usercontext.UIMode = ProviderPageMode.Locking; return new AdapterPresentation(this, context, Resources.GetString(ResourcesLocaleKind.Errors, "ErrorValidationTimeWindowElapsed"), ProviderPageMode.DefinitiveError); } if (!Utilities.CheckForReplay(Config, usercontext, request, Convert.ToInt32(totp))) { usercontext.UIMode = ProviderPageMode.Locking; return new AdapterPresentation(this, context, Resources.GetString(ResourcesLocaleKind.Errors, "ErrorReplayToken"), ProviderPageMode.DefinitiveError); } try { if ((int)AuthenticationResponseKind.Error!= SetAuthenticationResult(usercontext, totp)) { if (pincode) { if (Convert.ToInt32(pin) < 0) pin = Config.DefaultPin; if (Convert.ToInt32(pin)!= usercontext.PinCode) { if (usercontext.CurrentRetries >= Config.MaxRetries) { usercontext.UIMode = ProviderPageMode.Locking; return new AdapterPresentation(this, context, Resources.GetString(ResourcesLocaleKind.Errors, "ErrorInvalidIdentificationRestart"), ProviderPageMode.DefinitiveError); } else { usercontext.UIMode = ProviderPageMode.Identification; return new AdapterPresentation(this, context, Resources.GetString(ResourcesLocaleKind.Errors, "ErrorInvalidIdentificationRetry"), false); } } } claims = new Claim[] { GetAuthMethodClaim(usercontext.SelectedMethod) }; if (options) { usercontext.UIMode = ProviderPageMode.SelectOptions; return new AdapterPresentation(this, context); } else if ((usercontext.FirstChoiceMethod!= PreferredMethod.Choose) && (usercontext.FirstChoiceMethod!= PreferredMethod.None)) { IExternalProvider prov = RuntimeAuthProvider.GetProvider(usercontext.FirstChoiceMethod); if ((prov!= null) && (prov.ForceEnrollment!= ForceWizardMode.Disabled)) { if (usercontext.FirstChoiceMethod!= usercontext.PreferredMethod) { switch (usercontext.FirstChoiceMethod) { case PreferredMethod.Code: usercontext.WizContext = WizardContextMode.ForceWizard; usercontext.UIMode = ProviderPageMode.EnrollOTP; break; case PreferredMethod.Email: usercontext.WizContext = WizardContextMode.ForceWizard; usercontext.UIMode = ProviderPageMode.EnrollEmail; break; case PreferredMethod.External: usercontext.WizContext = WizardContextMode.ForceWizard; usercontext.UIMode = ProviderPageMode.EnrollPhone; break; case PreferredMethod.Biometrics: usercontext.WizContext = WizardContextMode.ForceWizard; usercontext.UIMode = ProviderPageMode.EnrollBiometrics; break; } return new AdapterPresentation(this, context); } } } } else { if (usercontext.CurrentRetries >= Config.MaxRetries) { usercontext.UIMode = ProviderPageMode.Locking; return new AdapterPresentation(this, context, Resources.GetString(ResourcesLocaleKind.Errors, "ErrorInvalidIdentificationRestart"), ProviderPageMode.DefinitiveError); } else { usercontext.UIMode = ProviderPageMode.Identification; return new AdapterPresentation(this, context, Resources.GetString(ResourcesLocaleKind.Errors, "ErrorInvalidIdentificationRetry"), false); } } } catch (CryptographicException cex) { usercontext.UIMode = ProviderPageMode.Locking; Log.WriteEntry(string.Format(Resources.GetString(ResourcesLocaleKind.Errors, "ErrorAuthenticating"), cex.Message), EventLogEntryType.Error, 10000); return new AdapterPresentation(this, context, Resources.GetString(ResourcesLocaleKind.Errors, "ErrorInvalidIdentificationRestart"), ProviderPageMode.DefinitiveError); } } else { if (usercontext.FirstChoiceMethod==PreferredMethod.Choose) usercontext.FirstChoiceMethod = usercontext.PreferredMethod; usercontext.UIMode = ProviderPageMode.ChooseMethod; return new AdapterPresentation(this, context); } } catch (Exception ex) { throw new ExternalAuthenticationException(usercontext.UPN + " : " + ex.Message, context); } return result; } /// <summary> /// TryManageOptions method implementation /// </summary> private IAdapterPresentation TryManageOptions(AuthenticationContext usercontext, IAuthenticationContext context, IProofData proofData, HttpListenerRequest request, out Claim[] claims) { ResourcesLocale Resources = new ResourcesLocale(usercontext.Lcid); claims = new Claim[] { GetAuthMethodClaim(usercontext.SelectedMethod) }; IAdapterPresentation result = null; usercontext.KeyChanged = false; try { int btnclicked = Convert.ToInt32(proofData.Properties["btnclicked"].ToString()); bool options = proofData.Properties.TryGetValue("disablemfa", out object opt); usercontext.Enabled =!options; usercontext.KeyChanged = false; switch (btnclicked) { case 1: // OK { string error = string.Empty; if (proofData.Properties.ContainsKey("selectopt")) { PreferredMethod m = (PreferredMethod)Convert.ToInt32(proofData.Properties["selectopt"].ToString()); usercontext.PreferredMethod = m; } try { ValidateUserOptions(usercontext, context, proofData, Resources, true); } catch (Exception ex) { error = ex.Message; return new AdapterPresentation(this, context, ex.Message, false); } RuntimeRepository.SetMFAUser(Config, (MFAUser)usercontext, usercontext.KeyStatus!= SecretKeyStatus.Success); usercontext.UIMode = ProviderPageMode.SelectOptions; result = new AdapterPresentation(this, context, Resources.GetString(ResourcesLocaleKind.Informations, "InfosConfigurationModified")); break; } case 2: // Cancel { usercontext.UIMode = ProviderPageMode.SelectOptions; result = new AdapterPresentation(this, context); break; } case 3: { usercontext.WizPageID = 0; usercontext.WizContext = WizardContextMode.ManageOptions; usercontext.UIMode = ProviderPageMode.EnrollOTP; GetAuthenticationData(usercontext, PreferredMethod.Code); result = new AdapterPresentation(this, context, ProviderPageMode.ManageOptions); break; } case 4: { usercontext.WizPageID = 0; usercontext.WizContext = WizardContextMode.ManageOptions; usercontext.UIMode = ProviderPageMode.EnrollEmail; GetAuthenticationData(usercontext, PreferredMethod.Email); result = new AdapterPresentation(this, context, ProviderPageMode.ManageOptions); break; } case 5: { usercontext.WizPageID = 0; usercontext.WizContext = WizardContextMode.ManageOptions; usercontext.UIMode = ProviderPageMode.EnrollPhone; GetAuthenticationData(usercontext, PreferredMethod.External); result = new AdapterPresentation(this, context, ProviderPageMode.ManageOptions); break; } case 6: { usercontext.WizPageID = 0; usercontext.WizContext = WizardContextMode.ManageOptions; usercontext.UIMode = ProviderPageMode.EnrollBiometrics; GetAuthenticationData(usercontext, PreferredMethod.Biometrics); result = new AdapterPresentation(this, context, ProviderPageMode.ManageOptions); break; } case 7: { usercontext.WizPageID = 0; usercontext.WizContext = WizardContextMode.ManageOptions; usercontext.UIMode = ProviderPageMode.EnrollPin; GetAuthenticationData(usercontext, PreferredMethod.Pin); result = new AdapterPresentation(this, context, ProviderPageMode.ManageOptions); break; } default: // Option frame changed { string error = string.Empty; try { ValidateUserOptions(usercontext, context, proofData, Resources, true); } catch (Exception ex) { error = ex.Message; } usercontext.UIMode = ProviderPageMode.ManageOptions; if (string.IsNullOrEmpty(error)) result = new AdapterPresentation(this, context); else result = new AdapterPresentation(this, context, error, false); break; } } } catch (Exception ex) { throw new ExternalAuthenticationException(usercontext.UPN + " : " + ex.Message, context); } return result; } /// <summary> /// TryRegistration method implementation /// </summary> private IAdapterPresentation TryRegistration(AuthenticationContext usercontext, IAuthenticationContext context, IProofData proofData, HttpListenerRequest request, out Claim[] claims) { ResourcesLocale Resources = new ResourcesLocale(usercontext.Lcid); claims = new Claim[] { GetAuthMethodClaim(usercontext.SelectedMethod) }; IAdapterPresentation result = null; usercontext.KeyChanged = false; try { int isprovider = Convert.ToInt32(proofData.Properties["isprovider"].ToString()); int btnclicked = Convert.ToInt32(proofData.Properties["btnclicked"].ToString()); bool skipwizard = (btnclicked==6); usercontext.KeyChanged = false; switch (isprovider) { case (int)PreferredMethod.Choose: { if (btnclicked == 1) // Initial Cancel Registration { usercontext.UIMode = ProviderPageMode.Bypass; result = new AdapterPresentation(this, context); } else if (btnclicked == 2) { usercontext.EnrollPageStatus = EnrollPageStatus.Run; usercontext.UIMode = ProviderPageMode.Registration; result = new AdapterPresentation(this, context); } else if (btnclicked == 3) // OK { usercontext.UIMode = ProviderPageMode.Registration; usercontext.EnrollPageStatus = EnrollPageStatus.Stop; result = new AdapterPresentation(this, context); } else if (btnclicked == 5) { usercontext.UIMode = ProviderPageMode.Bypass; usercontext.Enabled = true; RuntimeRepository.SetMFAUser(Config, (MFAUser)usercontext, usercontext.KeyStatus!= SecretKeyStatus.Success); result = new AdapterPresentation(this, context, Resources.GetString(ResourcesLocaleKind.Informations, "InfosConfigurationModified")); } else if (btnclicked == 6) { usercontext.UIMode = ProviderPageMode.Registration; usercontext.EnrollPageStatus = EnrollPageStatus.Run; result = new AdapterPresentation(this, context); } else if (btnclicked == 7) { usercontext.UIMode = ProviderPageMode.Locking; result = new AdapterPresentation(this, context, ProviderPageMode.DefinitiveError); } break; } case (int)PreferredMethod.Code: { usercontext.WizPageID = 0; usercontext.UIMode = ProviderPageMode.EnrollOTP; result = new AdapterPresentation(this, context, ProviderPageMode.Registration); break; } case (int)PreferredMethod.Email: { usercontext.WizPageID = 0; if (skipwizard) // Skip { usercontext.UIMode = ProviderPageMode.Registration; usercontext.EnrollPageID = PreferredMethod.Email; result = new AdapterPresentation(this, context); } else { usercontext.UIMode = ProviderPageMode.EnrollEmail; result = new AdapterPresentation(this, context, ProviderPageMode.Registration); } break; } case (int)PreferredMethod.External: { usercontext.WizPageID = 0; if (skipwizard) // Skip { usercontext.UIMode = ProviderPageMode.Registration; usercontext.EnrollPageID = PreferredMethod.External; result = new AdapterPresentation(this, context); } else { usercontext.UIMode = ProviderPageMode.EnrollPhone; result = new AdapterPresentation(this, context, ProviderPageMode.Registration); } break; } case (int)PreferredMethod.Biometrics: { usercontext.WizPageID = 0; if (skipwizard) // Skip { usercontext.UIMode = ProviderPageMode.Registration; usercontext.EnrollPageID = PreferredMethod.Biometrics; result = new AdapterPresentation(this, context); } else { usercontext.UIMode = ProviderPageMode.EnrollBiometrics; result = new AdapterPresentation(this, context, ProviderPageMode.Registration); } break; } case (int)PreferredMethod.Pin: { usercontext.WizPageID = 0; if (skipwizard) // Skip { usercontext.UIMode = ProviderPageMode.Registration; usercontext.EnrollPageID = PreferredMethod.Pin; result = new AdapterPresentation(this, context); } else { usercontext.UIMode = ProviderPageMode.EnrollPin; result = new AdapterPresentation(this, context, ProviderPageMode.Registration); } break; } case (int)PreferredMethod.None: usercontext.UIMode = ProviderPageMode.Registration; usercontext.EnrollPageStatus = EnrollPageStatus.Stop; result = new AdapterPresentation(this, context); break; } } catch (Exception ex) { throw new ExternalAuthenticationException(usercontext.UPN + " : " + ex.Message, context); } return result; } /// <summary> /// TryInvitation method implementation /// </summary> private IAdapterPresentation TryInvitation(AuthenticationContext usercontext, IAuthenticationContext context, IProofData proofData, HttpListenerRequest request, out Claim[] claims) { ResourcesLocale Resources = new ResourcesLocale(usercontext.Lcid); claims = new Claim[] { GetAuthMethodClaim(usercontext.SelectedMethod) }; IAdapterPresentation result = null; usercontext.KeyChanged = false; try { int isprovider = Convert.ToInt32(proofData.Properties["isprovider"].ToString()); int btnclicked = Convert.ToInt32(proofData.Properties["btnclicked"].ToString()); bool skipwizard = (btnclicked == 6); usercontext.KeyChanged = false; switch (isprovider) { case (int)PreferredMethod.Choose: { if (btnclicked == 1) // Continue { usercontext.UIMode = ProviderPageMode.Bypass; result = new AdapterPresentation(this, context, ProviderPageMode.DefinitiveError); } else if (btnclicked == 2) { usercontext.EnrollPageStatus = EnrollPageStatus.Run; usercontext.UIMode = ProviderPageMode.Invitation; result = new AdapterPresentation(this, context); } else if (btnclicked == 3) // OK { usercontext.UIMode = ProviderPageMode.Invitation; usercontext.EnrollPageStatus = EnrollPageStatus.Stop; result = new AdapterPresentation(this, context); } else if (btnclicked == 5) { usercontext.UIMode = ProviderPageMode.Bypass; usercontext.Enabled = false; RuntimeRepository.SetMFAUser(Config, (MFAUser)usercontext, usercontext.KeyStatus!= SecretKeyStatus.Success); if (Config.UserFeatures.InformationsRequired()) { usercontext.UIMode = ProviderPageMode.SendAdministrativeRequest; result = new AdapterPresentation(this, context); } else { usercontext.UIMode = ProviderPageMode.Locking; result = new AdapterPresentation(this, context, Resources.GetString(ResourcesLocaleKind.Errors, "ErrorAccountNotEnabled"), ProviderPageMode.DefinitiveError); } } else if (btnclicked == 6) { usercontext.UIMode = ProviderPageMode.Invitation; usercontext.EnrollPageStatus = EnrollPageStatus.Run; result = new AdapterPresentation(this, context); } else if (btnclicked == 7) // Quit Invitation { usercontext.UIMode = ProviderPageMode.Locking; result = new AdapterPresentation(this, context, ProviderPageMode.DefinitiveError); } break; } case (int)PreferredMethod.Code: { usercontext.WizPageID = 0; usercontext.UIMode = ProviderPageMode.EnrollOTP; result = new AdapterPresentation(this, context, ProviderPageMode.Invitation); break; } case (int)PreferredMethod.Email: { usercontext.WizPageID = 0; if (skipwizard) // Skip { usercontext.UIMode = ProviderPageMode.Invitation; usercontext.EnrollPageID = PreferredMethod.Email; result = new AdapterPresentation(this, context); } else { usercontext.UIMode = ProviderPageMode.EnrollEmail; result = new AdapterPresentation(this, context, ProviderPageMode.Invitation); } break; } case (int)PreferredMethod.External: { usercontext.WizPageID = 0; if (skipwizard) // Skip { usercontext.UIMode = ProviderPageMode.Invitation; usercontext.EnrollPageID = PreferredMethod.External; result = new AdapterPresentation(this, context); } else { usercontext.UIMode = ProviderPageMode.EnrollPhone; result = new AdapterPresentation(this, context, ProviderPageMode.Invitation); } break; } case (int)PreferredMethod.Biometrics: { usercontext.WizPageID = 0; if (skipwizard) // Skip { usercontext.UIMode = ProviderPageMode.Invitation; usercontext.EnrollPageID = PreferredMethod.Biometrics; result = new AdapterPresentation(this, context); } else { usercontext.UIMode = ProviderPageMode.EnrollBiometrics; result = new AdapterPresentation(this, context, ProviderPageMode.Invitation); } break; } case (int)PreferredMethod.Pin: { usercontext.WizPageID = 0; if (skipwizard) // Skip { usercontext.UIMode = ProviderPageMode.Invitation; usercontext.EnrollPageID = PreferredMethod.Pin; result = new AdapterPresentation(this, context); } else { usercontext.UIMode = ProviderPageMode.EnrollPin; result = new AdapterPresentation(this, context, ProviderPageMode.Invitation); } break; } case (int)PreferredMethod.None: usercontext.UIMode = ProviderPageMode.Invitation; usercontext.EnrollPageStatus = EnrollPageStatus.Stop; result = new AdapterPresentation(this, context); break; } } catch (Exception ex) { throw new ExternalAuthenticationException(usercontext.UPN + " : " + ex.Message, context); } return result; } /// <summary> /// TryInvitation method implementation /// </summary> private IAdapterPresentation TryActivation(AuthenticationContext usercontext, IAuthenticationContext context, IProofData proofData, HttpListenerRequest request, out Claim[] claims) { #region Invitation ResourcesLocale Resources = new ResourcesLocale(usercontext.Lcid); claims = new Claim[] { GetAuthMethodClaim(usercontext.SelectedMethod) }; IAdapterPresentation result = null; usercontext.KeyChanged = false; try { int btnclicked = Convert.ToInt32(proofData.Properties["btnclicked"].ToString()); usercontext.UIMode = ProviderPageMode.Bypass; if (btnclicked == 2) // Enable account RuntimeRepository.EnableMFAUser(Config, (MFAUser)usercontext); result = new AdapterPresentation(this, context); } catch (Exception ex) { throw new ExternalAuthenticationException(usercontext.UPN + " : " + ex.Message, context); } return result; #endregion } /// <summary> /// TrySelectOptions method implementation /// </summary> private IAdapterPresentation TrySelectOptions(AuthenticationContext usercontext, IAuthenticationContext context, IProofData proofData, HttpListenerRequest request, out Claim[] claims) { #region Select Options claims = new Claim[] { GetAuthMethodClaim(usercontext.SelectedMethod) }; IAdapterPresentation result = null; try { usercontext.KeyChanged = false; if (Config.UserFeatures.CanAccessOptions()) { int lnk = Convert.ToInt32(proofData.Properties["lnk"].ToString()); int btnclicked = Convert.ToInt32(proofData.Properties["btnclicked"].ToString()); if (btnclicked!= 0) { usercontext.UIMode = ProviderPageMode.Bypass; result = new AdapterPresentation(this, context); } else { switch (lnk) { case 1: usercontext.WizContext = WizardContextMode.ManageOptions; usercontext.UIMode = ProviderPageMode.ManageOptions; break; case 2: usercontext.UIMode = ProviderPageMode.ChangePassword; break; case 3: usercontext.WizContext = WizardContextMode.DirectWizards; usercontext.UIMode = ProviderPageMode.EnrollOTP; GetAuthenticationData(usercontext, PreferredMethod.Code); break; case 4: usercontext.WizContext = WizardContextMode.DirectWizards; usercontext.UIMode = ProviderPageMode.EnrollBiometrics; GetAuthenticationData(usercontext, PreferredMethod.Biometrics); break; case 5: usercontext.WizContext = WizardContextMode.DirectWizards; usercontext.UIMode = ProviderPageMode.EnrollEmail; GetAuthenticationData(usercontext, PreferredMethod.Email); break; case 6: usercontext.WizContext = WizardContextMode.DirectWizards; usercontext.UIMode = ProviderPageMode.EnrollPhone; GetAuthenticationData(usercontext, PreferredMethod.External); break; case 7: usercontext.WizContext = WizardContextMode.DirectWizards; usercontext.UIMode = ProviderPageMode.EnrollPin; GetAuthenticationData(usercontext, PreferredMethod.Pin); break; } usercontext.WizPageID = 0; result = new AdapterPresentation(this, context, ProviderPageMode.SelectOptions); } } else { usercontext.UIMode = ProviderPageMode.Bypass; result = new AdapterPresentation(this, context); } } catch (Exception ex) { throw new ExternalAuthenticationException(usercontext.UPN + " : " + ex.Message, context); } return result; #endregion } /// <summary> /// TryChooseMethod procedure implementation /// </summary> private IAdapterPresentation TryChooseMethod(AuthenticationContext usercontext, IAuthenticationContext context, IProofData proofData, HttpListenerRequest request, out Claim[] claims) { #region Choose method ResourcesLocale Resources = new ResourcesLocale(usercontext.Lcid); claims = null; IAdapterPresentation result = null; usercontext.KeyChanged = false; try { int btnclicked = Convert.ToInt32(proofData.Properties["btnclicked"].ToString()); int opt = Convert.ToInt32(proofData.Properties["opt"].ToString()); bool remember = proofData.Properties.TryGetValue("remember", out object rem); if (btnclicked == 0) { switch (opt) { case 0: if (RuntimeAuthProvider.IsProviderAvailable(usercontext, PreferredMethod.Code)) { usercontext.PreferredMethod = PreferredMethod.Code; usercontext.UIMode = GetAuthenticationContextRequest(usercontext); GetAuthenticationData(usercontext, PreferredMethod.Code); result = new AdapterPresentation(this, context); if (remember) RuntimeRepository.SetMFAUser(Config, (MFAUser)usercontext, false); } else { usercontext.PreferredMethod = PreferredMethod.Choose; usercontext.UIMode = ProviderPageMode.Locking; result = new AdapterPresentation(this, context, Resources.GetString(ResourcesLocaleKind.Errors, "ErrorInvalidIdentificationRestart"), ProviderPageMode.DefinitiveError); } break; case 1: if (RuntimeAuthProvider.IsProviderAvailable(usercontext, PreferredMethod.External)) { usercontext.PreferredMethod = PreferredMethod.External; usercontext.UIMode = GetAuthenticationContextRequest(usercontext); GetAuthenticationData(usercontext, PreferredMethod.External); result = new AdapterPresentation(this, context); if (remember) RuntimeRepository.SetMFAUser(Config, (MFAUser)usercontext, false); } else { usercontext.PreferredMethod = PreferredMethod.Choose; usercontext.UIMode = ProviderPageMode.Locking; result = new AdapterPresentation(this, context, Resources.GetString(ResourcesLocaleKind.Errors, "ErrorInvalidIdentificationRestart"), ProviderPageMode.DefinitiveError); } break; case 2: if (RuntimeAuthProvider.IsProviderAvailable(usercontext, PreferredMethod.Email)) { usercontext.PreferredMethod = PreferredMethod.Email; if (Utilities.ValidateEmail(usercontext.MailAddress, true)) { usercontext.UIMode = GetAuthenticationContextRequest(usercontext); GetAuthenticationData(usercontext, PreferredMethod.Email); result = new AdapterPresentation(this, context); if (remember) RuntimeRepository.SetMFAUser(Config, (MFAUser)usercontext, false); } else { usercontext.PreferredMethod = PreferredMethod.Choose; usercontext.UIMode = ProviderPageMode.Locking; result = new AdapterPresentation(this, context, Resources.GetString(ResourcesLocaleKind.Errors, "ErrorInvalidIdentificationRestart"), ProviderPageMode.DefinitiveError); } } else { usercontext.PreferredMethod = PreferredMethod.Choose; usercontext.UIMode = ProviderPageMode.Locking; result = new AdapterPresentation(this, context, Resources.GetString(ResourcesLocaleKind.Errors, "ErrorInvalidIdentificationRestart"), ProviderPageMode.DefinitiveError); } break; case 3: if (RuntimeAuthProvider.IsProviderAvailable(usercontext, PreferredMethod.Azure)) { usercontext.PreferredMethod = PreferredMethod.Azure; usercontext.UIMode = GetAuthenticationContextRequest(usercontext); GetAuthenticationData(usercontext, PreferredMethod.Azure); result = new AdapterPresentation(this, context); if (remember) RuntimeRepository.SetMFAUser(Config, (MFAUser)usercontext, false); } else { usercontext.PreferredMethod = PreferredMethod.Choose; usercontext.UIMode = ProviderPageMode.Locking; result = new AdapterPresentation(this, context, Resources.GetString(ResourcesLocaleKind.Errors, "ErrorInvalidIdentificationRestart"), ProviderPageMode.DefinitiveError); } break; case 4: if (RuntimeAuthProvider.IsProviderAvailable(usercontext, PreferredMethod.Biometrics)) { usercontext.PreferredMethod = PreferredMethod.Biometrics; usercontext.UIMode = GetAuthenticationContextRequest(usercontext); GetAuthenticationData(usercontext, PreferredMethod.Biometrics); result = new AdapterPresentation(this, context); if (remember) RuntimeRepository.SetMFAUser(Config, (MFAUser)usercontext, false); } else { usercontext.PreferredMethod = PreferredMethod.Choose; usercontext.UIMode = ProviderPageMode.Locking; result = new AdapterPresentation(this, context, Resources.GetString(ResourcesLocaleKind.Errors, "ErrorInvalidIdentificationRestart"), ProviderPageMode.DefinitiveError); } break; default: usercontext.PreferredMethod = PreferredMethod.Choose; usercontext.UIMode = ProviderPageMode.Locking; result = new AdapterPresentation(this, context, Resources.GetString(ResourcesLocaleKind.Errors, "ErrorInvalidIdentificationRestart"), ProviderPageMode.DefinitiveError); break; } } else { usercontext.PreferredMethod = PreferredMethod.Choose; usercontext.UIMode = ProviderPageMode.Locking; result = new AdapterPresentation(this, context, Resources.GetString(ResourcesLocaleKind.Errors, "ErrorInvalidIdentificationRestart"), ProviderPageMode.DefinitiveError); } } catch (Exception ex) { throw new ExternalAuthenticationException(usercontext.UPN + " : " + ex.Message, context); } return result; #endregion } /// <summary> /// TryChangePassword method implementation /// </summary> private IAdapterPresentation TryChangePassword(AuthenticationContext usercontext, IAuthenticationContext context, IProofData proofData, HttpListenerRequest request, out Claim[] claims) { #region Change Password ResourcesLocale Resources = new ResourcesLocale(usercontext.Lcid); claims = new Claim[] { GetAuthMethodClaim(usercontext.SelectedMethod) }; IAdapterPresentation result = null; usercontext.KeyChanged = false; if (_config.CustomUpdatePassword) { try { string oldpass = proofData.Properties["oldpwdedit"].ToString(); string newpass = proofData.Properties["newpwdedit"].ToString(); string cnfpass = proofData.Properties["cnfpwdedit"].ToString(); string btnclick = proofData.Properties["btnclicked"].ToString(); if (btnclick == "1") { if (!usercontext.NotificationSent) { MailUtilities.SendNotificationByEmail(Config, (MFAUser)usercontext, Config.MailProvider, Resources.Culture); usercontext.NotificationSent = true; } if (newpass.Equals(cnfpass)) { try { usercontext.UIMode = ProviderPageMode.SelectOptions; RuntimeRepository.ChangePassword(this.Config, usercontext.UPN, oldpass, newpass); result = new AdapterPresentation(this, context, Resources.GetString(ResourcesLocaleKind.Informations, "InfosPasswordModified")); } catch (Exception ex) { usercontext.UIMode = ProviderPageMode.Locking; result = new AdapterPresentation(this, context, ex.Message, ProviderPageMode.DefinitiveError); } } else { usercontext.UIMode = ProviderPageMode.ChangePassword; result = new AdapterPresentation(this, context, Resources.GetString(ResourcesLocaleKind.Errors, "ErrorInvalidPassword"), ProviderPageMode.DefinitiveError); } } else if (btnclick == "2") { usercontext.UIMode = ProviderPageMode.SelectOptions; result = new AdapterPresentation(this, context); } } catch (Exception ex) { throw new ExternalAuthenticationException(usercontext.UPN + " : " + ex.Message, context); } } else { usercontext.UIMode = ProviderPageMode.SelectOptions; result = new AdapterPresentation(this, context); } return result; #endregion } /// <summary> /// TryBypass method implementation /// </summary> private IAdapterPresentation TryBypass(AuthenticationContext usercontext, IAuthenticationContext context, IProofData proofData, HttpListenerRequest request, out Claim[] claims) { #region TryBypass ResourcesLocale Resources = new ResourcesLocale(usercontext.Lcid); claims = new Claim[] { GetAuthMethodClaim(usercontext.SelectedMethod) }; CheckOptionsCookie(usercontext, request); try { bool pincode = proofData.Properties.TryGetValue("pincode", out object pin); if (pincode) { if (Convert.ToInt32(pin) <= 0) pin = Config.DefaultPin; if (Convert.ToInt32(pin)!= usercontext.PinCode) { usercontext.UIMode = ProviderPageMode.Locking; return new AdapterPresentation(this, context, Resources.GetString(ResourcesLocaleKind.Errors, "ErrorInvalidIdentificationRestart"), ProviderPageMode.DefinitiveError); } } usercontext.KeyChanged = false; claims = new Claim[] { GetAuthMethodClaim(usercontext.SelectedMethod) }; if (usercontext.ShowOptions) { usercontext.ShowOptions = false; usercontext.UIMode = ProviderPageMode.SelectOptions; return new AdapterPresentation(this, context); } else if ((usercontext.FirstChoiceMethod!= PreferredMethod.Choose) && (usercontext.FirstChoiceMethod!= PreferredMethod.None)) { IExternalProvider prov = RuntimeAuthProvider.GetProvider(usercontext.FirstChoiceMethod); if ((prov!= null) && ((prov.WizardEnabled) && (prov.ForceEnrollment!=ForceWizardMode.Disabled))) { if (usercontext.FirstChoiceMethod!= usercontext.PreferredMethod) { switch (usercontext.FirstChoiceMethod) { case PreferredMethod.Code: usercontext.WizContext = WizardContextMode.ForceWizard; usercontext.UIMode = ProviderPageMode.EnrollOTP; break; case PreferredMethod.Email: usercontext.WizContext = WizardContextMode.ForceWizard; usercontext.UIMode = ProviderPageMode.EnrollEmail; break; case PreferredMethod.External: usercontext.WizContext = WizardContextMode.ForceWizard; usercontext.UIMode = ProviderPageMode.EnrollPhone; break; case PreferredMethod.Biometrics: usercontext.WizContext = WizardContextMode.ForceWizard; usercontext.UIMode = ProviderPageMode.EnrollBiometrics; break; } return new AdapterPresentation(this, context); } } } } catch (Exception ex) { throw new ExternalAuthenticationException(usercontext.UPN + " : " + ex.Message, context); } return null; #endregion } /// <summary> /// TryLocking method implementation /// </summary> private IAdapterPresentation TryLocking(AuthenticationContext usercontext, IAuthenticationContext context, IProofData proofData, HttpListenerRequest request, out Claim[] claims) { #region Locking claims = new Claim[] { GetAuthMethodClaim(usercontext.SelectedMethod) }; IAdapterPresentation result = null; ResourcesLocale Resources = new ResourcesLocale(usercontext.Lcid); try { ProviderPageMode lnk = usercontext.TargetUIMode; switch (lnk) { case ProviderPageMode.DefinitiveError: string msg = usercontext.UIMessage; throw new Exception(msg); default: usercontext.UIMode = usercontext.TargetUIMode; result = new AdapterPresentation(this, context, usercontext.UIMessage); break; } } catch (Exception ex) { throw new ExternalAuthenticationException(usercontext.UPN + " : " + ex.Message, context); } return result; #endregion } /// <summary> /// TrySendCodeRequest method implementation /// </summary> private IAdapterPresentation TrySendCodeRequest(AuthenticationContext usercontext, IAuthenticationContext context, IProofData proofData, HttpListenerRequest request, out Claim[] claims) { #region Requesting Code ResourcesLocale Resources = new ResourcesLocale(usercontext.Lcid); claims = new Claim[] { GetAuthMethodClaim(usercontext.SelectedMethod) }; usercontext.DirectLogin = false; IAdapterPresentation result = null; try { if (proofData.Properties.ContainsKey("lnk")) { int lnk = Convert.ToInt32(proofData.Properties["lnk"].ToString()); if (lnk == 3) { if (usercontext.FirstChoiceMethod==PreferredMethod.Choose) usercontext.FirstChoiceMethod = usercontext.PreferredMethod; usercontext.UIMode = ProviderPageMode.ChooseMethod; return new AdapterPresentation(this, context); } } if (!usercontext.IsRemote) { if ((int)AuthenticationResponseKind.Error == PostAuthenticationRequest(usercontext)) { usercontext.UIMode = ProviderPageMode.Locking; return new AdapterPresentation(this, context, Resources.GetString(ResourcesLocaleKind.Errors, "ErrorSendingToastInformation"), ProviderPageMode.DefinitiveError); } usercontext.UIMode = ProviderPageMode.Identification; } else if (!usercontext.IsTwoWay) { if ((int)AuthenticationResponseKind.Error == PostAuthenticationRequest(usercontext)) { usercontext.UIMode = ProviderPageMode.Locking; return new AdapterPresentation(this, context, Resources.GetString(ResourcesLocaleKind.Errors, "ErrorSendingToastInformation"), ProviderPageMode.DefinitiveError); } switch (usercontext.SelectedMethod) { case AuthenticationResponseKind.SmsOneWayOTP: case AuthenticationResponseKind.SmsOneWayOTPplusPin: case AuthenticationResponseKind.SmsOTP: usercontext.UIMode = ProviderPageMode.Identification; break; case AuthenticationResponseKind.EmailOTP: usercontext.UIMode = ProviderPageMode.Identification; break; case AuthenticationResponseKind.PhoneAppOTP: usercontext.UIMode = ProviderPageMode.Identification; break; case AuthenticationResponseKind.Sample1: case AuthenticationResponseKind.Sample2: case AuthenticationResponseKind.Sample3: usercontext.UIMode = ProviderPageMode.Identification; break; default: usercontext.UIMode = ProviderPageMode.Locking; return new AdapterPresentation(this, context, Resources.GetString(ResourcesLocaleKind.Errors, "ErrorSendingToastInformation"), ProviderPageMode.DefinitiveError); } } else if (usercontext.IsTwoWay) { if ((int)AuthenticationResponseKind.Error == PostAuthenticationRequest(usercontext)) { if (usercontext.CurrentRetries >= Config.MaxRetries) { usercontext.UIMode = ProviderPageMode.Locking; return new AdapterPresentation(this, context, Resources.GetString(ResourcesLocaleKind.Errors, "ErrorSendingToastInformation"), ProviderPageMode.DefinitiveError); } else { usercontext.UIMode = ProviderPageMode.SendAuthRequest; return new AdapterPresentation(this, context, Resources.GetString(ResourcesLocaleKind.Errors, "ErrorSendingToastInformationRetry"), false); } } string valuetopass = string.Empty; bool cancall = true; if (proofData.Properties.ContainsKey("btnclicked")) { int lnk = Convert.ToInt32(proofData.Properties["btnclicked"].ToString()); if (lnk == 1) valuetopass = proofData.Properties["assertionResponse"].ToString(); else cancall = false; } if (cancall && (int)AuthenticationResponseKind.Error!= SetAuthenticationResult(usercontext, valuetopass)) { switch (usercontext.SelectedMethod) { case AuthenticationResponseKind.SmsTwoWayOTP: case AuthenticationResponseKind.SmsTwoWayOTPplusPin: usercontext.UIMode = ProviderPageMode.Bypass; break; case AuthenticationResponseKind.PhoneAppNotification: usercontext.UIMode = ProviderPageMode.Bypass; break; case AuthenticationResponseKind.PhoneAppConfirmation: case AuthenticationResponseKind.VoiceTwoWayMobile: case AuthenticationResponseKind.VoiceTwoWayMobilePlusPin: case AuthenticationResponseKind.VoiceTwoWayOffice: case AuthenticationResponseKind.VoiceTwoWayOfficePlusPin: case AuthenticationResponseKind.VoiceTwoWayAlternateMobile: case AuthenticationResponseKind.VoiceTwoWayAlternateMobilePlusPin: usercontext.UIMode = ProviderPageMode.Bypass; break; case AuthenticationResponseKind.Sample1Async: case AuthenticationResponseKind.Sample2Async: case AuthenticationResponseKind.Sample3Async: usercontext.UIMode = ProviderPageMode.Bypass; break; case AuthenticationResponseKind.Biometrics: usercontext.UIMode = ProviderPageMode.Bypass; break; default: usercontext.UIMode = ProviderPageMode.Locking; return new AdapterPresentation(this, context, Resources.GetString(ResourcesLocaleKind.Errors, "ErrorSendingToastInformation"), ProviderPageMode.DefinitiveError); } } else { if (!cancall) usercontext.CurrentRetries++; // do not passed by SetAuthenticationResult if (usercontext.CurrentRetries >= Config.MaxRetries) { usercontext.UIMode = ProviderPageMode.Locking; return new AdapterPresentation(this, context, Resources.GetString(ResourcesLocaleKind.Errors, "ErrorSendingToastInformation"), ProviderPageMode.DefinitiveError); } else { usercontext.UIMode = ProviderPageMode.SendAuthRequest; if (!cancall) { if (proofData.Properties.ContainsKey("jserror")) { string jserror = proofData.Properties["jserror"].ToString(); return new AdapterPresentation(this, context, jserror, false); } else return new AdapterPresentation(this, context, Resources.GetString(ResourcesLocaleKind.Errors, "ErrorSendingToastInformationRetry"), false); } else return new AdapterPresentation(this, context, Resources.GetString(ResourcesLocaleKind.Errors, "ErrorSendingToastInformationRetry"), false); } } } result = new AdapterPresentation(this, context); } catch (Exception ex) { throw new ExternalAuthenticationException(usercontext.UPN + " : " + ex.Message, context); } return result; #endregion } /// <summary> /// TrySendAdministrativeRequest method implementation /// </summary> private IAdapterPresentation TrySendAdministrativeRequest(AuthenticationContext usercontext, IAuthenticationContext context, IProofData proofData, HttpListenerRequest request, out Claim[] claims) { #region Invitation Request ResourcesLocale Resources = new ResourcesLocale(usercontext.Lcid); claims = new Claim[] { GetAuthMethodClaim(usercontext.SelectedMethod) }; IAdapterPresentation result = null; try { usercontext.Notification = (int)PostInscriptionRequest(usercontext, (MFAUser)usercontext); if (usercontext.Notification == (int)AuthenticationResponseKind.Error) { usercontext.UIMode = ProviderPageMode.Locking; return new AdapterPresentation(this, context, Resources.GetString(ResourcesLocaleKind.Errors, "ErrorSendingToastInformation"), ProviderPageMode.DefinitiveError); } usercontext.Notification = (int)this.SetInscriptionResult(usercontext, (MFAUser)usercontext); if (usercontext.Notification == (int)AuthenticationResponseKind.EmailForInscription) { // Store Account as disabled and reload it usercontext.Enabled = false; MFAUser reg = RuntimeRepository.SetMFAUser(Config, (MFAUser)usercontext, false); usercontext.Assign(reg); if (Config.UserFeatures.IsMFANotRequired() || Config.UserFeatures.IsMFAAllowed()) // Bypass { usercontext.UIMode = ProviderPageMode.Bypass; result = new AdapterPresentation(this, context, Resources.GetString(ResourcesLocaleKind.Errors, "ErrorAccountAuthorized"), ProviderPageMode.Bypass); } else // Error Not Enabled { usercontext.UIMode = ProviderPageMode.Locking; result = new AdapterPresentation(this, context, Resources.GetString(ResourcesLocaleKind.Html, "ErrorAccountNotEnabled"), ProviderPageMode.DefinitiveError); } } else // Error { usercontext.UIMode = ProviderPageMode.Locking; return new AdapterPresentation(this, context, Resources.GetString(ResourcesLocaleKind.Errors, "ErrorSendingToastInformation"), ProviderPageMode.DefinitiveError); } } catch (Exception ex) { throw new ExternalAuthenticationException(usercontext.UPN + " : " + ex.Message, context); } return result; #endregion } /// <summary> /// TrySendKeyRequest implementation /// </summary> private IAdapterPresentation TrySendKeyRequest(AuthenticationContext usercontext, IAuthenticationContext context, IProofData proofData, HttpListenerRequest request, out Claim[] claims) { #region Sendkey Request ResourcesLocale Resources = new ResourcesLocale(usercontext.Lcid); claims = new Claim[] { GetAuthMethodClaim(usercontext.SelectedMethod) }; IAdapterPresentation result = null; try { usercontext.Notification = (int)this.PostSecretKeyRequest(usercontext); if (usercontext.Notification == (int)AuthenticationResponseKind.Error) { usercontext.UIMode = ProviderPageMode.Locking; result = new AdapterPresentation(this, context, Resources.GetString(ResourcesLocaleKind.Errors, "ErrorSendingToastInformation"), ProviderPageMode.DefinitiveError); } usercontext.Notification = (int)this.SetSecretKeyResult(usercontext); if (usercontext.Notification == (int)AuthenticationResponseKind.EmailForKey) { usercontext.UIMode = usercontext.TargetUIMode; result = new AdapterPresentation(this, context); } else { usercontext.UIMode = ProviderPageMode.Locking; return new AdapterPresentation(this, context, Resources.GetString(ResourcesLocaleKind.Errors, "ErrorSendingToastInformation"), ProviderPageMode.DefinitiveError); } } catch (Exception ex) { throw new ExternalAuthenticationException(usercontext.UPN + " : " + ex.Message, context); } return result; #endregion } /// <summary> /// TryShowQRCode method implementation /// </summary> private IAdapterPresentation TryShowQRCode(AuthenticationContext usercontext, IAuthenticationContext context, IProofData proofData, HttpListenerRequest request, out Claim[] claims) { #region Show QR Code claims = new Claim[] { GetAuthMethodClaim(usercontext.SelectedMethod) }; IAdapterPresentation result = null; try { usercontext.KeyChanged = false; if (usercontext.Enabled) { usercontext.UIMode = ProviderPageMode.ManageOptions; } else { usercontext.UIMode = ProviderPageMode.Invitation; } result = new AdapterPresentation(this, context); } catch (Exception ex) { throw new ExternalAuthenticationException(usercontext.UPN + " : " + ex.Message, context); } return result; #endregion } /// <summary> /// TryEnrollOTP implementation /// </summary> private IAdapterPresentation TryEnrollOTP(AuthenticationContext usercontext, IAuthenticationContext context, IProofData proofData, HttpListenerRequest request, out Claim[] claims) { ResourcesLocale Resources = new ResourcesLocale(usercontext.Lcid); claims = new Claim[] { GetAuthMethodClaim(usercontext.SelectedMethod) }; usercontext.FirstChoiceMethod = PreferredMethod.Choose; try { int btnclicked = Convert.ToInt32(proofData.Properties["btnclicked"].ToString()); bool remember = proofData.Properties.TryGetValue("remember", out object rem); usercontext.KeyChanged = false; switch (btnclicked) { case 1: // Cancel if (usercontext.TargetUIMode == ProviderPageMode.Registration) { usercontext.UIMode = ProviderPageMode.Registration; } else if (usercontext.TargetUIMode == ProviderPageMode.Invitation) { usercontext.UIMode = ProviderPageMode.Invitation; } else if (usercontext.TargetUIMode == ProviderPageMode.ManageOptions) { usercontext.UIMode = ProviderPageMode.ManageOptions; } else usercontext.UIMode = ProviderPageMode.SelectOptions; return new AdapterPresentation(this, context); case 2: // Next Button usercontext.WizPageID = 1; usercontext.KeyStatus = SecretKeyStatus.Success; if (remember) usercontext.PreferredMethod = PreferredMethod.Code; SetProviderOverrideOption(usercontext, context, proofData, PreferredMethod.Code); ValidateProviderManagementUrl(usercontext, context, proofData, PreferredMethod.Code); if (!usercontext.NotificationSent) { MailUtilities.SendNotificationByEmail(Config, (MFAUser)usercontext, Config.MailProvider, Resources.Culture); usercontext.NotificationSent = true; } return new AdapterPresentation(this, context); case 3: // Code verification try { if ((int)AuthenticationResponseKind.Error == PostAuthenticationRequest(usercontext, PreferredMethod.Code)) { usercontext.WizPageID = 4; usercontext.UIMode = ProviderPageMode.EnrollOTP; return new AdapterPresentation(this, context, Resources.GetString(ResourcesLocaleKind.Html, "HtmlLabelVERIFYOTPError"), false); } else { usercontext.WizPageID = 2; usercontext.UIMode = ProviderPageMode.EnrollOTP; return new AdapterPresentation(this, context); } } catch (Exception ex) { usercontext.UIMode = ProviderPageMode.EnrollOTP; usercontext.WizPageID = 0; return new AdapterPresentation(this, context, ex.Message, false); } case 4: // Code validation string totp = proofData.Properties["totp"].ToString(); if ((int)AuthenticationResponseKind.Error!= SetAuthenticationResult(usercontext, totp, PreferredMethod.Code)) { try { ValidateUserKey(usercontext, context, proofData, Resources, true); if (usercontext.WizContext==WizardContextMode.DirectWizards) RuntimeRepository.SetMFAUser(Config, (MFAUser)usercontext, usercontext.KeyStatus!= SecretKeyStatus.Success); else if (usercontext.WizContext == WizardContextMode.Registration) { usercontext.EnrollPageID = PreferredMethod.Code; usercontext.UIMode = ProviderPageMode.Registration; } else if (usercontext.WizContext == WizardContextMode.Invitation) { usercontext.EnrollPageID = PreferredMethod.Code; usercontext.UIMode = ProviderPageMode.Invitation; } else usercontext.UIMode = ProviderPageMode.EnrollOTP; usercontext.WizPageID = 3; return new AdapterPresentation(this, context, RuntimeAuthProvider.GetProvider(PreferredMethod.Code).GetUIEnrollValidatedLabel(usercontext), true); } catch (Exception) { usercontext.UIMode = ProviderPageMode.EnrollOTP; usercontext.WizPageID = 4; return new AdapterPresentation(this, context, Resources.GetString(ResourcesLocaleKind.Html, "HtmlLabelVERIFYOTPError"), false); } } else { usercontext.WizPageID = 4; usercontext.UIMode = ProviderPageMode.EnrollOTP; return new AdapterPresentation(this, context, Resources.GetString(ResourcesLocaleKind.Html, "HtmlLabelVERIFYOTPError"), false); } } } catch (Exception ex) { if (usercontext.TargetUIMode == ProviderPageMode.Registration) { usercontext.UIMode = ProviderPageMode.Registration; usercontext.TargetUIMode = ProviderPageMode.Bypass; } else if (usercontext.TargetUIMode == ProviderPageMode.Invitation) { usercontext.UIMode = ProviderPageMode.Invitation; if (Config.UserFeatures.IsMFARequired()) usercontext.TargetUIMode = ProviderPageMode.Locking; else usercontext.TargetUIMode = ProviderPageMode.Bypass; } else { usercontext.UIMode = ProviderPageMode.EnrollOTP; usercontext.WizPageID = 0; } return new AdapterPresentation(this, context, ex.Message, false); } return null; } /// <summary> /// TryEnrollEmail implementation /// </summary> private IAdapterPresentation TryEnrollEmail(AuthenticationContext usercontext, IAuthenticationContext context, IProofData proofData, HttpListenerRequest request, out Claim[] claims) { ResourcesLocale Resources = new ResourcesLocale(usercontext.Lcid); claims = new Claim[] { GetAuthMethodClaim(usercontext.SelectedMethod) }; usercontext.FirstChoiceMethod = PreferredMethod.Choose; try { int btnclicked = Convert.ToInt32(proofData.Properties["btnclicked"].ToString()); bool remember = proofData.Properties.TryGetValue("remember", out object rem); usercontext.KeyChanged = false; switch (btnclicked) { case 0: usercontext.WizPageID = 0; // Get Email return new AdapterPresentation(this, context); case 1: // Cancel if (usercontext.TargetUIMode == ProviderPageMode.Registration) { usercontext.UIMode = ProviderPageMode.Registration; } else if (usercontext.TargetUIMode == ProviderPageMode.Invitation) { usercontext.UIMode = ProviderPageMode.Invitation; } else if (usercontext.TargetUIMode == ProviderPageMode.ManageOptions) { usercontext.UIMode = ProviderPageMode.ManageOptions; } else usercontext.UIMode = ProviderPageMode.SelectOptions; return new AdapterPresentation(this, context); case 2: // Next Button try { usercontext.WizPageID = 1; // Goto Donut ValidateUserEmail(usercontext, context, proofData, Resources, true); if (remember) usercontext.PreferredMethod = PreferredMethod.Email; SetProviderOverrideOption(usercontext, context, proofData, PreferredMethod.Email); ValidateProviderManagementUrl(usercontext, context, proofData, PreferredMethod.Email); if (!usercontext.NotificationSent) { MailUtilities.SendNotificationByEmail(Config, (MFAUser)usercontext, Config.MailProvider, Resources.Culture); usercontext.NotificationSent = true; } return new AdapterPresentation(this, context); } catch (Exception ex) { usercontext.UIMode = ProviderPageMode.EnrollEmail; usercontext.WizPageID = 0; return new AdapterPresentation(this, context, ex.Message, false); } case 3: // Code Validation Donut try { ValidateUserEmail(usercontext, context, proofData, Resources, true); IExternalProvider prov = RuntimeAuthProvider.GetProvider(PreferredMethod.Email); AuthenticationResponseKind kd = prov.GetOverrideMethod(usercontext); if (prov.SetSelectedAuthenticationMethod(usercontext, kd, true)) { if ((int)AuthenticationResponseKind.Error == PostAuthenticationRequest(usercontext, PreferredMethod.Email)) { usercontext.WizPageID = 4; usercontext.UIMode = ProviderPageMode.EnrollEmail; return new AdapterPresentation(this, context, Resources.GetString(ResourcesLocaleKind.Html, "HtmlLabelVERIFYOTPError"), false); } else { if (!usercontext.IsRemote) //??? { usercontext.WizPageID = 2; } else if (!usercontext.IsTwoWay) { usercontext.WizPageID = 2; } else { // Not very usefull for email provider, because OneWay transmission, but if you implement an IExternalProvider of Email Kind, you can make it TwoWay if ((int)AuthenticationResponseKind.Error!= SetAuthenticationResult(usercontext, string.Empty, PreferredMethod.Email)) { if (usercontext.WizContext == WizardContextMode.DirectWizards) RuntimeRepository.SetMFAUser(Config, (MFAUser)usercontext, false); else if (usercontext.WizContext == WizardContextMode.Registration) { usercontext.EnrollPageID = PreferredMethod.Email; usercontext.UIMode = ProviderPageMode.Registration; } else if (usercontext.WizContext == WizardContextMode.Invitation) { usercontext.EnrollPageID = PreferredMethod.Email; usercontext.UIMode = ProviderPageMode.Invitation; } else usercontext.UIMode = ProviderPageMode.EnrollEmail; usercontext.WizPageID = 3; } else { usercontext.UIMode = ProviderPageMode.EnrollEmail; usercontext.WizPageID = 4; } } return new AdapterPresentation(this, context, RuntimeAuthProvider.GetProvider(PreferredMethod.Email).GetUIEnrollValidatedLabel(usercontext), true); } } else { usercontext.WizPageID = 4; usercontext.UIMode = ProviderPageMode.EnrollEmail; return new AdapterPresentation(this, context, Resources.GetString(ResourcesLocaleKind.Html, "HtmlLabelVERIFYOTPError"), false); } } catch (Exception ex) { usercontext.UIMode = ProviderPageMode.EnrollEmail; usercontext.WizPageID = 0; return new AdapterPresentation(this, context, ex.Message, false); } case 4: // Code Validation string totp = proofData.Properties["totp"].ToString(); if ((int)AuthenticationResponseKind.Error!= SetAuthenticationResult(usercontext, totp, PreferredMethod.Email)) { try { ValidateUserEmail(usercontext, context, proofData, Resources, true); if (usercontext.WizContext == WizardContextMode.DirectWizards) RuntimeRepository.SetMFAUser(Config, (MFAUser)usercontext, false); else if (usercontext.WizContext == WizardContextMode.Registration) { usercontext.EnrollPageID = PreferredMethod.Email; usercontext.UIMode = ProviderPageMode.Registration; } else if (usercontext.WizContext == WizardContextMode.Invitation) { usercontext.EnrollPageID = PreferredMethod.Email; usercontext.UIMode = ProviderPageMode.Invitation; } else usercontext.UIMode = ProviderPageMode.EnrollEmail; usercontext.WizPageID = 3; return new AdapterPresentation(this, context, RuntimeAuthProvider.GetProvider(PreferredMethod.Email).GetUIEnrollValidatedLabel(usercontext), true); } catch (Exception) { usercontext.UIMode = ProviderPageMode.EnrollEmail; usercontext.WizPageID = 4; MFAUser reg = RuntimeRepository.GetMFAUser(Config, usercontext.UPN); // Rollback usercontext.MailAddress = reg.MailAddress; return new AdapterPresentation(this, context, Resources.GetString(ResourcesLocaleKind.Html, "HtmlLabelVERIFYOTPError"), false); } } else { usercontext.WizPageID = 4; usercontext.UIMode = ProviderPageMode.EnrollEmail; MFAUser reg = RuntimeRepository.GetMFAUser(Config, usercontext.UPN); // Rollback usercontext.MailAddress = reg.MailAddress; return new AdapterPresentation(this, context, Resources.GetString(ResourcesLocaleKind.Html, "HtmlLabelVERIFYOTPError"), false); } } } catch (Exception ex) { if (usercontext.TargetUIMode == ProviderPageMode.Registration) { usercontext.UIMode = ProviderPageMode.Registration; usercontext.TargetUIMode = ProviderPageMode.Bypass; } else if (usercontext.TargetUIMode == ProviderPageMode.Invitation) { usercontext.UIMode = ProviderPageMode.Invitation; if (Config.UserFeatures.IsMFARequired()) usercontext.TargetUIMode = ProviderPageMode.Locking; else usercontext.TargetUIMode = ProviderPageMode.Bypass; } else { usercontext.UIMode = ProviderPageMode.EnrollEmail; usercontext.WizPageID = 0; } return new AdapterPresentation(this, context, ex.Message, false); } return null; } /// <summary> /// TryEnrollPhone implementation /// </summary> private IAdapterPresentation TryEnrollPhone(AuthenticationContext usercontext, IAuthenticationContext context, IProofData proofData, HttpListenerRequest request, out Claim[] claims) { ResourcesLocale Resources = new ResourcesLocale(usercontext.Lcid); claims = new Claim[] { GetAuthMethodClaim(usercontext.SelectedMethod) }; usercontext.KeyChanged = false; usercontext.FirstChoiceMethod = PreferredMethod.Choose; try { int btnclicked = Convert.ToInt32(proofData.Properties["btnclicked"].ToString()); bool remember = proofData.Properties.TryGetValue("remember", out object rem); usercontext.KeyChanged = false; switch (btnclicked) { case 0: // Next Button usercontext.WizPageID = 0; return new AdapterPresentation(this, context); case 1: // Cancel if (usercontext.TargetUIMode == ProviderPageMode.Registration) { usercontext.UIMode = ProviderPageMode.Registration; } else if (usercontext.TargetUIMode == ProviderPageMode.Invitation) { usercontext.UIMode = ProviderPageMode.Invitation; } else if (usercontext.TargetUIMode == ProviderPageMode.ManageOptions) { usercontext.UIMode = ProviderPageMode.ManageOptions; } else usercontext.UIMode = ProviderPageMode.SelectOptions; return new AdapterPresentation(this, context); case 2: // Next Button try { usercontext.WizPageID = 1; // Goto Donut ValidateUserPhone(usercontext, context, proofData, Resources, true); if (remember) usercontext.PreferredMethod = PreferredMethod.External; SetProviderOverrideOption(usercontext, context, proofData, PreferredMethod.External); ValidateProviderManagementUrl(usercontext, context, proofData, PreferredMethod.External); if (!usercontext.NotificationSent) { MailUtilities.SendNotificationByEmail(Config, (MFAUser)usercontext, Config.MailProvider, Resources.Culture); usercontext.NotificationSent = true; } return new AdapterPresentation(this, context); } catch (Exception ex) { usercontext.UIMode = ProviderPageMode.EnrollPhone; usercontext.WizPageID = 0; return new AdapterPresentation(this, context, ex.Message, false); } case 3: // Code Validation Donut try { ValidateUserPhone(usercontext, context, proofData, Resources, true); IExternalProvider prov = RuntimeAuthProvider.GetProvider(PreferredMethod.External); AuthenticationResponseKind kd = prov.GetOverrideMethod(usercontext); if (prov.SetSelectedAuthenticationMethod(usercontext, kd, true)) { if ((int)AuthenticationResponseKind.Error == PostAuthenticationRequest(usercontext, PreferredMethod.External)) { usercontext.WizPageID = 4; usercontext.UIMode = ProviderPageMode.EnrollPhone; return new AdapterPresentation(this, context, Resources.GetString(ResourcesLocaleKind.Html, "HtmlLabelVERIFYOTPError"), false); } else { if (!usercontext.IsRemote) { usercontext.WizPageID = 2; } else if (!usercontext.IsTwoWay) { usercontext.WizPageID = 2; } else { if ((int)AuthenticationResponseKind.Error!= SetAuthenticationResult(usercontext, string.Empty, PreferredMethod.External)) { if (usercontext.WizContext == WizardContextMode.DirectWizards) RuntimeRepository.SetMFAUser(Config, (MFAUser)usercontext, false); else if (usercontext.WizContext == WizardContextMode.Registration) { usercontext.EnrollPageID = PreferredMethod.External; usercontext.UIMode = ProviderPageMode.Registration; } else if (usercontext.WizContext == WizardContextMode.Invitation) { usercontext.EnrollPageID = PreferredMethod.External; usercontext.UIMode = ProviderPageMode.Invitation; } else usercontext.UIMode = ProviderPageMode.EnrollPhone; usercontext.WizPageID = 3; } else { usercontext.UIMode = ProviderPageMode.EnrollPhone; usercontext.WizPageID = 4; } } return new AdapterPresentation(this, context, RuntimeAuthProvider.GetProvider(PreferredMethod.External).GetUIEnrollValidatedLabel(usercontext), true); } } else { usercontext.WizPageID = 4; usercontext.UIMode = ProviderPageMode.EnrollPhone; return new AdapterPresentation(this, context, Resources.GetString(ResourcesLocaleKind.Html, "HtmlLabelVERIFYOTPError"), false); } } catch (Exception ex) { usercontext.UIMode = ProviderPageMode.EnrollPhone; usercontext.WizPageID = 0; return new AdapterPresentation(this, context, ex.Message, false); } case 4: // Code Validation string totp = proofData.Properties["totp"].ToString(); if ((int)AuthenticationResponseKind.Error!= SetAuthenticationResult(usercontext, totp, PreferredMethod.External)) { try { ValidateUserPhone(usercontext, context, proofData, Resources, true); if (usercontext.WizContext==WizardContextMode.DirectWizards) RuntimeRepository.SetMFAUser(Config, (MFAUser)usercontext, false); else if (usercontext.WizContext == WizardContextMode.Registration) { usercontext.EnrollPageID = PreferredMethod.External; usercontext.UIMode = ProviderPageMode.Registration; } else if (usercontext.WizContext == WizardContextMode.Invitation) { usercontext.EnrollPageID = PreferredMethod.External; usercontext.UIMode = ProviderPageMode.Invitation; } else usercontext.UIMode = ProviderPageMode.EnrollPhone; usercontext.WizPageID = 3; return new AdapterPresentation(this, context, RuntimeAuthProvider.GetProvider(PreferredMethod.External).GetUIEnrollValidatedLabel(usercontext), true); } catch (Exception) { usercontext.UIMode = ProviderPageMode.EnrollPhone; usercontext.WizPageID = 4; MFAUser reg = RuntimeRepository.GetMFAUser(Config, usercontext.UPN); // Rollback usercontext.PhoneNumber = reg.PhoneNumber; return new AdapterPresentation(this, context, Resources.GetString(ResourcesLocaleKind.Html, "HtmlLabelVERIFYOTPError"), false); } } else { usercontext.WizPageID = 4; usercontext.UIMode = ProviderPageMode.EnrollPhone; MFAUser reg = RuntimeRepository.GetMFAUser(Config, usercontext.UPN); // Rollback usercontext.PhoneNumber = reg.PhoneNumber; return new AdapterPresentation(this, context, Resources.GetString(ResourcesLocaleKind.Html, "HtmlLabelVERIFYOTPError"), false); } } } catch (Exception ex) { if (usercontext.TargetUIMode == ProviderPageMode.Registration) { usercontext.UIMode = ProviderPageMode.Registration; usercontext.TargetUIMode = ProviderPageMode.Bypass; } else if (usercontext.TargetUIMode == ProviderPageMode.Invitation) { usercontext.UIMode = ProviderPageMode.Invitation; if (Config.UserFeatures.IsMFARequired()) usercontext.TargetUIMode = ProviderPageMode.Locking; else usercontext.TargetUIMode = ProviderPageMode.Bypass; } else { usercontext.UIMode = ProviderPageMode.EnrollPhone; usercontext.WizPageID = 0; } return new AdapterPresentation(this, context, ex.Message, false); } return null; } /// <summary> /// TryEnrollBio implementation /// </summary> private IAdapterPresentation TryEnrollBio(AuthenticationContext usercontext, IAuthenticationContext context, IProofData proofData, HttpListenerRequest request, out Claim[] claims) { ResourcesLocale Resources = new ResourcesLocale(usercontext.Lcid); claims = new Claim[] { GetAuthMethodClaim(usercontext.SelectedMethod) }; usercontext.KeyChanged = false; usercontext.FirstChoiceMethod = PreferredMethod.Choose; IExternalProvider prov = RuntimeAuthProvider.GetProvider(PreferredMethod.Biometrics); IWebAuthNProvider web = prov as IWebAuthNProvider; try { int btnclicked = Convert.ToInt32(proofData.Properties["btnclicked"].ToString()); bool remember = proofData.Properties.TryGetValue("remember", out object rem); usercontext.KeyChanged = false; switch (btnclicked) { case 0: // Next Button usercontext.WizPageID = 0; return new AdapterPresentation(this, context); case 1: // Cancel ReleaseAuthenticationData(usercontext, PreferredMethod.Biometrics); if (usercontext.TargetUIMode == ProviderPageMode.Registration) { usercontext.UIMode = ProviderPageMode.Registration; } else if (usercontext.TargetUIMode == ProviderPageMode.Invitation) { usercontext.UIMode = ProviderPageMode.Invitation; } else if (usercontext.TargetUIMode == ProviderPageMode.ManageOptions) { usercontext.UIMode = ProviderPageMode.ManageOptions; } else usercontext.UIMode = ProviderPageMode.SelectOptions; return new AdapterPresentation(this, context); case 2: // Next Button try { usercontext.WizPageID = 1; // Goto Donut if (remember) usercontext.PreferredMethod = PreferredMethod.Biometrics; SetBiometricProviderKeyManagementOption(usercontext, context, proofData); ValidateProviderManagementUrl(usercontext, context, proofData, PreferredMethod.Biometrics); GetAuthenticationData(usercontext, PreferredMethod.Biometrics); if ((int)AuthenticationResponseKind.Error!= PostAuthenticationRequest(usercontext, PreferredMethod.Biometrics)) { if (!usercontext.NotificationSent) { MailUtilities.SendNotificationByEmail(Config, (MFAUser)usercontext, Config.MailProvider, Resources.Culture); usercontext.NotificationSent = true; } return new AdapterPresentation(this, context); } else { usercontext.UIMode = ProviderPageMode.EnrollBiometrics; usercontext.WizPageID = 4; return new AdapterPresentation(this, context, Resources.GetString(ResourcesLocaleKind.Html, "HtmlLabelVERIFYOTPError"), false); } } catch (Exception ex) { usercontext.UIMode = ProviderPageMode.EnrollBiometrics; usercontext.WizPageID = 0; return new AdapterPresentation(this, context, ex.Message, false); } case 3: // Code Validation Donut try { AuthenticationResponseKind kd = prov.GetOverrideMethod(usercontext); if (prov.SetSelectedAuthenticationMethod(usercontext, kd, true)) { string jsResponse = proofData.Properties["attestationResponse"].ToString(); if ((int)AuthenticationResponseKind.Error == SetAuthenticationResult(usercontext, jsResponse, PreferredMethod.Biometrics)) { usercontext.WizPageID = 4; usercontext.UIMode = ProviderPageMode.EnrollBiometrics; return new AdapterPresentation(this, context, Resources.GetString(ResourcesLocaleKind.Html, "HtmlLabelVERIFYOTPError"), false); } else { if (usercontext.WizContext == WizardContextMode.DirectWizards) RuntimeRepository.SetMFAUser(Config, (MFAUser)usercontext, false); else if (usercontext.WizContext == WizardContextMode.Registration) { usercontext.EnrollPageID = PreferredMethod.Biometrics; usercontext.UIMode = ProviderPageMode.Registration; } else if (usercontext.WizContext == WizardContextMode.Invitation) { usercontext.EnrollPageID = PreferredMethod.Biometrics; usercontext.UIMode = ProviderPageMode.Invitation; } else usercontext.UIMode = ProviderPageMode.EnrollBiometrics; usercontext.WizPageID = 3; return new AdapterPresentation(this, context, RuntimeAuthProvider.GetProvider(PreferredMethod.Biometrics).GetUIEnrollValidatedLabel(usercontext), true); } } else { usercontext.WizPageID = 4; usercontext.UIMode = ProviderPageMode.EnrollBiometrics; return new AdapterPresentation(this, context, Resources.GetString(ResourcesLocaleKind.Html, "HtmlLabelVERIFYOTPError"), false); } } catch (Exception ex) { usercontext.UIMode = ProviderPageMode.EnrollBiometrics; usercontext.WizPageID = 4; return new AdapterPresentation(this, context, Resources.GetString(ResourcesLocaleKind.Html, "HtmlLabelVERIFYOTPError") + "<br><br><i>" + ex.Message + "</i>", false); } case 4: // Code Validation try { if ((int)AuthenticationResponseKind.Error!= SetAuthenticationResult(usercontext, string.Empty, PreferredMethod.Biometrics)) { try { if (usercontext.WizContext == WizardContextMode.DirectWizards) RuntimeRepository.SetMFAUser(Config, (MFAUser)usercontext, false); else if (usercontext.WizContext == WizardContextMode.Registration) { usercontext.EnrollPageID = PreferredMethod.Biometrics; usercontext.UIMode = ProviderPageMode.Registration; } else if (usercontext.WizContext == WizardContextMode.Invitation) { usercontext.EnrollPageID = PreferredMethod.Biometrics; usercontext.UIMode = ProviderPageMode.Invitation; } else usercontext.UIMode = ProviderPageMode.EnrollBiometrics; usercontext.WizPageID = 3; return new AdapterPresentation(this, context, RuntimeAuthProvider.GetProvider(PreferredMethod.Biometrics).GetUIEnrollValidatedLabel(usercontext), true); } catch (Exception) { usercontext.UIMode = ProviderPageMode.EnrollBiometrics; usercontext.WizPageID = 4; MFAUser reg = RuntimeRepository.GetMFAUser(Config, usercontext.UPN); // Rollback return new AdapterPresentation(this, context, Resources.GetString(ResourcesLocaleKind.Html, "HtmlLabelVERIFYOTPError"), false); } } else { usercontext.WizPageID = 4; usercontext.UIMode = ProviderPageMode.EnrollBiometrics; MFAUser reg = RuntimeRepository.GetMFAUser(Config, usercontext.UPN); // Rollback return new AdapterPresentation(this, context, Resources.GetString(ResourcesLocaleKind.Html, "HtmlLabelVERIFYOTPError"), false); } } finally { ReleaseAuthenticationData(usercontext, PreferredMethod.Biometrics); } case 5: try { string jserror = proofData.Properties["jserror"].ToString(); usercontext.WizPageID = 4; usercontext.UIMode = ProviderPageMode.EnrollBiometrics; return new AdapterPresentation(this, context, Resources.GetString(ResourcesLocaleKind.Html, "HtmlLabelVERIFYOTPError") + "<br><br><i>" + jserror + "</i>", false); } finally { ReleaseAuthenticationData(usercontext, PreferredMethod.Biometrics); } case 7: usercontext.WizPageID = 5; return new AdapterPresentation(this, context); case 8: SetBiometricProviderKeyManagementOption(usercontext, context, proofData); usercontext.WizPageID = 0; return new AdapterPresentation(this, context); } } catch (Exception ex) { ReleaseAuthenticationData(usercontext, PreferredMethod.Biometrics); if (usercontext.TargetUIMode == ProviderPageMode.Registration) { usercontext.UIMode = ProviderPageMode.Registration; usercontext.TargetUIMode = ProviderPageMode.Bypass; } else if (usercontext.TargetUIMode == ProviderPageMode.Invitation) { usercontext.UIMode = ProviderPageMode.Invitation; if (Config.UserFeatures.IsMFARequired()) usercontext.TargetUIMode = ProviderPageMode.Locking; else usercontext.TargetUIMode = ProviderPageMode.Bypass; } else { usercontext.UIMode = ProviderPageMode.EnrollBiometrics; usercontext.WizPageID = 0; } return new AdapterPresentation(this, context, ex.Message, false); } return null; } /// <summary> /// TryEnrollPinCode implementation /// </summary> private IAdapterPresentation TryEnrollPinCode(AuthenticationContext usercontext, IAuthenticationContext context, IProofData proofData, HttpListenerRequest request, out Claim[] claims) { ResourcesLocale Resources = new ResourcesLocale(usercontext.Lcid); claims = new Claim[] { GetAuthMethodClaim(usercontext.SelectedMethod) }; try { int btnclicked = Convert.ToInt32(proofData.Properties["btnclicked"].ToString()); usercontext.KeyChanged = false; switch (btnclicked) { case 1: // Cancel if (usercontext.TargetUIMode == ProviderPageMode.Registration) { usercontext.UIMode = ProviderPageMode.Registration; } else if (usercontext.TargetUIMode == ProviderPageMode.Invitation) { usercontext.UIMode = ProviderPageMode.Invitation; } else if (usercontext.TargetUIMode == ProviderPageMode.ManageOptions) { usercontext.UIMode = ProviderPageMode.ManageOptions; } else usercontext.UIMode = ProviderPageMode.SelectOptions; return new AdapterPresentation(this, context); case 2: // Next Button try { if (!usercontext.NotificationSent) { MailUtilities.SendNotificationByEmail(Config, (MFAUser)usercontext, Config.MailProvider, Resources.Culture); usercontext.NotificationSent = true; } usercontext.WizPageID = 2; if (usercontext.PinCode <= 0) usercontext.PinCode = Config.DefaultPin; ValidateUserPin(usercontext, context, proofData, Resources, true); return new AdapterPresentation(this, context); } catch (Exception ex) { usercontext.UIMode = ProviderPageMode.EnrollPin; usercontext.WizPageID = 0; return new AdapterPresentation(this, context, ex.Message, false); } case 3: // Code verification try { int totp = Convert.ToInt32(proofData.Properties["pincode"]); if (usercontext.PinCode!= totp) { usercontext.WizPageID = 4; usercontext.UIMode = ProviderPageMode.EnrollPin; return new AdapterPresentation(this, context, Resources.GetString(ResourcesLocaleKind.Html, "HtmlLabelVERIFYOTPError"), false); } else { usercontext.WizPageID = 3; usercontext.UIMode = ProviderPageMode.EnrollPin; return new AdapterPresentation(this, context, Resources.GetString(ResourcesLocaleKind.Html, "HtmlLabelVERIFYOTPSuccess"), true); } } catch (Exception ex) { return new AdapterPresentation(this, context, ex.Message, false); } case 4: // Code validation int totp2 = Convert.ToInt32(proofData.Properties["pincode"]); if (usercontext.PinCode == totp2) { try { // ValidatePINCode(totp2.ToString(), Resources, true); ValidateUserPin(usercontext, context, proofData, Resources, true); if (usercontext.WizContext == WizardContextMode.DirectWizards) RuntimeRepository.SetMFAUser(Config, (MFAUser)usercontext, false); else if (usercontext.WizContext == WizardContextMode.Registration) { usercontext.EnrollPageID = PreferredMethod.Pin; usercontext.UIMode = ProviderPageMode.Registration; } else if (usercontext.WizContext == WizardContextMode.Invitation) { usercontext.EnrollPageID = PreferredMethod.Pin; usercontext.UIMode = ProviderPageMode.Invitation; } else usercontext.UIMode = ProviderPageMode.EnrollPin; usercontext.WizPageID = 3; return new AdapterPresentation(this, context, Resources.GetString(ResourcesLocaleKind.Html, "HtmlLabelVERIFYOTPSuccess"), true); } catch (Exception) { usercontext.UIMode = ProviderPageMode.EnrollPin; MFAUser reg = RuntimeRepository.GetMFAUser(Config, usercontext.UPN); // Rollback usercontext.PinCode = reg.PIN; return new AdapterPresentation(this, context, Resources.GetString(ResourcesLocaleKind.Html, "HtmlLabelVERIFYOTPError"), false); } } else { usercontext.WizPageID = 4; usercontext.UIMode = ProviderPageMode.EnrollPin; MFAUser reg = RuntimeRepository.GetMFAUser(Config, usercontext.UPN); // Rollback usercontext.PinCode = reg.PIN; return new AdapterPresentation(this, context, Resources.GetString(ResourcesLocaleKind.Html, "HtmlLabelVERIFYOTPError"), false); } } } catch (Exception ex) { if (usercontext.TargetUIMode == ProviderPageMode.Registration) { usercontext.UIMode = ProviderPageMode.Registration; usercontext.TargetUIMode = ProviderPageMode.Bypass; } else if (usercontext.TargetUIMode == ProviderPageMode.Invitation) { usercontext.UIMode = ProviderPageMode.Invitation; if (Config.UserFeatures.IsMFARequired()) usercontext.TargetUIMode = ProviderPageMode.Locking; else usercontext.TargetUIMode = ProviderPageMode.Bypass; } else { usercontext.UIMode = ProviderPageMode.EnrollPin; usercontext.WizPageID = 1; } return new AdapterPresentation(this, context, ex.Message, false); } return null; } #endregion #region private methods /// <summary> /// ValidateUserOptions method implementation /// </summary> private void ValidateUserOptions(AuthenticationContext usercontext, IAuthenticationContext context, IProofData proofData, ResourcesLocale Resources, bool checkempty = false) { ValidateUserKey(usercontext, context, proofData, Resources, checkempty); ValidateUserEmail(usercontext, context, proofData, Resources, checkempty); ValidateUserPhone(usercontext, context, proofData, Resources, checkempty); ValidateUserPin(usercontext, context, proofData, Resources, checkempty); } /// <summary> /// ValidateUserKey method implementation /// </summary> private void ValidateUserKey(AuthenticationContext usercontext, IAuthenticationContext context, IProofData proofData, ResourcesLocale Resources, bool checkempty = false) { IExternalProvider prov = RuntimeAuthProvider.GetProviderInstance(PreferredMethod.Code); if ((prov.Enabled) && (prov.IsRequired) && (prov.IsUIElementRequired(usercontext, RequiredMethodElements.KeyParameterRequired))) { string displaykey = string.Empty; if (usercontext.KeyStatus!= SecretKeyStatus.Success) throw new Exception(Resources.GetString(ResourcesLocaleKind.Errors, "ErrorInvalidKey")); } } /// <summary> /// ValidateUserEmail method implementation /// </summary> private void ValidateUserEmail(AuthenticationContext usercontext, IAuthenticationContext context, IProofData proofData, ResourcesLocale Resources, bool checkempty = false) { IExternalProvider prov = RuntimeAuthProvider.GetProviderInstance(PreferredMethod.Email); if ((prov.Enabled) && (prov.IsUIElementRequired(usercontext, RequiredMethodElements.EmailParameterRequired))) { string email = string.Empty; if (proofData.Properties.ContainsKey("email")) { email = proofData.Properties["email"].ToString(); if (string.IsNullOrEmpty(email)) email = usercontext.MailAddress; } else email = usercontext.MailAddress; if ((prov.Enabled) && (prov.IsRequired)) ValidateEmail(email, Resources, checkempty); usercontext.MailAddress = email; } } /// <summary> /// ValidateUserPhone method implementation /// </summary> private void ValidateUserPhone(AuthenticationContext usercontext, IAuthenticationContext context, IProofData proofData, ResourcesLocale Resources, bool checkempty = false) { string phone = string.Empty; IExternalProvider prov = RuntimeAuthProvider.GetProviderInstance(PreferredMethod.External); if ((prov.Enabled) && (prov.IsUIElementRequired(usercontext, RequiredMethodElements.PhoneParameterRequired))) { if (proofData.Properties.ContainsKey("phone")) { phone = proofData.Properties["phone"].ToString(); if (string.IsNullOrEmpty(phone)) phone = usercontext.PhoneNumber; } else phone = usercontext.PhoneNumber; if ((prov.Enabled) && (prov.IsRequired)) ValidatePhoneNumber(phone, Resources, checkempty); usercontext.PhoneNumber = phone; } if ((prov.Enabled) && (prov.IsUIElementRequired(usercontext, RequiredMethodElements.ExternalParameterRequired))) { if (proofData.Properties.ContainsKey("phone")) { phone = proofData.Properties["phone"].ToString(); if (string.IsNullOrEmpty(phone)) if (prov.Enabled && prov.IsRequired) throw new ArgumentException("Invalid value!"); } usercontext.PhoneNumber = phone; } } /// <summary> /// ValidateUserPin method implementation /// </summary> private void ValidateUserPin(AuthenticationContext usercontext, IAuthenticationContext context, IProofData proofData, ResourcesLocale Resources, bool checkempty = false) { if (RuntimeAuthProvider.IsPinCodeRequired(usercontext)) { string strpin = string.Empty; if (proofData.Properties.ContainsKey("pincode")) { strpin = proofData.Properties["pincode"].ToString(); if (string.IsNullOrEmpty(strpin)) strpin = usercontext.PinCode.ToString(); } else strpin = usercontext.PinCode.ToString(); ValidatePINCode(strpin, Resources, checkempty); usercontext.PinCode = Convert.ToInt32(strpin); } } /// <summary> /// ValidateAzureUrl method implementation /// </summary> private void ValidateProviderManagementUrl(AuthenticationContext ctx, IAuthenticationContext context, IProofData proofData, PreferredMethod pageid) { if (proofData.Properties.ContainsKey("manageaccount")) { bool mgtaccount = proofData.Properties.TryGetValue("manageaccount", out object rem); switch (pageid) { case PreferredMethod.Code: // TOTP ctx.AccountManagementUrl = RuntimeAuthProvider.GetProvider(PreferredMethod.Code).GetAccountManagementUrl(ctx); break; case PreferredMethod.Email: // Email IsMethodElementRequired ctx.AccountManagementUrl = RuntimeAuthProvider.GetProvider(PreferredMethod.Email).GetAccountManagementUrl(ctx); break; case PreferredMethod.External: // external API ctx.AccountManagementUrl = RuntimeAuthProvider.GetProvider(PreferredMethod.External).GetAccountManagementUrl(ctx); break; case PreferredMethod.Azure: // Azure MFA ctx.AccountManagementUrl = RuntimeAuthProvider.GetProvider(PreferredMethod.Azure).GetAccountManagementUrl(ctx); break; } } else ctx.AccountManagementUrl = null; return; } /// <summary> /// SetProviderOverrideOption method implementation /// </summary> private void SetProviderOverrideOption(AuthenticationContext usercontext, IAuthenticationContext context, IProofData proofData, PreferredMethod method) { if (proofData.Properties.ContainsKey("optionitem")) { bool chk = proofData.Properties.TryGetValue("optionitem", out object rem); if (chk) { AuthenticationResponseKind kind = (AuthenticationResponseKind)Enum.Parse(typeof(AuthenticationResponseKind), rem.ToString()); switch (method) { case PreferredMethod.Code: // Otp RuntimeAuthProvider.GetProvider(PreferredMethod.Code).SetOverrideMethod(usercontext, kind); break; case PreferredMethod.Email: // Email RuntimeAuthProvider.GetProvider(PreferredMethod.Email).SetOverrideMethod(usercontext, kind); break; case PreferredMethod.External: // External API switch (kind) { case AuthenticationResponseKind.SmsOTP: case AuthenticationResponseKind.SmsOneWayOTP: case AuthenticationResponseKind.SmsOneWayOTPplusPin: kind = AuthenticationResponseKind.SmsOneWayOTP; break; case AuthenticationResponseKind.SmsTwoWayOTP: case AuthenticationResponseKind.SmsTwoWayOTPplusPin: kind = AuthenticationResponseKind.SmsTwoWayOTP; break; case AuthenticationResponseKind.Sample1: kind = AuthenticationResponseKind.Sample1; break; case AuthenticationResponseKind.Sample2: kind = AuthenticationResponseKind.Sample2; break; case AuthenticationResponseKind.Sample3: kind = AuthenticationResponseKind.Sample3; break; case AuthenticationResponseKind.Sample1Async: kind = AuthenticationResponseKind.Sample1Async; break; case AuthenticationResponseKind.Sample2Async: kind = AuthenticationResponseKind.Sample2Async; break; case AuthenticationResponseKind.Sample3Async: kind = AuthenticationResponseKind.Sample3Async; break; default: if (RuntimeAuthProvider.GetProvider(PreferredMethod.External).IsTwoWayByDefault) kind = AuthenticationResponseKind.SmsTwoWayOTP; else kind = AuthenticationResponseKind.SmsOneWayOTP; break; } RuntimeAuthProvider.GetProvider(PreferredMethod.External).SetOverrideMethod(usercontext, kind); break; case PreferredMethod.Azure: // Azure MFA RuntimeAuthProvider.GetProvider(PreferredMethod.Azure).SetOverrideMethod(usercontext, kind); break; } } } return; } /// <summary> /// SetBiometricProviderKeyManagementOption method implementation /// </summary> private void SetBiometricProviderKeyManagementOption(AuthenticationContext usercontext, IAuthenticationContext context, IProofData proofData) { if (proofData.Properties.ContainsKey("optionitem")) { bool chk = proofData.Properties.TryGetValue("optionitem", out object optionitem); if (chk) { if (!optionitem.Equals(Guid.Empty.ToString())) { IExternalProvider provider = RuntimeAuthProvider.GetProvider(PreferredMethod.Biometrics); IWebAuthNProvider web = provider as IWebAuthNProvider; web.RemoveUserStoredCredentials(usercontext, optionitem.ToString()); } } } } #endregion #region Providers private methods /// <summary> /// GetAuthenticationContextRequest method implmentation /// </summary> private ProviderPageMode GetAuthenticationContextRequest(AuthenticationContext usercontext) { IExternalProvider provider = RuntimeAuthProvider.GetAuthenticationProvider(Config, usercontext); if ((provider!= null) && (provider.Enabled)) { provider.GetAuthenticationContext(usercontext); usercontext.UIMode = ProviderPageMode.SendAuthRequest; } else usercontext.UIMode = ProviderPageMode.ChooseMethod; return usercontext.UIMode; } /// <summary> /// PostAuthenticationRequest method implementation /// </summary> private int PostAuthenticationRequest(AuthenticationContext usercontext, PreferredMethod method = PreferredMethod.None) { try { IExternalProvider provider = null; if (method == PreferredMethod.None) provider = RuntimeAuthProvider.GetAuthenticationProvider(Config, usercontext); else provider = RuntimeAuthProvider.GetProvider(method); if ((provider!= null) && (provider.Enabled)) { return provider.PostAuthenticationRequest(usercontext); } else return (int)AuthenticationResponseKind.Error; } catch (Exception ex) { Log.WriteEntry(string.Format("PostAuthenticationRequest Error {0} \r\n {1} \r\n {2}", usercontext.UPN, ex.Message, ex.StackTrace), EventLogEntryType.Error, 800); return (int)AuthenticationResponseKind.Error; } } /// <summary> /// SetAuthenticationResult method implementation /// </summary> public int SetAuthenticationResult(AuthenticationContext usercontext, string totp, PreferredMethod method = PreferredMethod.None) { usercontext.CurrentRetries++; try { IExternalProvider provider = null; if (method == PreferredMethod.None) provider = RuntimeAuthProvider.GetAuthenticationProvider(Config, usercontext); else provider = RuntimeAuthProvider.GetProvider(method); if ((provider!= null) && (provider.Enabled)) { int res = provider.SetAuthenticationResult(usercontext, totp); return res; } else return (int)AuthenticationResponseKind.Error; } catch (Exception ex) { Log.WriteEntry(string.Format("SetAuthenticationResult Error {0} \r\n {1} \r\n {2}", usercontext.UPN, ex.Message, ex.StackTrace), EventLogEntryType.Error, 800); return (int)AuthenticationResponseKind.Error; } } /// <summary> /// GetAuthenticationData method implementation /// </summary> public void GetAuthenticationData(AuthenticationContext ctx, PreferredMethod method = PreferredMethod.None) { IExternalProvider provider = null; if (method == PreferredMethod.None) provider = RuntimeAuthProvider.GetAuthenticationProvider(Config, ctx); else provider = RuntimeAuthProvider.GetProvider(method); if ((provider!= null) && (provider.Enabled)) provider.GetAuthenticationData(ctx); } /// <summary> /// ReleaseAuthenticationData method implementation /// </summary> public void ReleaseAuthenticationData(AuthenticationContext ctx, PreferredMethod method = PreferredMethod.None) { IExternalProvider provider = null; if (method == PreferredMethod.None) provider = RuntimeAuthProvider.GetAuthenticationProvider(Config, ctx); else provider = RuntimeAuthProvider.GetProvider(method); if ((provider!= null) && (provider.Enabled)) provider.ReleaseAuthenticationData(ctx); } #endregion #region Administrative Provider methods /// <summary> /// GetAuthenticationContextRequest method implmentation /// </summary> private ProviderPageMode GetInscriptionContextRequest(AuthenticationContext usercontext) { IExternalAdminProvider _provider = RuntimeAuthProvider.GetAdministrativeProvider(Config); if (_provider!= null) { _provider.GetInscriptionContext(usercontext); usercontext.UIMode = ProviderPageMode.SendAdministrativeRequest; } else usercontext.UIMode = ProviderPageMode.Locking; return usercontext.UIMode; } /// <summary> /// PostInscriptionRequest method implementation /// </summary> private int PostInscriptionRequest(AuthenticationContext usercontext, MFAUser registration) { try { IExternalAdminProvider _provider = RuntimeAuthProvider.GetAdministrativeProvider(Config); if (_provider!= null) return _provider.PostInscriptionRequest(usercontext); else return (int)AuthenticationResponseKind.Error; } catch (Exception ex) { Log.WriteEntry(string.Format("PostInscriptionRequest Error {0} \r\n {1} \r\n {2}", usercontext.UPN, ex.Message, ex.StackTrace), EventLogEntryType.Error, 800); return (int)AuthenticationResponseKind.Error; } } /// <summary> /// SetInscriptionResult method implementation /// </summary> public int SetInscriptionResult(AuthenticationContext usercontext, MFAUser registration) { try { IExternalAdminProvider _provider = RuntimeAuthProvider.GetAdministrativeProvider(Config); if (_provider!= null) return _provider.SetInscriptionResult(usercontext); else return (int)AuthenticationResponseKind.Error; } catch (Exception ex) { Log.WriteEntry(string.Format("SetInscriptionResult Error {0} \r\n {1} \r\n {2}", usercontext.UPN, ex.Message, ex.StackTrace), EventLogEntryType.Error, 800); return (int)AuthenticationResponseKind.Error; } } #endregion #region Secret Key Provider /// <summary> /// GetAuthenticationContextRequest method implmentation /// </summary> private ProviderPageMode GetSecretKeyContextRequest(AuthenticationContext usercontext) { IExternalAdminProvider _provider = RuntimeAuthProvider.GetAdministrativeProvider(Config); if (_provider!= null) { _provider.GetSecretKeyContext(usercontext); usercontext.UIMode = ProviderPageMode.SendKeyRequest; } else usercontext.UIMode = ProviderPageMode.Locking; return usercontext.UIMode; } /// <summary> /// PostSecretKeyRequest method implementation /// </summary> private int PostSecretKeyRequest(AuthenticationContext usercontext) { try { IExternalAdminProvider _provider = RuntimeAuthProvider.GetAdministrativeProvider(Config); if (_provider!= null) return _provider.PostSecretKeyRequest(usercontext); else return (int)AuthenticationResponseKind.Error; } catch (Exception ex) { Log.WriteEntry(string.Format("PostSecretKeyRequest Error {0} \r\n {1} \r\n {2}", usercontext.UPN, ex.Message, ex.StackTrace), EventLogEntryType.Error, 800); return (int)AuthenticationResponseKind.Error; } } /// <summary> /// SetSecretKeyResult method implementation /// </summary> public int SetSecretKeyResult(AuthenticationContext usercontext) { try { IExternalAdminProvider _provider = RuntimeAuthProvider.GetAdministrativeProvider(Config); if (_provider!= null) return _provider.SetSecretKeyResult(usercontext); else return (int)AuthenticationResponseKind.Error; } catch (Exception ex) { Log.WriteEntry(string.Format("SetSecretKeyResult Error {0} \r\n {1} \r\n {2}", usercontext.UPN, ex.Message, ex.StackTrace), EventLogEntryType.Error, 800); return (int)AuthenticationResponseKind.Error; } } #endregion #region Other Private Methods /// <summary> /// GetAuthMethodClaim method implementation /// </summary> private Claim GetAuthMethodClaim(AuthenticationResponseKind notificationStatus) { switch (notificationStatus) { case AuthenticationResponseKind.PhoneAppOTP: return new Claim("http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod", "http://schemas.microsoft.com/ws/2012/12/authmethod/otp"); case AuthenticationResponseKind.EmailOTP: return new Claim("http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod", "http://schemas.microsoft.com/ws/2012/12/authmethod/email"); case AuthenticationResponseKind.SmsOTP: return new Claim("http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod", "http://schemas.microsoft.com/ws/2012/12/authmethod/sms"); case AuthenticationResponseKind.VoiceBiometric: return new Claim("http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod", "http://schemas.microsoft.com/ws/2012/12/authmethod/voicebiometrics"); case AuthenticationResponseKind.PhoneAppNotification: return new Claim("http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod", "http://schemas.microsoft.com/ws/2012/12/authmethod/phoneappnotification"); case AuthenticationResponseKind.PhoneAppConfirmation: return new Claim("http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod", "http://schemas.microsoft.com/ws/2012/12/authmethod/phoneconfirmation"); case AuthenticationResponseKind.Kba: return new Claim("http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod", "http://schemas.microsoft.com/ws/2012/12/authmethod/kba"); case AuthenticationResponseKind.FaceID: return new Claim("http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod", "http://schemas.microsoft.com/ws/2012/12/authmethod/facebiometrics"); case AuthenticationResponseKind.WindowsHello: return new Claim("http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod", "http://schemas.microsoft.com/ws/2012/12/authmethod/windowshello"); case AuthenticationResponseKind.FIDO: return new Claim("http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod", "http://schemas.microsoft.com/ws/2012/12/authmethod/fido"); case AuthenticationResponseKind.Biometrics: return new Claim("http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod", "http://schemas.microsoft.com/ws/2012/12/authmethod/webauthN"); // Azure case AuthenticationResponseKind.SmsOneWayOTPplusPin: case AuthenticationResponseKind.SmsOneWayOTP: return new Claim("http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod", "http://schemas.microsoft.com/ws/2012/12/authmethod/smsotp"); case AuthenticationResponseKind.SmsTwoWayOTPplusPin: case AuthenticationResponseKind.SmsTwoWayOTP: return new Claim("http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod", "http://schemas.microsoft.com/ws/2012/12/authmethod/smsreply"); case AuthenticationResponseKind.VoiceTwoWayMobilePlusPin: case AuthenticationResponseKind.VoiceTwoWayMobile: case AuthenticationResponseKind.VoiceTwoWayOfficePlusPin: case AuthenticationResponseKind.VoiceTwoWayOffice: case AuthenticationResponseKind.VoiceTwoWayAlternateMobilePlusPin: case AuthenticationResponseKind.VoiceTwoWayAlternateMobile: return new Claim("http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod", "http://schemas.microsoft.com/ws/2012/12/authmethod/phoneconfirmation"); // Quiz for fun case AuthenticationResponseKind.Sample1: case AuthenticationResponseKind.Sample2: case AuthenticationResponseKind.Sample3: case AuthenticationResponseKind.Sample1Async: case AuthenticationResponseKind.Sample2Async: case AuthenticationResponseKind.Sample3Async: return new Claim("http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod", "http://schemas.microsoft.com/ws/2012/12/authmethod/otp"); default: return new Claim("http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod", "http://schemas.microsoft.com/ws/2012/12/authmethod/none"); } } /// <summary> /// ValidateEmail method implementation /// </summary> private void ValidateEmail(string email, ResourcesLocale Resources, bool checkempty = false) { try { if (!Utilities.ChedkEmailValidity(email, Config.MailProvider.AllowedDomains, Config.MailProvider.BlockedDomains, checkempty)) throw new Exception(Resources.GetString(ResourcesLocaleKind.Errors, "ErrorEmailException")); else return; } catch (Exception ex) { Log. WriteEntry(ex.Message, EventLogEntryType.Error, 800); throw ex; } } /// <summary> /// ValidateEmail method implementation /// </summary> private void ValidatePhoneNumber(string phone, ResourcesLocale Resources, bool checkempty = false) { try { if (!Utilities.ValidatePhoneNumber(phone, checkempty)) throw new Exception(Resources.GetString(ResourcesLocaleKind.Errors, "ErrorInvalidPhoneException")); else return; } catch (Exception ex) { Log. WriteEntry(ex.Message, EventLogEntryType.Error, 800); throw ex; } } /// <summary> /// ValidatePINCode method implementation /// </summary> private void ValidatePINCode(string strpin, ResourcesLocale Resources, bool checkempty = false) { try { if (checkempty) { if (string.IsNullOrEmpty(strpin)) throw new Exception(Resources.GetString(ResourcesLocaleKind.Errors, "ErrorPinValue")); if (strpin.Length!= Config.PinLength) throw new Exception(string.Format(Resources.GetString(ResourcesLocaleKind.Errors, "ErrorPinLength"), Config.PinLength)); } if (Convert.ToInt32(strpin) < 0) throw new Exception(Resources.GetString(ResourcesLocaleKind.Errors, "ErrorPinValue")); } catch (Exception ex) { Log.WriteEntry(ex.Message, EventLogEntryType.Error, 800); throw ex; } } /// <summary> /// GetQRCodeString method implmentation /// </summary> public string GetQRCodeString(AuthenticationContext usercontext) { string displaykey = KeysManager.EncodedKey(usercontext.UPN); return QRUtilities.GetQRCodeString(usercontext.UPN, displaykey, this.Config); } /// <summary> /// OnMessageArrived method implmentation /// Reloads configuration /// </summary> private void OnMessageArrived(MailSlotServer maislotserver, MailSlotMessage message) { if ((message.Operation == (byte)NotificationsKind.ConfigurationReload) || (message.Operation == (byte)NotificationsKind.ConfigurationCreated) || (message.Operation == (byte)NotificationsKind.ConfigurationDeleted)) { Trace.TraceInformation("AuthenticationProvider:Configuration changed!"); _config = CFGUtilities.ReadConfiguration(); string computer = message.Text; if (string.IsNullOrEmpty(computer)) computer = Environment.MachineName; else computer = computer.Replace("$", ""); Trace.TraceInformation("AuthenticationProvider:Configuration loaded!"); ResourcesLocale Resources = new ResourcesLocale(CultureInfo.InstalledUICulture.LCID); switch (message.Operation) { case (byte)NotificationsKind.ConfigurationReload: default: Log.WriteEntry(string.Format(Resources.GetString(ResourcesLocaleKind.Informations, "InfosConfigurationReloaded"), computer), EventLogEntryType.Warning, 9999); break; case (byte)NotificationsKind.ConfigurationCreated: Log.WriteEntry(string.Format(Resources.GetString(ResourcesLocaleKind.Informations, "InfosConfigurationCacheCreated"), computer), EventLogEntryType.Warning, 9999); break; case (byte)NotificationsKind.ConfigurationDeleted: Log.WriteEntry(string.Format(Resources.GetString(ResourcesLocaleKind.Informations, "InfosConfigurationCacheDeleted"), computer), EventLogEntryType.Warning, 9999); break; } } } /// <summary> /// PatchUserContextWithSelectedMethod method implementation /// </summary> private void PatchUserContextWithSelectedMethod(AuthenticationContext usercontext) { IExternalProvider prov = RuntimeAuthProvider.GetProvider(usercontext.PreferredMethod); if (prov!= null) { List<AvailableAuthenticationMethod> lst = prov.GetAuthenticationMethods(usercontext); if (lst.Count > 0) { AvailableAuthenticationMethod itm = lst[0]; usercontext.IsRemote = itm.IsRemote; usercontext.IsTwoWay = itm.IsTwoWay; usercontext.IsSendBack = itm.IsSendBack; usercontext.SelectedMethod = itm.Method; } } } /// <summary> /// HookOptionParameter method implementation /// when MFA is disabled, allow the user to access his configuration /// </summary> private bool HookOptionParameter(HttpListenerRequest request) { Uri uri = new Uri(request.Url.AbsoluteUri); return uri.AbsoluteUri.Contains("mfaopts"); } /// <summary> /// CheckOptionsCookie method implmentation /// </summary> private void CheckOptionsCookie(AuthenticationContext usercontext, HttpListenerRequest request) { var cook = request.Cookies["showoptions"]; if (cook!= null) { if (cook.Value == "1") usercontext.ShowOptions = true; else usercontext.ShowOptions = false; } else usercontext.ShowOptions = false; } /// <summary> /// HasAccessToOptions method /// </summary> internal bool HasAccessToOptions(IExternalProvider prov) { if (prov == null) return false; if (!prov.Enabled) return false; if (!Config.UserFeatures.CanAccessOptions()) return false; if (Config.UserFeatures.CanManageOptions() || Config.UserFeatures.CanManagePassword()) return true; if (Config.UserFeatures.CanEnrollDevices() && (prov.WizardEnabled)) return true; return false; } /// <summary>
1,528
int32 | Contains the manager notify time in minutes | | TicketEnabled | bool | Enable ticket submission in offline mode | | TicketCategory | | Category on ticket created from off-line request | | TicketPriority | | Priority on ticket created from off-line request | | OpeningHoursEnabled | bool | Whether to use opening hours or not. | | OpeningHours | | Opening hours settings | | Widget | | Settings for the chat widget | | BotEnabled | bool | Enable chatbot on this topic. Run the trigger scripts on bot events. | | BotSettings | | Settings for chatbot: trigger script ids to run on bot events | | OfflineCollectConsent | bool | Collect offline consent to store from user | | WarnChatMessageMinutes | int32 | Contains the user notify time in minutes for new chat messages | | WarnManagerChatMessageMinutes | int32 | Contains the manager notify time in minutes for new chat messages | | UseQueueOfflineForm | bool | Use offline form capability from chat queue | | OfflineFormTimeLimit | int32 | The number of minutes in the queue before the offline form is available | | OfflineFormQueueLength | int32 | The number of customers in the queue before the offline form is available | | TableRight | | | | FieldProperties | object | | | _Links | object | | ## Sample Request ```http! GET /api/v1/ChatTopic/{id} Authorization: Basic dGplMDpUamUw Accept: application/json; charset=utf-8 Accept-Language: en ``` ```http_ HTTP/1.1 200 ChatTopicEntity found. Content-Type: application/json; charset=utf-8 { "ChatTopicId": 652, "Name": "Bauch-Bednar", "Description": "Synergistic solution-oriented capacity", "WelcomeMessage": "quos", "Language": { "Id": 400, "Value": "impedit", "Tooltip": "praesentium", "TableRight": {}, "FieldProperties": { "fieldName": { "FieldRight": { "Mask": "FULL", "Reason": "" }, "FieldType": "System.String", "FieldLength": 977 } } }, "LastAccept": "2013-04-12T18:25:50.1636295+02:00", "SecondsPrAccept": 694, "AlertRecipient": "ipsa", "AlertTemplate": { "ReplyTemplateId": 553, "Name": "<NAME> Mertz", "Description": "Down-sized explicit instruction set", "FolderId": 311 }, "CollectConsent": true, "BadgeHeader": "rerum", "CustomQueueTextEnabled": true, "CustomQueueText": "sunt", "WarnNewChatMinutes": 587, "WarnManagerNewChatMinutes": 328, "TicketEnabled": false, "TicketCategory": { "Id": 438, "Value": "amet", "Tooltip": "est", "TableRight": {}, "FieldProperties": { "fieldName": { "FieldRight": { "Mask": "FULL", "Reason": "" }, "FieldType": "System.Int32", "FieldLength": 107 } } }, "TicketPriority": { "Id": 238, "Value": "harum", "Tooltip": "ipsa", "TableRight": {}, "FieldProperties": { "fieldName": { "FieldRight": { "Mask": "FULL", "Reason": "" }, "FieldType": "System.Int32", "FieldLength": 44 } } }, "OpeningHoursEnabled": false, "OpeningHours": { "TzLocation": {}, "MonEnabled": true, "MonStart": "hic", "MonStop": "reiciendis", "TueEnabled": true, "TueStart": "perspiciatis", "TueStop": "doloribus", "WedEnabled": false, "WedStart": "nesciunt", "WedStop": "facilis", "ThuEnabled": true, "ThuStart": "vero", "ThuStop": "tempora", "FriEnabled": true, "FriStart": "labore", "FriStop": "dolores", "SatEnabled": false, "SatStart": "perspiciatis", "SatStop": "quia", "SunEnabled": false, "SunStart": "non", "SunStop": "voluptatem", "UseLunchHours": true, "LunchStart": "consequatur", "LunchStop": "id" }, "Widget": { "AutoFaqEnabled": true, "AutoFaqCategory": {}, "PreFormEnabled": false, "PreFormMessage": "consequatur", "RequiredFields": "Company", "PostFormEnabled": false, "PostFormHeader": "voluptatibus", "PostFormMessage": "repellendus", "PostTranscriptEnabled": false, "LanguageIsoCode": "magnam", "Size": "Large", "Theme": "Classic", "Color": "doloribus", "Font": "laborum", "LogoEnabled": true, "LogoBlobId": 412, "LogoName": "<NAME> and Cassin", "ShowAgentPhoto": false, "WelcomeTitle": "magnam", "WelcomeMessage": "sed", "OfflineHeader": "earum", "OfflineMessage": "aliquam", "OfflineFields": "Company", "UseAgentFirstname": true }, "BotEnabled": true, "BotSettings": { "BotName": "<NAME> and McGlynn", "BotRegisterScriptId": 698, "BotSessionCreatedScriptId": 515, "BotSessionChangedScriptId": 338, "BotMessageReceivedScriptId": 613 }, "OfflineCollectConsent": true, "WarnChatMessageMinutes": 507, "WarnManagerChatMessageMinutes": 714, "UseQueueOfflineForm": true, "OfflineFormTimeLimit": 930, "OfflineFormQueueLength": 450, "TableRight": { "Mask": "Delete", "Reason": "" }, "FieldProperties": { "fieldName": { "FieldRight": { "Mask": "FULL", "Reason": "" }, "FieldType": "System.String", "FieldLength": 257 } }, "_Links": { "Self": "https://www.example.com/api/v1/project/321", "Archive": "https://www.example.com/api/v1/project" } } ``` ======================= File: docs/api-reference/soap/Services88/Saint/index.md ======================= <reponame>SuperOfficeDocs/data-access --- title: Services88.SaintAgent SOAP uid: Services88-Saint-soap generated: 1 --- # Services88 Saint SOAP SOAP request and response examples, and WSDL files for **Remote/Services88/Saint.svc** Handled by the <see cref="T:SuperOffice.Services88.ISaintAgent">SuperOffice.Services88.ISaintAgent</see> interface. Interface for the Saint Agent Administration and maintenance of SAINT counters and statuses Download [WSDL file for Services88/Saint](../Services88-Saint.md) if you need to generate your own proxy code. * [CreateDefaultSaintConfiguration](CreateDefaultSaintConfiguration.md) * [CreateDefaultStatusMonitor](CreateDefaultStatusMonitor.md) * [CreateDefaultStatusMonitorPeriods](CreateDefaultStatusMonitorPeriods.md) * [GetSaintConfigurations](GetSaintConfigurations.md) * [GetStatusMonitor](GetStatusMonitor.md) * [GetStatusMonitorPeriods](GetStatusMonitorPeriods.md) * [GetStatusMonitors](GetStatusMonitors.md) * [RegenerateCounters](RegenerateCounters.md) * [RegenerateStatusMonitor](RegenerateStatusMonitor.md) * [RegenerateStatusMonitors](RegenerateStatusMonitors.md) * [SaveSaintConfiguration](SaveSaintConfiguration.md) * [SaveStatusMonitor](SaveStatusMonitor.md) * [SaveStatusMonitorPeriods](SaveStatusMonitorPeriods.md) * [SetRankOnStatusMonitors](SetRankOnStatusMonitors.md) ======================= File: docs/api-reference/soap/Services84/Services84-Preference.md ======================= <reponame>SuperOfficeDocs/data-access --- generated: 1 uid: wsdl-Services84-Preference title: Services84.PreferenceAgent WSDL --- # Services84.PreferenceAgent WSDL ```xml <?xml version="1.0" encoding="utf-8"?> <wsdl:definitions name="WcfPreferenceService" targetNamespace="http://www.superoffice.net/ws/crm/NetServer/Services84" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:wsap="http://schemas.xmlsoap.org/ws/2004/08/addressing/policy" xmlns:wsa10="http://www.w3.org/2005/08/addressing" xmlns:tns="http://www.superoffice.net/ws/crm/NetServer/Services84" xmlns:msc="http://schemas.microsoft.com/ws/2005/12/wsdl/contract" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:wsx="http://schemas.xmlsoap.org/ws/2004/09/mex" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:wsam="http://www.w3.org/2007/05/addressing/metadata" xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy" xmlns:wsaw="http://www.w3.org/2006/05/addressing/wsdl" xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <wsdl:types> <xs:schema elementFormDefault="qualified" targetNamespace="http://www.superoffice.net/ws/crm/NetServer/Services84" xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:import namespace="http://schemas.microsoft.com/2003/10/Serialization/Arrays" /> <xs:element name="CreateDefaultPreference"> <xs:complexType> <xs:sequence /> </xs:complexType> </xs:element> <xs:element name="ApplicationToken" nillable="true" type="xs:string" /> <xs:complexType name="SoCredentials"> <xs:sequence> <xs:element minOccurs="0" name="Ticket" nillable="true" type="xs:string" /> </xs:sequence> </xs:complexType> <xs:element name="SoCredentials" nillable="true" type="tns:SoCredentials" /> <xs:element name="Credentials" nillable="true" type="tns:SoCredentials" /> <xs:complexType name="SoTimeZone"> <xs:sequence> <xs:element minOccurs="0" name="SoTimeZoneId" type="xs:int" /> <xs:element minOccurs="0" name="SoTimeZoneLocationCode" nillable="true" type="xs:string" /> </xs:sequence> </xs:complexType> <xs:element name="SoTimeZone" nillable="true" type="tns:SoTimeZone" /> <xs:element name="TimeZone" nillable="true" type="tns:SoTimeZone" /> <xs:element name="CreateDefaultPreferenceResponse"> <xs:complexType> <xs:sequence> <xs:element minOccurs="0" name="Response" nillable="true" type="tns:Preference" /> </xs:sequence> </xs:complexType> </xs:element> <xs:complexType name="Preference"> <xs:complexContent mixed="false"> <xs:extension base="tns:Carrier"> <xs:sequence> <xs:element minOccurs="0" name="Level" type="tns:PreferenceLevel" /> <xs:element minOccurs="0" name="RawValue" nillable="true" type="xs:string" /> <xs:element minOccurs="0" name="Specification" nillable="true" type="tns:PreferenceSpec" /> <xs:element minOccurs="0" name="DisplayValue" nillable="true" type="xs:string" /> <xs:element minOccurs="0" name="DisplayTooltip" nillable="true" type="xs:string" /> <xs:element minOccurs="0" name="DisplayType" type="tns:PrefDescValueType" /> <xs:element minOccurs="0" name="TabOrder" nillable="true" type="tns:TabOrder" /> <xs:element minOccurs="0" name="TargetId" type="xs:int" /> <xs:element minOccurs="0" name="PrefDescId" type="xs:int" /> <xs:element minOccurs="0" name="TableName" nillable="true" type="xs:string" /> <xs:element minOccurs="0" name="UserPreferenceId" type="xs:int" /> </xs:sequence> </xs:extension> </xs:complexContent> </xs:complexType> <xs:element name="Preference" nillable="true" type="tns:Preference" /> <xs:complexType name="Carrier"> <xs:sequence> <xs:element minOccurs="0" name="TableRight" nillable="true" type="tns:TableRight" /> <xs:element minOccurs="0" name="FieldProperties" nillable="true" type="tns:FieldPropertyDictionary" /> </xs:sequence> </xs:complexType> <xs:element name="Carrier" nillable="true" type="tns:Carrier" /> <xs:complexType name="TableRight"> <xs:sequence> <xs:element minOccurs="0" name="Mask" type="tns:ETableRight" /> <xs:element minOccurs="0" name="Reason" nillable="true" type="xs:string" /> </xs:sequence> </xs:complexType> <xs:element name="TableRight" nillable="true" type="tns:TableRight" /> <xs:simpleType name="ETableRight"> <xs:list> <xs:simpleType> <xs:restriction base="xs:string"> <xs:enumeration value="Select" /> <xs:enumeration value="Update" /> <xs:enumeration value="Insert" /> <xs:enumeration value="Delete" /> <xs:enumeration value="Filtering" /> <xs:enumeration value="RestrictedUpdate" /> </xs:restriction> </xs:simpleType> </xs:list> </xs:simpleType> <xs:element name="ETableRight" nillable="true" type="tns:ETableRight" /> <xs:complexType name="FieldPropertyDictionary"> <xs:annotation> <xs:appinfo> <IsDictionary xmlns="http://schemas.microsoft.com/2003/10/Serialization/">true</IsDictionary> </xs:appinfo> </xs:annotation> <xs:sequence> <xs:element minOccurs="0" maxOccurs="unbounded" name="FieldPropertyDictionaryKeyValuePair"> <xs:complexType> <xs:sequence> <xs:element name="Key" nillable="true" type="xs:string" /> <xs:element name="Value" nillable="true" type="tns:FieldProperty" /> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> <xs:element name="FieldPropertyDictionary" nillable="true" type="tns:FieldPropertyDictionary" /> <xs:complexType name="FieldProperty"> <xs:sequence> <xs:element minOccurs="0" name="FieldRight" nillable="true" type="tns:FieldRight" /> <xs:element minOccurs="0" name="FieldType" nillable="true" type="xs:string" /> <xs:element minOccurs="0" name="FieldLength" type="xs:int" /> </xs:sequence> </xs:complexType> <xs:element name="FieldProperty" nillable="true" type="tns:FieldProperty" /> <xs:complexType name="FieldRight"> <xs:sequence> <xs:element minOccurs="0" name="Mask" type="tns:EFieldRight" /> <xs:element minOccurs="0" name="Reason" nillable="true" type="xs:string" /> </xs:sequence> </xs:complexType> <xs:element name="FieldRight" nillable="true" type="tns:FieldRight" /> <xs:simpleType name="EFieldRight"> <xs:list> <xs:simpleType> <xs:restriction base="xs:string"> <xs:enumeration value="Read" /> <xs:enumeration value="Write" /> <xs:enumeration value="Unused1" /> <xs:enumeration value="Unused2" /> <xs:enumeration value="Unused3" /> <xs:enumeration value="Unused4" /> <xs:enumeration value="UIHintMandatory" /> <xs:enumeration value="UIHintReadOnly" /> <xs:enumeration value="UndefinedValue256" /> </xs:restriction> </xs:simpleType> </xs:list> </xs:simpleType> <xs:element name="EFieldRight" nillable="true" type="tns:EFieldRight" /> <xs:simpleType name="PreferenceLevel"> <xs:annotation> <xs:appinfo> <ActualType Name="short" Namespace="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.microsoft.com/2003/10/Serialization/" /> </xs:appinfo> </xs:annotation> <xs:restriction base="xs:string"> <xs:enumeration value="Undefined" /> <xs:enumeration value="HardDefault" /> <xs:enumeration value="SystemWide" /> <xs:enumeration value="Database" /> <xs:enumeration value="Group" /> <xs:enumeration value="Individual" /> <xs:enumeration value="PC" /> </xs:restriction> </xs:simpleType> <xs:element name="PreferenceLevel" nillable="true" type="tns:PreferenceLevel" /> <xs:complexType name="PreferenceSpec"> <xs:complexContent mixed="false"> <xs:extension base="tns:Carrier"> <xs:sequence> <xs:element minOccurs="0" name="Section" nillable="true" type="xs:string" /> <xs:element minOccurs="0" name="Key" nillable="true" type="xs:string" /> </xs:sequence> </xs:extension> </xs:complexContent> </xs:complexType> <xs:element name="PreferenceSpec" nillable="true" type="tns:PreferenceSpec" /> <xs:simpleType name="PrefDescValueType"> <xs:annotation> <xs:appinfo> <ActualType Name="short" Namespace="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.microsoft.com/2003/10/Serialization/" /> </xs:appinfo> </xs:annotation> <xs:restriction base="xs:string"> <xs:enumeration value="Unknown" /> <xs:enumeration value="Number" /> <xs:enumeration value="Text" /> <xs:enumeration value="Bool" /> <xs:enumeration value="ListOfValues" /> <xs:enumeration value="ListTableRef" /> <xs:enumeration value="TimeList" /> <xs:enumeration value="ContactID" /> <xs:enumeration value="PersonID" /> <xs:enumeration value="ProjectID" /> <xs:enumeration value="SelectionID" /> <xs:enumeration value="PosSize" /> <xs:enumeration value="TimeZone" /> </xs:restriction> </xs:simpleType> <xs:element name="PrefDescValueType" nillable="true" type="tns:PrefDescValueType" /> <xs:complexType name="TabOrder"> <xs:complexContent mixed="false"> <xs:extension base="tns:Carrier"> <xs:sequence> <xs:element minOccurs="0" name="TabOrderId" type="xs:int" /> <xs:element minOccurs="0" name="TabName" nillable="true" type="xs:string" /> <xs:element minOccurs="0" name="Order" nillable="true" type="xs:string" /> <xs:element minOccurs="0" name="AssociateId" type="xs:int" /> </xs:sequence> </xs:extension> </xs:complexContent> </xs:complexType> <xs:element name="TabOrder" nillable="true" type="tns:TabOrder" /> <xs:complexType name="SoExceptionInfo"> <xs:sequence> <xs:element minOccurs="0" name="Message" nillable="true" type="xs:string" /> <xs:element minOccurs="0" name="StackTrace" nillable="true" type="xs:string" /> <xs:element minOccurs="0" name="FriendlyText" nillable="true" type="xs:string" /> <xs:element minOccurs="0" name="ExceptionType" nillable="true" type="xs:string" /> <xs:element minOccurs="0" name="Source" nillable="true" type="xs:string" /> <xs:element minOccurs="0" name="InnerException" nillable="true" type="tns:SoExceptionInfo" /> <xs:element minOccurs="0" name="Parameters" nillable="true" type="tns:SoExceptionInfoParameters" /> </xs:sequence> </xs:complexType> <xs:element name="SoExceptionInfo" nillable="true" type="tns:SoExceptionInfo" /> <xs:complexType name="SoExceptionInfoParameters"> <xs:annotation> <xs:appinfo> <IsDictionary xmlns="http://schemas.microsoft.com/2003/10/Serialization/">true</IsDictionary> </xs:appinfo> </xs:annotation> <xs:sequence> <xs:element minOccurs="0" maxOccurs="unbounded" name="SoExceptionInfoParametersKeyValuePair"> <xs:complexType> <xs:sequence> <xs:element name="Key" nillable="true" type="xs:string" /> <xs:element name="Value" nillable="true" type="xs:string" /> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> <xs:element name="SoExceptionInfoParameters" nillable="true" type="tns:SoExceptionInfoParameters" /> <xs:element name="ExceptionInfo" nillable="true" type="tns:SoExceptionInfo" /> <xs:complexType name="SoExtraInfo"> <xs:annotation> <xs:appinfo> <IsDictionary xmlns="http://schemas.microsoft.com/2003/10/Serialization/">true</IsDictionary> </xs:appinfo> </xs:annotation> <xs:sequence> <xs:element minOccurs="0" maxOccurs="unbounded" name="ExtraInfoNameValuePair"> <xs:complexType> <xs:sequence> <xs:element name="Key" nillable="true" type="xs:string" /> <xs:element name="Value" nillable="true" type="xs:string" /> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> <xs:element name="SoExtraInfo" nillable="true" type="tns:SoExtraInfo" /> <xs:element name="ExtraInfo" nillable="true" type="tns:SoExtraInfo" /> <xs:element name="Succeeded" type="xs:boolean" /> <xs:element name="CreateDefaultPreferenceDescription"> <xs:complexType> <xs:sequence /> </xs:complexType> </xs:element> <xs:element name="CreateDefaultPreferenceDescriptionResponse"> <xs:complexType> <xs:sequence> <xs:element minOccurs="0" name="Response" nillable="true" type="tns:PreferenceDescription" /> </xs:sequence> </xs:complexType> </xs:element> <xs:complexType name="PreferenceDescription"> <xs:complexContent mixed="false"> <xs:extension base="tns:Carrier"> <xs:sequence> <xs:element minOccurs="0" name="PrefDescId" type="xs:int" /> <xs:element minOccurs="0" name="Section" nillable="true" type="xs:string" /> <xs:element minOccurs="0" name="Key" nillable="true" type="xs:string" /> <xs:element minOccurs="0" name="Name" nillable="true" type="xs:string" /> <xs:element minOccurs="0" name="ValueType" type="tns:PrefDescValueType" /> <xs:element minOccurs="0" name="MaxLevel" type="tns:PreferenceLevel" /> <xs:element minOccurs="0" name="SysMaxLevel" type="tns:PreferenceLevel" /> <xs:element minOccurs="0" name="AccessFlags" type="tns:PrefDescAccessFlags" /> <xs:element minOccurs="0" name="Description" nillable="true" type="xs:string" /> <xs:element minOccurs="0" name="IsBuiltin" type="xs:boolean" /> <xs:element minOccurs="0" name="TableName" nillable="true" type="xs:string" /> <xs:element minOccurs="0" name="UserDefinedListId" type="xs:int" /> </xs:sequence> </xs:extension> </xs:complexContent> </xs:complexType> <xs:element name="PreferenceDescription" nillable="true" type="tns:PreferenceDescription" /> <xs:simpleType name="PrefDescAccessFlags"> <xs:annotation> <xs:appinfo> <ActualType Name="short" Namespace="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.microsoft.com/2003/10/Serialization/" /> </xs:appinfo> </xs:annotation> <xs:list> <xs:simpleType> <xs:restriction base="xs:string"> <xs:enumeration value="WizardMode" /> <xs:enumeration value="Level0" /> <xs:enumeration value="adminGUI" /> <xs:enumeration value="CRMGUI" /> </xs:restriction> </xs:simpleType> </xs:list> </xs:simpleType> <xs:element name="PrefDescAccessFlags" nillable="true" type="tns:PrefDescAccessFlags" /> <xs:element name="SavePreferenceDescription"> <xs:complexType> <xs:sequence> <xs:element minOccurs="0" name="PreferenceDescription" nillable="true" type="tns:PreferenceDescription" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="SavePreferenceDescriptionResponse"> <xs:complexType> <xs:sequence> <xs:element minOccurs="0" name="Response" nillable="true" type="tns:PreferenceDescription" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="DeletePreferenceDescription"> <xs:complexType> <xs:sequence> <xs:element minOccurs="0" name="PreferenceDescriptionId" type="xs:int" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="DeletePreferenceDescriptionResponse"> <xs:complexType> <xs:sequence /> </xs:complexType> </xs:element> <xs:element name="CreateDefaultPreferenceDescriptionLine"> <xs:complexType> <xs:sequence /> </xs:complexType> </xs:element> <xs:element name="CreateDefaultPreferenceDescriptionLineResponse"> <xs:complexType> <xs:sequence> <xs:element minOccurs="0" name="Response" nillable="true" type="tns:PreferenceDescriptionLine" /> </xs:sequence> </xs:complexType> </xs:element> <xs:complexType name="PreferenceDescriptionLine"> <xs:complexContent mixed="false"> <xs:extension base="tns:Carrier"> <xs:sequence> <xs:element minOccurs="0" name="PrefDescLineId" type="xs:int" /> <xs:element minOccurs="0" name="PrefDescId" type="xs:int" /> <xs:element minOccurs="0" name="PrefValue" nillable="true" type="xs:string" /> <xs:element minOccurs="0" name="PrefShowValue" nillable="true" type="xs:string" /> <xs:element minOccurs="0" name="Description" nillable="true" type="xs:string" /> <xs:element minOccurs="0" name="IsBuiltin" type="xs:boolean" /> </xs:sequence> </xs:extension> </xs:complexContent> </xs:complexType> <xs:element name="PreferenceDescriptionLine" nillable="true" type="tns:PreferenceDescriptionLine" /> <xs:element name="SavePreference"> <xs:complexType> <xs:sequence> <xs:element minOccurs="0" name="Preference" nillable="true" type="tns:Preference" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="SavePreferenceResponse"> <xs:complexType> <xs:sequence /> </xs:complexType> </xs:element> <xs:element name="SaveTabOrder"> <xs:complexType> <xs:sequence> <xs:element minOccurs="0" name="TabOrder" nillable="true" type="tns:TabOrder" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="SaveTabOrderResponse"> <xs:complexType> <xs:sequence /> </xs:complexType> </xs:element> <xs:element name="GetTabOrder"> <xs:complexType> <xs:sequence> <xs:element minOccurs="0" name="TabName" nillable="true" type="xs:string" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="GetTabOrderResponse"> <xs:complexType> <xs:sequence> <xs:element minOccurs="0" name="Response" nillable="true" type="tns:TabOrder" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="GetPreference"> <xs:complexType> <xs:sequence> <xs:element minOccurs="0" name="Id" type="xs:int" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="GetPreferenceResponse"> <xs:complexType> <xs:sequence> <xs:element minOccurs="0" name="Response" nillable="true" type="tns:Preference" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="SavePreferenceEntity"> <xs:complexType> <xs:sequence> <xs:element minOccurs="0" name="Preference" nillable="true" type="tns:Preference" /> <xs:element minOccurs="0" name="RemoveLowerLevels" type="xs:boolean" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="SavePreferenceEntityResponse"> <xs:complexType> <xs:sequence> <xs:element minOccurs="0" name="Response" nillable="true" type="tns:Preference" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="DeletePreference"> <xs:complexType> <xs:sequence> <xs:element minOccurs="0" name="Id" type="xs:int" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="DeletePreferenceResponse"> <xs:complexType> <xs:sequence /> </xs:complexType> </xs:element> <xs:element name="DeletePreferences"> <xs:complexType> <xs:sequence> <xs:element minOccurs="0" name="Ids" nillable="true" type="q1:ArrayOfint" xmlns:q1="http://schemas.microsoft.com/2003/10/Serialization/Arrays" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="DeletePreferencesResponse"> <xs:complexType> <xs:sequence /> </xs:complexType> </xs:element> <xs:element name="GetPreferenceByName"> <xs:complexType> <xs:sequence> <xs:element minOccurs="0" name="PrefSection" nillable="true" type="xs:string" /> <xs:element minOccurs="0" name="PrefKey" nillable="true" type="xs:string" /> <xs:element minOccurs="0" name="PrefLevel" type="tns:PreferenceLevel" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="GetPreferenceByNameResponse"> <xs:complexType> <xs:sequence> <xs:element minOccurs="0" name="Response" nillable="true" type="tns:Preference" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="GetNetServicesStatusUrl"> <xs:complexType> <xs:sequence /> </xs:complexType> </xs:element> <xs:element name="GetNetServicesStatusUrlResponse"> <xs:complexType> <xs:sequence> <xs:element minOccurs="0" name="Response" nillable="true" type="xs:string" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="UpdateNetServicesStatus"> <xs:complexType> <xs:sequence> <xs:element minOccurs="0" name="XmlOrJson" nillable="true" type="xs:string" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="UpdateNetServicesStatusResponse"> <xs:complexType> <xs:sequence /> </xs:complexType> </xs:element> <xs:element name="GetPreferenceDescription"> <xs:complexType> <xs:sequence> <xs:element minOccurs="0" name="PreferenceDescriptionId" type="xs:int" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="GetPreferenceDescriptionResponse"> <xs:complexType> <xs:sequence> <xs:element minOccurs="0" name="Response" nillable="true" type="tns:PreferenceDescription" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="GetFromSectionAndKey"> <xs:complexType> <xs:sequence> <xs:element minOccurs="0" name="Section" nillable="true" type="xs:string" /> <xs:element minOccurs="0" name="Key" nillable="true" type="xs:string" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="GetFromSectionAndKeyResponse"> <xs:complexType> <xs:sequence> <xs:element minOccurs="0" name="Response" nillable="true" type="tns:PreferenceDescription" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="GetAll"> <xs:complexType> <xs:sequence /> </xs:complexType> </xs:element> <xs:element name="GetAllResponse"> <xs:complexType> <xs:sequence> <xs:element minOccurs="0" name="Response" nillable="true" type="tns:ArrayOfPreferenceDescription" /> </xs:sequence> </xs:complexType> </xs:element> <xs:complexType name="ArrayOfPreferenceDescription"> <xs:sequence> <xs:element minOccurs="0" maxOccurs="unbounded" name="PreferenceDescription" nillable="true" type="tns:PreferenceDescription" /> </xs:sequence> </xs:complexType> <xs:element name="ArrayOfPreferenceDescription" nillable="true" type="tns:ArrayOfPreferenceDescription" /> <xs:element name="GetAllFromSection"> <xs:complexType> <xs:sequence> <xs:element minOccurs="0" name="Section" nillable="true" type="xs:string" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="GetAllFromSectionResponse"> <xs:complexType> <xs:sequence> <xs:element minOccurs="0" name="Response" nillable="true" type="tns:ArrayOfPreferenceDescription" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="SaveFromSectionAndKey"> <xs:complexType> <xs:sequence> <xs:element minOccurs="0" name="Section" nillable="true" type="xs:string" /> <xs:element minOccurs="0" name="Key" nillable="true" type="xs:string" /> <xs:element minOccurs="0" name="PreferenceDescription" nillable="true" type="tns:PreferenceDescription" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="SaveFromSectionAndKeyResponse"> <xs:complexType> <xs:sequence> <xs:element minOccurs="0" name="Response" nillable="true" type="tns:PreferenceDescription" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="DeleteFromSectionAndKey"> <xs:complexType> <xs:sequence> <xs:element minOccurs="0" name="Section" nillable="true" type="xs:string" /> <xs:element minOccurs="0" name="Key" nillable="true" type="xs:string" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="DeleteFromSectionAndKeyResponse"> <xs:complexType> <xs:sequence /> </xs:complexType> </xs:element> <xs:element name="GetPreferenceDescriptionLine"> <xs:complexType> <xs:sequence> <xs:element minOccurs="0" name="PreferenceDescriptionLineId" type="xs:int" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="GetPreferenceDescriptionLineResponse"> <xs:complexType> <xs:sequence> <xs:element minOccurs="0" name="Response" nillable="true" type="tns:PreferenceDescriptionLine" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="GetPreferenceDescriptionLineFromIdAndValue"> <xs:complexType> <xs:sequence> <xs:element minOccurs="0" name="PrefDescId" type="xs:int" /> <xs:element minOccurs="0" name="PrefValue" nillable="true" type="xs:string" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="GetPreferenceDescriptionLineFromIdAndValueResponse"> <xs:complexType> <xs:sequence> <xs:element minOccurs="0" name="Response" nillable="true" type="tns:PreferenceDescriptionLine" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="GetPreferences"> <xs:complexType> <xs:sequence> <xs:element minOccurs="0" name="Specifications" nillable="true" type="tns:ArrayOfPreferenceSpec" /> </xs:sequence> </xs:complexType> </xs:element> <xs:complexType name="ArrayOfPreferenceSpec"> <xs:sequence> <xs:element minOccurs="0" maxOccurs="unbounded" name="PreferenceSpec" nillable="true" type="tns:PreferenceSpec" /> </xs:sequence> </xs:complexType> <xs:element name="ArrayOfPreferenceSpec" nillable="true" type="tns:ArrayOfPreferenceSpec" /> <xs:element name="GetPreferencesResponse"> <xs:complexType> <xs:sequence> <xs:element minOccurs="0" name="Response" nillable="true" type="tns:ArrayOfPreference" /> </xs:sequence> </xs:complexType> </xs:element> <xs:complexType name="ArrayOfPreference"> <xs:sequence> <xs:element minOccurs="0" maxOccurs="unbounded" name="Preference" nillable="true" type="tns:Preference" /> </xs:sequence> </xs:complexType> <xs:element name="ArrayOfPreference" nillable="true" type="tns:ArrayOfPreference" /> <xs:element name="SavePreferences"> <xs:complexType> <xs:sequence> <xs:element minOccurs="0" name="Preferences" nillable="true" type="tns:ArrayOfPreference" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="SavePreferencesResponse"> <xs:complexType> <xs:sequence /> </xs:complexType> </xs:element> <xs:element name="GetPreferencesWithDisplayValues"> <xs:complexType> <xs:sequence> <xs:element minOccurs="0" name="Specifications" nillable="true" type="tns:ArrayOfPreferenceSpec" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="GetPreferencesWithDisplayValuesResponse"> <xs:complexType> <xs:sequence> <xs:element minOccurs="0" name="Response" nillable="true" type="tns:ArrayOfPreference" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="GetTabOrders"> <xs:complexType> <xs:sequence /> </xs:complexType> </xs:element> <xs:element name="GetTabOrdersResponse"> <xs:complexType> <xs:sequence> <xs:element minOccurs="0" name="Response" nillable="true" type="tns:ArrayOfTabOrder" /> </xs:sequence> </xs:complexType> </xs:element> <xs:complexType name="ArrayOfTabOrder"> <xs:sequence> <xs:element minOccurs="0" maxOccurs="unbounded" name="TabOrder" nillable="true" type="tns:TabOrder" /> </xs:sequence> </xs:complexType> <xs:element name="ArrayOfTabOrder" nillable="true" type="tns:ArrayOfTabOrder" /> <xs:element name="SaveTabOrders"> <xs:complexType> <xs:sequence> <xs:element minOccurs="0" name="TabOrders" nillable="true" type="tns:ArrayOfTabOrder" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="SaveTabOrdersResponse"> <xs:complexType> <xs:sequence /> </xs:complexType> </xs:element> </xs:schema> <xs:schema attributeFormDefault="qualified" elementFormDefault="qualified" targetNamespace="http://schemas.microsoft.com/2003/10/Serialization/" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:tns="http://schemas.microsoft.com/2003/10/Serialization/"> <xs:element name="anyType" nillable="true" type="xs:anyType" /> <xs:element name="anyURI" nillable="true" type="xs:anyURI" /> <xs:element name="base64Binary" nillable="true" type="xs:base64Binary" /> <xs:element name="boolean" nillable="true" type="xs:boolean" /> <xs:element name="byte" nillable="true" type="xs:byte" /> <xs:element name="dateTime" nillable="true" type="xs:dateTime" /> <xs:element name="decimal" nillable="true" type="xs:decimal" /> <xs:element name="double" nillable="true" type="xs:double" /> <xs:element name="float" nillable="true" type="xs:float" /> <xs:element name="int" nillable="true" type="xs:int" /> <xs:element name="long" nillable="true" type="xs:long" /> <xs:element name="QName" nillable="true" type="xs:QName" /> <xs:element name="short" nillable="true" type="xs:short" /> <xs:element name="string" nillable="true" type="xs:string" /> <xs:element name="unsignedByte" nillable="true" type="xs:unsignedByte" /> <xs:element name="unsignedInt" nillable="true" type="xs:unsignedInt" /> <xs:element name="unsignedLong" nillable="true" type="xs:unsignedLong" /> <xs:element name="unsignedShort" nillable="true" type="xs:unsignedShort" /> <xs:element name="char" nillable="true" type="tns:char" /> <xs:simpleType name="char"> <xs:restriction base="xs:int" /> </xs:simpleType> <xs:element name="duration" nillable="true" type="tns:duration" /> <xs:simpleType name="duration"> <xs:restriction base="xs:duration"> <xs:pattern value="\-?P(\d*D)?(T(\d*H)?(\d*M)?(\d*(\.\d*)?S)?)?" /> <xs:minInclusive value="-P10675199DT2H48M5.4775808S" /> <xs:maxInclusive value="P10675199DT2H48M5.4775807S" /> </xs:restriction> </xs:simpleType> <xs:element name="guid" nillable="true" type="tns:guid" /> <xs:simpleType name="guid"> <xs:restriction base="xs:string"> <xs:pattern value="[\da-fA-F]{8}-[\da-fA-F]{4}-[\da-fA-F]{4}-[\da-fA-F]{4}-[\da-fA-F]{12}" /> </xs:restriction> </xs:simpleType> <xs:attribute name="FactoryType" type="xs:QName" /> <xs:attribute name="Id" type="xs:ID" /> <xs:attribute name="Ref" type="xs:IDREF" /> </xs:schema> <xs:schema elementFormDefault="qualified" targetNamespace="http://schemas.microsoft.com/2003/10/Serialization/Arrays" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:tns="http://schemas.microsoft.com/2003/10/Serialization/Arrays"> <xs:complexType name="ArrayOfint"> <xs:sequence> <xs:element minOccurs="0" maxOccurs="unbounded" name="int" type="xs:int" /> </xs:sequence> </xs:complexType> <xs:element name="ArrayOfint" nillable="true" type="tns:ArrayOfint" /> </xs:schema> </wsdl:types> <wsdl:message name="CreateDefaultPreferenceRequest"> <wsdl:part name="parameters" element="tns:CreateDefaultPreference" /> </wsdl:message> <wsdl:message name="CreateDefaultPreferenceRequest_Headers"> <wsdl:part name="ApplicationToken" element="tns:ApplicationToken" /> <wsdl:part name="Credentials" element="tns:Credentials" /> <wsdl:part name="TimeZone" element="tns:TimeZone" /> </wsdl:message> <wsdl:message name="CreateDefaultPreferenceResponse"> <wsdl:part name="parameters" element="tns:CreateDefaultPreferenceResponse" /> </wsdl:message> <wsdl:message name="CreateDefaultPreferenceResponse_Headers"> <wsdl:part name="ExceptionInfo" element="tns:ExceptionInfo" /> <wsdl:part name="ExtraInfo" element="tns:ExtraInfo" /> <wsdl:part name="Succeeded" element="tns:Succeeded" /> <wsdl:part name="TimeZone" element="tns:TimeZone" /> </wsdl:message> <wsdl:message name="CreateDefaultPreferenceDescriptionRequest"> <wsdl:part name="parameters" element="tns:CreateDefaultPreferenceDescription" /> </wsdl:message> <wsdl:message name="CreateDefaultPreferenceDescriptionRequest_Headers"> <wsdl:part name="ApplicationToken" element="tns:ApplicationToken" /> <wsdl:part name="Credentials" element="tns:Credentials" /> <wsdl:part name="TimeZone" element="tns:TimeZone" /> </wsdl:message> <wsdl:message name="CreateDefaultPreferenceDescriptionResponse"> <wsdl:part name="parameters" element="tns:CreateDefaultPreferenceDescriptionResponse" /> </wsdl:message> <wsdl:message name="CreateDefaultPreferenceDescriptionResponse_Headers"> <wsdl:part name="ExceptionInfo" element="tns:ExceptionInfo" /> <wsdl:part name="ExtraInfo" element="tns:ExtraInfo" /> <wsdl:part name="Succeeded" element="tns:Succeeded" /> <wsdl:part name="TimeZone" element="tns:TimeZone" /> </wsdl:message> <wsdl:message name="SavePreferenceDescriptionRequest"> <wsdl:part name="parameters" element="tns:SavePreferenceDescription" /> </wsdl:message> <wsdl:message name="SavePreferenceDescriptionRequest_Headers"> <wsdl:part name="ApplicationToken" element="tns:ApplicationToken" /> <wsdl:part name="Credentials" element="tns:Credentials" /> <wsdl:part name="TimeZone" element="tns:TimeZone" /> </wsdl:message> <wsdl:message name="SavePreferenceDescriptionResponse"> <wsdl:part name="parameters" element="tns:SavePreferenceDescriptionResponse" /> </wsdl:message> <wsdl:message name="SavePreferenceDescriptionResponse_Headers"> <wsdl:part name="ExceptionInfo" element="tns:ExceptionInfo" /> <wsdl:part name="ExtraInfo" element="tns:ExtraInfo" /> <wsdl:part name="Succeeded" element="tns:Succeeded" /> <wsdl:part name="TimeZone" element="tns:TimeZone" /> </wsdl:message> <wsdl:message name="DeletePreferenceDescriptionRequest"> <wsdl:part name="parameters" element="tns:DeletePreferenceDescription" /> </wsdl:message> <wsdl:message name="DeletePreferenceDescriptionRequest_Headers"> <wsdl:part name="ApplicationToken" element="tns:ApplicationToken" /> <wsdl:part name="Credentials" element="tns:Credentials" /> <wsdl:part name="TimeZone" element="tns:TimeZone" /> </wsdl:message> <wsdl:message name="DeletePreferenceDescriptionResponse"> <wsdl:part name="parameters" element="tns:DeletePreferenceDescriptionResponse" /> </wsdl:message> <wsdl:message name="DeletePreferenceDescriptionResponse_Headers"> <wsdl:part name="ExceptionInfo" element="tns:ExceptionInfo" /> <wsdl:part name="ExtraInfo" element="tns:ExtraInfo" /> <wsdl:part name="Succeeded" element="tns:Succeeded" /> <wsdl:part name="TimeZone" element="tns:TimeZone" /> </wsdl:message> <wsdl:message name="CreateDefaultPreferenceDescriptionLineRequest"> <wsdl:part name="parameters" element="tns:CreateDefaultPreferenceDescriptionLine" /> </wsdl:message> <wsdl:message name="CreateDefaultPreferenceDescriptionLineRequest_Headers"> <wsdl:part name="ApplicationToken" element="tns:ApplicationToken" /> <wsdl:part name="Credentials" element="tns:Credentials" /> <wsdl:part name="TimeZone" element="tns:TimeZone" /> </wsdl:message> <wsdl:message name="CreateDefaultPreferenceDescriptionLineResponse"> <wsdl:part name="parameters" element="tns:CreateDefaultPreferenceDescriptionLineResponse" /> </wsdl:message> <wsdl:message name="CreateDefaultPreferenceDescriptionLineResponse_Headers"> <wsdl:part name="ExceptionInfo" element="tns:ExceptionInfo" /> <wsdl:part name="ExtraInfo" element="tns:ExtraInfo" /> <wsdl:part name="Succeeded" element="tns:Succeeded" /> <wsdl:part name="TimeZone" element="tns:TimeZone" /> </wsdl:message> <wsdl:message name="SavePreferenceRequest"> <wsdl:part name="parameters" element="tns:SavePreference" /> </wsdl:message> <wsdl:message name="SavePreferenceRequest_Headers"> <wsdl:part name="ApplicationToken" element="tns:ApplicationToken" /> <wsdl:part name="Credentials" element="tns:Credentials" /> <wsdl:part name="TimeZone" element="tns:TimeZone" /> </wsdl:message> <wsdl:message name="SavePreferenceResponse"> <wsdl:part name="parameters" element="tns:SavePreferenceResponse" /> </wsdl:message> <wsdl:message name="SavePreferenceResponse_Headers"> <wsdl:part name="ExceptionInfo" element="tns:ExceptionInfo" /> <wsdl:part name="ExtraInfo" element="tns:ExtraInfo" /> <wsdl:part name="Succeeded" element="tns:Succeeded" /> <wsdl:part name="TimeZone" element="tns:TimeZone" /> </wsdl:message> <wsdl:message name="SaveTabOrderRequest"> <wsdl:part name="parameters" element="tns:SaveTabOrder" /> </wsdl:message> <wsdl:message name="SaveTabOrderRequest_Headers"> <wsdl:part name="ApplicationToken" element="tns:ApplicationToken" /> <wsdl:part name="Credentials" element="tns:Credentials" /> <wsdl:part name="TimeZone" element="tns:TimeZone" /> </wsdl:message> <wsdl:message name="SaveTabOrderResponse"> <wsdl:part name="parameters" element="tns:SaveTabOrderResponse" /> </wsdl:message> <wsdl:message name="SaveTabOrderResponse_Headers"> <wsdl:part name="ExceptionInfo" element="tns:ExceptionInfo" /> <wsdl:part name="ExtraInfo" element="tns:ExtraInfo" /> <wsdl:part name="Succeeded" element="tns:Succeeded" /> <wsdl:part name="TimeZone" element="tns:TimeZone" /> </wsdl:message> <wsdl:message name="GetTabOrderRequest"> <wsdl:part name="parameters" element="tns:GetTabOrder" /> </wsdl:message> <wsdl:message name="GetTabOrderRequest_Headers"> <wsdl:part name="ApplicationToken" element="tns:ApplicationToken" /> <wsdl:part name="Credentials" element="tns:Credentials" /> <wsdl:part name="TimeZone" element="tns:TimeZone" /> </wsdl:message> <wsdl:message name="GetTabOrderResponse"> <wsdl:part name="parameters" element="tns:GetTabOrderResponse" /> </wsdl:message> <wsdl:message name="GetTabOrderResponse_Headers"> <wsdl:part name="ExceptionInfo" element="tns:ExceptionInfo" /> <wsdl:part name="ExtraInfo" element="tns:ExtraInfo" /> <wsdl:part name="Succeeded" element="tns:Succeeded" /> <wsdl:part name="TimeZone" element="tns:TimeZone" /> </wsdl:message> <wsdl:message name="GetPreferenceRequest"> <wsdl:part name="parameters" element="tns:GetPreference" /> </wsdl:message> <wsdl:message name="GetPreferenceRequest_Headers"> <wsdl:part name="ApplicationToken" element="tns:ApplicationToken" /> <wsdl:part name="Credentials" element="tns:Credentials" /> <wsdl:part name="TimeZone" element="tns:TimeZone" /> </wsdl:message> <wsdl:message name="GetPreferenceResponse"> <wsdl:part name="parameters" element="tns:GetPreferenceResponse" /> </wsdl:message> <wsdl:message name="GetPreferenceResponse_Headers"> <wsdl:part name="ExceptionInfo" element="tns:ExceptionInfo" /> <wsdl:part name="ExtraInfo" element="tns:ExtraInfo" /> <wsdl:part name="Succeeded" element="tns:Succeeded" /> <wsdl:part name="TimeZone" element="tns:TimeZone" /> </wsdl:message> <wsdl:message name="SavePreferenceEntityRequest"> <wsdl:part name="parameters" element="tns:SavePreferenceEntity" /> </wsdl:message> <wsdl:message name="SavePreferenceEntityRequest_Headers"> <wsdl:part name="ApplicationToken" element="tns:ApplicationToken" /> <wsdl:part name="Credentials" element="tns:Credentials" /> <wsdl:part name="TimeZone" element="tns:TimeZone" /> </wsdl:message> <wsdl:message name="SavePreferenceEntityResponse"> <wsdl:part name="parameters" element="tns:SavePreferenceEntityResponse" /> </wsdl:message> <wsdl:message name="SavePreferenceEntityResponse_Headers"> <wsdl:part name="ExceptionInfo" element="tns:ExceptionInfo" /> <wsdl:part name="ExtraInfo" element="tns:ExtraInfo" /> <wsdl:part name="Succeeded" element="tns:Succeeded" /> <wsdl:part name="TimeZone" element="tns:TimeZone" /> </wsdl:message> <wsdl:message name="DeletePreferenceRequest"> <wsdl:part name="parameters" element="tns:DeletePreference" /> </wsdl:message> <wsdl:message name="DeletePreferenceRequest_Headers"> <wsdl:part name="ApplicationToken" element="tns:ApplicationToken" /> <wsdl:part name="Credentials" element="tns:Credentials" /> <wsdl:part name="TimeZone" element="tns:TimeZone" /> </wsdl:message> <wsdl:message name="DeletePreferenceResponse"> <wsdl:part name="parameters" element="tns:DeletePreferenceResponse" /> </wsdl:message> <wsdl:message name="DeletePreferenceResponse_Headers"> <wsdl:part name="ExceptionInfo" element="tns:ExceptionInfo" /> <wsdl:part name="ExtraInfo" element="tns:ExtraInfo" /> <wsdl:part name="Succeeded" element="tns:Succeeded" /> <wsdl:part name="TimeZone" element="tns:TimeZone" /> </wsdl:message> <wsdl:message name="DeletePreferencesRequest"> <wsdl:part name="parameters" element="tns:DeletePreferences" /> </wsdl:message> <wsdl:message name="DeletePreferencesRequest_Headers"> <wsdl:part name="ApplicationToken" element="tns:ApplicationToken" /> <wsdl:part name="Credentials" element="tns:Credentials" /> <wsdl:part name="TimeZone" element="tns:TimeZone" /> </wsdl:message> <wsdl:message name="DeletePreferencesResponse"> <wsdl:part name="parameters" element="tns:DeletePreferencesResponse" /> </wsdl:message> <wsdl:message name="DeletePreferencesResponse_Headers"> <wsdl:part name="ExceptionInfo" element="tns:ExceptionInfo" /> <wsdl:part name="ExtraInfo" element="tns:ExtraInfo" /> <wsdl:part name="Succeeded" element="tns:Succeeded" /> <wsdl:part name="TimeZone" element="tns:TimeZone" /> </wsdl:message> <wsdl:message name="GetPreferenceByNameRequest"> <wsdl:part name="parameters" element="tns:GetPreferenceByName" /> </wsdl:message> <wsdl:message name="GetPreferenceByNameRequest_Headers"> <wsdl:part name="ApplicationToken" element="tns:ApplicationToken" /> <wsdl:part name="Credentials" element="tns:Credentials" /> <wsdl:part name="TimeZone" element="tns:TimeZone" /> </wsdl:message> <wsdl:message name="GetPreferenceByNameResponse"> <wsdl:part name="parameters" element="tns:GetPreferenceByNameResponse" /> </wsdl:message> <wsdl:message name="GetPreferenceByNameResponse_Headers"> <wsdl:part name="ExceptionInfo" element="tns:ExceptionInfo" /> <wsdl:part name="ExtraInfo" element="tns:ExtraInfo" /> <wsdl:part name="Succeeded" element="tns:Succeeded" /> <wsdl:part name="TimeZone" element="tns:TimeZone" /> </wsdl:message> <wsdl:message name="GetNetServicesStatusUrlRequest"> <wsdl:part name="parameters" element="tns:GetNetServicesStatusUrl" /> </wsdl:message> <wsdl:message name="GetNetServicesStatusUrlRequest_Headers"> <wsdl:part name="ApplicationToken" element="tns:ApplicationToken" /> <wsdl:part name="Credentials" element="tns:Credentials" /> <wsdl:part name="TimeZone" element="tns:TimeZone" /> </wsdl:message> <wsdl:message name="GetNetServicesStatusUrlResponse"> <wsdl:part name="parameters" element="tns:GetNetServicesStatusUrlResponse" /> </wsdl:message> <wsdl:message name="GetNetServicesStatusUrlResponse_Headers"> <wsdl:part name="ExceptionInfo" element="tns:ExceptionInfo" /> <wsdl:part name="ExtraInfo" element="tns:ExtraInfo" /> <wsdl:part name="Succeeded" element="tns:Succeeded" /> <wsdl:part name="TimeZone" element="tns:TimeZone" /> </wsdl:message> <wsdl:message name="UpdateNetServicesStatusRequest"> <wsdl:part name="parameters" element="tns:UpdateNetServicesStatus" /> </wsdl:message> <wsdl:message name="UpdateNetServicesStatusRequest_Headers"> <wsdl:part name="ApplicationToken" element="tns:ApplicationToken" /> <wsdl:part name="Credentials" element="tns:Credentials" /> <wsdl:part name="TimeZone" element="tns:TimeZone" /> </wsdl:message> <wsdl:message name="UpdateNetServicesStatusResponse"> <wsdl:part name="parameters" element="tns:UpdateNetServicesStatusResponse" /> </wsdl:message> <wsdl:message name="UpdateNetServicesStatusResponse_Headers"> <wsdl:part name="ExceptionInfo" element="tns:ExceptionInfo" /> <wsdl:part name="ExtraInfo" element="tns:ExtraInfo" /> <wsdl:part name="Succeeded" element="tns:Succeeded" /> <wsdl:part name="TimeZone" element="tns:TimeZone" /> </wsdl:message> <wsdl:message name="GetPreferenceDescriptionRequest"> <wsdl:part name="parameters" element="tns:GetPreferenceDescription" /> </wsdl:message> <wsdl:message name="GetPreferenceDescriptionRequest_Headers"> <wsdl:part name="ApplicationToken" element="tns:ApplicationToken" /> <wsdl:part name="Credentials" element="tns:Credentials" /> <wsdl:part name="TimeZone" element="tns:TimeZone" /> </wsdl:message> <wsdl:message name="GetPreferenceDescriptionResponse"> <wsdl:part name="parameters" element="tns:GetPreferenceDescriptionResponse" /> </wsdl:message> <wsdl:message name="GetPreferenceDescriptionResponse_Headers"> <wsdl:part name="ExceptionInfo" element="tns:ExceptionInfo" /> <wsdl:part name="ExtraInfo" element="tns:ExtraInfo" /> <wsdl:part name="Succeeded" element="tns:Succeeded" /> <wsdl:part name="TimeZone" element="tns:TimeZone" /> </wsdl:message> <wsdl:message name="GetFromSectionAndKeyRequest"> <wsdl:part name="parameters" element="tns:GetFromSectionAndKey" /> </wsdl:message> <wsdl:message name="GetFromSectionAndKeyRequest_Headers"> <wsdl:part name="ApplicationToken" element="tns:ApplicationToken" /> <wsdl:part name="Credentials" element="tns:Credentials" /> <wsdl:part name="TimeZone" element="tns:TimeZone" /> </wsdl:message> <wsdl:message name="GetFromSectionAndKeyResponse"> <wsdl:part name="parameters" element="tns:GetFromSectionAndKeyResponse" /> </wsdl:message> <wsdl:message name="GetFromSectionAndKeyResponse_Headers"> <wsdl:part name="ExceptionInfo" element="tns:ExceptionInfo" /> <wsdl:part name="ExtraInfo" element="tns:ExtraInfo" /> <wsdl:part name="Succeeded" element="tns:Succeeded" /> <wsdl:part name="TimeZone" element="tns:TimeZone" /> </wsdl:message> <wsdl:message name="GetAllRequest"> <wsdl:part name="parameters" element="tns:GetAll" /> </wsdl:message> <wsdl:message name="GetAllRequest_Headers"> <wsdl:part name="ApplicationToken" element="tns:ApplicationToken" /> <wsdl:part name="Credentials" element="tns:Credentials" /> <wsdl:part name="TimeZone" element="tns:TimeZone" /> </wsdl:message> <wsdl:message name="GetAllResponse"> <wsdl:part name="parameters" element="tns:GetAllResponse" /> </wsdl:message> <wsdl:message name="GetAllResponse_Headers"> <wsdl:part name="ExceptionInfo" element="tns:ExceptionInfo" /> <wsdl:part name="ExtraInfo" element="tns:ExtraInfo" /> <wsdl:part name="Succeeded" element="tns:Succeeded" /> <wsdl:part name="TimeZone" element="tns:TimeZone" /> </wsdl:message> <wsdl:message name="GetAllFromSectionRequest"> <wsdl:part name="parameters" element="tns:GetAllFromSection" /> </wsdl:message> <wsdl:message name="GetAllFromSectionRequest_Headers"> <wsdl:part name="ApplicationToken" element="tns:ApplicationToken" /> <wsdl:part name="Credentials" element="tns:Credentials" /> <wsdl:part name="TimeZone" element="tns:TimeZone" /> </wsdl:message> <wsdl:message name="GetAllFromSectionResponse"> <wsdl:part name="parameters" element="tns:GetAllFromSectionResponse" /> </wsdl:message> <wsdl:message name="GetAllFromSectionResponse_Headers"> <wsdl:part name="ExceptionInfo" element="tns:ExceptionInfo" /> <wsdl:part name="ExtraInfo" element="tns:ExtraInfo" /> <wsdl:part name="Succeeded" element="tns:Succeeded" /> <wsdl:part name="TimeZone" element="tns:TimeZone" /> </wsdl:message> <wsdl:message name="SaveFromSectionAndKeyRequest"> <wsdl:part name="parameters" element="tns:SaveFromSectionAndKey" /> </wsdl:message> <wsdl:message name="SaveFromSectionAndKeyRequest_Headers"> <wsdl:part name="ApplicationToken" element="tns:ApplicationToken" /> <wsdl:part name="Credentials" element="tns:Credentials" /> <wsdl:part name="TimeZone" element="tns:TimeZone" /> </wsdl:message> <wsdl:message name="SaveFromSectionAndKeyResponse"> <wsdl:part name="parameters" element="tns:SaveFromSectionAndKeyResponse" /> </wsdl:message> <wsdl:message name="SaveFromSectionAndKeyResponse_Headers"> <wsdl:part name="ExceptionInfo" element="tns:ExceptionInfo" /> <wsdl:part name="ExtraInfo" element="tns:ExtraInfo" /> <wsdl:part name="Succeeded" element="tns:Succeeded" /> <wsdl:part name="TimeZone" element="tns:TimeZone" /> </wsdl:message> <wsdl:message name="DeleteFromSectionAndKeyRequest"> <wsdl:part name="parameters" element="tns:DeleteFromSectionAndKey" /> </wsdl:message> <wsdl:message name="DeleteFromSectionAndKeyRequest_Headers"> <wsdl:part name="ApplicationToken" element="tns:ApplicationToken" /> <wsdl:part name="Credentials" element="tns:Credentials" /> <wsdl:part name="TimeZone" element="tns:TimeZone" /> </wsdl:message> <wsdl:message name="DeleteFromSectionAndKeyResponse"> <wsdl:part name="parameters" element="tns:DeleteFromSectionAndKeyResponse" /> </wsdl:message> <wsdl:message name="DeleteFromSectionAndKeyResponse_Headers"> <wsdl:part name="ExceptionInfo" element="tns:ExceptionInfo" /> <wsdl:part name="ExtraInfo" element="tns:ExtraInfo" /> <wsdl:part name="Succeeded" element="tns:Succeeded" /> <wsdl:part name="TimeZone" element="tns:TimeZone" /> </wsdl:message> <wsdl:message name="GetPreferenceDescriptionLineRequest"> <wsdl:part name="parameters" element="tns:GetPreferenceDescriptionLine" /> </wsdl:message> <wsdl:message name="GetPreferenceDescriptionLineRequest_Headers"> <wsdl:part name="ApplicationToken" element="tns:ApplicationToken" /> <wsdl:part name="Credentials" element="tns:Credentials" /> <wsdl:part name="TimeZone" element="tns:TimeZone" /> </wsdl:message> <wsdl:message name="GetPreferenceDescriptionLineResponse"> <wsdl:part name="parameters" element="tns:GetPreferenceDescriptionLineResponse" /> </wsdl:message> <wsdl:message name="GetPreferenceDescriptionLineResponse_Headers"> <wsdl:part name="ExceptionInfo" element="tns:ExceptionInfo" /> <wsdl:part name="ExtraInfo" element="tns:ExtraInfo" /> <wsdl:part name="Succeeded" element="tns:Succeeded" /> <wsdl:part name="TimeZone" element="tns:TimeZone" /> </wsdl:message> <wsdl:message name="GetPreferenceDescriptionLineFromIdAndValueRequest"> <wsdl:part name="parameters" element="tns:GetPreferenceDescriptionLineFromIdAndValue" /> </wsdl:message> <wsdl:message name="GetPreferenceDescriptionLineFromIdAndValueRequest_Headers"> <wsdl:part name="ApplicationToken" element="tns:ApplicationToken" /> <wsdl:part name="Credentials" element="tns:Credentials" /> <wsdl:part name="TimeZone" element="tns:TimeZone" /> </wsdl:message> <wsdl:message name="GetPreferenceDescriptionLineFromIdAndValueResponse"> <wsdl:part name="parameters" element="tns:GetPreferenceDescriptionLineFromIdAndValueResponse" /> </wsdl:message> <wsdl:message name="GetPreferenceDescriptionLineFromIdAndValueResponse_Headers"> <wsdl:part name="ExceptionInfo" element="tns:ExceptionInfo" /> <wsdl:part name="ExtraInfo" element="tns:ExtraInfo" /> <wsdl:part name="Succeeded" element="tns:Succeeded" /> <wsdl:part name="TimeZone" element="tns:TimeZone" /> </wsdl:message> <wsdl:message name="GetPreferencesRequest"> <wsdl:part name="parameters" element="tns:GetPreferences" /> </wsdl:message> <wsdl:message name="GetPreferencesRequest_Headers"> <wsdl:part name="ApplicationToken" element="tns:ApplicationToken" /> <wsdl:part name="Credentials" element="tns:Credentials" /> <wsdl:part name="TimeZone" element="tns:TimeZone" /> </wsdl:message> <wsdl:message name="GetPreferencesResponse"> <wsdl:part name="parameters" element="tns:GetPreferencesResponse" /> </wsdl:message> <wsdl:message name="GetPreferencesResponse_Headers"> <wsdl:part name="ExceptionInfo" element="tns:ExceptionInfo" /> <wsdl:part name="ExtraInfo" element="tns:ExtraInfo" /> <wsdl:part name="Succeeded" element="tns:Succeeded" /> <wsdl:part name="TimeZone" element="tns:TimeZone" /> </wsdl:message> <wsdl:message name="SavePreferencesRequest"> <wsdl:part name="parameters" element="tns:SavePreferences" /> </wsdl:message> <wsdl:message name="SavePreferencesRequest_Headers"> <wsdl:part name="ApplicationToken" element="tns:ApplicationToken" /> <wsdl:part name="Credentials" element="tns:Credentials" /> <wsdl:part name="TimeZone" element="tns:TimeZone" /> </wsdl:message> <wsdl:message name="SavePreferencesResponse"> <wsdl:part name="parameters" element="tns:SavePreferencesResponse" /> </wsdl:message> <wsdl:message name="SavePreferencesResponse_Headers"> <wsdl:part name="ExceptionInfo" element="tns:ExceptionInfo" /> <wsdl:part name="ExtraInfo" element="tns:ExtraInfo" /> <wsdl:part name="Succeeded" element="tns:Succeeded" /> <wsdl:part name="TimeZone" element="tns:TimeZone" /> </wsdl:message> <wsdl:message name="GetPreferencesWithDisplayValuesRequest"> <wsdl:part name="parameters" element="tns:GetPreferencesWithDisplayValues" /> </wsdl:message> <wsdl:message name="GetPreferencesWithDisplayValuesRequest_Headers"> <wsdl:part name="ApplicationToken" element="tns:ApplicationToken" /> <wsdl:part name="Credentials" element="tns:Credentials" /> <wsdl:part name="TimeZone" element="tns:TimeZone" /> </wsdl:message> <wsdl:message name="GetPreferencesWithDisplayValuesResponse"> <wsdl:part name="parameters" element="tns:GetPreferencesWithDisplayValuesResponse" /> </wsdl:message> <wsdl:message name="GetPreferencesWithDisplayValuesResponse_Headers"> <wsdl:part name="ExceptionInfo" element="tns:ExceptionInfo" /> <wsdl:part name="ExtraInfo" element="tns:ExtraInfo" /> <wsdl:part name="Succeeded" element="tns:Succeeded" /> <wsdl:part name="TimeZone" element="tns:TimeZone" /> </wsdl:message> <wsdl:message name="GetTabOrdersRequest"> <wsdl:part name="parameters" element="tns:GetTabOrders" /> </wsdl:message> <wsdl:message name="GetTabOrdersRequest_Headers"> <wsdl:part name="ApplicationToken" element="tns:ApplicationToken" /> <wsdl:part name="Credentials" element="tns:Credentials" /> <wsdl:part name="TimeZone" element="tns:TimeZone" /> </wsdl:message> <wsdl:message name="GetTabOrdersResponse"> <wsdl:part name="parameters" element="tns:GetTabOrdersResponse" /> </wsdl:message> <wsdl:message name="GetTabOrdersResponse_Headers"> <wsdl:part name="ExceptionInfo" element="tns:ExceptionInfo" /> <wsdl:part name="ExtraInfo" element="tns:ExtraInfo" /> <wsdl:part name="Succeeded" element="tns:Succeeded" /> <wsdl:part name="TimeZone" element="tns:TimeZone" /> </wsdl:message> <wsdl:message name="SaveTabOrdersRequest"> <wsdl:part name="parameters" element="tns:SaveTabOrders" /> </wsdl:message> <wsdl:message name="SaveTabOrdersRequest_Headers"> <wsdl:part name="ApplicationToken" element="tns:ApplicationToken" /> <wsdl:part name="Credentials" element="tns:Credentials" /> <wsdl:part name="TimeZone" element="tns:TimeZone" /> </wsdl:message> <wsdl:message name="SaveTabOrdersResponse"> <wsdl:part name="parameters" element="tns:SaveTabOrdersResponse" /> </wsdl:message> <wsdl:message name="SaveTabOrdersResponse_Headers"> <wsdl:part name="ExceptionInfo" element="tns:ExceptionInfo" /> <wsdl:part name="ExtraInfo" element="tns:ExtraInfo" /> <wsdl:part name="Succeeded" element="tns:Succeeded" /> <wsdl:part name="TimeZone" element="tns:TimeZone" /> </wsdl:message> <wsdl:portType name="Preference"> <wsdl:documentation> <summary>Declaration of Wcf web services for Preference</summary> </wsdl:documentation> <wsdl:operation name="CreateDefaultPreference"> <wsdl:documentation> <summary>Loading default values into a new Preference. NetServer calculates default values (e.g. Country) on the entity, which is required when creating/storing a new instance.</summary> </wsdl:documentation> <wsdl:input wsaw:Action="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/CreateDefaultPreference" name="CreateDefaultPreferenceRequest" message="tns:CreateDefaultPreferenceRequest" /> <wsdl:output wsaw:Action="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/CreateDefaultPreferenceResponse" name="CreateDefaultPreferenceResponse" message="tns:CreateDefaultPreferenceResponse" /> </wsdl:operation> <wsdl:operation name="CreateDefaultPreferenceDescription"> <wsdl:documentation> <summary>Loading default values into a new PreferenceDescription. NetServer calculates default values (e.g. Country) on the entity, which is required when creating/storing a new instance.</summary> </wsdl:documentation> <wsdl:input wsaw:Action="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/CreateDefaultPreferenceDescription" name="CreateDefaultPreferenceDescriptionRequest" message="tns:CreateDefaultPreferenceDescriptionRequest" /> <wsdl:output wsaw:Action="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/CreateDefaultPreferenceDescriptionResponse" name="CreateDefaultPreferenceDescriptionResponse" message="tns:CreateDefaultPreferenceDescriptionResponse" /> </wsdl:operation> <wsdl:operation name="SavePreferenceDescription"> <wsdl:documentation> <summary>Updates the existing PreferenceDescription or creates a new PreferenceDescription if the id parameter is empty.</summary> </wsdl:documentation> <wsdl:input wsaw:Action="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/SavePreferenceDescription" name="SavePreferenceDescriptionRequest" message="tns:SavePreferenceDescriptionRequest" /> <wsdl:output wsaw:Action="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/SavePreferenceDescriptionResponse" name="SavePreferenceDescriptionResponse" message="tns:SavePreferenceDescriptionResponse" /> </wsdl:operation> <wsdl:operation name="DeletePreferenceDescription"> <wsdl:documentation> <summary>Deletes the PreferenceDescription</summary> </wsdl:documentation> <wsdl:input wsaw:Action="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/DeletePreferenceDescription" name="DeletePreferenceDescriptionRequest" message="tns:DeletePreferenceDescriptionRequest" /> <wsdl:output wsaw:Action="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/DeletePreferenceDescriptionResponse" name="DeletePreferenceDescriptionResponse" message="tns:DeletePreferenceDescriptionResponse" /> </wsdl:operation> <wsdl:operation name="CreateDefaultPreferenceDescriptionLine"> <wsdl:documentation> <summary>Loading default values into a new PreferenceDescriptionLine. NetServer calculates default values (e.g. Country) on the entity, which is required when creating/storing a new instance.</summary> </wsdl:documentation> <wsdl:input wsaw:Action="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/CreateDefaultPreferenceDescriptionLine" name="CreateDefaultPreferenceDescriptionLineRequest" message="tns:CreateDefaultPreferenceDescriptionLineRequest" /> <wsdl:output wsaw:Action="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/CreateDefaultPreferenceDescriptionLineResponse" name="CreateDefaultPreferenceDescriptionLineResponse" message="tns:CreateDefaultPreferenceDescriptionLineResponse" /> </wsdl:operation> <wsdl:operation name="SavePreference"> <wsdl:documentation> <summary>Save this preference</summary> </wsdl:documentation> <wsdl:input wsaw:Action="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/SavePreference" name="SavePreferenceRequest" message="tns:SavePreferenceRequest" /> <wsdl:output wsaw:Action="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/SavePreferenceResponse" name="SavePreferenceResponse" message="tns:SavePreferenceResponse" /> </wsdl:operation> <wsdl:operation name="SaveTabOrder"> <wsdl:documentation> <summary>Saves the tab order. The order is saved pr. user.</summary> </wsdl:documentation> <wsdl:input wsaw:Action="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/SaveTabOrder" name="SaveTabOrderRequest" message="tns:SaveTabOrderRequest" /> <wsdl:output wsaw:Action="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/SaveTabOrderResponse" name="SaveTabOrderResponse" message="tns:SaveTabOrderResponse" /> </wsdl:operation> <wsdl:operation name="GetTabOrder"> <wsdl:documentation> <summary>Gets the tab order.</summary> </wsdl:documentation> <wsdl:input wsaw:Action="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/GetTabOrder" name="GetTabOrderRequest" message="tns:GetTabOrderRequest" /> <wsdl:output wsaw:Action="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/GetTabOrderResponse" name="GetTabOrderResponse" message="tns:GetTabOrderResponse" /> </wsdl:operation> <wsdl:operation name="GetPreference"> <wsdl:documentation> <summary>Get a preference by id</summary> </wsdl:documentation> <wsdl:input wsaw:Action="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/GetPreference" name="GetPreferenceRequest" message="tns:GetPreferenceRequest" /> <wsdl:output wsaw:Action="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/GetPreferenceResponse" name="GetPreferenceResponse" message="tns:GetPreferenceResponse" /> </wsdl:operation> <wsdl:operation name="SavePreferenceEntity"> <wsdl:documentation> <summary>Saves a complete preference object. Preference administrator rights are required to use this</summary> </wsdl:documentation> <wsdl:input wsaw:Action="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/SavePreferenceEntity" name="SavePreferenceEntityRequest" message="tns:SavePreferenceEntityRequest" /> <wsdl:output wsaw:Action="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/SavePreferenceEntityResponse" name="SavePreferenceEntityResponse" message="tns:SavePreferenceEntityResponse" /> </wsdl:operation> <wsdl:operation name="DeletePreference"> <wsdl:documentation> <summary>Delete a preference by id</summary> </wsdl:documentation> <wsdl:input wsaw:Action="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/DeletePreference" name="DeletePreferenceRequest" message="tns:DeletePreferenceRequest" /> <wsdl:output wsaw:Action="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/DeletePreferenceResponse" name="DeletePreferenceResponse" message="tns:DeletePreferenceResponse" /> </wsdl:operation> <wsdl:operation name="DeletePreferences"> <wsdl:documentation> <summary>Delete some preferences by id</summary> </wsdl:documentation> <wsdl:input wsaw:Action="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/DeletePreferences" name="DeletePreferencesRequest" message="tns:DeletePreferencesRequest" /> <wsdl:output wsaw:Action="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/DeletePreferencesResponse" name="DeletePreferencesResponse" message="tns:DeletePreferencesResponse" /> </wsdl:operation> <wsdl:operation name="GetPreferenceByName"> <wsdl:documentation> <summary>Get a preference by name</summary> </wsdl:documentation> <wsdl:input wsaw:Action="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/GetPreferenceByName" name="GetPreferenceByNameRequest" message="tns:GetPreferenceByNameRequest" /> <wsdl:output wsaw:Action="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/GetPreferenceByNameResponse" name="GetPreferenceByNameResponse" message="tns:GetPreferenceByNameResponse" /> </wsdl:operation> <wsdl:operation name="GetNetServicesStatusUrl"> <wsdl:documentation> <summary>Returns URL to status service. e.g. 'https://help.superoffice.com/sodispatcher/v1/status' Returns NULL if status does not need to be checked yet.</summary> </wsdl:documentation> <wsdl:input wsaw:Action="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/GetNetServicesStatusUrl" name="GetNetServicesStatusUrlRequest" message="tns:GetNetServicesStatusUrlRequest" /> <wsdl:output wsaw:Action="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/GetNetServicesStatusUrlResponse" name="GetNetServicesStatusUrlResponse" message="tns:GetNetServicesStatusUrlResponse" /> </wsdl:operation> <wsdl:operation name="UpdateNetServicesStatus"> <wsdl:documentation> <summary>Update the NetServices preferences with values contained in the content from the Status URL</summary> </wsdl:documentation> <wsdl:input wsaw:Action="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/UpdateNetServicesStatus" name="UpdateNetServicesStatusRequest" message="tns:UpdateNetServicesStatusRequest" /> <wsdl:output wsaw:Action="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/UpdateNetServicesStatusResponse" name="UpdateNetServicesStatusResponse" message="tns:UpdateNetServicesStatusResponse" /> </wsdl:operation> <wsdl:operation name="GetPreferenceDescription"> <wsdl:documentation> <summary>Gets a PreferenceDescription object..</summary> </wsdl:documentation> <wsdl:input wsaw:Action="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/GetPreferenceDescription" name="GetPreferenceDescriptionRequest" message="tns:GetPreferenceDescriptionRequest" /> <wsdl:output wsaw:Action="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/GetPreferenceDescriptionResponse" name="GetPreferenceDescriptionResponse" message="tns:GetPreferenceDescriptionResponse" /> </wsdl:operation> <wsdl:operation name="GetFromSectionAndKey"> <wsdl:documentation> <summary>Gets a PreferenceDescription based on the section and key</summary> </wsdl:documentation> <wsdl:input wsaw:Action="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/GetFromSectionAndKey" name="GetFromSectionAndKeyRequest" message="tns:GetFromSectionAndKeyRequest" /> <wsdl:output wsaw:Action="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/GetFromSectionAndKeyResponse" name="GetFromSectionAndKeyResponse" message="tns:GetFromSectionAndKeyResponse" /> </wsdl:operation> <wsdl:operation name="GetAll"> <wsdl:documentation> <summary>Gets a list of all PreferenceDescriptions in the system.</summary> </wsdl:documentation> <wsdl:input wsaw:Action="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/GetAll" name="GetAllRequest" message="tns:GetAllRequest" /> <wsdl:output wsaw:Action="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/GetAllResponse" name="GetAllResponse" message="tns:GetAllResponse" /> </wsdl:operation> <wsdl:operation name="GetAllFromSection"> <wsdl:documentation> <summary>Gets all PreferenceDescription-items in the specified section</summary> </wsdl:documentation> <wsdl:input wsaw:Action="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/GetAllFromSection" name="GetAllFromSectionRequest" message="tns:GetAllFromSectionRequest" /> <wsdl:output wsaw:Action="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/GetAllFromSectionResponse" name="GetAllFromSectionResponse" message="tns:GetAllFromSectionResponse" /> </wsdl:operation> <wsdl:operation name="SaveFromSectionAndKey"> <wsdl:documentation> <summary>Update a PreferenceDescription based on the section and key</summary> </wsdl:documentation> <wsdl:input wsaw:Action="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/SaveFromSectionAndKey" name="SaveFromSectionAndKeyRequest" message="tns:SaveFromSectionAndKeyRequest" /> <wsdl:output wsaw:Action="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/SaveFromSectionAndKeyResponse" name="SaveFromSectionAndKeyResponse" message="tns:SaveFromSectionAndKeyResponse" /> </wsdl:operation> <wsdl:operation name="DeleteFromSectionAndKey"> <wsdl:documentation> <summary>Gets a PreferenceDescription based on the section and key</summary> </wsdl:documentation> <wsdl:input wsaw:Action="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/DeleteFromSectionAndKey" name="DeleteFromSectionAndKeyRequest" message="tns:DeleteFromSectionAndKeyRequest" /> <wsdl:output wsaw:Action="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/DeleteFromSectionAndKeyResponse" name="DeleteFromSectionAndKeyResponse" message="tns:DeleteFromSectionAndKeyResponse" /> </wsdl:operation> <wsdl:operation name="GetPreferenceDescriptionLine"> <wsdl:documentation> <summary>Gets a PreferenceDescriptionLine object..</summary> </wsdl:documentation> <wsdl:input wsaw:Action="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/GetPreferenceDescriptionLine" name="GetPreferenceDescriptionLineRequest" message="tns:GetPreferenceDescriptionLineRequest" /> <wsdl:output wsaw:Action="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/GetPreferenceDescriptionLineResponse" name="GetPreferenceDescriptionLineResponse" message="tns:GetPreferenceDescriptionLineResponse" /> </wsdl:operation> <wsdl:operation name="GetPreferenceDescriptionLineFromIdAndValue"> <wsdl:documentation> <summary>Get a preference description line from a prefDesc_id and a prefValue</summary> </wsdl:documentation> <wsdl:input wsaw:Action="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/GetPreferenceDescriptionLineFromIdAndValue" name="GetPreferenceDescriptionLineFromIdAndValueRequest" message="tns:GetPreferenceDescriptionLineFromIdAndValueRequest" /> <wsdl:output wsaw:Action="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/GetPreferenceDescriptionLineFromIdAndValueResponse" name="GetPreferenceDescriptionLineFromIdAndValueResponse" message="tns:GetPreferenceDescriptionLineFromIdAndValueResponse" /> </wsdl:operation> <wsdl:operation name="GetPreferences"> <wsdl:documentation> <summary>Get one or more preferences based on a set of specifications.&lt;br/&gt;The prefDisplayvalue and prefDisplaytooltip are blank (faster processing relative to GetPreferencesWithDisplayValues)</summary> </wsdl:documentation> <wsdl:input wsaw:Action="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/GetPreferences" name="GetPreferencesRequest" message="tns:GetPreferencesRequest" /> <wsdl:output wsaw:Action="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/GetPreferencesResponse" name="GetPreferencesResponse" message="tns:GetPreferencesResponse" /> </wsdl:operation> <wsdl:operation name="SavePreferences"> <wsdl:documentation> <summary>Save this set of preferences all the way to the database.</summary> </wsdl:documentation> <wsdl:input wsaw:Action="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/SavePreferences" name="SavePreferencesRequest" message="tns:SavePreferencesRequest" /> <wsdl:output wsaw:Action="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/SavePreferencesResponse" name="SavePreferencesResponse" message="tns:SavePreferencesResponse" /> </wsdl:operation> <wsdl:operation name="GetPreferencesWithDisplayValues"> <wsdl:documentation> <summary>Get one or more preferences based on a set of specifications&lt;br/&gt;The PrefDisplayValue and PrefDisplaytooltip are populated, at some additional processing cost.</summary> </wsdl:documentation> <wsdl:input wsaw:Action="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/GetPreferencesWithDisplayValues" name="GetPreferencesWithDisplayValuesRequest" message="tns:GetPreferencesWithDisplayValuesRequest" /> <wsdl:output wsaw:Action="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/GetPreferencesWithDisplayValuesResponse" name="GetPreferencesWithDisplayValuesResponse" message="tns:GetPreferencesWithDisplayValuesResponse" /> </wsdl:operation> <wsdl:operation name="GetTabOrders"> <wsdl:documentation> <summary> </summary> </wsdl:documentation> <wsdl:input wsaw:Action="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/GetTabOrders" name="GetTabOrdersRequest" message="tns:GetTabOrdersRequest" /> <wsdl:output wsaw:Action="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/GetTabOrdersResponse" name="GetTabOrdersResponse" message="tns:GetTabOrdersResponse" /> </wsdl:operation> <wsdl:operation name="SaveTabOrders"> <wsdl:documentation> <summary> </summary> </wsdl:documentation> <wsdl:input wsaw:Action="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/SaveTabOrders" name="SaveTabOrdersRequest" message="tns:SaveTabOrdersRequest" /> <wsdl:output wsaw:Action="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/SaveTabOrdersResponse" name="SaveTabOrdersResponse" message="tns:SaveTabOrdersResponse" /> </wsdl:operation> </wsdl:portType> <wsdl:binding name="BasicHttpBinding_Preference" type="tns:Preference"> <soap:binding transport="http://schemas.xmlsoap.org/soap/http" /> <wsdl:operation name="CreateDefaultPreference"> <soap:operation soapAction="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/CreateDefaultPreference" style="document" /> <wsdl:input name="CreateDefaultPreferenceRequest"> <soap:header message="tns:CreateDefaultPreferenceRequest_Headers" part="ApplicationToken" use="literal" /> <soap:header message="tns:CreateDefaultPreferenceRequest_Headers" part="Credentials" use="literal" /> <soap:header message="tns:CreateDefaultPreferenceRequest_Headers" part="TimeZone" use="literal" /> <soap:body use="literal" /> </wsdl:input> <wsdl:output name="CreateDefaultPreferenceResponse"> <soap:header message="tns:CreateDefaultPreferenceResponse_Headers" part="ExceptionInfo" use="literal" /> <soap:header message="tns:CreateDefaultPreferenceResponse_Headers" part="ExtraInfo" use="literal" /> <soap:header message="tns:CreateDefaultPreferenceResponse_Headers" part="Succeeded" use="literal" /> <soap:header message="tns:CreateDefaultPreferenceResponse_Headers" part="TimeZone" use="literal" /> <soap:body use="literal" /> </wsdl:output> </wsdl:operation> <wsdl:operation name="CreateDefaultPreferenceDescription"> <soap:operation soapAction="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/CreateDefaultPreferenceDescription" style="document" /> <wsdl:input name="CreateDefaultPreferenceDescriptionRequest"> <soap:header message="tns:CreateDefaultPreferenceDescriptionRequest_Headers" part="ApplicationToken" use="literal" /> <soap:header message="tns:CreateDefaultPreferenceDescriptionRequest_Headers" part="Credentials" use="literal" /> <soap:header message="tns:CreateDefaultPreferenceDescriptionRequest_Headers" part="TimeZone" use="literal" /> <soap:body use="literal" /> </wsdl:input> <wsdl:output name="CreateDefaultPreferenceDescriptionResponse"> <soap:header message="tns:CreateDefaultPreferenceDescriptionResponse_Headers" part="ExceptionInfo" use="literal" /> <soap:header message="tns:CreateDefaultPreferenceDescriptionResponse_Headers" part="ExtraInfo" use="literal" /> <soap:header message="tns:CreateDefaultPreferenceDescriptionResponse_Headers" part="Succeeded" use="literal" /> <soap:header message="tns:CreateDefaultPreferenceDescriptionResponse_Headers" part="TimeZone" use="literal" /> <soap:body use="literal" /> </wsdl:output> </wsdl:operation> <wsdl:operation name="SavePreferenceDescription"> <soap:operation soapAction="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/SavePreferenceDescription" style="document" /> <wsdl:input name="SavePreferenceDescriptionRequest"> <soap:header message="tns:SavePreferenceDescriptionRequest_Headers" part="ApplicationToken" use="literal" /> <soap:header message="tns:SavePreferenceDescriptionRequest_Headers" part="Credentials" use="literal" /> <soap:header message="tns:SavePreferenceDescriptionRequest_Headers" part="TimeZone" use="literal" /> <soap:body use="literal" /> </wsdl:input> <wsdl:output name="SavePreferenceDescriptionResponse"> <soap:header message="tns:SavePreferenceDescriptionResponse_Headers" part="ExceptionInfo" use="literal" /> <soap:header message="tns:SavePreferenceDescriptionResponse_Headers" part="ExtraInfo" use="literal" /> <soap:header message="tns:SavePreferenceDescriptionResponse_Headers" part="Succeeded" use="literal" /> <soap:header message="tns:SavePreferenceDescriptionResponse_Headers" part="TimeZone" use="literal" /> <soap:body use="literal" /> </wsdl:output> </wsdl:operation> <wsdl:operation name="DeletePreferenceDescription"> <soap:operation soapAction="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/DeletePreferenceDescription" style="document" /> <wsdl:input name="DeletePreferenceDescriptionRequest"> <soap:header message="tns:DeletePreferenceDescriptionRequest_Headers" part="ApplicationToken" use="literal" /> <soap:header message="tns:DeletePreferenceDescriptionRequest_Headers" part="Credentials" use="literal" /> <soap:header message="tns:DeletePreferenceDescriptionRequest_Headers" part="TimeZone" use="literal" /> <soap:body use="literal" /> </wsdl:input> <wsdl:output name="DeletePreferenceDescriptionResponse"> <soap:header message="tns:DeletePreferenceDescriptionResponse_Headers" part="ExceptionInfo" use="literal" /> <soap:header message="tns:DeletePreferenceDescriptionResponse_Headers" part="ExtraInfo" use="literal" /> <soap:header message="tns:DeletePreferenceDescriptionResponse_Headers" part="Succeeded" use="literal" /> <soap:header message="tns:DeletePreferenceDescriptionResponse_Headers" part="TimeZone" use="literal" /> <soap:body use="literal" /> </wsdl:output> </wsdl:operation> <wsdl:operation name="CreateDefaultPreferenceDescriptionLine"> <soap:operation soapAction="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/CreateDefaultPreferenceDescriptionLine" style="document" /> <wsdl:input name="CreateDefaultPreferenceDescriptionLineRequest"> <soap:header message="tns:CreateDefaultPreferenceDescriptionLineRequest_Headers" part="ApplicationToken" use="literal" /> <soap:header message="tns:CreateDefaultPreferenceDescriptionLineRequest_Headers" part="Credentials" use="literal" /> <soap:header message="tns:CreateDefaultPreferenceDescriptionLineRequest_Headers" part="TimeZone" use="literal" /> <soap:body use="literal" /> </wsdl:input> <wsdl:output name="CreateDefaultPreferenceDescriptionLineResponse"> <soap:header message="tns:CreateDefaultPreferenceDescriptionLineResponse_Headers" part="ExceptionInfo" use="literal" /> <soap:header message="tns:CreateDefaultPreferenceDescriptionLineResponse_Headers" part="ExtraInfo" use="literal" /> <soap:header message="tns:CreateDefaultPreferenceDescriptionLineResponse_Headers" part="Succeeded" use="literal" /> <soap:header message="tns:CreateDefaultPreferenceDescriptionLineResponse_Headers" part="TimeZone" use="literal" /> <soap:body use="literal" /> </wsdl:output> </wsdl:operation> <wsdl:operation name="SavePreference"> <soap:operation soapAction="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/SavePreference" style="document" /> <wsdl:input name="SavePreferenceRequest"> <soap:header message="tns:SavePreferenceRequest_Headers" part="ApplicationToken" use="literal" /> <soap:header message="tns:SavePreferenceRequest_Headers" part="Credentials" use="literal" /> <soap:header message="tns:SavePreferenceRequest_Headers" part="TimeZone" use="literal" /> <soap:body use="literal" /> </wsdl:input> <wsdl:output name="SavePreferenceResponse"> <soap:header message="tns:SavePreferenceResponse_Headers" part="ExceptionInfo" use="literal" /> <soap:header message="tns:SavePreferenceResponse_Headers" part="ExtraInfo" use="literal" /> <soap:header message="tns:SavePreferenceResponse_Headers" part="Succeeded" use="literal" /> <soap:header message="tns:SavePreferenceResponse_Headers" part="TimeZone" use="literal" /> <soap:body use="literal" /> </wsdl:output> </wsdl:operation> <wsdl:operation name="SaveTabOrder"> <soap:operation soapAction="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/SaveTabOrder" style="document" /> <wsdl:input name="SaveTabOrderRequest"> <soap:header message="tns:SaveTabOrderRequest_Headers" part="ApplicationToken" use="literal" /> <soap:header message="tns:SaveTabOrderRequest_Headers" part="Credentials" use="literal" /> <soap:header message="tns:SaveTabOrderRequest_Headers" part="TimeZone" use="literal" /> <soap:body use="literal" /> </wsdl:input> <wsdl:output name="SaveTabOrderResponse"> <soap:header message="tns:SaveTabOrderResponse_Headers" part="ExceptionInfo" use="literal" /> <soap:header message="tns:SaveTabOrderResponse_Headers" part="ExtraInfo" use="literal" /> <soap:header message="tns:SaveTabOrderResponse_Headers" part="Succeeded" use="literal" /> <soap:header message="tns:SaveTabOrderResponse_Headers" part="TimeZone" use="literal" /> <soap:body use="literal" /> </wsdl:output> </wsdl:operation> <wsdl:operation name="GetTabOrder"> <soap:operation soapAction="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/GetTabOrder" style="document" /> <wsdl:input name="GetTabOrderRequest"> <soap:header message="tns:GetTabOrderRequest_Headers" part="ApplicationToken" use="literal" /> <soap:header message="tns:GetTabOrderRequest_Headers" part="Credentials" use="literal" /> <soap:header message="tns:GetTabOrderRequest_Headers" part="TimeZone" use="literal" /> <soap:body use="literal" /> </wsdl:input> <wsdl:output name="GetTabOrderResponse"> <soap:header message="tns:GetTabOrderResponse_Headers" part="ExceptionInfo" use="literal" /> <soap:header message="tns:GetTabOrderResponse_Headers" part="ExtraInfo" use="literal" /> <soap:header message="tns:GetTabOrderResponse_Headers" part="Succeeded" use="literal" /> <soap:header message="tns:GetTabOrderResponse_Headers" part="TimeZone" use="literal" /> <soap:body use="literal" /> </wsdl:output> </wsdl:operation> <wsdl:operation name="GetPreference"> <soap:operation soapAction="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/GetPreference" style="document" /> <wsdl:input name="GetPreferenceRequest"> <soap:header message="tns:GetPreferenceRequest_Headers" part="ApplicationToken" use="literal" /> <soap:header message="tns:GetPreferenceRequest_Headers" part="Credentials" use="literal" /> <soap:header message="tns:GetPreferenceRequest_Headers" part="TimeZone" use="literal" /> <soap:body use="literal" /> </wsdl:input> <wsdl:output name="GetPreferenceResponse"> <soap:header message="tns:GetPreferenceResponse_Headers" part="ExceptionInfo" use="literal" /> <soap:header message="tns:GetPreferenceResponse_Headers" part="ExtraInfo" use="literal" /> <soap:header message="tns:GetPreferenceResponse_Headers" part="Succeeded" use="literal" /> <soap:header message="tns:GetPreferenceResponse_Headers" part="TimeZone" use="literal" /> <soap:body use="literal" /> </wsdl:output> </wsdl:operation> <wsdl:operation name="SavePreferenceEntity"> <soap:operation soapAction="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/SavePreferenceEntity" style="document" /> <wsdl:input name="SavePreferenceEntityRequest"> <soap:header message="tns:SavePreferenceEntityRequest_Headers" part="ApplicationToken" use="literal" /> <soap:header message="tns:SavePreferenceEntityRequest_Headers" part="Credentials" use="literal" /> <soap:header message="tns:SavePreferenceEntityRequest_Headers" part="TimeZone" use="literal" /> <soap:body use="literal" /> </wsdl:input> <wsdl:output name="SavePreferenceEntityResponse"> <soap:header message="tns:SavePreferenceEntityResponse_Headers" part="ExceptionInfo" use="literal" /> <soap:header message="tns:SavePreferenceEntityResponse_Headers" part="ExtraInfo" use="literal" /> <soap:header message="tns:SavePreferenceEntityResponse_Headers" part="Succeeded" use="literal" /> <soap:header message="tns:SavePreferenceEntityResponse_Headers" part="TimeZone" use="literal" /> <soap:body use="literal" /> </wsdl:output> </wsdl:operation> <wsdl:operation name="DeletePreference"> <soap:operation soapAction="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/DeletePreference" style="document" /> <wsdl:input name="DeletePreferenceRequest"> <soap:header message="tns:DeletePreferenceRequest_Headers" part="ApplicationToken" use="literal" /> <soap:header message="tns:DeletePreferenceRequest_Headers" part="Credentials" use="literal" /> <soap:header message="tns:DeletePreferenceRequest_Headers" part="TimeZone" use="literal" /> <soap:body use="literal" /> </wsdl:input> <wsdl:output name="DeletePreferenceResponse"> <soap:header message="tns:DeletePreferenceResponse_Headers" part="ExceptionInfo" use="literal" /> <soap:header message="tns:DeletePreferenceResponse_Headers" part="ExtraInfo" use="literal" /> <soap:header message="tns:DeletePreferenceResponse_Headers" part="Succeeded" use="literal" /> <soap:header message="tns:DeletePreferenceResponse_Headers" part="TimeZone" use="literal" /> <soap:body use="literal" /> </wsdl:output> </wsdl:operation> <wsdl:operation name="DeletePreferences"> <soap:operation soapAction="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/DeletePreferences" style="document" /> <wsdl:input name="DeletePreferencesRequest"> <soap:header message="tns:DeletePreferencesRequest_Headers" part="ApplicationToken" use="literal" /> <soap:header message="tns:DeletePreferencesRequest_Headers" part="Credentials" use="literal" /> <soap:header message="tns:DeletePreferencesRequest_Headers" part="TimeZone" use="literal" /> <soap:body use="literal" /> </wsdl:input> <wsdl:output name="DeletePreferencesResponse"> <soap:header message="tns:DeletePreferencesResponse_Headers" part="ExceptionInfo" use="literal" /> <soap:header message="tns:DeletePreferencesResponse_Headers" part="ExtraInfo" use="literal" /> <soap:header message="tns:DeletePreferencesResponse_Headers" part="Succeeded" use="literal" /> <soap:header message="tns:DeletePreferencesResponse_Headers" part="TimeZone" use="literal" /> <soap:body use="literal" /> </wsdl:output> </wsdl:operation> <wsdl:operation name="GetPreferenceByName"> <soap:operation soapAction="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/GetPreferenceByName" style="document" /> <wsdl:input name="GetPreferenceByNameRequest"> <soap:header message="tns:GetPreferenceByNameRequest_Headers" part="ApplicationToken" use="literal" /> <soap:header message="tns:GetPreferenceByNameRequest_Headers" part="Credentials" use="literal" /> <soap:header message="tns:GetPreferenceByNameRequest_Headers" part="TimeZone" use="literal" /> <soap:body use="literal" /> </wsdl:input> <wsdl:output name="GetPreferenceByNameResponse"> <soap:header message="tns:GetPreferenceByNameResponse_Headers" part="ExceptionInfo" use="literal" /> <soap:header message="tns:GetPreferenceByNameResponse_Headers" part="ExtraInfo" use="literal" /> <soap:header message="tns:GetPreferenceByNameResponse_Headers" part="Succeeded" use="literal" /> <soap:header message="tns:GetPreferenceByNameResponse_Headers" part="TimeZone" use="literal" /> <soap:body use="literal" /> </wsdl:output> </wsdl:operation> <wsdl:operation name="GetNetServicesStatusUrl"> <soap:operation soapAction="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/GetNetServicesStatusUrl" style="document" /> <wsdl:input name="GetNetServicesStatusUrlRequest"> <soap:header message="tns:GetNetServicesStatusUrlRequest_Headers" part="ApplicationToken" use="literal" /> <soap:header message="tns:GetNetServicesStatusUrlRequest_Headers" part="Credentials" use="literal" /> <soap:header message="tns:GetNetServicesStatusUrlRequest_Headers" part="TimeZone" use="literal" /> <soap:body use="literal" /> </wsdl:input> <wsdl:output name="GetNetServicesStatusUrlResponse"> <soap:header message="tns:GetNetServicesStatusUrlResponse_Headers" part="ExceptionInfo" use="literal" /> <soap:header message="tns:GetNetServicesStatusUrlResponse_Headers" part="ExtraInfo" use="literal" /> <soap:header message="tns:GetNetServicesStatusUrlResponse_Headers" part="Succeeded" use="literal" /> <soap:header message="tns:GetNetServicesStatusUrlResponse_Headers" part="TimeZone" use="literal" /> <soap:body use="literal" /> </wsdl:output> </wsdl:operation> <wsdl:operation name="UpdateNetServicesStatus"> <soap:operation soapAction="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/UpdateNetServicesStatus" style="document" /> <wsdl:input name="UpdateNetServicesStatusRequest"> <soap:header message="tns:UpdateNetServicesStatusRequest_Headers" part="ApplicationToken" use="literal" /> <soap:header message="tns:UpdateNetServicesStatusRequest_Headers" part="Credentials" use="literal" /> <soap:header message="tns:UpdateNetServicesStatusRequest_Headers" part="TimeZone" use="literal" /> <soap:body use="literal" /> </wsdl:input> <wsdl:output name="UpdateNetServicesStatusResponse"> <soap:header message="tns:UpdateNetServicesStatusResponse_Headers" part="ExceptionInfo" use="literal" /> <soap:header message="tns:UpdateNetServicesStatusResponse_Headers" part="ExtraInfo" use="literal" /> <soap:header message="tns:UpdateNetServicesStatusResponse_Headers" part="Succeeded" use="literal" /> <soap:header message="tns:UpdateNetServicesStatusResponse_Headers" part="TimeZone" use="literal" /> <soap:body use="literal" /> </wsdl:output> </wsdl:operation> <wsdl:operation name="GetPreferenceDescription"> <soap:operation soapAction="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/GetPreferenceDescription" style="document" /> <wsdl:input name="GetPreferenceDescriptionRequest"> <soap:header message="tns:GetPreferenceDescriptionRequest_Headers" part="ApplicationToken" use="literal" /> <soap:header message="tns:GetPreferenceDescriptionRequest_Headers" part="Credentials" use="literal" /> <soap:header message="tns:GetPreferenceDescriptionRequest_Headers" part="TimeZone" use="literal" /> <soap:body use="literal" /> </wsdl:input> <wsdl:output name="GetPreferenceDescriptionResponse"> <soap:header message="tns:GetPreferenceDescriptionResponse_Headers" part="ExceptionInfo" use="literal" /> <soap:header message="tns:GetPreferenceDescriptionResponse_Headers" part="ExtraInfo" use="literal" /> <soap:header message="tns:GetPreferenceDescriptionResponse_Headers" part="Succeeded" use="literal" /> <soap:header message="tns:GetPreferenceDescriptionResponse_Headers" part="TimeZone" use="literal" /> <soap:body use="literal" /> </wsdl:output> </wsdl:operation> <wsdl:operation name="GetFromSectionAndKey"> <soap:operation soapAction="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/GetFromSectionAndKey" style="document" /> <wsdl:input name="GetFromSectionAndKeyRequest"> <soap:header message="tns:GetFromSectionAndKeyRequest_Headers" part="ApplicationToken" use="literal" /> <soap:header message="tns:GetFromSectionAndKeyRequest_Headers" part="Credentials" use="literal" /> <soap:header message="tns:GetFromSectionAndKeyRequest_Headers" part="TimeZone" use="literal" /> <soap:body use="literal" /> </wsdl:input> <wsdl:output name="GetFromSectionAndKeyResponse"> <soap:header message="tns:GetFromSectionAndKeyResponse_Headers" part="ExceptionInfo" use="literal" /> <soap:header message="tns:GetFromSectionAndKeyResponse_Headers" part="ExtraInfo" use="literal" /> <soap:header message="tns:GetFromSectionAndKeyResponse_Headers" part="Succeeded" use="literal" /> <soap:header message="tns:GetFromSectionAndKeyResponse_Headers" part="TimeZone" use="literal" /> <soap:body use="literal" /> </wsdl:output> </wsdl:operation> <wsdl:operation name="GetAll"> <soap:operation soapAction="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/GetAll" style="document" /> <wsdl:input name="GetAllRequest"> <soap:header message="tns:GetAllRequest_Headers" part="ApplicationToken" use="literal" /> <soap:header message="tns:GetAllRequest_Headers" part="Credentials" use="literal" /> <soap:header message="tns:GetAllRequest_Headers" part="TimeZone" use="literal" /> <soap:body use="literal" /> </wsdl:input> <wsdl:output name="GetAllResponse"> <soap:header message="tns:GetAllResponse_Headers" part="ExceptionInfo" use="literal" /> <soap:header message="tns:GetAllResponse_Headers" part="ExtraInfo" use="literal" /> <soap:header message="tns:GetAllResponse_Headers" part="Succeeded" use="literal" /> <soap:header message="tns:GetAllResponse_Headers" part="TimeZone" use="literal" /> <soap:body use="literal" /> </wsdl:output> </wsdl:operation> <wsdl:operation name="GetAllFromSection"> <soap:operation soapAction="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/GetAllFromSection" style="document" /> <wsdl:input name="GetAllFromSectionRequest"> <soap:header message="tns:GetAllFromSectionRequest_Headers" part="ApplicationToken" use="literal" /> <soap:header message="tns:GetAllFromSectionRequest_Headers" part="Credentials" use="literal" /> <soap:header message="tns:GetAllFromSectionRequest_Headers" part="TimeZone" use="literal" /> <soap:body use="literal" /> </wsdl:input> <wsdl:output name="GetAllFromSectionResponse"> <soap:header message="tns:GetAllFromSectionResponse_Headers" part="ExceptionInfo" use="literal" /> <soap:header message="tns:GetAllFromSectionResponse_Headers" part="ExtraInfo" use="literal" /> <soap:header message="tns:GetAllFromSectionResponse_Headers" part="Succeeded" use="literal" /> <soap:header message="tns:GetAllFromSectionResponse_Headers" part="TimeZone" use="literal" /> <soap:body use="literal" /> </wsdl:output> </wsdl:operation> <wsdl:operation name="SaveFromSectionAndKey"> <soap:operation soapAction="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/SaveFromSectionAndKey" style="document" /> <wsdl:input name="SaveFromSectionAndKeyRequest"> <soap:header message="tns:SaveFromSectionAndKeyRequest_Headers" part="ApplicationToken" use="literal" /> <soap:header message="tns:SaveFromSectionAndKeyRequest_Headers" part="Credentials" use="literal" /> <soap:header message="tns:SaveFromSectionAndKeyRequest_Headers" part="TimeZone" use="literal" /> <soap:body use="literal" /> </wsdl:input> <wsdl:output name="SaveFromSectionAndKeyResponse"> <soap:header message="tns:SaveFromSectionAndKeyResponse_Headers" part="ExceptionInfo" use="literal" /> <soap:header message="tns:SaveFromSectionAndKeyResponse_Headers" part="ExtraInfo" use="literal" /> <soap:header message="tns:SaveFromSectionAndKeyResponse_Headers" part="Succeeded" use="literal" /> <soap:header message="tns:SaveFromSectionAndKeyResponse_Headers" part="TimeZone" use="literal" /> <soap:body use="literal" /> </wsdl:output> </wsdl:operation> <wsdl:operation name="DeleteFromSectionAndKey"> <soap:operation soapAction="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/DeleteFromSectionAndKey" style="document" /> <wsdl:input name="DeleteFromSectionAndKeyRequest"> <soap:header message="tns:DeleteFromSectionAndKeyRequest_Headers" part="ApplicationToken" use="literal" /> <soap:header message="tns:DeleteFromSectionAndKeyRequest_Headers" part="Credentials" use="literal" /> <soap:header message="tns:DeleteFromSectionAndKeyRequest_Headers" part="TimeZone" use="literal" /> <soap:body use="literal" /> </wsdl:input> <wsdl:output name="DeleteFromSectionAndKeyResponse"> <soap:header message="tns:DeleteFromSectionAndKeyResponse_Headers" part="ExceptionInfo" use="literal" /> <soap:header message="tns:DeleteFromSectionAndKeyResponse_Headers" part="ExtraInfo" use="literal" /> <soap:header message="tns:DeleteFromSectionAndKeyResponse_Headers" part="Succeeded" use="literal" /> <soap:header message="tns:DeleteFromSectionAndKeyResponse_Headers" part="TimeZone" use="literal" /> <soap:body use="literal" /> </wsdl:output> </wsdl:operation> <wsdl:operation name="GetPreferenceDescriptionLine"> <soap:operation soapAction="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/GetPreferenceDescriptionLine" style="document" /> <wsdl:input name="GetPreferenceDescriptionLineRequest"> <soap:header message="tns:GetPreferenceDescriptionLineRequest_Headers" part="ApplicationToken" use="literal" /> <soap:header message="tns:GetPreferenceDescriptionLineRequest_Headers" part="Credentials" use="literal" /> <soap:header message="tns:GetPreferenceDescriptionLineRequest_Headers" part="TimeZone" use="literal" /> <soap:body use="literal" /> </wsdl:input> <wsdl:output name="GetPreferenceDescriptionLineResponse"> <soap:header message="tns:GetPreferenceDescriptionLineResponse_Headers" part="ExceptionInfo" use="literal" /> <soap:header message="tns:GetPreferenceDescriptionLineResponse_Headers" part="ExtraInfo" use="literal" /> <soap:header message="tns:GetPreferenceDescriptionLineResponse_Headers" part="Succeeded" use="literal" /> <soap:header message="tns:GetPreferenceDescriptionLineResponse_Headers" part="TimeZone" use="literal" /> <soap:body use="literal" /> </wsdl:output> </wsdl:operation> <wsdl:operation name="GetPreferenceDescriptionLineFromIdAndValue"> <soap:operation soapAction="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/GetPreferenceDescriptionLineFromIdAndValue" style="document" /> <wsdl:input name="GetPreferenceDescriptionLineFromIdAndValueRequest"> <soap:header message="tns:GetPreferenceDescriptionLineFromIdAndValueRequest_Headers" part="ApplicationToken" use="literal" /> <soap:header message="tns:GetPreferenceDescriptionLineFromIdAndValueRequest_Headers" part="Credentials" use="literal" /> <soap:header message="tns:GetPreferenceDescriptionLineFromIdAndValueRequest_Headers" part="TimeZone" use="literal" /> <soap:body use="literal" /> </wsdl:input> <wsdl:output name="GetPreferenceDescriptionLineFromIdAndValueResponse"> <soap:header message="tns:GetPreferenceDescriptionLineFromIdAndValueResponse_Headers" part="ExceptionInfo" use="literal" /> <soap:header message="tns:GetPreferenceDescriptionLineFromIdAndValueResponse_Headers" part="ExtraInfo" use="literal" /> <soap:header message="tns:GetPreferenceDescriptionLineFromIdAndValueResponse_Headers" part="Succeeded" use="literal" /> <soap:header message="tns:GetPreferenceDescriptionLineFromIdAndValueResponse_Headers" part="TimeZone" use="literal" /> <soap:body use="literal" /> </wsdl:output> </wsdl:operation> <wsdl:operation name="GetPreferences"> <soap:operation soapAction="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/GetPreferences" style="document" /> <wsdl:input name="GetPreferencesRequest"> <soap:header message="tns:GetPreferencesRequest_Headers" part="ApplicationToken" use="literal" /> <soap:header message="tns:GetPreferencesRequest_Headers" part="Credentials" use="literal" /> <soap:header message="tns:GetPreferencesRequest_Headers" part="TimeZone" use="literal" /> <soap:body use="literal" /> </wsdl:input> <wsdl:output name="GetPreferencesResponse"> <soap:header message="tns:GetPreferencesResponse_Headers" part="ExceptionInfo" use="literal" /> <soap:header message="tns:GetPreferencesResponse_Headers" part="ExtraInfo" use="literal" /> <soap:header message="tns:GetPreferencesResponse_Headers" part="Succeeded" use="literal" /> <soap:header message="tns:GetPreferencesResponse_Headers" part="TimeZone" use="literal" /> <soap:body use="literal" /> </wsdl:output> </wsdl:operation> <wsdl:operation name="SavePreferences"> <soap:operation soapAction="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/SavePreferences" style="document" /> <wsdl:input name="SavePreferencesRequest"> <soap:header message="tns:SavePreferencesRequest_Headers" part="ApplicationToken" use="literal" /> <soap:header message="tns:SavePreferencesRequest_Headers" part="Credentials" use="literal" /> <soap:header message="tns:SavePreferencesRequest_Headers" part="TimeZone" use="literal" /> <soap:body use="literal" /> </wsdl:input> <wsdl:output name="SavePreferencesResponse"> <soap:header message="tns:SavePreferencesResponse_Headers" part="ExceptionInfo" use="literal" /> <soap:header message="tns:SavePreferencesResponse_Headers" part="ExtraInfo" use="literal" /> <soap:header message="tns:SavePreferencesResponse_Headers" part="Succeeded" use="literal" /> <soap:header message="tns:SavePreferencesResponse_Headers" part="TimeZone" use="literal" /> <soap:body use="literal" /> </wsdl:output> </wsdl:operation> <wsdl:operation name="GetPreferencesWithDisplayValues"> <soap:operation soapAction="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/GetPreferencesWithDisplayValues" style="document" /> <wsdl:input name="GetPreferencesWithDisplayValuesRequest"> <soap:header message="tns:GetPreferencesWithDisplayValuesRequest_Headers" part="ApplicationToken" use="literal" /> <soap:header message="tns:GetPreferencesWithDisplayValuesRequest_Headers" part="Credentials" use="literal" /> <soap:header message="tns:GetPreferencesWithDisplayValuesRequest_Headers" part="TimeZone" use="literal" /> <soap:body use="literal" /> </wsdl:input> <wsdl:output name="GetPreferencesWithDisplayValuesResponse"> <soap:header message="tns:GetPreferencesWithDisplayValuesResponse_Headers" part="ExceptionInfo" use="literal" /> <soap:header message="tns:GetPreferencesWithDisplayValuesResponse_Headers" part="ExtraInfo" use="literal" /> <soap:header message="tns:GetPreferencesWithDisplayValuesResponse_Headers" part="Succeeded" use="literal" /> <soap:header message="tns:GetPreferencesWithDisplayValuesResponse_Headers" part="TimeZone" use="literal" /> <soap:body use="literal" /> </wsdl:output> </wsdl:operation> <wsdl:operation name="GetTabOrders"> <soap:operation soapAction="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/GetTabOrders" style="document" /> <wsdl:input name="GetTabOrdersRequest"> <soap:header message="tns:GetTabOrdersRequest_Headers" part="ApplicationToken" use="literal" /> <soap:header message="tns:GetTabOrdersRequest_Headers" part="Credentials" use="literal" /> <soap:header message="tns:GetTabOrdersRequest_Headers" part="TimeZone" use="literal" /> <soap:body use="literal" /> </wsdl:input> <wsdl:output name="GetTabOrdersResponse"> <soap:header message="tns:GetTabOrdersResponse_Headers" part="ExceptionInfo" use="literal" /> <soap:header message="tns:GetTabOrdersResponse_Headers" part="ExtraInfo" use="literal" /> <soap:header message="tns:GetTabOrdersResponse_Headers" part="Succeeded" use="literal" /> <soap:header message="tns:GetTabOrdersResponse_Headers" part="TimeZone" use="literal" /> <soap:body use="literal" /> </wsdl:output> </wsdl:operation> <wsdl:operation name="SaveTabOrders"> <soap:operation soapAction="http://www.superoffice.net/ws/crm/NetServer/Services84/Preference/SaveTabOrders" style="document" /> <wsdl:input name="SaveTabOrdersRequest"> <soap:header message="tns:SaveTabOrdersRequest_Headers" part="ApplicationToken" use="literal" /> <soap:header message="tns:SaveTabOrdersRequest_Headers" part="Credentials" use="literal" /> <soap:header message="tns:SaveTabOrdersRequest_Headers" part="TimeZone" use="literal" /> <soap:body use="literal" /> </wsdl:input> <wsdl:output name="SaveTabOrdersResponse"> <soap:header message="tns:SaveTabOrdersResponse_Headers" part="ExceptionInfo" use="literal" /> <soap:header message="tns:SaveTabOrdersResponse_Headers" part="ExtraInfo" use="literal" /> <soap:header message="tns:SaveTabOrdersResponse_Headers" part="Succeeded" use="literal" /> <soap:header message="tns:SaveTabOrdersResponse_Headers" part="TimeZone" use="literal" /> <soap:body use="literal" /> </wsdl:output> </wsdl:operation> </wsdl:binding> <wsdl:service name="WcfPreferenceService"> <wsdl:port name="BasicHttpBinding_Preference" binding="tns:BasicHttpBinding_Preference"> <soap:address location="https://sod.superoffice.com/Cust12345/Remote/Services84/Preference.svc" /> </wsdl:port> </wsdl:service> </wsdl:definitions> ``` ======================= File: docs/api-reference/soap/Services86/Ticket/DeleteTicketMessageEntity.md ======================= <reponame>SuperOfficeDocs/data-access<gh_stars>0 --- title: Services86.TicketAgent.DeleteTicketMessageEntity SOAP generated: 1 uid: Services86-Ticket-DeleteTicketMessageEntity --- # Services86 Ticket DeleteTicketMessageEntity SOAP request and response examples **Remote/Services86/Ticket.svc** Implemented by the <see cref="M:SuperOffice.Services86.ITicketAgent.DeleteTicketMessageEntity">SuperOffice.Services86.ITicketAgent.DeleteTicketMessageEntity</see> method. ## DeleteTicketMessageEntity Delete a ticket message * **ticketMessageEntityId:** The ticket message to delete **Returns:** returns void [WSDL file for Services86/Ticket](../Services86-Ticket.md) Obtain a ticket from the [Services86/SoPrincipal.svc](../SoPrincipal/index.md) Application tokens must be specified if calling an Online installation. ApplicationTokens are not checked for on-site installations. ## DeleteTicketMessageEntity Request ```xml <?xml version="1.0" encoding="UTF-8"?> <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://www.w3.org/2003/05/soap-envelope" xmlns:SOAP-ENC="http://www.w3.org/2003/05/soap-encoding" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:NetServerServices862="http://schemas.microsoft.com/2003/10/Serialization/Arrays" xmlns:NetServerServices861="http://schemas.microsoft.com/2003/10/Serialization/" xmlns:Ticket="http://www.superoffice.net/ws/crm/NetServer/Services86"> <Ticket:ApplicationToken><PASSWORD>-<PASSWORD>-<PASSWORD></Ticket:ApplicationToken> <Ticket:Credentials> <Ticket:Ticket>7T:1234abcxyzExample==</Ticket:Ticket> </Ticket:Credentials> <SOAP-ENV:Body> <Ticket:DeleteTicketMessageEntity> <Ticket:TicketMessageEntityId xsi:type="xsd:int">0</Ticket:TicketMessageEntityId> </Ticket:DeleteTicketMessageEntity> </SOAP-ENV:Body> </SOAP-ENV:Envelope> ``` ## DeleteTicketMessageEntity Response ```xml <?xml version="1.0" encoding="UTF-8"?> <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://www.w3.org/2003/05/soap-envelope" xmlns:SOAP-ENC="http://www.w3.org/2003/05/soap-encoding" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:NetServerServices862="http://schemas.microsoft.com/2003/10/Serialization/Arrays" xmlns:NetServerServices861="http://schemas.microsoft.com/2003/10/Serialization/" xmlns:Ticket="http://www.superoffice.net/ws/crm/NetServer/Services86"> <SOAP-ENV:Body> <Ticket:DeleteTicketMessageEntityResponse> </Ticket:DeleteTicketMessageEntityResponse> </SOAP-ENV:Body> </SOAP-ENV:Envelope> ``` ======================= File: docs/api-reference/restful/agent/Replication_Agent/v1ReplicationAgent_GetArea.md ======================= --- title: POST Agents/Replication/GetArea id: v1ReplicationAgent_GetArea --- # POST Agents/Replication/GetArea ```http POST /api/v1/Agents/Replication/GetArea ``` Gets a Area object. ## Online Restricted: ## The Replication agent is not available in Online by default. Not available in Online. Only used on-site. ## Query String Parameters | Parameter Name | Type | Description | |----------------|------|--------------| | areaId | int32 | **Required** The primary key. | | $select | string | Optional comma separated list of properties to include in the result. Other fields are then nulled out to reduce payload size: "Name,department,category". Default = show all fields. | ```http POST /api/v1/Agents/Replication/GetArea?areaId=714 POST /api/v1/Agents/Replication/GetArea?$select=name,department,category/id ``` ## Request Headers | Parameter Name | Description | |----------------|-------------| | Authorization | Supports 'Basic', 'SoTicket' and 'Bearer' schemes, depending on installation type. | | X-XSRF-TOKEN | If not using Authorization header, you must provide XSRF value from cookie or hidden input field | | Accept | Content-type(s) you would like the response in: `application/json`, `text/json`, `application/xml`, `text/xml`, `application/json-patch+json`, `application/merge-patch+json` | | Accept-Language | Convert string references and multi-language values into a specified language (iso2) code. | | SO-Language | Convert string references and multi-language values into a specified language (iso2) code. Overrides Accept-Language value. | | SO-Culture | Number, date formatting in a specified culture (iso2 language) code. Partially overrides SO-Language/Accept-Language value. Ignored if no Language set. | | SO-TimeZone | Specify the timezone code that you would like date/time responses converted to. | | SO-AppToken | The application token that identifies the partner app. Used when calling Online WebAPI from a server. | ## Response: object Carrier object for Area. Services for the Area Carrier is available from the <see cref="T:SuperOffice.CRM.Services.IReplicationAgent">Replication Agent</see>. | Response | Description | |----------------|-------------| | 200 | OK | Response body: object | Property Name | Type | Description | |----------------|------|--------------| | AreaId | int32 | Primary key | | Name | string | Area name | | MaxDataAge | int32 | Max age of data when generating db's based on this area | | NumberOfUsers | int32 | | | NumberOfLogins | int32 | | | FreetextEnabeled | bool | | | TableRight | | | | FieldProperties | object | | ## Sample Request ```http! POST /api/v1/Agents/Replication/GetArea Authorization: Basic dGplMDpUamUw Accept: application/json; charset=utf-8 Accept-Language: sv ``` ```http_ HTTP/1.1 200 OK Content-Type: application/json; charset=utf-8 { "AreaId": 861, "Name": "Bahringer-Rodriguez", "MaxDataAge": 736, "NumberOfUsers": 888, "NumberOfLogins": 335, "FreetextEnabeled": false, "TableRight": { "Mask": "Delete", "Reason": "" }, "FieldProperties": { "fieldName": { "FieldRight": { "Mask": "FULL", "Reason": "" }, "FieldType": "System.String", "FieldLength": 663 } } } ``` ======================= File: docs/api-reference/soap/Services88/List/SetTicketStatusSortOrder.md ======================= --- title: Services88.ListAgent.SetTicketStatusSortOrder SOAP generated: 1 uid: Services88-List-SetTicketStatusSortOrder --- # Services88 List SetTicketStatusSortOrder SOAP request and response examples **Remote/Services88/List.svc** Implemented by the <see cref="M:SuperOffice.Services88.IListAgent.SetTicketStatusSortOrder">SuperOffice.Services88.IListAgent.SetTicketStatusSortOrder</see> method. ## SetTicketStatusSortOrder This method will set sort order of ticket status in a list * **ticketStatusId:** Id of ticket status * **sortOrder:** Indicates the sort order for this status. 1 is first. Any records following this one will be renumbered automatically **Returns:** This method has no return value [WSDL file for Services88/List](../Services88-List.md) Obtain a ticket from the [Services88/SoPrincipal.svc](../SoPrincipal/index.md) Application tokens must be specified if calling an Online installation. ApplicationTokens are not checked for on-site installations. ## SetTicketStatusSortOrder Request ```xml <?xml version="1.0" encoding="UTF-8"?> <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://www.w3.org/2003/05/soap-envelope" xmlns:SOAP-ENC="http://www.w3.org/2003/05/soap-encoding" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:NetServerServices882="http://schemas.microsoft.com/2003/10/Serialization/Arrays" xmlns:NetServerServices881="http://schemas.microsoft.com/2003/10/Serialization/" xmlns:List="http://www.superoffice.net/ws/crm/NetServer/Services88"> <List:ApplicationToken><PASSWORD></List:ApplicationToken> <List:Credentials> <List:Ticket>7T:1234abcxyzExample==</List:Ticket> </List:Credentials> <SOAP-ENV:Body> <List:SetTicketStatusSortOrder> <List:TicketStatusId xsi:type="xsd:int">0</List:TicketStatusId> <List:SortOrder xsi:type="xsd:int">0</List:SortOrder> </List:SetTicketStatusSortOrder> </SOAP-ENV:Body> </SOAP-ENV:Envelope> ``` ## SetTicketStatusSortOrder Response ```xml <?xml version="1.0" encoding="UTF-8"?> <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://www.w3.org/2003/05/soap-envelope" xmlns:SOAP-ENC="http://www.w3.org/2003/05/soap-encoding" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:NetServerServices882="http://schemas.microsoft.com/2003/10/Serialization/Arrays" xmlns:NetServerServices881="http://schemas.microsoft.com/2003/10/Serialization/" xmlns:List="http://www.superoffice.net/ws/crm/NetServer/Services88"> <SOAP-ENV:Body> <List:SetTicketStatusSortOrderResponse> </List:SetTicketStatusSortOrderResponse> </SOAP-ENV:Body> </SOAP-ENV:Envelope> ``` ======================= File: docs/service-soap/ports/ticket/getactiveticketsstatus.md ======================= <filename>docs/service-soap/ports/ticket/getactiveticketsstatus.md<gh_stars>0 --- title: getActiveTicketsStatus uid: cs_soap_ports_ticket_getactiveticketsstatus description: Services SOAP interface ticket reference getActiveTicketsStatus author: {github-id} keywords: soap so.date: 01.25.2021 so.topic: reference --- # getActiveTicketsStatus ## Description Returns all active tickets for the user and their read/unread status. ## In parameters | Parameter | Description | |---|---| | sessionKey | A valid session key | ## Out parameters | Parameter | Description | |---|---| | errorCode | [See list of codes][1] | | ticketStatusResult - An array containing the active tickets:<br>ticketId<br>readStatus – {1=green (read), 2=yellow(new info), 3=red(unread)} | ## Example ```csharp ticket.ticketService ticketService = new ticket.ticketService(); string sessionKey; string errorCode = ticketService.login("egon", "norges bank", out sessionKey); if (errorCode.Equals("0") { ticket.ActiveTicketsStruct[] tickets; getActiveTicketsStatus(sessionKey, out tickets); foreach(ticket.ActiveTicketsStruct i in tickets) { cout << "ticket ID:" << i.ticketId << endl; cout << "read status:" << i.readStatus << endl; } } ``` <!-- Referenced links --> [1]:../../error-codes.md ======================= File: docs/netserver/archive-providers/reference/userpreferences.md ======================= --- uid: UserPreferences title: UserPreferences description: User (and system) preference settings, at all levels keywords: - "archive" - "provider" - "archive provider" - "UserPreferences" so.generated: true so.date: 03.23.2021 so.topic: reference so.envir: - "onsite" - "online" --- # "UserPreferences" This provider name is implemented by the class <see cref="T:SuperOffice.CRM.ArchiveLists.UserPreferencesProvider">SuperOffice.CRM.ArchiveLists.UserPreferencesProvider</see> inside NetServer's SODatabase assembly. User (and system) preference settings, at all levels The <see cref="T:SuperOffice.Data.SoPreference" /> class will return the <b>current</b> setting for a preference for the current principal. This archive provider is for administrative purposes, and returns <b>all</b> settings for the preference(s) selected. <br /> Preferences have multiple sources: the userpreference table (<see cref="T:SuperOffice.CRM.ArchiveLists.UserPreferenceTableProvider" />, and various Service settings that are mapped into preferences, retrieved by <see cref="T:SuperOffice.CRM.ArchiveLists.MappedPreferenceProvider" />. ## Supported Entities | Name | Description | | ---- | ----- | |"default"|[default]| |"system"|[system]| |"database"|Database| |"group"|Group| |"user"|User| ## Supported Columns | Name | Restriction | Description | OrderBy | ---- | ----- | ------- | ------ | |sectionKey|string|Section!Key| | |getAllRows| *None* |GetAll: Get all rows of archive - use with care, you may be fetching the whole database| | |getNoRows| *None* |GetNone: Do not get any rows from the archive| | |userpreferenceId|int|Database ID: The database ID of the row in the userpreference table| x | |deflevel|int|Level: The level at which the preference is defined; closest-to-the-user wins| x | |deflevelname|string|Level: The type of the preference value (string, company, yes/no etc)| x | |maxlevel|int|Max level: The maximum (closest to the user) level this preference is allowed on| x | |maxlevelname|string|Max level: The maximum (closest to the user) level this preference is allowed on| x | |ownerId|int|Owner: The owner of the preference value| x | |owner|string|Who: Who is the owner of this preference value| x | |prefsection|string|Section: The prefsection field in the database| x | |prefkey|string|Key: The prefkey field in the database| x | |prefvalue|string|Raw value: The raw value as it is in the database| x | |value|string|Value: The value of the preference| x | ## Sample ```http! GET /api/v1/archive/UserPreferences?$select=userpreferenceId,prefkey,deflevel Authorization: Basic dGplMDpUamUw Accept: application/json; charset=utf-8 Accept-Language: sv ``` See also: <see cref="T:SuperOffice.CRM.Services.IArchiveAgent">IArchiveAgent</see>.</p> ======================= File: docs/api-reference/restful/rest/Attachment/index.md ======================= <reponame>SuperOfficeDocs/data-access --- title: Attachment --- ```http /api/v1/Attachment ``` * [GET Attachment/default](v1AttachmentEntity_DefaultAttachmentEntity.md) * [POST Attachment](v1AttachmentEntity_PostAttachmentEntity.md) * [GET Attachment/{id}](v1AttachmentEntity_GetAttachmentEntity.md) * [PUT Attachment/{id}](v1AttachmentEntity_PutAttachmentEntity.md) * [PATCH Attachment/{id}](v1AttachmentEntity_PatchAttachmentEntity.md) * [GET Attachment/{id}/Content](v1AttachmentEntity_GetAttachmentStream.md) * [POST Attachment/{id}/Content](v1AttachmentEntity_UploadAttachment.md) ======================= File: docs/api-reference/soap/Services86/ViewState/SetHistoryLengthPrefValue.md ======================= <reponame>SuperOfficeDocs/data-access --- title: Services86.ViewStateAgent.SetHistoryLengthPrefValue SOAP generated: 1 uid: Services86-ViewState-SetHistoryLengthPrefValue --- # Services86 ViewState SetHistoryLengthPrefValue SOAP request and response examples **Remote/Services86/ViewState.svc** Implemented by the <see cref="M:SuperOffice.Services86.IViewStateAgent.SetHistoryLengthPrefValue">SuperOffice.Services86.IViewStateAgent.SetHistoryLengthPrefValue</see> method. ## SetHistoryLengthPrefValue Set the logged on user's preferred history list length. * **length:** The new history list lenght [WSDL file for Services86/ViewState](../Services86-ViewState.md) Obtain a ticket from the [Services86/SoPrincipal.svc](../SoPrincipal/index.md) Application tokens must be specified if calling an Online installation. ApplicationTokens are not checked for on-site installations. ## SetHistoryLengthPrefValue Request ```xml <?xml version="1.0" encoding="UTF-8"?> <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://www.w3.org/2003/05/soap-envelope" xmlns:SOAP-ENC="http://www.w3.org/2003/05/soap-encoding" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:NetServerServices862="http://schemas.microsoft.com/2003/10/Serialization/Arrays" xmlns:NetServerServices861="http://schemas.microsoft.com/2003/10/Serialization/" xmlns:ViewState="http://www.superoffice.net/ws/crm/NetServer/Services86"> <ViewState:ApplicationToken><PASSWORD></ViewState:ApplicationToken> <ViewState:Credentials> <ViewState:Ticket>7T:1234abcxyzExample==</ViewState:Ticket> </ViewState:Credentials> <SOAP-ENV:Body> <ViewState:SetHistoryLengthPrefValue> <ViewState:Length xsi:type="xsd:int">0</ViewState:Length> </ViewState:SetHistoryLengthPrefValue> </SOAP-ENV:Body> </SOAP-ENV:Envelope> ``` ## SetHistoryLengthPrefValue Response ```xml <?xml version="1.0" encoding="UTF-8"?> <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://www.w3.org/2003/05/soap-envelope" xmlns:SOAP-ENC="http://www.w3.org/2003/05/soap-encoding" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:NetServerServices862="http://schemas.microsoft.com/2003/10/Serialization/Arrays" xmlns:NetServerServices861="http://schemas.microsoft.com/2003/10/Serialization/" xmlns:ViewState="http://www.superoffice.net/ws/crm/NetServer/Services86"> <SOAP-ENV:Body> <ViewState:SetHistoryLengthPrefValueResponse> </ViewState:SetHistoryLengthPrefValueResponse> </SOAP-ENV:Body> </SOAP-ENV:Envelope> ``` ======================= File: docs/api-reference/soap/Services84/User/SetPasswordFromName.md ======================= --- title: Services84.UserAgent.SetPasswordFromName SOAP generated: 1 uid: Services84-User-SetPasswordFromName --- # Services84 User SetPasswordFromName SOAP request and response examples **Remote/Services84/User.svc** Implemented by the <see cref="M:SuperOffice.Services84.IUserAgent.SetPasswordFromName">SuperOffice.Services84.IUserAgent.SetPasswordFromName</see> method. ## SetPasswordFromName * **associateName:** * **password:** [WSDL file for Services84/User](../Services84-User.md) Obtain a ticket from the [Services84/SoPrincipal.svc](../SoPrincipal/index.md) Application tokens must be specified if calling an Online installation. ApplicationTokens are not checked for on-site installations. ## SetPasswordFromName Request ```xml <?xml version="1.0" encoding="UTF-8"?> <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://www.w3.org/2003/05/soap-envelope" xmlns:SOAP-ENC="http://www.w3.org/2003/05/soap-encoding" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:NetServerServices842="http://schemas.microsoft.com/2003/10/Serialization/Arrays" xmlns:NetServerServices841="http://schemas.microsoft.com/2003/10/Serialization/" xmlns:User="http://www.superoffice.net/ws/crm/NetServer/Services84"> <User:ApplicationToken><PASSWORD></User:ApplicationToken> <User:Credentials> <User:Ticket>7T:1234abcxyzExample==</User:Ticket> </User:Credentials> <SOAP-ENV:Body> <User:SetPasswordFromName> <User:AssociateName xsi:type="xsd:string"></User:AssociateName> <User:Password xsi:type="xsd:string"></User:Password> </User:SetPasswordFromName> </SOAP-ENV:Body> </SOAP-ENV:Envelope> ``` ## SetPasswordFromName Response ```xml <?xml version="1.0" encoding="UTF-8"?> <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://www.w3.org/2003/05/soap-envelope" xmlns:SOAP-ENC="http://www.w3.org/2003/05/soap-encoding" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:NetServerServices842="http://schemas.microsoft.com/2003/10/Serialization/Arrays" xmlns:NetServerServices841="http://schemas.microsoft.com/2003/10/Serialization/" xmlns:User="http://www.superoffice.net/ws/crm/NetServer/Services84"> <SOAP-ENV:Body> <User:SetPasswordFromNameResponse> <User:Response xsi:type="xsd:boolean">false</User:Response> </User:SetPasswordFromNameResponse> </SOAP-ENV:Body> </SOAP-ENV:Envelope> ``` ======================= File: docs/netserver/lists/entity/create-list-plugin.md ======================= --- title: Create your own list plugin uid: create_list_plugin description: Create a plugin list provider author: {github-id} keywords: so.topic: howto # so.envir: # so.client: --- # Create your own list plugin A plugin is an enhancement or a manipulation that you can develop to an existing NetServer feature. There are many types of plugins that you can develop. Here, we look at plugins you can develop for the various lists in SuperOffice to give your own functionality to those lists. In SuperOffice the lists can be of mainly 2 types: lists that are constructed from a table in the database and lists that have been hard-coded. First, let’s show you how you can develop a plugin for a list that is constructed from a table in the SuperOffice database. This example shows how you can manipulate the country list that is constructed from the `country` table of the SuperOffice database. [!code-csharp[CS](includes/demolist-plugin.cs)] ## MDOProviderPlugin attribute Notice that the class is preceded by an attribute. This tells NetServer that this is a plugin and we give a specific attribute since we want to tell NetServer that this is a plugin of type MDO list provider and the name `MDOProviderPlugin` is the name that is given by NetServer for it to identify this is an MDO list plugin. The `MDOProviderPlugin` attribute must be provided with what is the list that you’re trying to enhance or manipulate as a parameter in the above example it is the country list. > [!NOTE] > It is paramount that we give only one list name as the parameter and that should be the exact name of the table that holds the data and it must be known at compile time. ## MDOProviderBase class Next, we tell NetServer that we have developed a plugin to enhance or manipulate the functionality of the country list. We do this by inheriting the `MDOProviderBase` class and overriding its methods. This is the same class that NetServer uses to implement its own list. So when we override its methods, we supersede the NetServer functionality of the particular list. When you inherit from the `MDOProviderBase` class, you have to implement the `Construct` method and the `HistoryInfo` method. Why? Because you have to specify from which table you are going to pull the Root data and from which table you are going to pull the History data. In the above example, the `Construct` method is overridden to say that the data for the list will be pulled out of the `country` table. We have also inserted a list item called Default country and likewise, you can implement the `Construct` method to suit your application purpose. So now you have enhanced the country list by adding an item to the list. Many methods can be overridden in the `MDOProviderBase` class. For example, you can add some text to the tooltip of the list items: ```csharp protected override string GetItemTooltip(ListTableRow row) { //check for the country name if (row.GetValue("name").ToString() == "Norway") { //add the additional tool tip word to the already //existing tool tip return row.Tooltip + " " + "Home Country"; } else { //if the another country return the default tool tip return row.Tooltip; } } ``` ## Change the data coming to the list Now let’s look at how you can manipulate the actual data that is coming to the list. Let’s write some OSQL ([Objectified SQL][1]). In this example, we are going to override the `GetSimpleListQuery` method of the `MDOProviderBase` class since it is where we have to define our query if we want to get some data that we want. ```csharp private TableInfo tableInfo = null; private ListInfo listInfo = null; protected override ListTableRows.CustomSearch GetSimpleListQuery() { //get the table info tableInfo = TablesInfo.GetTableInfo("country"); //get the list info listInfo = tableInfo.Definition.MDOListInfo; //declare a query of type ListTableRows.CustomSearch ListTableRows.CustomSearch query = new ListTableRows.CustomSearch(tableInfo); //we have to set a common alias for the list item ID tableInfo.Definition.MDOListInfo.PrimaryKey.Alias = new Alias("ListItemId"); //we are retrieving all the fields in the list table query.AdditionalReturnFields.Add(listInfo.ListTable.All); //lets distinct the results query.IsDistinct = true; //lets not take the deleted ones query.Restriction = listInfo.Deleted.Equal(S.Parameter(0)); //order the list by the rank of each item query.OrderBy.Add (listInfo.Rank); //lets take only the countries that starts with A query.Restriction = query.Restriction.And(listInfo.Name.Like("A%")); //return query return query; } ``` Here we filter out only the countries that start with A. See [In depth OSQL][1]. ## Use plugin Now that we have developed our plugin, let's discuss how we can use it. ### Config How do we inform NetServer that we have developed a plugin? We have to specify in our *app.config* file that NetServer should use our new plugin instead. Below is an example of how we have to configure our plugin in the *app.config* file. ```XML <Factory> <DynamicLoad> <add key="PluginDemos" value="C:\\TestApps\\Pulgin\\Pulgin\\bin\\Debug\\Pulgin.dll" /> </DynamicLoad> </Factory> ``` When you declare your *plugin.dll* in the `DynamicLoad` section of the `Factory` section group of your *app.config* file, NetServer will load your DLL along with its other DLLs. ### Example Now let’s see how we can use the developed plugin in a normal Windows forms-based application. Here we will use the plugin that we developed to extend the functionality of the country list. ```csharp using SuperOffice.CRM.Services; using SuperOffice.CRM.Lists; using SuperOffice; using(SoSession session = SoSession.Authenticate("SAL0", "")) { //get the country list. Notice that even though you have not written //a plugin to the country list this is the method that you will call //to get the country list since we have written a plugin NetServer //will execute our plugin instead of the NetServer one ISoListProvider testList = SoLists.GetCountryList(); if (testList.RootItems.Count > 0) { listView1.View = View.List; listView1.ShowItemToolTips = true; int i = 0; //add the root items of the list to the list view foreach (SoListItem item in testList.RootItems) { listView1.Items.Add(item.Name); listView1.Items[i].ToolTipText = testList.RootItems[i].Tooltip; i++; } } } ``` In the above example when we get the country list using the `GetCountryList` method of the `SoLists` class, it will create the list using the methods we overrode and it will revert to the original implementation of the methods that we did not override. So here we will only get the countries that start with the letter A. <!-- Referenced links --> [1]:../../osql/index.md ======================= File: docs/netserver/quote-connectors/api/enums/quoteaction.md ======================= <filename>docs/netserver/quote-connectors/api/enums/quoteaction.md --- title: QuoteAction uid: quote_connector_enum_quoteaction description: ERP Quote Connector Interface enum - QuoteAction author: {github-id} so.date: keywords: quote so.topic: reference --- # QuoteAction An enumeration hinting about what the user has asked for. | Value | Description | |---|---| | Unknown | The system was unable to tell what action has triggered the call. | | Validate | The system just wants to validate. | | SendQuote | The user has pressed the Send Quote button. | | PlaceOrder | The user has pressed the Place Order button. | | UpdatePrices | The user has pressed the update prices button. | ======================= File: docs/api-reference/soap/Services86/Replication/index.md ======================= --- title: Services86.ReplicationAgent SOAP uid: Services86-Replication-soap generated: 1 --- # Services86 Replication SOAP SOAP request and response examples, and WSDL files for **Remote/Services86/Replication.svc** Handled by the <see cref="T:SuperOffice.Services86.IReplicationAgent">SuperOffice.Services86.IReplicationAgent</see> interface. Interface for the Replication Agent Replication/Travel administration <para /><b>Online Restricted:</b> This agent is not available in Online by default. Not available in Online. Only used on-site. Download [WSDL file for Services86/Replication](../Services86-Replication.md) if you need to generate your own proxy code. * [CreateDefaultSatellite](CreateDefaultSatellite.md) * [GetArea](GetArea.md) * [GetAreaList](GetAreaList.md) * [GetCentralLicense](GetCentralLicense.md) * [GetSatellite](GetSatellite.md) * [SaveCentralLicense](SaveCentralLicense.md) * [SaveSatellite](SaveSatellite.md) * [SetFreetextSearchEnabledOnArea](SetFreetextSearchEnabledOnArea.md) ======================= File: docs/documents/services/configure-access.md ======================= --- title: Configuring document access uid: config_document_services description: How to configure document access author: <NAME> so.date: 12.08.2021 keywords: document, API, services, document agent, SO_ARC, ArchivePath, TemporaryPath, ImpersonateUser so.topic: howto so.category: document so.area: api-services --- # Configuring document access For the application to run properly, some modifications are required in the application configuration file. ```XML <Documents> <add key="ArchivePath" value="C:\\SO_ARC" /> <add key="TemporaryPath" value="C:\\temp" /> <add key="ImpersonateUser" value="false" /> </Documents> ``` In this example, we have set the impersonation false because this is a Windows application and the client runs the NetServer code in the same process, and the application inherits the user's identity. Read more about these settings in the [NetServer configuration][1]. <!-- Referenced links --> [1]:../../netserver/config/documents.md <!-- Referenced images --> ======================= File: docs/api-reference/restful/rest/Document/v1DocumentEntity_UndoCheckoutDocument.md ======================= <reponame>SuperOfficeDocs/data-access<filename>docs/api-reference/restful/rest/Document/v1DocumentEntity_UndoCheckoutDocument.md --- title: DEL Document/{id}/Lock id: v1DocumentEntity_UndoCheckoutDocument --- # DEL Document/{id}/Lock ```http DELETE /api/v1/Document/{documentId}/Lock ``` Undo (abandon) a checkout | Path Part | Type | Description | |-----------|------|-------------| | documentId | int32 | SuperOffice document ID **Required** | ## Query String Parameters | Parameter Name | Type | Description | |----------------|------|--------------| | allowedReturnTypes | array | List of return types that the client is prepared to handle, in case the document plugin needs to request additional processing.&lt;br/&gt;Standard allowed return types include 'None', 'Message', 'SoProtocol', 'CustomGui', 'Other'.&lt;br/&gt;An empty array implies that the client places no restriction on possible return action requests. | ```http DELETE /api/v1/Document/{documentId}/Lock?allowedReturnTypes=Message ``` ## Request Headers | Parameter Name | Description | |----------------|-------------| | Authorization | Supports 'Basic', 'SoTicket' and 'Bearer' schemes, depending on installation type. | | X-XSRF-TOKEN | If not using Authorization header, you must provide XSRF value from cookie or hidden input field | | Accept | Content-type(s) you would like the response in: `application/json`, `text/json`, `application/xml`, `text/xml`, `application/json-patch+json`, `application/merge-patch+json` | | SO-AppToken | The application token that identifies the partner app. Used when calling Online WebAPI from a server. | ## Response: object | Response | Description | |----------------|-------------| | 200 | OK | Response body: object | Property Name | Type | Description | |----------------|------|--------------| | ExternalReference | string | | | VersionId | string | | | Success | bool | | | Type | string | | | Value | string | | | AdditionalInfo | string | | ## Sample Request ```http! DELETE /api/v1/Document/{documentId}/Lock Authorization: Basic dGplMDpUamUw Accept: application/json; charset=utf-8 Accept-Language: en ``` ```http_ HTTP/1.1 200 OK Content-Type: application/json; charset=utf-8 { "ExternalReference": "rerum", "VersionId": "id", "Success": false, "Type": "CustomGui", "Value": "quia", "AdditionalInfo": "nobis" } ``` ======================= File: docs/netserver/archive-providers/reference/mail.md ======================= --- uid: Mail title: Mail description: Provides populated mail envelope rows as an archive based on a query string keywords: - "archive" - "provider" - "archive provider" - "Mail" so.generated: true so.date: 03.23.2021 so.topic: reference so.envir: - "onsite" - "online" --- # "Mail" This provider name is implemented by the class <see cref="T:SuperOffice.CRM.ArchiveLists.MailItemSearchProvider">SuperOffice.CRM.ArchiveLists.MailItemSearchProvider</see> inside NetServer's SODatabase assembly. Provides populated mail envelope rows as an archive based on a query string This subclass filter envelopes based on a provided string, only envelopes containing the string in either subject, sender, recipient or date are returned ## Supported Entities | Name | Description | | ---- | ----- | |"companies"|Companies| |"associates"|Associates| |"others"|Others| ## Supported Columns | Name | Restriction | Description | OrderBy | ---- | ----- | ------- | ------ | |id| *None* |ID: ID of the e-mail| | |status| *None* |Status| x | |attachment| *None* |Attachment: Indicates whether the e-mail has one or more attachments| x | |from| *None* |From: The sender of the e-mail| x | |to| *None* |To: The recipient of the e-mail| x | |subject| *None* |Subject: The subject of the e-mail| x | |size| *None* |Size: The size of the e-mail| x | |archived| *None* |Archived: Indicates whether the e-mail has been archived in SuperOffice CRM| | |priority| *None* |Priority: The e-mail's priority| x | |sent| *None* |Date : The time this e-mail was sent at| x | |company| *None* |Company: Company| | |person| *None* |Contact: Contact| | ## Sample ```http! GET /api/v1/archive/Mail?$select=attachment,to,size Authorization: Basic dGplMDpUamUw Accept: application/json; charset=utf-8 Accept-Language: sv ``` See also: <see cref="T:SuperOffice.CRM.Services.IArchiveAgent">IArchiveAgent</see>.</p> ======================= File: docs/api-reference/restful/agent/EMail_Agent/v1EMailAgent_SendEMails.md ======================= --- title: POST Agents/EMail/SendEMails id: v1EMailAgent_SendEMails --- # POST Agents/EMail/SendEMails ```http POST /api/v1/Agents/EMail/SendEMails ``` Send the provided e-mails ## Online Restricted: ## The EMail agent is not available in Online by default. Access must be requested specifically when app is registered. ## Query String Parameters | Parameter Name | Type | Description | |----------------|------|--------------| | $select | string | Optional comma separated list of properties to include in the result. Other fields are then nulled out to reduce payload size: "Name,department,category". Default = show all fields. | ```http POST /api/v1/Agents/EMail/SendEMails?$select=name,department,category/id ``` ## Request Headers | Parameter Name | Description | |----------------|-------------| | Authorization | Supports 'Basic', 'SoTicket' and 'Bearer' schemes, depending on installation type. | | X-XSRF-TOKEN | If not using Authorization header, you must provide XSRF value from cookie or hidden input field | | Content-Type | Content-type of the request body: `application/json`, `text/json`, `application/xml`, `text/xml`, `application/x-www-form-urlencoded`, `application/json-patch+json`, `application/merge-patch+json` | | Accept | Content-type(s) you would like the response in: `application/json`, `text/json`, `application/xml`, `text/xml`, `application/json-patch+json`, `application/merge-patch+json` | | Accept-Language | Convert string references and multi-language values into a specified language (iso2) code. | | SO-Language | Convert string references and multi-language values into a specified language (iso2) code. Overrides Accept-Language value. | | SO-Culture | Number, date formatting in a specified culture (iso2 language) code. Partially overrides SO-Language/Accept-Language value. Ignored if no Language set. | | SO-TimeZone | Specify the timezone code that you would like date/time responses converted to. | | SO-AppToken | The application token that identifies the partner app. Used when calling Online WebAPI from a server. | ## Request Body: request OutgoingConnectionInfo, Emails, SentItemsConnectionInfo | Property Name | Type | Description | |----------------|------|--------------| | OutgoingConnectionInfo | | All information needed to connect to a mailserver <para /> Carrier object for EMailConnectionInfo. Services for the EMailConnectionInfo Carrier is available from the <see cref="T:SuperOffice.CRM.Services.IEMailAgent">EMail Agent</see>. | | Emails | array | | | SentItemsConnectionInfo | | All information needed to connect to a mailserver <para /> Carrier object for EMailConnectionInfo. Services for the EMailConnectionInfo Carrier is available from the <see cref="T:SuperOffice.CRM.Services.IEMailAgent">EMail Agent</see>. | ## Response: array | Response | Description | |----------------|-------------| | 200 | OK | Response body: array | Property Name | Type | Description | |----------------|------|--------------| | To | array | To recipients of e-mail | | Cc | array | Cc recipients of e-mail | | Bcc | array | Bcc recipient of e-mail | | Subject | string | Subject of the e-mail | | HTMLBody | string | Body formatted in HTML | | From | | Who did the e-mail originate from | | Sent | date-time | When was the e-mail sent | | Size | int32 | Total size of the e-mail | | Priority | string | Importance of the e-mail | | Flags | string | Flag status of this mail (unread, replied, deleted ) | | MessageID | string | Unique id of e-mails | | PlainBody | string | Body formatted in plain text | | IsSent | bool | Is this a sent e-mail (not new) | | EMailSOInfo | | Glue between SuperOffice data and an e-mail. | | ServerId | int32 | Unique id for the e-mail on the server | | Attachments | array | | | CustomHeaderList | array | Non standard e-mail headers | | FolderName | string | Name of folder the e-mail belongs in | | EmailItemId | int32 | Primary key | | AccountId | int32 | Account Id | | ReceivedAt | date-time | Received date time | | InReplyTo | | The envelope of the email this email is a reply to, if it exists | | RepliedAt | date-time | When this email was replied at | | HasCalendarData | bool | If this email contains exactly one iCal appointment | | CalMethod | string | Method stored in the associated iCal appointment. Indicates if the iCal data is a reply, counter proposal etc. | | CalReplyStatus | string | Reply status stored in calendar data for the ical method is REPLY | | TableRight | | | | FieldProperties | object | | ## Sample Request ```http! POST /api/v1/Agents/EMail/SendEMails Authorization: Basic dGplMDpUamUw Accept: application/json; charset=utf-8 Accept-Language: en Content-Type: application/json; charset=utf-8 { "OutgoingConnectionInfo": { "ServerName": "Shields-Feil", "UserName": "Dooley Inc and Sons", "Password": "<PASSWORD>", "Folder": "esse", "UseSSL": false }, "Emails": [ { "To": [ {}, {} ], "Cc": [ {}, {} ], "Bcc": [ {}, {} ], "Subject": "vel", "HTMLBody": "blanditiis", "From": {}, "Sent": "2002-07-30T18:28:49.1139282+02:00", "Size": 741, "Priority": "High", "Flags": "Answered", "MessageID": "qui", "PlainBody": "itaque", "IsSent": false, "EMailSOInfo": {}, "ServerId": 994, "Attachments": [ {}, {} ], "CustomHeaderList": [ {}, {} ], "FolderName": "Pollich-Jones", "EmailItemId": 191, "AccountId": 461, "ReceivedAt": "2020-03-19T18:28:49.1139282+01:00", "InReplyTo": {}, "RepliedAt": "2013-03-21T18:28:49.1139282+01:00", "HasCalendarData": false, "CalMethod": "Add", "CalReplyStatus": "Accepted" } ], "SentItemsConnectionInfo": { "ServerName": "Bogan, Ondricka and Stanton", "UserName": "<NAME> and Mertz", "Password": "at", "Folder": "at", "UseSSL": true } } ``` ```http_ HTTP/1.1 200 OK Content-Type: application/json; charset=utf-8 [ { "To": [ { "ContactId": 573, "ContactName": "<NAME> and Ullrich", "PersonId": 832, "PersonName": "<NAME> and Schmeler", "AssociateId": 500, "Address": "incidunt", "EmailId": 733, "DuplicatePersonIds": [ 873, 337 ], "Name": "<NAME> and Howell", "TableRight": {}, "FieldProperties": { "fieldName": { "FieldRight": { "Mask": "FULL", "Reason": "" }, "FieldType": "System.Int32", "FieldLength": 85 } } } ], "Cc": [ { "ContactId": 863, "ContactName": "Hintz Inc and Sons", "PersonId": 215, "PersonName": "<NAME>", "AssociateId": 656, "Address": "et", "EmailId": 382, "DuplicatePersonIds": [ 62, 855 ], "Name": "<NAME>", "TableRight": {}, "FieldProperties": { "fieldName": { "FieldRight": { "Mask": "FULL", "Reason": "" }, "FieldType": "System.Int32", "FieldLength": 302 } } } ], "Bcc": [ { "ContactId": 379, "ContactName": "<NAME> and Hayes", "PersonId": 749, "PersonName": "<NAME> and Windler", "AssociateId": 134, "Address": "veritatis", "EmailId": 445, "DuplicatePersonIds": [ 852, 458 ], "Name": "<NAME> and Swift", "TableRight": {}, "FieldProperties": { "fieldName": { "FieldRight": { "Mask": "FULL", "Reason": "" }, "FieldType": "System.String", "FieldLength": 233 } } } ], "Subject": "ad", "HTMLBody": "possimus", "From": { "ContactId": 177, "ContactName": "<NAME> and Block", "PersonId": 785, "PersonName": "Beer-Considine", "AssociateId": 646, "Address": "et", "EmailId": 221, "DuplicatePersonIds": [ 641, 365 ], "Name": "Hilll-Ruecker", "TableRight": {}, "FieldProperties": { "fieldName": { "FieldRight": { "Mask": "FULL", "Reason": "" }, "FieldType": "System.Int32", "FieldLength": 962 } } }, "Sent": "1995-03-08T18:28:49.1169561+01:00", "Size": 227, "Priority": "High", "Flags": "Answered", "MessageID": "nesciunt", "PlainBody": "repellat", "IsSent": true, "EMailSOInfo": { "DocumentId": 67, "AppointmentId": 914, "ProjectId": 947, "SaleId": 88, "Archived": false, "ArchivedAt": "2002-03-05T18:28:49.1169561+01:00", "ArchivedBy": 604, "ArchivedDisplayName": "Gottlieb-Williamson", "TableRight": {}, "FieldProperties": { "fieldName": { "FieldRight": { "Mask": "FULL", "Reason": "" }, "FieldType": "System.Int32", "FieldLength": 174 } } }, "ServerId": 564, "Attachments": [ { "Description": "Profound web-enabled standardization", "Filename": "et", "Size": 731, "Type": "nihil", "Encoding": "numquam", "Id": "sit", "Disposition": "rerum", "Stream": "GIF89....File contents as raw bytes...", "TableRight": {}, "FieldProperties": { "fieldName": { "FieldRight": { "Mask": "FULL", "Reason": "" }, "FieldType": "System.String", "FieldLength": 146 } } } ], "CustomHeaderList": [ { "Name": "Schoen-Larson", "Values": [ "omnis", "sint" ], "TableRight": {}, "FieldProperties": { "fieldName": { "FieldRight": { "Mask": "FULL", "Reason": "" }, "FieldType": "System.String", "FieldLength": 452 } } }, { "Name": "Schoen-Larson", "Values": [ "omnis", "sint" ], "TableRight": {}, "FieldProperties": { "fieldName": { "FieldRight": { "Mask": "FULL", "Reason": "" }, "FieldType": "System.String", "FieldLength": 452 } } } ], "FolderName": "O'Connell-Turcotte", "EmailItemId": 54, "AccountId": 356, "ReceivedAt": "2008-10-31T18:28:49.1179644+01:00", "InReplyTo": { "ServerId": 750, "MessageId": "quis", "Subject": "in", "From": {}, "To": [ {}, {} ], "Sent": "2000-04-15T18:28:49.1179644+02:00", "Priority": "High", "Flags": "Answered", "Size": 872, "EMailSOInfo": {}, "TableRight": {}, "FieldProperties": { "fieldName": { "FieldRight": { "Mask": "FULL", "Reason": "" }, "FieldType": "System.String", "FieldLength": 593 } } }, "RepliedAt": "2016-06-03T18:28:49.1179644+02:00", "HasCalendarData": false, "CalMethod": "Add", "CalReplyStatus": "Accepted", "TableRight": { "Mask": "Delete", "Reason": "" }, "FieldProperties": { "fieldName": { "FieldRight": { "Mask": "FULL", "Reason": "" }, "FieldType": "System.Int32", "FieldLength": 92 } } } ] ``` ======================= File: docs/netserver/archive-providers/reference/emailcontactaddress.md ======================= <reponame>SuperOfficeDocs/data-access --- uid: emailcontactaddress title: emailcontactaddress description: Contact subchannel for special purpose archive provider used to search for email addresses. keywords: - "archive" - "provider" - "archive provider" - "emailcontactaddress" so.generated: true so.date: 03.23.2021 so.topic: reference so.envir: - "onsite" - "online" --- # "emailcontactaddress" This provider name is implemented by the class <see cref="T:SuperOffice.CRM.ArchiveLists.EmailContactAddressProvider">SuperOffice.CRM.ArchiveLists.EmailContactAddressProvider</see> inside NetServer's SODatabase assembly. Contact subchannel for special purpose archive provider used to search for email addresses. This channel will match on either the email address itself, or contact.name The resulting rows will have entity name 'contact', but the primary key will always be the email_id. ## Supported Entities | Name | Description | | ---- | ----- | |"email"|[email]| |"contact"|Contact| ## Supported Columns | Name | Restriction | Description | OrderBy | ---- | ----- | ------- | ------ | |getAllRows|bool|GetAll: Get all rows of archive - use with care, you may be fetching the whole database| | |getNoRows|bool|GetNone: Do not get any rows from the archive| | |emailMatch|string|emailMatch: Restriction only: (partial) email / person / contact to match| | |emailProtocol|string|Protocol: E-mail protocol, such as SMTP| x | |emailAddress|string|E-mail| x | |emailDescription|string|Description| x | |emailId|int|ID| x | |emailLastSent|datetime|Last sent: The date and time an e-mail was last sent to this address| x | |emailBounceCount|int|Bounce count: Bounce count for this e-mail address| x | |emailLastBounce|datetime|Last bounce: Date and time for last bounce to this e-mail address| x | |emailHasBounced|bool|Has bounced: This checkbox is active if delivery to this e-mail address has failed.| x | |contactId|int|Company ID: Database ID of company| x | |name|stringorPK|Company name| x | |department|string|Department| x | |nameDepartment| *None* |Company: Displays the company an activity is linked to| x | |hasInfoText|bool|Has note: Displays an icon indicating if there is additional information available about the contact| x | |hasInterests|bool|Has interests: Displays an Icon indicating if the contact has active interests| x | |associateId|associate|Our contact: Displays our contact| x | |category|listAny|Category| x | |business|listAny|Business| x | |country|listAny|Country: This criterion corresponds to the Country field on the Company card.| x | |number|string|Number| x | |code|string|Code| x | |orgnr|string|VAT No.| x | |stop|bool|Stop| x | |contactNoMail|bool|No mailings (company| x | |updatedBy|associate|Updated by: The user who last updated the data| x | |updatedDate|date|Updated: The date/time the data was last updated in UTC.| x | |registeredBy|associate|Registered by: The user who registered the data| x | |registeredDate|date|Registered date: The date/time the data was registered in UTC.| x | |contactSource|listAny|Source: Source (Company)| x | |contactDeleted|bool|Deleted: Deleted| x | |phone/formattedNumber|string|Phone : Displays phone number| | |activeErpLinks|bool|ERP connected: Is there an active ERP Sync?| x | |deletedDate|datetime|Deleted date: Deleted date| | |mainContact| *None* |Main contact: Main contact for this company| x | |who| *None* |Company: Displays the name of a selection member's company| x | |contactPhone/formattedNumber|string|Telephone - Phone: Displays phone number| | |contactPhone/description|string|Telephone - Description: Phone number description| x | |contactFax/formattedNumber|string|Fax - Phone: Displays phone number| | |contactFax/description|string|Fax - Description: Phone number description| x | |searchPhone/formattedNumber|string|Searchphone - Phone: Displays phone number| | |searchPhone/description|string|Searchphone - Description: Phone number description| x | |email/emailProtocol|string|Protocol: E-mail protocol, such as SMTP| x | |email/emailAddress|string|E-mail| x | |email/emailDescription|string|Description| x | |email/emailId|int|ID| x | |email/emailLastSent|datetime|Last sent: The date and time an e-mail was last sent to this address| x | |email/emailBounceCount|int|Bounce count: Bounce count for this e-mail address| x | |email/emailLastBounce|datetime|Last bounce: Date and time for last bounce to this e-mail address| x | |email/emailHasBounced|bool|Has bounced: This checkbox is active if delivery to this e-mail address has failed.| x | |postAddress/addressId|int|Postal address - Address ID: Database ID for the address record| x | |postAddress/line1|string|Postal address - Address 1: First line of the address| x | |postAddress/line2|string|Postal address - Address 2: Second line of the address| x | |postAddress/line3|string|Postal address - Address 3: Third line of the address| x | |postAddress/county|string|Postal address - County: This criterion corresponds to the County field on the Company card. It will only be visible if required by a country's address format.| x | |postAddress/city|string|Postal address - City: This criterion corresponds to the City field on the Company card.| x | |postAddress/zip|string|Postal address - Postcode: This criterion corresponds to the Zip Code field on the Company card.| x | |postAddress/state|string|Postal address - State: This criterion corresponds to the State field on the Company card. \It will only be visible if required by a country's address format.| x | |postAddress/wgs84latitude|decimal|Postal address - Latitude: Latitude| x | |postAddress/wgs84longitude|decimal|Postal address - Longitude: Longitude| x | |postAddress/formattedAddress| *None* |Postal address - {formattedAddress}: {formattedAddress}| | |postAddress/formattedMultiLineAddress| *None* |Postal address - {formattedAddress}: {formattedAddress}| | |restrictionPostalAddress/addressId|int|Postal address - Address ID: Database ID for the address record| x | |restrictionPostalAddress/line1|string|Postal address - Address 1: First line of the address| x | |restrictionPostalAddress/line2|string|Postal address - Address 2: Second line of the address| x | |restrictionPostalAddress/line3|string|Postal address - Address 3: Third line of the address| x | |restrictionPostalAddress/county|string|Postal address - County: This criterion corresponds to the County field on the Company card. It will only be visible if required by a country's address format.| x | |restrictionPostalAddress/city|string|Postal address - City: This criterion corresponds to the City field on the Company card.| x | |restrictionPostalAddress/zip|string|Postal address - Postcode: This criterion corresponds to the Zip Code field on the Company card.| x | |restrictionPostalAddress/state|string|Postal address - State: This criterion corresponds to the State field on the Company card. \It will only be visible if required by a country's address format.| x | |restrictionPostalAddress/wgs84latitude|decimal|Postal address - Latitude: Latitude| x | |restrictionPostalAddress/wgs84longitude|decimal|Postal address - Longitude: Longitude| x | |restrictionPostalAddress/formattedAddress| *None* |Postal address - {formattedAddress}: {formattedAddress}| | |restrictionPostalAddress/formattedMultiLineAddress| *None* |Postal address - {formattedAddress}: {formattedAddress}| | |streetAddress/addressId|int|Street address - Address ID: Database ID for the address record| x | |streetAddress/line1|string|Street address - Address 1: First line of the address| x | |streetAddress/line2|string|Street address - Address 2: Second line of the address| x | |streetAddress/line3|string|Street address - Address 3: Third line of the address| x | |streetAddress/county|string|Street address - County: This criterion corresponds to the County field on the Company card. It will only be visible if required by a country's address format.| x | |streetAddress/city|string|Street address - City: This criterion corresponds to the City field on the Company card.| x | |streetAddress/zip|string|Street address - Postcode: This criterion corresponds to the Zip Code field on the Company card.| x | |streetAddress/state|string|Street address - State: This criterion corresponds to the State field on the Company card. \It will only be visible if required by a country's address format.| x | |streetAddress/wgs84latitude|decimal|Street address - Latitude: Latitude| x | |streetAddress/wgs84longitude|decimal|Street address - Longitude: Longitude| x | |streetAddress/formattedAddress| *None* |Street address - {formattedAddress}: {formattedAddress}| | |streetAddress/formattedMultiLineAddress| *None* |Street address - {formattedAddress}: {formattedAddress}| | |restrictionAddress/addressId|int|Search address - Address ID: Database ID for the address record| x | |restrictionAddress/line1|string|Search address - Address 1: First line of the address| x | |restrictionAddress/line2|string|Search address - Address 2: Second line of the address| x | |restrictionAddress/line3|string|Search address - Address 3: Third line of the address| x | |restrictionAddress/county|string|Search address - County: This criterion corresponds to the County field on the Company card. It will only be visible if required by a country's address format.| x | |restrictionAddress/city|string|Search address - City: This criterion corresponds to the City field on the Company card.| x | |restrictionAddress/zip|string|Search address - Postcode: This criterion corresponds to the Zip Code field on the Company card.| x | |restrictionAddress/state|string|Search address - State: This criterion corresponds to the State field on the Company card. \It will only be visible if required by a country's address format.| x | |restrictionAddress/wgs84latitude|decimal|Search address - Latitude: Latitude| x | |restrictionAddress/wgs84longitude|decimal|Search address - Longitude: Longitude| x | |restrictionAddress/formattedAddress| *None* |Search address - {formattedAddress}: {formattedAddress}| | |restrictionAddress/formattedMultiLineAddress| *None* |Search address - {formattedAddress}: {formattedAddress}| | |url/URLAddress|string|URL| x | |url/URLDescription|string|Description| x | |contactAssociate/firstName|string|First name: Displays the contact's first name| x | |contactAssociate/lastName|string|Last name: Displays the contact's last name| x | |contactAssociate/middleName|string|Middle Name : Displays the contact's middle name.| x | |contactAssociate/fullName|string|Full name: Displays full name of user (first, middle, last - according to settings)| x | |contactAssociate/contactId|int|Company ID: Database ID of the company the user belongs to| | |contactAssociate/personId|int|Contact ID: Database ID of the contact row| | |contactAssociate/mrMrs|string|Mr/Ms: Displays whether the contact is addressed as Mr or Ms| x | |contactAssociate/title|string|Title: Displays whether the contact is addressed as Mr or Ms| x | |contactAssociate/associateDbId|associate|ID| x | |contactAssociate/contactName|string|Owning company: Name of the company the user belongs to| x | |contactAssociate/contactDepartment|string|Owning department: Name of the department at the company the user belongs to| x | |contactAssociate/usergroup|userGroup|Primary group: The user's primary user group| x | |contactAssociate/contactFullName|string|Owner: Name and department of the company the user belongs to| x | |contactAssociate/contactCategory|listAny|Category: Category| x | |contactAssociate/role|listAny|Role : Role| x | |contactAssociate/assocName|associate|User ID : User ID| x | |contactAssociate/assocTooltip|string|Description : Description| | |contactAssociate/assocType|listAny|Type: Type of user: associate, external user, system user, anonymous account| x | |contactAssociate/ejUserId|int|Service user ID: The database ID of a Service user| | |contactAssociate/simultaneousEjUser|bool|Simultaneous Service user: If this flag is set, then the user will only have access if the maximum number of simultaneous users is not exceeded| | |contactAssociate/ejDisplayName|string|Nick name: User's nick name in Service| x | |contactAssociate/ejStatus|int|Service status: Status for Service user: Normal; Unavailable / holiday; Deleted; Read-only| | |contactAssociate/credentialType| *None* |Auth. type: What type of credentials to use when this user logs in| x | |contactAssociate/credentialDisplayValue| *None* |Auth. value: Credential value (public, visible part) to be used when this user logs in| x | |contactAssociate/isActive|bool|Active: Is this user active, and should be able to log in?| x | |contactAssociate/isActiveText|bool|Active status: Is this user active, and should be able to log in?| x | |contactAssociate/portraitThumbnail| *None* |Person image: Person image| | |contactAssociate/otherGroups|userGroup|Other groups: Other groups| | |contactAssociate/userName|string|User name: User name| x | |contactAssociate/personEmail|string|E-mail| x | |contactSupportAssociate/firstName|string|Our service contact - First name: Displays the contact's first name| x | |contactSupportAssociate/lastName|string|Our service contact - Last name: Displays the contact's last name| x | |contactSupportAssociate/middleName|string|Our service contact - Middle Name: Displays the contact's middle name.| x | |contactSupportAssociate/fullName|string|Our service contact - Full name: Displays full name of user (first, middle, last - according to settings)| x | |contactSupportAssociate/contactId|int|Our service contact - Company ID: Database ID of the company the user belongs to| | |contactSupportAssociate/personId|int|Our service contact - Contact ID: Database ID of the contact row| | |contactSupportAssociate/mrMrs|string|Our service contact - Mr/Ms: Displays whether the contact is addressed as Mr or Ms| x | |contactSupportAssociate/title|string|Our service contact - Title: Displays whether the contact is addressed as Mr or Ms| x | |contactSupportAssociate/associateDbId|associate|Our service contact - ID| x | |contactSupportAssociate/contactName|string|Our service contact - Owning company: Name of the company the user belongs to| x | |contactSupportAssociate/contactDepartment|string|Our service contact - Owning department: Name of the department at the company the user belongs to| x | |contactSupportAssociate/usergroup|userGroup|Our service contact - Primary group: The user's primary user group| x | |contactSupportAssociate/contactFullName|string|Our service contact - Owner: Name and department of the company the user belongs to| x | |contactSupportAssociate/contactCategory|listAny|Our service contact - Category: Category| x | |contactSupportAssociate/role|listAny|Our service contact - Role: Role| x | |contactSupportAssociate/assocName|associate|Our service contact - User ID: User ID| x | |contactSupportAssociate/assocTooltip|string|Our service contact - Description: Description| | |contactSupportAssociate/assocType|listAny|Our service contact - Type: Type of user: associate, external user, system user, anonymous account| x | |contactSupportAssociate/ejUserId|int|Our service contact - Service user ID: The database ID of a Service user| | |contactSupportAssociate/simultaneousEjUser|bool|Our service contact - Simultaneous Service user: If this flag is set, then the user will only have access if the maximum number of simultaneous users is not exceeded| | |contactSupportAssociate/ejDisplayName|string|Our service contact - Nick name: User's nick name in Service| x | |contactSupportAssociate/ejStatus|int|Our service contact - Service status: Status for Service user: Normal; Unavailable / holiday; Deleted; Read-only| | |contactSupportAssociate/credentialType| *None* |Our service contact - Auth. type: What type of credentials to use when this user logs in| x | |contactSupportAssociate/credentialDisplayValue| *None* |Our service contact - Auth. value: Credential value (public, visible part) to be used when this user logs in| x | |contactSupportAssociate/isActive|bool|Our service contact - Active: Is this user active, and should be able to log in?| x | |contactSupportAssociate/isActiveText|bool|Our service contact - Active status: Is this user active, and should be able to log in?| x | |contactSupportAssociate/portraitThumbnail| *None* |Our service contact - Person image: Person image| | |contactSupportAssociate/otherGroups|userGroup|Our service contact - Other groups: Other groups| | |contactSupportAssociate/userName|string|Our service contact - User name: User name| x | |contactSupportAssociate/personEmail|string|Our service contact - E-mail| x | |contactSupportPerson/personId|int|User support contact - DB ID: Displays the database ID of a contact| x | |contactSupportPerson/firstName|string|User support contact - First name: Displays the contact's first name| x | |contactSupportPerson/lastName|string|User support contact - Last name: Displays the contact's last name| x | |contactSupportPerson/middleName|string|User support contact - Middle name: Displays the contact's middle name.| x | |contactSupportPerson/fullName|stringorPK|User support contact - Contact: Displays the contact to which an item is linked| x | |contactSupportPerson/contactId|int|User support contact - Company ID: Database ID of company| x | |contactSupportPerson/hasInfoText|bool|User support contact - Has note: Displays an icon indicating if there is additional information available about the contact| x | |contactSupportPerson/hasInterests|bool|User support contact - Has interests: Displays an Icon indicating if the contact has active interests| x | |contactSupportPerson/personHasInterests|bool|User support contact - Has interests: Displays an Icon indicating if the contact has active interests| x | |contactSupportPerson/mrMrs|string|User support contact - Mr/Ms: Displays whether the contact is addressed as Mr or Ms| x | |contactSupportPerson/position|listAny|User support contact - Position| x | |contactSupportPerson/personNumber|string|User support contact - Number: Displays the contact's number| x | |contactSupportPerson/title|string|User support contact - Title: Displays the contact's job title| x | |contactSupportPerson/personCountry|listAny|User support contact - Country: Country| x | |contactSupportPerson/personNoMail|bool|User support contact - No Mailings: Displays the contact's No Mailings checkbox| x | |contactSupportPerson/rank|int|User support contact - Rank: Displays a contact's current rank| x | |contactSupportPerson/birthdate| *None* |User support contact - Birthdate: Displays the contact's date of birth| | |contactSupportPerson/associateType| *None* |User support contact - User type: Displays an icon indicating if a contact is an associate or external contact with log-in rights and currently online. This information is updated only once while the archive is loading.| | |contactSupportPerson/useAsMailingAddress|bool|User support contact - Use as postal address: Use as postal address| x | |contactSupportPerson/personSource|listAny|User support contact - Source: Source (Contact)| x | |contactSupportPerson/retired|bool|User support contact - Former employee: Indicates whether the contact has retired/left the company| x | |contactSupportPerson/birthYear|int|User support contact - Birth year: Displays contact's birth year| x | |contactSupportPerson/birthMonth|int|User support contact - Birth month: Displays contact's birth month| x | |contactSupportPerson/birthDay|int|User support contact - Birth day: Displays contact's birth day (day of month)| x | |contactSupportPerson/kanaFirstName|string|User support contact - First name, kana: Contact's first name, in kana alphabet| x | |contactSupportPerson/kanaLastName|string|User support contact - Last name, kana: Contact's last name, in kana alphabet| x | |contactSupportPerson/personUpdatedBy|associate|User support contact - Updated by: The user who last updated the data| x | |contactSupportPerson/personUpdatedDate|date|User support contact - Updated: The date/time the data was last updated in UTC.| x | |contactSupportPerson/personRegisteredBy|associate|User support contact - Registered by: The user who registered the data| x | |contactSupportPerson/personRegisteredDate|date|User support contact - Registered date: The date/time the data was registered in UTC.| x | |contactSupportPerson/portraitThumbnail| *None* |User support contact - Person image: Person image| | |contactSupportPerson/personActiveErpLinks|bool|User support contact - ERP connected: Is there an active ERP Sync?| x | |contactSupportPerson/ticketPriority|listAny|User support contact - Service priority: Default service priority for this contact| x | |contactSupportPerson/supportLanguage|listAny|User support contact - Preferred language: Preferred language used for reply templates and more| x | |contactSupportPerson/supportAssociate|associate|User support contact - Our service contact: Default service contact for this contact| x | |contactSupportPerson/personAssociateId|associate|User support contact - Our contact: Displays our contact| x | |contactSupportPerson/personCategory|listAny|User support contact - Category| x | |contactSupportPerson/personBusiness|listAny|User support contact - Business| x | |contactSupportPerson/personDeletedDate|datetime|User support contact - Deleted date: Deleted date| | |contactSupportPerson/hasCompany|bool|User support contact - Has company: The contact is associated with a company| x | |contactSupportPerson/isProjectMember|bool|User support contact - Is project member: This person is a project member| x | |contactSupportPerson/isStakeholder|bool|User support contact - Is stakeholder: This person is a sale stakeholder| x | |contactSupportPerson/who| *None* |User support contact - Full name: Displays the contact's full name.| x | |contactSupportPerson/personInfo/textId|int|User support contact - Text ID| x | |contactSupportPerson/personInfo/infoText|positiveString|User support contact - Information: Displays the text entered in the description field| x | |contactSupportPerson/personUdef/SuperOffice:1|string|User support contact - contactshorttext: tooltipshorttext| x | |contactSupportPerson/personUdef/SuperOffice:2|string|User support contact - contactlongtext: tooltiplongtext| x | |contactSupportPerson/personUdef/SuperOffice:3|int|User support contact - contactnumber| x | |contactSupportPerson/personUdef/SuperOffice:4|date|User support contact - contactdate| x | |contactSupportPerson/personUdef/SuperOffice:5|unlimitedDate|User support contact - contactunlimiteddate: tooltipunlimiteddate| x | |contactSupportPerson/personUdef/SuperOffice:6|bool|User support contact - contactcheckbox| x | |contactSupportPerson/personUdef/SuperOffice:7|listAny|User support contact - contactdropdownlistbox| x | |contactSupportPerson/personUdef/SuperOffice:8|decimal|User support contact - contactdecimal| x | |contactSupportPerson/personUdef/SuperOffice:9|string|User support contact - page1saleonly| x | |contactSupportPerson/personUdef/SuperOffice:10|string|User support contact - page1marketingonly| x | |contactSupportPerson/personUdef/SuperOffice:11|string|User support contact - page1adminonly| x | |contactSupportPerson/isMailingRecipient|bool|User support contact - isMailingRecipient: isMailingRecipient| x | |contactSupportPerson/hasStoreConsent|bool|User support contact - Consent - Sales and service: The purpose to store data about this contact is to sell to and/or provide services to this contact. This purpose is usually used when storing contacts who are defined as potential or existing customers.| | |contactSupportPerson/withdrawnStoreConsent|bool|User support contact - Consent is withdrawn - Sales and service: The purpose to store data about this contact is to sell to and/or provide services to this contact. This purpose is usually used when storing contacts who are defined as potential or existing customers.| | |contactSupportPerson/hasEmarketingConsent|bool|User support contact - Consent - E-marketing: The purpose is to gain the explicit consent to communicate electronically (bulk e-mail) on topics related to our products and services. This might include newsletters, invitations and product-related content. The subscription system is used to refine the individual marketing choices this contact makes.| | |contactSupportPerson/withdrawnEmarketingConsent|bool|User support contact - Consent is withdrawn - E-marketing: The purpose is to gain the explicit consent to communicate electronically (bulk e-mail) on topics related to our products and services. This might include newsletters, invitations and product-related content. The subscription system is used to refine the individual marketing choices this contact makes.| | |contactSupportPerson/subscription|listAny|User support contact - Subscription: Subscription for marketing| x | |contactSupportPerson/legalBaseStore|listAny|User support contact - Legal basis - Sales and service: The purpose to store data about this contact is to sell to and/or provide services to this contact. This purpose is usually used when storing contacts who are defined as potential or existing customers.| x | |contactSupportPerson/legalBaseEmarketing|listAny|User support contact - Legal basis - E-marketing: The purpose is to gain the explicit consent to communicate electronically (bulk e-mail) on topics related to our products and services. This might include newsletters, invitations and product-related content. The subscription system is used to refine the individual marketing choices this contact makes.| x | |contactSupportPerson/consentSourceStore|listAny|User support contact - Source - Sales and service: The purpose to store data about this contact is to sell to and/or provide services to this contact. This purpose is usually used when storing contacts who are defined as potential or existing customers.| x | |contactSupportPerson/consentSourceEmarketing|listAny|User support contact - Source - E-marketing: The purpose is to gain the explicit consent to communicate electronically (bulk e-mail) on topics related to our products and services. This might include newsletters, invitations and product-related content. The subscription system is used to refine the individual marketing choices this contact makes.| x | |contactInterestIds|listInterest|Company Interest: This criterion corresponds to the Interests tab on the Company card.| | |contactUdef/SuperOffice:1|string|companyshorttext: tooltipshorttext| x | |contactUdef/SuperOffice:2|string|companylongtext: tooltiplongtext| x | |contactUdef/SuperOffice:3|int|companynumber| x | |contactUdef/SuperOffice:4|date|companydate| x | |contactUdef/SuperOffice:5|unlimitedDate|companyunlimiteddate: tooltipunlimiteddate| x | |contactUdef/SuperOffice:6|bool|companycheckbox| x | |contactUdef/SuperOffice:7|listAny|companydropdownlistbox| x | |contactUdef/SuperOffice:8|decimal|companydecimal| x | |contactUdef/SuperOffice:9|string|page1saleonly| x | |contactUdef/SuperOffice:10|string|page1marketingonly| x | |contactUdef/SuperOffice:11|string|page1adminonly| x | |contactUdef/SuperOffice:12|listAny|Udlist one: Static tooltip for udlist one| x | |contactUdef/SuperOffice:13|listAny|Udlist two: Static tooltip for udlist two| x | |NumberOfActivities|int|Number of activities| | |NumberOfActivitiesInPeriod|int|Number of activities in last 90 days| | |NumberOfNotCompletedActivities|int|Number of non-completed activities| | |NumberOfNotCompletedActivitiesInPeriod|int|Number of non-completed activities in last 90 days| | |LastActivity|date|Date of last activity| | |LastCompletedActivity|date|Date of last completed activity| | |LastDoByActivity|date|Date of last non-completed activity| | |NumberOfSales|int|Number of sales| | |NumberOfSalesInPeriod|int|Number of sales in last 90 days| | |NumberOfNotCompletedSales|int|Number of non-completed sales| | |NumberOfNotCompletedSalesInPeriod|int|Number of non-completed sales in last 90 days| | |LastSale|date|Date of last sale| | |LastCompletedSale|date|Date of last completed sale| | |LastDoBySale|date|Date of last non-completed sale| | |NumberOfTickets|int|Number of requests| | |NumberOfTicketsInPeriod|int|Number of requests in last 90 days| | |NumberOfNotCompletedTickets|int|Number of non-completed requests| | |NumberOfNotCompletedTicketsInPeriod|int|Number of non-completed requests in last 90 days| | |LastTicket|date|Date of last request| | |LastCompletedTicket|date|Date of last completed request| | |LastDoByTicket|date|Date of last non-completed request| | |SaintStatus1|saintStatus|Neglected customer| | |SaintStatus2|saintStatus|C-company| | |saintSaleStatus|listAny|With status| | |saintAmountClass|listAny|Amount class| | |saintActivityType|listAny|SAINT type| | |saintDirection|listAny|Direction| | |saintIntention|listAny|Intention| | |saintTicketStatus|listAny|Status| | |saintTicketCategory|listAny|Category| | |selectionMemberId| *None* |Selection member ID: The database ID of the selection member record| | |selectionIdRequest|int|Selection ID: Database ID of selection which members are to be fetched from| | ## Sample ```http! GET /api/v1/archive/emailcontactaddress?$select=hasInterests,contactAssociate/credentialType,contactAssociate/isActiveText Authorization: Basic dGplMDpUamUw Accept: application/json; charset=utf-8 Accept-Language: sv ``` See also: <see cref="T:SuperOffice.CRM.Services.IArchiveAgent">IArchiveAgent</see>.</p> ======================= File: docs/netserver/mdo-providers/reference/webpanelgroup.md ======================= --- uid: webpanelgroup title: webpanelgroup keywords: - "mdo" - "provider" - "mdo provider" - "webpanelgroup" so.generated: true so.date: 03.19.2021 so.topic: reference so.envir: - "onsite" - "online" --- # "webpanelgroup" MDO List List of WebPanels with visible for groups as commaseperated ids in extrainfo field. This list only makes sence if the setting use groups and heading are turned on for Implemented by the <see cref="T:SuperOffice.CRM.Lists.WebPanelGroupProvider">WebPanelGroupProvider</see> class. The name of the MDO list is 'webpanelgroup'. ## Sample Request ```http! GET /api/v1/MDOList/webpanelgroup Authorization: Basic dGplMDpUamUw Accept: application/json; charset=utf-8 Accept-Language: * ``` ## Sample Code ```cs var listProvider = SuperOffice.CRM.Lists.SoListProviderFactory.Create("webpanelgroup", forceFlatList: true); foreach (var item in listProvider.RootItems) { Console.WriteLine("{0} {1} {2} {3}", item.Id, ResourceManager.ParseInlineResources(item.Name), item.StyleHint, item.ExtraInfo); } ``` ## Sample Output |Id | Name |StyleHint|ExtraInfo | | --- | ----- | ------- | -------- | |2|Echo||1,2,3,4,5| ## Related MDO Lists * "webpanelgroupheadings" * "webpanelgroupheadingswithallitem" * "webpanelgroupheadingswithallitemwithnoselection" * "webpanelgroupheadingswithnoselection" * "webpanelgroupwithallitem" * "webpanelgroupwithallitemwithnoselection" * "webpanelgroupwithnoselection" ======================= File: docs/api-reference/restful/agent/EMail_Agent/v1EMailAgent_GetUnsanitizedEMailFromAttachmentId.md ======================= <filename>docs/api-reference/restful/agent/EMail_Agent/v1EMailAgent_GetUnsanitizedEMailFromAttachmentId.md --- title: POST Agents/EMail/GetUnsanitizedEMailFromAttachmentId id: v1EMailAgent_GetUnsanitizedEMailFromAttachmentId --- # POST Agents/EMail/GetUnsanitizedEMailFromAttachmentId ```http POST /api/v1/Agents/EMail/GetUnsanitizedEMailFromAttachmentId ``` Get an e-mail based on an email and attachment id. The returned value is not sanitized. ## Online Restricted: ## The EMail agent is not available in Online by default. Access must be requested specifically when app is registered. ## Query String Parameters | Parameter Name | Type | Description | |----------------|------|--------------| | $select | string | Optional comma separated list of properties to include in the result. Other fields are then nulled out to reduce payload size: "Name,department,category". Default = show all fields. | ```http POST /api/v1/Agents/EMail/GetUnsanitizedEMailFromAttachmentId?$select=name,department,category/id ``` ## Request Headers | Parameter Name | Description | |----------------|-------------| | Authorization | Supports 'Basic', 'SoTicket' and 'Bearer' schemes, depending on installation type. | | X-XSRF-TOKEN | If not using Authorization header, you must provide XSRF value from cookie or hidden input field | | Content-Type | Content-type of the request body: `application/json`, `text/json`, `application/xml`, `text/xml`, `application/x-www-form-urlencoded`, `application/json-patch+json`, `application/merge-patch+json` | | Accept | Content-type(s) you would like the response in: `application/json`, `text/json`, `application/xml`, `text/xml`, `application/json-patch+json`, `application/merge-patch+json` | | Accept-Language | Convert string references and multi-language values into a specified language (iso2) code. | | SO-Language | Convert string references and multi-language values into a specified language (iso2) code. Overrides Accept-Language value. | | SO-Culture | Number, date formatting in a specified culture (iso2 language) code. Partially overrides SO-Language/Accept-Language value. Ignored if no Language set. | | SO-TimeZone | Specify the timezone code that you would like date/time responses converted to. | | SO-AppToken | The application token that identifies the partner app. Used when calling Online WebAPI from a server. | ## Request Body: request EmailId, AttachmentIds, IncludeAttachments | Property Name | Type | Description | |----------------|------|--------------| | EmailId | int32 | | | AttachmentIds | array | | | IncludeAttachments | bool | | ## Response: object All information about an e-mail Carrier object for EMailEntity. Services for the EMailEntity Carrier is available from the <see cref="T:SuperOffice.CRM.Services.IEMailAgent">EMail Agent</see>. | Response | Description | |----------------|-------------| | 200 | OK | Response body: object | Property Name | Type | Description | |----------------|------|--------------| | To | array | To recipients of e-mail | | Cc | array | Cc recipients of e-mail | | Bcc | array | Bcc recipient of e-mail | | Subject | string | Subject of the e-mail | | HTMLBody | string | Body formatted in HTML | | From | | Who did the e-mail originate from | | Sent | date-time | When was the e-mail sent | | Size | int32 | Total size of the e-mail | | Priority | string | Importance of the e-mail | | Flags | string | Flag status of this mail (unread, replied, deleted ) | | MessageID | string | Unique id of e-mails | | PlainBody | string | Body formatted in plain text | | IsSent | bool | Is this a sent e-mail (not new) | | EMailSOInfo | | Glue between SuperOffice data and an e-mail. | | ServerId | int32 | Unique id for the e-mail on the server | | Attachments | array | | | CustomHeaderList | array | Non standard e-mail headers | | FolderName | string | Name of folder the e-mail belongs in | | EmailItemId | int32 | Primary key | | AccountId | int32 | Account Id | | ReceivedAt | date-time | Received date time | | InReplyTo | | The envelope of the email this email is a reply to, if it exists | | RepliedAt | date-time | When this email was replied at | | HasCalendarData | bool | If this email contains exactly one iCal appointment | | CalMethod | string | Method stored in the associated iCal appointment. Indicates if the iCal data is a reply, counter proposal etc. | | CalReplyStatus | string | Reply status stored in calendar data for the ical method is REPLY | | TableRight | | | | FieldProperties | object | | ## Sample Request ```http! POST /api/v1/Agents/EMail/GetUnsanitizedEMailFromAttachmentId Authorization: Basic dGplMDpUamUw Accept: application/json; charset=utf-8 Accept-Language: fr,de,ru,zh Content-Type: application/json; charset=utf-8 { "EmailId": 272, "AttachmentIds": [ "assumenda", "suscipit" ], "IncludeAttachments": false } ``` ```http_ HTTP/1.1 200 OK Content-Type: application/json; charset=utf-8 { "To": [ { "ContactId": 27, "ContactName": "Leuschke, <NAME>", "PersonId": 807, "PersonName": "<NAME>", "AssociateId": 312, "Address": "sed", "EmailId": 232, "DuplicatePersonIds": [ 882, 335 ], "Name": "Bartoletti Inc and Sons", "TableRight": {}, "FieldProperties": { "fieldName": { "FieldRight": { "Mask": "FULL", "Reason": "" }, "FieldType": "System.String", "FieldLength": 434 } } } ], "Cc": [ { "ContactId": 683, "ContactName": "O'Keefe-Wyman", "PersonId": 163, "PersonName": "Mertz Inc and Sons", "AssociateId": 980, "Address": "maiores", "EmailId": 716, "DuplicatePersonIds": [ 63, 828 ], "Name": "Schuppe Inc and Sons", "TableRight": {}, "FieldProperties": { "fieldName": { "FieldRight": { "Mask": "FULL", "Reason": "" }, "FieldType": "System.String", "FieldLength": 244 } } } ], "Bcc": [ { "ContactId": 431, "ContactName": "Wehner-Langworth", "PersonId": 292, "PersonName": "<NAME> and Johnston", "AssociateId": 798, "Address": "veritatis", "EmailId": 595, "DuplicatePersonIds": [ 24, 206 ], "Name": "Jacobson LLC", "TableRight": {}, "FieldProperties": { "fieldName": { "FieldRight": { "Mask": "FULL", "Reason": "" }, "FieldType": "System.String", "FieldLength": 334 } } } ], "Subject": "omnis", "HTMLBody": "illum", "From": { "ContactId": 508, "ContactName": "<NAME>", "PersonId": 646, "PersonName": "Dicki Inc and Sons", "AssociateId": 830, "Address": "totam", "EmailId": 873, "DuplicatePersonIds": [ 187, 31 ], "Name": "Lubowitz-Kohler", "TableRight": {}, "FieldProperties": { "fieldName": { "FieldRight": { "Mask": "FULL", "Reason": "" }, "FieldType": "System.Int32", "FieldLength": 805 } } }, "Sent": "2020-01-09T18:28:49.0329563+01:00", "Size": 687, "Priority": "High", "Flags": "Answered", "MessageID": "vitae", "PlainBody": "aspernatur", "IsSent": false, "EMailSOInfo": { "DocumentId": 388, "AppointmentId": 1000, "ProjectId": 473, "SaleId": 397, "Archived": false, "ArchivedAt": "2017-05-11T18:28:49.0329563+02:00", "ArchivedBy": 536, "ArchivedDisplayName": "Towne-Skiles", "TableRight": {}, "FieldProperties": { "fieldName": { "FieldRight": { "Mask": "FULL", "Reason": "" }, "FieldType": "System.Int32", "FieldLength": 419 } } }, "ServerId": 935, "Attachments": [ { "Description": "Robust tangible methodology", "Filename": "omnis", "Size": 224, "Type": "et", "Encoding": "nihil", "Id": "non", "Disposition": "perspiciatis", "Stream": "GIF89....File contents as raw bytes...", "TableRight": {}, "FieldProperties": { "fieldName": { "FieldRight": { "Mask": "FULL", "Reason": "repurpose strategic synergies" }, "FieldType": "System.Int32", "FieldLength": 473 } } } ], "CustomHeaderList": [ { "Name": "Schamberger-Hegmann", "Values": [ "sit", "natus" ], "TableRight": {}, "FieldProperties": { "fieldName": { "FieldRight": { "Mask": "FULL", "Reason": "" }, "FieldType": "System.Int32", "FieldLength": 694 } } }, { "Name": "Schamberger-Hegmann", "Values": [ "sit", "natus" ], "TableRight": {}, "FieldProperties": { "fieldName": { "FieldRight": { "Mask": "FULL", "Reason": "" }, "FieldType": "System.Int32", "FieldLength": 694 } } } ], "FolderName": "VonRueden Group", "EmailItemId": 710, "AccountId": 477, "ReceivedAt": "2011-11-23T18:28:49.0339616+01:00", "InReplyTo": { "ServerId": 320, "MessageId": "quis", "Subject": "quia", "From": {}, "To": [ {}, {} ], "Sent": "2002-12-08T18:28:49.0339616+01:00", "Priority": "High", "Flags": "Answered", "Size": 501, "EMailSOInfo": {}, "TableRight": {}, "FieldProperties": { "fieldName": { "FieldRight": { "Mask": "FULL", "Reason": "" }, "FieldType": "System.String", "FieldLength": 703 } } }, "RepliedAt": "2005-01-24T18:28:49.0339616+01:00", "HasCalendarData": true, "CalMethod": "Add", "CalReplyStatus": "Accepted", "TableRight": { "Mask": "Delete", "Reason": "incentivize open-source deliverables" }, "FieldProperties": { "fieldName": { "FieldRight": { "Mask": "FULL", "Reason": "" }, "FieldType": "System.Int32", "FieldLength": 285 } } } ``` ======================= File: docs/tutorials/minimal-csharp-app/includes/customer-info.md ======================= ```csharp namespace SuperOffice.DevNet.Online.SystemUser.PartnerDBLibrary.Models { public class CustomerInfo { public int ID { get; set; } public int AssociateID { get; set; } public bool IsActive { get; set; } public string SystemUserToken { get; set; } public string ContextIdentifier { get; set; } public DateTime LastSync { get; set; } } } ``` ======================= File: docs/api-reference/restful/agent/Webhook_Agent/v1WebhookAgent_GetAllWebhooks.md ======================= <filename>docs/api-reference/restful/agent/Webhook_Agent/v1WebhookAgent_GetAllWebhooks.md --- title: POST Agents/Webhook/GetAllWebhooks id: v1WebhookAgent_GetAllWebhooks --- # POST Agents/Webhook/GetAllWebhooks ```http POST /api/v1/Agents/Webhook/GetAllWebhooks ``` Returns all webhooks, according to filter criteria ## Online Restricted: ## The Webhook agent is not available in Online by default. Access must be requested specifically when app is registered. ## Query String Parameters | Parameter Name | Type | Description | |----------------|------|--------------| | $select | string | Optional comma separated list of properties to include in the result. Other fields are then nulled out to reduce payload size: "Name,department,category". Default = show all fields. | ```http POST /api/v1/Agents/Webhook/GetAllWebhooks?$select=name,department,category/id ``` ## Request Headers | Parameter Name | Description | |----------------|-------------| | Authorization | Supports 'Basic', 'SoTicket' and 'Bearer' schemes, depending on installation type. | | X-XSRF-TOKEN | If not using Authorization header, you must provide XSRF value from cookie or hidden input field | | Content-Type | Content-type of the request body: `application/json`, `text/json`, `application/xml`, `text/xml`, `application/x-www-form-urlencoded`, `application/json-patch+json`, `application/merge-patch+json` | | Accept | Content-type(s) you would like the response in: `application/json`, `text/json`, `application/xml`, `text/xml`, `application/json-patch+json`, `application/merge-patch+json` | | Accept-Language | Convert string references and multi-language values into a specified language (iso2) code. | | SO-Language | Convert string references and multi-language values into a specified language (iso2) code. Overrides Accept-Language value. | | SO-Culture | Number, date formatting in a specified culture (iso2 language) code. Partially overrides SO-Language/Accept-Language value. Ignored if no Language set. | | SO-TimeZone | Specify the timezone code that you would like date/time responses converted to. | | SO-AppToken | The application token that identifies the partner app. Used when calling Online WebAPI from a server. | ## Request Body: request NameFilter, EventFilter, StatusFilter | Property Name | Type | Description | |----------------|------|--------------| | NameFilter | string | | | EventFilter | string | | | StatusFilter | string | | ## Response: array | Response | Description | |----------------|-------------| | 200 | OK | Response body: array | Property Name | Type | Description | |----------------|------|--------------| | WebhookId | int32 | Primary Key. Unique id for this webhook. | | Name | string | Name to identify this webhook. Does not have to be unique. | | Events | array | Array of event names that trigger this webhook: ['contact.created','sale.changed'] | | TargetUrl | string | Destination to POST event info to. URL for webhooks. Id for CRM scripts | | Secret | string | Shared secret key used for generating SHA256 HMAC signature, so that receiver can verify that call came from this server | | State | string | Webhook status - should we post events to the URL? 1=Active, 2=Stopped or 3=TooManyErrors | | Type | string | Name of plugin that handles this webhook. 'webhook' for webhooks, which are handled by the system plugin. | | Headers | object | Custom HTTP Headers to add to webhook requests. | | Properties | object | Custom values to inject into JSON body of webhook call. | | Registered | date-time | Registered when in UTC. | | RegisteredAssociate | | The user that created the webhook. | | Updated | date-time | Last updated when in UTC. | | UpdatedAssociate | | The user that last updated the webhook. | ## Sample Request ```http! POST /api/v1/Agents/Webhook/GetAllWebhooks Authorization: Basic dGplMDpUamUw Accept: application/json; charset=utf-8 Accept-Language: * Content-Type: application/json; charset=utf-8 { "NameFilter": "Mayert Inc and Sons", "EventFilter": "excepturi", "StatusFilter": "Active" } ``` ```http_ HTTP/1.1 200 OK Content-Type: application/json; charset=utf-8 [ { "WebhookId": 233, "Name": "<NAME>", "Events": [ "aut", "tempore" ], "TargetUrl": "http://www.example.com/", "Secret": "ipsa", "State": "Active", "Type": "minus", "Headers": { "Headers1": "alias", "Headers2": "quas" }, "Properties": { "fieldName": {} }, "Registered": "2009-10-17T18:28:50.6134149+02:00", "RegisteredAssociate": { "AssociateId": 216, "Name": "<NAME>", "PersonId": 773, "Rank": 8, "Tooltip": "a", "Type": "AnonymousAssociate", "GroupIdx": 174, "FullName": "<NAME>", "FormalName": "<NAME>", "Deleted": true, "EjUserId": 487, "UserName": "<NAME> and Kiehn", "TableRight": {}, "FieldProperties": { "fieldName": { "FieldRight": { "Mask": "FULL", "Reason": "incentivize vertical schemas" }, "FieldType": "System.Int32", "FieldLength": 322 } } }, "Updated": "2020-07-30T18:28:50.6134149+02:00", "UpdatedAssociate": { "AssociateId": 919, "Name": "<NAME>", "PersonId": 253, "Rank": 841, "Tooltip": "adipisci", "Type": "AnonymousAssociate", "GroupIdx": 158, "FullName": "<NAME>", "FormalName": "Beer-Aufderhar", "Deleted": false, "EjUserId": 53, "UserName": "Kulas Group", "TableRight": {}, "FieldProperties": { "fieldName": { "FieldRight": { "Mask": "FULL", "Reason": "" }, "FieldType": "System.String", "FieldLength": 169 } } } } ] ``` ======================= File: docs/api-reference/restful/agent/Person_Agent/v1PersonAgent_CreateDefaultPersonEntity.md ======================= --- title: POST Agents/Person/CreateDefaultPersonEntity id: v1PersonAgent_CreateDefaultPersonEntity --- # POST Agents/Person/CreateDefaultPersonEntity ```http POST /api/v1/Agents/Person/CreateDefaultPersonEntity ``` Set default values into a new PersonEntity. NetServer calculates default values on the entity, which is required when creating/storing a new instance ## Request Headers | Parameter Name | Description | |----------------|-------------| | Authorization | Supports 'Basic', 'SoTicket' and 'Bearer' schemes, depending on installation type. | | X-XSRF-TOKEN | If not using Authorization header, you must provide XSRF value from cookie or hidden input field | | Accept | Content-type(s) you would like the response in: `application/json`, `text/json`, `application/xml`, `text/xml`, `application/json-patch+json`, `application/merge-patch+json` | | Accept-Language | Convert string references and multi-language values into a specified language (iso2) code. | | SO-Language | Convert string references and multi-language values into a specified language (iso2) code. Overrides Accept-Language value. | | SO-Culture | Number, date formatting in a specified culture (iso2 language) code. Partially overrides SO-Language/Accept-Language value. Ignored if no Language set. | | SO-TimeZone | Specify the timezone code that you would like date/time responses converted to. | | SO-AppToken | The application token that identifies the partner app. Used when calling Online WebAPI from a server. | ## Response: object | Response | Description | |----------------|-------------| | 200 | OK | Response body: object | Property Name | Type | Description | |----------------|------|--------------| | PersonId | int32 | Primary key | | Firstname | string | First name | | MiddleName | string | Middle name or 'van' etc. | | Lastname | string | Last name | | Mrmrs | string | e.g. Mrs sex_title <para>Use MDO List name "mrmrs" to get list items.</para> | | Title | string | Title | | UpdatedDate | date-time | Last updated date in UTC. | | CreatedDate | date-time | Registered date in UTC. | | BirthDate | date-time | The Person birth date as Date | | CreatedBy | | The user that created the person object | | Emails | array | A collection of the person's emails | | Description | string | The actual text, max 2047 significant characters even though it is stored as a larger data type on some databases | | IsAssociate | bool | Checks if the person object is an associate. The property is read-only. | | PrivatePhones | array | Returns a collection of phone numbers that belong to the contact person. | | Faxes | array | Returns a collection of fax numbers that belong to the contact person. | | MobilePhones | array | Returns a collection of mobile phone numbers that belong to the contact person. | | OfficePhones | array | Returns a collection of office phone numbers that belong to the contact person. | | OtherPhones | array | Returns a collection of pagers that belong to the contact person. | | Position | | The position. This is a predefined SuperOffice value, different from Title <para>Use MDO List name "perspos" to get list items.</para> | | UpdatedBy | | The person that last updated the person object | | Contact | | The contact the contact person is registered on. This is required unless the 'MandatoryContactOnPerson' preference is set. <para>Use MDO List name "contact_new" to get list items.</para> | | Country | | The country this contact person is located in. <para>Use MDO List name "country" to get list items.</para> | | Interests | array | The person's available and selected interests. <para>Use MDO List name "persint" to get list items.</para> | | PersonNumber | string | Alphanumeric user field | | FullName | string | The person's full name localized to the current culture/country. (internal name used in clients for employees) | | NoMailing | bool | Spam filter. Indicates if this person should retrieve advertising. | | UsePersonAddress | bool | True if the person's address should be used as mailing address, instead of the contact's address. | | Retired | bool | True if the user is retired and should have no rights, not appear in lists, etc. | | Urls | array | The urls related to this person. | | FormalName | string | Get formal name for a person, as used in labels. (Full name + person title + academic title) | | Address | | Structure holding formatted address data. The layout of the array structure indicates the layout of the localized address. | | Post3 | string | Postal address, used in Japanese versions only | | Post2 | string | Postal address, used in Japanese versions only | | Post1 | string | Postal address, used in Japanese versions only | | Kanalname | string | Kana last name, used in Japanese versions only | | Kanafname | string | Kana first name, used in Japanese versions only | | CorrespondingAssociate | | The associate corresponding to this person. Will be empty if the person is not a user (internal associate user, external user). | | Category | | Person's category. Usually null. Refer to the Contact.Category instead. Intended for use when individual persons are created. (i.e. when Person.Contact is blank) <para>Use MDO List name "category" to get list items.</para> | | Business | | Person's business - usually blank. Use Contact.Business instead. Intended for use when individual persons are created. (i.e. when Person.Contact is blank) <para>Use MDO List name "business" to get list items.</para> | | Associate | | The associate owning this person (similar to contact.Associate) - usually blank. Use the Person.Contact.Associate instead. Intended for use when individual persons are created (i.e. when Person.Contact is blank) <para>Use MDO List name "associate" to get list items.</para> | | Salutation | string | Academic title, populated from Salutation list but can be overwritten with anything at all <para>Use MDO List name "salutation" to get list items.</para> | | ActiveInterests | int32 | The number of active interests. | | SupportAssociate | | <para>Use MDO List name "associate" to get list items.</para> | | TicketPriority | | <para>Use MDO List name "ticketpriority" to get list items.</para> | | CustomerLanguage | | <para>Use MDO List name "customerlanguage" to get list items.</para> | | DbiAgentId | int32 | Integration agent (eJournal) | | DbiKey | string | The primary key for the integrated entry in the external datasource. | | DbiLastModified | date-time | When the entry was last modified. | | DbiLastSyncronized | date-time | Last external syncronization. | | SentInfo | int32 | Has information on username/password been sent (ejournal) | | ShowContactTickets | int32 | Should tickets related to the company be shown to this person | | UserInfo | | Information about the user if this person is a user. If IsAssociate (e.g. is user is true) the UserInfo will be provided. | | ChatEmails | array | | | InternetPhones | array | | | Source | int32 | How did we get this person? For future integration needs | | ActiveErpLinks | int32 | How many active ERP links are there for this person? | | ShipmentTypes | array | The person's available and selected shipment types. | | Consents | array | The person's available consent information. Missing consents are not deleted. To remove a consent, mark its legalbase as 'WITHDRAWN' | | BounceEmails | array | Email addresses with a positive bounce counter. | | ActiveStatusMonitorId | int32 | Active status monitor identity with the lowest rank for person | | UserDefinedFields | object | Deprecated: Use {SuperOffice.CRM.Services.PersonEntity.CustomFields} instead. Dictionary of user defined field data. The key string is the ProgId of the UdefField, or if the ProgId is empty it is a string of the format "SuperOffice:[UdefFieldIdentity]", e.g. "SuperOffice:1234" | | ExtraFields | object | Deprecated: Use {SuperOffice.CRM.Services.PersonEntity.CustomFields} instead. Extra fields added to the carrier. This could be data from Plug-ins, the foreign key system, external applications, etc. | | CustomFields | object | Udef + Extra fields added to the carrier. Extra fields as defined by changes to database schema + user-defined fields as defined by admin. Custom fields combines user defined fields and extra fields into one bucket. The individual {SuperOffice.CRM.Services.PersonEntity.ExtraFields} and <see cref="P:SuperOffice.CRM.Services.PersonEntity.UserDefinedFields">UserDefinedFields</see> properties are deprecated in favor of this combined collection. | | TableRight | | | | FieldProperties | object | | ## Sample Request ```http! POST /api/v1/Agents/Person/CreateDefaultPersonEntity Authorization: Basic dGplMDpUamUw Accept: application/json; charset=utf-8 Accept-Language: en ``` ```http_ HTTP/1.1 200 OK Content-Type: application/json; charset=utf-8 { "PersonId": 330, "Firstname": "Haylie", "MiddleName": "<NAME> and Sons", "Lastname": "Lang", "Mrmrs": "consequatur", "Title": "sed", "UpdatedDate": "1994-08-27T18:28:49.5410876+02:00", "CreatedDate": "2006-11-10T18:28:49.5410876+01:00", "BirthDate": "2001-03-01T18:28:49.5410876+01:00", "CreatedBy": { "AssociateId": 671, "Name": "<NAME> Pfeffer", "PersonId": 336, "Rank": 972, "Tooltip": "minima", "Type": "AnonymousAssociate", "GroupIdx": 760, "FullName": "<NAME>", "FormalName": "Keebler-Balistreri", "Deleted": true, "EjUserId": 660, "UserName": "Parisian-Parker", "TableRight": {}, "FieldProperties": { "fieldName": { "FieldRight": { "Mask": "FULL", "Reason": "" }, "FieldType": "System.Int32", "FieldLength": 529 } } }, "Emails": [ { "Value": "recusandae", "StrippedValue": "laborum", "Description": "Focused executive standardization", "TableRight": {}, "FieldProperties": { "fieldName": { "FieldRight": { "Mask": "FULL", "Reason": "" }, "FieldType": "System.String", "FieldLength": 434 } } }, { "Value": "recusandae", "StrippedValue": "laborum", "Description": "Focused executive standardization", "TableRight": {}, "FieldProperties": { "fieldName": { "FieldRight": { "Mask": "FULL", "Reason": "" }, "FieldType": "System.String", "FieldLength": 434 } } } ], "Description": "Open-architected exuding policy", "IsAssociate": true, "PrivatePhones": [ { "Value": "natus", "StrippedValue": "sapiente", "Description": "Re-engineered discrete help-desk", "TableRight": {}, "FieldProperties": { "fieldName": { "FieldRight": { "Mask": "FULL", "Reason": "" }, "FieldType": "System.String", "FieldLength": 500 } } }, { "Value": "natus", "StrippedValue": "sapiente", "Description": "Re-engineered discrete help-desk", "TableRight": {}, "FieldProperties": { "fieldName": { "FieldRight": { "Mask": "FULL", "Reason": "" }, "FieldType": "System.String", "FieldLength": 500 } } } ], "Faxes": [ { "Value": "velit", "StrippedValue": "eaque", "Description": "Organic human-resource initiative", "TableRight": {}, "FieldProperties": { "fieldName": { "FieldRight": { "Mask": "FULL", "Reason": "" }, "FieldType": "System.String", "FieldLength": 132 } } }, { "Value": "velit", "StrippedValue": "eaque", "Description": "Organic human-resource initiative", "TableRight": {}, "FieldProperties": { "fieldName": { "FieldRight": { "Mask": "FULL", "Reason": "" }, "FieldType": "System.String", "FieldLength": 132 } } } ], "MobilePhones": [ { "Value": "totam", "StrippedValue": "est", "Description": "Diverse grid-enabled open architecture", "TableRight": {}, "FieldProperties": { "fieldName": { "FieldRight": { "Mask": "FULL", "Reason": "" }, "FieldType": "System.Int32", "FieldLength": 923 } } }, { "Value": "totam", "StrippedValue": "est", "Description": "Diverse grid-enabled open architecture", "TableRight": {}, "FieldProperties": { "fieldName": { "FieldRight": { "Mask": "FULL", "Reason": "" }, "FieldType": "System.Int32", "FieldLength": 923 } } } ], "OfficePhones": [ { "Value": "harum", "StrippedValue": "omnis", "Description": "Synchronised heuristic core", "TableRight": {}, "FieldProperties": { "fieldName": { "FieldRight": { "Mask": "FULL", "Reason": "" }, "FieldType": "System.String", "FieldLength": 106 } } }, { "Value": "harum", "StrippedValue": "omnis", "Description": "Synchronised heuristic core", "TableRight": {}, "FieldProperties": { "fieldName": { "FieldRight": { "Mask": "FULL", "Reason": "" }, "FieldType": "System.String", "FieldLength": 106 } } } ], "OtherPhones": [ { "Value": "rem", "StrippedValue": "doloremque", "Description": "Assimilated even-keeled throughput", "TableRight": {}, "FieldProperties": { "fieldName": { "FieldRight": { "Mask": "FULL", "Reason": "" }, "FieldType": "System.String", "FieldLength": 752 } } }, { "Value": "rem", "StrippedValue": "doloremque", "Description": "Assimilated even-keeled throughput", "TableRight": {}, "FieldProperties": { "fieldName": { "FieldRight": { "Mask": "FULL", "Reason": "" }, "FieldType": "System.String", "FieldLength": 752 } } } ], "Position": { "Id": 919, "Value": "aut", "Tooltip": "ab", "TableRight": {}, "FieldProperties": { "fieldName": { "FieldRight": { "Mask": "FULL", "Reason": "" }, "FieldType": "System.String", "FieldLength": 356 } } }, "UpdatedBy": { "AssociateId": 995, "Name": "Wisozk-Kessler", "PersonId": 357, "Rank": 916, "Tooltip": "harum", "Type": "AnonymousAssociate", "GroupIdx": 570, "FullName": "Dr. <NAME>", "FormalName": "<NAME>", "Deleted": true, "EjUserId": 340, "UserName": "Kuphal LLC", "TableRight": {}, "FieldProperties": { "fieldName": { "FieldRight": { "Mask": "FULL", "Reason": "" }, "FieldType": "System.String", "FieldLength": 814 } } }, "Contact": { "ContactId": 970, "Name": "<NAME>", "OrgNr": "649087", "Department": "synergize dot-com synergies", "URL": "http://www.example.com/", "City": "consequuntur", "DirectPhone": "280.775.1167 x851", "AssociateId": 304, "CountryId": 494, "EmailAddress": "<EMAIL>", "Kananame": "ea", "EmailAddressName": "<EMAIL>", "URLName": "http://www.example.com/", "AssociateFullName": "<NAME>", "BusinessName": "Information Technology", "CategoryName": "VIP Customer", "CountryName": "Sokovia", "Address": {}, "FormattedAddress": "consequatur", "FullName": "<NAME> Jr.", "IsOwnerContact": false, "ActiveErpLinks": 253, "TableRight": {}, "FieldProperties": { "fieldName": { "FieldRight": { "Mask": "FULL", "Reason": "" }, "FieldType": "System.Int32", "FieldLength": 620 } } }, "Country": { "CountryId": 560, "Name": "Sawayn-Bartoletti", "CurrencyId": 25, "EnglishName": "<NAME> and Mertz", "TwoLetterISOCountry": "Sokovia", "ThreeLetterISOCountry": "Sokovia", "ImageDescription": "Multi-tiered bottom-line open architecture", "OrgNrText": "1009742", "InterAreaPrefix": "sunt", "DialInPrefix": "ipsam", "ZipPrefix": "similique", "DomainName": "Hammes, Simonis and Stehr", "AddressLayoutId": 509, "DomesticAddressLayoutId": 463, "ForeignAddressLayoutId": 984, "Rank": 825, "Tooltip": "nesciunt", "Deleted": true, "TableRight": {}, "FieldProperties": { "fieldName": { "FieldRight": { "Mask": "FULL", "Reason": "" }, "FieldType": "System.Int32", "FieldLength": 708 } } }, "Interests": [ { "Id": 371, "Name": "Koss-Funk", "ToolTip": "Exercitationem non.", "Deleted": false, "Rank": 665, "Type": "dignissimos", "ColorBlock": 500, "IconHint": "labore", "Selected": true, "LastChanged": "1998-08-03T18:28:49.5440875+02:00", "ChildItems": [ {}, {} ], "ExtraInfo": "dolorum", "StyleHint": "distinctio", "Hidden": true, "FullName": "<NAME>", "TableRight": {}, "FieldProperties": { "fieldName": { "FieldRight": { "Mask": "FULL", "Reason": "" }, "FieldType": "System.String", "FieldLength": 273 } } } ], "PersonNumber": "698886", "FullName": "<NAME>", "NoMailing": true, "UsePersonAddress": true, "Retired": true, "Urls": [ { "Value": "veritatis", "StrippedValue": "enim", "Description": "Reduced fault-tolerant challenge", "TableRight": {}, "FieldProperties": { "fieldName": { "FieldRight": { "Mask": "FULL", "Reason": "" }, "FieldType": "System.String", "FieldLength": 17 } } }, { "Value": "veritatis", "StrippedValue": "enim", "Description": "Reduced fault-tolerant challenge", "TableRight": {}, "FieldProperties": { "fieldName": { "FieldRight": { "Mask": "FULL", "Reason": "" }, "FieldType": "System.String", "FieldLength": 17 } } } ], "FormalName": "Bartell-Hackett", "Address": { "Wgs84Latitude": 12601.814, "Wgs84Longitude": 1319.414, "LocalizedAddress": [ [ { "Name": "<NAME>", "Value": "occaecati", "Tooltip": "eligendi", "Label": "cum", "ValueLength": 941, "AddressType": "in", "TableRight": { "Mask": "Delete", "Reason": "" }, "FieldProperties": { "fieldName": { "FieldRight": { "Mask": "FULL", "Reason": "" }, "FieldType": "System.String", "FieldLength": 901 } } } ], [ { "Name": "Rowe, Feest and Gusikowski", "Value": "nulla", "Tooltip": "nostrum", "Label": "animi", "ValueLength": 754, "AddressType": "labore", "TableRight": { "Mask": "Delete", "Reason": "" }, "FieldProperties": { "fieldName": { "FieldRight": { "Mask": "FULL", "Reason": "" }, "FieldType": "System.String", "FieldLength": 693 } } } ] ], "Street": {}, "Postal": {}, "Formatted": "animi", "TableRight": {}, "FieldProperties": { "fieldName": { "FieldRight": { "Mask": "FULL", "Reason": "" }, "FieldType": "System.Int32", "FieldLength": 595 } } }, "Post3": "eveniet", "Post2": "et", "Post1": "adipisci", "Kanalname": "temporibus", "Kanafname": "eum", "CorrespondingAssociate": { "AssociateId": 643, "Name": "<NAME>", "PersonId": 148, "Rank": 232, "Tooltip": "sunt", "Type": "AnonymousAssociate", "GroupIdx": 648, "FullName": "<NAME>", "FormalName": "<NAME>", "Deleted": true, "EjUserId": 28, "UserName": "Weissnat LLC", "TableRight": {}, "FieldProperties": { "fieldName": { "FieldRight": { "Mask": "FULL", "Reason": "" }, "FieldType": "System.Int32", "FieldLength": 947 } } }, "Category": { "Id": 766, "Value": "sint", "Tooltip": "ut", "TableRight": {}, "FieldProperties": { "fieldName": { "FieldRight": { "Mask": "FULL", "Reason": "scale one-to-one systems" }, "FieldType": "System.String", "FieldLength": 141 } } }, "Business": { "Id": 68, "Value": "consequatur", "Tooltip": "ad", "TableRight": {}, "FieldProperties": { "fieldName": { "FieldRight": { "Mask": "FULL", "Reason": "" }, "FieldType": "System.Int32", "FieldLength": 535 } } }, "Associate": { "AssociateId": 224, "Name": "Sauer-Jacobs", "PersonId": 101, "Rank": 766, "Tooltip": "dignissimos", "Type": "AnonymousAssociate", "GroupIdx": 707, "FullName": "<NAME>", "FormalName": "<NAME> and Willms", "Deleted": true, "EjUserId": 594, "UserName": "Hand-Mueller", "TableRight": {}, "FieldProperties": { "fieldName": { "FieldRight": { "Mask": "FULL", "Reason": "" }, "FieldType": "System.Int32", "FieldLength": 406 } } }, "Salutation": "dignissimos", "ActiveInterests": 116, "SupportAssociate": { "AssociateId": 471, "Name": "<NAME>", "PersonId": 717, "Rank": 136, "Tooltip": "odio", "Type": "AnonymousAssociate", "GroupIdx": 276, "FullName": "<NAME>", "FormalName": "<NAME> and Ferry", "Deleted": false, "EjUserId": 933, "UserName": "Osinski-Lind", "TableRight": {}, "FieldProperties": { "fieldName": { "FieldRight": { "Mask": "FULL", "Reason": "" }, "FieldType": "System.String", "FieldLength": 32 } } }, "TicketPriority": { "Id": 881, "Value": "illo", "Tooltip": "ut", "TableRight": {}, "FieldProperties": { "fieldName": { "FieldRight": { "Mask": "FULL", "Reason": "enhance killer mindshare" }, "FieldType": "System.Int32", "FieldLength": 842 } } }, "CustomerLanguage": { "Id": 148, "Value": "soluta", "Tooltip": "non", "TableRight": {}, "FieldProperties": { "fieldName": { "FieldRight": { "Mask": "FULL", "Reason": "" }, "FieldType": "System.Int32", "FieldLength": 687 } } }, "DbiAgentId": 216, "DbiKey": "distinctio", "DbiLastModified": "2017-05-13T18:28:49.5470874+02:00", "DbiLastSyncronized": "2010-04-21T18:28:49.5470874+02:00", "SentInfo": 514, "ShowContactTickets": 525, "UserInfo": { "Deleted": false, "UserInfoId": 221, "UserName": "Kuphal-Nitzsche", "PersonId": 686, "Rank": 256, "Tooltip": "iure", "UserGroupId": 117, "EjUserId": 374, "UserType": "AnonymousAssociate", "GrantedLicenses": [ "cumque", "tempore" ], "CanLogon": true, "RoleName": "Herzog-Kunze", "RoleTooltip": "voluptatem", "UserGroupName": "Donnelly-McGlynn", "UserGroupTooltip": "nisi", "TableRight": {}, "FieldProperties": { "fieldName": { "FieldRight": { "Mask": "FULL", "Reason": "" }, "FieldType": "System.Int32", "FieldLength": 196 } } }, "ChatEmails": [ { "Value": "corrupti", "StrippedValue": "odio", "Description": "Distributed dedicated process improvement", "TableRight": {}, "FieldProperties": { "fieldName": { "FieldRight": { "Mask": "FULL", "Reason": "" }, "FieldType": "System.Int32", "FieldLength": 425 } } }, { "Value": "corrupti", "StrippedValue": "odio", "Description": "Distributed dedicated process improvement", "TableRight": {}, "FieldProperties": { "fieldName": { "FieldRight": { "Mask": "FULL", "Reason": "" }, "FieldType": "System.Int32", "FieldLength": 425 } } } ], "InternetPhones": [ { "Value": "vel", "StrippedValue": "voluptatem", "Description": "Open-source zero defect throughput", "TableRight": {}, "FieldProperties": { "fieldName": { "FieldRight": { "Mask": "FULL", "Reason": "" }, "FieldType": "System.String", "FieldLength": 65 } } }, { "Value": "vel", "StrippedValue": "voluptatem", "Description": "Open-source zero defect throughput", "TableRight": {}, "FieldProperties": { "fieldName": { "FieldRight": { "Mask": "FULL", "Reason": "" }, "FieldType": "System.String", "FieldLength": 65 } } } ], "Source": 16, "ActiveErpLinks": 614, "ShipmentTypes": [ { "Id": 647, "Name": "Graham-Volkman", "ToolTip": "Laboriosam deserunt.", "Deleted": false, "Rank": 996, "Type": "saepe", "ColorBlock": 816, "IconHint": "voluptatem", "Selected": true, "LastChanged": "2010-04-24T18:28:49.5480874+02:00", "ChildItems": [ {}, {} ], "ExtraInfo": "velit", "StyleHint": "voluptatem", "Hidden": true, "FullName": "<NAME>", "TableRight": {}, "FieldProperties": { "fieldName": { "FieldRight": { "Mask": "FULL", "Reason": "" }, "FieldType": "System.String", "FieldLength": 935 } } } ], "Consents": [ { "ConsentPersonId": 852, "Comment": "esse", "Registered": "2008-12-23T18:28:49.5480874+01:00", "RegisteredAssociateId": 1001, "Updated": "2000-03-02T18:28:49.5480874+01:00", "UpdatedAssociateId": 590, "LegalBaseId": 966, "LegalBaseKey": "aut", "LegalBaseName": "<NAME>", "ConsentPurposeId": 139, "ConsentPurposeKey": "ab", "ConsentPurposeName": "Gulgowski Group", "ConsentSourceId": 871, "ConsentSourceKey": "consectetur", "ConsentSourceName": "Cummerata-Pouros", "TableRight": {}, "FieldProperties": { "fieldName": { "FieldRight": { "Mask": "FULL", "Reason": "" }, "FieldType": "System.String", "FieldLength": 35 } } } ], "BounceEmails": [ "<EMAIL>", "<EMAIL>" ], "ActiveStatusMonitorId": 502, "UserDefinedFields": { "SuperOffice:1": "<NAME>", "SuperOffice:2": "<NAME>" }, "ExtraFields": { "ExtraFields1": "repellendus", "ExtraFields2": "eos" }, "CustomFields": { "CustomFields1": "omnis", "CustomFields2": "dolorem" }, "TableRight": { "Mask": "Delete", "Reason": "" }, "FieldProperties": { "fieldName": { "FieldRight": { "Mask": "FULL", "Reason": "" }, "FieldType": "System.Int32", "FieldLength": 718 } } } ``` ======================= File: docs/netserver/erp-connectors/online/erp-connector-in-online.md ======================= --- title: ERP Sync Connectors uid: erp_sync description: ERP Sync Connectors author: {github-id} keywords: ERP, EIS, sync connector --- # ERP Sync Connectors The **SuperOffice ERP Integration Server** (EIS) was introduced in SuperOffice CRM in version 7.5 and provides partners an API to create Sync Connectors that handle the synchronization of data between SuperOffice and an ERP system. While this article is not an instruction on how to build an ERP Sync Connector, the [existing documentation does a great job of that][1], it is an instructional read that defines an additional requirement when building ERP Connectors for SuperOffice Online. ## Architecture The standard architecture for ERP synchronization includes the ERP Integration Server (EIS), hosted as a service that facilitates all synchronization tasks. In the middle layer are the administrative aspects of the architecture; where consultants or administrators register connectors and establish connections. ![architecture-simplified][img1] On the right is the remote ERP Connector, a remote website that exposes the web service that implements the IErpConnector interface. This is where SuperOffice will connect to obtain ERP data. ## Configure When administrators configure an ERP Sync Connector inside SuperOffice today, they must fill in a Sync Connector name and a Sync Connector URL. ![editsyncconnector -screenconnector][img2] The Sync Connector name will be used as a reference for all connections created to this connector, and the Sync Connector URL specifies where SuperOffice EIS will contact to synchronize data. SuperOffice EIS will periodically invoke the web services to conduct data synchronization. This invocation is a blind call, meaning that no exchange of credentials or security layers exists between SuperOffice and the website hosting the web services. This configuration works great for onsite customer installations where both SuperOffice CRM and the ERP system reside inside the secure network but leaves much to be desired in the online environment. ## Continue reading * [Security][2] * [API changes][3] <!-- Referenced links --> [1]:../index.md [2]: secure-in-online.md [3]: example-api.md <!-- Referenced images --> [img1]: media/architecture-simplified.png [img2]: media/editsyncconnector.png ======================= File: docs/api-reference/restful/agent/Find_Agent/v1FindAgent_GetRestrictionGroups.md ======================= <reponame>SuperOfficeDocs/data-access<gh_stars>0 --- title: POST Agents/Find/GetRestrictionGroups id: v1FindAgent_GetRestrictionGroups --- # POST Agents/Find/GetRestrictionGroups ```http POST /api/v1/Agents/Find/GetRestrictionGroups ``` Return all the restriction groups. ## Query String Parameters | Parameter Name | Type | Description | |----------------|------|--------------| | $select | string | Optional comma separated list of properties to include in the result. Other fields are then nulled out to reduce payload size: "Name,department,category". Default = show all fields. | ```http POST /api/v1/Agents/Find/GetRestrictionGroups?$select=name,department,category/id ``` ## Request Headers | Parameter Name | Description | |----------------|-------------| | Authorization | Supports 'Basic', 'SoTicket' and 'Bearer' schemes, depending on installation type. | | X-XSRF-TOKEN | If not using Authorization header, you must provide XSRF value from cookie or hidden input field | | Content-Type | Content-type of the request body: `application/json`, `text/json`, `application/xml`, `text/xml`, `application/x-www-form-urlencoded`, `application/json-patch+json`, `application/merge-patch+json` | | Accept | Content-type(s) you would like the response in: `application/json`, `text/json`, `application/xml`, `text/xml`, `application/json-patch+json`, `application/merge-patch+json` | | Accept-Language | Convert string references and multi-language values into a specified language (iso2) code. | | SO-Language | Convert string references and multi-language values into a specified language (iso2) code. Overrides Accept-Language value. | | SO-Culture | Number, date formatting in a specified culture (iso2 language) code. Partially overrides SO-Language/Accept-Language value. Ignored if no Language set. | | SO-TimeZone | Specify the timezone code that you would like date/time responses converted to. | | SO-AppToken | The application token that identifies the partner app. Used when calling Online WebAPI from a server. | ## Request Body: request StorageType, ProviderName, StorageKey, Context | Property Name | Type | Description | |----------------|------|--------------| | StorageType | string | | | ProviderName | string | | | StorageKey | string | | | Context | string | | ## Response: array | Response | Description | |----------------|-------------| | 200 | OK | Response body: array | Property Name | Type | Description | |----------------|------|--------------| | Name | string | | | Description | string | | | Rank | int32 | | | Restrictions | array | | ## Sample Request ```http! POST /api/v1/Agents/Find/GetRestrictionGroups Authorization: Basic dGplMDpUamUw Accept: application/json; charset=utf-8 Accept-Language: en Content-Type: application/json; charset=utf-8 { "StorageType": "voluptatem", "ProviderName": "Murray, Leannon and Botsford", "StorageKey": "repudiandae", "Context": "inventore" } ``` ```http_ HTTP/1.1 200 OK Content-Type: application/json; charset=utf-8 [ { "Name": "Schowalter-Mitchell", "Description": "Profound composite collaboration", "Rank": 161, "Restrictions": [ { "Name": "Macejkovic, Schaefer and Bashirian", "Operator": "ut", "Values": [ "reiciendis", "ad" ], "DisplayValues": [ "necessitatibus", "ex" ], "ColumnInfo": {}, "IsActive": false, "SubRestrictions": [ {}, {} ], "InterParenthesis": 987, "InterOperator": "And", "UniqueHash": 52 } ] }, { "Name": "Schowalter-Mitchell", "Description": "Profound composite collaboration", "Rank": 161, "Restrictions": [ { "Name": "Macejkovic, Schaefer and Bashirian", "Operator": "ut", "Values": [ "reiciendis", "ad" ], "DisplayValues": [ "necessitatibus", "ex" ], "ColumnInfo": {}, "IsActive": false, "SubRestrictions": [ {}, {} ], "InterParenthesis": 987, "InterOperator": "And", "UniqueHash": 52 } ] } ] ``` ======================= File: docs/netserver/quote-connectors/start-client.md ======================= --- title: Start the client uid: quote_connectors_start description: How to start the quote connector client author: {github-id} so.date: keywords: quote so.topic: howto --- # Start the client Connections are initialized on demand. The SuperOffice windows client calls `InitializeConnection` during startup using the values saved from the **Create** connection dialog in the Admin client and then checks the return value to see if the ERP system is available. If the connection initialized OK, then SuperOffice will mark the connection as available for use. If the `InitializeConnection` returned NOT OK then the connection is marked as unavailable – and the connection will not be used for the remainder of the session. This means that any quotes created using this connection cannot be edited, and the **OPEN** button will be disabled. ![06][img1] If a connection fails to initialize then the result is cached, so that the client can get the initialize result later (for tooltips and the like). ## Int CRMConnectionId The ID of this connection in the CRM system. ## PluginResponseInfo InitializeConnection( QuoteConnectionInfo connectionData, Dictionary <string, string> configurationFields, IProductRegisterCache productRegister) Set up the connection to the ERP system. Will be called as part of SuperOffice client startup for each installed connection. Configuration data comes from the config dialog shown in the Admin client. See `IQuoteConnectorSetup.GetConfigurationFields` in [the setup][1]. The key in the Dictionary is the `FieldKey`, and must match the key in the `FieldMetadataInfo`. The value is the user's input during setup. **Return value IsOk:** False means the connection is not available, and quotes based on this connection cannot be edited. `IsOk`is set to false if the connector can’t provide service (no network). Text will explain this to the user. ## Dictionary < string, PluginResponseInfo > GetCapabilities() Returns a set of capability name-status pairs that tell the system what capabilities this connector provides. Using the `PluginResponseInfo` gives the connector the possibility to disable a capability, with a reason string that might be shown to the user. ## QuoteVersionResponseInfo OnBeforeCreateQuote ( QuoteContextInfo context ) Called when a user is creating a quote. Returns an updated context. The Quote does not exist in database at this time. Any changes in the returned `QuoteContextInfo` will be saved and the GUI updated. The following parts of the QuoteContextInfo can be updated by this method: * Quote * QuoteVersion * QuoteAlternative Changes to other parts of the `QuoteContextInfo` will be ignored. ## void OnAfterSaveQuote( QuoteContextInfo context ) Called after a sale containing a quote is saved: after quote is created, and after quote dialog is closed. > [!NOTE] > New items have now gotten their ids in the CRM system. Changes to the QuoteContextInfo are ignored. ## void OnBeforeDeleteQuote( QuoteInfo quote, ISaleInfo sale ) Called before a sale containing a quote is deleted. Clean up in the ERP system, if needed. <!-- Referenced links --> [1]: set-up.md <!-- Referenced images --> [img1]: media/image006.jpg ======================= File: docs/nuget/crm-online-winclient.md ======================= --- title: CRM Online WinClient uid: so_nuget_crm_online_winclient description: SuperOffice NuGet CRM Online WinClient author: <NAME> so.date: 02.29.2016 keywords: authentication so.topic: reference so.envir: so.client: --- # CRM Online WinClient SuperOffice Online WinClient is for WinForms or WPF applications that need support for SuperOffice online federated authentication. ## Get it `Install-Package SuperOffice.Crm.Online.WinClient` ## Assemblies * SuperOffice.SuperId.WinClient ## Package dependencies * SuperOffice.Crm.Online.Core ======================= File: docs/api-reference/restful/agent/Find_Agent/v1FindAgent_FindFromRestrictionsColumns.md ======================= --- title: POST Agents/Find/FindFromRestrictionsColumns id: v1FindAgent_FindFromRestrictionsColumns --- # POST Agents/Find/FindFromRestrictionsColumns ```http POST /api/v1/Agents/Find/FindFromRestrictionsColumns ``` Execute a Find operation and return a page of results. &lt;para/&gt;The criteria for the Find are passed in directly, not fetched by a restriction storage provider. &lt;para/&gt;The desired columns of the result set are also passed in directly.&lt;para/&gt;The orderby information is calculated by the system.&lt;para/&gt;Use the GetCriteriaInformation and GetDefaultDesiredColumns service methods to let the system calculate these values, if you want to use or modify them. Archive Restriction Info objects represent search terms. Column names and operator strings are defined elsewhere. Values should be encoded using the CultureDataFormatter, so 10 is "[I:10]". Default string encodings should be handled ok, but beware of non-invariant cultures leading to incorrect date and float parsing. ``` var restriction1 = new ArchiveRestrictionInfo("category", "equals", "[I:10]"); ``` ## Query String Parameters | Parameter Name | Type | Description | |----------------|------|--------------| | $select | string | Optional comma separated list of properties to include in the result. Other fields are then nulled out to reduce payload size: "Name,department,category". Default = show all fields. | ```http POST /api/v1/Agents/Find/FindFromRestrictionsColumns?$select=name,department,category/id ``` ## Request Headers | Parameter Name | Description | |----------------|-------------| | Authorization | Supports 'Basic', 'SoTicket' and 'Bearer' schemes, depending on installation type. | | X-XSRF-TOKEN | If not using Authorization header, you must provide XSRF value from cookie or hidden input field | | Content-Type | Content-type of the request body: `application/json`, `text/json`, `application/xml`, `text/xml`, `application/x-www-form-urlencoded`, `application/json-patch+json`, `application/merge-patch+json` | | Accept | Content-type(s) you would like the response in: `application/json`, `text/json`, `application/xml`, `text/xml`, `application/json-patch+json`, `application/merge-patch+json` | | Accept-Language | Convert string references and multi-language values into a specified language (iso2) code. | | SO-Language | Convert string references and multi-language values into a specified language (iso2) code. Overrides Accept-Language value. | | SO-Culture | Number, date formatting in a specified culture (iso2 language) code. Partially overrides SO-Language/Accept-Language value. Ignored if no Language set. | | SO-TimeZone | Specify the timezone code that you would like date/time responses converted to. | | SO-AppToken | The application token that identifies the partner app. Used when calling Online WebAPI from a server. | ## Request Body: request Restrictions, ProviderName, DesiredColumns, PageSize, PageNumber | Property Name | Type | Description | |----------------|------|--------------| | Restrictions | array | | | ProviderName | string | | | DesiredColumns | array | | | PageSize | int32 | | | PageNumber | int32 | | ## Response: object Result carrier for the Find operation. It contains a set of column specifications, and a set of row, where each row contains the columns. The row set is the result of carrying out some search operation. Carrier object for FindResults. Services for the FindResults Carrier is available from the <see cref="T:SuperOffice.CRM.Services.IFindAgent
1,529
team dashboards. Instead, your home page serves as a [single team dashboard](team-dashboard.md). For information on SharePoint dashboards, see [Project portal dashboards](../sharepoint-dashboards/project-portal-dashboards.md). ::: moniker-end ::: moniker range="tfs-2017" > [!NOTE] > For information on SharePoint dashboards, see [Project portal dashboards](../sharepoint-dashboards/project-portal-dashboards.md). ::: moniker-end [!INCLUDE [temp](../includes/dashboard-prerequisites.md)] ## Connect to your project All dashboards are associated with a team. ::: moniker range=">= azure-devops-2019" Open a web browser, connect to your project, and choose **Overview>Dashboards**. The dashboard directory page opens. > [!div class="mx-imgBorder"] >![Dashboards Directory, new navigation](media/dashboards/open-dashboards-vert.png) It lists dashboards in the following order: - Your last visited dashboard - Your favorited dashboards - All dashboards of teams that you belong to - All dashboards defined for the project in alphabetical order. Choose the![ ](../../media/icons/filter-icon.png) filter icon to filter the list by keyword or team. Keywords apply to dashboard titles, descriptions, and team names. > [!div class="mx-imgBorder"] >![Filter the dashboard directory](media/dashboards/filter-directory.png) If you need to switch to a different project, choose the![ ](../../media/icons/project-icon.png) Azure DevOps logo to [browse all projects](../../project/navigation/go-to-project-repo.md). ::: moniker-end ::: moniker range=">= tfs-2015 <= tfs-2018" Open a web browser, connect to your project, and choose **Dashboards**. ![Dashboards directory, previous navigation](media/dashboards-go-to.png) If you need to switch to a different project, choose the![ ](../../media/icons/project-icon.png) Azure DevOps logo to [browse all projects](../../project/navigation/go-to-project-repo.md). ::: moniker-end <a id="choose-dashboard" /> ::: moniker range=">= azure-devops-2019" ## Select a dashboard 1. Choose a dashboard from the directory list, or from the selector. To return to the dashboard directory, choose the **Browse all dashboards** option. > [!div class="mx-imgBorder"] >![Dashboards, Browse all dashboards option](media/dashboards/browse-all-dashboards.png) 1. To favorite a dashboard, hover over the dashboard and choose the![star icon](../../media/icons/icon-favorite-star.png). > [!div class="mx-imgBorder"] >![Dashboards, Favorite a dashboard](media/dashboards/favorite-dashboard.png) Favoriting a dashboard will cause it to appear under **My Favorites dashboards** list on the dashboards directory. Also, it will appear towards the top in the **Dashboards** selector and in your [personal Favorites list](../../project/navigation/set-favorites.md).. ::: moniker-end ::: moniker range=">= tfs-2015 <= tfs-2018" ## Select a dashboard 1. Select the team whose dashboards you want to view. To switch your team focus, see [Switch project, repo or team](../../project/navigation/go-to-project-repo.md#switch-team-context). 2. From **Dashboards**, choose the name of the dashboard to view it. For example, here we choose to view the Work in Progress dashboard. > [!div class="mx-imgBorder"] >![Dashboards, Choose a team dashboard](media/dashboards/choose-dashboard.png) ::: moniker-end ## Add a dashboard Add a new dashboard as needed to support your team's needs. You can also edit and rename any existing dashboards associated with your team. ::: moniker range="azure-devops" 1. From the Dashboards directory, choose **New Dashboard**. Or, when viewing a dashboard, open the selector and choose the![plus icon](media/icons/blue-plus-icon.png) **New Dashboard** option. > [!div class="mx-imgBorder"] >![Open the create a dashboard dialog](media/dashboards/open-new-dashboard-dialog.png) If you don't see the![plus icon](media/icons/blue-plus-icon.png) **New Dashboard** option, then you're not a team admin for the currently selected team, or you don't have permissions to add and edit dashboards. Either [switch the context to your team](../../project/navigation/go-to-project-repo.md?toc=/azure/devops/report/toc.json&bc=/azure/devops/report/breadcrumb/toc.json), or request you be added as a [team admin](../../organizations/settings/add-team-administrator.md?toc=/azure/devops/report/toc.json&bc=/azure/devops/report/breadcrumb/toc.json). 2. Enter the name of the dashboard and other information you want to capture. Here we choose to create a Project dashboard. To create a team dashboard, choose **Team Dashboard** and then select a team. To add a team, see [Add a team](../../organizations/settings/add-teams.md). > [!div class="mx-imgBorder"] >![Open the create a dashboard dialog](media/dashboards/create-dashboard-project-dialog.png) Choose **Save**. 3. The widget catalog opens. You can add one or more widgets to the dashboard. You can then configure and resize each widget as needed. 4. You can move the widgets around the dashboard to place them where you want them. 5. When you're done making changes, choose **Done Editing**. ::: moniker-end ::: moniker range="azure-devops-2019" 1. From the Dashboards directory, choose **New Dashboard**. Or, when viewing a dashboard, open the selector and choose the![plus icon](media/icons/blue-plus-icon.png) **New Dashboard** option. > [!div class="mx-imgBorder"] >![Open the create a dashboard dialog](media/dashboards/open-new-dashboard-dialog.png) If you don't see the![plus icon](media/icons/blue-plus-icon.png) **New Dashboard** option, then you're not a team admin for the currently selected team, or you don't have permissions to add and edit dashboards. Either [switch the context to your team](../../project/navigation/go-to-project-repo.md?toc=/azure/devops/report/toc.json&bc=/azure/devops/report/breadcrumb/toc.json), or request you be added as a [team admin](../../organizations/settings/add-team-administrator.md?toc=/azure/devops/report/toc.json&bc=/azure/devops/report/breadcrumb/toc.json). 2. Enter the name of the dashboard and other information you want to capture. > [!div class="mx-imgBorder"] >![Create a dashboard dialog](media/dashboards/create-dashboard-bug-status.png) Choose **Save**. 3. The widget catalog opens. You can add one or more widgets to the dashboard. You can then configure and resize each widget as needed. 4. You can move the widgets around the dashboard to place them where you want them. 5. When you're done making changes, choose **Done Editing**. ::: moniker-end ::: moniker range=">= tfs-2015 <= tfs-2018" From **Dashboards**, choose the![plus icon](../../boards/media/icons/green_plus_icon.png) and enter a dashboard name. ![Add and name a dashboard](media/dashboards-new-ts.png) If you don't see the![plus icon](../../boards/media/icons/green_plus_icon.png), then you're not a team admin for the currently selected team, or you don't have permissions to add and edit dashboards. Either [switch the context to your team](../../project/navigation/go-to-project-repo.md?toc=/azure/devops/report/dashboards/toc.json&bc=/azure/devops/report/breadcrumb/dashboards/toc.json), or request you be added as a [team admin](../../organizations/settings/add-team-administrator.md?toc=/azure/devops/report/dashboards/toc.json&bc=/azure/devops/report/breadcrumb/dashboards/toc.json). With the dashboard selected, you can add [widgets and charts to the dashboard](add-widget-to-dashboard.md). Or, you can [add charts to a team dashboard from the Work, Build, or Test pages](add-charts-to-dashboard.md). ::: moniker-end <a id="manage"> </a> ## Rename, delete, and enable auto-refresh You can rename or delete a dashboard. Also, you can enable auto-refresh, and the dashboard will automatically update every 5 minutes. ::: moniker range=">= tfs-2015 <= tfs-2017" > [!NOTE] > You can configure the auto-refresh setting for each dashboard for TFS 2015.2 and later versions. For TFS 2017.1 and later versions, you can [set dashboard permissions](dashboard-permissions.md). ::: moniker-end ::: moniker range=">= azure-devops-2019" - To rename a dashboard, modify it's description, or change it's automatic refresh setting, open the dashboard, choose the![gear icon](media/icons/gear-icon.png) gear icon, and change the field options shown. Save your changes. - To delete a dashboard, open the Dashboards directory, choose the![ ](../../media/icons/actions-icon.png) actions icon for the dashboard, and select the **Delete** menu option. > [!div class="mx-imgBorder"] >![Delete a dashboard](media/dashboards/delete-dashboard.png) - To set permissions for a dashboard, choose the **Security** option. For details, see [Set dashboard permissions](dashboard-permissions.md). ::: moniker-end ::: moniker range=">= tfs-2017 <= tfs-2018" 1. To manage dashboards, choose the![configure icon](media/icons/configure-icon.png) wrench icon. ![Open Manage dashboards dialog](media/dashboards-configure-ts.png) 2. Drag and drop the dashboards into the sequence you want them to appear. ![Manage dashboards dialog](media/manage-dashboards-ts.png) 3. (Optional) Select the Auto-refresh checkbox when you want the dashboard to refresh every five minutes. 4. To delete a dashboard, choose the![ ](media/icons/delete_icon.png) delete icon. 5. Choose Save to save your changes. You can also [manage dashboard permissions](dashboard-permissions.md). ::: moniker-end ::: moniker range="tfs-2015" 1. To manage dashboards, choose the![ ](../../media/icons/admin-gear-icon.png) gear icon. ![Open Manage dashboards dialog](media/dashboards-open-manage-dashboards-tfs.png) 2. Drag and drop the dashboards into the sequence you want them to appear. ![Manage dashboards dialog](media/manage-dashboards.png) 3. (Optional) Select the Auto-refresh checkbox when you want the dashboard to refresh every five minutes. The Auto-refresh feature requires TFS 2015.2 or later version. 4. To delete a dashboard, choose the![ ](media/icons/delete_icon.png) delete icon. 5. Choose **Save** to save your changes. ::: moniker-end ## Move or delete a widget > [!NOTE] > Just as you have to be a team admin, a project admin, or have the necessary permissions to add items to a dashboard, you must have the [necessary permissions](#permissions) to remove items. ::: moniker range=">= azure-devops-2019" Choose![ ](media/icons/edit-icon.png) **Edit** to modify your dashboard. You can then add widgets or drag tiles to reorder their sequence on the dashboard. To remove a widget, choose the![actions icon](../../media/icons/actions-icon.png) actions icon and select the **Delete** option from the menu. > [!div class="mx-imgBorder"] >![Delete a widget from a dashboard](media/dashboards/delete-widget.png) When you're finished with your changes, choose **Done Editing** to exit dashboard edit mode. > [!TIP] > When you're in dashboard edit mode, you can remove, rearrange, and configure widgets, as well as add new widgets. Once you leave edit mode, the widget tiles remain locked, reducing the chances of accidentally moving a widget. ::: moniker-end ::: moniker range=">= tfs-2015 <= tfs-2018" Choose![Edit dashboard icon](media/edit-dashboard-icon.png) to modify your dashboard. You can then drag tiles to reorder their sequence on the dashboard. To remove a widget, choose the widget's![Trash icon](media/dashboard-trash-icon.png) or![Delete icon](media/dashboard-delete-icon.png) delete icons. When you're finished with your changes, choose![Exit edit-dashboard-mode icon](media/exit-edit-dashboard-mode-icon.png) to exit dashboard editing. > [!TIP] > When you're in dashboard edit mode, you can remove, rearrange, and configure widgets, as well as add new widgets. Once you leave edit mode, the widget tiles remain locked, reducing the chances of accidentally moving a widget. Note that you can drag and drop a widget from the catalog onto the dashboard. ::: moniker-end ## Try this next As you can see, you can use team dashboards to provide guidance and keep your team in sync, providing visibility across your org about status, trends, and progress. > [!div class="nextstepaction"] > [Add a widget to a dashboard](add-widget-to-dashboard.md) ## Related articles - [Add a team](../../organizations/settings/add-teams.md) - [Widget catalog](widget-catalog.md) - [Marketplace widgets](https://marketplace.visualstudio.com/search?term=widget&target=VSTS&category=All%20categories&sortBy=Relevance) ### Extensibility Using the REST API service, you can [create a dashboard widget](../../extend/develop/add-dashboard-widget.md). To learn more about the REST APIs for dashboards and widgets, see [Dashboards (API)](/rest/api/azure/devops/dashboard/dashboards). ======================= File: docs/cli/auto-detect-and-git-aliases.md ======================= <filename>docs/cli/auto-detect-and-git-aliases.md --- title: Auto detect configuration and git aliases titleSuffix: Azure DevOps description: Auto detect configuration and git aliases when using Azure DevOps extension command-line interface ms.topic: conceptual ms.prod: devops ms.technology: devops-ref ms.manager: mijacobs ms.author: geverghe author: KathrynEE monikerRange: 'azure-devops' ms.date: 06/18/2019 --- # Auto detect configuration and git aliases [!INCLUDE [temp](../includes/version-vsts-only.md)] The Azure DevOps CLI has been optimized to allow developers to use Azure Repos and work well with their git workflows. ## Auto detect configuration The Azure DevOps Extension evaluates if your current working directory is an Azure Repos git repository to auto detect configuration setting - organization, project, and repository. Auto detection is controlled by the `--detect` flag, which is `true` by default. With this capability, you can run `az repos pr list` in your local git checkout to view all PRs in the repository. ## Git alias You can also configure the Azure DevOps Extension to add git aliases for common git-based Azure Repos commands like creating or adding reviewers to pull requests. Run the following command to enable git aliases. ```bash az devops configure --use-git-aliases true ``` All `az repos` commands will now be aliased to `git repo` and all `az repos pr` commands to `git pr`. For example, a pull request can now be created using the following command: ```bash git pr create --target-branch {branch\_name} ``` ## Parameter hierarchy There are three main ways by which parameters can be provided to a command. They have been listed in order of priority: 1. Command parameters For example: `az repos list --organization https://dev.azure.com/contoso --project webApplication` 2. Auto detection from git context if `--detect` is `true`. Detect is `true` by default. 3. Default configuration For example: `az devops configure --defaults organization=https://dev.azure.com/contoso project=webApplication` Say a customer runs the following commands ```bash ~/$ az devops configure --defaults organization=https://dev.azure.com/contoso project=webApp ~/$ az repos list --organization=https://dev.azure.com/contosoTest --project=testApplication ```` The organization and project parameter provided via command will be used since command parameters take top priority. Let's have a look at another example. Say a user has pre-configured the default organization to `contoso` and project to `webApp`. However, the user is working out of a local checkout of a git repo, which is in the `contosoTest` organization and `testApplication` project. Further, `--detect` is `true` by default. ```bash ~/contosoTest/portal$ az devops configure --defaults organization=https://dev.azure.com/contoso project=webApp ~/contosoTest/portal$ az repos list ``` In this case, `contosoTest` and `testApplication` will be auto detected as the target organization and project from git context and will override the defaults that have been set. ======================= File: release-notes/2019/includes/boards/sprint-150-update.md ======================= <reponame>Chibuikekenneth/azure-devops-docs<filename>release-notes/2019/includes/boards/sprint-150-update.md --- ms.topic: include --- ### Query work based on Azure Active Directory groups With the increased adoption of Azure Active Directory and prevalence of using groups to manage security, teams have increasingly been looking for ways to leverage those groups in Azure Boards. Now, in addition to querying work items which have been assigned or changed by specific people using the **In Group** or **Not In Group** operators, you can also use Azure Active Directory groups directly. See the [query operators]( https://docs.microsoft.com/azure/devops/boards/queries/query-by-workflow-changes?view=azure-devops#team-or-group-membership-queries) documentation for more information. > [!div class="mx-imgBorder"] >![Badge](../../media/150_04.png "Query for work based") ### Share your team’s board using a badge The repository’s README is often the home that your project team turns to for information about how to contribute to and use your solution. Now, like you can with a build or deployment status in Azure Pipelines, you can add to your README a badge for your team’s board in Azure Boards. You can configure the badge to show only the **In Progress** columns or all columns, and even make the badge visible publicly if your project is open source. > [!div class="mx-imgBorder"] >![Badge](../../media/150_29.png "Share your team's boards using badge") If your README is based on Markdown you can simply copy the sample Markdown from the status badge settings page and paste it into your file. > [!div class="mx-imgBorder"] >![Badge](../../media/150_28.png "Badge in a README on GitHub") ### Query for work relative to the start of the day, week, month, or year While teams often focus on work within the context of what’s coming up next or based on sprint iterations, it’s often interesting to look back at work through the lens of the calendar to report on all the work that happened last month or in the first quarter of the year. Now you can use the following new set of <strong>@StartOf</strong> macros along with any date-based field to query based on the start of the day, week, month or year: * @StartOfYear * @StartOfMonth * @StartOfWeek * @StartOfDay Each of these macros also accepts a new modifier string that lets you shift the data by different date units. For example, you can write a query to find all work items completed in the first quarter of this year by querying on State Change Date >= @StartOfYear and State Change Date <= @StartOfYear(“+3M”). See the [query macros](https://docs.microsoft.com/azure/devops/boards/queries/query-operators-variables?view=azure-devops#query-macros-or-variables) documentation for more information. > [!div class="mx-imgBorder"] >![Badge](../../media/150_26.png "Query for work relative to the start of the day, week, month, or year" ) ### Export query results to a CSV file You can now export query results directly to a CSV format file from the web. > [!div class="mx-imgBorder"] >![Badge](../../media/150_31.gif "Export query results") ======================= File: docs/report/excel/build-quality-excel-report.md ======================= --- title: Build Quality Excel Report description: Help monitor the success or failure rate of test activity with each build - Team Foundation Server titleSuffix: TFS ms.technology: devops-analytics ms.topic: reference ms.assetid: 60e637b9-4599-4fe5-bff1-e6adade81d9c ms.author: kaelli author: KathrynEE monikerRange: '<= tfs-2017' ms.date: 12/30/2016 --- # Build Quality Excel report [!INCLUDE [temp](../includes/tfs-sharepoint-version.md)] > [!IMPORTANT] > This report is only applicable for XAML builds, which are deprecated for TFS 2018 and later versions. If your build process isn't based on XAML builds, this report and the TFS Warehouse for builds won't yield any meaningful data. Teams who are responsible for testing software can use the Build Quality report to help monitor the success or failure rate of test activity with each build. The Build Quality report provides the following reports, which show the test results for all build pipelines for a team project. - **Build Verification Testing**: Helps the team monitor the quality of builds by showing test results for all automated tests that are marked as Build Verification Test (BVT) that are run during the build process. - **Test Activity Per Build**: Helps the team monitor the quality of builds by showing test results for all tests that have been run against the build for all or selected test plans. > [!NOTE] > You can view the Build Quality report if you open Team Explorer, open the team project, open the **Excel Reports** folder, and open the **Test Team Management** folder. You can access this folder only if your team project portal has been enabled and is configured to use SharePoint Server Enterprise Edition. For more information, see [Share information using the project portal](../sharepoint-dashboards/share-information-using-the-project-portal.md). These reports are available only when the team creates test plans and starts to run tests by using Microsoft Test Manager. For information about how to define test suites and test plans, see [Plan your tests](../../test/create-test-cases.md). For information about how to access this report, see [Excel reports](excel-reports.md). **Required permissions** To view the report, you must be assigned or belong to a group that has been assigned the **Read** permissions in SharePoint Products for the team project. To modify or customize the report, you must be a member of the **TfsWarehouseDataReaders** security role in SQL Server Analysis Services. You must also be assigned or belong to a group that has been assigned the **Members** permissions in SharePoint Products for the team project. For more information, see [Grant Access to the Databases of the Data Warehouse for Team System](../admin/grant-permissions-to-reports.md). <a name="Data"></a> ## Data in the reports The Build Quality reports illustrate the cumulative count of test results for all build pipelines for a team project. Both reports are based on PivotTable reports that access data that is stored in the data warehouse. The count that is shown in each report is a count of the most recent version of each test result in a particular build. **Build verification testing** ![Build Quality Excel Report](media/procg_buildqualitybvt.png "ProcG_BuildQualityBVT") **Test activity per build** ![Test Activity PerBuild Excel Report](media/procg_testactperbuild.png "ProcG_TestActPerBuild") The following table describes the report filters and fields that are used in the PivotTables that generate the Build Quality reports. | Filters | Fields | |------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | - **Team Project - Team Project Hierarchy**: Includes build results for build pipelines that are defined for the selected team project.<br />- **Test Result - Iteration Hierarchy**: Includes test results that were run from test cases that were assigned to the selected iterations.<br />- **Test Result - Area Hierarchy**: Includes test results that were run from test cases that were assigned to the selected product areas.<br />- **Build - Build Pipeline Name**: Includes test results that were run against builds that belong to the selected build pipelines.<br /><br /> **Filter specific to the Build Verification Testing report**:<br /><br /> - **Test Run - Is Build Verification Run**: Includes test results from all automated tests that were run during the build process and configured as BVT. | - **Test Result - Outcome**: The outcome of the test (for example, Blocked, Never Run, Failed, None, and Passed).<br />- **(Measure) Test Result - Build Result Count Trend**: Counts the most recent version of each test result in a particular build.<br />- **Build - Build Name**: The name of the build. Each time that a build is run, it is assigned a name that contains the build pipeline name as its prefix. | <a name="RequiredActivities"></a> ### Required activities for monitoring build quality For the Build Quality report to be useful and accurate, the team must perform the following activities: - Define test cases and test plans, and assign test cases to the test plans. - **Define tests to run automatically as part of the build**. As part of the build pipeline, you can define tests to run as part of the build or to fail if the tests fail. For more information, see [Run tests in your build process](../../pipelines/test/test-build.md). - **Run builds regularly**. You can run builds at set intervals or after every check-in. You can create regular builds when you use the schedule trigger. For more information, see [Get started with CI/CD](../../pipelines/get-started-designer.md). - **Run tests**. For more information, see [Run your tests](../../test/run-manual-tests.md). - (Optional) To support filtering, assign **Iteration** and **Area** paths to each test case. > [!NOTE] > The project administrator for each team project defines area and iteration paths for that project so that the team can track progress by those designations. For more information, see[Define area paths](../../organizations/settings/set-area-paths.md) or [Define iteration paths](../../organizations/settings/set-iteration-paths-sprints.md). <a name="Updating"></a> ## Update and customize the report You can update the Build Quality report by opening it in Office Excel and changing the filter options for the PivotTable report for one of the worksheets. You can customize each report to support other views, as the following table describes. |View|Action| |----------|------------| |Build quality for select iterations|Change the filter for **Iteration** (default=All)| |Build quality for select product areas|Change the filter for **Area** (default=All)| |Build quality for select build pipelines|Change the filter for **Build Pipeline Name** (default=All)| |Build quality for the most recent six, eight, or more weeks|In the Columns PivotTable Field List, add the **Date - Sets** field and select **@@Last 6 weeks@@** or other set| ## Related articles - [Excel reports](excel-reports.md) - [Design the layout and format of a PivotTable](https://support.office.com/article/design-the-layout-and-format-of-a-pivottable-a9600265-95bf-4900-868e-641133c05a80) ======================= File: docs/extend/reference/client/api/TFS/Work/Contracts/Activity.md ======================= <reponame>Chibuikekenneth/azure-devops-docs<filename>docs/extend/reference/client/api/TFS/Work/Contracts/Activity.md --- title: TFS/Work/Contracts Activity API | Extensions for Azure DevOps Services ms.assetid: 57257f6f-2a5b-6d03-2ef2-0617bcceadc0 ms.technology: devops-ecosystem generated: true author: chcomley ms.topic: article ms.author: chcomley ms.date: 08/04/2016 --- # Activity Module path: `TFS/Work/Contracts` ### Members * `capacityPerDay`: number. * `name`: string. ======================= File: docs/extend/reference/client/api/TFS/TestManagement/Contracts/FunctionCoverage.md ======================= <reponame>Chibuikekenneth/azure-devops-docs --- title: TFS/TestManagement/Contracts FunctionCoverage API | Extensions for Azure DevOps Services description: Data representation of a function coverage. ms.assetid: 49fd64d7-eb18-d835-e0a1-0049994be27f ms.technology: devops-ecosystem generated: true author: chcomley ms.topic: article ms.author: chcomley ms.date: 08/04/2016 --- # FunctionCoverage Module path: `TFS/TestManagement/Contracts` ### Members * `class`: string. * `name`: string. * `namespace`: string. * `sourceFile`: string. * `statistics`: [CoverageStatistics](../../../TFS/TestManagement/Contracts/CoverageStatistics.md). ======================= File: docs/organizations/settings/includes/change-process-preview-note.md ======================= --- ms.topic: include --- > [!NOTE] > The **Change process** feature is currently in private preview for Azure DevOps Services only. ======================= File: docs/report/powerbi/includes/sample-fulllist.md ======================= <filename>docs/report/powerbi/includes/sample-fulllist.md --- ms.topic: include --- - [Open bugs](/azure/devops/report/powerbi/sample-boards-openbugs) - [Bug trend](/azure/devops/report/powerbi/sample-boards-bugtrend) - [Rollup](/azure/devops/report/powerbi/sample-boards-rollup) - [Feature progress](/azure/devops/report/powerbi/sample-boards-featureprogress) - [Work items and direct links](/azure/devops/report/powerbi/sample-boards-directlinks) - [Release burndown](/azure/devops/report/powerbi/sample-boards-releaseburndown) - [Sprint burndown](/azure/devops/report/powerbi/sample-boards-sprintburndown) - [Cumulative Flow Diagram (CFD)](/azure/devops/report/powerbi/sample-boards-cfd) - [Lead/Cycle Time](/azure/devops/report/powerbi/sample-boards-leadcycletime) ======================= File: docs/extend/reference/client/api/VSS/References/VSS_SDK_Interfaces/IExtensionContext.md ======================= <gh_stars>1-10 --- title: VSS/References/VSS.SDK.Interfaces IExtensionContext API | Extensions for Azure DevOps Services description: Context about the app that owns the content that is being hosted ms.assetid: c4bd9815-17f9-9c4f-6240-c8549564fce7 ms.technology: devops-ecosystem generated: true ms.author: chcomley author: chcomley ms.topic: article monikerRange: '>= tfs-2017' ms.date: 08/04/2016 --- # IExtensionContext Defined in vss.d.ts Context about the app that owns the content that is being hosted ### Members * `publisherId`: string. Friendly unique ID of the publisher * `extensionId`: string. Friendly ID of the extension (unique within the publisher) * `version`: string. Version of the extension * `baseUri`: string. The base uri to be used with relative urls in contribution properties ======================= File: docs/pipelines/tasks/package/npm-authenticate.md ======================= <gh_stars>1-10 --- title: npm Authenticate task (for task runners) ms.custom: seodec18 description: Don't use this task if you're also using the npm task. Provides npm credentials to an `.npmrc` file in your repository for the scope of the build. This enables npm task runners like gulp and Grunt to authenticate with private registries. ms.topic: reference ms.assetid: ad884ca2-732e-4b85-b2d3-ed71bcbd2788 ms.author: vijayma author: vijayma ms.date: 04/21/2020 monikerRange: 'azure-devops' --- # Package: npm Authenticate task (for task runners) **Azure Pipelines** Use this task to provide npm credentials to an `.npmrc` file in your repository for the scope of the build. This enables npm, as well as npm task runners like gulp and Grunt, to authenticate with private registries. ::: moniker range="> tfs-2018" ## YAML snippet [!INCLUDE [temp](../includes/yaml/NpmAuthenticateV0.md)] ::: moniker-end ## Arguments |Argument| Description | | -------|------------ | | `workingFile`<br/>.npmrc file to authenticate | Path to the.npmrc file that specifies the registries you want to work with. Select the file, not the folder. <br/>For example \/packages/mypackage.npmrc"| | `customEndpoint`<br/>Credentials for registries outside this organization/collection | (Optional) Comma-separated list of [npm service connection](../../library/service-endpoints.md)names for registries outside this organization/collection. The specified `.npmrc` file must contain registry entries corresponding to the service connections. If you only need registries in this organization/collection, leave this blank. The build’s credentials are used automatically.| ## Examples ### Restore npm packages for your project from a registry within your organization If the only authenticated registries you use are Azure Artifacts registries in your organization, you only need to specify the path to an.npmrc file to the npmAuthenticate task. ####.npmrc ``` registry=https://pkgs.dev.azure.com/{organization}/_packaging/{feed}/npm/registry/ always-auth=true ``` #### npm ```YAML - task: npmAuthenticate@0 inputs: workingFile:.npmrc - script: npm ci #... - script: npm publish ``` ### Restore and publish npm packages outside your organization If your `.npmrc` contains Azure Artifacts registries from a different organization or use a third-party authenticated package repository, you'll need to set up <a href="~/pipelines/library/service-endpoints.md#sep-npm">npm service connections</a> and specify them in the `customEndpoint` input. Registries within your Azure Artifacts organization will also be automatically authenticated. ####.npmrc ``` registry=https://pkgs.dev.azure.com/{organization}/{project}/_packaging/{feed}/npm/registry/ @{scope}:registry=https://pkgs.dev.azure.com/{otherorganization}/_packaging/{feed}/npm/registry/ @{otherscope}:registry=https://{thirdPartyRepository}/npm/registry/ always-auth=true ``` The registry URL pointing to an Azure Artifacts feed may or may not contain the project. An URL for a project scoped feed must contain the project, and the URL for a organization scoped feed must not contain the project. [Learn more](../../../artifacts/feeds/project-scoped-feeds.md). #### npm ```YAML - task: npmAuthenticate@0 inputs: workingFile:.npmrc customEndpoint: OtherOrganizationNpmConnection, ThirdPartyRepositoryNpmConnection - script: npm ci #... - script: npm publish -registry https://pkgs.dev.azure.com/{otherorganization}/_packaging/{feed}/npm/registry/ ``` `OtherOrganizationNpmConnection` and `ThirdPartyRepositoryNpmConnection` are the names of <a href="~/pipelines/library/service-endpoints.md#sep-npm">npm service connections</a> that have been configured and authorized for use in your pipeline, and have URLs that match those in the specified `.npmrc` file. <tr> <th style="text-align: center" colspan="2"><a href="~/pipelines/process/tasks.md#controloptions">Control options</a></th> </tr> </table> ## Open source This task is open source [on GitHub](https://github.com/Microsoft/azure-pipelines-tasks). Feedback and contributions are welcome. ## Q & A <!-- BEGINSECTION class="md-qanda" --> ### How does this task work? This task searches the specified `.npmrc` file for registry entries, then appends authentication details for the discovered registries to the end of the file. For all registries in the current organization/collection, the build's credentials are used. For registries in a different organization or hosted by a third-party, the registry URIs will be compared to the URIs of the <a href="~/pipelines/library/service-endpoints.md#sep-npm">npm service connections</a> specified by the `customEndpoint` input, and the corresponding credentials will be used. The `.npmrc` file will be reverted to its original state at the end of the pipeline execution. ### When in my pipeline should I run this task? This task must run before you use npm, or an npm task runner, to install or push packages to an authenticated npm repository such as Azure Artifacts. There are no other ordering requirements. ### I have multiple npm projects. Do I need to run this task for each.npmrc file? This task will only add authentication details to one `.npmrc` file at a time. If you need authentication for multiple `.npmrc` files, you can run the task multiple times, once for each `.npmrc` file. Alternately, consider creating an `.npmrc` file that specifies all registries used by your projects, running npmAuthenticate on this `.npmrc` file, then setting an environment variable to designate this `.npmrc` file as the npm per-user configuration file. ```YAML - task: npmAuthenticate@0 inputs: workingFile: $(agent.tempdirectory)/.npmrc - script: echo ##vso[task.setvariable variable=NPM_CONFIG_USERCONFIG]$(agent.tempdirectory)/.npmrc - script: npm ci workingDirectory: project1 - script: npm ci workingDirectory: project2 ``` ### My agent is behind a web proxy. Will npmAuthenticate set up npm/gulp/Grunt to use my proxy? The answer is no. While this task itself will work behind a web proxy <a href="~/pipelines/agents/proxy.md">your agent has been configured to use</a>, it does not configure npm or npm task runners to use the proxy. To do so, you can either: * Set the environment variables `http_proxy`/`https_proxy` and optionally `no_proxy` to your proxy settings. See [npm config](https://docs.npmjs.com/misc/config#https-proxy) for details. Note that these are commonly used variables which other non-npm tools (e.g. curl) may also use. * Add the proxy settings to the [npm configuration](https://docs.npmjs.com/misc/config), either manually, by using [npm config set](https://docs.npmjs.com/cli/config#set), or by setting [environment variables](https://docs.npmjs.com/misc/config#environment-variables) prefixed with `NPM_CONFIG_`. >**Caution:** >npm task runners may not be compatible with all methods of proxy configuration supported by npm. * Specify the proxy with a command line flag when calling npm ```YAML - script: npm ci --https-proxy $(agent.proxyurl) ``` If your proxy requires authentication, you may need to add an additional build step to construct an authenticated proxy uri. ```YAML - script: node -e "let u = url.parse(`$(agent.proxyurl)`); u.auth = `$(agent.proxyusername):$(agent.proxypassword)`; console.log(`##vso[task.setvariable variable=proxyAuthUri;issecret=true]` + url.format(u))" - script: npm publish --https-proxy $(proxyAuthUri) ``` <!-- ENDSECTION --> ======================= File: docs/extend/reference/client/api/TFS/VersionControl/Contracts/ItemContent.md ======================= <filename>docs/extend/reference/client/api/TFS/VersionControl/Contracts/ItemContent.md --- title: TFS/VersionControl/Contracts ItemContent API | Extensions for Azure DevOps Services ms.assetid: 6168c0ae-5f16-570f-4032-4938581ec9c8 ms.technology: devops-ecosystem generated: true author: chcomley ms.topic: article ms.author: chcomley ms.date: 08/04/2016 --- # ItemContent Module path: `TFS/VersionControl/Contracts` ### Members * `content`: string. * `contentType`: [ItemContentType](../../../TFS/VersionControl/Contracts/ItemContentType.md). ======================= File: docs/pipelines/tasks/build/gulp.md ======================= --- title: Gulp build and release task ms.custom: seodec18 description: Gulp build and release task for Azure Pipelines and Team Foundation Server (TFS) ms.topic: reference ms.assetid: EC168F1F-4B27-4688-87CE-E4D12E885CC5 ms.author: vijayma author: vijayma ms.date: 12/17/2019 monikerRange: '>= tfs-2015' --- # Gulp task [!INCLUDE [temp](../../includes/version-tfs-2015-rtm.md)] Use this task to run gulp tasks using the Node.js streaming task-based build system. ## Demands gulp ::: moniker range="> tfs-2018" ## YAML snippet [!INCLUDE [temp](../includes/yaml/GulpV1.md)] ::: moniker-end ## Arguments |Argument|Description| |--- |--- | |`gulpFile` <br/>gulp File Path|(Required) Relative path from the repo root of the gulp file script that you want to run. <br/>Default value: gulpfile.js| |`targets` <br/>gulp Task(s)|(Optional) Space-delimited list of tasks to run. If not specified, the default task will run.| |`arguments` <br/>Arguments|Additional arguments passed to gulp. <br/>Tip: --gulpfile is not needed since already added via gulpFile input above| |`cwd` <br/>Working Directory|(Optional) Current working directory when the script is run. Defaults to the folder where the script is located. <br/>Argument aliases: `workingDirectory`| |`gulpjs` <br/>gulp.js location|(Optional) Path to an alternative gulp.js, relative to the working directory. <br/>Argument aliases: `workingDirectory`| |`publishJUnitResults` <br/>Publish to Azure Pipelines|Select this option to publish JUnit test results produced by the gulp build to Azure Pipelines <br/>Default value: false| |`testResultsFiles` <br/>Test Results Files|(Required) Test results files path. Wildcards can be used. For example, \*\*/TEST-\*.xml for all XML files whose name starts with TEST-. <br/>Default value: \*\*/TEST-\*.xml| |`testRunTitle` <br/>Test Run Title|(Optional) Provide a name for the test run| |`enableCodeCoverage` <br/>Enable Code Coverage|(Optional) Select this option to enable Code Coverage using Istanbul <br/>Default value: false| |`testFramework` <br/>Test Framework|(Optional) Select your test framework <br/>Default value: Mocha| |`srcFiles` <br/>Source Files|(Optional) Provide the path to your source files, that you want to hookRequire ()| |`testFiles` <br/>Test Script Files|(Required) Provide the path to your test script files <br/>Default value: test/*.js| ## Example ### Run gulp.js On the [Build](../../index.yml) tab: <table> <tr> <td> ![Package: npm](../package/media/npm.png) <br/>[Package: npm](../package/npm.md)</td> <td> <p>Install npm.</p> <ul> <li>Command: <code>install</code></li> </ul> </td> </tr> <tr> <td> ![Build: gulp](media/gulp.png) <br/>[Build: gulp](gulp.md)</td> <td> <p>Run your script.</p> <ul> <li>gulp file path: <code>gulpfile.js</code></li> <li>Advanced, gulp.js location: <code>node_modules/gulp/bin/gulp.js</code></li> </ul> </td> </tr> </table> ### Build a Node.js app [Build your Node.js app with gulp](../../ecosystems/javascript.md) ## Open source This task is open source [on GitHub](https://github.com/Microsoft/azure-pipelines-tasks). Feedback and contributions are welcome. ## Q & A <!-- BEGINSECTION class="md-qanda" --> [!INCLUDE [temp](../../includes/qa-agents.md)] ::: moniker range="< azure-devops" [!INCLUDE [temp](../../includes/qa-versions.md)] ::: moniker-end <!-- ENDSECTION --> ======================= File: docs/pipelines/build/ci-build-git.md ======================= <filename>docs/pipelines/build/ci-build-git.md<gh_stars>1-10 --- title: Building multiple branches description: Build multiple branches using Azure Pipelines or TFS ms.author: mlearned ms.topic: conceptual ms.assetid: E9684A1D-8D2B-4D5E-808A-D3677D314DB6 ms.date: 04/02/2019 monikerRange: '>=tfs-2017' --- # Build multiple branches [!INCLUDE [version-tfs-2017-rtm](../includes/version-tfs-2017-rtm.md)] ::: moniker range="<= tfs-2018" [!INCLUDE [temp](../includes/concept-rename-note.md)] ::: moniker-end You can build every commit and pull request to your Git repository using Azure Pipelines or TFS. In this tutorial, we will discuss additional considerations when building multiple branches in your Git repository. You will learn how to: > [!div class="checklist"] > * Set up a CI trigger for topic branches > * Automatically build a change in topic branch > * Exclude or include tasks for builds based on the branch being built > * Keep code quality high by building pull requests > * Use retention policies to clean up completed builds ## Prerequisites * You need a Git repository in Azure Pipelines, TFS, or GitHub with your app. If you do not have one, we recommend importing the [sample.NET Core app](https://github.com/MicrosoftDocs/pipelines-dotnet-core) into your Azure Pipelines or TFS project, or forking it into your GitHub repository. Note that you must use Azure Pipelines to build a GitHub repository. You cannot use TFS. * You also need a working build for your repository. ## Set up a CI trigger for a topic branch A common workflow with Git is to create temporary branches from your master branch. These branches are called topic or feature branches and help you isolate your work. In this workflow, you create a branch for a particular feature or bug fix. Eventually, you merge the code back to the master branch and delete the topic branch. #### [YAML](#tab/yaml/) ::: moniker range="azure-devops" Unless you specify a [trigger](../yaml-schema.md#push-trigger) in your YAML file, a change in any of the branches will trigger a build. Add the following snippet to your YAML file in the `master` branch. This will cause any changes to `master` and `feature/*` branches to be automatically built. ```yaml trigger: - master - feature/* ``` ::: moniker-end ::: moniker range="< azure-devops" YAML builds are not yet available on TFS. ::: moniker-end #### [Classic](#tab/classic/) Follow the steps below to create a CI trigger that will run a build for feature branches. 1. Select **Pipelines**, and then choose **Builds**. 2. Locate the build pipeline that services your master branch. Select **Edit**. 3. Select the **Triggers** menu for your build. Ensure you have **Continuous integration** enabled. 4. Select the **+ Add** icon under **Branch filters**. 5. Under the **Branch specification** dropdown, type `feature/*` in the **Filter my branches** text box and press **Enter**. The trigger now supports CI for all feature branches that match the wildcard as well as the master branch. > [!NOTE] > Note that the filtered list of branches may not populate as you type `*`. > You can still press **Enter** and save the branch filter. 6. Select the **Save & queue** menu and then Select **Save**. * * * ## Automatically build a change in topic branch You're now ready for CI for both the master branch and future feature branches that match the branch pattern. Every code change for the branch will use an automated build pipeline to ensure the quality of your code remains high. Follow the steps below to edit a file and create a new topic branch. 1. Navigate to your code in Azure Repos, TFS, or GitHub. 1. Create a new branch for your code that starts with `feature/`, e.g., `feature/feature-123`. 1. Make a change to your code in the feature branch and commit the change. 1. Navigate to the **Pipelines** menu in Azure Pipelines or TFS and select **Builds**. 1. Select the build pipeline for this repo. You should now see a new build executing for the topic branch. This build was initiated by the trigger you created earlier. Wait for the build to finish. Your typical development process includes developing code locally and periodically pushing to your remote topic branch. Each push you make results in a build pipeline executing in the background. The build pipeline helps you catch errors earlier and helps you to maintain a quality topic branch that can be safely merged to master. Practicing CI for your topic branches helps to minimize risk when merging back to master. ## Exclude or include tasks for builds based on the branch being built The master branch typically produces deployable artifacts such as binaries. You do not need to spend time creating and storing those artifacts for short-lived feature branches. You implement custom conditions in Azure Pipelines or TFS so that certain tasks only execute on your master branch during a build run. You can use a single build with multiple branches and skip or perform certain tasks based on conditions. #### [YAML](#tab/yaml/) Edit the `azure-pipelines.yml` file in your `master` branch, locate a task in your YAML file, and add a condition to it. For example, the following snippet adds a condition to [publish artifacts](../tasks/utility/publish-build-artifacts.md) task. ::: moniker range="azure-devops" ```yaml - task: PublishBuildArtifacts@1 condition: and(succeeded(), eq(variables['Build.SourceBranch'],'refs/heads/master')) ``` ::: moniker-end ::: moniker range="< azure-devops" YAML builds are not yet available on TFS. ::: moniker-end #### [Classic](#tab/classic/) 1. Locate the build pipeline that services your master branch. Select **Edit**. 2. Choose a task in your build pipeline. If you are following the.NET Core sample, then select the [**Publish Artifact**](../tasks/utility/publish-build-artifacts.md) task. 3. Select **Control Options** for the task on the bottom right hand part of your screen. 4. Select the dropdown for **Run this task** and choose **Custom conditions**. ![Custom condition](media/ci-build-git/customconditions.png) 5. Enter the following snippet: ``` and(succeeded(), eq(variables['Build.SourceBranch'],'refs/heads/master')) ``` 6. Select **Save & queue**. 7. Choose your **topic branch**. Select **Queue**. We are not building the master branch, and the task for **Publish artifacts** will not execute. 8. Select the build to monitor the progress. Once the build completes, confirm the build skipped the **Publish artifacts** task. * * * ## Validate pull requests Use policies to protect your branches by requiring successful builds before merging pull requests. You have options to always require a new successful build before merging changes to important branches such as the master branch. There are other branch policy settings to build less frequently. You can also require a certain number of code reviewers to help ensure your pull requests are high quality and don't result in broken builds for your branches. ### GitHub repository #### [YAML](#tab/yaml/) ::: moniker range="azure-devops" Unless you specify `pr` triggers in your YAML file, pull request builds are automatically enabled for all branches. You can specify the target branches for your pull request builds. For example, to run the build only for pull requests that target: `master` and `feature/*`: ```yaml pr: - master - feature/* ``` For more details, see [Triggers](../build/triggers.md). ::: moniker-end ::: moniker range="< azure-devops" YAML builds are not yet available on TFS. ::: moniker-end #### [Classic](#tab/classic/) 1. Navigate to your project in Azure Pipelines or TFS. Select **Pipelines**, and then select **Builds**. Locate your build, and select **Edit**. 1. Select **Triggers**. Enable the **Pull request validation** trigger. Ensure you include the **master branch** under **Branch filters**. 1. Select **Save & queue**, then select **Save**. 1. Navigate to your GitHub account. Navigate to the main page for your **repository**. 1. Select the **Branch** selector, and then type a name for a new branch and press enter. This will create a branch based on master. 1. Edit a file in your new branch. **Commit** your change to the new branch. 1. Select **Pull requests**. Select **New pull request**. 1. Create the pull request. Navigate back to your build pipeline. A build will be queued or completed for the merge commit of your pull request. * * * ### Azure Pipelines or TFS repository 1. Navigate to the **Repos** hub in Azure Repos or TFS. 1. Choose your **repository** and select **Branches**. Choose the **master branch**. 1. You will implement a branch policy to protect the master branch. Select the **ellipsis** to the right of your branch name and select **Branch policies**. 1. Choose the checkbox for **Protect this branch**. There are several options for protecting the branch. 1. Under the **Build validation** menu choose **Add build policy**. 1. Choose the appropriate build pipeline. 1. Ensure **Trigger** is set to automatic and the **Policy requirement** is set to required. 1. Enter a descriptive **Display name** to describe the policy. 1. Select **Save** to create and enable the policy. Select **Save changes** at the top left of your screen. 1. To test the policy navigate to the **Pull request** menu in Azure Pipelines or TFS. 1. Select **New pull request**. Ensure your topic branch is set to merge into your master branch. Select **create**. 1. Your screen displays the **policy** being executed. 1. Select the **policy name** to examine the build. If the build succeeds your code will be merged to master. If the build fails the merge is blocked. Once the work is completed in the topic branch and merged to master, you can delete your topic branch. You can then create additional feature or bug fix branches as necessary. ## Use retention policies to clean up your completed builds Retention policies allow you to control and automate the cleanup of your various builds. For shorter-lived branches like topic branches, you may want to retain less history to reduce clutter and storage costs. If you create CI builds on multiple related branches, it will become less important to keep builds for all of your branches. 1. Navigate to the **Pipelines** menu in Azure Pipelines or TFS. 2. Locate the build pipeline that you set up for your repo. 3. Select **Edit** at the top right of your screen. 4. Under the build pipeline name, Select the **Retention** tab. Select **Add** to add a new retention policy. ![Retention menu](media/ci-build-git/retentionpolicy.png) 5. Type **feature/*** in the **Branch specification** dropdown. This ensures any feature branches matching the wildcard will use the policy. 6. Set **Days to keep** to 1 and **Minimum to keep** to 1. 7. Select the **Save & queue** menu and then Select **Save**. Policies are evaluated in order, applying the first matching policy to each build. The default rule at the bottom matches all builds. The retention policy will clean up build resources each day. You retain at least one build at all times. You can also choose to keep any particular build for an indefinite amount of time. ## Next steps In this tutorial, you learned how to manage CI for multiple branches in your Git repositories using Azure Pipelines or TFS. You learned how to: > [!div class="checklist"] > * Set up a CI trigger for topic branches > * Automatically build a change in topic branch > * Exclude or include tasks for builds based on the branch being built > * Keep code quality high by building pull requests > * Use retention policies to clean up completed builds ======================= File: docs/integrate/previous-apis/hooks/publishers.md ======================= --- ms.technology: devops-ecosystem monikerRange: '>= tfs-2015 < azure-devops' title: Service Hook Publishers | REST API Reference for Team Foundation Server description: Work with service hook publishers programmatically using the REST APIs for Team Foundation Server. ms.assetid: F61EDE31-0F8D-4C4E-AE03-B4480C51C5FD ms.topic: article ms.author: chcomley author: chcomley ms.date: 08/04/2016 --- # Service hook publishers [!INCLUDE [azure-devops](../_data/azure-devops-message.md)] [!INCLUDE [API_version](../_data/version.md)] A publisher is a service that publishes events to service hooks. For example, Team Foundation Server is a publisher which sends code, build, work item, and other events. [!INCLUDE [GET_STARTED](../_data/get-started.md)] ## Get a list of publishers <a name="getalistofpublishers" /> #### Sample request ``` GET https://mytfsserver/DefaultCollection/_apis/hooks/publishers?api-version=1.0 ``` #### Sample response ```json { "count": 1, "value": [ { "id": "tfs", "url": "https://mytfsserver/DefaultCollection/_apis/hooks/publishers/tfs", "name": "Team Foundation Server", "description": "Publishes Team Foundation Server events", "supportedEvents": [ { "publisherId": "tfs", "id": "build.complete", "url": "https://mytfsserver/DefaultCollection/_apis/hooks/publishers/tfs/eventTypes/build.complete", "name": "Build completed", "description": "A build completes", "supportedResourceVersions": [ "1.0-preview.1" ], "inputDescriptors": [ { "id": "definitionName", "name": "Build Definition", "description": "Filter events to include only completed builds for the specified definition", "inputMode": "combo", "isConfidential": false, "useInDefaultDescription": false, "validation": { "dataType": "string" }, "values": { "defaultValue": "", "possibleValues": [ { "value": "", "displayValue": "[Any]" } ], "isLimitedToPossibleValues": true }, "hasDynamicValueInformation": true }, { "id": "buildStatus", "name": "Build Status", "description": "Filter events to include only completed builds for the specified completion status", "inputMode": "combo", "isConfidential": false, "useInDefaultDescription": false, "values": { "defaultValue": "", "possibleValues": [ { "value": "", "displayValue": "[Any]" }, { "value": "Succeeded", "displayValue": "Succeeded" }, { "value": "PartiallySucceeded", "displayValue": "Partially Succeeded" }, { "value": "Failed", "displayValue": "Failed" }, { "value": "Stopped", "displayValue": "Stopped" } ], "isLimitedToPossibleValues": true } } ] }, { "publisherId": "tfs", "id": "message.posted", "url": "https://mytfsserver/DefaultCollection/_apis/hooks/publishers/tfs/eventTypes/message.posted", "name": "Team room message posted", "description": "Triggers when a message is posted to a team room", "supportedResourceVersions": [ "1.0-preview.1" ], "inputDescriptors": [ { "id": "roomId", "name": "Team room", "description": "Filter events to include only messages sent to the specified Team room", "inputMode": "combo", "isConfidential": false, "useInDefaultDescription": false, "validation": { "dataType": "number", "isRequired": true }, "values": { "defaultValue": "", "possibleValues": [] }, "hasDynamicValueInformation": true }, { "id": "messagePattern", "name": "Message contains string", "description": "The string that must be found in the message", "inputMode": "textBox", "isConfidential": false, "useInDefaultDescription": false, "validation": { "dataType": "string", "pattern": "^[^&<>'\"]*$", "patternMismatchErrorMessage": "Value cannot contain any of characters: &, <, >,'(apostrophe), or \\\" (quote).", "maxLength": 1024 }, "values": { "defaultValue": "", "possibleValues": [] } } ] }, { "publisherId": "tfs", "id": "git.pullrequest.created", "url": "https://mytfsserver/DefaultCollection/_apis/hooks/publishers/tfs/eventTypes/git.pullrequest.created", "name": "Pull request created", "description": "Pull request is created in a git repository", "supportedResourceVersions": [ "1.0-preview.1" ], "inputDescriptors": [ { "id": "repository", "name": "Repository", "description": "The repository that code was pushed to", "inputMode": "combo", "isConfidential": false, "useInDefaultDescription": false, "validation": { "dataType": "guid" }, "values": { "possibleValues": [ { "value": "", "displayValue": "[Any]" } ], "isLimitedToPossibleValues": true }, "hasDynamicValueInformation": true }, { "id": "branch", "name": "Target branch", "description": "The target branch of the pull request", "inputMode": "combo", "isConfidential": false, "useInDefaultDescription": false, "values": { "possibleValues": [ { "value": "", "displayValue": "[Any]" } ], "isLimitedToPossibleValues": true }, "dependencyInputIds": [ "repository" ], "hasDynamicValueInformation": true } ] }, { "publisherId": "tfs", "id": "git.pullrequest.updated", "url": "https://mytfsserver/DefaultCollection/_apis/hooks/publishers/tfs/eventTypes/git.pullrequest.updated", "name": "Pull request updated", "description": "Pull request is updated – status, review list, reviewer vote changed or the source branch is updated with a push", "supportedResourceVersions": [ "1.0-preview.1" ], "inputDescriptors": [ { "id": "repository", "name": "Repository", "description": "The repository that code was pushed to", "inputMode": "combo", "isConfidential": false, "useInDefaultDescription": false, "validation": { "dataType": "guid" }, "values": { "possibleValues": [ { "value": "", "displayValue": "[Any]" } ], "isLimitedToPossibleValues": true }, "hasDynamicValueInformation": true }, { "id": "branch", "name": "Target branch", "description": "The target branch of the pull request", "inputMode": "combo", "isConfidential": false, "useInDefaultDescription": false, "values": { "possibleValues": [ { "value": "", "displayValue": "[Any]" } ], "isLimitedToPossibleValues": true }, "dependencyInputIds": [ "repository" ], "hasDynamicValueInformation": true }, { "id": "notificationType", "name": "Change", "description": "The type of pull request change", "inputMode": "combo", "isConfidential": false, "useInDefaultDescription": false, "validation": { "dataType": "string" }, "values": { "defaultValue": "", "possibleValues": [ { "value": "", "displayValue": "[Any]" }, { "value": "PushNotification", "displayValue": "Source branch updated" }, { "value": "ReviewersUpdateNotification", "displayValue": "Reviewers changed" }, { "value": "StatusUpdateNotification", "displayValue": "Status changed" }, { "value": "ReviewerVoteNotification", "displayValue": "Votes score changed" } ], "isLimitedToPossibleValues": true, "isReadOnly": true } } ] }, { "publisherId": "tfs", "id": "git.push", "url": "https://mytfsserver/DefaultCollection/_apis/hooks/publishers/tfs/eventTypes/git.push", "name": "Code pushed", "description": "Code is pushed to a git repository", "supportedResourceVersions": [ "1.0-preview.1" ], "inputDescriptors": [ { "id": "repository", "name": "Repository", "description": "The repository that code was pushed to", "inputMode": "combo", "isConfidential": false, "useInDefaultDescription": false, "validation": { "dataType": "guid" }, "values": { "possibleValues": [ { "value": "", "displayValue": "[Any]" } ], "isLimitedToPossibleValues": true }, "hasDynamicValueInformation": true }, { "id": "branch", "name": "Branch", "description": "The branch that code was pushed into", "inputMode": "combo", "isConfidential": false, "useInDefaultDescription": false, "values": { "possibleValues": [ { "value": "", "displayValue": "[Any]" } ], "isLimitedToPossibleValues": true }, "dependencyInputIds": [ "repository" ], "hasDynamicValueInformation": true } ] }, { "publisherId": "tfs", "id": "tfvc.checkin", "url": "https://mytfsserver/DefaultCollection/_apis/hooks/publishers/tfs/eventTypes/tfvc.checkin", "name": "Code checked in", "description": "A changeset is checked into version control.", "supportedResourceVersions": [ "1.0-preview.1" ], "inputDescriptors": [ { "id": "path", "name": "Under path", "description": "Filter to checkins that change one or more files under the specified path", "inputMode": "textBox", "isConfidential": false, "useInDefaultDescription": false, "validation": { "dataType": "string", "isRequired": true, "pattern": "^\\$\\/[^&<>'\"]*$" }, "values": { "defaultValue": "$/" } } ] }, { "publisherId": "tfs", "id": "workitem.created", "url": "https://mytfsserver/DefaultCollection/_apis/hooks/publishers/tfs/eventTypes/workitem.created", "name": "Work item created", "description": "Filter events to include only newly created work items.", "supportedResourceVersions": [ "1.0-preview.2", "1.0-preview.1" ], "inputDescriptors": [ { "id": "areaPath", "name": "Area path", "description": "Filter events to include only work items under the specified area path.", "inputMode": "combo", "isConfidential": false, "useInDefaultDescription": false, "validation": { "dataType": "string" }, "values": { "defaultValue": "", "possibleValues": [ { "value": "", "displayValue": "[Any]" } ], "isLimitedToPossibleValues": true, "isReadOnly": true }, "hasDynamicValueInformation": true }, { "id": "workItemType", "name": "Work item type", "description": "Filter events to include only work items of the specified type.", "inputMode": "combo", "isConfidential": false, "useInDefaultDescription": false, "validation": { "dataType": "string" }, "values": { "defaultValue": "", "possibleValues": [ { "value": "", "displayValue": "[Any]" } ], "isLimitedToPossibleValues": true, "isReadOnly": true }, "hasDynamicValueInformation": true } ] }, { "publisherId": "tfs", "id": "workitem.commented", "url": "https://mytfsserver/DefaultCollection/_apis/hooks/publishers/tfs/eventTypes/workitem.commented", "name": "Work item commented on", "description": "Filter events to include only work items commented on.", "supportedResourceVersions": [ "1.0-preview.2", "1.0-preview.1" ], "inputDescriptors": [ { "id": "areaPath", "name": "Area path", "description": "Filter events to include only work items under the specified area path.", "inputMode": "combo", "isConfidential": false, "useInDefaultDescription": false, "validation": { "dataType": "string" }, "values": { "defaultValue": "", "possibleValues": [ { "value": "", "displayValue": "[Any]" } ], "isLimitedToPossibleValues": true, "isReadOnly": true }, "hasDynamicValueInformation": true }, { "id": "workItemType", "name": "Work item type", "description": "Filter events to include only work items of the specified type.", "inputMode": "combo", "isConfidential": false, "useInDefaultDescription": false, "validation": { "dataType": "string" }, "values": { "defaultValue": "", "possibleValues": [ { "value": "", "displayValue": "[Any]" } ], "isLimitedToPossibleValues": true, "isReadOnly": true }, "hasDynamicValueInformation": true }, { "id": "commentPattern", "name": "Contains string", "description": "The string that must be found in the comment.", "inputMode": "textBox", "isConfidential": false, "useInDefaultDescription": false, "validation": { "dataType": "string", "pattern": "^\\s*[^\\s&<>'\"][^&<>'\"]*$", "patternMismatchErrorMessage": "Value should contain at least one non whitespace character and cannot contain any of characters: &, <, >,'(apostrophe), or \" (quote).", "minLength": 1, "maxLength": 1024 }, "values": { "defaultValue": "", "possibleValues": [] } } ] }, { "publisherId": "tfs", "id": "workitem.updated", "url": "https://mytfsserver/DefaultCollection/_apis/hooks/publishers/tfs/eventTypes/workitem.updated", "name": "Work item updated", "description": "Filter events to include only changed work items.", "supportedResourceVersions": [ "1.0-preview.2", "1.0-preview.1" ], "inputDescriptors": [ { "id": "areaPath", "name": "Area path", "description": "Filter events to include only work items under the specified area path.", "inputMode": "combo", "isConfidential": false, "useInDefaultDescription": false, "validation": { "dataType": "string" }, "values": { "defaultValue": "", "possibleValues": [ { "value": "", "displayValue": "[Any]" } ], "isLimitedToPossibleValues": true, "isReadOnly": true }, "hasDynamicValueInformation": true }, { "id": "workItemType", "name": "Work item type", "description": "Filter events to include only work items of the specified type.", "inputMode": "combo", "isConfidential": false, "useInDefaultDescription": false, "validation": { "dataType": "string" }, "values": { "defaultValue": "", "possibleValues": [ { "value": "", "displayValue": "[Any]" } ], "isLimitedToPossibleValues": true, "isReadOnly": true }, "hasDynamicValueInformation": true }, { "id": "changedFields", "name": "Field", "description": "Filter events to include only work items with the specified field(s) changed.", "inputMode": "combo", "isConfidential": false, "useInDefaultDescription": false, "validation": { "dataType": "string" }, "values": { "defaultValue": "", "possibleValues": [ { "value": "", "displayValue": "[Any]" } ], "isLimitedToPossibleValues": true, "isReadOnly": true }, "dependencyInputIds": [ "workItemType" ], "hasDynamicValueInformation": true } ] } ], "inputDescriptors": [ { "id": "projectId", "name": "Project", "description": "Project to restrict events to", "inputMode": "none", "isConfidential": false, "useInDefaultDescription": false, "validation": { "dataType": "guid" } }, { "id": "teamId", "name": "Team", "description": "Team that the subscription is associated with", "inputMode": "none", "isConfidential": false, "useInDefaultDescription": false, "validation": { "dataType": "guid" } } ] } ] } ``` ## Get supported events #### Sample request ``` GET https://mytfsserver/DefaultCollection/_apis/hooks/publishers/tfs/eventTypes?api-version=1.0 ``` #### Sample response ```json { "count": 9, "value": [ { "publisherId": "tfs", "id": "build.complete", "url": "https://mytfsserver/DefaultCollection/_apis/hooks/publishers/tfs/eventTypes/build.complete", "name": "Build completed", "description": "A build completes", "supportedResourceVersions": [ "1.0-preview.1" ], "inputDescriptors": [ { "id": "definitionName", "name": "Build Definition", "description": "Filter events to include only completed builds for the specified definition", "inputMode": "combo", "isConfidential": false, "useInDefaultDescription": false, "validation": { "dataType": "string" }, "values": { "defaultValue": "", "possibleValues": [ { "value": "", "displayValue": "[Any]" } ], "isLimitedToPossibleValues": true }, "hasDynamicValueInformation": true }, { "id": "buildStatus", "name": "Build Status", "description": "Filter events to include only completed builds for the specified completion status", "inputMode": "combo", "isConfidential": false, "useInDefaultDescription": false, "values": { "defaultValue": "", "possibleValues": [ { "value": "", "displayValue": "[Any]" }, { "value": "Succeeded", "displayValue": "Succeeded" }, { "value": "PartiallySucceeded", "displayValue": "Partially Succeeded" }, { "value": "Failed", "displayValue": "Failed" }, { "value": "Stopped", "displayValue": "Stopped" } ], "isLimitedToPossibleValues": true } } ] }, { "publisherId": "tfs", "id": "message.posted", "url": "https://mytfsserver/DefaultCollection/_apis/hooks/publishers/tfs/eventTypes/message.posted", "name": "Team room message posted", "description": "Triggers when a message is posted to a team room", "supportedResourceVersions": [ "1.0-preview.1" ], "inputDescriptors": [ { "id": "roomId", "name": "Team room", "description": "Filter events to include only messages sent to the specified Team room", "inputMode": "combo", "isConfidential": false, "useInDefaultDescription": false, "validation": { "dataType": "number", "isRequired": true }, "values": { "defaultValue": "", "possibleValues": [] }, "hasDynamicValueInformation": true }, { "id": "messagePattern", "name": "Message contains string", "description": "The string that must be found in the message", "inputMode": "textBox", "isConfidential": false, "useInDefaultDescription": false, "validation": { "dataType": "string", "pattern": "^[^&<>'\"]*$", "patternMismatchErrorMessage": "Value cannot contain any of characters: &, <, >,'(apostrophe), or \\\" (quote).", "maxLength": 1024 }, "values": { "defaultValue": "", "possibleValues": [] } } ] }, { "publisherId": "tfs", "id": "git.pullrequest.created", "url": "https://mytfsserver/DefaultCollection/_apis/hooks/publishers/tfs/eventTypes/git.pullrequest.created", "name": "Pull request created", "description": "Pull request is created in a git repository", "supportedResourceVersions": [ "1.0-preview.1" ], "inputDescriptors": [ { "id": "repository", "name": "Repository", "description": "The repository that code was pushed to", "inputMode": "combo", "isConfidential": false, "useInDefaultDescription": false, "validation": { "dataType": "guid" }, "values": { "possibleValues": [ { "value": "", "displayValue": "[Any]" } ], "isLimitedToPossibleValues": true }, "hasDynamicValueInformation": true }, { "id": "branch", "name": "Target branch", "description": "The target branch of the pull request", "inputMode": "combo", "isConfidential": false, "useInDefaultDescription": false, "values": { "possibleValues": [ { "value": "", "displayValue": "[Any]" } ], "isLimitedToPossibleValues": true }, "dependencyInputIds": [ "repository" ], "hasDynamicValueInformation": true } ] }, { "publisherId": "tfs", "id": "git.pullrequest.updated", "url": "https://mytfsserver/DefaultCollection/_apis/hooks/publishers/tfs/eventTypes/git.pullrequest.updated", "name": "Pull request updated", "description": "Pull request is updated – status, review list, reviewer vote changed or the source branch is updated with a push", "supportedResourceVersions": [ "1.0-preview.1" ], "inputDescriptors": [ { "id": "repository", "name": "Repository", "description": "The repository that code was pushed to", "inputMode": "combo", "isConfidential": false, "useInDefaultDescription": false, "validation": { "dataType": "guid" }, "values": { "possibleValues": [ { "value": "", "displayValue": "[Any]" } ], "isLimitedToPossibleValues": true }, "hasDynamicValueInformation": true }, { "id": "branch", "name": "Target branch", "description": "The target branch of the pull request", "inputMode": "combo", "isConfidential": false, "useInDefaultDescription": false, "values": { "possibleValues": [ { "value": "", "displayValue": "[Any]" } ], "isLimitedToPossibleValues": true }, "dependencyInputIds": [ "repository" ], "hasDynamicValueInformation": true }, { "id": "notificationType", "name": "Change", "description": "The type of pull request change", "inputMode": "combo", "isConfidential": false, "useInDefaultDescription": false, "validation": { "dataType": "string" }, "values": { "defaultValue": "", "possibleValues": [ { "value": "", "displayValue": "[Any]" }, { "value": "PushNotification", "displayValue": "Source branch updated" }, { "value": "ReviewersUpdateNotification", "displayValue": "Reviewers changed" }, { "value": "StatusUpdateNotification", "displayValue": "Status changed" }, { "value": "ReviewerVoteNotification", "displayValue": "Votes score changed" } ], "isLimitedToPossibleValues": true, "isReadOnly": true } } ] }, { "publisherId": "tfs", "id": "git.push", "url": "https://mytfsserver/DefaultCollection/_apis/hooks/publishers/tfs/eventTypes/git.push", "name": "Code pushed", "description": "Code is pushed to a git repository", "supportedResourceVersions": [ "1.0-preview.1" ], "inputDescriptors": [ { "id": "repository", "name": "Repository", "description": "The repository that code was pushed to", "inputMode": "combo", "isConfidential": false, "useInDefaultDescription": false, "validation": { "dataType": "guid" }, "values": { "possibleValues": [ { "value": "", "displayValue": "[Any]" } ], "isLimitedToPossibleValues": true }, "hasDynamicValueInformation": true }, { "id": "branch", "name": "Branch", "description": "The branch that code was pushed into", "inputMode": "combo", "isConfidential": false, "useInDefaultDescription": false, "values": { "possibleValues": [ { "value": "", "displayValue": "[Any]" } ], "isLimitedToPossibleValues": true }, "dependencyInputIds": [ "repository" ], "hasDynamicValueInformation": true } ] }, { "publisherId": "tfs", "id": "tfvc.checkin", "url": "https://mytfsserver/DefaultCollection/_apis/hooks/publishers/tfs/eventTypes/tfvc.checkin", "name": "Code checked in", "description": "A changeset is checked into version control.", "supportedResourceVersions": [ "1.0-preview.1" ], "inputDescriptors": [ { "id": "path", "name": "Under path", "description": "Filter to checkins that change one or more files under the specified path", "inputMode": "textBox", "isConfidential": false, "useInDefaultDescription": false, "validation": { "dataType": "string", "isRequired": true, "pattern": "^\\$\\/[^&<>'\"]*$" }, "values": { "defaultValue": "$/" } } ] }, { "publisherId": "tfs", "id": "workitem.created", "url": "https://mytfsserver/DefaultCollection/_apis/hooks/publishers/tfs/eventTypes/workitem.created", "name": "Work item created", "description": "Filter events to include only newly created work items.", "supportedResourceVersions": [ "1.0-preview.2", "1.0-preview.1" ], "inputDescriptors": [ { "id": "areaPath", "name": "Area path", "description": "Filter events to include only work items under the specified area path.", "inputMode": "combo", "isConfidential": false, "useInDefaultDescription": false, "validation": { "dataType": "string" }, "values": { "defaultValue": "", "possibleValues": [ { "value": "", "displayValue": "[Any]" } ], "isLimitedToPossibleValues": true, "isReadOnly": true }, "hasDynamicValueInformation": true }, { "id": "workItemType", "name": "Work item type", "description": "Filter events to include only work items of the specified type.", "inputMode": "combo", "isConfidential": false, "useInDefaultDescription": false, "validation": { "dataType": "string" }, "values": { "defaultValue": "", "possibleValues": [ { "value": "", "displayValue": "[Any]" } ], "isLimitedToPossibleValues": true, "isReadOnly": true }, "hasDynamicValueInformation": true } ] }, { "publisherId": "tfs", "id": "workitem.commented", "url": "https://mytfsserver/DefaultCollection/_apis/hooks/publishers/tfs/eventTypes/workitem.commented", "name": "Work item commented on", "description": "Filter events to include only work items commented on.", "supportedResourceVersions": [ "1.0-preview.2", "1.0-preview.1" ], "inputDescriptors": [ { "id": "areaPath", "name": "Area path", "description": "Filter events to include only work items under the specified area path.", "inputMode": "combo", "isConfidential": false, "useInDefaultDescription": false, "validation": { "dataType": "string" }, "values": { "defaultValue": "", "possibleValues": [ { "value": "", "displayValue": "[Any]" } ], "isLimitedToPossibleValues": true, "isReadOnly": true }, "hasDynamicValueInformation": true }, { "id": "workItemType", "name": "Work item type", "description": "Filter events to include only work items of the specified type.", "inputMode": "combo", "isConfidential": false, "useInDefaultDescription": false, "validation": { "dataType": "string" }, "values": { "defaultValue": "", "possibleValues": [ { "value": "", "displayValue": "[Any]" } ], "isLimitedToPossibleValues": true, "isReadOnly": true }, "hasDynamicValueInformation": true }, { "id": "commentPattern", "name": "Contains string", "description": "The string that must be found in the comment.", "inputMode": "textBox", "isConfidential": false, "useInDefaultDescription": false, "validation": { "dataType": "string", "pattern": "^\\s*[^\\s&<>'\"][^&<>'\"]*$", "patternMismatchErrorMessage": "Value should contain at least one non whitespace character and cannot contain any of characters: &, <, >,'(apostrophe), or \" (quote).", "minLength": 1, "maxLength": 1024 }, "values": { "defaultValue": "", "possibleValues": [] } } ] }, { "publisherId": "tfs", "id": "workitem.updated", "url": "https://mytfsserver/DefaultCollection/_apis/hooks/publishers/tfs/eventTypes/workitem.updated", "name": "Work item updated", "description": "Filter events to include only changed work items.", "supportedResourceVersions": [ "1.0-preview.2", "1.0-preview.1" ], "inputDescriptors": [ { "id": "areaPath", "name": "Area path", "description": "Filter events to include only work items under the specified area path.", "inputMode": "combo", "isConfidential": false, "useInDefaultDescription": false, "validation": { "dataType": "string" }, "values": { "defaultValue": "", "possibleValues": [ { "value": "", "displayValue": "[Any]" } ], "isLimitedToPossibleValues": true, "isReadOnly": true }, "hasDynamicValueInformation": true }, { "id": "workItemType", "name": "Work item type", "description": "Filter events to include only work items of the specified type.", "inputMode": "combo", "isConfidential": false, "useInDefaultDescription": false, "validation": { "dataType": "string" }, "values": { "defaultValue": "", "possibleValues": [ { "value": "", "displayValue": "[Any]" } ], "isLimitedToPossibleValues": true, "isReadOnly": true }, "hasDynamicValueInformation": true }, { "id": "changedFields", "name": "Field", "description": "Filter events to include only work items with the specified field(s) changed.", "inputMode": "combo", "isConfidential": false, "useInDefaultDescription": false, "validation": { "dataType": "string" }, "values": { "defaultValue": "", "possibleValues": [ { "value": "", "displayValue": "[Any]" } ], "isLimitedToPossibleValues": true, "isReadOnly": true }, "dependencyInputIds": [ "workItemType" ], "hasDynamicValueInformation": true } ] } ] } ``` ======================= File: docs/boards/backlogs/filter-backlogs.md ======================= --- title: Filter backlogs and queries titleSuffix: Azure Boards description: Filter a backlog or query based on keywords, tags, or other fields ms.custom: "boards-backlogs, seodec18" ms.technology: devops-agile ms.assetid: ms.author: kaelli author: KathrynEE ms.topic: conceptual monikerRange: '>= tfs-2013' ms.date: 10/16/2019 --- # Filter backlogs or queries based on keywords, tags, or other fields [!INCLUDE [temp](../includes/version-vsts-tfs-all-versions.md)] <a id="filter"></a> If you have many items listed in your product or portfolio backlog&mdash;and you want to focus on a subset of them&mdash;you can filter the set. ::: moniker range=">= azure-devops-2019" ## Filter based on keywords or fields You can filter work items by typing a keyword or using one or more of the fields provided, such as work item type, assigned to, state, and tags. Based on the keyword that you enter, the filter function will list work items based on any visible/displayed column or field, including tags. Also, you can enter a value for an ID, whether or not the ID field is visible. To show the filter toolbar, choose the![ ](../../media/icons/filter-icon.png) filter icon, or enter the **Ctrl+Shift+f** keyboard shortcut. You can filter all backlogs, boards, and query results. > [!div class="mx-imgBorder"] >![Filter by keyword](media/filter/filter-s144.png) Choose one or more values from the multi-select drop-down menu for each field. The values for these fields are populated as follows: - **Assigned To**: All users who are currently assigned to work items on the board plus Unassigned - **Iteration**: All Iteration Paths [selected for the current team](../sprints/define-sprints.md) and for which there are work items assigned to that iteration - **Work item type**: Work item types defined for the Requirements Category (product backlog) or Features or Epic categories (feature or epic portfolio backlogs), subject to work items being assigned to the work item types - **Tags**: All tags assigned to work items on the board - **Parent Work Items**: All features defined for the team, or all epics defined for the team when viewing the Features board (The Parent Work Items field doesn't appear when viewing the Epic or top-level Kanban board) > [!NOTE] > Filter options are dependent on the work items that meet the filter criteria. For example, if you don't have any work items assigned to Sprint 4, then the Sprint 4 option won't appear in the filter options for the Iteration Path. Here we show a filtered backlog based on the keyword "issues". Filtered pages show the![ ](../../media/icons/filtered.png) filtered icon. The filtered set is always a flat list, even if you've selected to show a hierarchical backlog view. > [!div class="mx-imgBorder"] >![Filter by keyword](media/filter/filter-issues-keyword.png) To clear and dismiss filtering, choose the![ ](../../media/icons/close-filter.png) close filter icon. ::: moniker-end ::: moniker range="tfs-2018" ## Filter based on keywords or fields You can filter work items by typing a keyword or using one or more of the fields provided, such as work item type, assigned to, state, and tags. Based on the keyword that you enter, the filter function will list work items based on any visible/displayed column or field, including tags. Also, you can enter a value for an ID, whether or not the ID field is visible. To show the filter toolbar, choose the![ ](../../media/icons/filter-icon.png) filter icon, or enter the **Ctrl+Shift+f** keyboard shortcut. You can filter all backlogs, boards, and query results. ![Backlogs, turn filtering on](media/filter-backlogs-options.png) The filtered set is always a flat list, even if you've selected to show parents. ::: moniker-end ::: moniker range="<= tfs-2017" ## Filter based on keywords You can use keywords to filter your backlogs or queries. The filter function lists those work items based on any visible/displayed column or field, including tags, based on the keyword that you enter. Also, you can enter a value for an ID, whether or not the ID field is visible. Here, we filter the backlog to only show items that include 'Web' in any one of the displayed column fields. <img src="media/cyb-filter-backlog.png" alt="Apply text filter" style="border: 1px solid #C3C3C3;" /> The filtered set is always a flat list, even if you've selected to show parents. ## Filter based on tags If you've [added tags to your work items](../queries/add-tags-to-work-items.md), you can filter your backlogs, Kanban boards, and query results using the![tag filter icon](../media/icons/tag_filter_icon.png) tag filter. For backlogs and query results, add Tags as a column option prior to filtering on tags. To learn more about filtering using tags, see [Add tags to work items to categorize and filter lists and boards, Filter lists using tags](../queries/add-tags-to-work-items.md#filter). ::: moniker-end ## Characters ignored by keyword filter criteria ::: moniker range=">= azure-devops-2019" The filter criteria ignores the following characters: `,` (comma), `.` (period), `/` (forward slash), and `\` (back slash). ::: moniker-end ::: moniker range=">= tfs-2017 <= tfs-2018" The filter criteria ignores the following characters when the field value starts with the character: ```{, (, [,!, @, #, $, %, ^, &, *, ~, `, ', "```. ::: moniker-end ## Related articles - [Tags](../queries/add-tags-to-work-items.md) - [Set column options](set-column-options.md) - [Keyboard shortcuts](../../project/navigation/keyboard-shortcuts.md) ======================= File: docs/integrate/previous-apis/policy/types.md ======================= --- ms.technology: devops-ecosystem monikerRange: '>= tfs-2015 < azure-devops' title: Policy Types | REST API Reference for Team Foundation Server description: Work with policy types programmatically using the REST APIs for Team Foundation Server. ms.assetid: c7025882-81ca-4d4a-a879-416560546992 ms.topic: article ms.author: chcomley author: chcomley ms.date: 08/04/2016 --- # Policy types [!INCLUDE [azure-devops](../_data/azure-devops-message.md)] [!INCLUDE [API_version](../_data/version2-preview1.md)] [!INCLUDE [disclaimer](../_data/disclaimer.md)] [!INCLUDE [GET_STARTED](../_data/get-started.md)] ## Get a list of policy types ```no-highlight GET https://{instance}/defaultcollection/{project}/_apis/policy/types?api-version={version} ``` | Parameter | Type | Notes |:--------------|:-------|:---------------------------------------------------------------------------------------------------------------------------- | URL | instance | string | TFS server name ({server:port}). | project | string | The name or ID of the project. | Query | api-version | string | [Version](../../concepts/rest-api-versioning.md) of the API to use. #### Sample request ``` GET https://mytfsserver/DefaultCollection/fabrikam-fiber-git/_apis/policy/types?api-version=2.0-preview ``` #### Sample response ```json { "count": 4, "value": [ { "description": "This policy will require a successful build has been performed before updating protected refs.", "_links": { "self": { "href": "https://mytfsserver/DefaultCollection/1be3fc5b-c58c-4173-8fd7-6647d11eccd1/_apis/policy/types/0609b952-1397-4640-95ec-e00a01b2c241" } }, "id": "0609b952-1397-4640-95ec-e00a01b2c241", "url": "https://mytfsserver/DefaultCollection/1be3fc5b-c58c-4173-8fd7-6647d11eccd1/_apis/policy/types/0609b952-1397-4640-95ec-e00a01b2c241", "displayName": "Build" }, { "description": "This policy will reject pushes to a repository for files which exceed the specified size.", "_links": { "self": { "href": "https://mytfsserver/DefaultCollection/1be3fc5b-c58c-4173-8fd7-6647d11eccd1/_apis/policy/types/2e26e725-8201-4edd-8bf5-978563c34a80" } }, "id": "2e26e725-8201-4edd-8bf5-978563c34a80", "url": "https://mytfsserver/DefaultCollection/1be3fc5b-c58c-4173-8fd7-6647d11eccd1/_apis/policy/types/2e26e725-8201-4edd-8bf5-978563c34a80", "displayName": "File size restriction" }, { "description": "This policy will ensure that required reviewers are added for files with certain extensions.", "_links": { "self": { "href": "https://mytfsserver/DefaultCollection/1be3fc5b-c58c-4173-8fd7-6647d11eccd1/_apis/policy/types/fd2167ab-b0be-447a-8ec8-39368250530e" } }, "id": "fd2167ab-b0be-447a-8ec8-39368250530e", "url": "https://mytfsserver/DefaultCollection/1be3fc5b-c58c-4173-8fd7-6647d11eccd1/_apis/policy/types/fd2167ab-b0be-447a-8ec8-39368250530e", "displayName": "Required reviewers" }, { "description": "This policy will ensure that a minimum number of reviewers have approved a pull request before completion.", "_links": { "self": { "href": "https://mytfsserver/DefaultCollection/1be3fc5b-c58c-4173-8fd7-6647d11eccd1/_apis/policy/types/fa4e907d-c16b-4a4c-9dfa-4906e5d171dd" } }, "id": "fa4e907d-c16b-4a4c-9dfa-4906e5d171dd", "url": "https://mytfsserver/DefaultCollection/1be3fc5b-c58c-4173-8fd7-6647d11eccd1/_apis/policy/types/fa4e907d-c16b-4a4c-9dfa-4906e5d171dd", "displayName": "Minimum approval count" } ] } ``` ## Get a policy type ```no-highlight GET https://{instance}/defaultcollection/{project}/_apis/policy/types/{id}?api-version={version} ``` | Parameter | Type | Notes |:--------------|:-------|:---------------------------------------------------------------------------------------------------------------------------- | URL | instance | string | TFS server name ({server:port}). | project | string | The name or ID of the project. | id | guid | The ID of the policy type. | Query | api-version | string | [Version](../../concepts/rest-api-versioning.md) of the API to use. #### Sample request ``` GET https://mytfsserver/DefaultCollection/fabrikam-fiber-git/_apis/policy/types/0609b952-1397-4640-95ec-e00a01b2c241?api-version=2.0-preview ``` #### Sample response ```json { "description": "This policy will require a successful build has been performed before updating protected refs.", "_links": { "self": { "href": "https://mytfsserver/DefaultCollection/1be3fc5b-c58c-4173-8fd7-6647d11eccd1/_apis/policy/types/0609b952-1397-4640-95ec-e00a01b2c241" } }, "id": "0609b952-1397-4640-95ec-e00a01b2c241", "url": "https://mytfsserver/DefaultCollection/1be3fc5b-c58c-4173-8fd7-6647d11eccd1/_apis/policy/types/0609b952-1397-4640-95ec-e00a01b2c241", "displayName": "Build" } ``` ======================= File: docs/includes/sign-up-msft-account.md ======================= <reponame>Chibuikekenneth/azure-devops-docs --- ms.topic: include --- ## Sign up with a personal Microsoft account 1. Select the sign-up link for [Azure DevOps](https://azure.microsoft.com/services/devops/). 2. Enter your email address, phone number, or Skype ID for your Microsoft account. If you're a Visual Studio subscriber and you get Azure DevOps as a benefit, use the Microsoft account associated with your subscription. Select **Next**. ![Sign in with your Microsoft account](/azure/devops/media/sign-in-with-microsoft-account.png) If you don't have a Microsoft account, choose **Create one**. To learn more, see [create a Microsoft account](https://support.microsoft.com/help/4026324/microsoft-account-how-to-create). 3. Enter your password and select **Sign in**. ![Enter your password and sign in](/azure/devops/media/enter-password-sign-in.png) 4. To get started with Azure DevOps, select **Continue**. ![Choose Continue to sign up for Azure DevOps](/azure/devops/media/sign-up-azure-devops.png) An organization is created based on the account you used to sign in. Sign in to your organization at any time, (`https://dev.azure.com/{yourorganization}`). You can rename and delete your organization, or change the organization location. To learn more, see the following articles: - [Rename an organization](/azure/devops/organizations/accounts/rename-organization) - [Change the location of your organization](/azure/devops/organizations/accounts/change-organization-location) If you signed in with an existing Microsoft account, your next step is to [Create a project](/azure/devops/user-guide/sign-up-invite-teammates#CreateProject). If you signed in with a newly created Microsoft account, then your project is automatically created and named after your account name. To learn more about managing projects, see [Manage projects](/azure/devops/organizations/projects/about-projects). ======================= File: docs/extend/reference/client/api/TFS/DistributedTask/Contracts/TaskLogReference.md ======================= <reponame>Chibuikekenneth/azure-devops-docs<gh_stars>1-10 --- title: TFS/DistributedTask/Contracts TaskLogReference API | Extensions for Azure DevOps Services description: Data representation of a task log reference. ms.assetid: 0b4c7761-25e7-8ed0-d761-aa925b5f278e ms.technology: devops-ecosystem generated: true author: chcomley ms.topic: article ms.author: chcomley ms.date: 08/04/2016 --- # TaskLogReference Module path: `TFS/DistributedTask/Contracts` ### Members * `id`: number. * `location`: string. ======================= File: docs/extend/reference/client/api/TFS/DistributedTask/Contracts/TaskSourceDefinition.md ======================= --- title: TFS/DistributedTask/Contracts TaskSourceDefinition API | Extensions for Azure DevOps Services description: Data representation of task source definition. ms.assetid: 17238a00-5073-870d-dd5b-4222ba9a7cca ms.technology: devops-ecosystem generated: true author: chcomley ms.topic: article ms.author: chcomley ms.date: 08/04/2016 --- # TaskSourceDefinition Module path: `TFS/DistributedTask/Contracts` ### Members * `authKey`: string. * `endpoint`: string. * `keySelector`: string. * `selector`: string. * `target`: string. ======================= File: docs/boards/includes/faq-milestone-marker.md ======================= <reponame>Chibuikekenneth/azure-devops-docs<filename>docs/boards/includes/faq-milestone-marker.md --- ms.technology: devops-agile ms.manager: mijacobs ms.author: kaelli author: KathrynEE ms.topic: include ms.date: 02/21/2020 --- <a id="milestone" /> ### Q: How to mark a task or work item as a milestone task? **A:** Milestone markers aren't used in Azure Boards work tracking, except for Delivery Plans. Delivery Plans provide a calendar view and allow you to define a milestone marker. For more information, see [Review team Delivery Plans](/azure/devops/boards/plans/review-team-plans). However, you can use one or more of the following options to mark a work item as a milestone: - Simply prepend or append the word **Milestone** in the title of your work item - [Add a work item tag](/azure/devops/boards/queries/add-tags-to-work-items) labeled **Milestone** - [Add a custom field](/azure/devops/organizations/settings/work/customize-process-field) labeled **Milestone** and populate it with a pick list of milestones - [Link work items](/azure/devops/boards/backlogs/add-link) using the Predecessor/Successor or Related link type to a milestone work item - [Assign the milestone work item to the sprint](/azure/devops/boards/sprints/assign-work-sprint) in which it's targeted for completion. ======================= File: docs/extend/reference/client/api/TFS/WorkItemTracking/Contracts/WorkItemDelete.md ======================= --- title: TFS/WorkItemTracking/Contracts WorkItemDelete API | Extensions for Azure DevOps Services ms.assetid: e24515e5-0ddc-4a77-3bf4-7837de8ed752 ms.technology: devops-ecosystem generated: true author: chcomley ms.topic: article ms.author: chcomley ms.date: 08/04/2016 --- # WorkItemDelete Module path: `TFS/WorkItemTracking/Contracts` Extends: [WorkItemDeleteReference](../../../TFS/WorkItemTracking/Contracts/WorkItemDeleteReference.md) ### Members * `resource`: [WorkItem](../../../TFS/WorkItemTracking/Contracts/WorkItem.md). ======================= File: docs/integrate/previous-apis/chat/users.md ======================= <gh_stars>1-10 --- ms.technology: devops-ecosystem monikerRange: '>= tfs-2015 < azure-devops' title: Team Room Users | REST API Reference for Team Foundation Server description: Work with users in team rooms programmatically using the REST APIs for Team Foundation Server. ms.assetid: 6452FEDA-E518-4983-B37B-C50BB17E0047 ms.topic: article ms.author: chcomley author: chcomley ms.date: 08/04/2016 --- # Team room users [!INCLUDE [azure-devops](../_data/azure-devops-message.md)] [!INCLUDE [API_version](../_data/version.md)] [!INCLUDE [GET_STARTED](../_data/get-started.md)] ## Get a list of users ```no-highlight GET https://{instance}/DefaultCollection/_apis/chat/rooms/{roomId}/users?api-version={version} ``` | Parameter | Type | Notes |:------------|:-------|:------------------------------------------------------------------------------------------------------------- | URL | instance | string | TFS server name ({server:port}). | roomId | int | ID of the team room. | Query | api-version | string | [Version](../../concepts/rest-api-versioning.md) of the API to use. #### Sample request ``` GET https://mytfsserver/DefaultCollection/_apis/chat/rooms/305/users?api-version=1.0 ``` #### Sample response ```json { "count": 6, "value": [ { "roomId": 305, "user": { "id": "d6245f20-2af8-44f4-9451-8107cb2767db", "displayName": "<NAME>", "url": "https://mytfsserver/DefaultCollection/_apis/Identities/d6245f20-2af8-44f4-9451-8107cb2767db", "imageUrl": "https://mytfsserver/DefaultCollection/_api/_common/identityImage?id=d6245f20-2af8-44f4-9451-8107cb2767db" }, "lastActivity": "2014-10-27T16:36:02.28Z", "joinedDate": "2014-10-27T16:36:02.203Z", "isOnline": true }, { "roomId": 305, "user": { "id": "3b5f0c34-4aec-4bf4-8708-1d36f0dbc468", "displayName": "<NAME>", "url": "https://mytfsserver/DefaultCollection/_apis/Identities/3b5f0c34-4aec-4bf4-8708-1d36f0dbc468", "imageUrl": "https://mytfsserver/DefaultCollection/_api/_common/identityImage?id=3b5f0c34-4aec-4bf4-8708-1d36f0dbc468" }, "lastActivity": "0001-01-01T00:00:00", "joinedDate": "0001-01-01T00:00:00", "isOnline": false }, { "roomId": 305, "user": { "id": "8c8c7d32-6b1b-47f4-b2e9-30b477b5ab3d", "displayName": "<NAME>", "url": "https://mytfsserver/DefaultCollection/_apis/Identities/8c8c7d32-6b1b-47f4-b2e9-30b477b5ab3d", "imageUrl": "https://mytfsserver/DefaultCollection/_api/_common/identityImage?id=8c8c7d32-6b1b-47f4-b2e9-30b477b5ab3d" }, "lastActivity": "0001-01-01T00:00:00", "joinedDate": "0001-01-01T00:00:00", "isOnline": false }, { "roomId": 305, "user": { "id": "e5a5f7f8-6507-4c34-b397-6c4818e002f4", "displayName": "<NAME>", "url": "https://mytfsserver/DefaultCollection/_apis/Identities/e5a5f7f8-6507-4c34-b397-6c4818e002f4", "imageUrl": "https://mytfsserver/DefaultCollection/_api/_common/identityImage?id=e5a5f7f8-6507-4c34-b397-6c4818e002f4" }, "lastActivity": "0001-01-01T00:00:00", "joinedDate": "0001-01-01T00:00:00", "isOnline": false }, { "roomId": 305, "user": { "id": "19d9411e-9a34-45bb-b985-d24d9d87c0c9", "displayName": "<NAME>", "url": "https://mytfsserver/DefaultCollection/_apis/Identities/19d9411e-9a34-45bb-b985-d24d9d87c0c9", "imageUrl": "https://mytfsserver/DefaultCollection/_api/_common/identityImage?id=19d9411e-9a34-45bb-b985-d24d9d87c0c9" }, "lastActivity": "0001-01-01T00:00:00", "joinedDate": "0001-01-01T00:00:00", "isOnline": false }, { "roomId": 305, "user": { "id": "d291b0c4-a05c-4ea6-8df1-4b41d5f39eff", "displayName": "<NAME>", "url": "https://mytfsserver/DefaultCollection/_apis/Identities/d291b0c4-a05c-4ea6-8df1-4b41d5f39eff", "imageUrl": "https://mytfsserver/DefaultCollection/_api/_common/identityImage?id=d291b0c4-a05c-4ea6-8df1-4b41d5f39eff" }, "lastActivity": "0001-01-01T00:00:00", "joinedDate": "0001-01-01T00:00:00", "isOnline": false } ] } ``` ## Get a user ```no-highlight GET https://{instance}/DefaultCollection/_apis/chat/rooms/{roomId}/users/{userId}?api-version={version} ``` | Parameter | Type | Notes |:------------|:-------|:------------------------------------------------------------------------------------------------------------- | URL | instance | string | TFS server name ({server:port}). | roomId | int | ID of the team room. | userId | int | ID of the user. | Query | api-version | string | [Version](../../concepts/rest-api-versioning.md) of the API to use. #### Sample request ``` GET https://mytfsserver/DefaultCollection/_apis/chat/rooms/305/users/d6245f20-2af8-44f4-9451-8107cb2767db?api-version=1.0 ``` #### Sample response ```json { "roomId": 305, "user": { "id": "d6245f20-2af8-44f4-9451-8107cb2767db", "displayName": "<NAME>", "url": "https://mytfsserver/DefaultCollection/_apis/Identities/d6245f20-2af8-44f4-9451-8107cb2767db", "imageUrl": "https://mytfsserver/DefaultCollection/_api/_common/identityImage?id=d6245f20-2af8-44f4-9451-8107cb2767db" }, "lastActivity": "2014-10-27T16:36:02.28Z", "joinedDate": "2014-10-27T16:36:02.203Z", "isOnline": true } ``` ## Join a room <a name="joinaroom" /> ```no-highlight PUT https://{instance}/DefaultCollection/_apis/chat/rooms/{roomId}/users/{userId}?api-version={version} ``` ```http Content-Type: application/json ``` ```json { userId: {int} } ``` | Parameter | Type | Notes |:------------|:-------|:------------------------------------------------------------------------------------------------------------- | URL | instance | string | TFS server name ({server:port}). | roomId | int | ID of the team room. | userId | int | ID of the user. | Query | api-version | string | [Version](../../concepts/rest-api-versioning.md) of the API to use. #### Sample request ``` PUT https://mytfsserver/DefaultCollection/_apis/chat/rooms/305/users/d6245f20-2af8-44f4-9451-8107cb2767db?api-version=1.0 ``` ```json { "userId": "d6245f20-2af8-44f4-9451-8107cb2767db" } ``` ## Leave a room ```no-highlight DELETE https://{instance}/DefaultCollection/_apis/chat/rooms/{roomId}/users/{userId}?api-version={version} ``` | Parameter | Type | Notes |:------------|:-------|:------------------------------------------------------------------------------------------------------------- | URL | instance | string | TFS server name ({server:port}). | roomId | int | ID of the team room. | userId | int | ID of the user. | Query | api-version | string | [Version](../../concepts/rest-api-versioning.md) of the API to use. #### Sample request ``` DELETE https://mytfsserver/DefaultCollection/_apis/chat/rooms/305/users/d6245f20-2af8-44f4-9451-8107cb2767db?api-version=1.0 ``` ======================= File: docs/repos/tfvc/administering-team-foundation-version-control.md ======================= --- title: Administering Team Foundation Version Control titleSuffix: Azure Repos description: Administering Team Foundation Version Control ms.assetid: 0d96b6d2-f00a-4d28-98b9-83fe75cde284 ms.technology: devops-code-tfvc ms.author: apawast author: apawast ms.topic: conceptual ms.date: 08/10/2016 monikerRange: '>= tfs-2015' --- # Administering Team Foundation Version Control #### Azure Repos | Azure DevOps Server 2019 | TFS 2018 | TFS 2017 | TFS 2015 | VS 2017 | VS 2015 | VS 2013 Topics in this section describe how to complete common administrative version control tasks using Team Foundation. ## In This Section [Configure Check-Out Settings](configure-check-out-settings.md) Explains how to configure source control check-out settings. [Managing File Types](/azure/devops/server/admin/manage-file-types) Describes how to add, edit, and remove file type extensions associated with Team Foundation version control check-ins. [Set and Enforce Quality Gates](set-enforce-quality-gates.md) Describes the purpose of check-in policies and notes, and how to customize them. [Control Access to Team Foundation Version Control](control-access-team-foundation-version-control.md) Explains the steps required to add users and groups to Team Foundation version control. [Remove Access to Version Control Files](remove-access-version-control-files.md) Describes how to remove access to a file under version control. [Undo Changes in Another User's Workspace](undo-changes-another-user-workspace.md) Describes how to undo pending changes in another user's workspace. [Clean Up Files When Users Leave](clean-up-files-when-users-leave.md) Explains how to dispose of obsolete files. [Destroy Version Controlled Files](destroy-version-controlled-files.md) Describes how to destroy files and folders. [Migrate from Visual SourceSafe](https://msdn.microsoft.com/library/ms253060) Explains how to use the Team Foundation VSSConverter command-line tool to migrate projects, files, version history, labels, and user information from your Microsoft Visual SourceSafe 2005 database to Team Foundation version control. ## Reference [Tf Command-Line Utility Commands](https://msdn.microsoft.com/library/z51z7zy0) ======================= File: docs/integrate/previous-apis/git/refs.md ======================= <gh_stars>1-10 --- ms.technology: devops-ecosystem monikerRange: '>= tfs-2015 < azure-devops' title: Git Refs | REST API Reference for Team Foundation Server description: Work with Git references programmatically using the REST APIs for Team Foundation Server. ms.assetid: 7E4F1631-12C0-4B17-A460-6A6BE002C838 ms.topic: article ms.author: chcomley author: chcomley ms.date: 08/04/2016 --- # Git refs [!INCLUDE [azure-devops](../_data/azure-devops-message.md)] [!INCLUDE [API_version](../_data/version.md)] [!INCLUDE [GET_STARTED](../_data/get-started.md)] Refs are named references to Git objects. The most common type of ref is a branch. A branch is a ref that points to a commit. There are [code samples](https://github.com/microsoft/azure-devops-dotnet-samples/blob/master/ClientLibrary/Samples/Git/RefsSample.cs) available for this endpoint. ## Get a list of references ```no-highlight GET https://{instance}/DefaultCollection/{project}/_apis/repos/git/repositories/{repository}/refs[/{filter}]?api-version={version}[&includeStatuses={bool}] ``` | Parameter | Type | Notes |:----------- |:-------|:---------------------------------------------------------------------------------------------------------------------------- | URL | instance | string | TFS server name ({server:port}). | project | string | ID or name of the [project](../tfs/projects.md). *Optional if specifying an ID for repository.* | repository | string | ID or name of the [repository](./repositories.md). | filter | string | Git ref name filter. If you specify this parameter, only refs that start with that string are returned. | Query | api-version | string | [Version](../../concepts/rest-api-versioning.md) of the API to use. |includeStatuses | bool | If `true`, gets the status of each ref. If `false`, doesn't get the status of any ref. [!INCLUDE [ID_vs_Name](_data/id_or_name.md)] #### Sample request ``` GET https://mytfsserver/DefaultCollection/_apis/git/repositories/278d5cd2-584d-4b63-824a-2ba458937249/refs?api-version=1.0 ``` #### Sample response ```json { "count": 6, "value": [ { "name": "refs/heads/develop", "objectId": "67cae2b029dff7eb3dc062b49403aaedca5bad8d", "url": "https://mytfsserver/DefaultCollection/_apis/git/repositories/278d5cd2-584d-4b63-824a-2ba458937249/refs/heads/develop" }, { "name": "refs/heads/master", "objectId": "23d0bc5b128a10056dc68afece360d8a0fabb014", "url": "https://mytfsserver/DefaultCollection/_apis/git/repositories/278d5cd2-584d-4b63-824a-2ba458937249/refs/heads/master" }, { "name": "refs/heads/npaulk/feature", "objectId": "23d0bc5b128a10056dc68afece360d8a0fabb014", "url": "https://mytfsserver/DefaultCollection/_apis/git/repositories/278d5cd2-584d-4b63-824a-2ba458937249/refs/heads/npaulk/feature" }, { "name": "refs/tags/v1.0", "objectId": "23d0bc5b128a10056dc68afece360d8a0fabb014", "url": "https://mytfsserver/DefaultCollection/_apis/git/repositories/278d5cd2-584d-4b63-824a-2ba458937249/refs/tags/v1.0" }, { "name": "refs/tags/v1.1", "objectId": "23d0bc5b128a10056dc68afece360d8a0fabb014", "url": "https://mytfsserver/DefaultCollection/_apis/git/repositories/278d5cd2-584d-4b63-824a-2ba458937249/refs/tags/v1.1" }, { "name": "refs/tags/v2.0", "objectId": "23d0bc5b128a10056dc68afece360d8a0fabb014", "url": "https://mytfsserver/DefaultCollection/_apis/git/repositories/278d5cd2-584d-4b63-824a-2ba458937249/refs/tags/v2.0" } ] } ``` ### Just branches #### Sample request ``` GET https://mytfsserver/DefaultCollection/_apis/git/repositories/278d5cd2-584d-4b63-824a-2ba458937249/refs/heads?api-version=1.0 ``` #### Sample response ```json { "count": 3, "value": [ { "name": "refs/heads/develop", "objectId": "67cae2b029dff7eb3dc062b49403aaedca5bad8d", "url": "https://mytfsserver/DefaultCollection/_apis/git/repositories/278d5cd2-584d-4b63-824a-2ba458937249/refs/heads/develop" }, { "name": "refs/heads/master", "objectId": "23d0bc5b128a10056dc68afece360d8a0fabb014", "url": "https://mytfsserver/DefaultCollection/_apis/git/repositories/278d5cd2-584d-4b63-824a-2ba458937249/refs/heads/master" }, { "name": "refs/heads/npaulk/feature", "objectId": "23d0bc5b128a10056dc68afece360d8a0fabb014", "url": "https://mytfsserver/DefaultCollection/_apis/git/repositories/278d5cd2-584d-4b63-824a-2ba458937249/refs/heads/npaulk/feature" } ] } ``` ### Just tags #### Sample request ``` GET https://mytfsserver/DefaultCollection/_apis/git/repositories/278d5cd2-584d-4b63-824a-2ba458937249/refs/tags?api-version=1.0 ``` #### Sample response ```json { "count": 3, "value": [ { "name": "refs/tags/v1.0", "objectId": "23d0bc5b128a10056dc68afece360d8a0fabb014", "url": "https://mytfsserver/DefaultCollection/_apis/git/repositories/278d5cd2-584d-4b63-824a-2ba458937249/refs/tags/v1.0" }, { "name": "refs/tags/v1.1", "objectId": "23d0bc5b128a10056dc68afece360d8a0fabb014", "url": "https://mytfsserver/DefaultCollection/_apis/git/repositories/278d5cd2-584d-4b63-824a-2ba458937249/refs/tags/v1.1" }, { "name": "refs/tags/v2.0", "objectId": "23d0bc5b128a10056dc68afece360d8a0fabb014", "url": "https://mytfsserver/DefaultCollection/_apis/git/repositories/278d5cd2-584d-4b63-824a-2ba458937249/refs/tags/v2.0" } ] } ``` ### Include commit status See also: [commit status](./commits.md#commit_status) #### Sample request ``` GET https://mytfsserver/DefaultCollection/_apis/git/repositories/278d5cd2-584d-4b63-824a-2ba458937249/refs/heads/master?includeStatuses=true&api-version=2.1 ``` #### Sample response ```json { "name": "refs/tags/v1.0", "objectId": "278d5cd2-584d-4b63-824a-2ba458937249", "url": "https://mytfsserver/DefaultCollection/_apis/git/repositories/278d5cd2-584d-4b63-824a-2ba458937249/refs?filter=heads%2Fmaster", "statuses": { "state": "succeeded", "description": "The build is successful", "context": { "name": "Build123", "genre": "continuous-integration" }, "creationDate": "2016-01-27T09:33:07Z", "createdBy": { "id": "278d5cd2-584d-4b63-824a-2ba458937249", "displayName": "<NAME>", "uniqueName": "Fabrikamfiber16", "url": "https://mytfsserver/DefaultCollection/_apis/Identities/278d5cd2-584d-4b63-824a-2ba458937249", "imageUrl": "https://mytfsserver/DefaultCollection/_api/_common/identityImage?id=278d5cd2-584d-4b63-824a-2ba458937249" }, "targetUrl": "https://ci.fabrikam.com/my-project/build/123 " } } ``` ## Modify one or more refs Creating, updating, and deleting refs (branches) are all done by the same endpoint. * Updating a ref means making it point at a different commit than it used to. You must specify both the old and new commit to avoid race conditions. * Creating a ref is the represented by updating the ref from the nil commit (represented by 40 `0`s) to a different commit. * Deleting a ref is represented by updating the ref from its current commit to the nil commit. ``` POST https://{instance}/DefaultCollection/{project}/_apis/repos/git/repositories/{repository}/refs?api-version={version} ``` ```http Content-Type: application/json ``` ```json [ { "name": {string}, "oldObjectId": {string}, "newObjectId": {string} } ] ``` | Parameter | Type | Notes |:----------- |:-------|:---------------------------------------------------------------------------------------------------------------------------- | URL | instance | string | TFS server name ({server:port}). | project | string | ID or name of the [project](../tfs/projects.md). *Optional if specifying an ID for repository.* | repository | string | ID or name of the [repository](./repositories.md). | Query | api-version | string | [Version](../../concepts/rest-api-versioning.md) of the API to use. | Body | name | string | Name of the new ref or the ref to update. | oldObjectId | string | The current commit id the ref is at. `0000000000000000000000000000000000000000` when creating a new ref. | newObjectId | string | The new commit id for the ref. `0000000000000000000000000000000000000000` when deleting a ref. #### Sample request ``` POST https://mytfsserver/DefaultCollection/_apis/git/repositories/278d5cd2-584d-4b63-824a-2ba458937249/refs?api-version=1.0 ``` ```json [ { "name": "refs/heads/live", "oldObjectId": "0000000000000000000000000000000000000000", "newObjectId": "4b223e9c93ec3b6aaa6499f06e3ebb7c702e6106" }, { "name": "refs/heads/master", "oldObjectId": "4b223e9c93ec3b6aaa6499f06e3ebb7c702e6106", "newObjectId": "7b019e53c7980d7fafcbd84aa71946793d10a881" }, { "name": "refs/heads/fabrikamfiber16", "oldObjectId": "4b223e9c93ec3b6aaa6499f06e3ebb7c702e6106", "newObjectId": "0000000000000000000000000000000000000000" } ] ``` #### Sample response ```json { "value": [ { "repositoryId": "278d5cd2-584d-4b63-824a-2ba458937249", "name": "refs/heads/live", "oldObjectId": "0000000000000000000000000000000000000000", "newObjectId": "4b223e9c93ec3b6aaa6499f06e3ebb7c702e6106", "isLocked": "false", "updateStatus": "succeeded", "success": true }, { "repositoryId": "278d5cd2-584d-4b63-824a-2ba458937249", "name": "refs/heads/master", "oldObjectId": "4b223e9c93ec3b6aaa6499f06e3ebb7c702e6106", "newObjectId": "7b019e53c7980d7fafcbd84aa71946793d10a881", "isLocked": "false", "updateStatus": "succeeded", "success": true }, { "repositoryId": "7ba192ab-3f08-4fae-a233-ca1fb08c59bf", "name": "refs/heads/fabrikamfiber16", "oldObjectId": "4b223e9c93ec3b6aaa6499f06e3ebb7c702e6106", "newObjectId": "0000000000000000000000000000000000000000", "isLocked": "false", "updateStatus": "succeeded", "success": true } ], "count": 3 } ``` ## Lock a branch ``` PATCH https://{instance}/DefaultCollection/{project}/_apis/repos/git/repositories/{repository}/{ref}?api-version={version} ``` | Parameter | Type | Notes |:----------- |:-------|:---------------------------------------------------------------------------------------------------------------------------- | URL | instance | string | TFS server name ({server:port}). | project | string | ID or name of the [project](../tfs/projects.md). *Optional if specifying an ID for repository.* | repository | string | ID or name of the [repository](./repositories.md). | ref | string | Git ref name. | Query | api-version | string | [Version](../../concepts/rest-api-versioning.md) of the API to use. #### Sample request ``` PATCH https://mytfsserver/DefaultCollection/_apis/git/repositories/5febef5a-833d-4e14-b9c0-14cb638f91e6/refs/heads/master?api-version=1.0 ``` ```json { "isLocked": true } ``` #### Sample response ```json { "name": "refs/heads/master", "objectId": "23d0bc5b128a10056dc68afece360d8a0fabb014", "isLockedBy": { "id": "d6245f20-2af8-44f4-9451-8107cb2767db", "displayName": "Normal Paulk", "uniqueName": "<EMAIL>", "url": "https://mytfsserver/DefaultCollection/_apis/Identities/d6245f20-2af8-44f4-9451-8107cb2767db", "imageUrl": "https://mytfsserver/DefaultCollection/_api/_common/identityImage?id=d6245f20-2af8-44f4-9451-8107cb2767db" }, "isLocked": true, "url": "https://mytfsserver/DefaultCollection/_apis/git/repositories/5febef5a-833d-4e14-b9c0-14cb638f91e6/refs?filter=heads%2Fmaster" } ``` ======================= File: docs/repos/git/share-your-code-in-git-vs-2013.md ======================= --- title: Share your code with Git using Visual Studio 2013 titleSuffix: Azure Repos description: Share code in Git using Visual Studio 2013 ms.assetid: d4d85217-1967-412d-b253-b6c6289dc459 ms.technology: devops-code-git toc: show ms.author: apawast author: apawast ms.topic: quickstart ms.date: 08/29/2017 monikerRange: '>= tfs-2013' --- # Share your code with Visual Studio 2013 and Azure Repos Git > [!div class="op_single_selector"] > - [Visual Studio 2017](share-your-code-in-git-vs-2017.md) > - [Visual Studio 2015 Update 2](share-your-code-in-git-vs.md) > - [Visual Studio 2013](share-your-code-in-git-vs-2013.md) #### Azure Repos | Azure DevOps Server 2019 | TFS 2018 | TFS 2017 | TFS 2015 Whether your software project is large, small, or brand new, in most cases you'll be better off if you use version control as early as possible. Here, we'll show you how to get started with Git, a distributed system. If you want to work in a centralized system, you can instead use [TFVC with Azure Repos](../../repos/tfvc/share-your-code-in-tfvc-vs.md). [!INCLUDE [temp](includes/open-team-project-in-vs.md)] ## Clone your repository 1. Clone the repository onto your dev machine. ![Choose Clone Repository](media/share-your-code-in-git-vs/IC684063.png) 2. Store the repository locally. ![Choose Clone to store the repository locally](media/share-your-code-in-git-vs/IC682931.png) ## Create a new app If you don't already have an app in the repo, create one. 1. Create a new project. ![New solution from team explorer](media/share-your-code-in-git-vs/team-explorer-git-new-solution.png) 2. Choose a template and add the new code project to version control. ![Choose a template](media/create-your-app-vs/IC687148.png) ## Confirm your settings and add the app 1. On the changes page (Keyboard: Ctrl + 0, G), if you haven't already done it, confirm your user name and email address. ![Configure settings from the changes page](media/share-your-code-in-git-vs/confirm-git-settings-from-changes-page.png) ![Confirm the default settings](media/share-your-code-in-git-vs/git-initial-settings-with-default-values.png) 2. Add a comment and commit your app to version control. ![Add app to version control on Changes page](media/share-your-code-in-git-vs/team-explorer-git-changes-add-app.png) ## Snapshot (commit) your code With your code project stored in a local Git repository on your dev machine, you can commit as early and as often as you like. 1. As you write your code, your changes are automatically tracked by Visual Studio. You can commit one or more specific changes to your local repository from Solution Explorer (Keyboard: Ctrl + Alt + L). ![When your changes are ready, select Commit](media/share-your-code-in-git-vs/IC683030.png) 2. On the Changes page, add a comment and then commit your changes. ![Add a comment and choose Commit](media/share-your-code-in-git-vs/IC683031.png) These changes are now committed. ![Your changes are now committed](media/share-your-code-in-git-vs/IC683032.png) ## Pull changes from your team Pull changes on a regular basis to ensure your code integrates well with the latest code from the team. 1. From the commits page (Keyboard: Ctrl + 0, O), fetch the commits to see any changes that your team has made. ![Choose Fetch to see any changes that your team has made](media/share-your-code-in-git-vs/IC682939.png) 2. When you're ready, pull these commits into your local repository. ![Choose Pull to get these commits locally](media/share-your-code-in-git-vs/IC682942.png) 3. The changes from your team are now integrated in your local repository. ![The changes are now integrated](media/share-your-code-in-git-vs/IC682943.png) ## Push your local commits to the server When the code you've written on your dev machine is ready, you can push your changes from your local Git repository to the project. 1. From the changes page (Keyboard: Ctrl + 0, G), make sure you've committed your changes. ![Committing from the Changes page](media/share-your-code-in-git-vs/IC682975.png) 2. Go to the commits page (Keyboard: Ctrl + 0, C). ![Push changes](media/share-your-code-in-git-vs/IC682976.png) 3. Push your changes. ![Push changes](media/share-your-code-in-git-vs/IC682977.png) ## Q&A <!-- BEGINSECTION class="md-qanda" --> [!INCLUDE [temp](includes/open-team-project-in-vs-qa.md)] [!INCLUDE [temp](includes/qa-vs-launch-fail.md)] #### Q: How can I see what I've changed? A: To see what you've changed, compare your changes with the last commit. ![Choose Compare with Unmodified from the context menu](media/share-your-code-in-git-vs/IC685270.png) #### Q: How can I get more information about the commits from my team before I pull them? A: Sometimes you need to see the details about incoming commits from your team. That way you can understand how a change will integrate with your work. ![Choose View Commit Details](media/share-your-code-in-git-vs/IC682940.png) You can get details on the changes to each file. ![Choose Compare with Previous from the context menu](media/share-your-code-in-git-vs/IC685291.png) #### Q: How do I associate my changes with related work items? A: From the changes page you can run a query, and then drag a work item into the list of related work items. ![Associating a work item on the Changes page](media/share-your-code-in-git-vs/IC685315.png) #### Q: Can I use Git command-prompt tools? A: Yes. See [Use Git from the command prompt](command-prompt.md). #### Q: Where can I learn more? A: [Use Visual Studio and Team Foundation Server with Git](overview.md) <!-- ENDSECTION --> ======================= File: release-notes/2019/includes/general/sprint-147-update.md ======================= <reponame>Chibuikekenneth/azure-devops-docs<gh_stars>1-10 --- ms.topic: include --- ### All users now on New Navigation With this sprint all users have been moved to the New Navigation. We’ve removed the preview feature toggle that allowed users to return to the previous navigation model. To learn more about navigating in the web portal, see [Web portal navigation in Azure DevOps](https://docs.microsoft.com/azure/devops/project/navigation/index?view=azure-devops&tabs=new-nav). ======================= File: docs/notifications/manage-organization-notifications-settings.md ======================= --- title: Manage organization notification delivery settings titleSuffix: Azure DevOps description: Manage organization notification delivery settings ms.technology: devops-collab ms.reviewer: wismythe ms.author: chcomley author: chcomley ms.topic: conceptual ms.date: 12/30/2019 monikerRange: '>= tfs-2017' --- # Manage organization notification settings [!INCLUDE [version-vsts-tfs-2017-on](../includes/version-tfs-2017-through-vsts.md)] Choose to allow or block delivery of emails for all subscriptions owned by a team or a group. It's a default setting which applies only if the team or group hasn't explicitly set the option. [!INCLUDE [note-smtp-server](includes/note-smtp-server.md)] ## Manage the default delivery setting 1. [Open organization notifications settings](navigating-the-ui.md#open-org-level). 2. Select the **Settings** tab. 3. Configure the default the delivery setting. > [!div class="mx-imgBorder"] >![Organization notification settings delivery option](media/manage-organization-notifications-settings-delivery.png) ## Related articles Learn about the following details at the [organization notifications page](manage-organization-notifications.md): * [Default subscriptions](manage-organization-notifications.md#organization-notifications-page-default-subscriptions) - view all [default notification subscriptions](./oob-built-in-notifications.md) * [Subscribers](manage-organization-notifications.md#organization-notifications-page-subscribers) - view notification subscriptions for a specific group, team, or individual * [Statistics](manage-organization-notifications.md#organization-notifications-page-statistics) - view the most active subscriptions and top event initiators * [Settings](manage-organization-notifications.md#organization-notifications-page-settings) - manage organization-level settings, such as delivery preferences ======================= File: docs/artifacts/includes/npm/publish.md ======================= --- ms.topic: include ms.technology: devops-cicd ms.author: rabououn author: ramiMSFT ms.date: 02/19/2020 --- Publish npm packages to a feed in Azure Artifacts to share them with your team and your organization. 1. [Set up the npm client with your feed](../../npm/npmrc.md). 1. Open a shell and navigate to the directory that contains your package's **package.json** file. If you don't have a **package.json** file, run `npm init` ([see the npm CLI docs](https://docs.npmjs.com/cli/init)). 1. Push your package by running `npm publish`. See the [npm CLI docs](https://docs.npmjs.com/cli/publish) for more publish options. ======================= File: docs/extend/reference/client/api/TFS/DistributedTask/Contracts/MaskType.md ======================= --- title: TFS/DistributedTask/Contracts MaskType API | Extensions for Azure DevOps Services description: Data representation of a mask type. ms.assetid: 4c3e1ede-5960-85fb-7a06-0ba1310787e5 ms.technology: devops-ecosystem generated: true author: chcomley ms.topic: article ms.author: chcomley ms.date: 08/04/2016 --- # MaskType Module path: `TFS/DistributedTask/Contracts` ### Values * `Variable` * `Regex` ======================= File: docs/pipelines/tasks/index.md ======================= <gh_stars>1-10 --- title: Catalog of the built-in tasks for build-release and Azure Pipelines & TFS ms.custom: seodec18 description: Catalog of the built-in tasks on Azure Pipelines and Team Foundation Server ms.topic: reference ms.assetid: D2DE8A26-AF89-4B08-9FCD-30CD58635B0A ms.date: 05/03/2018 monikerRange: '>= tfs-2015' --- # Build and release tasks **Azure Pipelines | TFS 2018 | TFS 2017 | TFS 2015 | [Previous versions (XAML builds)](https://msdn.microsoft.com/library/ms400688%28v=vs.120%29.aspx)** ::: moniker range="<= tfs-2018" [!INCLUDE [temp](../includes/concept-rename-note.md)] ::: moniker-end This article provides an index of built-in tasks. To learn more about tasks, including creating custom tasks, custom extensions, and finding tasks on the Visual Studio Marketplace, see [Tasks concepts](../process/tasks.md). [!INCLUDE [task-list](includes/task-list.md)] To learn more about tool installer tasks, see [Tool installers](../process/tasks.md#tool-installers). ## Open source These tasks are open source [on GitHub](https://github.com/Microsoft/azure-pipelines-tasks). Feedback and contributions are welcome. ## Q & A <!-- BEGINSECTION class="md-qanda" --> ### Where can I learn step-by-step how to build my app? [Build your app](../apps/index.md) ### Can I add my own build tasks? Yes: [Add a build task](../../extend/develop/add-build-task.md) [!INCLUDE [temp](../includes/qa-agents.md)] ::: moniker range="< azure-devops" [!INCLUDE [temp](../includes/qa-versions.md)] ::: moniker-end <!-- ENDSECTION --> ======================= File: docs/integrate/previous-apis/tfs/projects.md ======================= --- ms.technology: devops-ecosystem monikerRange: '>= tfs-2015 < azure-devops' title: Projects | REST API Reference for Team Foundation Server description: Work with projects programmatically using the REST APIs for Team Foundation Server. ms.assetid: 537E1A1F-DAE8-4110-AF0F-63D5D52F2AB6 ms.topic: article ms.author: chcomley author: chcomley ms.date: 08/16/2016 --- # Projects [!INCLUDE [azure-devops](../_data/azure-devops-message.md)] [!INCLUDE [API_version](../_data/version.md)] Projects contain source code, work items, and other resources. [!INCLUDE [GET_STARTED](../_data/get-started.md)] ## Get a list of projects <a id="GetProjects"></a> Get all projects in the project collection that the authenticated user has access to. ```no-highlight GET https://{instance}/DefaultCollection/_apis/projects?api-version={version}[&stateFilter{string}&$top={integer}&skip={integer}] ``` | Parameter | Type | Default | Notes |:-------------------|:---------------------------------------------------------|:-----------|:---------------------------------------------------------------------------------------------------------------------------- | URL | instance | string | | TFS server name ({server:port}). | Query | api-version | string | | [Version](../../concepts/rest-api-versioning.md) of the API to use. | stateFilter | enum {<br/>&nbsp;&nbsp;WellFormed,<br/>&nbsp;&nbsp;CreatePending,<br/>&nbsp;&nbsp;Deleting,<br/>&nbsp;&nbsp;New,<br/>&nbsp;&nbsp;All<br/>} | WellFormed | Return projects in a specific [project state](#by-state). | $top | integer | 100 | Number of projects to return. | $skip | integer | 0 | Number of projects to skip. #### Sample request ``` GET https://mytfsserver/DefaultCollection/_apis/projects?api-version=1.0 ``` #### Sample response ```json { "count": 3, "value": [ { "id": "eb6e4656-77fc-42a1-9181-4c6d8e9da5d1", "name": "Fabrikam-Fiber-TFVC", "description": "Team Foundation Version Control projects.", "url": "https://mytfsserver/DefaultCollection/_apis/projects/eb6e4656-77fc-42a1-9181-4c6d8e9da5d1", "state": "wellFormed" }, { "id": "6ce954b1-ce1f-45d1-b94d-e6bf2464ba2c", "name": "Fabrikam-Fiber-Git", "description": "Git projects", "url": "https://mytfsserver/DefaultCollection/_apis/projects/6ce954b1-ce1f-45d1-b94d-e6bf2464ba2c", "state": "wellFormed" }, { "id": "281f9a5b-af0d-49b4-a1df-fe6f5e5f84d0", "name": "TestGit", "url": "https://mytfsserver/DefaultCollection/_apis/projects/281f9a5b-af0d-49b4-a1df-fe6f5e5f84d0", "state": "wellFormed" } ] } ``` #### Sample code * [C# (ListAllProjectsAndTeams method)](https://github.com/microsoft/azure-devops-dotnet-samples/blob/master/ClientLibrary/Samples/ProjectsAndTeams/ProjectsSample.cs#L22) ### By state <a id="projectStates"></a> | State Name | Explanation |:--------------|:----------------- | All | All projects regardless of state. | CreatePending | Project has been queued for creation, but the process has not yet started. | Deleting | Project is in the process of being deleted. | New | Project is in the process of being created. | WellFormed | <b>Default: </b>Project is completely created and ready to use. #### Sample request ``` GET https://mytfsserver/DefaultCollection/_apis/projects?stateFilter=All&api-version=1.0 ``` #### Sample response ```json { "count": 3, "value": [ { "id": "eb6e4656-77fc-42a1-9181-4c6d8e9da5d1", "name": "Fabrikam-Fiber-TFVC", "description": "Team Foundation Version Control projects.", "url": "https://mytfsserver/DefaultCollection/_apis/projects/eb6e4656-77fc-42a1-9181-4c6d8e9da5d1", "state": "wellFormed" }, { "id": "6ce954b1-ce1f-45d1-b94d-e6bf2464ba2c", "name": "Fabrikam-Fiber-Git", "description": "Git projects", "url": "https://mytfsserver/DefaultCollection/_apis/projects/6ce954b1-ce1f-45d1-b94d-e6bf2464ba2c", "state": "wellFormed" }, { "id": "281f9a5b-af0d-49b4-a1df-fe6f5e5f84d0", "name": "TestGit", "url": "https://mytfsserver/DefaultCollection/_apis/projects/281f9a5b-af0d-49b4-a1df-fe6f5e5f84d0", "state": "wellFormed" } ] } ``` #### Sample code * [C# (ListProjectsByState method)](https://github.com/microsoft/azure-devops-dotnet-samples/blob/master/ClientLibrary/Samples/ProjectsAndTeams/ProjectsSample.cs#L359) ### A page at a time <a name="projectpageatatime"></a> #### Sample request ``` GET https://mytfsserver/DefaultCollection/_apis/projects?$top=1&$skip=1&api-version=1.0 ``` #### Sample response ```json { "count": 1, "value": [ { "id": "eb6e4656-77fc-42a1-9181-4c6d8e9da5d1", "name": "Fabrikam-Fiber-TFVC", "description": "Team Foundation Version Control projects.", "url": "https://mytfsserver/DefaultCollection/_apis/projects/eb6e4656-77fc-42a1-9181-4c6d8e9da5d1", "state": "wellFormed" } ] } ``` ## Get a project <a id="GetProject"></a> <a name="getateamproject" /> ```no-highlight GET https://{instance}/DefaultCollection/_apis/projects/{project}?api-version={version}[&includeCapabilities={boolean}&includeHistory={boolean}] ``` | Parameter | Type | Default | Notes |:-------------------|:--------|:--------|:---------------------------------------------------------------------------------------------------------------------------- | URL | instance | string | | TFS server name ({server:port}). | project | string | | Name or ID of the project. | Query | api-version | string | | [Version](../../concepts/rest-api-versioning.md) of the API to use. | includeCapabilities | boolean | `false` | Use `true` to [include capabilities](#withcapabilities) (such as source control) in the project result. | includeHistory | boolean | `false` | Use `true` to search within renamed projects that had such name in the past. ### With capabilities <a name="withcapabilities" /> Get metadata on a project, including its capabilities. #### Sample request ``` GET https://mytfsserver/DefaultCollection/_apis/projects/Fabrikam-Fiber-TFVC?includeCapabilities=true&api-version=1.0 ``` #### Sample response ```json { "id": "eb6e4656-77fc-42a1-9181-4c6d8e9da5d1", "name": "Fabrikam-Fiber-TFVC", "url": "https://mytfsserver/DefaultCollection/_apis/projects/eb6e4656-77fc-42a1-9181-4c6d8e9da5d1", "description": "Team Foundation Version Control projects.", "state": "wellFormed", "capabilities": { "versioncontrol": { "sourceControlType": "Tfvc" }, "processTemplate": { "templateName": "Microsoft Visual Studio Scrum 2013" } }, "_links": { "self": { "href": "https://mytfsserver/DefaultCollection/_apis/projects/eb6e4656-77fc-42a1-9181-4c6d8e9da5d1" }, "collection": { "href": "https://mytfsserver/DefaultCollection/_apis/projectCollections/d81542e4-cdfa-4333-b082-1ae2d6c3ad16" }, "web": { "href": "https://mytfsserver/DefaultCollection/Fabrikam-Fiber-TFVC" } }, "defaultTeam": { "id": "66df9be7-3586-467b-9c5f-425b29afedfd", "name": "Fabrikam-Fiber-TFVC Team", "url": "https://mytfsserver/DefaultCollection/_apis/projects/eb6e4656-77fc-42a1-9181-4c6d8e9da5d1/teams/66df9be7-3586-467b-9c5f-425b29afedfd" } } ``` #### Sample code * [C# (GetProjectDetails method)](https://github.com/microsoft/azure-devops-dotnet-samples/blob/master/ClientLibrary/Samples/ProjectsAndTeams/ProjectsSample.cs#L98) ## Create a project <a name="createateamproject" /> Create a project in a VSTS organization. Use the <a href="#GetOperation" data-raw-source="[GetOperation](#GetOperation)">GetOperation</a> to periodically check for create project status. ```no-highlight POST https://{instance}/defaultcollection/_apis/projects?api-version={version} ``` | Parameter | Type | Notes |:------------|:--------:|:--------------------------------------------------- | URL | instance | string | TFS server name ({server:port}). | Query | api-version | string | [Version](../../concepts/rest-api-versioning.md) of the API to use. | Request Body | name | string | Name for the project. | description | string | Description for the project. | capabilities.versioncontrol.sourceControlType | enum { Git, Tfvc } | Version control type for the project. | capabilities.processTemplate.templateTypeId | string | Software development schema for the project. See the [processes](processes.md#getalistofprocesses) REST API for how to retrieve the list of available processes and their corresponding IDs. #### Sample request ``` POST https://mytfsserver/DefaultCollection/_apis/projects?api-version=2.0-preview ``` ```json { "name": "FabrikamTravel", "description": "Fabrikam travel app for Windows Phone", "capabilities": { "versioncontrol": { "sourceControlType": "Git" }, "processTemplate": { "templateTypeId": "6b724908-ef14-45cf-84f8-768b5384da45" } } } ``` #### Sample response ```json { "id": "066488b8-b14e-43d1-befc-a2e655266e2b", "status": "queued", "url": "https://mytfsserver/DefaultCollection/_apis/operations/066488b8-b14e-43d1-befc-a2e655266e2b" } ``` #### Sample code * [C# (CreateProject method)](https://github.com/microsoft/azure-devops-dotnet-samples/blob/master/ClientLibrary/Samples/ProjectsAndTeams/ProjectsSample.cs#L121) ## Update a project <a name="updateateamproject" /> Update a project's description or name. Use the [GetOperation](#GetOperation) to periodically check for update project status. ```no-highlight PATCH https://{instance}/defaultcollection/_api/projects/{projectID}?api-version={version} ``` ```http Content-Type: application/json ``` ``` { "name": {string}, "description": {string} } ``` | Parameter | Type | Notes |:-----------|:--------:|:--------------------------------------------------- | URL | instance | string | TFS server name ({server:port}). | projectID | string | ID for the project. | Query | api-version | string | [Version](../../concepts/rest-api-versioning.md) of the API to use. | Request Body | name | string | Name of the project. | description | string | Description for the project. ### Rename a project <a id="UpdateName"></a> #### Sample request ``` PATCH https://mytfsserver/DefaultCollection/_apis/projects/eb6e4656-77fc-42a1-9181-4c6d8e9da5d1?api-version=2.0-preview ``` ```json { "name": "Fabrikam-Fiber" } ``` #### Sample response ```json { "id": "b5f386e9-c67d-4caf-8e78-4e58230c7e90", "status": "queued", "url": "https://mytfsserver/DefaultCollection/_apis/operations/b5f386e9-c67d-4caf-8e78-4e58230c7e90" } ``` #### Sample code * [C# (RenameProject method)](https://github.com/microsoft/azure-devops-dotnet-samples/blob/master/ClientLibrary/Samples/ProjectsAndTeams/ProjectsSample.cs#L280) ### Change a project description <a id="UpdateDescription"></a> #### Sample request ``` PATCH https://mytfsserver/DefaultCollection/_apis/projects/eb6e4656-77fc-42a1-9181-4c6d8e9da5d1?api-version=2.0-preview ``` ```json { "description": "TFVC projects." } ``` #### Sample response ```json { "id": "b5f386e9-c67d-4caf-8e78-4e58230c7e90", "status": "queued", "url": "https://mytfsserver/DefaultCollection/_apis/operations/b5f386e9-c67d-4caf-8e78-4e58230c7e90" } ``` #### Sample code * [C# (ChangeProjectDescription method)](https://github.com/microsoft/azure-devops-dotnet-samples/blob/master/ClientLibrary/Samples/ProjectsAndTeams/ProjectsSample.cs#L235) ## Get an operation <a id="GetOperation"></a> Monitor the progress of an asynchronous REST API call. ```no-highlight GET https://{instance}/defaultcollection/_apis/operations/{operationid}?api-version={version} ``` | Parameter | Type | Default | Notes |:-------------------|:---------------------------------------------------------|:-----------|:---------------------------------------------------------------------------------------------------------------------------- | URL | instance | string | | TFS server name ({server:port}). | operationId | string | | ID of the operation. | Query | api-version | string | | [Version](../../concepts/rest-api-versioning.md) of the API to use. #### Sample request ``` GET https://mytfsserver/DefaultCollection/_apis/operations/109787e4-3f2e-4fbb-af75-0be32e63e45d?api-version=2.0 ``` #### Sample response ```json { "id": "109787e4-3f2e-4fbb-af75-0be32e63e45d", "status": "inProgress", "url": "https://mytfsserver/DefaultCollection/_apis/operations/109787e4-3f2e-4fbb-af75-0be32e63e45d", "_links": { "self": { "href": "https://mytfsserver/DefaultCollection/_apis/operations/109787e4-3f2e-4fbb-af75-0be32e63e45d" } } } ``` #### Sample code * [C# (WaitForLongRunningOperation method)](https://github.com/microsoft/azure-devops-dotnet-samples/blob/master/ClientLibrary/Samples/ProjectsAndTeams/ProjectsSample.cs#L204) ## Delete a project <a id="DeleteProject"></a> Delete a project. Use the [GetOperation](#GetOperation) to periodically check for delete project status. ```no-highlight DELETE https://{instance}/defaultcollection/_apis/projects/{id}?api-version={version} ``` | Parameter | Type | Notes |:-----------|:--------:|:--------------------------------------------------- | URL | instance | string | TFS server name ({server:port}). | id | string | ID for the project. | Query | api-version | string | [Version](../../concepts/rest-api-versioning.md) of the API to use. #### Sample request ```no-highlight DELETE https://fabrikam.visualstudio.com/DefaultCollection/_apis/projects/98dd5ded-8110-459b-8241-3d12b2eeaf18?api-version=1.0 ``` #### Sample response *Status Code:* 204 #### Sample code * [C# (DeleteProject method)](https://github.com/microsoft/azure-devops-dotnet-samples/blob/master/ClientLibrary/Samples/ProjectsAndTeams/ProjectsSample.cs#L323) <a name="Get project properties"></a> ## Get project properties Get a collection of project properties. ```no-highlight GET https://{instance}/_apis/projects/{projectId}/properties?api-version={version} ``` #### Authorization scopes For more details, see section on how to [authorize access to REST APIs](../../get-started/Authentication/oauth.md). | Scope | Name | Notes |:------|:-----|:----- | vso.profile | User profile (read) | Grants the ability to read your profile, accounts, collections, projects, teams, and other top-level organizational artifacts. | vso.project | Project and team (read) | Grants the ability to read projects and teams. #### Request parameters | Name | In | Type | Notes |:--------------|:-----------|:---------|:------------ | <code>projectId</code> | URL | GUID | Required. The project ID. | <code>api-version</code> | Query | string | Required. [Version](../../concepts/rest-api-versioning.md) of the API to use. This should be set to '4.0-preview' to use this version of the API. | <code>keys</code> | Query | array (string) | Optional. A comma-delimited string of project property names. Wildcard characters ("?" and "*") are supported. If no key is specified, all properties will be returned. #### Response | Type | Notes |:-----------|:--------- | VssJsonCollectionWrapper&lt;array ([ProjectProperty](./contracts.md#ProjectProperty))&gt; | A collection of project properties. ### Get all project properties #### Sample request ``` GET https://mytfsserver/DefaultCollection/_apis/projects/94e82dfb-8ce4-430c-aa97-07ee10c83d5f/properties?api-version=4.0-preview ``` #### Sample response ```json { "count": 8, "value": [ { "name": "System.CurrentProcessTemplateId", "value": "2dc3221a-2d39-4138-a4e1-fc4d20d8912d" }, { "name": "System.OriginalProcessTemplateId", "value": "2dc3221a-2d39-4138-a4e1-fc4d20d8912d" }, { "name": "System.ProcessTemplateType", "value": "adcc42ab-9882-485e-a3ed-7678f01f66bc" }, { "name": "System.Process Template", "value": "Agile" }, { "name": "System.Microsoft.TeamFoundation.Team.Default", "value": "9b7ae5b9-826f-4353-99d6-daaa5cd94ec6" }, { "name": "System.SourceControlCapabilityFlags", "value": "2" }, { "name": "System.SourceControlGitEnabled", "value": "True" }, { "name": "System.SourceControlGitPermissionsInitialized", "value": "True" } ] } ``` ### Get specific project properties #### Sample request ``` GET https://mytfsserver/DefaultCollection/_apis/projects/94e82dfb-8ce4-430c-aa97-07ee10c83d5f/properties?keys=System.CurrentProcessTemplateId,*SourceControl*&api-version=4.0-preview ``` #### Sample response ```json { "count": 4, "value": [ { "name": "System.CurrentProcessTemplateId", "value": "2dc3221a-2d39-4138-a4e1-fc4d20d8912d" }, { "name": "System.SourceControlCapabilityFlags", "value": "2" }, { "name": "System.SourceControlGitEnabled", "value": "True" }, { "name": "System.SourceControlGitPermissionsInitialized", "value": "True" } ] } ``` <a name="Set project properties"></a> ## Set project properties Create, update, and delete project properties. ```no-highlight PATCH https://{instance}/_apis/projects/{projectId}/properties?api-version={version} ``` #### Authorization scopes For more details, see section on how to [authorize access to REST APIs](../../get-started/Authentication/oauth.md). | Scope | Name | Notes |:------|:-----|:----- | vso.project_write | Project and team (read and write) | Grants the ability to read and update projects and teams. #### Request parameters | Name | In | Type | Notes |:--------------|:-----------|:---------|:------------ | <code>projectId</code> | URL | GUID | Required. The project ID. | <code>api-version</code> | Query | string | Required. [Version](../../concepts/rest-api-versioning.md) of the API to use. This should be set to '4.0-preview' to use this version of the API. | | Body | [JsonPatchDocument](./contracts.md#JsonPatchDocument) | Required. A JSON Patch document that represents an array of property operations. See RFC 6902 for more details on JSON Patch. The accepted operation verbs are Add and Remove, where Add is used for both creating and updating properties. The path consists of a forward slash and a property name. Media Type: "application/json-patch+json" ### Create or update a project property #### Sample request ``` PATCH https://mytfsserver/DefaultCollection/_apis/projects/94e82dfb-8ce4-430c-aa97-07ee10c83d5f/properties?api-version=4.0-preview ``` ```json [ { "op": "add", "path": "/Alias", "value": "Fabrikam" } ] ``` ### Delete a project property #### Sample request ``` PATCH https://mytfsserver/DefaultCollection/_apis/projects/94e82dfb-8ce4-430c-aa97-07ee10c83d5f/properties?api-version=4.0-preview ``` ```json [ { "op": "remove", "path": "/Alias" } ] ``` ======================= File: docs/extend/reference/client/api/VSS/References/SDK_Interfaces/ContributionBase.md ======================= <filename>docs/extend/reference/client/api/VSS/References/SDK_Interfaces/ContributionBase.md --- title: VSS/References/SDK.Interfaces ContributionBase API | Extensions for Azure DevOps Services description: Base class shared by contributions and contribution types ms.assetid: f4b51e85-b7a0-fc22-2a14-c3e1aafce419 ms.technology: devops-ecosystem generated: true ms.author: chcomley author: chcomley ms.topic: article monikerRange: '>= tfs-2017' ms.date: 08/04/2016 --- # ContributionBase Defined in vss.d.ts Base class shared by contributions and contribution types ### Members * `description`: string. Description of the contribution/type * `id`: string. Extension-relative identifier of the contribution/type ======================= File: docs/pipelines/includes/get-status-badge.md ======================= <reponame>Chibuikekenneth/azure-devops-docs --- ms.topic: include ms.technology: devops-cicd ms.manager: mijacobs ms.author: jukullam author: juliakm ms.date: 02/13/2020 --- <a name="get-the-status-badge"></a> ## Add a status badge to your repository Many developers like to show that they're keeping their code quality high by displaying a status badge in their repo. ![Status badge shows Azure pipeline succeeded](../media/azure-pipelines-succeeded.png) To copy the status badge to your clipboard: 1. In Azure Pipelines, go to the **Pipelines** page to view the list of pipelines. Select the pipeline you created in the previous section. 2. In the context menu for the pipeline, select **Status badge**. 3. Copy the sample Markdown from the status badge panel. Now with the badge Markdown in your clipboard, take the following steps in GitHub: 1. Go to the list of files and select `Readme.md`. Select the pencil icon to edit. 2. Paste the status badge Markdown at the beginning of the file. 3. Commit the change to the `master` branch. 4. Notice that the status badge appears in the description of your repository. To configure anonymous access to badges: 1. Navigate to **Project Settings** 2. Open the **Settings** tab under **Pipelines** 3. Toggle the **Disable anonymous access to badges** slider under **General** > [!NOTE] > Even in a private project, anonymous badge access is enabled by default. With anonymous badge access enabled, users outside your organization might be able to query information such as project names, branch names, job names, and build status through the badge status API. Because you just changed the `Readme.md` file in this repository, Azure Pipelines automatically builds your code, according to the configuration in the `azure-pipelines.yml` file at the root of your repository. Back in Azure Pipelines, observe that a new run appears. Each time you make an edit, Azure Pipelines starts a new run. ======================= File: docs/pipelines/agents/prepare-permissions.md ======================= --- title: Prepare permissions ms.custom: seodec18 description: Prepare permissions ms.topic: conceptual ms.assetid: D54EB55B-78E0-4B32-9DDB-C8C0B58A3AB3 robots: NOINDEX, NOFOLLOW ms.date: 3/14/2017 monikerRange: '>= tfs-2015' --- # Prepare permissions [!INCLUDE [version-tfs-2015-rtm](../includes/version-tfs-2015-rtm.md)] [!INCLUDE [include](includes/v2/prepare-permissions.md)] ======================= File: docs/pipelines/tasks/deploy/includes/rm-webapp-functionapp-troubleshoot-shared.md ======================= --- author: ninallam ms.prod: devops ms.technology: devops-cicd-tasks ms.topic: include ms.date: 12/10/2019 ms.manager: mijacobs ms.author: ninallam --- ### Error: No package found with specified pattern Check if the package mentioned in the task is published as an artifact in the build or a previous stage and downloaded in the current job. ### Error: Publish using zip deploy option is not supported for msBuild package type Web packages created using MSBuild task (with default arguments) have a nested folder structure that can only be deployed correctly by Web Deploy. Publish to zip deploy option can not be used to deploy those packages. To convert the packaging structure, follow the below steps. * In Build Solution task, change the MSBuild Arguments to /p:DeployOnBuild=true /p:DeployDefaultTarget=WebPublish /p:WebPublishMethod=FileSystem /p:DeleteExistingFiles=True /p:publishUrl="$(System.DefaultWorkingDirectory)\\WebAppContent" * Add Archive Task and change the inputs as follows: * Change *Root folder or file to archive* to $(System.DefaultWorkingDirectory)\\WebAppContent ![Root folder or file to archive](../media/azure-rm-web-app-deployment-03.png) * Disable *Prepend root folder name to archive paths* option ![Prepend root folder name to archive paths](../media/azure-rm-web-app-deployment-04.png) ======================= File: docs/extend/reference/client/api/TFS/VersionControl/Contracts/GitStatus.md ======================= <gh_stars>1-10 --- title: TFS/VersionControl/Contracts GitStatus API | Extensions for Azure DevOps Services ms.assetid: 46222fb4-12c2-f6cf-f2a9-15d9b9e222b9 ms.technology: devops-ecosystem generated: true author: chcomley ms.topic: article ms.author: chcomley ms.date: 08/04/2016 --- # GitStatus Module path: `TFS/VersionControl/Contracts` ### Members * `_links`: any. * `context`: [GitStatusContext](../../../TFS/VersionControl/Contracts/GitStatusContext.md). * `createdBy`: [VSS_Common_Contracts.IdentityRef](../../../VSS/WebApi/Contracts/IdentityRef.md). * `creationDate`: Date. * `description`: string. * `state`: [GitStatusState](../../../TFS/VersionControl/Contracts/GitStatusState.md). * `targetUrl`: string. ======================= File: release-notes/2020/includes/pipelines/sprint-166-update.md ======================= --- ms.topic: include --- ### Runtime parameters With this update, we're adding runtime parameters. Runtime parameters let you have more control over what values can be passed to a pipeline. Unlike variables, runtime parameters have data types and don't automatically become environment variables. With runtime parameters you can: * Supply different values to scripts and tasks at runtime * Control parameter types, ranges allowed, and defaults * Dynamically select jobs and stages with template expression To learn more about runtime parameters, see the documentation [here](https://docs.microsoft.com/azure/devops/pipelines/process/runtime-parameters?view=azure-devops). ### Agent diagnostics We've added diagnostics for many common agent related problems such as many networking issues and common causes of upgrade failures. To get started with diagnostics, use **run.sh --diagnostics** or **run.cmd --diagnostics** on Windows. ======================= File: release-notes/2019/includes/pipelines/sprint-151-update.md ======================= --- ms.topic: include --- ### Azure Pipelines app for Microsoft Teams We're excited to announce the new Azure Pipelines app for Microsoft Teams. You can now easily monitor Azure DevOps Pipelines and approve releases in Teams. In addition, you can manage subscriptions for completed builds, releases, pending approvals and get notifications for these events in your Teams channels. To get started, install the Azure Pipelines app from the Microsoft Teams app store and see the documentation [here](https://docs.microsoft.com/azure/devops/pipelines/integrations/microsoft-teams?view=azure-devops). > [!div class="mx-imgBorder"] >![Badge](../../media/151_09.png "Azure Pipelines app for Microsoft Teams") ### Updates to pipeline creation experience Previously, we had two entry points when you created a build pipeline. One for classic build pipelines and another for YAML build pipelines. Whether you saw one or the other was controlled by a preview features toggle. With this update we removed the preview features toggle so you will have a single entry point that covers both YAML and classic builds. The new experience supports all the repo types that were supported in the classic experience. However, if a repo type supports both YAML and classic builds (e.g., GitHub or Azure Repos), the preference is given to YAML builds. You can always override and choose the classic editor to create a pipeline without YAML. > [!div class="mx-imgBorder"] >![Badge](../../media/151_10.png "New pipeline - where is your code?") ======================= File: docs/extend/reference/client/api/VSS/Operations/Contracts/Operation.md ======================= <filename>docs/extend/reference/client/api/VSS/Operations/Contracts/Operation.md --- title: VSS/Operations/Contracts Operation API | Extensions for Azure DevOps Services description: Represents an async operation and its progress or result information. ms.assetid: 4c2bca2f-ba0b-c38a-9129-960ee5c76b3d ms.technology: devops-ecosystem generated: true author: chcomley ms.topic: article ms.author: chcomley ms.date: 08/25/2016 --- # VSS/Operations/Contracts Operation Module path: `VSS/Operations/Contracts` Extends: [OperationReference](../../../VSS/Operations/Contracts/OperationReference.md) ### Members * `_links`: any. The links to other objects related to this object. * `resultMessage`: string. The result message which is generally not set. ======================= File: docs/report/sharepoint-dashboards/share-information-using-the-project-portal.md ======================= <gh_stars>1-10 --- title: Share information using the project portal titleSuffix: TFS description: Use the SharePoint project portal to share information with your team ms.technology: devops-analytics ms.assetid: 74f0e0bc-6528-4757-b906-b53aa869507b ms.author: kaelli author: KathrynEE ms.date: 09/09/2017 monikerRange: '>= tfs-2013' ms.topic: conceptual --- # Share information using the project portal [!INCLUDE [temp](../includes/tfs-sharepoint-version.md)] Teams use project portals to share information and support how their team works. If you install TFS with a configuration that includes SharePoint Products and you created a project portal when you created your team project, your team project is configured with a SharePoint site for the project portal. ## Open the project portal 1. From Team Explorer, open the documents page. <table> <tbody valign="top"> <tr> <td><strong>Git</strong></td> <td><strong>TFVC</strong></td> </tr> <tr> <td><img src="media/alm_te_githome.png" alt="Team Explorer Home page with Git as source control" title="ALM_TE_GitHome"/></td> <td><img src="media/tracking_teamproject.png" alt="Team Explorer Home page w&#47; TFVC as source control" title="Tracking_TeamProject"/></td> </tr> </tbody> </table> If you don't see the documents icon, your team project is not configured with a SharePoint site. To learn how to configure a SharePoint site for your team project, see [Configure or add a project portal](../../project/configure-or-add-a-project-portal.md). 2. Show the project portal. ![Show Project Portal link on Documents page](media/alm_pg_showprojectportal.png "ALM_PG_ShowProjectPortal") From the web portal, choose the **Go to project portal** from the home page or a dashboard which contains the [Other links widget](../widget-catalog.md). The link opens to the Project, Progress, or Release dashboard, depending on your SharePoint site configuration and the process template used to create your team project. To learn more about SharePoint dashboards, see [Project portal dashboards](project-portal-dashboards.md). If you can't open the portal, you need to be added to a [permissions group in SharePoint](../../organizations/security/set-sharepoint-permissions.md). ## Related notes - [Dashboards and reports](../overview.md) - [Agile process guidance](../../boards/work-items/guidance/agile-process.md) - [CMMI process guidance](../../boards/work-items/guidance/cmmi-process.md) - [Scrum process guidance](../../boards/work-items/guidance/scrum-process.md) ### Q: What artifacts are available with a SharePoint project portal? **A:** The artifacts you'll have access to depend on the process template created with your team project. For an overview of the artifacts available with the default process templates, see [Choose a process](../../boards/work-items/guidance/choose-process.md). ### Q: How do I access process guidance? **A:** If your team project is configured with a SharePoint site for its project portal, you can access process guidance from the work item forms in Team Explorer. Choose the![Open process guidance for work item](media/processguidance_wi_icon.png "ProcessGuidance_WI_Icon") process guidance icon or press F1. These links access information contained in the Documents **Support** folder. From the web portal, you can access process guidance from the home page or a dashboard When you choose the![Open process guidance for work item](media/processguidance_wi_icon.png "ProcessGuidance_WI_Icon") process guidance icon that appears in the work item forms in Team Explorer, a web browser opens and the page that's defined in the process guidance support file for the corresponding work item type is displayed. If you have not configured your team project with a project portal, or you haven't uploaded the process guidance support files to the project portal, then this link will be inactive. You can [redirect process guidance](../../project/configure-or-redirect-process-guidance.md) to your custom content. <a name="addportal"></a> ### Q: How do I add a project portal to my team project? How do I enable process guidance? **A:** If you want to specify an existing website as your team project's portal or support process guidance, see [Configure a project portal](../../project/configure-or-add-a-project-portal.md). > [!IMPORTANT] > If you add another type of website, the links to open the project portal from the web portal and Team Explorer don't appear. Also, the **Documents** page doesn't appear in Team Explorer. **A:** If you have a SharePoint site already configured with Team Foundation Server Extensions for SharePoint, see [Configure a project portal](../../project/configure-or-add-a-project-portal.md). If you need to install a SharePoint product first, see [Manually install SharePoint products for Team Foundation Server](/azure/devops/server/install/sharepoint/install-sharepoint). ### Q: Can I customize the process guidance? **A:** Yes. See [Configure or redirect process guidance](../../project/configure-or-redirect-process-guidance.md). ### Q: Do you want more information about SharePoint site features? **A:** See the [SharePoint Online Tutorial](https://office.microsoft.com/sharepoint-server-help/sharepoint-pages-i-an-introduction-RZ101837217.aspx?CTT=1). ======================= File: docs/extend/reference/client/api/TFS/Build/Contracts/PropertyValue.md ======================= --- title: TFS/Build/Contracts PropertyValue API | Extensions for Azure DevOps Services description: Data representation of a property value. ms.assetid: 7566ca43-591e-4ec3-05bc-6632988b7629 ms.technology: devops-ecosystem generated: true author: chcomley ms.topic: article ms.author: chcomley ms.date: 08/04/2016 --- # PropertyValue Module path: `TFS/Build/Contracts` ### Members * `changedBy`: string. Guid of identity that changed this property value * `changedDate`: Date. The date this property value was changed * `propertyName`: string. Name in the name value mapping * `value`: any. Value in the name value mapping ======================= File: docs/pipelines/archive/news/2015-01.md ======================= <gh_stars>1-10 --- toc: show parent:../index.md ms.topic: conceptual title: January 2015 Azure Pipelines Update description: Update for Azure Pipelines January 2015, for TFS 2015 and TFS 2017 ms.assetid: 30053D42-F6AB-4952-8397-EF0ED5AB6581 ms.custom: seodec18 ms.date: 08/04/2016 monikerRange: '>= tfs-2015 <= tfs-2017' --- # January 2015 **TFS 2017 | TFS 2015** ## Variable Secrets Build definitions variables can be locked so not viewable in the web and masked in logs <iframe width="420" height="315" src="https://www.youtube.com/embed/90-Pa_EwOvk" frameborder="0" allowfullscreen="true"></iframe> ## Build Issues with Source Links Errors and Warnings show up in build summary with links to source code. Available to all tasks as api. <iframe width="420" height="315" src="https://www.youtube.com/embed/ZISvtGw_oGI" frameborder="0" allowfullscreen="true"></iframe> ## Friendly Names and Navigation Build tasks get useful friendly names with overrides. Improvements in navigation from build summary. <iframe width="420" height="315" src="https://www.youtube.com/embed/UBdv145hkFc" frameborder="0" allowfullscreen="true"></iframe> ## Queue Time Demands At queue time, control which agent will get this queued build without editing definition. <iframe width="420" height="315" src="https://www.youtube.com/embed/yLsqHdVGc8g" frameborder="0" allowfullscreen="true"></iframe> ======================= File: docs/artifacts/index-to-delete.md ======================= <reponame>Chibuikekenneth/azure-devops-docs --- title: Azure Artifacts Documentation titleSuffix: Azure DevOps Services description: Code once and share packages Nuget, npm, and Maven with Azure Artifacts for more reliable, scalable builds. layout: LandingPage hide_bc: true ms.topic: landing-page ms.prod: devops ms.technology: devops-artifacts ms.assetid: ms.manager: mijacobs ms.author: kaelli ms.date: 05/6/2019 featureFlags: - clicktale --- <p><a href="/azure/devops/index">Azure DevOps</a> / Azure Artifacts</p> # Azure Artifacts Documentation <p>Code once and share packages across your organization. Host your private Nuget, npm, and Maven packages with Azure Artifacts for more reliable, scalable builds.</p> <ul class="panelContent cardsF"> <li> <div class="cardSize"> <div class="cardPadding"> <div class="card"> <div class="cardImageOuter"> <div class="cardImage"> <img src="../media/index/DevOpsIconArtifacts40.svg" /> </div> </div> <div class="cardText"> <h3>Azure Artifacts &amp; Package Management</h3> <p> <a href="/azure/devops/artifacts/overview">What is Azure Artifacts?</a> </p> <p> <a href="/azure/devops/artifacts/nuget/move-from-fileshares">Move your packages to the cloud</a> </p> <p> <a href="/azure/devops/artifacts/concepts/best-practices">Best practices for using Azure Artifacts</a> </p> <p> <a href="/azure/devops/artifacts/concepts/upstream-sources">Consume packages from public sources</a> </p> </div> </div> </div> </div> </li> <li> <div class="cardSize"> <div class="cardPadding"> <div class="card"> <div class="cardImageOuter"> <div class="cardImage"> <img src="media/index/logo_nuget.svg" alt="NuGet logo" /> </div> </div> <div class="cardText"> <h3>NuGet</h3> <p> <a href="/azure/devops/artifacts/get-started-nuget">Get started with NuGet packages</a> </p> <p> <a href="/azure/devops/pipelines/artifacts/nuget">Set up Azure Pipelines and NuGet</a> </p> <p> <a href="/azure/devops/artifacts/nuget/publish">Publish a NuGet package</a> </p> <p> <a href="/azure/devops/artifacts/nuget/consume">Consume NuGet packages</a> </p> <p> <a href="/azure/devops/artifacts/nuget/upstream-sources">Use packages from nuget.org</a> </p> </div> </div> </div> </div> </li> <li> <div class="cardSize"> <div class="cardPadding"> <div class="card"> <div class="cardImageOuter"> <div class="cardImage"> <img src="media/index/logo_npm.svg" alt="npm logo" /> </div> </div> <div class="cardText"> <h3>npm</h3> <p> <a href="/azure/devops/artifacts/get-started-npm">Use npm to store JavaScript packages</a> </p> <p> <a href="/azure/devops/pipelines/artifacts/npm">Publish npm packages</a> </p> <p> <a href="/azure/devops/artifacts/npm/npmrc">Set up your client&#39;s npmrc</a> </p> <p> <a href="/azure/devops/artifacts/npm/upstream-sources">Use packages from npmjs.com</a> </p> </div> </div> </div> </div> </li> <li> <div class="cardSize"> <div class="cardPadding"> <div class="card"> <div class="cardImageOuter"> <div class="cardImage"> <img src="media/index/logo_maven.svg" alt="Maven logo" /> </div> </div> <div class="cardText"> <h3>Maven</h3> <p> <a href="/azure/devops/artifacts/get-started-maven">Get started with Maven packages</a> </p> <p> <a href="/azure/devops/pipelines/artifacts/maven">Set up Azure Pipelines and Maven</a> </p> <p> <a href="/azure/devops/artifacts/maven/publish">Publish Maven artifacts</a> </p> <p> <a href="/azure/devops/artifacts/maven/install">Install Maven artifacts</a> </p> <p> <a href="/azure/devops/artifacts/maven/upstream-sources">Use packages from Maven Central</a> </p> </div> </div> </div> </div> </li> <li> <div class="cardSize"> <div class="cardPadding"> <div class="card"> <div class="cardImageOuter"> <div class="cardImage"> <img src="https://docs.microsoft.com/media/logos/logo_python.svg" alt="python logo" /> </div> </div> <div class="cardText"> <h3>Python</h3> <p> <a href="/azure/devops/artifacts/quickstarts/python-packages">Get started with Python packages</a> </p> <p> <a href="/azure/devops/pipelines/artifacts/pypi">Publish Python packages in Azure Pipelines</a> </p> </div> </div> </div> </div> </li> <li> <div class="cardSize"> <div class="cardPadding"> <div class="card"> <div class="cardImageOuter"> <div class="cardImage"> <img src="https://docs.microsoft.com/media/common/i_package.svg" alt="universal packages logo" /> </div> </div> <div class="cardText"> <h3>Universal Packages</h3> <p> <a href="/azure/devops/artifacts/quickstarts/universal-packages">Get started with Universal packages</a> </p> <p> <a href="/azure/devops/pipelines/artifacts/universal-packages">Publish and download Universal Packages in Azure Pipelines</a> </p> </div> </div> </div> </div> </li> </ul> ======================= File: docs/pipelines/overview.md ======================= --- title: Start using Build and Release titleSuffix: TFS description: Build and deploy your app using Team Foundation Server (TFS) ms.assetid: B1233296-C583-4F2E-981C-82D6A39CFEE4 ms.author: sdanie author: steved0x ms.date: 08/31/2018 ms.topic: overview monikerRange: '>= tfs-2015 < azure-devops' --- # Start using Build and Release [!INCLUDE [version-tfs-only-2015](includes/version-tfs-only-2015.md)] Team Foundation Server (TFS) is the on-premises Azure DevOps offering. TFS includes Build and Release and can be installed and managed on your own servers. ![A typical CI and CD process for web applications](./media/pipeline-concept-end-to-end.png) Continuous Integration (CI) is the practice used by development teams to automate the merging and testing of code. Implementing CI helps to catch bugs early in the development cycle, which makes them less expensive to fix. Automated tests execute as part of the CI process to ensure quality. Artifacts are produced from CI systems and fed to release processes to drive frequent deployments. The Build service in TFS helps you set up and manage CI for your applications. Continuous Delivery (CD) is a process by which code is built, tested, and deployed to one or more test and production environments. Deploying and testing in multiple environments drives quality. CI systems produce the deployable artifacts including infrastructure and apps. Automated release processes consume these artifacts to release new versions and fixes to existing systems. Monitoring and alerting systems run continually to drive visibility into the entire CD process. The Release service in TFS helps you set up and manage CD for your applications. Continuous Testing (CT) on-premises or in the cloud is the use of automated build-deploy-test workflows, with a choice of technologies and frameworks, that test your changes continuously in a fast, scalable, and efficient manner. ## Version control systems The starting point for configuring CI and CD for your applications is to have your source code in a version control system. TFS supports two forms of version control - Git and Team Foundation Version Control. The Build service integrates with both of these version control systems. Once you have configured CI, any changes you push to your version control repository will be automatically built and validated. You can also manage your source code in Subversion, Bitbucket Cloud, GitHub, or any other Git repository. The Build service integrates with all of these version control systems. ## Application types To configure CI, you create a build definition. A build definition is a representation of the automation process that you want to run to build and test your application. The automation process is defined as a collection of tasks. TFS has a number of tasks to build and test your application. For example, tasks exist to build.Net, Java, Node, Android, Xcode, and C++ applications. Similarly, there are tasks to run tests using a number of testing frameworks and services. You can also run command line, PowerShell, or Shell scripts in your automation. ## Deployment targets Once you have continuous integration in place, the next step is to create a release definition to automate the deployment of your application to one or more environments. This automation process is again defined as a collection of tasks. TFS supports deploying your application to virtual machines, containers, on-premises and cloud platforms, or PaaS services. You can also publish your mobile application to a store. ## Continuous testing Whether your app is on-premises or in the cloud, you can automate build-deploy-test workflows and choose the technologies and frameworks, then [test your changes continuously](ecosystems/dotnet-core.md#run-your-tests) in a fast, scalable, and efficient manner. * Maintain quality and find problems as you develop. Continuous testing with TFS ensures your app still works after every check-in and build, enabling you to find problems earlier by running tests automatically with each build. * Any test type and any test framework. Choose the test technologies and frameworks you prefer to use. * Rich analytics and reporting. When your build is done, review your test results to start resolving the problems you find. Rich and actionable build-on-build reports let you instantly see if your builds are getting healthier. But it's not just about speed - detailed and customizable test results measure the quality of your app. Now that you understand the basics, follow the quickstart to [create your first pipeline](create-first-pipeline.md). ======================= File: docs/organizations/settings/includes/open-process-admin-context-ts-only.md ======================= --- ms.topic: include --- <a id="open-process-wit"></a> ## Organization Settings > Process You create, manage, and make customizations to processes from **Organization settings > Process**. 1. Choose the![Azure DevOps logo](/azure/devops/media/icons/project-icon.png) Azure DevOps logo to open **Projects**. Then choose **Organization settings**. > [!div class="mx-imgBorder"] >![Open Organization settings](/azure/devops/media/settings/open-admin-settings-vert.png) 1. Under **Boards**, choose **Process**. > [!div class="mx-imgBorder"] >![Organization Settings > Process page](/azure/devops/organizations/settings/work/media/process/open-process-page-s150.png) > [!IMPORTANT] > If you don't see **Process**, you're working from on-premises Team Foundation Server. The **Process** page isn't supported. You must use the features supported for the on-premises XML process model as described in [Customize your work tracking experience](/azure/devops/reference/customize-work). ======================= File: docs/organizations/public/clone-git-repo-public.md ======================= <reponame>Chibuikekenneth/azure-devops-docs<filename>docs/organizations/public/clone-git-repo-public.md --- title: Clone a Git repository in a public project titleSuffix: Azure DevOps Services Public Project description: Create a local copy of a repo using Visual Studio or command line clone ms.technology: devops-public-projects ms.assetid: ms.author: sdanie author: steved0x ms.topic: conceptual ms.date: 02/14/2019 monikerRange: 'azure-devops' --- # Clone a Git repository in a public project [!INCLUDE [temp](includes/version-public-projects.md)] You can create a complete local copy of a Git repository from a public project by cloning it. Cloning a repo downloads all commits and branches in the repo and sets up a named relationship with the existing repo you cloned. If you are signed in as a member of the project, you can use this relationship to interact with the existing repo, pushing and pulling changes to share code with the public project team. > [!NOTE] > By default you have read-only access to the code in the repository. To perform operations such as forking, creating branches, and making pull requests, you must be [invited to contribute](invite-users-public.md). If you just want a copy of the code to review, instead of cloning you can [download the code](browse-code-public.md#download-code). <a name="clone_url"></a> ## Get the clone URL of the Git repo Before you can clone the repo from a public project, you'll need the clone URL. 1. To open a repository, choose **Repos>Files**. > [!div class="mx-imgBorder"] >![Open Repos>Files, anonymous user](media/browse-code/open-code-vert-brn.png) 2. Choose the repository you want to clone from the repository selector. > [!div class="mx-imgBorder"] >![Select repository](media/browse-code/select-repository-vert.png) 3. Choose **Clone**. In the Clone repository dialog, choose the![Clone URL](../../media/icons/copy-clone-icon.png) copy-clone icon to have the URL copied to your clipboard. Store it in a place where you can find it easily. > [!div class="mx-imgBorder"] >![Clone URL, new navigation](media/clone-git-repo-public/clone-url-vert.png) ## Clone the repo to your local computer > [!NOTE] > The steps in this section show how to clone a public project Git repo in Visual Studio when you are not a member of the project. For instructions for cloning a public project Git repository when you are signed in to Visual Studio as a member of the public project, see [Clone a Git repo](../../repos/git/clone.md). ### Clone using Visual Studio and Team Explorer 1. In Team Explorer, (1) open up the **Connect** page by selecting the **Connect** icon. (2) Choose **Clone** under **Local Git Repositories**, (3) enter the clone URL, verify your local folder in which to clone, and (4) select the **Clone** button. ![Connecting to Azure DevOps](media/clone-git-repo-public/clone-vs.png) 2. After cloning, you have a local Git repository containing the code of the repository you cloned. You can view and make local changes, but in order to push changes and make pull requests to the remote repository, you must be [invited to contribute](invite-users-public.md). ### Clone using the command line ### Prerequisites * Ensure you have installed the [Git command line package](https://git-scm.com/download) for your platform as well as the right [Git Credential Manager](../../repos/git/set-up-credential-managers.md) before continuing. You'll need a clone URL to tell Git what repository you want to clone to your computer. Use the URL you copied earlier during the [previous step](#clone_url) in this article. Pass this clone URL to `git clone` to make a local copy of the repo: ``` git clone https://dev.azure.com/public1/MyFirstProject/_git/MyGreatLibrary ``` `git clone` clones the repository from the URL in a folder under the current one. You can pass in a folder name after the URL to create the repo in a specific location, for example: ``` git clone https://dev.azure.com/public1/MyFirstProject/_git/MyGreatLibrary C:\Repos\MyGreatLibrary ``` ## Related articles * [Browse code, download code](browse-code-public.md) ======================= File: docs/reference/error/tf30032-ntpw-common-structure-component-no-connect-tfs.md ======================= --- title: TF30032-The New Team Project Wizard can't connect to TFS description: Occurs when the New Team Project Wizard is unable to connect to the application-tier {name} when creating a project. ms.technology: devops-agile ms.assetid: 889f7f5e-9610-47f4-b6a0-592325b75151 ms.author: kaelli author: KathrynEE ms.topic: Troubleshooting ms.date: 01/20/2017 --- # TF30032: The New Team Project Wizard common structure component could not connect to the Team Foundation Server {0}. [!INCLUDE [temp](../../includes/version-vsts-tfs-all-versions.md)] This error occurs when the New Team Project Wizard is unable to connect to the application-tier {*name*} when creating a project. An active connection cannot be made because of one of the following conditions: - A server in the Team Foundation deployment is incorrectly configured. This problem is especially common after a server move, failover, or other maintenance activity. - A critical file from the server {name} is missing. Because the connection to Team Foundation Server failed, the wizard could not create the project data objects on the application-tier server. ### To correct this error 1. Contact your Team Foundation Server administrator to verify that the server configuration is correct. Your administrator can verify by using the **/view** option of the **TfsAdmin ConfigureConnections** command to. For more information, see [Settings Command](https://msdn.microsoft.com/2b96fbbf-34c8-4500-82d8-724cc65dc9a4). 2. If the server configuration is correct, review the project creation log and follow any instructions provided. The log shows each action taken by the wizard at the time of the failure and may include additional details about the error. To open the log: 1. Start Notepad. 2. On the **File** menu, click **Open**. 3. Navigate to $:\Documents and Settings\\*user name*\Local Settings\Temp\Team Services_TeamProjectCreation_yyyy_mm_dd_hh_mm_ss.log. 4. Click **Open**. 5. On the **Edit** menu, click **Find**. 6. In the **Find what** dialog box, type **Exception** or **Error**, and then click **Find Next**. 7. Review the log entries to find network or file related issues. 3. If the problem persists, contact your Team Foundation Server administrator. ## Related articles - [Create a project](../../organizations/projects/create-project.md) ======================= File: docs/repos/tfvc/clean-up-files-when-users-leave.md ======================= <gh_stars>1-10 --- title: Clean Up Files When Users Leave titleSuffix: Azure Repos description: Clean Up Files When Users Leave ms.assetid: 7e8249cc-2933-4caa-8bee-ea93a3aff01a ms.technology: devops-code-tfvc ms.author: apawast author: apawast ms.topic: conceptual ms.date: 08/10/2016 monikerRange: '>= tfs-2015' --- # Clean Up Files When Users Leave #### Azure Repos | Azure DevOps Server 2019 | TFS 2018 | TFS 2017 | TFS 2015 | VS 2017 | VS 2015 | VS 2013 When a member leaves a team, version control administrators must correctly dispose of that member's files. **Required Permissions** To perform these procedures, you must be a member of the **Team Foundation Administrators** security group. For more information, see [Permissions and groups reference](../../organizations/security/permissions.md). ### To clean up version-controlled files after a team member leaves 1. Check in any files that are checked out to the team member who has left. > [!NOTE] > If the member's checked-out files do not need to be saved, omit this step. 2. Delete the workspaces of the member who has left. This operation can be performed only from the command line. For more information, see [Workspace Command](workspace-command.md). ## See Also #### Tasks [Remove a User From a Project or Project Collection](https://msdn.microsoft.com/library/ms253182) ======================= File: docs/integrate/previous-apis/packaging/packages.md ======================= <gh_stars>1-10 --- title: Packages | REST API Reference for VSTS description: Work with packages programmatically using the REST APIs for VSTS. ms.assetid: 1f8825e8-7916-488b-b71e-c807f1f5234d ms.date: 09/29/2016 ms.technology: devops-ecosystem monikerRange: '>= tfs-2015 < azure-devops' ms.topic: article ms.author: chcomley author: chcomley ms.date: 08/04/2016 --- # Packages [!INCLUDE [azure-devops](../_data/azure-devops-message.md)] [!INCLUDE [API_version](../_data/version2-preview1.md)] [!INCLUDE [disclaimer](../_data/disclaimer.md)] [!INCLUDE [GET_STARTED](../_data/get-started.md)] ## Get packages ```no-highlight GET https://{account}.feeds.VisualStudio.com/DefaultCollection/_apis/packaging/feeds/{feed}/packages?api-version={version} ``` | Parameter | Type | Default | Notes |:----------------------|:--------|:----------|:--------------------------------------------------------------------------------------------------- | URL | account | string | | VSTS organization | feed | string | | Name or ID of the feed | Query | packageNameQuery | string | | Include packages where the display name includes this query | normalizedPackageName | string | | Include the package where its normalized package name exactly matches this parameter. Must be used in conjunction with protocolType. Cannot be used in conjunction with packageNameQuery | protocolType | string | | The protocol type of the package e.g. NuGet | includeUrls | boolean | true | Include REST Urls with the response | includeAllVersions | boolean | false | Include minimum details of all packages, otherwise the latest packages is the only listed | includeDescription | boolean | false | Include descriptions on the version details | isListed | boolean?| null | True only displays listed packages (at least one listed version), False shows only delisted packages (packages with at least one delisted version), null shows all packages | getTopPackageVersions | boolean | false | Changes the behavior of top/skip to take the top package versions instead of top packages. Must be used in conjunction with includeAllVersions=true | $top | integer | 1000 | Get the top N packages (or package versions with getTopPackageVersions=true) | $skip | integer | 0 | Skip N packages (or package versions with getTopPackageVersions=true) | api-version | string | | [Version](../../concepts/rest-api-versioning.md) of the API to use #### Sample request ``` GET https://mytfsserver/DefaultCollection/_apis/packaging/feeds/EngineeringInternal/packages?api-version=2.0-preview ``` #### Sample response ```json { "count": 1, "value": [ { "id": "e3d6b8ad-9a15-40cf-ab6c-d08a409bba6b", "normalizedName": "feed.client", "name": "Feed.Client", "protocolType": "NuGet", "url": "https://mytfsserver/DefaultCollection/_apis/Packaging/Feeds/ebe02934-8b9a-419b-bd8d-0cd33d7c86f4/Packages/e3d6b8ad-9a15-40cf-ab6c-d08a409bba6b", "versions": [ { "id": "c2f2a3a8-517d-46c4-ad66-a1a7ec6d20d2", "normalizedVersion": "0.1.4", "version": "0.1.4", "isLatest": true, "isListed": true, "storageId": "32D68E06C0EA73CB32BA03071C99F1B351C86D9E3384B02D04210C9ACB9F2BA300" } ], "_links": { "self": { "href": "https://mytfsserver/DefaultCollection/_apis/Packaging/Feeds/ebe02934-8b9a-419b-bd8d-0cd33d7c86f4/Packages/e3d6b8ad-9a15-40cf-ab6c-d08a409bba6b" }, "feed": { "href": "https://mytfsserver/DefaultCollection/_apis/Packaging/Feeds/ebe02934-8b9a-419b-bd8d-0cd33d7c86f4" }, "versions": { "href": "https://mytfsserver/DefaultCollection/_apis/Packaging/Feeds/ebe02934-8b9a-419b-bd8d-0cd33d7c86f4/Packages/e3d6b8ad-9a15-40cf-ab6c-d08a409bba6b/Versions" } } } ] } ``` ## Get a package ```no-highlight GET https://{account}.feeds.VisualStudio.com/DefaultCollection/_apis/packaging/feeds/{feed}/packages/{packageId}?api-version={version} ``` | Parameter | Type | Default | Notes |:----------------------|:--------|:----------|:--------------------------------------------------------------------------------------------------- | URL | account | string | | VSTS organization | feed | string | | Name or ID of the feed | packageId | guid | | ID of the package | Query | includeUrls | boolean | true | Include REST Urls with the response | includeAllVersions | boolean | false | Include minimum details of all packages, otherwise the latest packages is the only listed | includeDescription | boolean | false | Include descriptions on the version details | api-version | string | | [Version](../../concepts/rest-api-versioning.md) of the API to use #### Sample request ``` GET https://mytfsserver/DefaultCollection/_apis/packaging/feeds/EngineeringInternal/packages/e3d6b8ad-9a15-40cf-ab6c-d08a409bba6b/?api-version=2.0-preview ``` #### Sample response ```json { "id": "e3d6b8ad-9a15-40cf-ab6c-d08a409bba6b", "normalizedName": "feed.client", "name": "Feed.Client", "protocolType": "NuGet", "url": "https://mytfsserver/DefaultCollection/_apis/Packaging/Feeds/ebe02934-8b9a-419b-bd8d-0cd33d7c86f4/Packages/e3d6b8ad-9a15-40cf-ab6c-d08a409bba6b", "versions": [ { "id": "c2f2a3a8-517d-46c4-ad66-a1a7ec6d20d2", "normalizedVersion": "0.1.4", "version": "0.1.4", "isLatest": true, "isListed": true, "storageId": "32D68E06C0EA73CB32BA03071C99F1B351C86D9E3384B02D04210C9ACB9F2BA300" } ], "_links": { "self": { "href": "https://mytfsserver/DefaultCollection/_apis/Packaging/Feeds/ebe02934-8b9a-419b-bd8d-0cd33d7c86f4/Packages/e3d6b8ad-9a15-40cf-ab6c-d08a409bba6b" }, "feed": { "href": "https://mytfsserver/DefaultCollection/_apis/Packaging/Feeds/ebe02934-8b9a-419b-bd8d-0cd33d7c86f4" }, "versions": { "href": "https://mytfsserver/DefaultCollection/_apis/Packaging/Feeds/ebe02934-8b9a-419b-bd8d-0cd33d7c86f4/Packages/e3d6b8ad-9a15-40cf-ab6c-d08a409bba6b/Versions" } } } ``` ## Get all package versions ```no-highlight GET https://{account}.feeds.VisualStudio.com/DefaultCollection/_apis/packaging/feeds/{feed}/packages/{packageId}/versions?api-version={version} ``` | Parameter | Type | Default | Notes |:----------------------|:--------|:----------|:--------------------------------------------------------------------------------------------------- | URL | account | string | | VSTS organization | feed | string | | Name or ID of the feed | packageId | guid | | ID of the package | Query | includeUrls | boolean | true | Include REST Urls with the response | isListed | boolean?| null | True only displays listed packages (at least one listed version), False shows only delisted packages (packages with at least one delisted version), null shows all packages | api-version | string | | [Version](../../concepts/rest-api-versioning.md) of the API to use #### Sample request ``` GET https://mytfsserver/DefaultCollection/_apis/packaging/feeds/EngineeringInternal/packages/e3d6b8ad-9a15-40cf-ab6c-d08a409bba6b/versions?api-version=2.0-preview ``` #### Sample response ```json { "count": 2, "value": [ { "author": "Microsoft", "description": "Feed.Client", "publishDate": "2016-05-05T15:41:00.3343232Z", "protocolMetadata": { "schemaVersion": 1, "data": { "copyright": "© Microsoft Corporation. All rights reserved.", "requireLicenseAcceptance": false } }, "tags": [], "url": "https://mytfsserver/DefaultCollection/_apis/Packaging/Feeds/ebe02934-8b9a-419b-bd8d-0cd33d7c86f4/Packages/e3d6b8ad-9a15-40cf-ab6c-d08a409bba6b/Versions", "dependencies": [ { "packageName": "Microsoft.AspNet.WebApi.Client", "versionRange": "[5.2.2, )" }, { "packageName": "Microsoft.AspNet.WebApi.Core", "versionRange": "[5.2.2, )" }, { "packageName": "Newtonsoft.Json", "versionRange": "[6.0.5, )" }, { "packageName": "Vssf.Client", "versionRange": "[14.83.0-preview, )" } ], "_links": { "self": { "href": "https://mytfsserver/DefaultCollection/_apis/Packaging/Feeds/ebe02934-8b9a-419b-bd8d-0cd33d7c86f4/Packages/e3d6b8ad-9a15-40cf-ab6c-d08a409bba6b/Versions" }, "feed": { "href": "https://mytfsserver/DefaultCollection/_apis/Packaging/Feeds/ebe02934-8b9a-419b-bd8d-0cd33d7c86f4" }, "package": { "href": "https://mytfsserver/DefaultCollection/_apis/Packaging/Feeds/ebe02934-8b9a-419b-bd8d-0cd33d7c86f4/Packages/e3d6b8ad-9a15-40cf-ab6c-d08a409bba6b" } }, "id": "c2f2a3a8-517d-46c4-ad66-a1a7ec6d20d2", "normalizedVersion": "0.1.4", "version": "0.1.4", "isLatest": true, "isListed": true, "storageId": "32D68E06C0EA73CB32BA03071C99F1B351C86D9E3384B02D04210C9ACB9F2BA300" }, { "author": "Microsoft", "description": "Feed.Client", "publishDate": "2016-05-05T15:40:25.6265392Z", "protocolMetadata": { "schemaVersion": 1, "data": { "requireLicenseAcceptance": false } }, "tags": [], "url": "https://mytfsserver/DefaultCollection/_apis/Packaging/Feeds/ebe02934-8b9a-419b-bd8d-0cd33d7c86f4/Packages/e3d6b8ad-9a15-40cf-ab6c-d08a409bba6b/Versions", "dependencies": [ { "packageName": "Microsoft.AspNet.WebApi.Client", "versionRange": "[5.2.2, )" }, { "packageName": "Microsoft.AspNet.WebApi.Core", "versionRange": "[5.2.2, )" }, { "packageName": "Newtonsoft.Json", "versionRange": "[6.0.5, )" }, { "packageName": "Vssf.Client", "versionRange": "[14.81.0-preview, )" } ], "_links": { "self": { "href": "https://mytfsserver/DefaultCollection/_apis/Packaging/Feeds/ebe02934-8b9a-419b-bd8d-0cd33d7c86f4/Packages/e3d6b8ad-9a15-40cf-ab6c-d08a409bba6b/Versions" }, "feed": { "href": "https://mytfsserver/DefaultCollection/_apis/Packaging/Feeds/ebe02934-8b9a-419b-bd8d-0cd33d7c86f4" }, "package": { "href": "https://mytfsserver/DefaultCollection/_apis/Packaging/Feeds/ebe02934-8b9a-419b-bd8d-0cd33d7c86f4/Packages/e3d6b8ad-9a15-40cf-ab6c-d08a409bba6b" } }, "id": "b8a2a277-f77b-4ef2-acfd-0c0e550af5f7", "normalizedVersion": "0.1.1", "version": "0.1.1", "isLatest": false, "isListed": true, "storageId": "BC547A2DDC1217DCD0EE1998A5C2410F0559B5746CCC37BAB2B8A21D88BE594400" } ] } ``` ## Get a package version ```no-highlight GET https://{account}.feeds.VisualStudio.com/DefaultCollection/_apis/packaging/feeds/{feed}/packages/{packageId}/versions/{versionId}?api-version={version} ``` | Parameter | Type | Default | Notes |:----------------------|:--------|:----------|:--------------------------------------------------------------------------------------------------- | URL | account | string | | VSTS organization | feed | string | | Name or ID of the feed | packageId | guid | | ID of the package | versionId | guid | | ID of the package version | Query | includeUrls | boolean | true | Include REST Urls with the response | api-version | string | | [Version](../../concepts/rest-api-versioning.md) of the API to use #### Sample request ``` GET https://mytfsserver/DefaultCollection/_apis/packaging/feeds/EngineeringInternal/packages/e3d6b8ad-9a15-40cf-ab6c-d08a409bba6b/versions/b8a2a277-f77b-4ef2-acfd-0c0e550af5f7?api-version=2.0-preview ``` #### Sample response ```json { "author": "Microsoft", "description": "Feed.Client", "publishDate": "2016-05-05T15:40:25.6265392Z", "protocolMetadata": { "schemaVersion": 1, "data": { "requireLicenseAcceptance": false } }, "tags": [], "url": "https://mytfsserver/DefaultCollection/_apis/Packaging/Feeds/ebe02934-8b9a-419b-bd8d-0cd33d7c86f4/Packages/e3d6b8ad-9a15-40cf-ab6c-d08a409bba6b/Versions", "dependencies": [ { "packageName": "Microsoft.AspNet.WebApi.Client", "versionRange": "[5.2.2, )" }, { "packageName": "Microsoft.AspNet.WebApi.Core", "versionRange": "[5.2.2, )" }, { "packageName": "Newtonsoft.Json", "versionRange": "[6.0.5, )" }, { "packageName": "Vssf.Client", "versionRange": "[14.81.0-preview, )" } ], "_links": { "self": { "href": "https://mytfsserver/DefaultCollection/_apis/Packaging/Feeds/ebe02934-8b9a-419b-bd8d-0cd33d7c86f4/Packages/e3d6b8ad-9a15-40cf-ab6c-d08a409bba6b/Versions" }, "feed": { "href": "https://mytfsserver/DefaultCollection/_apis/Packaging/Feeds/ebe02934-8b9a-419b-bd8d-0cd33d7c86f4" }, "package": { "href": "https://mytfsserver/DefaultCollection/_apis/Packaging/Feeds/ebe02934-8b9a-419b-bd8d-0cd33d7c86f4/Packages/e3d6b8ad-9a15-40cf-ab6c-d08a409bba6b" } }, "id": "b8a2a277-f77b-4ef2-acfd-0c0e550af5f7", "normalizedVersion": "0.1.1", "version": "0.1.1", "isLatest": false, "isListed": true, "storageId": "BC547A2DDC1217DCD0EE1998A5C2410F0559B5746CCC37BAB2B8A21D88BE594400" } ``` ## Protocol Endpoints We intend to provide a mechanism for retrieving protocol-specific packaging endpoints. Until that mechanism exists, you may use a convention-based approach to convert a feed response into a NuGet endpoint URL. For example, consider this feed response: #### Sample request ``` GET https://mytfsserver/DefaultCollection/_apis/packaging/feeds/EngineeringInternal?api-version=2.0-preview.1 ``` #### Sample response ```json { "id": "64ccc8b7-705d-48f7-a91c-d9be3cd36468", "name": "EngineeringInternal", "description": "Contains packages internal to the engineering organization", "url": "https://mytfsserver/DefaultCollection/_apis/Packaging/Feeds/64ccc8b7-705d-48f7-a91c-d9be3cd36468", "_links": { "self": { "href": "https://mytfsserver/DefaultCollection/_apis/Packaging/Feeds/64ccc8b7-705d-48f7-a91c-d9be3cd36468" } } } ``` To construct the [NuGet v3](https://docs.nuget.org/) endpoint URL, take the organization name *contoso* and feed name *EngineeringInternal* and insert them into this URL template: `https://{account}.pkgs.visualstudio.com/DefaultCollection/_packaging/{feedName}/nuget/v3/index.json` For example, the NuGet v3 endpoint for the feed shown above is `https://contoso.pkgs.visualstudio.com/DefaultCollection/_packaging/EngineeringInternal/nuget/v3/index.json`. To construct the NuGet v2 endpoint URL, take the organization name *contoso* and feed name *EngineeringInternal* and insert them into this URL template: `https://{account}.pkgs.visualstudio.com/DefaultCollection/_packaging/{feedName}/nuget/v2` For example, the NuGet v2 endpoint for the feed shown above is `https://contoso.pkgs.visualstudio.com/DefaultCollection/_packaging/EngineeringInternal/nuget/v2`. ======================= File: docs/extend/reference/client/api/TFS/Build/Contracts/BuildBadge.md ======================= <filename>docs/extend/reference/client/api/TFS/Build/Contracts/BuildBadge.md --- title: TFS/Build/Contracts BuildBadge API | Extensions for Azure DevOps Services description: Data representation of a build badge. ms.assetid: ddd4dcfd-24b6-a094-ee50-a91526674d2c ms.technology: devops-ecosystem generated: true author: chcomley ms.topic: article ms.author: chcomley ms.date: 08/04/2016 --- # BuildBadge Module path: `TFS/Build/Contracts` ### Members * `buildId`: number. Build id, if exists that this badge corresponds to * `imageUrl`: string. Self Url that generates SVG ======================= File: docs/pipelines/agents/includes/agent-queues-tab/agent-queues-tab-tfs-2017.md ======================= --- ms.topic: include ms.technology: devops-cicd ms.manager: mijacobs ms.author: sdanie author: steved0x ms.date: 02/12/2020 --- Navigate to your project and choose **Settings** (gear icon) > **Agent Queues**. ![Choose settings, Agent Queues](../../media/agent-queues-tab/settings-agent-queues-2017.png) ======================= File: docs/artifacts/includes/availability-symbols.md ======================= <reponame>Chibuikekenneth/azure-devops-docs --- ms.topic: include ms.technology: devops-cicd ms.manager: mijacobs ms.author: rabououn author: ramiMSFT ms.date: 02/19/2020 --- > [!NOTE] > A symbol server is available with **Azure Artifacts** in Azure DevOps Services and works best with **Visual Studio 2017 Update 4 or later**. **Team Foundation Server** users and users without the **Azure Artifacts** extension can publish symbols to a file share using a [build task](/azure/devops/pipelines/tasks/build/index-sources-publish-symbols). ======================= File: docs/pipelines/release/integrate-jenkins-pipelines-aks.md ======================= <reponame>Chibuikekenneth/azure-devops-docs --- title: Deploy to Kubernetes on AKS with Jenkins description: Set up continuous integration (CI) and continuous deployment (CD) with Kubernetes for your apps using Jenkins, Azure Container Service (AKS), and Azure Pipelines ms.topic: tutorial ms.author: mlearned author: mlearned ms.reviewer: nicolela ms.custom: "mvc, seodec18" ms.date: 04/17/2018 monikerRange: '>= tfs-2015' --- # Tutorial: Deploy to Kubernetes on Azure Container Service (AKS) with Jenkins CI and Azure Pipelines CD [!INCLUDE [version-tfs-2015-rtm](../includes/version-tfs-2015-rtm.md)] ::: moniker range="<= tfs-2018" [!INCLUDE [temp](../includes/concept-rename-note.md)] ::: moniker-end Azure Pipelines provides integration with Jenkins so that you can: * Continue to use your existing investments in Jenkins. * Create a single release pipeline using Azure Pipelines that deploys to a variety of Azure targets. In this tutorial, you use Jenkins for Continuous Integration (CI) and Azure Pipelines for Continuous Delivery (CD) to deploy a **Spring Boot app** to an **Azure Container Service (AKS) Kubernetes cluster**. You will: > [!div class="checklist"] > * Get the sample app > * Configure the sample app to build and push a Docker image to your ACR > * Configure the sample app to include a YAML file used for deploying to your AKS cluster > * Configure Jenkins credentials to connect to Azure Pipelines > * Configure Jenkins Maven global settings > * Create Jenkins Service Hooks in Azure Pipelines > * Configure a Jenkins CI build with Azure Pipelines integration > * Install the Release Management Utility tasks Azure Pipelines extension > * Create an Azure Pipelines release pipeline for CD to Azure > * Test the CI/CD pipeline with a pull request > * View the deployed sample app > * Delete your AKS cluster ## Prerequisites * An Azure DevOps organization. If you don't have one, you can [create one for free](https://go.microsoft.com/fwlink/?LinkId=307137). If your team already has one, then make sure you are an administrator of the project you want to use. * An Azure subscription. You can get one free from [Visual Studio Dev Essentials](https://visualstudio.microsoft.com/dev-essentials/). * The [Azure Command-Line Interface (CLI)](/cli/azure/index?view=azure-cli-latest). * You need a Spring Boot app. You can fork the sample app found [here](https://github.com/spring-guides/gs-spring-boot-docker.git). * You need an Azure Container Registry (ACR). You can follow steps to deploy an ACR and login to the registry using the Azure CLI via the steps [here](/azure/aks/tutorial-kubernetes-prepare-acr). * An AKS cluster. You can follow the steps for creating this [here](/azure/aks/tutorial-kubernetes-deploy-cluster). * Access to a Jenkins server with Maven and the VSTS plugin configured. If you have not yet created a Jenkins server, see [Create a Jenkins master on an Azure Virtual Machine](/azure/jenkins/install-jenkins-solution-template). Also, the following Jenkins plugins must be installed: * **VS Team Services Continuous Deployment** plugin. You can find additional information about the **TFS plugin** [here](https://github.com/jenkinsci/tfs-plugin). * **Config File Provider** plugin. You can find additional information about the **Config File plugin** [here](https://wiki.jenkins.io/display/JENKINS/Config+File+Provider+Plugin). * **Maven Integration** plugin. You can find additional information about the **Maven Integration plugin** [here](https://plugins.jenkins.io/maven-plugin). ## Get the sample app You need an app stored in a Git repository. You use this app to build and deploy. For this tutorial, we recommend you use [this Spring Boot sample app available from GitHub](https://github.com/spring-guides/gs-spring-boot-docker.git). This tutorial uses a Spring Boot sample application that is configured for deployment to an AKS cluster. If you want to work with your own repository, you should configure a similar sample. 1. In Azure Repos, on the **Code** page for your Azure Repos project, select the option to **Import repository**. 2. In the **Import a Git repository** dialog box, paste the following URL into the **Clone URL** text box. ``` https://github.com/spring-guides/gs-spring-boot-docker ``` 3. Click **Import** to copy the sample code into your Git repo. 4. Select **Clone** at the top right, and keep the **clone URL** for future steps in this tutorial. ## Configure the sample app to build and push a Docker image to your ACR The [Spotify Dockerfile Maven plugin](https://github.com/spotify/dockerfile-maven) is used to build and push a Docker image to a registry, such as ACR. The Spring Boot sample app's Maven **pom.xml** file is already configured to use this plugin. You will find the **pom.xml** file in your repository in the folder named **complete**. You must update the **pom.xml** file with your ACR's login server: 1. Navigate to your Azure Repos project. Select the **Code** tab. 1. In the code explorer, expand the **complete** folder and select the **pom.xml** file. 1. In the **Contents** pane that shows the contents of the **pom.xml** file, select the **Edit** button. 1. Update the `<properties>` collection in the **pom.xml** with the login server value for your ACR. The login server is the name of your ACR appended with *.azurecr.io*. For example, **yourACRName.azurecr.io**. ```xml <properties> <docker.image.prefix>wingtiptoysregistry.azurecr.io</docker.image.prefix> <java.version>1.8</java.version> </properties> ``` 1. Update the **com.spotify** plugin in the **pom.xml** file so that the `<configuration>` section includes the tag for the Docker image that will be built and pushed to your ACR. The tag will be set to the current Jenkins build id. Also, add the **useMavenSettingsForAuth** setting to the configuration so that in a later step, you can configure Maven to authenticate with your ACR which is a private registry. ```xml <plugin> <groupId>com.spotify</groupId> <artifactId>dockerfile-maven-plugin</artifactId> <version>1.3.4</version> <configuration> <repository>${docker.image.prefix}/${project.artifactId}</repository> <tag>${env.BUILD_NUMBER}</tag> <useMavenSettingsForAuth>true</useMavenSettingsForAuth> <buildArgs> <JAR_FILE>target/${project.build.finalName}.jar</JAR_FILE> </buildArgs> </configuration> </plugin> ``` 1. Select **Commit** and choose to commit these changes to the **master** branch. ## Configure the sample app to include a YAML file used for deploying to your AKS cluster The YAML file contains deployment settings for pulling the docker image from the ACR. Update this file to include the name of your ACR: 1. Navigate to your Azure Repos project. Select the **Code** tab. 1. In the code explorer, select the **complete** folder's ellipsis button to open the context menu that shows more actions. 1. From the context menu, select **New**, **File**. 1. Name the file **K8sDeploy.yaml** and select **Create**. 1. Copy and paste the following contents into the **K8sDeploy.yaml** file. Ensure the image prefix `<yourACRName>` is replaced with the name of your ACR appended with *.azurecr.io*. Also, notice that the image is tagged with **__Build.BuildId__**. This is a token that will be automatically replaced during the Azure Pipelines release so that it's set to the current Jenkins build id. For example, if the current Jenkins build id is 5, the full name of an image that will be pulled during the Azure Pipelines release will look similar to: yourACRName.azurecr.io/gs-spring-boot-docker:5. ```yaml apiVersion: extensions/v1beta1 kind: Deployment metadata: name: gs-spring-boot-docker spec: replicas: 3 template: metadata: labels: app: gs-spring-boot-docker spec: containers: - image: <yourACRName>.azurecr.io/gs-spring-boot-docker:__Build.BuildId__ name: gs-spring-boot-docker imagePullPolicy: Always ports: - containerPort: 8080 imagePullSecrets: - name: regsecret --- apiVersion: v1 kind: Service metadata: name: gs-spring-boot-docker spec: ports: - protocol: TCP port: 80 targetPort: 8080 selector: app: gs-spring-boot-docker type: LoadBalancer ``` 1. Select **Commit** and choose to commit these changes to the **master** branch. ## Configure Jenkins credentials to connect to Azure Pipelines You must configure credentials for connecting to Azure Pipelines. When using credentials to connect to Azure Pipelines, it is a best practice to use a **personal access token (PAT)**. You also need to create a Jenkins credential to use in your Jenkins build jobs. > [!NOTE] > Ensure the PAT you use for the following steps contains the **Release (read, write, execute and manage), Code (read), Build (read and execute) permissions in Azure Pipelines**. 1. Create a PAT in your Azure Pipelines account. Jenkins requires this information to access your Azure DevOps organization. Ensure you **store** the token information for upcoming steps in this section. Read [How do I create a personal access token for Azure Pipelines and TFS](../../organizations/accounts/use-personal-access-tokens-to-authenticate.md) to learn how to generate a PAT, or use an existing PAT if you have one. 1. Open your Jenkins account and select **Credentials**, **System**, and then choose **Add Domain**. 1. Enter a **name**, **description**, and then select **Add** **hostname**. 1. In the **Include** text box, enter ```\dev.azure.com/*``` to enable this credential for all Azure DevOps organizations. You can optionally enter your specific Azure DevOps organization. 1. Select **Ok**. You will see a message about empty credentials. Select the link for **adding some credentials**. 1. For **Kind**, choose **Username with password**. Enter the **Username** and the **PAT** you created earlier for **Password**. Select **Ok**. ## Configure Jenkins Maven global settings Since your ACR is a private registry, you must configure the user name and password for your ACR in Maven's global settings in Jenkins. This will authenticate Maven so that it can push images to your ACR during a build. 1. Retrieve the password for your ACR using the Azure CLI. Replace `<yourACRName>` with the name of your registry. ``` az acr credential show --name <acrName> --query passwords[0] ``` 1. Navigate to your Jenkins server. Select **Manage Jenkins** and then select the **Managed files** link. 1. To create the Maven **settings.xml** file the first time, select the **Add a new Config** link. 1. Select the **Maven settings.xml** radio button and select the **Submit** button. 1. Enter a **Name** for the file. 1. In the **Content** window, update the `<servers>` section of the contents to include the name of your ACR and its password. For example: ```xml <server> <id>yourACRName.azurecr.io</id> <username>yourACRName</username> <password><PASSWORD>> </server> ``` 1. Select the **Submit** button to save the settings. ## Configure a Jenkins CI build with Azure Pipelines integration You create a Jenkins build job to use the source code stored in your Azure Repos repository and execute a basic build. Ensure your Jenkins server has **Maven** installed and configured. You also create triggers to enable CI builds when code changes are pushed to the repository, and a CD trigger to initiate an Azure Pipelines release after the Jenkins build completes via a post build action. 1. Navigate to your Jenkins server. Click **New Item**. Enter an **item name**. 1. Choose **Maven project**. Select **OK**. 1. In the **Source Code Management** tab, select **Git** and enter the **clone URL** you saved earlier for the Azure Repos **Repository URL** and the branch containing your app code. If you are using Team Foundation Server, you can choose the option for **Team Foundation Version Control (TFVC)**. ![Add a repo to your build](media/integrate-jenkins-vsts-cicd/jenkins-git.png) 1. Select the **Credentials** drop down and choose the credential you created earlier. You should successfully authenticate to your Azure Repos repository and not receive errors before continuing. If you see errors, you likely have an issue with your credentials and Azure DevOps **PAT**. 1. Select the **Build Triggers** tab, then **tick** the checkboxes for **Build when a change is pushed to TFS/Team Services** and **Build when a change is pushed to a TFS pull request**. These two options rely on **Azure Pipelines Service Hooks** which you create in the next section. 1. Select the **Build** tab, set the **Root POM** to the relative path to the sample app's **pom.xml**: **complete/pom.xml**. 1. Enter **clean package** for **Goals**. 1. Select the **Advanced...** button. Set the **Settings file** to **provided settings.xml** and set **Provided Settings** to the name of the Maven settings.xml file that you created earlier. 1. Select the **Post-build Actions** tab. Choose **Add post-build action**, then select **Archive the artifacts**. 1. For **Files to archive** enter the relative path to the Kubernetes YAML deployment file: **complete/K8sDeploy.yaml**. 1. Select the **Post-build Actions** tab. Choose **Add post-build action**, then select **Trigger release in TFS/Team Services**. 1. Enter a **Collection URL**. An example is `https://dev.azure.com/{your-organization}/DefaultCollection` 1. Enter the **project** and choose a **release pipeline** name. Store the **release pipeline** name since it is needed in later steps of this tutorial. 1. Enter the **username** and **PAT** you created earlier. 1. **Save** the Jenkins project. ## Create a Jenkins and AKS service connection in Azure Pipelines You configure a Jenkins service connection to allow Azure Pipelines to connect to your Jenkins server. You also need to configure an AKS service connection to allow Azure Pipelines to access your AKS cluster to configure deployment. 1. Open the **Services** page in Azure Pipelines, open the **New service connection** list, and choose **Jenkins**. ![Add a Jenkins connection](media/integrate-jenkins-vsts-cicd/add-jenkins-endpoint.png) 1. Enter a name for the connection. 1. Enter the URL of your Jenkins server, and if using **http** tick the **Accept untrusted SSL certificates** option. An example URL is: `http://{YourJenkinsURL}.westcentralus.cloudapp.azure.com` 1. Enter the **user name and password** for your Jenkins account. 1. Choose **Verify connection** to check that the information is correct. 1. Choose **OK** to create the service connection. Add a second service connection for the AKS cluster. 1. Opening the **New service connection** list, and choose **Kubernetes**. 1. Enter a name for the connection. 1. Set the **Server URL** to the cluster's fully qualified domain name, such as **http:\//yourAKSCluster-yourResourceGroup-e65186-1e0d187e.hcp.eastus.azmk8s.io**. Retrieve the fully qualified domain name using the Azure CLI. Replace `<yourResourceGroup>` with the name of the resource group that contains the AKS cluster. Replace `<yourAKSCluster>` with the name of the AKS cluster. ``` az aks show --resource-group <yourResourceGroup> --name <yourAKSCluster> --query fqdn ``` 1. Set the **KubeConfig** to the access credentials for the AKS cluster. Use the Azure CLI to get these credentials: ``` az aks get-credentials --resource-group <yourResourceGroup> --name <yourAKSCluster> ``` This command will get the access credentials for the AKS cluster. Navigate to the **.kube** folder under your home directory, such as **C:\Users\YOUR_HOMEDIR\.kube**. Copy the contents of the **config** file and paste it in the **Kubernetes Connection** window. Select **OK** to create the service connection. ## Create Jenkins Service Hooks in Azure Pipelines You must also configure two Jenkins service hooks so you can execute CI builds via automated triggers for both simple commits as well as pull requests to your Azure Repos Git repository. 1. From the **Service Hooks** page in Azure Pipelines, Select the **+** to add a new service and choose **Jenkins**. Select **next**. 1. Choose **Code pushed** for the type of event trigger. Select your **code repository** that contains the sample application you imported earlier. Select **Next**. 1. Enter the URL of your Jenkins server. An example is below. `http://{YourJenkinsURL}.westcentralus.cloudapp.azure.com` 1. Enter the **user name and password** for your Jenkins account. 1. Select the Jenkins build you created earlier. 1. Choose **Test** to check that the information is correct. 1. Choose **Finish** to create the service connection. 1. Repeat the steps in this section to create another **service hook** for the **pull request merge attempted** trigger type. This will allow either simple commits to the repository as well as pull requests to both trigger the Jenkins build. ## Install the Release Management Utility tasks Azure Pipelines extension A release pipeline specifies the steps that Azure Pipelines executes to deploy the app. In this example, you deploy your app that originates from the Jenkins CI system. You deploy to a Docker image running Tomcat and a Spring Boot app to an AKS cluster. Before you create the release pipeline, you need to install an Azure Pipelines extension that will be used to replace the **K8sDeploy.yaml** file's **__Build.BuildId__** token with the current Jenkins build id. 1. In your Azure DevOps organization, on the top right-hand side of the browser, Select the **Browse Marketplace** menu item. (The icon appears as a shopping bag.) 2. Search for the **Release Management Utility Tasks** extension provided by **Microsoft DevLabs**. The extension includes the **Tokenizer** utility. 3. Select the **Get it free** button. 4. Select your Azure DevOps organization and select the **Install** button to install the extension. 5. After the extension is installed, select the **Proceed to Organization** button and navigate back to your Azure DevOps project. ## Create an Azure Pipelines release pipeline for CD to Azure 1. Open **Releases** in **Azure Pipelines**, and choose **Create release pipeline**. 1. Select the **Empty** template by choosing **Start with an empty pipeline**. 1. In the **Artifacts** section, click on **+ Add Artifact** and choose **Jenkins** for **Source type**. Select your Jenkins service connection. Then select the Jenkins source job and choose **Add**. Add two tasks to the release pipeline. The first task updates the **K8sDeploy.yaml** file to pull the image tagged with the current Jenkins build id. 1. Next to the **1 job, 0 stages** link, select the **+** on the **Agent Job** to add a task to the job. 1. Search for the **Tokenize with XPath/Regular expressions** task which was added with the extension that was installed in the previous step. Select **Add** to add the task. 1. Set the **Source filename** to the **K8sDeploy.yaml** that is archived by the Jenkins job during the build. This task automatically replaces the **__Build.BuildId__** token with the current Jenkins build id. The second task deploys to the AKS cluster: 1. Select the **+** button to add a second task. Search for the **Deploy to Kubernetes** task. Select **Add** to add the task. 1. Set the **Kubernetes Service Connection** to the name of the service connection that you created for the AKS cluster. 1. Set the **Command** to **apply**. 1. Select the **Use Configuration files** check box and set the **Configuration File** to the **K8sDeploy.yml** file. 1. Expand the **Container Registry Details** section of the task. 1. Set **Container Registry type** to **Azure Container Registry**. 1. Set **Azure subscription** to your subscription. If you do not have an existing Azure connection in Azure Pipelines, you can follow the steps [here](../library/connect-to-azure.md) to create one. 1. Set **Azure Container Registry** to the name of your ACR. 1. Set **Secret name** to the secret provided in the **K8sDeploy.yaml** file which is named **regsecret**. This is the name of an object in the AKS cluster that is used to store an authentication token. The cluster uses this token to authenticate to the ACR to pull images. 1. Ensure the **name** for your release pipeline matches the same name you chose earlier during the **Create a Jenkins service connection and service hooks in Azure Pipelines** steps. 1. Click **Save**, and then click **OK** to save the release pipeline. ## Test the CI/CD pipeline with a pull request You can initiate the CI build and the subsequent CD deployment to Azure by completing a pull request into your master branch. The Jenkins build will initiate due to the service hook you set up earlier, and the Jenkins post build action will initiate an Azure Pipelines release which will deploy your app to the Azure App Service. 1. Navigate to **Code** in Azure Repos, then select your **repository**. 1. Select **New branch** to create a branch from the master branch. Enter a **name** for your new branch, and then select **Create branch**. 1. Select your new branch, then navigate to the **complete/src/main/java/hello/Application.java** file. 1. Select **Edit**, then make a change to the message displayed in the **home()** method and **Commit** your changes. 1. Select **Pull Requests**, then select **New Pull Request**. Select **Create** to issue a pull request from your branch to master. 1. Select **Approve**, then select **Complete**, then **Complete Merge**. This code change will initiate a CI build in Jenkins. 1. Navigate to your **Jenkins dashboard** and examine the build that is executing. Once it finishes, a new Docker image will be pushed to your ACR that is tagged with the current Jenkins build id. You can then navigate to Azure Pipelines to watch the **Release Pipeline** execute. In a few moments, the Docker image for the current Jenkins build will be deployed to your AKS cluster. You are now using Jenkins CI builds with an Azure Repos code repository and an Azure Pipelines release pipeline to perform CI/CD to **Azure Container Services (AKS)**. You can easily track your code changes and deployments via the rich reporting capabilities of Azure Pipelines, and leverage Jenkins to execute CI builds. ## View the deployed sample app Once the app is deployed to the AKS cluster, you can query the external IP address using **kubectl**, the Kubernetes command-line client. You can learn how to install and connect **kubectl** to your AKS Cluster by following [these steps](/azure/aks/tutorial-kubernetes-deploy-cluster#install-the-kubernetes-cli). 1. Use the following command for querying the external IP address for the deployed app: ``` kubectl get svc -w ``` **kubectl** will display the internal and external IP addresses; for example: ``` NAME CLUSTER-IP EXTERNAL-IP PORT(S) AGE kubernetes 10.0.0.1 <none> 443/TCP 19h gs-spring-boot-docker 10.0.242.8 172.16.58.3 80:31215/TCP 3m ``` 1. Use the external IP address to open the sample app in a web browser. ## Delete your AKS cluster When your AKS cluster is no longer needed, you can use the `az group delete` command to remove the resource group, which will remove all of its related resources; for example: ```azurecli az group delete --name <yourAKSCluster> --yes --no-wait ``` ## Next Steps In this tutorial, you automated the deployment of an app to Azure using Jenkins build and Azure Pipelines for release. You learned how to: > [!div class="checklist"] > * Get the sample app > * Configure the sample app to build and push a Docker image to your ACR > * Configure the sample app to include a YAML file used for deploying to your AKS cluster > * Configure Jenkins credentials to connect to Azure Pipelines > * Configure Jenkins Maven global settings > * Create Jenkins Service Hooks in Azure Pipelines > * Configure a Jenkins CI build with Azure Pipelines integration > * Install the Release Management Utility tasks Azure Pipelines extension > * Create an Azure Pipelines release pipeline for CD to Azure > * Test the CI/CD pipeline with a pull request > * View the deployed sample app > * Delete your AKS cluster > [!div class="nextstepaction"] > [Integrate your Jenkins CI jobs with Azure Pipelines](integrate-jenkins-pipelines-cicd.md) > [Deploy to Kubernetes with Fabric8](/java/azure/spring-framework/deploy-spring-boot-java-app-using-fabric8-maven-plugin) ======================= File: docs/artifacts/includes/maven/publish.md ======================= <reponame>Chibuikekenneth/azure-devops-docs<filename>docs/artifacts/includes/maven/publish.md<gh_stars>1-10 --- ms.topic: include ms.technology: devops-cicd ms.author: rabououn author: ramiMSFT ms.date: 02/19/2020 --- Publish Maven artifacts to a feed in **Azure Artifacts** to share them with your team and organization. To publish a Maven artifact, you'll need to have a Maven artifact to publish on your local machine. If you don't have one, you can generate one by running the following command: ```Command mvn -B archetype:generate -DarchetypeGroupId="org.apache.maven.archetypes" -DgroupId="MyGroup" -DartifactId="myFirstApp" ``` 1. [Set up the Maven client with your feed](../../maven/pom-and-settings.md). 2. Navigate to the directory containing your Maven artifact's **pom.xml** file. If you've just created an artifact, the **pom.xml** file will be in the *myFirstApp* folder. 3. From the directory containing your **pom.xml** file, run the command, `mvn build` and `mvn deploy`. The Maven artifact should appear in your feed. See the [Maven CLI docs](https://maven.apache.org/plugins/maven-deploy-plugin/) for more publish options. ======================= File: docs/extend/reference/client/api/TFS/Build/Contracts/BuildSettings.md ======================= --- title: TFS/Build/Contracts BuildSettings API | Extensions for Azure DevOps Services description: Data representation of a build settings. ms.assetid: 69daca31-5114-7cf4-1b0f-8c8670512cdf ms.technology: devops-ecosystem generated: true author: chcomley ms.topic: article ms.author: chcomley ms.date: 08/04/2016 --- # BuildSettings Module path: `TFS/Build/Contracts` ### Members * `defaultRetentionPolicy`: [RetentionPolicy](./RetentionPolicy.md). * `maximumRetentionPolicy`: [RetentionPolicy](./RetentionPolicy.md). ======================= File: docs/organizations/security/faq-trace-permissions.md ======================= <reponame>Chibuikekenneth/azure-devops-docs --- title: Troubleshoot tracing permissions description: Learn how to trace permissions if you're having permissions issues with Azure DevOps ms.technology: devops-accounts ms.assetid: 12cffcaf-295a-4931-9844-81a12c512158 ms.topic: conceptual ms.author: kaelli author: KathrynEE ms.date: 04/21/2020 monikerRange: 'azure-devops' --- # Troubleshoot tracing permissions **Azure DevOps** ### Q: Why doesn't a user have access to something? **A 1:** Their permissions are specified by multiple groups If one of your users is having permissions issues and you use default security groups or custom groups for permissions, administrators can investigate where those permissions are coming from by using our permissions tracing. Users can receive their effective permissions either directly or via groups. By following these steps, administrators can understand where exactly those permissions are coming from and adjust them as needed. 1. Go to the **Security** page for the project that the user is having access problems. 2. Enter their name into the box in the upper left-hand corner. ![Enter user name to view permissions](media/security-page-enter-user-name.png) 3. You should now have a user-specific view that shows what permissions they have. To trace why a user does or doesn't have any of the listed permissions, hover over the permission and choose **Why**. ![Choose Why in permissions list view for project level information](media/permissions-list-view-project-level-information.png) 4. The resulting trace lets you know how they're inheriting the listed permission. You can then adjust the user's permissions by adjusting those provided to the groups they're in. ![Trace showing inherited permissions](media/trace-permission-group-member-inheritance.png) **A 2:** Their permissions haven't propagated yet It can take up to 1 hour for Azure AD group memberships or permissions changes to propagate throughout Azure DevOps. If a user is having issues that don't seem to clear up immediately, wait a day to see if they resolve. **A 3:** The user does not have the necessary access level Access levels enable administrators to provide their users base access to the features they need, and only pay for those features. Several features can only be accessed with a Basic access level or higher. To assign access levels or check the access level of a user in your account, see the following topics: * For cloud Azure DevOps: [Manage users and access in Azure DevOps](../accounts/add-organization-users.md) * For on-premises Azure DevOps: [Change access levels](/azure/devops/organizations/security/change-access-levels?view=azure-devops) ## Related articles * [Grant or restrict access to select features and functions](/azure/devops/organizations/security/restrict-access?view=azure-devops) * [Change individual permissions](/azure/devops/organizations/security/change-individual-permissions?view=azure-devops) ======================= File: docs/pipelines/tasks/utility/download-package.md ======================= <reponame>Chibuikekenneth/azure-devops-docs --- title: Download Package task description: Download a package from a Package Management feed in Azure Artifacts or TFS. ms.topic: reference ms.assetid: 8d6e8f7e-267d-442d-8c92-1f586864c62f ms.custom: seodec18 ms.date: 12/07/2018 monikerRange: 'azure-devops' --- # Download Package task **Azure Pipelines** Use this task to download a package from a package management feed in Azure Artifacts or TFS. Requires the Package Management extension. ::: moniker range="> tfs-2018" ## YAML snippet [!INCLUDE [temp](../includes/yaml/DownloadPackageV1.md)] ::: moniker-end ## Arguments <table><thead><tr><th>Argument</th><th>Description</th></tr></thead> <tr><td>Package type</td><td>(Required) Select the type of package to download</td></tr> <tr><td>Feed</td><td>(Required) ID of the feed that contains the package. For project-scoped feeds, the format is projectID/feedID. See our <a href="#qa">Q&As</a> below for information on how to get a feed or project ID, or information on using project and feed name instead.</td></tr> <tr><td>View</td><td>(Optional) Select a view to see package versions only promoted to that view.</td></tr> <tr><td>Package</td><td>(Required) Select the package to download</td></tr> <tr><td>Version</td><td>(Required) Version of the package</td></tr> <tr><td>Destination directory</td><td>(Required) Path on the agent machine where the package will be downloaded</td></tr> <tr><td>Extract</td><td>(Optional) Specify whether to extract the package contents at the destination directory</td></tr> <tr><td>Files</td><td>(Optional) Specify files to be downloaded as multiline minimatch patterns. <a href="https://aka.ms/minimatchexamples" data-raw-source="[More Information](https://aka.ms/minimatchexamples)">More Information</a>.<p>The default pattern (<code>**</code>) will download all files within the artifact.</p></td></tr> <tr> <th style="text-align: center" colspan="2"><a href="~/pipelines/process/tasks.md#controloptions" data-raw-source="[Control options](../../process/tasks.md#controloptions)">Control options</a></th> </tr> </table> ## Examples ### Download a nuget package from an organization-scoped feed and extract to destination directory ```YAML # Download an artifact with id 'cfe01b64-ded4-47b7-a569-2ac17cbcedbd' to $(System.ArtifactsDirectory) - task: DownloadPackage@1 inputs: packageType: 'nuget' feed: '6a60ef3b-e29f-41b6-9885-7874278baac7' definition: 'cfe01b64-ded4-47b7-a569-2ac17cbcedbd' # Can also be package name version: '1.0.0' extract: true downloadPath: '$(System.ArtifactsDirectory)' ``` ### Download a maven package from a project-scoped feed and download only pom files. ```YAML # Download an artifact with name 'com.test:testpackage' to $(System.ArtifactsDirectory) - task: DownloadPackage@1 inputs: packageType:'maven' feed: '132f5c2c-2aa0-475a-8b47-02c79617954b/c85e5de9-7b12-4cfd-9293-1b33cdff540e' # <projectId>/<feedId> definition: 'com.test:testpackage' version: '1.0.0-snapshot' # Should be normalized version files: '*.pom' downloadPath: '$(System.ArtifactsDirectory)' ``` ## Q&A ### How do I find the id of the feed (or project) I want to download my artifact from The get feed api can be used to retrieve the feed and project id for your feed. The api is documented [here](https://go.microsoft.com/fwlink/?linkid=2099537). ### Can I use the project or feed name instead of ids Yes, you can use the project or feed name in your definition, however if your project or feed is renamed in the future, your task will also have to be updated or it might fail. ## Open source This task is open source [on GitHub](https://github.com/Microsoft/azure-pipelines-tasks). Feedback and contributions are welcome. ======================= File: docs/boards/includes/process-customize.md ======================= --- ms.topic: include --- ::: moniker range="azure-devops" > [!NOTE] > You can customize the work tracking system for your project by creating and customizing an inherited process and applying that process to your project. To learn more, see [Inheritance process model](/azure/devops/organizations/settings/work/inheritance-process-model). ::: moniker-end ::: moniker range="azure-devops-2019" > [!NOTE] > The latest version of each process uploads automatically when you install or upgrade to the latest version of Azure DevOps Server. You can [customize projects](/azure/devops/reference/on-premises-xml-process-model) and use the [Process Template Manager](/azure/devops/boards/work-items/guidance/manage-process-templates) to upload and download process templates. > > Additional artifacts, such as SQL Server reports are only available when you connect to a project. Other resource requirements apply. ::: moniker-end ::: moniker range="<= tfs-2017" > [!NOTE] > The latest version of each process uploads automatically when you install or upgrade your on-premises deployment. You can [customize projects](/azure/devops/reference/on-premises-xml-process-model) and use the [Process Template Manager](/azure/devops/boards/work-items/guidance/manage-process-templates) to upload and download process templates. > > The following WITs are available as follows: Epic, TFS 2015 and later versions; > Shared Parameters, TFS 2013.2 and later versions; > and Test Plan and Test Suite, TFS 2013.3 and later versions. > > Additional artifacts, such as SQL Server reports and SharePoint dashboards, are only available when you connect to a project from an on-premises Azure DevOps. Other resource requirements apply. ::: moniker-end ======================= File: docs/report/sql-reports/create-aggregate-report-report-designer-analysis-services-cube.md ======================= <gh_stars>1-10 --- title: Create an aggregate report with Report Designer titleSuffix: TFS ms.technology: devops-analytics ms.topic: conceptual description: How to create a report that shows how many active work items are assigned to each person on the team - Team Foundation Server ms.assetid: b02997f4-2c4b-4814-868e-37e0c2414254 ms.author: kaelli author: KathrynEE ms.date: 10/17/2017 --- # Create an aggregate report using Report Designer and the Analysis Services Cube [!INCLUDE [temp](../includes/tfs-report-platform-version.md)] You can track your team's progress more easily by creating reports that aggregate data from Visual Studio Application Lifecycle Management (ALM) (TFS) into charts and tables. For example, you can create a report that shows how many active work items are assigned to each person on the team. To create this type of report, you use Report Designer in SQL Server and the SQL Server Analysis Services cube for TFS. After you create your first report, you might change it by experimenting with different measures, dimensions, and layouts. For example, you can change the chart from a simple column chart to a stacked-bar chart. If you have not created reports for TFS before, see [Dashboards and reports](../admin/review-team-activities-for-useful-reports.md). If you have not used Report Designer before, see the following page on the Microsoft Web site: [Designing and Implementing Reports Using Report Designer](https://go.microsoft.com/fwlink/?LinkId=181954). For information about how to create reports that include line-item details (such as titles of work items), see [Create a Detailed Report using Report Designer](create-a-detailed-report-using-report-designer.md). **Requirements** - You must have Visual Studio and SQL Server Business Intelligence Development Studio installed on the same computer. To install Business Intelligence Development Studio, run the Setup program for SQL Server, and select the **Client Components** check box when you specify the components to install. To install the most recent service pack for SQL Server, see the following page on the Microsoft Web site: [How to obtain the latest service pack for SQL Server 2008](https://go.microsoft.com/fwlink/?LinkID=182174). - You must be a member of the **TfsWarehouseDataReaders** security role in the Analysis Services database on the data-tier server of Team Foundation Server. For more information, see [How to: Grant Access to the Databases of the Data Warehouse](../admin/grant-permissions-to-reports.md). - You must be a member of the **Team Foundation Content Manager** role in SQL Server Reporting Services. For more information, see [Add accounts to administer TFS](/azure/devops/server/admin/add-administrator). ### To create a report 1. In Visual Studio, create or open a Report Server project. For more information, see [Create a Report Server Project](create-a-report-server-project.md). 2. On the **Project** menu, choose **Add New Item**. The **Add New Item** dialog box appears. 3. Choose **Report Wizard**, and then choose **Add**. The **Report Wizard** opens to the **Select Data Source** page. 4. Choose the **Tfs2010OlapReportDS** shared data source, and then choose **Next**. Even though you might have installed or upgraded to TFS 2013, these names, which were assigned to the data sources for TFS 2010 are in use. The wizard advances to the **Design the Query** page. > [!NOTE] > The data source that you specified connects to the analysis services database for TFS. For more information, see [Choose the source of data and authoring tool](https://msdn.microsoft.com/library/bb649557.aspx). If your project does not have this data source, create it. For more information, see [Create a Report Server Project](create-a-report-server-project.md). 5. Choose **Query Builder**. The **Query Build** dialog box appears. ### To create the query that will retrieve the data for the report 1. Choose the **Team System** cube, as the following illustration shows. ![Query Builder &#45; click the Team System cube](media/reportdesignercube.png "ReportDesignerCube") > [!NOTE] > If your data warehouse is using SQL Server Enterprise Edition, the list of cubes will include Team System and a set of perspectives. The perspectives provide a focused view of the data so that you do not have to scroll through the dimensions and measures in the whole Team System cube. For this procedure, you can use the Work Item History perspective if it is available. For more information, see [Perspectives and measure groups provided in the Analysis Services cube](https://msdn.microsoft.com/library/ms244710.aspx). 2. Expand **Measures**, expand the **Work Item History** measure group, and then drag the **Cumulative Count** measure into the data area, as the following illustration shows. ![Query Builder &#45; add Cumulative Count measure](media/reportdesignmeasure.png "ReportDesignMeasure") > [!NOTE] > Cumulative Count shows how many work items are selected. Because you have not yet applied any filters, the number that appears is the total number of work items. For more information about work item measures, see [Perspectives and measure groups provided in the Analysis Services cube](https://msdn.microsoft.com/library/ms244710.aspx). 3. Expand the **Assigned To** dimension, and then drag the **Person** property into the data area, as the following illustration shows. ![Query Builder &#45; add Person dimension](media/querybuilder.png "QueryBuilder") The query now returns the number of work items that are assigned to each person. > [!NOTE] > The **Assigned To** field generally contains Windows accounts. For each Windows account, the **Person** property contains the display name of that account, and the **Alias** property contains the alias. 4. Expand the **Work Item** dimension, drag the **State** property into the data area, and then click **OK**. The **Query Builder** is closed, and the **Design the Query** page of the **Report Wizard** reappears. ### To design the initial report layout 1. Choose **Next**. The wizard advances to the **Report Type** page. 2. Choose **Matrix**, and then choose **Next**. The wizard advances to the **Design the Matrix** page. 3. Choose **Cumulative_Count**, and then choose **Details**. 4. Choose **State**, and then choose **Columns**. 5. Choose **Person**, choose **Rows**, and then click **Next**. The wizard advances to the **Choose the Matrix Style** page. 6. Choose any style, and then choose **Next**. The wizard advances to the **Completing the Report** page. 7. Type a name for the report, choose **Preview Report**, and then choose **Finish** to create the report. The wizard closes, and the report document window appears with the **Preview** tab active. ### To replace the table with a chart 1. In the report document window, choose the **Layout** tab. > [!NOTE] > Report Designer uses three tabs, as the following table describes briefly. | Tab | Description | |---------|--------------------------------------------------------| | Data | Define the data sets that your report uses. | | Layout | Design and arrange the visual elements of your report. | | Preview | Run your report to see how it looks. | 2. Highlight the table, and then press **Delete**. > [!NOTE] > To highlight the whole table, choose anywhere in the table, and then choose the upper-left corner of the table. 3. From the **Toolbox** pane, drag a **Chart** element to the report's layout area, and then size the chart to meet your needs. > [!NOTE] > By default, the **Toolbox** and **Datasets** panes are tabs on the left of the Visual Studio surface. 4. Right-click the chart, and then choose **Properties**. The **Chart Properties** dialog box appears. 5. Choose the **Data** tab, and then click the **TfsOlapReportDS** dataset name. 6. Under **Values**, choose the **Add** button. The **Edit Chart Value** dialog box appears. 7. On the **Value** tab, in the **Value** list, choose<strong>=Sum(Fields!Cumulative_Count.Value)</strong>, and then choose **OK**. 8. Under **Category groups**, choose the **Add** button. The **Grouping and Sorting Properties** dialog box appears. > [!NOTE] > The category groups appear on the x-axis of the chart. 9. In the first row of the **Expression** table, choose<strong>=Fields!Person.Value</strong>, and then choose **OK**. 10. Under **Series groups**, choose the **Add** button. The **Grouping and Sorting Properties** dialog box appears. 11. In the first row of the **Expression** table, choose<strong>=Fields!State.Value</strong>, choose **OK**, and then choose **OK**. 12. Choose the **Preview** tab to display a chart that shows how many work items are assigned to each team member, organized by the work item state. ### To deploy the report 1. In **Solution Explorer**, choose the report. 2. On the **Build** menu, click **Deploy** *ReportName*. > [!IMPORTANT] > To successfully deploy the report, your project settings must be set to appropriate values. For more information, see [Create a Report Server Project](create-a-report-server-project.md). ## Related notes [Perspectives and measure groups provided in the Analysis Services cube](https://msdn.microsoft.com/library/ms244710.aspx) ======================= File: docs/notifications/change-email-address.md ======================= --- title: Change your preferred notification email address titleSuffix: Azure DevOps description: Change the email address used to receive alerts or email notifications managed in Azure DevOps or Team Foundation Server (TFS) ms.technology: devops-collab ms.topic: conceptual ms.author: chcomley author: chcomley ms.date: 12/30/2019 monikerRange: '>= tfs-2015' --- # Change your preferred email address for notifications [!INCLUDE [temp](../includes/version-ts-tfs-2015-2016.md)] You can change your preferred email address for notifications from your organization preferences profile page. Notifications are sent by default to the preferred email address for your organization profile. It's typically the email address you signed into Azure DevOps or TFS with. > [!NOTE] > Your preferred email address applies across all of your organizations and can't be changed on a per-organization
1,530
Repo: stuntguy3000/LIFX-LAN-SDK ======================= File: docs/index-files/index-20.html ======================= <filename>docs/index-files/index-20.html <!-- ~ Copyright 2021 <NAME> (stuntguy3000) ~ ~ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: ~ ~ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. ~ ~ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_312) on Thu Dec 02 16:48:51 ACDT 2021 --> <title>V-Index</title> <meta name="date" content="2021-12-02"> <link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style"> <script type="text/javascript" src="../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="V-Index"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../overview-summary.html">Overview</a></li> <li>Package</li> <li>Class</li> <li><a href="../overview-tree.html">Tree</a></li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li class="navBarCell1Rev">Index</li> <li><a href="../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="index-19.html">Prev Letter</a></li> <li><a href="index-21.html">Next Letter</a></li> </ul> <ul class="navList"> <li><a href="../index.html?index-files/index-20.html" target="_top">Frames</a></li> <li><a href="index-20.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="contentContainer"><a href="index-1.html">A</a>&nbsp;<a href="index-2.html">B</a>&nbsp;<a href="index-3.html">C</a>&nbsp;<a href="index-4.html">D</a>&nbsp;<a href="index-5.html">E</a>&nbsp;<a href="index-6.html">F</a>&nbsp;<a href="index-7.html">G</a>&nbsp;<a href="index-8.html">H</a>&nbsp;<a href="index-9.html">I</a>&nbsp;<a href="index-10.html">K</a>&nbsp;<a href="index-11.html">L</a>&nbsp;<a href="index-12.html">M</a>&nbsp;<a href="index-13.html">N</a>&nbsp;<a href="index-14.html">O</a>&nbsp;<a href="index-15.html">P</a>&nbsp;<a href="index-16.html">R</a>&nbsp;<a href="index-17.html">S</a>&nbsp;<a href="index-18.html">T</a>&nbsp;<a href="index-19.html">U</a>&nbsp;<a href="index-20.html">V</a>&nbsp;<a href="index-21.html">W</a>&nbsp;<a href="index-22.html">X</a>&nbsp;<a href="index-23.html">Y</a>&nbsp;<a href="index-24.html">Z</a>&nbsp;<a name="I:V"> <!-- --> </a> <h2 class="title">V</h2> <dl> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/object/protocol/enums/DeviceType.html#valueOf-java.lang.String-">valueOf(String)</a></span> - Static method in enum com.stuntguy3000.lifxlansdk.object.protocol.enums.<a href="../com/stuntguy3000/lifxlansdk/object/protocol/enums/DeviceType.html" title="enum in com.stuntguy3000.lifxlansdk.object.protocol.enums">DeviceType</a></dt> <dd> <div class="block">Returns the enum constant of this type with the specified name.</div> </dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/object/protocol/enums/Direction.html#valueOf-java.lang.String-">valueOf(String)</a></span> - Static method in enum com.stuntguy3000.lifxlansdk.object.protocol.enums.<a href="../com/stuntguy3000/lifxlansdk/object/protocol/enums/Direction.html" title="enum in com.stuntguy3000.lifxlansdk.object.protocol.enums">Direction</a></dt> <dd> <div class="block">Returns the enum constant of this type with the specified name.</div> </dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/object/protocol/enums/LightLastHevCycleResult.html#valueOf-java.lang.String-">valueOf(String)</a></span> - Static method in enum com.stuntguy3000.lifxlansdk.object.protocol.enums.<a href="../com/stuntguy3000/lifxlansdk/object/protocol/enums/LightLastHevCycleResult.html" title="enum in com.stuntguy3000.lifxlansdk.object.protocol.enums">LightLastHevCycleResult</a></dt> <dd> <div class="block">Returns the enum constant of this type with the specified name.</div> </dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/object/protocol/enums/MultiZoneApplicationRequest.html#valueOf-java.lang.String-">valueOf(String)</a></span> - Static method in enum com.stuntguy3000.lifxlansdk.object.protocol.enums.<a href="../com/stuntguy3000/lifxlansdk/object/protocol/enums/MultiZoneApplicationRequest.html" title="enum in com.stuntguy3000.lifxlansdk.object.protocol.enums">MultiZoneApplicationRequest</a></dt> <dd> <div class="block">Returns the enum constant of this type with the specified name.</div> </dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/object/protocol/enums/MultiZoneEffectType.html#valueOf-java.lang.String-">valueOf(String)</a></span> - Static method in enum com.stuntguy3000.lifxlansdk.object.protocol.enums.<a href="../com/stuntguy3000/lifxlansdk/object/protocol/enums/MultiZoneEffectType.html" title="enum in com.stuntguy3000.lifxlansdk.object.protocol.enums">MultiZoneEffectType</a></dt> <dd> <div class="block">Returns the enum constant of this type with the specified name.</div> </dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/object/protocol/enums/MultiZoneExtendedApplicationRequest.html#valueOf-java.lang.String-">valueOf(String)</a></span> - Static method in enum com.stuntguy3000.lifxlansdk.object.protocol.enums.<a href="../com/stuntguy3000/lifxlansdk/object/protocol/enums/MultiZoneExtendedApplicationRequest.html" title="enum in com.stuntguy3000.lifxlansdk.object.protocol.enums">MultiZoneExtendedApplicationRequest</a></dt> <dd> <div class="block">Returns the enum constant of this type with the specified name.</div> </dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/object/protocol/enums/Service.html#valueOf-java.lang.String-">valueOf(String)</a></span> - Static method in enum com.stuntguy3000.lifxlansdk.object.protocol.enums.<a href="../com/stuntguy3000/lifxlansdk/object/protocol/enums/Service.html" title="enum in com.stuntguy3000.lifxlansdk.object.protocol.enums">Service</a></dt> <dd> <div class="block">Returns the enum constant of this type with the specified name.</div> </dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/object/protocol/enums/TileEffectType.html#valueOf-java.lang.String-">valueOf(String)</a></span> - Static method in enum com.stuntguy3000.lifxlansdk.object.protocol.enums.<a href="../com/stuntguy3000/lifxlansdk/object/protocol/enums/TileEffectType.html" title="enum in com.stuntguy3000.lifxlansdk.object.protocol.enums">TileEffectType</a></dt> <dd> <div class="block">Returns the enum constant of this type with the specified name.</div> </dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/object/protocol/enums/Waveform.html#valueOf-java.lang.String-">valueOf(String)</a></span> - Static method in enum com.stuntguy3000.lifxlansdk.object.protocol.enums.<a href="../com/stuntguy3000/lifxlansdk/object/protocol/enums/Waveform.html" title="enum in com.stuntguy3000.lifxlansdk.object.protocol.enums">Waveform</a></dt> <dd> <div class="block">Returns the enum constant of this type with the specified name.</div> </dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/object/protocol/enums/DeviceType.html#values--">values()</a></span> - Static method in enum com.stuntguy3000.lifxlansdk.object.protocol.enums.<a href="../com/stuntguy3000/lifxlansdk/object/protocol/enums/DeviceType.html" title="enum in com.stuntguy3000.lifxlansdk.object.protocol.enums">DeviceType</a></dt> <dd> <div class="block">Returns an array containing the constants of this enum type, in the order they are declared.</div> </dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/object/protocol/enums/Direction.html#values--">values()</a></span> - Static method in enum com.stuntguy3000.lifxlansdk.object.protocol.enums.<a href="../com/stuntguy3000/lifxlansdk/object/protocol/enums/Direction.html" title="enum in com.stuntguy3000.lifxlansdk.object.protocol.enums">Direction</a></dt> <dd> <div class="block">Returns an array containing the constants of this enum type, in the order they are declared.</div> </dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/object/protocol/enums/LightLastHevCycleResult.html#values--">values()</a></span> - Static method in enum com.stuntguy3000.lifxlansdk.object.protocol.enums.<a href="../com/stuntguy3000/lifxlansdk/object/protocol/enums/LightLastHevCycleResult.html" title="enum in com.stuntguy3000.lifxlansdk.object.protocol.enums">LightLastHevCycleResult</a></dt> <dd> <div class="block">Returns an array containing the constants of this enum type, in the order they are declared.</div> </dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/object/protocol/enums/MultiZoneApplicationRequest.html#values--">values()</a></span> - Static method in enum com.stuntguy3000.lifxlansdk.object.protocol.enums.<a href="../com/stuntguy3000/lifxlansdk/object/protocol/enums/MultiZoneApplicationRequest.html" title="enum in com.stuntguy3000.lifxlansdk.object.protocol.enums">MultiZoneApplicationRequest</a></dt> <dd> <div class="block">Returns an array containing the constants of this enum type, in the order they are declared.</div> </dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/object/protocol/enums/MultiZoneEffectType.html#values--">values()</a></span> - Static method in enum com.stuntguy3000.lifxlansdk.object.protocol.enums.<a href="../com/stuntguy3000/lifxlansdk/object/protocol/enums/MultiZoneEffectType.html" title="enum in com.stuntguy3000.lifxlansdk.object.protocol.enums">MultiZoneEffectType</a></dt> <dd> <div class="block">Returns an array containing the constants of this enum type, in the order they are declared.</div> </dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/object/protocol/enums/MultiZoneExtendedApplicationRequest.html#values--">values()</a></span> - Static method in enum com.stuntguy3000.lifxlansdk.object.protocol.enums.<a href="../com/stuntguy3000/lifxlansdk/object/protocol/enums/MultiZoneExtendedApplicationRequest.html" title="enum in com.stuntguy3000.lifxlansdk.object.protocol.enums">MultiZoneExtendedApplicationRequest</a></dt> <dd> <div class="block">Returns an array containing the constants of this enum type, in the order they are declared.</div> </dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/object/protocol/enums/Service.html#values--">values()</a></span> - Static method in enum com.stuntguy3000.lifxlansdk.object.protocol.enums.<a href="../com/stuntguy3000/lifxlansdk/object/protocol/enums/Service.html" title="enum in com.stuntguy3000.lifxlansdk.object.protocol.enums">Service</a></dt> <dd> <div class="block">Returns an array containing the constants of this enum type, in the order they are declared.</div> </dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/object/protocol/enums/TileEffectType.html#values--">values()</a></span> - Static method in enum com.stuntguy3000.lifxlansdk.object.protocol.enums.<a href="../com/stuntguy3000/lifxlansdk/object/protocol/enums/TileEffectType.html" title="enum in com.stuntguy3000.lifxlansdk.object.protocol.enums">TileEffectType</a></dt> <dd> <div class="block">Returns an array containing the constants of this enum type, in the order they are declared.</div> </dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/object/protocol/enums/Waveform.html#values--">values()</a></span> - Static method in enum com.stuntguy3000.lifxlansdk.object.protocol.enums.<a href="../com/stuntguy3000/lifxlansdk/object/protocol/enums/Waveform.html" title="enum in com.stuntguy3000.lifxlansdk.object.protocol.enums">Waveform</a></dt> <dd> <div class="block">Returns an array containing the constants of this enum type, in the order they are declared.</div> </dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/messages/state/device/StateVersion.html#vendor">vendor</a></span> - Variable in class com.stuntguy3000.lifxlansdk.messages.state.device.<a href="../com/stuntguy3000/lifxlansdk/messages/state/device/StateVersion.html" title="class in com.stuntguy3000.lifxlansdk.messages.state.device">StateVersion</a></dt> <dd> <div class="block">For LIFX products this value is 1.</div> </dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/messages/state/device/StateHostFirmware.html#version_major">version_major</a></span> - Variable in class com.stuntguy3000.lifxlansdk.messages.state.device.<a href="../com/stuntguy3000/lifxlansdk/messages/state/device/StateHostFirmware.html" title="class in com.stuntguy3000.lifxlansdk.messages.state.device">StateHostFirmware</a></dt> <dd> <div class="block">The major component of the firmware version</div> </dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/messages/state/device/StateWifiFirmware.html#version_major">version_major</a></span> - Variable in class com.stuntguy3000.lifxlansdk.messages.state.device.<a href="../com/stuntguy3000/lifxlansdk/messages/state/device/StateWifiFirmware.html" title="class in com.stuntguy3000.lifxlansdk.messages.state.device">StateWifiFirmware</a></dt> <dd> <div class="block">The major component of the version.</div> </dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/messages/state/device/StateHostFirmware.html#version_minor">version_minor</a></span> - Variable in class com.stuntguy3000.lifxlansdk.messages.state.device.<a href="../com/stuntguy3000/lifxlansdk/messages/state/device/StateHostFirmware.html" title="class in com.stuntguy3000.lifxlansdk.messages.state.device">StateHostFirmware</a></dt> <dd> <div class="block">The minor component of the firmware version</div> </dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/messages/state/device/StateWifiFirmware.html#version_minor">version_minor</a></span> - Variable in class com.stuntguy3000.lifxlansdk.messages.state.device.<a href="../com/stuntguy3000/lifxlansdk/messages/state/device/StateWifiFirmware.html" title="class in com.stuntguy3000.lifxlansdk.messages.state.device">StateWifiFirmware</a></dt> <dd> <div class="block">The minor component of the version.</div> </dd> </dl> <a href="index-1.html">A</a>&nbsp;<a href="index-2.html">B</a>&nbsp;<a href="index-3.html">C</a>&nbsp;<a href="index-4.html">D</a>&nbsp;<a href="index-5.html">E</a>&nbsp;<a href="index-6.html">F</a>&nbsp;<a href="index-7.html">G</a>&nbsp;<a href="index-8.html">H</a>&nbsp;<a href="index-9.html">I</a>&nbsp;<a href="index-10.html">K</a>&nbsp;<a href="index-11.html">L</a>&nbsp;<a href="index-12.html">M</a>&nbsp;<a href="index-13.html">N</a>&nbsp;<a href="index-14.html">O</a>&nbsp;<a href="index-15.html">P</a>&nbsp;<a href="index-16.html">R</a>&nbsp;<a href="index-17.html">S</a>&nbsp;<a href="index-18.html">T</a>&nbsp;<a href="index-19.html">U</a>&nbsp;<a href="index-20.html">V</a>&nbsp;<a href="index-21.html">W</a>&nbsp;<a href="index-22.html">X</a>&nbsp;<a href="index-23.html">Y</a>&nbsp;<a href="index-24.html">Z</a>&nbsp;</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../overview-summary.html">Overview</a></li> <li>Package</li> <li>Class</li> <li><a href="../overview-tree.html">Tree</a></li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li class="navBarCell1Rev">Index</li> <li><a href="../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="index-19.html">Prev Letter</a></li> <li><a href="index-21.html">Next Letter</a></li> </ul> <ul class="navList"> <li><a href="../index.html?index-files/index-20.html" target="_top">Frames</a></li> <li><a href="index-20.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html> ======================= File: docs/index-files/index-6.html ======================= <!-- ~ Copyright 2021 <NAME> (stuntguy3000) ~ ~ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: ~ ~ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. ~ ~ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_312) on Thu Dec 02 16:48:51 ACDT 2021 --> <title>F-Index</title> <meta name="date" content="2021-12-02"> <link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style"> <script type="text/javascript" src="../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="F-Index"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../overview-summary.html">Overview</a></li> <li>Package</li> <li>Class</li> <li><a href="../overview-tree.html">Tree</a></li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li class="navBarCell1Rev">Index</li> <li><a href="../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="index-5.html">Prev Letter</a></li> <li><a href="index-7.html">Next Letter</a></li> </ul> <ul class="navList"> <li><a href="../index.html?index-files/index-6.html" target="_top">Frames</a></li> <li><a href="index-6.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="contentContainer"><a href="index-1.html">A</a>&nbsp;<a href="index-2.html">B</a>&nbsp;<a href="index-3.html">C</a>&nbsp;<a href="index-4.html">D</a>&nbsp;<a href="index-5.html">E</a>&nbsp;<a href="index-6.html">F</a>&nbsp;<a href="index-7.html">G</a>&nbsp;<a href="index-8.html">H</a>&nbsp;<a href="index-9.html">I</a>&nbsp;<a href="index-10.html">K</a>&nbsp;<a href="index-11.html">L</a>&nbsp;<a href="index-12.html">M</a>&nbsp;<a href="index-13.html">N</a>&nbsp;<a href="index-14.html">O</a>&nbsp;<a href="index-15.html">P</a>&nbsp;<a href="index-16.html">R</a>&nbsp;<a href="index-17.html">S</a>&nbsp;<a href="index-18.html">T</a>&nbsp;<a href="index-19.html">U</a>&nbsp;<a href="index-20.html">V</a>&nbsp;<a href="index-21.html">W</a>&nbsp;<a href="index-22.html">X</a>&nbsp;<a href="index-23.html">Y</a>&nbsp;<a href="index-24.html">Z</a>&nbsp;<a name="I:F"> <!-- --> </a> <h2 class="title">F</h2> <dl> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/object/product/Device.html#fetchGroup--">fetchGroup()</a></span> - Method in class com.stuntguy3000.lifxlansdk.object.product.<a href="../com/stuntguy3000/lifxlansdk/object/product/Device.html" title="class in com.stuntguy3000.lifxlansdk.object.product">Device</a></dt> <dd> <div class="block">Fetches the device's group (and updates local cache)</div> </dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/object/product/Device.html#fetchLabel--">fetchLabel()</a></span> - Method in class com.stuntguy3000.lifxlansdk.object.product.<a href="../com/stuntguy3000/lifxlansdk/object/product/Device.html" title="class in com.stuntguy3000.lifxlansdk.object.product">Device</a></dt> <dd> <div class="block">Fetches the device's label (and updates local cache)</div> </dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/object/product/Device.html#fetchLocation--">fetchLocation()</a></span> - Method in class com.stuntguy3000.lifxlansdk.object.product.<a href="../com/stuntguy3000/lifxlansdk/object/product/Device.html" title="class in com.stuntguy3000.lifxlansdk.object.product">Device</a></dt> <dd> <div class="block">Fetches the device's location (and updates local cache)</div> </dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/object/product/MultiZone.html#fetchZonesCount--">fetchZonesCount()</a></span> - Method in class com.stuntguy3000.lifxlansdk.object.product.<a href="../com/stuntguy3000/lifxlansdk/object/product/MultiZone.html" title="class in com.stuntguy3000.lifxlansdk.object.product">MultiZone</a></dt> <dd> <div class="block">Fetches the MultiZones's zonesCount (and updates local cache)</div> </dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/helper/DeviceHelper.html#findDevices--">findDevices()</a></span> - Static method in class com.stuntguy3000.lifxlansdk.helper.<a href="../com/stuntguy3000/lifxlansdk/helper/DeviceHelper.html" title="class in com.stuntguy3000.lifxlansdk.helper">DeviceHelper</a></dt> <dd> <div class="block">Attempt to find all LIFX Devices on a network.</div> </dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/helper/LightHelper.html#findLights--">findLights()</a></span> - Static method in class com.stuntguy3000.lifxlansdk.helper.<a href="../com/stuntguy3000/lifxlansdk/helper/LightHelper.html" title="class in com.stuntguy3000.lifxlansdk.helper">LightHelper</a></dt> <dd> <div class="block">Attempt to find all LIFX Lights on a network.</div> </dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/helper/MultiZoneHelper.html#findMultiZones--">findMultiZones()</a></span> - Static method in class com.stuntguy3000.lifxlansdk.helper.<a href="../com/stuntguy3000/lifxlansdk/helper/MultiZoneHelper.html" title="class in com.stuntguy3000.lifxlansdk.helper">MultiZoneHelper</a></dt> <dd> <div class="block">Attempt to find all LIFX MultiZone lights on a network.</div> </dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/helper/RelayHelper.html#findRelay--">findRelay()</a></span> - Static method in class com.stuntguy3000.lifxlansdk.helper.<a href="../com/stuntguy3000/lifxlansdk/helper/RelayHelper.html" title="class in com.stuntguy3000.lifxlansdk.helper">RelayHelper</a></dt> <dd> <div class="block">Attempt to find all LIFX Relay devices on a network.</div> </dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/helper/TileHelper.html#findTiles--">findTiles()</a></span> - Static method in class com.stuntguy3000.lifxlansdk.helper.<a href="../com/stuntguy3000/lifxlansdk/helper/TileHelper.html" title="class in com.stuntguy3000.lifxlansdk.helper">TileHelper</a></dt> <dd> <div class="block">Attempt to find all LIFX Tile lights on a network.</div> </dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/object/protocol/TileData.html#firmware_build">firmware_build</a></span> - Variable in class com.stuntguy3000.lifxlansdk.object.protocol.<a href="../com/stuntguy3000/lifxlansdk/object/protocol/TileData.html" title="class in com.stuntguy3000.lifxlansdk.object.protocol">TileData</a></dt> <dd> <div class="block">The epoch of the time the firmware was created (See <a href="../com/stuntguy3000/lifxlansdk/messages/state/device/StateHostFirmware.html" title="class in com.stuntguy3000.lifxlansdk.messages.state.device"><code>StateHostFirmware</code></a> (15))</div> </dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/object/protocol/TileData.html#firmware_version_major">firmware_version_major</a></span> - Variable in class com.stuntguy3000.lifxlansdk.object.protocol.<a href="../com/stuntguy3000/lifxlansdk/object/protocol/TileData.html" title="class in com.stuntguy3000.lifxlansdk.object.protocol">TileData</a></dt> <dd> <div class="block">The major component of the firmware version (See <a href="../com/stuntguy3000/lifxlansdk/messages/state/device/StateHostFirmware.html" title="class in com.stuntguy3000.lifxlansdk.messages.state.device"><code>StateHostFirmware</code></a> (15))</div> </dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/object/protocol/TileData.html#firmware_version_minor">firmware_version_minor</a></span> - Variable in class com.stuntguy3000.lifxlansdk.object.protocol.<a href="../com/stuntguy3000/lifxlansdk/object/protocol/TileData.html" title="class in com.stuntguy3000.lifxlansdk.object.protocol">TileData</a></dt> <dd> <div class="block">The minor component of the firmware version (See <a href="../com/stuntguy3000/lifxlansdk/messages/state/device/StateHostFirmware.html" title="class in com.stuntguy3000.lifxlansdk.messages.state.device"><code>StateHostFirmware</code></a> (15))</div> </dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/util/TypeUtil.html#floatToBytesLittleEndian-float-">floatToBytesLittleEndian(float)</a></span> - Static method in class com.stuntguy3000.lifxlansdk.util.<a href="../com/stuntguy3000/lifxlansdk/util/TypeUtil.html" title="class in com.stuntguy3000.lifxlansdk.util">TypeUtil</a></dt> <dd>&nbsp;</dd> <dt><a href="../com/stuntguy3000/lifxlansdk/object/protocol/FrameAddress.html" title="class in com.stuntguy3000.lifxlansdk.object.protocol"><span class="typeNameLink">FrameAddress</span></a> - Class in <a href="../com/stuntguy3000/lifxlansdk/object/protocol/package-summary.html">com.stuntguy3000.lifxlansdk.object.protocol</a></dt> <dd> <div class="block">Represents a LIFX packet Frame Header</div> </dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/object/protocol/FrameAddress.html#FrameAddress--">FrameAddress()</a></span> - Constructor for class com.stuntguy3000.lifxlansdk.object.protocol.<a href="../com/stuntguy3000/lifxlansdk/object/protocol/FrameAddress.html" title="class in com.stuntguy3000.lifxlansdk.object.protocol">FrameAddress</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/object/protocol/Packet.html#frameAddress">frameAddress</a></span> - Variable in class com.stuntguy3000.lifxlansdk.object.protocol.<a href="../com/stuntguy3000/lifxlansdk/object/protocol/Packet.html" title="class in com.stuntguy3000.lifxlansdk.object.protocol">Packet</a></dt> <dd>&nbsp;</dd> <dt><a href="../com/stuntguy3000/lifxlansdk/object/protocol/FrameHeader.html" title="class in com.stuntguy3000.lifxlansdk.object.protocol"><span class="typeNameLink">FrameHeader</span></a> - Class in <a href="../com/stuntguy3000/lifxlansdk/object/protocol/package-summary.html">com.stuntguy3000.lifxlansdk.object.protocol</a></dt> <dd> <div class="block">Represents a LIFX packet Frame Header</div> </dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/object/protocol/FrameHeader.html#FrameHeader--">FrameHeader()</a></span> - Constructor for class com.stuntguy3000.lifxlansdk.object.protocol.<a href="../com/stuntguy3000/lifxlansdk/object/protocol/FrameHeader.html" title="class in com.stuntguy3000.lifxlansdk.object.protocol">FrameHeader</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/object/protocol/Packet.html#frameHeader">frameHeader</a></span> - Variable in class com.stuntguy3000.lifxlansdk.object.protocol.<a href="../com/stuntguy3000/lifxlansdk/object/protocol/Packet.html" title="class in com.stuntguy3000.lifxlansdk.object.protocol">Packet</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/object/protocol/Color.html#fromRGB-int-int-int-">fromRGB(int, int, int)</a></span> - Static method in class com.stuntguy3000.lifxlansdk.object.protocol.<a href="../com/stuntguy3000/lifxlansdk/object/protocol/Color.html" title="class in com.stuntguy3000.lifxlansdk.object.protocol">Color</a></dt> <dd> <div class="block">Create a new Color object from RGB</div> </dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/object/protocol/Color.html#fromRGBK-int-int-int-int-">fromRGBK(int, int, int, int)</a></span> - Static method in class com.stuntguy3000.lifxlansdk.object.protocol.<a href="../com/stuntguy3000/lifxlansdk/object/protocol/Color.html" title="class in com.stuntguy3000.lifxlansdk.object.protocol">Color</a></dt> <dd> <div class="block">Create a new Color object from RGB</div> </dd> </dl> <a href="index-1.html">A</a>&nbsp;<a href="index-2.html">B</a>&nbsp;<a href="index-3.html">C</a>&nbsp;<a href="index-4.html">D</a>&nbsp;<a href="index-5.html">E</a>&nbsp;<a href="index-6.html">F</a>&nbsp;<a href="index-7.html">G</a>&nbsp;<a href="index-8.html">H</a>&nbsp;<a href="index-9.html">I</a>&nbsp;<a href="index-10.html">K</a>&nbsp;<a href="index-11.html">L</a>&nbsp;<a href="index-12.html">M</a>&nbsp;<a href="index-13.html">N</a>&nbsp;<a href="index-14.html">O</a>&nbsp;<a href="index-15.html">P</a>&nbsp;<a href="index-16.html">R</a>&nbsp;<a href="index-17.html">S</a>&nbsp;<a href="index-18.html">T</a>&nbsp;<a href="index-19.html">U</a>&nbsp;<a href="index-20.html">V</a>&nbsp;<a href="index-21.html">W</a>&nbsp;<a href="index-22.html">X</a>&nbsp;<a href="index-23.html">Y</a>&nbsp;<a href="index-24.html">Z</a>&nbsp;</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../overview-summary.html">Overview</a></li> <li>Package</li> <li>Class</li> <li><a href="../overview-tree.html">Tree</a></li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li class="navBarCell1Rev">Index</li> <li><a href="../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="index-5.html">Prev Letter</a></li> <li><a href="index-7.html">Next Letter</a></li> </ul> <ul class="navList"> <li><a href="../index.html?index-files/index-6.html" target="_top">Frames</a></li> <li><a href="index-6.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html> ======================= File: docs/com/stuntguy3000/lifxlansdk/handler/PacketHandler.html ======================= <!-- ~ Copyright 2021 <NAME> (stuntguy3000) ~ ~ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: ~ ~ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. ~ ~ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_312) on Thu Dec 02 16:48:51 ACDT 2021 --> <title>PacketHandler</title> <meta name="date" content="2021-12-02"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="PacketHandler"; } } catch(err) { } //--> var methods = {"i0":9,"i1":9,"i2":9,"i3":9,"i4":9,"i5":9,"i6":9,"i7":9,"i8":9,"i9":9}; var tabs = {65535:["t0","All Methods"],1:["t1","Static Methods"],8:["t4","Concrete Methods"]}; var altColor = "altColor"; var rowColor = "rowColor"; var tableTab = "tableTab"; var activeTableTab = "activeTableTab"; </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev&nbsp;Class</li> <li>Next&nbsp;Class</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?com/stuntguy3000/lifxlansdk/handler/PacketHandler.html" target="_top">Frames</a></li> <li><a href="PacketHandler.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#field.summary">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field.detail">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">com.stuntguy3000.lifxlansdk.handler</div> <h2 title="Class PacketHandler" class="title">Class PacketHandler</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>com.stuntguy3000.lifxlansdk.handler.PacketHandler</li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <hr> <br> <pre>public class <span class="typeNameLabel">PacketHandler</span> extends java.lang.Object</pre> <div class="block">A handler for all Packet related functions</div> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- =========== FIELD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="field.summary"> <!-- --> </a> <h3>Field Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation"> <caption><span>Fields</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Field and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>private static java.net.InetAddress</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/stuntguy3000/lifxlansdk/handler/PacketHandler.html#broadcastAddress">broadcastAddress</a></span></code> <div class="block">The broadcast address to send packets on.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>private static java.util.HashMap&lt;java.lang.Integer,java.lang.Class&lt;? extends <a href="../../../../com/stuntguy3000/lifxlansdk/object/protocol/abstracts/Message.html" title="class in com.stuntguy3000.lifxlansdk.object.protocol.abstracts">Message</a>&gt;&gt;</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/stuntguy3000/lifxlansdk/handler/PacketHandler.html#responseMessagesMap">responseMessagesMap</a></span></code> <div class="block">A map of packet ID and it's associated Message class for packet object response mapping</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>private static short</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/stuntguy3000/lifxlansdk/handler/PacketHandler.html#sequence">sequence</a></span></code> <div class="block">Packet sequence number</div> </td> </tr> </table> </li> </ul> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><span class="memberNameLink"><a href="../../../../com/stuntguy3000/lifxlansdk/handler/PacketHandler.html#PacketHandler--">PacketHandler</a></span>()</code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method.summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd">&nbsp;</span></span><span id="t1" class="tableTab"><span><a href="javascript:show(1);">Static Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd">&nbsp;</span></span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr id="i0" class="altColor"> <td class="colFirst"><code>private static <a href="../../../../com/stuntguy3000/lifxlansdk/object/protocol/abstracts/Message.html" title="class in com.stuntguy3000.lifxlansdk.object.protocol.abstracts">Message</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/stuntguy3000/lifxlansdk/handler/PacketHandler.html#buildMessage-int-byte:A-">buildMessage</a></span>(int&nbsp;messageType, byte[]&nbsp;messageBytes)</code> <div class="block">Builds a LIFX Message</div> </td> </tr> <tr id="i1" class="rowColor"> <td class="colFirst"><code>private static <a href="../../../../com/stuntguy3000/lifxlansdk/object/protocol/Packet.html" title="class in com.stuntguy3000.lifxlansdk.object.protocol">Packet</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/stuntguy3000/lifxlansdk/handler/PacketHandler.html#buildPacket-byte:A-">buildPacket</a></span>(byte[]&nbsp;receivedData)</code> <div class="block">Builds a LIFX Packet from received data</div> </td> </tr> <tr id="i2" class="altColor"> <td class="colFirst"><code>private static <a href="../../../../com/stuntguy3000/lifxlansdk/object/protocol/Packet.html" title="class in com.stuntguy3000.lifxlansdk.object.protocol">Packet</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/stuntguy3000/lifxlansdk/handler/PacketHandler.html#buildPacket-com.stuntguy3000.lifxlansdk.object.protocol.abstracts.Message-com.stuntguy3000.lifxlansdk.object.product.Device-boolean-">buildPacket</a></span>(<a href="../../../../com/stuntguy3000/lifxlansdk/object/protocol/abstracts/Message.html" title="class in com.stuntguy3000.lifxlansdk.object.protocol.abstracts">Message</a>&nbsp;message, <a href="../../../../com/stuntguy3000/lifxlansdk/object/product/Device.html" title="class in com.stuntguy3000.lifxlansdk.object.product">Device</a>&nbsp;device, boolean&nbsp;resultRequired)</code> <div class="block">Internal packet builder for packets to be sent, not received.</div> </td> </tr> <tr id="i3" class="rowColor"> <td class="colFirst"><code>private static short</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/stuntguy3000/lifxlansdk/handler/PacketHandler.html#getNextPacketSequenceNumber--">getNextPacketSequenceNumber</a></span>()</code> <div class="block">Increment the packet sequence in a 0-255 loop.</div> </td> </tr> <tr id="i4" class="altColor"> <td class="colFirst"><code>private static void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/stuntguy3000/lifxlansdk/handler/PacketHandler.html#init--">init</a></span>()</code> <div class="block">Initializes the responseMessagesMap object</div> </td> </tr> <tr id="i5" class="rowColor"> <td class="colFirst"><code>static java.util.List&lt;<a href="../../../../com/stuntguy3000/lifxlansdk/object/protocol/Packet.html" title="class in com.stuntguy3000.lifxlansdk.object.protocol">Packet</a>&gt;</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/stuntguy3000/lifxlansdk/handler/PacketHandler.html#sendMessage-com.stuntguy3000.lifxlansdk.object.protocol.abstracts.Message-com.stuntguy3000.lifxlansdk.object.product.Device-">sendMessage</a></span>(<a href="../../../../com/stuntguy3000/lifxlansdk/object/protocol/abstracts/Message.html" title="class in com.stuntguy3000.lifxlansdk.object.protocol.abstracts">Message</a>&nbsp;message, <a href="../../../../com/stuntguy3000/lifxlansdk/object/product/Device.html" title="class in com.stuntguy3000.lifxlansdk.object.product">Device</a>&nbsp;device)</code> <div class="block">Send a Message to a device</div> </td> </tr> <tr id="i6" class="altColor"> <td class="colFirst"><code>static java.util.List&lt;<a href="../../../../com/stuntguy3000/lifxlansdk/object/protocol/Packet.html" title="class in com.stuntguy3000.lifxlansdk.object.protocol">Packet</a>&gt;</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/stuntguy3000/lifxlansdk/handler/PacketHandler.html#sendMessage-com.stuntguy3000.lifxlansdk.object.protocol.abstracts.Message-com.stuntguy3000.lifxlansdk.object.product.Device-boolean-">sendMessage</a></span>(<a href="../../../../com/stuntguy3000/lifxlansdk/object/protocol/abstracts/Message.html" title="class in com.stuntguy3000.lifxlansdk.object.protocol.abstracts">Message</a>&nbsp;message, <a href="../../../../com/stuntguy3000/lifxlansdk/object/product/Device.html" title="class in com.stuntguy3000.lifxlansdk.object.product">Device</a>&nbsp;device, boolean&nbsp;resultRequired)</code> <div class="block">Send a Message to a device</div> </td> </tr> <tr id="i7" class="rowColor"> <td class="colFirst"><code>static java.util.List&lt;<a href="../../../../com/stuntguy3000/lifxlansdk/object/protocol/Packet.html" title="class in com.stuntguy3000.lifxlansdk.object.protocol">Packet</a>&gt;</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/stuntguy3000/lifxlansdk/handler/PacketHandler.html#sendMessage-com.stuntguy3000.lifxlansdk.object.protocol.abstracts.Message-com.stuntguy3000.lifxlansdk.object.product.Device-boolean-int-">sendMessage</a></span>(<a href="../../../../com/stuntguy3000/lifxlansdk/object/protocol/abstracts/Message.html" title="class in com.stuntguy3000.lifxlansdk.object.protocol.abstracts">Message</a>&nbsp;message, <a href="../../../../com/stuntguy3000/lifxlansdk/object/product/Device.html" title="class in com.stuntguy3000.lifxlansdk.object.product">Device</a>&nbsp;device, boolean&nbsp;resultRequired, int&nbsp;maxReceiveMessageCount)</code> <div class="block">Send a Message to a device</div> </td> </tr> <tr id="i8" class="altColor"> <td class="colFirst"><code>static java.util.List&lt;<a href="../../../../com/stuntguy3000/lifxlansdk/object/protocol/Packet.html" title="class in com.stuntguy3000.lifxlansdk.object.protocol">Packet</a>&gt;</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/stuntguy3000/lifxlansdk/handler/PacketHandler.html#sendMessage-com.stuntguy3000.lifxlansdk.object.protocol.abstracts.Message-com.stuntguy3000.lifxlansdk.object.product.Device-boolean-int-int-">sendMessage</a></span>(<a href="../../../../com/stuntguy3000/lifxlansdk/object/protocol/abstracts/Message.html" title="class in com.stuntguy3000.lifxlansdk.object.protocol.abstracts">Message</a>&nbsp;message, <a href="../../../../com/stuntguy3000/lifxlansdk/object/product/Device.html" title="class in com.stuntguy3000.lifxlansdk.object.product">Device</a>&nbsp;device, boolean&nbsp;resultRequired, int&nbsp;maxReceiveMessageCount, int&nbsp;timeout)</code> <div class="block">Send a Message to a device</div> </td> </tr> <tr id="i9" class="rowColor"> <td class="colFirst"><code>static java.util.List&lt;<a href="../../../../com/stuntguy3000/lifxlansdk/object/protocol/Packet.html" title="class in com.stuntguy3000.lifxlansdk.object.protocol">Packet</a>&gt;</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/stuntguy3000/lifxlansdk/handler/PacketHandler.html#sendMessage-com.stuntguy3000.lifxlansdk.object.protocol.abstracts.Message-com.stuntguy3000.lifxlansdk.object.product.Device-boolean-int-int-int-">sendMessage</a></span>(<a href="../../../../com/stuntguy3000/lifxlansdk/object/protocol/abstracts/Message.html" title="class in com.stuntguy3000.lifxlansdk.object.protocol.abstracts">Message</a>&nbsp;message, <a href="../../../../com/stuntguy3000/lifxlansdk/object/product/Device.html" title="class in com.stuntguy3000.lifxlansdk.object.product">Device</a>&nbsp;device, boolean&nbsp;resultRequired, int&nbsp;maxReceiveMessageCount, int&nbsp;timeout, int&nbsp;retry)</code> <div class="block">Send a Message to a device</div> </td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods.inherited.from.class.java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ============ FIELD DETAIL =========== --> <ul class="blockList"> <li class="blockList"><a name="field.detail"> <!-- --> </a> <h3>Field Detail</h3> <a name="responseMessagesMap"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>responseMessagesMap</h4> <pre>private static final&nbsp;java.util.HashMap&lt;java.lang.Integer,java.lang.Class&lt;? extends <a href="../../../../com/stuntguy3000/lifxlansdk/object/protocol/abstracts/Message.html" title="class in com.stuntguy3000.lifxlansdk.object.protocol.abstracts">Message</a>&gt;&gt; responseMessagesMap</pre> <div class="block">A map of packet ID and it's associated Message class for packet object response mapping</div> </li> </ul> <a name="sequence"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>sequence</h4> <pre>private static&nbsp;short sequence</pre> <div class="block">Packet sequence number <p> For usage, see <a href="../../../../com/stuntguy3000/lifxlansdk/handler/PacketHandler.html#getNextPacketSequenceNumber--"><code>getNextPacketSequenceNumber()</code></a></div> </li> </ul> <a name="broadcastAddress"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>broadcastAddress</h4> <pre>private static&nbsp;java.net.InetAddress broadcastAddress</pre> <div class="block">The broadcast address to send packets on.</div> </li> </ul> </li> </ul> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="PacketHandler--"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>PacketHandler</h4> <pre>public&nbsp;PacketHandler()</pre> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method.detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="init--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>init</h4> <pre>private static&nbsp;void&nbsp;init()</pre> <div class="block">Initializes the responseMessagesMap object</div> </li> </ul> <a name="sendMessage-com.stuntguy3000.lifxlansdk.object.protocol.abstracts.Message-com.stuntguy3000.lifxlansdk.object.product.Device-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>sendMessage</h4> <pre>public static&nbsp;java.util.List&lt;<a href="../../../../com/stuntguy3000/lifxlansdk/object/protocol/Packet.html" title="class in com.stuntguy3000.lifxlansdk.object.protocol">Packet</a>&gt;&nbsp;sendMessage(<a href="../../../../com/stuntguy3000/lifxlansdk/object/protocol/abstracts/Message.html" title="class in com.stuntguy3000.lifxlansdk.object.protocol.abstracts">Message</a>&nbsp;message, <a href="../../../../com/stuntguy3000/lifxlansdk/object/product/Device.html" title="class in com.stuntguy3000.lifxlansdk.object.product">Device</a>&nbsp;device)</pre> <div class="block">Send a Message to a device <p> This function piggybacks off other functions to use default values for: - resultRequired - maxReceiveMessageCount - timeout - retry</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>message</code> - the message to send</dd> <dd><code>device</code> - the device to send it to</dd> <dt><span class="returnLabel">Returns:</span></dt> <dd>a list of returned packets (usually 1), can be empty</dd> </dl> </li> </ul> <a name="sendMessage-com.stuntguy3000.lifxlansdk.object.protocol.abstracts.Message-com.stuntguy3000.lifxlansdk.object.product.Device-boolean-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>sendMessage</h4> <pre>public static&nbsp;java.util.List&lt;<a href="../../../../com/stuntguy3000/lifxlansdk/object/protocol/Packet.html" title="class in com.stuntguy3000.lifxlansdk.object.protocol">Packet</a>&gt;&nbsp;sendMessage(<a href="../../../../com/stuntguy3000/lifxlansdk/object/protocol/abstracts/Message.html" title="class in com.stuntguy3000.lifxlansdk.object.protocol.abstracts">Message</a>&nbsp;message, <a href="../../../../com/stuntguy3000/lifxlansdk/object/product/Device.html" title="class in com.stuntguy3000.lifxlansdk.object.product">Device</a>&nbsp;device, boolean&nbsp;resultRequired)</pre> <div class="block">Send a Message to a device <p> This function piggybacks off other functions to use default values for: - maxReceiveMessageCount - timeout - retry</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>message</code> - the message to send</dd> <dd><code>device</code> - the device to send it to</dd> <dd><code>resultRequired</code> - true if a result is required (return packet)</dd> <dt><span class="returnLabel">Returns:</span></dt> <dd>a list of returned packets (usually 1), can be empty</dd> </dl> </li> </ul> <a name="sendMessage-com.stuntguy3000.lifxlansdk.object.protocol.abstracts.Message-com.stuntguy3000.lifxlansdk.object.product.Device-boolean-int-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>sendMessage</h4> <pre>public static&nbsp;java.util.List&lt;<a href="../../../../com/stuntguy3000/lifxlansdk/object/protocol/Packet.html" title="class in com.stuntguy3000.lifxlansdk.object.protocol">Packet</a>&gt;&nbsp;sendMessage(<a href="../../../../com/stuntguy3000/lifxlansdk/object/protocol/abstracts/Message.html" title="class in com.stuntguy3000.lifxlansdk.object.protocol.abstracts">Message</a>&nbsp;message, <a href="../../../../com/stuntguy3000/lifxlansdk/object/product/Device.html" title="class in com.stuntguy3000.lifxlansdk.object.product">Device</a>&nbsp;device, boolean&nbsp;resultRequired, int&nbsp;maxReceiveMessageCount)</pre> <div class="block">Send a Message to a device <p> This function piggybacks off other functions to use default values for: - timeout - retry</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>message</code> - the message to send</dd> <dd><code>device</code> - the device to send it to</dd> <dd><code>resultRequired</code> - true if a result is required (return packet)</dd> <dd><code>maxReceiveMessageCount</code> - the amount of messages to receive before returning all packets (used for optimization)</dd> <dt><span class="returnLabel">Returns:</span></dt> <dd>a list of returned packets (usually 1), can be empty</dd> </dl> </li> </ul> <a name="sendMessage-com.stuntguy3000.lifxlansdk.object.protocol.abstracts.Message-com.stuntguy3000.lifxlansdk.object.product.Device-boolean-int-int-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>sendMessage</h4> <pre>public static&nbsp;java.util.List&lt;<a href="../../../../com/stuntguy3000/lifxlansdk/object/protocol/Packet.html" title="class in com.stuntguy3000.lifxlansdk.object.protocol">Packet</a>&gt;&nbsp;sendMessage(<a href="../../../../com/stuntguy3000/lifxlansdk/object/protocol/abstracts/Message.html" title="class in com.stuntguy3000.lifxlansdk.object.protocol.abstracts">Message</a>&nbsp;message, <a href="../../../../com/stuntguy3000/lifxlansdk/object/product/Device.html" title="class in com.stuntguy3000.lifxlansdk.object.product">Device</a>&nbsp;device, boolean&nbsp;resultRequired, int&nbsp;maxReceiveMessageCount, int&nbsp;timeout)</pre> <div class="block">Send a Message to a device <p> This function piggybacks off other functions to use default values for: - retry</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>message</code> - the message to send</dd> <dd><code>device</code> - the device to send it to</dd> <dd><code>resultRequired</code> - true if a result is required (return packet)</dd> <dd><code>maxReceiveMessageCount</code> - the amount of messages to receive before returning all packets (used for optimization)</dd> <dd><code>timeout</code> - the maximum wait time for replies (in ms)</dd> <dt><span class="returnLabel">Returns:</span></dt> <dd>a list of returned packets (usually 1), can be empty</dd> </dl> </li> </ul> <a name="sendMessage-com.stuntguy3000.lifxlansdk.object.protocol.abstracts.Message-com.stuntguy3000.lifxlansdk.object.product.Device-boolean-int-int-int-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>sendMessage</h4> <pre>public static&nbsp;java.util.List&lt;<a href="../../../../com/stuntguy3000/lifxlansdk/object/protocol/Packet.html" title="class in com.stuntguy3000.lifxlansdk.object.protocol">Packet</a>&gt;&nbsp;sendMessage(<a href="../../../../com/stuntguy3000/lifxlansdk/object/protocol/abstracts/Message.html" title="class in com.stuntguy3000.lifxlansdk.object.protocol.abstracts">Message</a>&nbsp;message, <a href="../../../../com/stuntguy3000/lifxlansdk/object/product/Device.html" title="class in com.stuntguy3000.lifxlansdk.object.product">Device</a>&nbsp;device, boolean&nbsp;resultRequired, int&nbsp;maxReceiveMessageCount, int&nbsp;timeout, int&nbsp;retry)</pre> <div class="block">Send a Message to a device</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>message</code> - the message to send</dd> <dd><code>device</code> - the device to send it to</dd> <dd><code>resultRequired</code> - true if a result is required (return packet)</dd> <dd><code>maxReceiveMessageCount</code> - the amount of messages to receive before returning all packets (used for optimization)</dd> <dd><code>timeout</code> - the maximum wait time for replies (in ms)</dd> <dd><code>retry</code> - the amount of retries if socket the socket timeout is hit</dd> <dt><span class="returnLabel">Returns:</span></dt> <dd>a list of returned packets (usually 1), can be empty</dd> </dl> </li> </ul> <a name="buildPacket-byte:A-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>buildPacket</h4> <pre>private static&nbsp;<a href="../../../../com/stuntguy3000/lifxlansdk/object/protocol/Packet.html" title="class in com.stuntguy3000.lifxlansdk.object.protocol">Packet</a>&nbsp;buildPacket(byte[]&nbsp;receivedData)</pre> <div class="block">Builds a LIFX Packet from received data</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>receivedData</code> - the received data</dd> <dt><span class="returnLabel">Returns:</span></dt> <dd>the constructed packet (or null if invalid)</dd> </dl> </li> </ul> <a name="buildPacket-com.stuntguy3000.lifxlansdk.object.protocol.abstracts.Message-com.stuntguy3000.lifxlansdk.object.product.Device-boolean-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>buildPacket</h4> <pre>private static&nbsp;<a href="../../../../com/stuntguy3000/lifxlansdk/object/protocol/Packet.html" title="class in com.stuntguy3000.lifxlansdk.object.protocol">Packet</a>&nbsp;buildPacket(<a href="../../../../com/stuntguy3000/lifxlansdk/object/protocol/abstracts/Message.html" title="class in com.stuntguy3000.lifxlansdk.object.protocol.abstracts">Message</a>&nbsp;message, <a href="../../../../com/stuntguy3000/lifxlansdk/object/product/Device.html" title="class in com.stuntguy3000.lifxlansdk.object.product">Device</a>&nbsp;device, boolean&nbsp;resultRequired)</pre> <div class="block">Internal packet builder for packets to be sent, not received. For received packet processing, see the other buildPacket function</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>message</code> - the message</dd> <dd><code>device</code> - the targeted device, can be null to represent a broadcast</dd> <dd><code>resultRequired</code> - if a result is required (only useful for controlling Set requests)</dd> <dt><span class="returnLabel">Returns:</span></dt> <dd>the constructed packet (or null)</dd> </dl> </li> </ul> <a name="buildMessage-int-byte:A-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>buildMessage</h4> <pre>private static&nbsp;<a href="../../../../com/stuntguy3000/lifxlansdk/object/protocol/abstracts/Message.html" title="class in com.stuntguy3000.lifxlansdk.object.protocol.abstracts">Message</a>&nbsp;buildMessage(int&nbsp;messageType, byte[]&nbsp;messageBytes)</pre> <div class="block">Builds a LIFX Message</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>messageType</code> - the type of message (packet ID)</dd> <dd><code>messageBytes</code> - the payload data of the message</dd> <dt><span class="returnLabel">Returns:</span></dt> <dd>the constructed message (or null)</dd> </dl> </li> </ul> <a name="getNextPacketSequenceNumber--"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>getNextPacketSequenceNumber</h4> <pre>private static&nbsp;short&nbsp;getNextPacketSequenceNumber()</pre> <div class="block">Increment the packet sequence in a 0-255 loop.</div> <dl> <dt><span class="returnLabel">Returns:</span></dt> <dd>short the next packet sequence number</dd> </dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev&nbsp;Class</li> <li>Next&nbsp;Class</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?com/stuntguy3000/lifxlansdk/handler/PacketHandler.html" target="_top">Frames</a></li> <li><a href="PacketHandler.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#field.summary">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field.detail">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html> ======================= File: docs/index-files/index-3.html ======================= <reponame>stuntguy3000/LIFX-LAN-SDK <!-- ~ Copyright 2021 <NAME> (stuntguy3000) ~ ~ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: ~ ~ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. ~ ~ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_312) on Thu Dec 02 16:48:51 ACDT 2021 --> <title>C-Index</title> <meta name="date" content="2021-12-02"> <link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style"> <script type="text/javascript" src="../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="C-Index"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../overview-summary.html">Overview</a></li> <li>Package</li> <li>Class</li> <li><a href="../overview-tree.html">Tree</a></li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li class="navBarCell1Rev">Index</li> <li><a href="../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="index-2.html">Prev Letter</a></li> <li><a href="index-4.html">Next Letter</a></li> </ul> <ul class="navList"> <li><a href="../index.html?index-files/index-3.html" target="_top">Frames</a></li> <li><a href="index-3.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="contentContainer"><a href="index-1.html">A</a>&nbsp;<a href="index-2.html">B</a>&nbsp;<a href="index-3.html">C</a>&nbsp;<a href="index-4.html">D</a>&nbsp;<a href="index-5.html">E</a>&nbsp;<a href="index-6.html">F</a>&nbsp;<a href="index-7.html">G</a>&nbsp;<a href="index-8.html">H</a>&nbsp;<a href="index-9.html">I</a>&nbsp;<a href="index-10.html">K</a>&nbsp;<a href="index-11.html">L</a>&nbsp;<a href="index-12.html">M</a>&nbsp;<a href="index-13.html">N</a>&nbsp;<a href="index-14.html">O</a>&nbsp;<a href="index-15.html">P</a>&nbsp;<a href="index-16.html">R</a>&nbsp;<a href="index-17.html">S</a>&nbsp;<a href="index-18.html">T</a>&nbsp;<a href="index-19.html">U</a>&nbsp;<a href="index-20.html">V</a>&nbsp;<a href="index-21.html">W</a>&nbsp;<a href="index-22.html">X</a>&nbsp;<a href="index-23.html">Y</a>&nbsp;<a href="index-24.html">Z</a>&nbsp;<a name="I:C"> <!-- --> </a> <h2 class="title">C</h2> <dl> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/object/protocol/Color.html#clone--">clone()</a></span> - Method in class com.stuntguy3000.lifxlansdk.object.protocol.<a href="../com/stuntguy3000/lifxlansdk/object/protocol/Color.html" title="class in com.stuntguy3000.lifxlansdk.object.protocol">Color</a></dt> <dd>&nbsp;</dd> <dt><a href="../com/stuntguy3000/lifxlansdk/object/protocol/Color.html" title="class in com.stuntguy3000.lifxlansdk.object.protocol"><span class="typeNameLink">Color</span></a> - Class in <a href="../com/stuntguy3000/lifxlansdk/object/protocol/package-summary.html">com.stuntguy3000.lifxlansdk.object.protocol</a></dt> <dd> <div class="block">Represents a LIFX color Structure (HSBK)</div> </dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/object/protocol/Color.html#Color--">Color()</a></span> - Constructor for class com.stuntguy3000.lifxlansdk.object.protocol.<a href="../com/stuntguy3000/lifxlansdk/object/protocol/Color.html" title="class in com.stuntguy3000.lifxlansdk.object.protocol">Color</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/messages/state/multizone/StateExtendedColorZones.html#color_count">color_count</a></span> - Variable in class com.stuntguy3000.lifxlansdk.messages.state.multizone.<a href="../com/stuntguy3000/lifxlansdk/messages/state/multizone/StateExtendedColorZones.html" title="class in com.stuntguy3000.lifxlansdk.messages.state.multizone">StateExtendedColorZones</a></dt> <dd> <div class="block">The number of HSBK values in the colors array that map to zones.</div> </dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/messages/set/multizone/SetExtendedColorZones.html#colors">colors</a></span> - Variable in class com.stuntguy3000.lifxlansdk.messages.set.multizone.<a href="../com/stuntguy3000/lifxlansdk/messages/set/multizone/SetExtendedColorZones.html" title="class in com.stuntguy3000.lifxlansdk.messages.set.multizone">SetExtendedColorZones</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/messages/set/tile/Set64.html#colors">colors</a></span> - Variable in class com.stuntguy3000.lifxlansdk.messages.set.tile.<a href="../com/stuntguy3000/lifxlansdk/messages/set/tile/Set64.html" title="class in com.stuntguy3000.lifxlansdk.messages.set.tile">Set64</a></dt> <dd> <div class="block">The HSBK values to assign to each zone specified by this packet.</div> </dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/messages/state/multizone/StateExtendedColorZones.html#colors">colors</a></span> - Variable in class com.stuntguy3000.lifxlansdk.messages.state.multizone.<a href="../com/stuntguy3000/lifxlansdk/messages/state/multizone/StateExtendedColorZones.html" title="class in com.stuntguy3000.lifxlansdk.messages.state.multizone">StateExtendedColorZones</a></dt> <dd> <div class="block">The HSBK values currently set on each zone.</div> </dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/messages/state/multizone/StateMultiZone.html#colors">colors</a></span> - Variable in class com.stuntguy3000.lifxlansdk.messages.state.multizone.<a href="../com/stuntguy3000/lifxlansdk/messages/state/multizone/StateMultiZone.html" title="class in com.stuntguy3000.lifxlansdk.messages.state.multizone">StateMultiZone</a></dt> <dd> <div class="block"><span class="deprecatedLabel">Deprecated.</span></div> <div class="block">The HSBK values of the zones this packet refers to.</div> </dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/messages/state/tile/State64.html#colors">colors</a></span> - Variable in class com.stuntguy3000.lifxlansdk.messages.state.tile.<a href="../com/stuntguy3000/lifxlansdk/messages/state/tile/State64.html" title="class in com.stuntguy3000.lifxlansdk.messages.state.tile">State64</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/messages/set/multizone/SetExtendedColorZones.html#colors_count">colors_count</a></span> - Variable in class com.stuntguy3000.lifxlansdk.messages.set.multizone.<a href="../com/stuntguy3000/lifxlansdk/messages/set/multizone/SetExtendedColorZones.html" title="class in com.stuntguy3000.lifxlansdk.messages.set.multizone">SetExtendedColorZones</a></dt> <dd>&nbsp;</dd> <dt><a href="../com/stuntguy3000/lifxlansdk/handler/package-summary.html">com.stuntguy3000.lifxlansdk.handler</a> - package com.stuntguy3000.lifxlansdk.handler</dt> <dd>&nbsp;</dd> <dt><a href="../com/stuntguy3000/lifxlansdk/helper/package-summary.html">com.stuntguy3000.lifxlansdk.helper</a> - package com.stuntguy3000.lifxlansdk.helper</dt> <dd>&nbsp;</dd> <dt><a href="../com/stuntguy3000/lifxlansdk/messages/get/device/package-summary.html">com.stuntguy3000.lifxlansdk.messages.get.device</a> - package com.stuntguy3000.lifxlansdk.messages.get.device</dt> <dd>&nbsp;</dd> <dt><a href="../com/stuntguy3000/lifxlansdk/messages/get/discovery/package-summary.html">com.stuntguy3000.lifxlansdk.messages.get.discovery</a> - package com.stuntguy3000.lifxlansdk.messages.get.discovery</dt> <dd>&nbsp;</dd> <dt><a href="../com/stuntguy3000/lifxlansdk/messages/get/light/package-summary.html">com.stuntguy3000.lifxlansdk.messages.get.light</a> - package com.stuntguy3000.lifxlansdk.messages.get.light</dt> <dd>&nbsp;</dd> <dt><a href="../com/stuntguy3000/lifxlansdk/messages/get/multizone/package-summary.html">com.stuntguy3000.lifxlansdk.messages.get.multizone</a> - package com.stuntguy3000.lifxlansdk.messages.get.multizone</dt> <dd>&nbsp;</dd> <dt><a href="../com/stuntguy3000/lifxlansdk/messages/get/relay/package-summary.html">com.stuntguy3000.lifxlansdk.messages.get.relay</a> - package com.stuntguy3000.lifxlansdk.messages.get.relay</dt> <dd>&nbsp;</dd> <dt><a href="../com/stuntguy3000/lifxlansdk/messages/get/tile/package-summary.html">com.stuntguy3000.lifxlansdk.messages.get.tile</a> - package com.stuntguy3000.lifxlansdk.messages.get.tile</dt> <dd>&nbsp;</dd> <dt><a href="../com/stuntguy3000/lifxlansdk/messages/set/device/package-summary.html">com.stuntguy3000.lifxlansdk.messages.set.device</a> - package com.stuntguy3000.lifxlansdk.messages.set.device</dt> <dd>&nbsp;</dd> <dt><a href="../com/stuntguy3000/lifxlansdk/messages/set/light/package-summary.html">com.stuntguy3000.lifxlansdk.messages.set.light</a> - package com.stuntguy3000.lifxlansdk.messages.set.light</dt> <dd>&nbsp;</dd> <dt><a href="../com/stuntguy3000/lifxlansdk/messages/set/multizone/package-summary.html">com.stuntguy3000.lifxlansdk.messages.set.multizone</a> - package com.stuntguy3000.lifxlansdk.messages.set.multizone</dt> <dd>&nbsp;</dd> <dt><a href="../com/stuntguy3000/lifxlansdk/messages/set/relay/package-summary.html">com.stuntguy3000.lifxlansdk.messages.set.relay</a> - package com.stuntguy3000.lifxlansdk.messages.set.relay</dt> <dd>&nbsp;</dd> <dt><a href="../com/stuntguy3000/lifxlansdk/messages/set/tile/package-summary.html">com.stuntguy3000.lifxlansdk.messages.set.tile</a> - package com.stuntguy3000.lifxlansdk.messages.set.tile</dt> <dd>&nbsp;</dd> <dt><a href="../com/stuntguy3000/lifxlansdk/messages/state/core/package-summary.html">com.stuntguy3000.lifxlansdk.messages.state.core</a> - package com.stuntguy3000.lifxlansdk.messages.state.core</dt> <dd>&nbsp;</dd> <dt><a href="../com/stuntguy3000/lifxlansdk/messages/state/device/package-summary.html">com.stuntguy3000.lifxlansdk.messages.state.device</a> - package com.stuntguy3000.lifxlansdk.messages.state.device</dt> <dd>&nbsp;</dd> <dt><a href="../com/stuntguy3000/lifxlansdk/messages/state/discovery/package-summary.html">com.stuntguy3000.lifxlansdk.messages.state.discovery</a> - package com.stuntguy3000.lifxlansdk.messages.state.discovery</dt> <dd>&nbsp;</dd> <dt><a href="../com/stuntguy3000/lifxlansdk/messages/state/light/package-summary.html">com.stuntguy3000.lifxlansdk.messages.state.light</a> - package com.stuntguy3000.lifxlansdk.messages.state.light</dt> <dd>&nbsp;</dd> <dt><a href="../com/stuntguy3000/lifxlansdk/messages/state/multizone/package-summary.html">com.stuntguy3000.lifxlansdk.messages.state.multizone</a> - package com.stuntguy3000.lifxlansdk.messages.state.multizone</dt> <dd>&nbsp;</dd> <dt><a href="../com/stuntguy3000/lifxlansdk/messages/state/relay/package-summary.html">com.stuntguy3000.lifxlansdk.messages.state.relay</a> - package com.stuntguy3000.lifxlansdk.messages.state.relay</dt> <dd>&nbsp;</dd> <dt><a href="../com/stuntguy3000/lifxlansdk/messages/state/tile/package-summary.html">com.stuntguy3000.lifxlansdk.messages.state.tile</a> - package com.stuntguy3000.lifxlansdk.messages.state.tile</dt> <dd>&nbsp;</dd> <dt><a href="../com/stuntguy3000/lifxlansdk/object/product/package-summary.html">com.stuntguy3000.lifxlansdk.object.product</a> - package com.stuntguy3000.lifxlansdk.object.product</dt> <dd>&nbsp;</dd> <dt><a href="../com/stuntguy3000/lifxlansdk/object/protocol/package-summary.html">com.stuntguy3000.lifxlansdk.object.protocol</a> - package com.stuntguy3000.lifxlansdk.object.protocol</dt> <dd>&nbsp;</dd> <dt><a href="../com/stuntguy3000/lifxlansdk/object/protocol/abstracts/package-summary.html">com.stuntguy3000.lifxlansdk.object.protocol.abstracts</a> - package com.stuntguy3000.lifxlansdk.object.protocol.abstracts</dt> <dd>&nbsp;</dd> <dt><a href="../com/stuntguy3000/lifxlansdk/object/protocol/enums/package-summary.html">com.stuntguy3000.lifxlansdk.object.protocol.enums</a> - package com.stuntguy3000.lifxlansdk.object.protocol.enums</dt> <dd>&nbsp;</dd> <dt><a href="../com/stuntguy3000/lifxlansdk/test/package-summary.html">com.stuntguy3000.lifxlansdk.test</a> - package com.stuntguy3000.lifxlansdk.test</dt> <dd>&nbsp;</dd> <dt><a href="../com/stuntguy3000/lifxlansdk/util/package-summary.html">com.stuntguy3000.lifxlansdk.util</a> - package com.stuntguy3000.lifxlansdk.util</dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/object/protocol/Color.html#CYAN">CYAN</a></span> - Static variable in class com.stuntguy3000.lifxlansdk.object.protocol.<a href="../com/stuntguy3000/lifxlansdk/object/protocol/Color.html" title="class in com.stuntguy3000.lifxlansdk.object.protocol">Color</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/messages/set/light/SetWaveform.html#cycles">cycles</a></span> - Variable in class com.stuntguy3000.lifxlansdk.messages.set.light.<a href="../com/stuntguy3000/lifxlansdk/messages/set/light/SetWaveform.html" title="class in com.stuntguy3000.lifxlansdk.messages.set.light">SetWaveform</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/messages/set/light/SetWaveformOptional.html#cycles">cycles</a></span> - Variable in class com.stuntguy3000.lifxlansdk.messages.set.light.<a href="../com/stuntguy3000/lifxlansdk/messages/set/light/SetWaveformOptional.html" title="class in com.stuntguy3000.lifxlansdk.messages.set.light">SetWaveformOptional</a></dt> <dd>&nbsp;</dd> </dl> <a href="index-1.html">A</a>&nbsp;<a href="index-2.html">B</a>&nbsp;<a href="index-3.html">C</a>&nbsp;<a href="index-4.html">D</a>&nbsp;<a href="index-5.html">E</a>&nbsp;<a href="index-6.html">F</a>&nbsp;<a href="index-7.html">G</a>&nbsp;<a href="index-8.html">H</a>&nbsp;<a href="index-9.html">I</a>&nbsp;<a href="index-10.html">K</a>&nbsp;<a href="index-11.html">L</a>&nbsp;<a href="index-12.html">M</a>&nbsp;<a href="index-13.html">N</a>&nbsp;<a href="index-14.html">O</a>&nbsp;<a href="index-15.html">P</a>&nbsp;<a href="index-16.html">R</a>&nbsp;<a href="index-17.html">S</a>&nbsp;<a href="index-18.html">T</a>&nbsp;<a href="index-19.html">U</a>&nbsp;<a href="index-20.html">V</a>&nbsp;<a href="index-21.html">W</a>&nbsp;<a href="index-22.html">X</a>&nbsp;<a href="index-23.html">Y</a>&nbsp;<a href="index-24.html">Z</a>&nbsp;</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../overview-summary.html">Overview</a></li> <li>Package</li> <li>Class</li> <li><a href="../overview-tree.html">Tree</a></li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li class="navBarCell1Rev">Index</li> <li><a href="../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="index-2.html">Prev Letter</a></li> <li><a href="index-4.html">Next Letter</a></li> </ul> <ul class="navList"> <li><a href="../index.html?index-files/index-3.html" target="_top">Frames</a></li> <li><a href="index-3.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html> ======================= File: docs/com/stuntguy3000/lifxlansdk/object/product/Device.html ======================= <gh_stars>1-10 <!-- ~ Copyright 2021 <NAME> (stuntguy3000) ~ ~ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: ~ ~ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. ~ ~ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_312) on Thu Dec 02 16:48:50 ACDT 2021 --> <title>Device</title> <meta name="date" content="2021-12-02"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Device"; } } catch(err) { } //--> var methods = {"i0":10,"i1":10,"i2":10,"i3":10,"i4":10,"i5":10,"i6":10,"i7":10,"i8":10,"i9":10,"i10":10,"i11":10,"i12":10,"i13":10,"i14":10,"i15":10,"i16":10}; var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],8:["t4","Concrete Methods"]}; var altColor = "altColor"; var rowColor = "rowColor"; var tableTab = "tableTab"; var activeTableTab = "activeTableTab"; </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev&nbsp;Class</li> <li><a href="../../../../../com/stuntguy3000/lifxlansdk/object/product/Light.html" title="class in com.stuntguy3000.lifxlansdk.object.product"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/stuntguy3000/lifxlansdk/object/product/Device.html" target="_top">Frames</a></li> <li><a href="Device.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#field.summary">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field.detail">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">com.stuntguy3000.lifxlansdk.object.product</div> <h2 title="Class Device" class="title">Class Device</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>com.stuntguy3000.lifxlansdk.object.product.Device</li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>All Implemented Interfaces:</dt> <dd><a href="../../../../../com/stuntguy3000/lifxlansdk/object/protocol/abstracts/StateSavable.html" title="interface in com.stuntguy3000.lifxlansdk.object.protocol.abstracts">StateSavable</a></dd> </dl> <dl> <dt>Direct Known Subclasses:</dt> <dd><a href="../../../../../com/stuntguy3000/lifxlansdk/object/product/Light.html" title="class in com.stuntguy3000.lifxlansdk.object.product">Light</a>, <a href="../../../../../com/stuntguy3000/lifxlansdk/object/product/Relay.html" title="class in com.stuntguy3000.lifxlansdk.object.product">Relay</a></dd> </dl> <hr> <br> <pre>public class <span class="typeNameLabel">Device</span> extends java.lang.Object implements <a href="../../../../../com/stuntguy3000/lifxlansdk/object/protocol/abstracts/StateSavable.html" title="interface in com.stuntguy3000.lifxlansdk.object.protocol.abstracts">StateSavable</a></pre> <div class="block">Represents a LIFX Device <p> LIFX devices are more than lights, they can include relay switches. <p> Are you looking for <a href="../../../../../com/stuntguy3000/lifxlansdk/object/product/Light.html" title="class in com.stuntguy3000.lifxlansdk.object.product"><code>Light</code></a>?</div> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- =========== FIELD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="field.summary"> <!-- --> </a> <h3>Field Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation"> <caption><span>Fields</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Field and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>private java.net.InetAddress</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/stuntguy3000/lifxlansdk/object/product/Device.html#ipAddress">ipAddress</a></span></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>private java.lang.String</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/stuntguy3000/lifxlansdk/object/product/Device.html#macAddress">macAddress</a></span></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>private int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/stuntguy3000/lifxlansdk/object/product/Device.html#servicePort">servicePort</a></span></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>private <a href="../../../../../com/stuntguy3000/lifxlansdk/messages/state/device/StateGroup.html" title="class in com.stuntguy3000.lifxlansdk.messages.state.device">StateGroup</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/stuntguy3000/lifxlansdk/object/product/Device.html#stateGroup">stateGroup</a></span></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>private <a href="../../../../../com/stuntguy3000/lifxlansdk/messages/state/device/StateLabel.html" title="class in com.stuntguy3000.lifxlansdk.messages.state.device">StateLabel</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/stuntguy3000/lifxlansdk/object/product/Device.html#stateLabel">stateLabel</a></span></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>private <a href="../../../../../com/stuntguy3000/lifxlansdk/messages/state/device/StateLocation.html" title="class in com.stuntguy3000.lifxlansdk.messages.state.device">StateLocation</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/stuntguy3000/lifxlansdk/object/product/Device.html#stateLocation">stateLocation</a></span></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>private <a href="../../../../../com/stuntguy3000/lifxlansdk/messages/state/device/StateVersion.html" title="class in com.stuntguy3000.lifxlansdk.messages.state.device">StateVersion</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/stuntguy3000/lifxlansdk/object/product/Device.html#stateVersion">stateVersion</a></span></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>private <a href="../../../../../com/stuntguy3000/lifxlansdk/object/protocol/enums/DeviceType.html" title="enum in com.stuntguy3000.lifxlansdk.object.protocol.enums">DeviceType</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/stuntguy3000/lifxlansdk/object/product/Device.html#type">type</a></span></code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><span class="memberNameLink"><a href="../../../../../com/stuntguy3000/lifxlansdk/object/product/Device.html#Device-java.net.InetAddress-java.lang.String-int-">Device</a></span>(java.net.InetAddress&nbsp;ipAddress, java.lang.String&nbsp;macAddress, int&nbsp;servicePort)</code> <div class="block">Construct a new Device</div> </td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method.summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd">&nbsp;</span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd">&nbsp;</span></span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr id="i0" class="altColor"> <td class="colFirst"><code><a href="../../../../../com/stuntguy3000/lifxlansdk/messages/state/device/EchoResponse.html" title="class in com.stuntguy3000.lifxlansdk.messages.state.device">EchoResponse</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/stuntguy3000/lifxlansdk/object/product/Device.html#echoRequest-java.lang.String-">echoRequest</a></span>(java.lang.String&nbsp;message)</code> <div class="block">Echo request</div> </td> </tr> <tr id="i1" class="rowColor"> <td class="colFirst"><code><a href="../../../../../com/stuntguy3000/lifxlansdk/messages/state/device/StateGroup.html" title="class in com.stuntguy3000.lifxlansdk.messages.state.device">StateGroup</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/stuntguy3000/lifxlansdk/object/product/Device.html#fetchGroup--">fetchGroup</a></span>()</code> <div class="block">Fetches the device's group (and updates local cache)</div> </td> </tr> <tr id="i2" class="altColor"> <td class="colFirst"><code><a href="../../../../../com/stuntguy3000/lifxlansdk/messages/state/device/StateLabel.html" title="class in com.stuntguy3000.lifxlansdk.messages.state.device">StateLabel</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/stuntguy3000/lifxlansdk/object/product/Device.html#fetchLabel--">fetchLabel</a></span>()</code> <div class="block">Fetches the device's label (and updates local cache)</div> </td> </tr> <tr id="i3" class="rowColor"> <td class="colFirst"><code><a href="../../../../../com/stuntguy3000/lifxlansdk/messages/state/device/StateLocation.html" title="class in com.stuntguy3000.lifxlansdk.messages.state.device">StateLocation</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/stuntguy3000/lifxlansdk/object/product/Device.html#fetchLocation--">fetchLocation</a></span>()</code> <div class="block">Fetches the device's location (and updates local cache)</div> </td> </tr> <tr id="i4" class="altColor"> <td class="colFirst"><code><a href="../../../../../com/stuntguy3000/lifxlansdk/messages/state/device/StateHostFirmware.html" title="class in com.stuntguy3000.lifxlansdk.messages.state.device">StateHostFirmware</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/stuntguy3000/lifxlansdk/object/product/Device.html#getHostFirmware--">getHostFirmware</a></span>()</code> <div class="block">Get Host Firmware</div> </td> </tr> <tr id="i5" class="rowColor"> <td class="colFirst"><code><a href="../../../../../com/stuntguy3000/lifxlansdk/messages/state/device/StateInfo.html" title="class in com.stuntguy3000.lifxlansdk.messages.state.device">StateInfo</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/stuntguy3000/lifxlansdk/object/product/Device.html#getInfo--">getInfo</a></span>()</code> <div class="block">Get device information</div> </td> </tr> <tr id="i6" class="altColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/stuntguy3000/lifxlansdk/object/product/Device.html#getLabel--">getLabel</a></span>()</code> <div class="block">A special helper function to streamline accessing the cached label of this device</div> </td> </tr> <tr id="i7" class="rowColor"> <td class="colFirst"><code>private <a href="../../../../../com/stuntguy3000/lifxlansdk/messages/state/device/StatePower.html" title="class in com.stuntguy3000.lifxlansdk.messages.state.device">StatePower</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/stuntguy3000/lifxlansdk/object/product/Device.html#getPower--">getPower</a></span>()</code> <div class="block">Get device power</div> </td> </tr> <tr id="i8" class="altColor"> <td class="colFirst"><code><a href="../../../../../com/stuntguy3000/lifxlansdk/messages/state/device/StateWifiFirmware.html" title="class in com.stuntguy3000.lifxlansdk.messages.state.device">StateWifiFirmware</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/stuntguy3000/lifxlansdk/object/product/Device.html#getWifiFirmware--">getWifiFirmware</a></span>()</code> <div class="block">Get WiFi Firmware</div> </td> </tr> <tr id="i9" class="rowColor"> <td class="colFirst"><code><a href="../../../../../com/stuntguy3000/lifxlansdk/messages/state/device/StateWifiInfo.html" title="class in com.stuntguy3000.lifxlansdk.messages.state.device">StateWifiInfo</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/stuntguy3000/lifxlansdk/object/product/Device.html#getWifiInfo--">getWifiInfo</a></span>()</code> <div class="block">Get WiFi Info</div> </td> </tr> <tr id="i10" class="altColor"> <td class="colFirst"><code>private void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/stuntguy3000/lifxlansdk/object/product/Device.html#init--">init</a></span>()</code> <div class="block">For static (or mostly-static) device information, save the developer some time and pre-fetch this information.</div> </td> </tr> <tr id="i11" class="rowColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/stuntguy3000/lifxlansdk/object/product/Device.html#isPowered--">isPowered</a></span>()</code> <div class="block">Returns if the device is powered</div> </td> </tr> <tr id="i12" class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/stuntguy3000/lifxlansdk/object/product/Device.html#reboot--">reboot</a></span>()</code> <div class="block">Reboot the device</div> </td> </tr> <tr id="i13" class="rowColor"> <td class="colFirst"><code><a href="../../../../../com/stuntguy3000/lifxlansdk/messages/state/device/StateGroup.html" title="class in com.stuntguy3000.lifxlansdk.messages.state.device">StateGroup</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/stuntguy3000/lifxlansdk/object/product/Device.html#setGroup-java.util.UUID-java.lang.String-">setGroup</a></span>(java.util.UUID&nbsp;group, java.lang.String&nbsp;label)</code> <div class="block">Set the group of the device</div> </td> </tr> <tr id="i14" class="altColor"> <td class="colFirst"><code><a href="../../../../../com/stuntguy3000/lifxlansdk/messages/state/device/StateLabel.html" title="class in com.stuntguy3000.lifxlansdk.messages.state.device">StateLabel</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/stuntguy3000/lifxlansdk/object/product/Device.html#setLabel-java.lang.String-">setLabel</a></span>(java.lang.String&nbsp;label)</code> <div class="block">Set the label of the device</div> </td> </tr> <tr id="i15" class="rowColor"> <td class="colFirst"><code><a href="../../../../../com/stuntguy3000/lifxlansdk/messages/state/device/StateLocation.html" title="class in com.stuntguy3000.lifxlansdk.messages.state.device">StateLocation</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/stuntguy3000/lifxlansdk/object/product/Device.html#setLocation-java.util.UUID-java.lang.String-">setLocation</a></span>(java.util.UUID&nbsp;location, java.lang.String&nbsp;label)</code> <div class="block">Set the location of the device</div> </td> </tr> <tr id="i16" class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/stuntguy3000/lifxlansdk/object/product/Device.html#setPower-boolean-">setPower</a></span>(boolean&nbsp;powered)</code> <div class="block">Set the power state of the device</div> </td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods.inherited.from.class.java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="methods.inherited.from.class.com.stuntguy3000.lifxlansdk.object.protocol.abstracts.StateSavable"> <!-- --> </a> <h3>Methods inherited from interface&nbsp;com.stuntguy3000.lifxlansdk.object.protocol.abstracts.<a href="../../../../../com/stuntguy3000/lifxlansdk/object/protocol/abstracts/StateSavable.html" title="interface in com.stuntguy3000.lifxlansdk.object.protocol.abstracts">StateSavable</a></h3> <code><a href="../../../../../com/stuntguy3000/lifxlansdk/object/protocol/abstracts/StateSavable.html#restoreState-int-">restoreState</a>, <a href="../../../../../com/stuntguy3000/lifxlansdk/object/protocol/abstracts/StateSavable.html#saveState--">saveState</a></code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ============ FIELD DETAIL =========== --> <ul class="blockList"> <li class="blockList"><a name="field.detail"> <!-- --> </a> <h3>Field Detail</h3> <a name="ipAddress"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>ipAddress</h4> <pre>private final&nbsp;java.net.InetAddress ipAddress</pre> </li> </ul> <a name="macAddress"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>macAddress</h4> <pre>private final&nbsp;java.lang.String macAddress</pre> </li> </ul> <a name="servicePort"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>servicePort</h4> <pre>private final&nbsp;int servicePort</pre> </li> </ul> <a name="stateLabel"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>stateLabel</h4> <pre>private&nbsp;<a href="../../../../../com/stuntguy3000/lifxlansdk/messages/state/device/StateLabel.html" title="class in com.stuntguy3000.lifxlansdk.messages.state.device">StateLabel</a> stateLabel</pre> </li> </ul> <a name="stateLocation"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>stateLocation</h4> <pre>private&nbsp;<a href="../../../../../com/stuntguy3000/lifxlansdk/messages/state/device/StateLocation.html" title="class in com.stuntguy3000.lifxlansdk.messages.state.device">StateLocation</a> stateLocation</pre> </li> </ul> <a name="stateGroup"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>stateGroup</h4> <pre>private&nbsp;<a href="../../../../../com/stuntguy3000/lifxlansdk/messages/state/device/StateGroup.html" title="class in com.stuntguy3000.lifxlansdk.messages.state.device">StateGroup</a> stateGroup</pre> </li> </ul> <a name="stateVersion"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>stateVersion</h4> <pre>private&nbsp;<a href="../../../../../com/stuntguy3000/lifxlansdk/messages/state/device/StateVersion.html" title="class in com.stuntguy3000.lifxlansdk.messages.state.device">StateVersion</a> stateVersion</pre> </li> </ul> <a name="type"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>type</h4> <pre>private&nbsp;<a href="../../../../../com/stuntguy3000/lifxlansdk/object/protocol/enums/DeviceType.html" title="enum in com.stuntguy3000.lifxlansdk.object.protocol.enums">DeviceType</a> type</pre> </li> </ul> </li> </ul> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="Device-java.net.InetAddress-java.lang.String-int-"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>Device</h4> <pre>public&nbsp;Device(java.net.InetAddress&nbsp;ipAddress, java.lang.String&nbsp;macAddress, int&nbsp;servicePort)</pre> <div class="block">Construct a new Device</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>ipAddress</code> - the IP address of the device (can be null if unknown)</dd> <dd><code>macAddress</code> - the MAC address of the device</dd> <dd><code>servicePort</code> - the port to communicate on</dd> </dl> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method.detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="init--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>init</h4> <pre>private&nbsp;void&nbsp;init()</pre> <div class="block">For static (or mostly-static) device information, save the developer some time and pre-fetch this information. <p> This can lead to some inconsistencies if these pieces of information change, which is unlikely. <p> Specific fetch functions exist for these data fields if they must be up-to-date.</div> </li> </ul> <a name="fetchLabel--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>fetchLabel</h4> <pre>public&nbsp;<a href="../../../../../com/stuntguy3000/lifxlansdk/messages/state/device/StateLabel.html" title="class in com.stuntguy3000.lifxlansdk.messages.state.device">StateLabel</a>&nbsp;fetchLabel()</pre> <div class="block">Fetches the device's label (and updates local cache) <p> This information is precached by <a href="../../../../../com/stuntguy3000/lifxlansdk/object/product/Device.html#init--"><code>init()</code></a>, but, it can change. If you rely on this information always being correct, update the cache through this function.</div> <dl> <dt><span class="returnLabel">Returns:</span></dt> <dd>the response packet object for this request</dd> </dl> </li> </ul> <a name="fetchLocation--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>fetchLocation</h4> <pre>public&nbsp;<a href="../../../../../com/stuntguy3000/lifxlansdk/messages/state/device/StateLocation.html" title="class in com.stuntguy3000.lifxlansdk.messages.state.device">StateLocation</a>&nbsp;fetchLocation()</pre> <div class="block">Fetches the device's location (and updates local cache) <p> This information is precached by <a href="../../../../../com/stuntguy3000/lifxlansdk/object/product/Device.html#init--"><code>init()</code></a>, but, it can change. If you rely on this information always being correct, update the cache through this function.</div> <dl> <dt><span class="returnLabel">Returns:</span></dt> <dd>the response packet object for this request</dd> </dl> </li> </ul> <a name="fetchGroup--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>fetchGroup</h4> <pre>public&nbsp;<a href="../../../../../com/stuntguy3000/lifxlansdk/messages/state/device/StateGroup.html" title="class in com.stuntguy3000.lifxlansdk.messages.state.device">StateGroup</a>&nbsp;fetchGroup()</pre> <div class="block">Fetches the device's group (and updates local cache) <p> This information is precached by <a href="../../../../../com/stuntguy3000/lifxlansdk/object/product/Device.html#init--"><code>init()</code></a>, but, it can change. If you rely on this information always being correct, update the cache through this function.</div> <dl> <dt><span class="returnLabel">Returns:</span></dt> <dd>the response packet object for this request</dd> </dl> </li> </ul> <a name="getLabel--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getLabel</h4> <pre>public&nbsp;java.lang.String&nbsp;getLabel()</pre> <div class="block">A special helper function to streamline accessing the cached label of this device</div> <dl> <dt><span class="returnLabel">Returns:</span></dt> <dd>the label of the device</dd> </dl> </li> </ul> <a name="getHostFirmware--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getHostFirmware</h4> <pre>public&nbsp;<a href="../../../../../com/stuntguy3000/lifxlansdk/messages/state/device/StateHostFirmware.html" title="class in com.stuntguy3000.lifxlansdk.messages.state.device">StateHostFirmware</a>&nbsp;getHostFirmware()</pre> <div class="block">Get Host Firmware <p> See returned object for more information.</div> <dl> <dt><span class="returnLabel">Returns:</span></dt> <dd>the response packet object for this request</dd> </dl> </li> </ul> <a name="getWifiInfo--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getWifiInfo</h4> <pre>public&nbsp;<a href="../../../../../com/stuntguy3000/lifxlansdk/messages/state/device/StateWifiInfo.html" title="class in com.stuntguy3000.lifxlansdk.messages.state.device">StateWifiInfo</a>&nbsp;getWifiInfo()</pre> <div class="block">Get WiFi Info <p> See returned object for more information.</div> <dl> <dt><span class="returnLabel">Returns:</span></dt> <dd>the response packet object for this request</dd> </dl> </li> </ul> <a name="getWifiFirmware--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getWifiFirmware</h4> <pre>public&nbsp;<a href="../../../../../com/stuntguy3000/lifxlansdk/messages/state/device/StateWifiFirmware.html" title="class in com.stuntguy3000.lifxlansdk.messages.state.device">StateWifiFirmware</a>&nbsp;getWifiFirmware()</pre> <div class="block">Get WiFi Firmware <p> See returned object for more information.</div> <dl> <dt><span class="returnLabel">Returns:</span></dt> <dd>the response packet object for this request</dd> </dl> </li> </ul> <a name="getPower--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getPower</h4> <pre>private&nbsp;<a href="../../../../../com/stuntguy3000/lifxlansdk/messages/state/device/StatePower.html" title="class in com.stuntguy3000.lifxlansdk.messages.state.device">StatePower</a>&nbsp;getPower()</pre> <div class="block">Get device power <p> See returned object for more information.</div> <dl> <dt><span class="returnLabel">Returns:</span></dt> <dd>the response packet object for this request</dd> </dl> </li> </ul> <a name="setPower-boolean-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setPower</h4> <pre>public&nbsp;void&nbsp;setPower(boolean&nbsp;powered)</pre> <div class="block">Set the power state of the device</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>powered</code> - true if the device is powered</dd> </dl> </li> </ul> <a name="isPowered--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>isPowered</h4> <pre>public&nbsp;boolean&nbsp;isPowered()</pre> <div class="block">Returns if the device is powered <p> Shortcut-function from <a href="../../../../../com/stuntguy3000/lifxlansdk/object/product/Device.html#getPower--"><code>getPower()</code></a></div> <dl> <dt><span class="returnLabel">Returns:</span></dt> <dd>true if the device is powered</dd> </dl> </li> </ul> <a name="getInfo--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getInfo</h4> <pre>public&nbsp;<a href="../../../../../com/stuntguy3000/lifxlansdk/messages/state/device/StateInfo.html" title="class in com.stuntguy3000.lifxlansdk.messages.state.device">StateInfo</a>&nbsp;getInfo()</pre> <div class="block">Get device information <p> See returned object for more information.</div> <dl> <dt><span class="returnLabel">Returns:</span></dt> <dd>the response packet object for this request</dd> </dl> </li> </ul> <a name="echoRequest-java.lang.String-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>echoRequest</h4> <pre>public&nbsp;<a href="../../../../../com/stuntguy3000/lifxlansdk/messages/state/device/EchoResponse.html" title="class in com.stuntguy3000.lifxlansdk.messages.state.device">EchoResponse</a>&nbsp;echoRequest(java.lang.String&nbsp;message)</pre> <div class="block">Echo request</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>message</code> - the message to be echoed by the device</dd> <dt><span class="returnLabel">Returns:</span></dt> <dd>the response packet object for this request</dd> </dl> </li> </ul> <a name="setLabel-java.lang.String-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setLabel</h4> <pre>public&nbsp;<a href="../../../../../com/stuntguy3000/lifxlansdk/messages/state/device/StateLabel.html" title="class in com.stuntguy3000.lifxlansdk.messages.state.device">StateLabel</a>&nbsp;setLabel(java.lang.String&nbsp;label)</pre> <div class="block">Set the label of the device</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>label</code> - the desired label</dd> <dt><span class="returnLabel">Returns:</span></dt> <dd>the response packet object for this request</dd> </dl> </li> </ul> <a name="reboot--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>reboot</h4> <pre>public&nbsp;void&nbsp;reboot()</pre> <div class="block">Reboot the device</div> </li> </ul> <a name="setLocation-java.util.UUID-java.lang.String-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setLocation</h4> <pre>public&nbsp;<a href="../../../../../com/stuntguy3000/lifxlansdk/messages/state/device/StateLocation.html" title="class in com.stuntguy3000.lifxlansdk.messages.state.device">StateLocation</a>&nbsp;setLocation(java.util.UUID&nbsp;location, java.lang.String&nbsp;label)</pre> <div class="block">Set the location of the device</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>location</code> - the UUID id of the location</dd> <dd><code>label</code> - the label of the location</dd> <dt><span class="returnLabel">Returns:</span></dt> <dd>the response packet object for this request</dd> </dl> </li> </ul> <a name="setGroup-java.util.UUID-java.lang.String-"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>setGroup</h4> <pre>public&nbsp;<a href="../../../../../com/stuntguy3000/lifxlansdk/messages/state/device/StateGroup.html" title="class in com.stuntguy3000.lifxlansdk.messages.state.device">StateGroup</a>&nbsp;setGroup(java.util.UUID&nbsp;group, java.lang.String&nbsp;label)</pre> <div class="block">Set the group of the device</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>group</code> - the UUID id of the group</dd> <dd><code>label</code> - the label of the group</dd> <dt><span class="returnLabel">Returns:</span></dt> <dd>the response packet object for this request</dd> </dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev&nbsp;Class</li> <li><a href="../../../../../com/stuntguy3000/lifxlansdk/object/product/Light.html" title="class in com.stuntguy3000.lifxlansdk.object.product"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/stuntguy3000/lifxlansdk/object/product/Device.html" target="_top">Frames</a></li> <li><a href="Device.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#field.summary">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field.detail">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html> ======================= File: docs/index-files/index-11.html ======================= <filename>docs/index-files/index-11.html <!-- ~ Copyright 2021 <NAME> (stuntguy3000) ~ ~ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: ~ ~ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. ~ ~ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_312) on Thu Dec 02 16:48:51 ACDT 2021 --> <title>L-Index</title> <meta name="date" content="2021-12-02"> <link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style"> <script type="text/javascript" src="../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="L-Index"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../overview-summary.html">Overview</a></li> <li>Package</li> <li>Class</li> <li><a href="../overview-tree.html">Tree</a></li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li class="navBarCell1Rev">Index</li> <li><a href="../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="index-10.html">Prev Letter</a></li> <li><a href="index-12.html">Next Letter</a></li> </ul> <ul class="navList"> <li><a href="../index.html?index-files/index-11.html" target="_top">Frames</a></li> <li><a href="index-11.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="contentContainer"><a href="index-1.html">A</a>&nbsp;<a href="index-2.html">B</a>&nbsp;<a href="index-3.html">C</a>&nbsp;<a href="index-4.html">D</a>&nbsp;<a href="index-5.html">E</a>&nbsp;<a href="index-6.html">F</a>&nbsp;<a href="index-7.html">G</a>&nbsp;<a href="index-8.html">H</a>&nbsp;<a href="index-9.html">I</a>&nbsp;<a href="index-10.html">K</a>&nbsp;<a href="index-11.html">L</a>&nbsp;<a href="index-12.html">M</a>&nbsp;<a href="index-13.html">N</a>&nbsp;<a href="index-14.html">O</a>&nbsp;<a href="index-15.html">P</a>&nbsp;<a href="index-16.html">R</a>&nbsp;<a href="index-17.html">S</a>&nbsp;<a href="index-18.html">T</a>&nbsp;<a href="index-19.html">U</a>&nbsp;<a href="index-20.html">V</a>&nbsp;<a href="index-21.html">W</a>&nbsp;<a href="index-22.html">X</a>&nbsp;<a href="index-23.html">Y</a>&nbsp;<a href="index-24.html">Z</a>&nbsp;<a name="I:L"> <!-- --> </a> <h2 class="title">L</h2> <dl> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/messages/set/device/SetGroup.html#label">label</a></span> - Variable in class com.stuntguy3000.lifxlansdk.messages.set.device.<a href="../com/stuntguy3000/lifxlansdk/messages/set/device/SetGroup.html" title="class in com.stuntguy3000.lifxlansdk.messages.set.device">SetGroup</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/messages/set/device/SetLabel.html#label">label</a></span> - Variable in class com.stuntguy3000.lifxlansdk.messages.set.device.<a href="../com/stuntguy3000/lifxlansdk/messages/set/device/SetLabel.html" title="class in com.stuntguy3000.lifxlansdk.messages.set.device">SetLabel</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/messages/set/device/SetLocation.html#label">label</a></span> - Variable in class com.stuntguy3000.lifxlansdk.messages.set.device.<a href="../com/stuntguy3000/lifxlansdk/messages/set/device/SetLocation.html" title="class in com.stuntguy3000.lifxlansdk.messages.set.device">SetLocation</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/messages/state/device/StateGroup.html#label">label</a></span> - Variable in class com.stuntguy3000.lifxlansdk.messages.state.device.<a href="../com/stuntguy3000/lifxlansdk/messages/state/device/StateGroup.html" title="class in com.stuntguy3000.lifxlansdk.messages.state.device">StateGroup</a></dt> <dd> <div class="block">The name assigned to this group</div> </dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/messages/state/device/StateLabel.html#label">label</a></span> - Variable in class com.stuntguy3000.lifxlansdk.messages.state.device.<a href="../com/stuntguy3000/lifxlansdk/messages/state/device/StateLabel.html" title="class in com.stuntguy3000.lifxlansdk.messages.state.device">StateLabel</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/messages/state/device/StateLocation.html#label">label</a></span> - Variable in class com.stuntguy3000.lifxlansdk.messages.state.device.<a href="../com/stuntguy3000/lifxlansdk/messages/state/device/StateLocation.html" title="class in com.stuntguy3000.lifxlansdk.messages.state.device">StateLocation</a></dt> <dd> <div class="block">The name assigned to this location</div> </dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/messages/state/light/LightState.html#label">label</a></span> - Variable in class com.stuntguy3000.lifxlansdk.messages.state.light.<a href="../com/stuntguy3000/lifxlansdk/messages/state/light/LightState.html" title="class in com.stuntguy3000.lifxlansdk.messages.state.light">LightState</a></dt> <dd> <div class="block">The current label on the device.</div> </dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/messages/state/light/StateHevCycle.html#last_power">last_power</a></span> - Variable in class com.stuntguy3000.lifxlansdk.messages.state.light.<a href="../com/stuntguy3000/lifxlansdk/messages/state/light/StateHevCycle.html" title="class in com.stuntguy3000.lifxlansdk.messages.state.light">StateHevCycle</a></dt> <dd> <div class="block">The power state before the HEV cycle started, which will be the power state once the cycle completes.</div> </dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/messages/get/tile/Get64.html#length">length</a></span> - Variable in class com.stuntguy3000.lifxlansdk.messages.get.tile.<a href="../com/stuntguy3000/lifxlansdk/messages/get/tile/Get64.html" title="class in com.stuntguy3000.lifxlansdk.messages.get.tile">Get64</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/messages/set/tile/Set64.html#length">length</a></span> - Variable in class com.stuntguy3000.lifxlansdk.messages.set.tile.<a href="../com/stuntguy3000/lifxlansdk/messages/set/tile/Set64.html" title="class in com.stuntguy3000.lifxlansdk.messages.set.tile">Set64</a></dt> <dd> <div class="block">The number of devices in the chain to change starting from tile_index</div> </dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/messages/set/device/SetPower.html#level">level</a></span> - Variable in class com.stuntguy3000.lifxlansdk.messages.set.device.<a href="../com/stuntguy3000/lifxlansdk/messages/set/device/SetPower.html" title="class in com.stuntguy3000.lifxlansdk.messages.set.device">SetPower</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/messages/set/light/SetLightPower.html#level">level</a></span> - Variable in class com.stuntguy3000.lifxlansdk.messages.set.light.<a href="../com/stuntguy3000/lifxlansdk/messages/set/light/SetLightPower.html" title="class in com.stuntguy3000.lifxlansdk.messages.set.light">SetLightPower</a></dt> <dd> <div class="block">If you specify 0 the light will turn off and if you specify 65535 the device will turn on.</div> </dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/messages/set/relay/SetRPower.html#level">level</a></span> - Variable in class com.stuntguy3000.lifxlansdk.messages.set.relay.<a href="../com/stuntguy3000/lifxlansdk/messages/set/relay/SetRPower.html" title="class in com.stuntguy3000.lifxlansdk.messages.set.relay">SetRPower</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/messages/state/device/StatePower.html#level">level</a></span> - Variable in class com.stuntguy3000.lifxlansdk.messages.state.device.<a href="../com/stuntguy3000/lifxlansdk/messages/state/device/StatePower.html" title="class in com.stuntguy3000.lifxlansdk.messages.state.device">StatePower</a></dt> <dd> <div class="block">The current level of the device's power.</div> </dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/messages/state/light/StateLightPower.html#level">level</a></span> - Variable in class com.stuntguy3000.lifxlansdk.messages.state.light.<a href="../com/stuntguy3000/lifxlansdk/messages/state/light/StateLightPower.html" title="class in com.stuntguy3000.lifxlansdk.messages.state.light">StateLightPower</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/messages/state/relay/StateRPower.html#level">level</a></span> - Variable in class com.stuntguy3000.lifxlansdk.messages.state.relay.<a href="../com/stuntguy3000/lifxlansdk/messages/state/relay/StateRPower.html" title="class in com.stuntguy3000.lifxlansdk.messages.state.relay">StateRPower</a></dt> <dd> <div class="block">The new value of the relay</div> </dd> <dt><a href="../com/stuntguy3000/lifxlansdk/object/product/Light.html" title="class in com.stuntguy3000.lifxlansdk.object.product"><span class="typeNameLink">Light</span></a> - Class in <a href="../com/stuntguy3000/lifxlansdk/object/product/package-summary.html">com.stuntguy3000.lifxlansdk.object.product</a></dt> <dd> <div class="block">Represents a LIFX Light</div> </dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/object/product/Light.html#Light-java.net.InetAddress-java.lang.String-int-">Light(InetAddress, String, int)</a></span> - Constructor for class com.stuntguy3000.lifxlansdk.object.product.<a href="../com/stuntguy3000/lifxlansdk/object/product/Light.html" title="class in com.stuntguy3000.lifxlansdk.object.product">Light</a></dt> <dd> <div class="block">Construct a new light</div> </dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/object/product/Light.html#Light-com.stuntguy3000.lifxlansdk.object.product.Device-">Light(Device)</a></span> - Constructor for class com.stuntguy3000.lifxlansdk.object.product.<a href="../com/stuntguy3000/lifxlansdk/object/product/Light.html" title="class in com.stuntguy3000.lifxlansdk.object.product">Light</a></dt> <dd> <div class="block">Constructs a new Light object</div> </dd> <dt><a href="../com/stuntguy3000/lifxlansdk/helper/LightHelper.html" title="class in com.stuntguy3000.lifxlansdk.helper"><span class="typeNameLink">LightHelper</span></a> - Class in <a href="../com/stuntguy3000/lifxlansdk/helper/package-summary.html">com.stuntguy3000.lifxlansdk.helper</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/helper/LightHelper.html#LightHelper--">LightHelper()</a></span> - Constructor for class com.stuntguy3000.lifxlansdk.helper.<a href="../com/stuntguy3000/lifxlansdk/helper/LightHelper.html" title="class in com.stuntguy3000.lifxlansdk.helper">LightHelper</a></dt> <dd>&nbsp;</dd> <dt><a href="../com/stuntguy3000/lifxlansdk/object/protocol/enums/LightLastHevCycleResult.html" title="enum in com.stuntguy3000.lifxlansdk.object.protocol.enums"><span class="typeNameLink">LightLastHevCycleResult</span></a> - Enum in <a href="../com/stuntguy3000/lifxlansdk/object/protocol/enums/package-summary.html">com.stuntguy3000.lifxlansdk.object.protocol.enums</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/object/protocol/enums/LightLastHevCycleResult.html#LightLastHevCycleResult--">LightLastHevCycleResult()</a></span> - Constructor for enum com.stuntguy3000.lifxlansdk.object.protocol.enums.<a href="../com/stuntguy3000/lifxlansdk/object/protocol/enums/LightLastHevCycleResult.html" title="enum in com.stuntguy3000.lifxlansdk.object.protocol.enums">LightLastHevCycleResult</a></dt> <dd>&nbsp;</dd> <dt><a href="../com/stuntguy3000/lifxlansdk/messages/state/light/LightState.html" title="class in com.stuntguy3000.lifxlansdk.messages.state.light"><span class="typeNameLink">LightState</span></a> - Class in <a href="../com/stuntguy3000/lifxlansdk/messages/state/light/package-summary.html">com.stuntguy3000.lifxlansdk.messages.state.light</a></dt> <dd> <div class="block">The current visual state of the device and it's label</div> </dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/messages/state/light/LightState.html#LightState--">LightState()</a></span> - Constructor for class com.stuntguy3000.lifxlansdk.messages.state.light.<a href="../com/stuntguy3000/lifxlansdk/messages/state/light/LightState.html" title="class in com.stuntguy3000.lifxlansdk.messages.state.light">LightState</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/object/protocol/Color.html#LIME">LIME</a></span> - Static variable in class com.stuntguy3000.lifxlansdk.object.protocol.<a href="../com/stuntguy3000/lifxlansdk/object/protocol/Color.html" title="class in com.stuntguy3000.lifxlansdk.object.protocol">Color</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/util/TypeUtil.html#littleEndianBytesToFloat-byte...-">littleEndianBytesToFloat(byte...)</a></span> - Static method in class com.stuntguy3000.lifxlansdk.util.<a href="../com/stuntguy3000/lifxlansdk/util/TypeUtil.html" title="class in com.stuntguy3000.lifxlansdk.util">TypeUtil</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/util/TypeUtil.html#littleEndianBytesToUint16-byte...-">littleEndianBytesToUint16(byte...)</a></span> - Static method in class com.stuntguy3000.lifxlansdk.util.<a href="../com/stuntguy3000/lifxlansdk/util/TypeUtil.html" title="class in com.stuntguy3000.lifxlansdk.util">TypeUtil</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/util/TypeUtil.html#littleEndianBytesToUint32-byte...-">littleEndianBytesToUint32(byte...)</a></span> - Static method in class com.stuntguy3000.lifxlansdk.util.<a href="../com/stuntguy3000/lifxlansdk/util/TypeUtil.html" title="class in com.stuntguy3000.lifxlansdk.util">TypeUtil</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/util/TypeUtil.html#littleEndianBytesToUint64-byte...-">littleEndianBytesToUint64(byte...)</a></span> - Static method in class com.stuntguy3000.lifxlansdk.util.<a href="../com/stuntguy3000/lifxlansdk/util/TypeUtil.html" title="class in com.stuntguy3000.lifxlansdk.util">TypeUtil</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/util/TypeUtil.html#littleEndianBytesToUint8-byte-">littleEndianBytesToUint8(byte)</a></span> - Static method in class com.stuntguy3000.lifxlansdk.util.<a href="../com/stuntguy3000/lifxlansdk/util/TypeUtil.html" title="class in com.stuntguy3000.lifxlansdk.util">TypeUtil</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/messages/set/device/SetLocation.html#location">location</a></span> - Variable in class com.stuntguy3000.lifxlansdk.messages.set.device.<a href="../com/stuntguy3000/lifxlansdk/messages/set/device/SetLocation.html" title="class in com.stuntguy3000.lifxlansdk.messages.set.device">SetLocation</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/stuntguy3000/lifxlansdk/messages/state/device/StateLocation.html#location">location</a></span> - Variable in class com.stuntguy3000.lifxlansdk.messages.state.device.<a href="../com/stuntguy3000/lifxlansdk/messages/state/device/StateLocation.html" title="class in com.stuntguy3000.lifxlansdk.messages.state.device">StateLocation</a></dt> <dd> <div class="block">The unique identifier of this group as a uuid.</div> </dd> </dl> <a href="index-1.html">A</a>&nbsp;<a href="index-2.html">B</a>&nbsp;<a href="index-3.html">C</a>&nbsp;<a href="index-4.html">D</a>&nbsp;<a href="index-5.html">E</a>&nbsp;<a href="index-6.html">F</a>&nbsp;<a href="index-7.html">G</a>&nbsp;<a href="index-8.html">H</a>&nbsp;<a href="index-9.html">I</a>&nbsp;<a href="index-10.html">K</a>&nbsp;<a href="index-11.html">L</a>&nbsp;<a href="index-12.html">M</a>&nbsp;<a href="index-13.html">N</a>&nbsp;<a href="index-14.html">O</a>&nbsp;<a href="index-15.html">P</a>&nbsp;<a href="index-16.html">R</a>&nbsp;<a href="index-17.html">S</a>&nbsp;<a href="index-18.html">T</a>&nbsp;<a href="index-19.html">U</a>&nbsp;<a href="index-20.html">V</a>&nbsp;<a href="index-21.html">W</a>&nbsp;<a href="index-22.html">X</a>&nbsp;<a href="index-23.html">Y</a>&nbsp;<a href="index-24.html">Z</a>&nbsp;</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../overview-summary.html">Overview</a></li> <li>Package</li> <li>Class</li> <li><a href="../overview-tree.html">Tree</a></li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li class="navBarCell1Rev">Index</li> <li><a href="../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="index-10.html">Prev Letter</a></li> <li><a href="index-12.html">Next Letter</a></li> </ul> <ul class="navList"> <li><a href="../index.html?index-files/index-11.html" target="_top">Frames</a></li> <li><a href="index-11.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html> ======================= File: src/main/java/com/stuntguy3000/lifxlansdk/messages/state/device/StatePower.java ======================= <reponame>stuntguy3000/LIFX-LAN-SDK<gh_stars>1-10 /* * Copyright 2021 <NAME> (stuntguy3000) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.stuntguy3000.lifxlansdk.messages.state.device; import com.stuntguy3000.lifxlansdk.object.protocol.abstracts.Message; import com.stuntguy3000.lifxlansdk.util.TypeUtil; import lombok.Getter; import lombok.Setter; import lombok.ToString; /** * This packet tells us the current power level of the device. 0 means off and any other value means on. Note that 65535 * is full power and during a power transition (i.e. via {@link com.stuntguy3000.lifxlansdk.messages.set.light.SetLightPower} * (117)) the value may be any value between 0 and 65535. * <p> * This packet is the reply to the {@link com.stuntguy3000.lifxlansdk.messages.get.device.GetPower} (20) and {@link * com.stuntguy3000.lifxlansdk.messages.set.device.SetPower} (21) messages */ @Getter @Setter @ToString public class StatePower extends Message { /** * The current level of the device's power. */ private int level; public StatePower() { super(22); } @Override public void decodeBytes(byte[] data) { level = TypeUtil.littleEndianBytesToUint16(data[0], data[1]); } } ======================= File: src/main/java/com/stuntguy3000/lifxlansdk/object/protocol/FrameAddress.java ======================= <filename>src/main/java/com/stuntguy3000/lifxlansdk/object/protocol/FrameAddress.java /* * Copyright 2021 <NAME> (stuntguy3000) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.stuntguy3000.lifxlansdk.object.protocol; import com.stuntguy3000.lifxlansdk.object.protocol.abstracts.ByteData; import com.stuntguy3000.lifxlansdk.util.TypeUtil; import lombok.Getter; import lombok.Setter; import java.io.ByteArrayOutputStream; import java.util.BitSet; /** * Represents a LIFX packet Frame Header * <p> * https://lan.developer.lifx.com/docs/packet-contents#frame-address */ @Getter @Setter public class FrameAddress implements ByteData { /** * 6 byte device address (MAC address) or zero (0) means all devices. The last two bytes should be 0 bytes. */ private String target; /** * State message required. However, Get messages will send State messages anyway and State messages to Set messages * are usually not useful. */ private boolean res_required = true; // Defaulted to True to support SDK functions of returning data /** * Acknowledgement message required */ private boolean ack_required; // Whilst supported, acknowledgements are not used by this SDK /** * Wrap around message sequence number * <p> * The sequence number allows the client to provide a unique value, which will be included by the LIFX device in any * message that is sent in response to a message sent by the client. This allows the client to distinguish between * different messages sent with the same source identifier in the Frame Header. We recommend that your program has * one source value and keeps incrementing sequence per device for each message you send. * <p> * Once sequence reaches the maximum value of 255 for that device, roll it back to 0 and keep incrementing from * there. */ private short sequence; @Override public void decodeBytes(byte[] data) { // target byte[] targetBytes = new byte[6]; System.arraycopy(data, 0, targetBytes, 0, 6); target = TypeUtil.injectColonsIntoMacAddress(TypeUtil.bytesToHex(targetBytes)); // res_required // ack_required BitSet bitSet = BitSet.valueOf(new byte[]{data[14]}); res_required = bitSet.get(0); ack_required = bitSet.get(1); // sequence sequence = data[15]; } @Override public byte[] toBytes() { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); try { // Bytes 0 - 7 (LIFX 0-Indexed Location, Bytes 8 - 15) byteArrayOutputStream.write(TypeUtil.hexToBytes(target.replace("-", "").replaceAll(":", ""))); byteArrayOutputStream.write(0); byteArrayOutputStream.write(0); // Bytes 8 - 13 (LIFX 0-Indexed Location, Bytes 16 - 21) // Reserved Bytes for (int i = 0; i < 6; i++) { byteArrayOutputStream.write(0); } // Byte 14 (LIFX 0-Indexed Location, Bytes 22) // Includes 6 Reserved Bits if (!res_required &&!ack_required) { byteArrayOutputStream.write(0); } else { BitSet bitSet = new BitSet(8); bitSet.set(0, res_required); bitSet.set(1, ack_required); byteArrayOutputStream.write(bitSet.toByteArray()); } // Byte 15 (LIFX 0-Indexed Location, Bytes 23) byte[] sequenceBytes = TypeUtil.uint16ToBytesLittleEndian(sequence); byteArrayOutputStream.write(sequenceBytes[0]); } catch (Exception e) { e.printStackTrace(); } return byteArrayOutputStream.toByteArray(); } } ======================= File: src/main/java/com/stuntguy3000/lifxlansdk/object/product/MultiZone.java ======================= /* * Copyright 2021 <NAME> (stuntguy3000) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.stuntguy3000.lifxlansdk.object.product; import com.stuntguy3000.lifxlansdk.handler.PacketHandler; import com.stuntguy3000.lifxlansdk.messages.get.multizone.GetColorZones; import com.stuntguy3000.lifxlansdk.messages.get.multizone.GetExtendedColorZones; import com.stuntguy3000.lifxlansdk.messages.get.multizone.GetMultiZoneEffect; import com.stuntguy3000.lifxlansdk.messages.set.multizone.SetColorZones; import com.stuntguy3000.lifxlansdk.messages.set.multizone.SetExtendedColorZones; import com.stuntguy3000.lifxlansdk.messages.set.multizone.SetMultiZoneEffect; import com.stuntguy3000.lifxlansdk.messages.state.multizone.StateExtendedColorZones; import com.stuntguy3000.lifxlansdk.messages.state.multizone.StateMultiZone; import com.stuntguy3000.lifxlansdk.messages.state.multizone.StateMultiZoneEffect; import com.stuntguy3000.lifxlansdk.messages.state.multizone.StateZone; import com.stuntguy3000.lifxlansdk.object.protocol.Color; import com.stuntguy3000.lifxlansdk.object.protocol.Packet; import com.stuntguy3000.lifxlansdk.object.protocol.abstracts.Message; import com.stuntguy3000.lifxlansdk.object.protocol.enums.Direction; import com.stuntguy3000.lifxlansdk.object.protocol.enums.MultiZoneApplicationRequest; import com.stuntguy3000.lifxlansdk.object.protocol.enums.MultiZoneEffectType; import com.stuntguy3000.lifxlansdk.object.protocol.enums.MultiZoneExtendedApplicationRequest; import com.stuntguy3000.lifxlansdk.util.TypeUtil; import lombok.Getter; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Random; /** * Represents a LIFX MultiZone light * <p> * Technically speaking, Lights (bulbs) are not MultiZones (strips), but since they share common API calls, we ignore * that definition issue and implement the Light feature set. */ @Getter public class MultiZone extends Light { private int zonesCount; private StateExtendedColorZones savedState; /** * Constructs a new MultiZone object * * @param device the generic device representing the multizone */ public MultiZone(Device device) { super(device.getIpAddress(), device.getMacAddress(), device.getServicePort()); // The device initialization only occurs when we have an IP address, meaning actual communication has occupied // and the device object reflects a real-world device and not a hypothetical one if (device.getIpAddress()!= null) { init(); } } /** * For static (or mostly-static) MultiZone information, save the developer some time and pre-fetch this * information. * <p> * This can lead to some inconsistencies if these pieces of information change, which is unlikely. * <p> * Specific fetch functions exist for these data fields if they must be up-to-date. */ private void init() { zonesCount = getExtendedColorZones().getZones_count(); } /** * Fetches the MultiZones's zonesCount (and updates local cache) * <p> * This information is precached by {@link MultiZone#init()}, but, it can change. If you rely on this information * always being correct, update the cache through this function. * * @return the amount of zones this multizone has */ public int fetchZonesCount() { zonesCount = getExtendedColorZones().getZones_count(); return zonesCount; } /** * Returns all color zones specified between two indexes * * @param start_index the index to start at (inclusive) * @param end_index the index to end at (inclusive) * * @return the response packet object for this request */ @Deprecated public List<Message> getColorZones(int start_index, int end_index) { List<Packet> packets = PacketHandler.sendMessage(new GetColorZones(start_index, end_index), this, true, 0); List<Message> messages = new ArrayList<>(); for (Packet packet : packets) { Message message = packet.getMessage(); if (message instanceof StateZone) { StateZone stateZone = (StateZone) message; messages.add(stateZone); } else if (message instanceof StateMultiZone) { StateMultiZone stateMultiZone = (StateMultiZone) message; messages.add(stateMultiZone); } } return messages; } /** * Gets the current multizone effect * * @return the response packet object for this request */ public StateMultiZoneEffect getMultiZoneEffect() { List<Packet> packets = PacketHandler.sendMessage(new GetMultiZoneEffect(), this); return (StateMultiZoneEffect) packets.get(0).getMessage(); } /** * Gets the current extended color zones for the multizone * * @return the response packet object for this request */ public StateExtendedColorZones getExtendedColorZones() { List<Packet> packets = PacketHandler.sendMessage(new GetExtendedColorZones(), this); return (StateExtendedColorZones) packets.get(0).getMessage(); } /** * Sets zones between two indexes to a particular color * * @param start_index the index to start at (inclusive) * @param end_index the index to end at (inclusive) * @param color the desired color * @param duration the duration (in milliseconds) it takes to make this change * @param awaitReply true to await a reply, false to just send a single packet with no acknowledgement */ public void setColorZones(int start_index, int end_index, Color color, int duration, boolean awaitReply) { PacketHandler.sendMessage(new SetColorZones(start_index, end_index, color.getHue(), color.getSaturation(), color.getBrightness(), color.getKelvin(), duration, MultiZoneApplicationRequest.APPLY), this, awaitReply); } /** * Sets the zones on a multizone to each item in array (one color per zone) * * @param duration the duration (in milliseconds) it takes to make this change * @param zone_index the index to start at (usually 0) * @param awaitReply true to await a reply, false to just send a single packet with no acknowledgement * @param colors the desired colours, in order */ public void setExtendedColorZones(int duration, int zone_index, boolean awaitReply, Color... colors) { PacketHandler.sendMessage(new SetExtendedColorZones(duration, MultiZoneExtendedApplicationRequest.APPLY, zone_index, colors.length, colors), this, awaitReply); } /** * Stops any active multizone effect * * @param awaitReply true to await a reply, false to just send a single packet with no acknowledgement */ public void stopMultiZoneEffect(boolean awaitReply) { PacketHandler.sendMessage(new SetMultiZoneEffect(new Random().nextInt(), MultiZoneEffectType.OFF, 0, 0, new byte[32]), this, awaitReply); } /** * Run the multizone MOVE effect * * @param speed the time it takes for one cycle of the effect in milliseconds * @param duration the time the effect will run for in nanoseconds * @param direction the direction to move the zones in * * @return the response packet object for this request */ public StateMultiZoneEffect runMultiZoneEffectMove(int speed, long duration, Direction direction) { // Build Parameters ByteArrayOutputStream parameters = new ByteArrayOutputStream(64); for (int i = 0; i < 4; i++) { parameters.write(0); } try { parameters.write(TypeUtil.uint32ToBytesLittleEndian(direction.getNumericValue())); } catch (IOException e) { e.printStackTrace(); } for (int i = 0; i < 8; i++) { parameters.write(0); } // Send Packet List<Packet> packets = PacketHandler.sendMessage(new SetMultiZoneEffect(new Random().nextInt(), MultiZoneEffectType.MOVE, speed, duration, parameters.toByteArray()), this); return (StateMultiZoneEffect) packets.get(0).getMessage(); } @Override public void saveState() { this.savedState = getExtendedColorZones(); } @Override public boolean restoreState(int duration) { if (savedState!= null) { // Disable Firmware Effect stopMultiZoneEffect(true); // Restore Lights setExtendedColorZones(duration, savedState.getZone_index(), true, savedState.getColors()); } return false; } } ======================= File: src/main/java/com/stuntguy3000/lifxlansdk/messages/state/device/StateHostFirmware.java ======================= <gh_stars>1-10 /* * Copyright 2021 <NAME> (stuntguy3000) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.stuntguy3000.lifxlansdk.messages.state.device; import com.stuntguy3000.lifxlansdk.object.protocol.abstracts.Message; import com.stuntguy3000.lifxlansdk.util.TypeUtil; import lombok.Getter; import lombok.Setter; import lombok.ToString; /** * This packet will tell you what version of firmware is on the device. * <p> * Typically you would use this information along with {@link StateVersion} (33) to determine the capabilities of your * device as specified in our Product Registry. * <p> * The version_major and version_minor should be thought of as a pair of (major, minor). So say major is 3 and minor is * 60, then the version is (3, 60). This means that (2, 80) is considered less than (3, 60) and (3, 70) is considered * greater. * <p> * LIFX products will specify a different major for each generation of our devices. * <p> * This packet is the reply to the {@link com.stuntguy3000.lifxlansdk.messages.get.device.GetHostFirmware} (14) message */ @Getter @Setter @ToString public class StateHostFirmware extends Message { /** * The timestamp of the firmware that is on the device as an epoch */ private long build; /** * The minor component of the firmware version */ private int version_minor; /** * The major component of the firmware version */ private int version_major; public StateHostFirmware() { super(15); } @Override public void decodeBytes(byte[] data) { build = TypeUtil.littleEndianBytesToUint64(data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7]); version_minor = TypeUtil.littleEndianBytesToUint16(data[16], data[17]); version_major = TypeUtil.littleEndianBytesToUint16(data[18], data[19]); } } ======================= File: src/main/java/com/stuntguy3000/lifxlansdk/messages/state/device/StateWifiFirmware.java ======================= <reponame>stuntguy3000/LIFX-LAN-SDK<gh_stars>1-10 /* * Copyright 2021 <NAME> (stuntguy3000) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.stuntguy3000.lifxlansdk.messages.state.device; import com.stuntguy3000.lifxlansdk.object.protocol.abstracts.Message; import com.stuntguy3000.lifxlansdk.util.TypeUtil; import lombok.Getter; import lombok.Setter; import lombok.ToString; /** * This packet is the reply to the {@link com.stuntguy3000.lifxlansdk.messages.get.device.GetWifiFirmware} (18) message */ @Getter @Setter @ToString public class StateWifiFirmware extends Message { /** * The timestamp when the wifi firmware was created as an epoch, This is only relevant for the first two generations * of our products. */ private long build; /** * The minor component of the version. */ private int version_minor; /** * The major component of the version. */ private int version_major; public StateWifiFirmware() { super(19); } @Override public void decodeBytes(byte[] data) { build = TypeUtil.littleEndianBytesToUint64(data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7]); version_minor = TypeUtil.littleEndianBytesToUint16(data[16], data[17]); version_major = TypeUtil.littleEndianBytesToUint16(data[18], data[19]); } } ======================= File: src/main/java/com/stuntguy3000/lifxlansdk/messages/state/tile/StateTileEffect.java ======================= <gh_stars>1-10 /* * Copyright 2021 <NAME> (stuntguy3000) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.stuntguy3000.lifxlansdk.messages.state.tile; import com.stuntguy3000.lifxlansdk.object.protocol.Color; import com.stuntguy3000.lifxlansdk.object.protocol.abstracts.Message; import com.stuntguy3000.lifxlansdk.object.protocol.enums.TileEffectType; import com.stuntguy3000.lifxlansdk.util.TypeUtil; import lombok.Getter; import lombok.Setter; import lombok.ToString; /** * The current Firmware Effect running on the device * <p> * This packet requires the device has the Matrix Zones capability. You may use {@link * com.stuntguy3000.lifxlansdk.messages.get.device.GetVersion} (32), {@link com.stuntguy3000.lifxlansdk.messages.get.device.GetHostFirmware} * (14) and the Product Registry to determine whether your device has this capability * <p> * This packet is the reply to the {@link com.stuntguy3000.lifxlansdk.messages.get.tile.GetTileEffect} (718) and {@link * StateTileEffect} (719) messages */ @Getter @Setter @ToString public class StateTileEffect extends Message { /** * The unique value identifying the request */ private int instanceid; private TileEffectType effectType; /** * The time it takes for one cycle in milliseconds. */ private int speed; /** * The amount of time left in the current effect in nanoseconds */ private long duration; /** * The parameters as specified in the request. */ private byte[] parameters = new byte[32]; /** * The number of colors in the palette that are relevant */ private int palette_count; /** * The colors specified for the effect. */ private Color[] palette = new Color[16]; public StateTileEffect() { super(720); } @Override public void decodeBytes(byte[] data) { byte[] instanceidBytes = new byte[32]; System.arraycopy(data, 1, instanceidBytes, 0, 32); instanceid = TypeUtil.littleEndianBytesToUint32(instanceidBytes); effectType = TileEffectType.getByValue(TypeUtil.littleEndianBytesToUint8(data[33])); speed = TypeUtil.littleEndianBytesToUint32(data[34], data[35], data[36], data[37]); duration = TypeUtil.littleEndianBytesToUint32(data[38], data[39], data[40], data[41], data[42], data[43], data[44], data[45]); palette_count = TypeUtil.littleEndianBytesToUint8(data[54]); int colorsIndex = 0; for (int dataOffset = 0; dataOffset < 16; dataOffset += 8) { byte[] colorBytes = new byte[8]; System.arraycopy(data, 55 + dataOffset, colorBytes, 0, 8); Color color = new Color(); color.decodeBytes(colorBytes); palette[colorsIndex] = color; colorsIndex++; } } } ======================= File: src/main/java/com/stuntguy3000/lifxlansdk/object/protocol/Packet.java ======================= /* * Copyright 2021 <NAME> (stuntguy3000) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.stuntguy3000.lifxlansdk.object.protocol; import com.stuntguy3000.lifxlansdk.object.protocol.abstracts.ByteData; import com.stuntguy3000.lifxlansdk.object.protocol.abstracts.Message; import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.Setter; import lombok.ToString; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.InetAddress; @Getter @Setter @RequiredArgsConstructor @ToString public class Packet implements ByteData { private final FrameHeader frameHeader; private final FrameAddress frameAddress; private final ProtocolHeader protocolHeader; private final Message message; /** * This is only filled on packets that are received, not constructed pre-sent packets */ private InetAddress ipAddress; @Override public byte[] toBytes() { byte[] frameAddressBytes = frameAddress.toBytes(); byte[] protocolHeaderBytes = protocolHeader.toBytes(); byte[] messageBytes = message.toBytes(); // Manipulate Frame Data if Required // Calculate Message Size // A LIFX packet header is 36 bytes, plus the payload frameHeader.setSize((short) (32 + messageBytes.length)); byte[] frameHeaderBytes = frameHeader.toBytes(); // Bring it all together ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); try { byteArrayOutputStream.write(frameHeaderBytes); byteArrayOutputStream.write(frameAddressBytes); byteArrayOutputStream.write(protocolHeaderBytes); byteArrayOutputStream.write(messageBytes); } catch (IOException e) { e.printStackTrace(); } return byteArrayOutputStream.toByteArray(); } } ======================= File: src/test/java/com/stuntguy3000/lifxlansdk/test/HelperTests.java ======================= <reponame>stuntguy3000/LIFX-LAN-SDK /* * Copyright 2021 <NAME> (stuntguy3000) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.stuntguy3000.lifxlansdk.test; import com.stuntguy3000.lifxlansdk.handler.PacketHandler; import com.stuntguy3000.lifxlansdk.helper.DeviceHelper; import com.stuntguy3000.lifxlansdk.helper.LightHelper; import com.stuntguy3000.lifxlansdk.helper.MultiZoneHelper; import com.stuntguy3000.lifxlansdk.helper.TileHelper; import com.stuntguy3000.lifxlansdk.messages.state.device.EchoResponse; import com.stuntguy3000.lifxlansdk.messages.state.device.StateGroup; import com.stuntguy3000.lifxlansdk.messages.state.device.StateLabel; import com.stuntguy3000.lifxlansdk.messages.state.device.StateLocation; import com.stuntguy3000.lifxlansdk.messages.state.multizone.StateMultiZone; import com.stuntguy3000.lifxlansdk.messages.state.multizone.StateZone; import com.stuntguy3000.lifxlansdk.object.product.Device; import com.stuntguy3000.lifxlansdk.object.product.Light; import com.stuntguy3000.lifxlansdk.object.product.MultiZone; import com.stuntguy3000.lifxlansdk.object.product.Tile; import com.stuntguy3000.lifxlansdk.object.protocol.Color; import com.stuntguy3000.lifxlansdk.object.protocol.abstracts.Message; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.List; import java.util.UUID; import static org.junit.jupiter.api.Assertions.*; public class HelperTests { @BeforeAll public static void setup() { try { PacketHandler.setBroadcastAddress(InetAddress.getByName("192.168.1.255")); } catch (UnknownHostException e) { e.printStackTrace(); } } @Test public void testFindDevices() { List<Device> deviceList = DeviceHelper.findDevices(); for (Device device : deviceList) { System.out.println(device.getStateLabel()); System.out.println(" " + device.getMacAddress()); System.out.println(" " + device.getIpAddress()); System.out.println(" " + device.getStateVersion()); System.out.println(" " + device.isPowered()); System.out.println(" " + device.getHostFirmware()); System.out.println(" " + device.getWifiFirmware()); System.out.println(" " + device.getWifiInfo()); System.out.println(" " + device.getInfo()); System.out.println(" " + device.getStateGroup()); System.out.println(" " + device.getStateLocation()); System.out.println("---"); } assertTrue(deviceList.size() > 0); } //@Test public void testFindLights() { List<Light> lightList = LightHelper.findLights(); for (Light light : lightList) { System.out.println(light.getLabel()); System.out.println(light.getColor()); System.out.println(light.getLightPower()); System.out.println("---"); } assertTrue(lightList.size() > 0); } @Test public void testFindMultizone() { List<MultiZone> multiZoneList = MultiZoneHelper.findMultiZones(); for (MultiZone multiZone : multiZoneList) { System.out.println(multiZone.getLabel()); List<Message> stateZoneList = multiZone.getColorZones(0, 0); List<Message> stateMultiZoneList = multiZone.getColorZones(0, 255); assertTrue(stateZoneList.size() > 0); assertTrue(stateMultiZoneList.size() > 0); for (Message message : stateZoneList) { assertTrue(message instanceof StateZone); StateZone stateZone = (StateZone) message; System.out.println(stateZone); } for (Message message : stateMultiZoneList) { assertTrue(message instanceof StateMultiZone); StateMultiZone stateMultiZone = (StateMultiZone) message; System.out.println(stateMultiZone); } System.out.println(multiZone.getMultiZoneEffect()); System.out.println(multiZone.getExtendedColorZones()); System.out.println("---"); } assertTrue(multiZoneList.size() > 0); } /*@Test public void testFindTile() { List<Tile> tileList = TileHelper.findTiles(); for (Tile tile : tileList) { System.out.println(tile.getLabel()); System.out.println(tile.getDeviceChain()); System.out.println(tile.get64(0, 3, 0, 0, 5)); System.out.println(tile.getTileEffect()); System.out.println("---"); } assertTrue(tileList.size() > 0); }*/ @Test public void testDeviceSet() { Device device = DeviceHelper.getDeviceByLabel("Doors"); // Label StateLabel stateLabel = device.getStateLabel(); StateLabel stateLabelReturn = device.setLabel("SDK Test"); assertEquals("SDK Test", stateLabelReturn.getLabel()); device.setLabel(stateLabel.getLabel()); // Location UUID randomLocationID = UUID.randomUUID(); StateLocation stateLocation = device.getStateLocation(); StateLocation stateLocationReturn = device.setLocation(randomLocationID, "SDK Test Location"); assertEquals(randomLocationID, stateLocationReturn.getLocation()); assertEquals("SDK Test Location", stateLocationReturn.getLabel()); device.setLocation(stateLocation.getLocation(), stateLocation.getLabel()); // Group UUID randomGroupID = UUID.randomUUID(); StateGroup stateGroup = device.getStateGroup(); StateGroup stateGroupReturn = device.setGroup(randomGroupID, "SDK Test Group"); assertEquals(randomGroupID, stateGroupReturn.getGroup()); assertEquals("SDK Test Group", stateGroupReturn.getLabel()); device.setGroup(stateGroup.getGroup(), stateGroup.getLabel()); // Echo Request EchoResponse echoResponse = device.echoRequest("This is an echo test."); assertEquals("This is an echo test.", echoResponse.getEchoing()); // Device Power Level boolean statePower = device.isPowered(); device.setPower(true); // Some Delay is required try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } boolean statePowerReturn = device.isPowered(); assertTrue(statePowerReturn); device.setPower(false); // Some Delay is required try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } statePowerReturn = device.isPowered(); assertFalse(statePowerReturn); // Some Delay is required try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } device.setPower(statePower); } @Test public void testLightSet() { List<Light> lights = LightHelper.findLights(); try { Thread.sleep(2000); for (Light light : lights) { System.out.println(light.getLabel() + " - Light color Test"); light.setLightPower(65535, 1000, true); light.setColor(Color.RED, 0, true); Thread.sleep(1000); light.setColor(Color.CYAN, 0, true); Thread.sleep(1000); light.setColor(Color.BLUE, 0, true); Thread.sleep(1000); light.setColor(Color.PINK, 0, true); Thread.sleep(1000); light.setColor(Color.PURPLE, 0, true); Thread.sleep(1000); light.setColor(Color.GREEN, 0, true); Thread.sleep(1000); light.setColor(Color.YELLOW, 0, true); Thread.sleep(1000); light.setColor(Color.ORANGE, 0, true); Thread.sleep(1000); light.setLightPower(0, 1000, true); Thread.sleep(1000); light.setInfrared(true, true); Thread.sleep(1000); light.setInfrared(false, true); Thread.sleep(1000); } } catch (InterruptedException e) { e.printStackTrace(); } } @Test public void testMultizoneSet() { MultiZone multiZone = MultiZoneHelper.getMultiZoneByLabel("Doors"); try { Thread.sleep(2000); System.out.println("Doors (" + multiZone.getIpAddress().toString() + ") - Light color Test"); multiZone.setLightPower(65535, 1000, true); // Setup Color[] colors = new Color[8]; colors[0] = Color.RED; colors[1] = Color.PURPLE; colors[2] = Color.BLUE; colors[3] = Color.CYAN; colors[4] = Color.GREEN; colors[5] = Color.ORANGE; colors[6] = Color.YELLOW; colors[7] = Color.WHITE; // Basic Full colors for (int loop = 0; loop < 3; loop++) { for (Color color : colors) { multiZone.setColor(color, 0, true); Thread.sleep(1000); } } // Zones Test Color[] zonecolors = new Color[multiZone.getZonesCount()]; int colorIndex = 0; int colorIndexOffset = 0; for (int loop = 0; loop < 3; loop++) { for (int zoneIndex = 0; zoneIndex < multiZone.getZonesCount(); zoneIndex++) { zonecolors[zoneIndex] = colors[(colorIndex + colorIndexOffset) > 7? (colorIndex + colorIndexOffset) - 7 : colorIndex + colorIndexOffset]; // Set Next color colorIndex += 1; if (colorIndex > 4) { colorIndex = 0; } } // Make it rain multiZone.setExtendedColorZones(1000, 0, true, zonecolors); Thread.sleep(1000); colorIndexOffset += 1; if (colorIndexOffset > 4) { colorIndexOffset = 0; } } multiZone.setLightPower(0, 1000, true); Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } @Test public void testTileEffects() { List<Tile> tileList = TileHelper.findTiles(); try { for (Tile tile : tileList) { tile.setPower(true); Thread.sleep(1000); tile.runTileEffectFlame(1000, 10000000000L); Thread.sleep(5000); tile.stopTileEffect(); Thread.sleep(2000); tile.runTileEffectMorph(1000, 10000000000L, Color.RED, Color.BLUE, Color.GREEN); Thread.sleep(5000); tile.stopTileEffect(); Thread.sleep(2000); tile.setPower(false); } } catch (InterruptedException e) { e.printStackTrace(); } } } ======================= File: src/main/java/com/stuntguy3000/lifxlansdk/messages/state/light/StateHevCycle.java ======================= <reponame>stuntguy3000/LIFX-LAN-SDK /* * Copyright 2021 <NAME> (stuntguy3000) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.stuntguy3000.lifxlansdk.messages.state.light; import com.stuntguy3000.lifxlansdk.object.protocol.abstracts.Message; import com.stuntguy3000.lifxlansdk.util.TypeUtil; import lombok.Getter; import lombok.Setter; import lombok.ToString; /** * This says whether a HEV cycle is running on the device. * <p> * This packet requires the device has the hev capability. You may use {@link com.stuntguy3000.lifxlansdk.messages.get.device.GetVersion} * (32), {@link com.stuntguy3000.lifxlansdk.messages.get.device.GetHostFirmware} (14) and the Product Registry to * determine whether your device has this capability * <p> * This packet is the reply to the {@link com.stuntguy3000.lifxlansdk.messages.get.light.GetHevCycle} (142) and {@link * StateHevCycle} (143) messages */ @Getter @Setter @ToString public class StateHevCycle extends Message { /** * The duration, in seconds, this cycle was set to. */ private int duration_s; /** * The duration, in seconds, remaining in this cycle */ private int remaining_s; /** * The power state before the HEV cycle started, which will be the power state once the cycle completes. This is * only relevant if remaining_s is larger than 0. */ private boolean last_power; public StateHevCycle() { super(144); } @Override public void decodeBytes(byte[] data) { duration_s = TypeUtil.littleEndianBytesToUint32(data[0], data[1], data[2], data[3]); remaining_s = TypeUtil.littleEndianBytesToUint32(data[4], data[5], data[6], data[7]); last_power = TypeUtil.bytesToBoolint(data[8], data[9], data[10], data[11]); } } ======================= File: src/main/java/com/stuntguy3000/lifxlansdk/object/protocol/TileData.java ======================= /* * Copyright 2021 <NAME> (stuntguy3000) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.stuntguy3000.lifxlansdk.object.protocol; import com.stuntguy3000.lifxlansdk.object.protocol.abstracts.ByteData; import com.stuntguy3000.lifxlansdk.util.TypeUtil; import lombok.*; /** * Represents a LIFX Tile Structure * <p> * https://lan.developer.lifx.com/docs/field-types#tile */ @Getter @Setter @ToString @AllArgsConstructor @NoArgsConstructor public class TileData implements ByteData { /** * See Tile Orientation (https://lan.developer.lifx.com/docs/tile-control#tile-orientation) */ private int accel_meas_x; /** * See Tile Orientation (https://lan.developer.lifx.com/docs/tile-control#tile-orientation) */ private int accel_meas_y; /** * See Tile Orientation (https://lan.developer.lifx.com/docs/tile-control#tile-orientation) */ private int accel_meas_z; /** * See Tile Positions (https://lan.developer.lifx.com/docs/tile-control#tile-positioning) */ private float user_x; /** * See Tile Positions (https://lan.developer.lifx.com/docs/tile-control#tile-positioning) */ private float user_y; /** * The number of zones that make up each row */ private int width; /** * The number of zones that make up each column */ private int height; /** * The vendor id of the device (See {@link com.stuntguy3000.lifxlansdk.messages.state.device.StateVersion} (33)) */ private int device_version_vendor; /** * The product id of the device (See {@link com.stuntguy3000.lifxlansdk.messages.state.device.StateVersion} (33)) */ private int device_version_product; /** * The epoch of the time the firmware was created (See {@link com.stuntguy3000.lifxlansdk.messages.state.device.StateHostFirmware} * (15)) */ private long firmware_build; /** * The minor component of the firmware version (See {@link com.stuntguy3000.lifxlansdk.messages.state.device.StateHostFirmware} * (15)) */ private int firmware_version_minor; /** * The major component of the firmware version (See {@link com.stuntguy3000.lifxlansdk.messages.state.device.StateHostFirmware} * (15)) */ private int firmware_version_major; @Override public void decodeBytes(byte[] data) { accel_meas_x = TypeUtil.littleEndianBytesToUint16(data[0], data[1]); accel_meas_y = TypeUtil.littleEndianBytesToUint16(data[2], data[3]); accel_meas_z = TypeUtil.littleEndianBytesToUint16(data[4], data[5]); user_x = TypeUtil.littleEndianBytesToFloat(data[8], data[9], data[10], data[11]); user_y = TypeUtil.littleEndianBytesToFloat(data[12], data[13], data[14], data[15]); width = TypeUtil.littleEndianBytesToUint8(data[16]); height = TypeUtil.littleEndianBytesToUint8(data[17]); device_version_vendor = TypeUtil.littleEndianBytesToUint32(data[19], data[20], data[21], data[22]); device_version_product = TypeUtil.littleEndianBytesToUint32(data[23], data[24], data[25], data[26]); firmware_build = TypeUtil.littleEndianBytesToUint64(data[31], data[32], data[33], data[34], data[35], data[36], data[37], data[38]); firmware_version_minor = TypeUtil.littleEndianBytesToUint16(data[47], data[48]); firmware_version_major = TypeUtil.littleEndianBytesToUint16(data[49], data[50]); } } ======================= File: src/main/java/com/stuntguy3000/lifxlansdk/helper/TileHelper.java ======================= <filename>src/main/java/com/stuntguy3000/lifxlansdk/helper/TileHelper.java<gh_stars>1-10 /* * Copyright 2021 <NAME> (stuntguy3000) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.stuntguy3000.lifxlansdk.helper; import com.stuntguy3000.lifxlansdk.object.product.Device; import com.stuntguy3000.lifxlansdk.object.product.Tile; import com.stuntguy3000.lifxlansdk.object.protocol.enums.DeviceType; import java.util.ArrayList; import java.util.List; public class TileHelper { /** * Attempt to find all LIFX Tile lights on a network. * * @return the list of discovered Tile (can be empty) */ public static List<Tile> findTiles() { List<Device> deviceList = DeviceHelper.findDevices(); List<Tile> tileList = new ArrayList<>(); for (Device device : deviceList) { if (device.getType() == DeviceType.MATRIX) { tileList.add(new Tile(device)); } } return tileList; } /** * Attempt to find a LIFX Tile by it's label. * * @param label the label of the Tile * * @return the discovered Tile (or null) */ public static Tile getTileByLabel(String label) { List<Tile> tileList = findTiles(); for (Tile tile : tileList) { if (tile.getLabel().equalsIgnoreCase(label)) { return tile; } } return null; } /** * Attempt to find a LIFX Tile by it's MAC address. * * @param macAddress the MAC address of the Tile * * @return the discovered Tile (or null) */ public static Tile getTileByMacAddress(String macAddress) { List<Tile> tileList = findTiles(); for (Tile tile : tileList) { if (tile.getMacAddress().equalsIgnoreCase(macAddress)) { return tile; } } return null; } } ======================= File: src/main/java/com/stuntguy3000/lifxlansdk/helper/MultiZoneHelper.java ======================= <filename>src/main/java/com/stuntguy3000/lifxlansdk/helper/MultiZoneHelper.java /* * Copyright 2021 <NAME> (stuntguy3000) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.stuntguy3000.lifxlansdk.helper; import com.stuntguy3000.lifxlansdk.object.product.Device; import com.stuntguy3000.lifxlansdk.object.product.MultiZone; import com.stuntguy3000.lifxlansdk.object.protocol.enums.DeviceType; import java.util.ArrayList; import java.util.List; public class MultiZoneHelper { /** * Attempt to find all LIFX MultiZone lights on a network. * * @return the list of discovered MultiZone (can be empty) */ public static List<MultiZone> findMultiZones() { List<Device> deviceList = DeviceHelper.findDevices(); List<MultiZone> multiZoneList = new ArrayList<>(); for (Device device : deviceList) { if (device.getType() == DeviceType.MULTIZONE) { multiZoneList.add(new MultiZone(device)); } } return multiZoneList; } /** * Attempt to find a LIFX MultiZone by it's label. * * @param label the label of the MultiZone * * @return the discovered MultiZone (or null) */ public static MultiZone getMultiZoneByLabel(String label) { List<MultiZone> multiZoneList = findMultiZones(); for (MultiZone multiZone : multiZoneList) { if (multiZone.getLabel().equalsIgnoreCase(label)) { return multiZone; } } return null; } /** * Attempt to find a LIFX MultiZone by it's MAC address. * * @param macAddress the MAC address of the MultiZone * * @return the discovered MultiZone (or null) */ public static MultiZone getMultiZoneByMacAddress(String macAddress) { List<MultiZone> multiZoneList = findMultiZones(); for (MultiZone multiZone : multiZoneList) { if (multiZone.getMacAddress().equalsIgnoreCase(macAddress)) { return multiZone; } } return null; } } ======================= File: src/main/java/com/stuntguy3000/lifxlansdk/messages/set/tile/SetUserPosition.java ======================= /* * Copyright 2021 <NAME> (stuntguy3000) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.stuntguy3000.lifxlansdk.messages.set.tile; import com.stuntguy3000.lifxlansdk.object.protocol.abstracts.Message; import com.stuntguy3000.lifxlansdk.util.TypeUtil; import java.io.ByteArrayOutputStream; import java.io.IOException; /** * Allows you to specify the position of this device in the chain relative to other device in the chain. * <p> * You can find more information about this data by looking at Tile Positions. * <p> * This message has no response packet even if you set res_required=1. * <p> * This packet requires the device has the Matrix Zones capability. You may use {@link * com.stuntguy3000.lifxlansdk.messages.get.device.GetVersion} (32), {@link com.stuntguy3000.lifxlansdk.messages.get.device.GetHostFirmware} * (14) and the Product Registry to determine whether your device has this capability */ public class SetUserPosition extends Message { /** * The device to change. This is 0 indexed and starts from the device closest to the controller. */ private final int tile_index; private final float user_x; private final float user_y; public SetUserPosition(int tile_index, float user_x, float user_y) { super(703); this.tile_index = tile_index; this.user_x = user_x; this.user_y = user_y; } @Override public byte[] toBytes() { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); try { byteArrayOutputStream.write(TypeUtil.uint8ToBytesLittleEndian(tile_index)); byteArrayOutputStream.write(TypeUtil.floatToBytesLittleEndian(user_x)); byteArrayOutputStream.write(TypeUtil.floatToBytesLittleEndian(user_y)); } catch (IOException ioException) { ioException.printStackTrace(); } return byteArrayOutputStream.toByteArray(); } } ======================= File: src/main/java/com/stuntguy3000/lifxlansdk/messages/state/light/StateLastHevCycleResult.java ======================= /* * Copyright 2021 <NAME> (stuntguy3000) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.stuntguy3000.lifxlansdk.messages.state.light; import com.stuntguy3000.lifxlansdk.object.protocol.abstracts.Message; import com.stuntguy3000.lifxlansdk.object.protocol.enums.LightLastHevCycleResult; import com.stuntguy3000.lifxlansdk.util.TypeUtil; import lombok.Getter; import lombok.Setter; import lombok.ToString; /** * This packet tells you the result of the last HEV cycle that was run * <p> * This packet requires the device has the hev capability. You may use {@link com.stuntguy3000.lifxlansdk.messages.get.device.GetVersion} * (32), {@link com.stuntguy3000.lifxlansdk.messages.get.device.GetHostFirmware} (14) and the Product Registry to * determine whether your device has this capability * <p> * This packet is the reply to the {@link com.stuntguy3000.lifxlansdk.messages.get.light.GetLastHevCycleResult} (148) * message */ @Getter @Setter @ToString public class StateLastHevCycleResult extends Message { /** * An enum saying whether the last cycle completed or interrupted. */ private LightLastHevCycleResult result; public StateLastHevCycleResult() { super(144); } @Override public void decodeBytes(byte[] data) { result = LightLastHevCycleResult.getByValue(TypeUtil.littleEndianBytesToUint8(data[0])); } } ======================= File: src/main/java/com/stuntguy3000/lifxlansdk/messages/set/device/SetLocation.java ======================= <reponame>stuntguy3000/LIFX-LAN-SDK /* * Copyright 2021 <NAME> (stuntguy3000) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.stuntguy3000.lifxlansdk.messages.set.device; import com.stuntguy3000.lifxlansdk.object.protocol.abstracts.Message; import com.stuntguy3000.lifxlansdk.util.TypeUtil; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.UUID; /** * This packet lets you set the location information on the device. * <p> * Will return one StateLocation (50) message */ public class SetLocation extends Message { private final UUID location; private final String label; private final long updated_at; public SetLocation(UUID location, String label, long updated_at) { super(49); this.location = location; this.label = label; this.updated_at = updated_at; } @Override public byte[] toBytes() { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); try { byteArrayOutputStream.write(TypeUtil.uuidObjectToUUIDBytes(location)); byteArrayOutputStream.write(TypeUtil.stringToBytesWithPadding(label, 32)); byteArrayOutputStream.write(TypeUtil.uint64ToBytesLittleEndian(updated_at)); } catch (IOException ioException) { ioException.printStackTrace(); } return byteArrayOutputStream.toByteArray(); } } ======================= File: src/main/java/com/stuntguy3000/lifxlansdk/object/protocol/enums/Waveform.java ======================= <filename>src/main/java/com/stuntguy3000/lifxlansdk/object/protocol/enums/Waveform.java /* * Copyright 2021 <NAME> (stuntguy3000) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.stuntguy3000.lifxlansdk.object.protocol.enums; import lombok.Getter; import lombok.RequiredArgsConstructor; /** * @see "https://lan.developer.lifx.com/docs/waveforms" */ @Getter @RequiredArgsConstructor public enum Waveform { SAW(0), SINE(1), HALF_SINE(2), TRIANGLE(3), PULSE(4); private final int numericValue; public static Waveform getByValue(int value) { for (Waveform waveform : Waveform.values()) { if (waveform.numericValue == value) { return waveform; } } return null; } } ======================= File: src/main/java/com/stuntguy3000/lifxlansdk/object/product/Light.java ======================= <filename>src/main/java/com/stuntguy3000/lifxlansdk/object/product/Light.java /* * Copyright 2021 <NAME> (stuntguy3000) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.stuntguy3000.lifxlansdk.object.product; import com.stuntguy3000.lifxlansdk.handler.PacketHandler; import com.stuntguy3000.lifxlansdk.messages.get.light.*; import com.stuntguy3000.lifxlansdk.messages.set.light.SetColor; import com.stuntguy3000.lifxlansdk.messages.set.light.SetInfrared; import com.stuntguy3000.lifxlansdk.messages.set.light.SetLightPower; import com.stuntguy3000.lifxlansdk.messages.state.light.*; import com.stuntguy3000.lifxlansdk.object.protocol.Color; import com.stuntguy3000.lifxlansdk.object.protocol.Packet; import java.net.InetAddress; import java.util.List; /** * Represents a LIFX Light */ public class Light extends Device { /** * Stores any saved state of the light for later restoration */ private LightState savedState; /** * Construct a new light * * @param ipAddress the IP address of the light * @param macAddress the MAC address of the light * @param servicePort the UDP service port to communicate on */ public Light(InetAddress ipAddress, String macAddress, int servicePort) { super(ipAddress, macAddress, servicePort); } /** * Constructs a new Light object * * @param device the generic device representing the light */ public Light(Device device) { super(device.getIpAddress(), device.getMacAddress(), device.getServicePort()); } /** * Gets the current color of the light * * @return the response packet object for this request */ public LightState getColor() { List<Packet> packets = PacketHandler.sendMessage(new GetColor(), this); return (LightState) packets.get(0).getMessage(); } /** * Gets the current HEV cycle of the light * * @return the response packet object for this request */ public StateHevCycle getHevCycle() { List<Packet> packets = PacketHandler.sendMessage(new GetHevCycle(), this); return (StateHevCycle) packets.get(0).getMessage(); } /** * Gets the HEV cycle configuration for the light * * @return the response packet object for this request */ public StateHevCycleConfiguration getHevCycleConfiguration() { List<Packet> packets = PacketHandler.sendMessage(new GetHevCycleConfiguration(), this); return (StateHevCycleConfiguration) packets.get(0).getMessage(); } /** * Gets the infrared status for the light * * @return the response packet object for this request */ public StateInfrared getInfrared() { List<Packet> packets = PacketHandler.sendMessage(new GetInfrared(), this); return (StateInfrared) packets.get(0).getMessage(); } /** * Gets the last HEV cycle's result for the light * * @return the response packet object for this request */ public StateLastHevCycleResult getLastHevCycleResult() { List<Packet> packets = PacketHandler.sendMessage(new GetLastHevCycleResult(), this); return (StateLastHevCycleResult) packets.get(0).getMessage(); } /** * Gets the current power level of the light * * @return the response packet object for this request */ public StateLightPower getLightPower() { List<Packet> packets = PacketHandler.sendMessage(new GetLightPower(), this); return (StateLightPower) packets.get(0).getMessage(); } /** * Set the color of the light * * @param color the desired color * @param duration the duration (in milliseconds) it takes to make this change * @param awaitReply true to await a reply, false to just send a single packet with no acknowledgement */ public void setColor(Color color, int duration, boolean awaitReply) { PacketHandler.sendMessage(new SetColor(color.getHue(), color.getSaturation(), color.getBrightness(), color.getKelvin(), duration), this, awaitReply); } /** * Set the light's power level (on or off) * * @param level the power level between 0 and 65535 * @param duration the duration (in milliseconds) it takes to make this change * @param awaitReply true to await a reply, false to just send a single packet with no acknowledgement */ public void setLightPower(int level, int duration, boolean awaitReply) { PacketHandler.sendMessage(new SetLightPower(level, duration), this, awaitReply); } /** * Set the infrared brightness for the light * * @param powered true for powered, false for off * @param awaitReply true to await a reply, false to just send a single packet with no acknowledgement */ public void setInfrared(boolean powered, boolean awaitReply) { PacketHandler.sendMessage(new SetInfrared(powered? 65535 : 0), this, awaitReply); } @Override public void saveState() { this.savedState = getColor(); } @Override public boolean restoreState(int duration) { if (savedState!= null) { setColor(new Color(savedState.getHue(), savedState.getSaturation(), savedState.getBrightness(), savedState.getKelvin()), duration, true); setLightPower(savedState.getPower(), duration, true); } return false; } } ======================= File: src/main/java/com/stuntguy3000/lifxlansdk/object/protocol/ProtocolHeader.java ======================= <filename>src/main/java/com/stuntguy3000/lifxlansdk/object/protocol/ProtocolHeader.java /* * Copyright 2021 <NAME> (stuntguy3000) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.stuntguy3000.lifxlansdk.object.protocol; import com.stuntguy3000.lifxlansdk.object.protocol.abstracts.ByteData; import com.stuntguy3000.lifxlansdk.util.TypeUtil; import lombok.Getter; import lombok.Setter; import java.io.ByteArrayOutputStream; /** * Represents a LIFX packet Frame Header * <p> * https://lan.developer.lifx.com/docs/packet-contents#protocol-header */ @Getter @Setter public class ProtocolHeader implements ByteData { /** * Message type determines the payload being used */ private int type; @Override public void decodeBytes(byte[] data) { type = TypeUtil.littleEndianBytesToUint16(data[8], data[9]); } @Override public byte[] toBytes() { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); try { // Bytes 0 - 7 (LIFX 0-Indexed Location, Bytes 24 - 31) // Reserved Bytes byteArrayOutputStream.write(0); byteArrayOutputStream.write(0); byteArrayOutputStream.write(0); byteArrayOutputStream.write(0); byteArrayOutputStream.write(0); byteArrayOutputStream.write(0); byteArrayOutputStream.write(0); byteArrayOutputStream.write(0); // Bytes 8 - 9 (LIFX 0-Indexed Location, Bytes 32 - 33) byte[] typeBytes = TypeUtil.uint16ToBytesLittleEndian(type); byteArrayOutputStream.write(typeBytes[0]); byteArrayOutputStream.write(typeBytes[1]); // Bytes 0 - 7 (LIFX 0-Indexed Location, Bytes 34 - 35) // Reserved Bytes byteArrayOutputStream.write(0); byteArrayOutputStream.write(0); } catch (Exception e) { e.printStackTrace(); } return byteArrayOutputStream.toByteArray(); } } ======================= File: src/main/java/com/stuntguy3000/lifxlansdk/messages/state/tile/State64.java ======================= /* * Copyright 2021 <NAME> (stuntguy3000) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.stuntguy3000.lifxlansdk.messages.state.tile; import com.stuntguy3000.lifxlansdk.object.protocol.Color; import com.stuntguy3000.lifxlansdk.object.protocol.abstracts.Message; import com.stuntguy3000.lifxlansdk.util.TypeUtil; import lombok.Getter; import lombok.Setter; import lombok.ToString; /** * The current HSBK values of the zones in a single device. * <p> * This packet requires the device has the Matrix Zones capability. You may use {@link * com.stuntguy3000.lifxlansdk.messages.get.device.GetVersion} (32), {@link com.stuntguy3000.lifxlansdk.messages.get.device.GetHostFirmware} * (14) and the Product Registry to determine whether your device has this capability * <p> * This packet is the reply to the {@link com.stuntguy3000.lifxlansdk.messages.get.tile.Get64} (707) and {@link * com.stuntguy3000.lifxlansdk.messages.set.tile.Set64} (715) messages */ @Getter @Setter @ToString public class State64 extends Message { /** * The index of the device in the chain this packet refers to. This is 0 based starting from the device closest to * the controller. */ private int start_index; /** * The x coordinate the colors start from */ private int x; /** * The y coordinate the colors start from */ private int y; /** * The width of each row */ private int width; private Color[] colors = new Color[64]; public State64() { super(711); } @Override public void decodeBytes(byte[] data) { start_index = TypeUtil.littleEndianBytesToUint8(data[0]); x = TypeUtil.littleEndianBytesToUint8(data[2]); y = TypeUtil.littleEndianBytesToUint8(data[3]); width = TypeUtil.littleEndianBytesToUint8(data[4]); int colorsIndex = 0; for (int dataOffset = 0; dataOffset < 64; dataOffset += 8) { byte[] colorBytes = new byte[8]; System.arraycopy(data, 5 + dataOffset, colorBytes, 0, 8); Color color = new Color(); color.decodeBytes(colorBytes); colors[colorsIndex] = color; colorsIndex++; } } } ======================= File: src/main/java/com/stuntguy3000/lifxlansdk/messages/state/device/StateLabel.java ======================= /* * Copyright 2021 <NAME> (stuntguy3000) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.stuntguy3000.lifxlansdk.messages.state.device; import com.stuntguy3000.lifxlansdk.object.protocol.abstracts.Message; import com.stuntguy3000.lifxlansdk.util.TypeUtil; import lombok.Getter; import lombok.Setter; import lombok.ToString; /** * This packet tells us the label of the device. * <p> * This packet is the reply to the {@link com.stuntguy3000.lifxlansdk.messages.get.device.GetLabel} (23) and {@link * com.stuntguy3000.lifxlansdk.messages.set.device.SetLabel} (24) messages */ @Getter @Setter @ToString public class StateLabel extends Message { private String label; public StateLabel() { super(25); } @Override public void decodeBytes(byte[] data) { // Thanks, https://stackoverflow.com/a/8843313 label = TypeUtil.bytesToString(data); } } ======================= File: src/main/java/com/stuntguy3000/lifxlansdk/messages/set/light/SetInfrared.java ======================= <gh_stars>1-10 /* * Copyright 2021 <NAME> (stuntguy3000) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.stuntguy3000.lifxlansdk.messages.set.light; import com.stuntguy3000.lifxlansdk.object.protocol.abstracts.Message; import com.stuntguy3000.lifxlansdk.util.TypeUtil; /** * This packet lets you change the current infrared value on the device * <p> * Will return one StateInfrared (121) message * <p> * This packet requires the device has the infrared capability. You may use GetVersion (32), GetHostFirmware (14) and * the Product Registry to determine whether your device has this capability */ public class SetInfrared extends Message { private final int brightness; public SetInfrared(int brightness) { super(122); this.brightness = brightness; } @Override public byte[] toBytes() { return TypeUtil.uint16ToBytesLittleEndian(brightness); } } ======================= File: src/main/java/com/stuntguy3000/lifxlansdk/messages/state/tile/StateDeviceChain.java ======================= /* * Copyright 2021 <NAME> (stuntguy3000) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.stuntguy3000.lifxlansdk.messages.state.tile; import com.stuntguy3000.lifxlansdk.object.protocol.TileData; import com.stuntguy3000.lifxlansdk.object.protocol.abstracts.Message; import com.stuntguy3000.lifxlansdk.util.TypeUtil; import lombok.Getter; import lombok.Setter; import lombok.ToString; /** * Information about each device in the chain. * <p> * This packet requires the device has the Matrix Zones capability. You may use {@link * com.stuntguy3000.lifxlansdk.messages.get.device.GetVersion} (32), {@link com.stuntguy3000.lifxlansdk.messages.get.device.GetHostFirmware} * (14) and the Product Registry to determine whether your device has this capability * <p> * This packet is the reply to the {@link com.stuntguy3000.lifxlansdk.messages.get.tile.GetDeviceChain} (701) message */ @Getter @Setter @ToString public class StateDeviceChain extends Message { /** * The index of the first device in the chain this packet refers to */ private int start_index; /** * The information for each device in the chain */ private TileData[] tile_devices = new TileData[16]; /** * The number of device in tile_devices that map to devices in the chain. */ private int tile_devices_count; public StateDeviceChain() { super(702); } @Override public void decodeBytes(byte[] data) { start_index = TypeUtil.littleEndianBytesToUint8(data[0]); tile_devices_count = TypeUtil.littleEndianBytesToUint8(data[881]); int tilesIndex = 0; for (int dataOffset = 0; dataOffset < tile_devices_count * 55; dataOffset += 55) { byte[] tileBytes = new byte[55]; System.arraycopy(data, 1 + dataOffset, tileBytes, 0, 55); TileData tileData = new TileData(); tileData.decodeBytes(tileBytes); tile_devices[tilesIndex] = tileData; tilesIndex++; } } } ======================= File: src/main/java/com/stuntguy3000/lifxlansdk/messages/get/discovery/GetService.java ======================= <gh_stars>1-10 /* * Copyright 2021 <NAME> (stuntguy3000) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.stuntguy3000.lifxlansdk.messages.get.discovery; import com.stuntguy3000.lifxlansdk.object.protocol.abstracts.Message; /** * This packet is used for Discovery of devices. Typically you would broadcast this message to the network (with tagged * field in the header set to 0 and the target field in the header set to all zeros) * <p> * Each device on the network that receives this packet will send back multiple {@link * com.stuntguy3000.lifxlansdk.messages.state.discovery.StateService} (3) messages that say what services are available * and the port those services are on. * <p> * The only {@link com.stuntguy3000.lifxlansdk.messages.state.discovery.StateService} (3) message you care about will * tell you that UDP is available on a port that is usually 56700. You can determine the IP address of the device from * information your UDP socket should receive when it gets those bytes. */ public class GetService extends Message { public GetService() { super(2, true); } } ======================= File: src/main/java/com/stuntguy3000/lifxlansdk/messages/set/light/SetLightPower.java ======================= /* * Copyright 2021 <NAME> (stuntguy3000) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.stuntguy3000.lifxlansdk.messages.set.light; import com.stuntguy3000.lifxlansdk.object.protocol.abstracts.Message; import com.stuntguy3000.lifxlansdk.util.TypeUtil; import java.io.ByteArrayOutputStream; import java.io.IOException; /** * This is the same as {@link com.stuntguy3000.lifxlansdk.messages.set.device.SetPower} (21) but allows you to specify * how long it will take to transition to the new power state. * <p> * Will return one {@link com.stuntguy3000.lifxlansdk.messages.state.light.StateLightPower} (118) message */ public class SetLightPower extends Message { /** * If you specify 0 the light will turn off and if you specify 65535 the device will turn on. */ private final int level; /** * The time it will take to transition to the new state in milliseconds. */ private final int duration; public SetLightPower(int level, int duration) { super(117); this.level = level; this.duration = duration; } @Override public byte[] toBytes() { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(6); try { byteArrayOutputStream.write(TypeUtil.uint16ToBytesLittleEndian(level)); byteArrayOutputStream.write(TypeUtil.uint32ToBytesLittleEndian(duration)); } catch (IOException ioException) { ioException.printStackTrace(); } return byteArrayOutputStream.toByteArray(); } } ======================= File: src/main/java/com/stuntguy3000/lifxlansdk/handler/PacketHandler.java ======================= <reponame>stuntguy3000/LIFX-LAN-SDK /* * Copyright 2021 <NAME> (stuntguy3000) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.stuntguy3000.lifxlansdk.handler; import com.stuntguy3000.lifxlansdk.messages.state.core.Acknowledgement; import com.stuntguy3000.lifxlansdk.messages.state.device.*; import com.stuntguy3000.lifxlansdk.messages.state.discovery.StateService; import com.stuntguy3000.lifxlansdk.messages.state.light.*; import com.stuntguy3000.lifxlansdk.messages.state.multizone.StateExtendedColorZones; import com.stuntguy3000.lifxlansdk.messages.state.multizone.StateMultiZone; import com.stuntguy3000.lifxlansdk.messages.state.multizone.StateMultiZoneEffect; import com.stuntguy3000.lifxlansdk.messages.state.multizone.StateZone; import com.stuntguy3000.lifxlansdk.messages.state.relay.StateRPower; import com.stuntguy3000.lifxlansdk.messages.state.tile.State64; import com.stuntguy3000.lifxlansdk.messages.state.tile.StateDeviceChain; import com.stuntguy3000.lifxlansdk.messages.state.tile.StateTileEffect; import com.stuntguy3000.lifxlansdk.object.product.Device; import com.stuntguy3000.lifxlansdk.object.protocol.FrameAddress; import com.stuntguy3000.lifxlansdk.object.protocol.FrameHeader; import com.stuntguy3000.lifxlansdk.object.protocol.Packet; import com.stuntguy3000.lifxlansdk.object.protocol.ProtocolHeader; import com.stuntguy3000.lifxlansdk.object.protocol.abstracts.Message; import com.stuntguy3000.lifxlansdk.util.TypeUtil; import lombok.Setter; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketTimeoutException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; /** * A handler for all Packet related functions */ public class PacketHandler { /** * A map of packet ID and it's associated Message class for packet object response mapping */ private static final HashMap<Integer, Class<? extends Message>> responseMessagesMap = new HashMap<>(); /** * Packet sequence number * <p> * For usage, see {@link PacketHandler#getNextPacketSequenceNumber()} */ private static short sequence = 0; /** * The broadcast address to send packets on. */ @Setter private static InetAddress broadcastAddress = null; /** * Initializes the responseMessagesMap object */ private static void init() { if (responseMessagesMap.isEmpty()) { // Core responseMessagesMap.put(new Acknowledgement().getType(), Acknowledgement.class); // Device responseMessagesMap.put(new EchoResponse("").getType(), EchoResponse.class); responseMessagesMap.put(new StateGroup().getType(), StateGroup.class); responseMessagesMap.put(new StateHostFirmware().getType(), StateHostFirmware.class); responseMessagesMap.put(new StateInfo().getType(), StateInfo.class); responseMessagesMap.put(new StateLabel().getType(), StateLabel.class); responseMessagesMap.put(new StateLocation().getType(), StateLocation.class); responseMessagesMap.put(new StatePower().getType(), StatePower.class); responseMessagesMap.put(new StateVersion().getType(), StateVersion.class); responseMessagesMap.put(new StateWifiFirmware().getType(), StateWifiFirmware.class); responseMessagesMap.put(new StateWifiInfo().getType(), StateWifiInfo.class); responseMessagesMap.put(new StateUnhandled().getType(), StateUnhandled.class); // Discovery responseMessagesMap.put(new StateService().getType(), StateService.class); // Light responseMessagesMap.put(new LightState().getType(), LightState.class); responseMessagesMap.put(new StateHevCycle().getType(), StateHevCycle.class); responseMessagesMap.put(new StateHevCycleConfiguration().getType(), StateHevCycleConfiguration.class); responseMessagesMap.put(new StateInfrared().getType(), StateInfrared.class); responseMessagesMap.put(new StateLastHevCycleResult().getType(), StateLastHevCycleResult.class); responseMessagesMap.put(new StateLightPower().getType(), StateLightPower.class); // Multizone responseMessagesMap.put(new StateMultiZone().getType(), StateMultiZone.class); responseMessagesMap.put(new StateZone().getType(), StateZone.class); responseMessagesMap.put(new StateMultiZoneEffect().getType(), StateMultiZoneEffect.class); responseMessagesMap.put(new StateExtendedColorZones().getType(), StateExtendedColorZones.class); // Relay responseMessagesMap.put(new StateRPower().getType(), StateRPower.class); // Tile responseMessagesMap.put(new State64().getType(), State64.class); responseMessagesMap.put(new StateDeviceChain().getType(), StateDeviceChain.class); responseMessagesMap.put(new StateTileEffect().getType(), StateTileEffect.class); } } /** * Send a Message to a device * <p> * This function piggybacks off other functions to use default values for: - resultRequired - maxReceiveMessageCount * - timeout - retry * * @param message the message to send * @param device the device to send it to * * @return a list of returned packets (usually 1), can be empty */ public static List<Packet> sendMessage(Message message, Device device) { return sendMessage(message, device, true); } /** * Send a Message to a device * <p> * This function piggybacks off other functions to use default values for: - maxReceiveMessageCount - timeout - * retry * * @param message the message to send * @param device the device to send it to * @param resultRequired true if a result is required (return packet) * * @return a list of returned packets (usually 1), can be empty */ public static List<Packet> sendMessage(Message message, Device device, boolean resultRequired) { return sendMessage(message, device, resultRequired, 1); } /** * Send a Message to a device * <p> * This function piggybacks off other functions to use default values for: - timeout - retry * * @param message the message to send * @param device the device to send it to * @param resultRequired true if a result is required (return packet) * @param maxReceiveMessageCount the amount of messages to receive before returning all packets (used for * optimization) * * @return a list of returned packets (usually 1), can be empty */ public static List<Packet> sendMessage(Message message, Device device, boolean resultRequired, int maxReceiveMessageCount) { return sendMessage(message, device, resultRequired, maxReceiveMessageCount, 150); } /** * Send a Message to a device * <p> * This function piggybacks off other functions to use default values for: - retry * * @param message the message to send * @param device the device to send it to * @param resultRequired true if a result is required (return packet) * @param maxReceiveMessageCount the amount of messages to receive before returning all packets (used for * optimization) * @param timeout the maximum wait time for replies (in ms) * * @return a list of returned packets (usually 1), can be empty */ public static List<Packet> sendMessage(Message message, Device device, boolean resultRequired, int maxReceiveMessageCount, int timeout) { return sendMessage(message, device, resultRequired, maxReceiveMessageCount, timeout, 5); } /** * Send a Message to a device * * @param message the message to send * @param device the device to send it to * @param resultRequired true if a result is required (return packet) * @param maxReceiveMessageCount the amount of messages to receive before returning all packets (used for * optimization) * @param timeout the maximum wait time for replies (in ms) * @param retry the amount of retries if socket the socket timeout is hit * * @return a list of returned packets (usually 1), can be empty */ public static List<Packet> sendMessage(Message message, Device device, boolean resultRequired, int maxReceiveMessageCount, int timeout, int retry) { // Init init(); // Build Packet Packet packet = buildPacket(message, device, resultRequired); List<Packet> returnedPackets = new ArrayList<>(); while (retry > 0) { try { // Send Packet InetAddress targetAddress; int targetPort = 56700; if (device == null) { // Broadcast Packet targetAddress = broadcastAddress; } else { // Targeted Packet targetAddress = device.getIpAddress(); targetPort = device.getServicePort(); } byte[] sendData = packet.toBytes(); DatagramSocket socket = new DatagramSocket(); DatagramPacket datagramPacket = new DatagramPacket(sendData, sendData.length, targetAddress, targetPort); socket.setReuseAddress(true); if (!resultRequired) { socket.send(datagramPacket); return returnedPackets; } socket.setSoTimeout(timeout); socket.send(datagramPacket); // Process Replies // Keep going until we time out while (true) { // Wait to receive byte[] receivedData = new byte[1024]; // LIFX Packets can get big! Biggest seen is stateDeviceChain at 918 bytes. DatagramPacket receivedDatagramPacket = new DatagramPacket(receivedData, receivedData.length); socket.receive(receivedDatagramPacket); // Process Result Packet receivedPacket = buildPacket(receivedData); // Does it have a payload? if (receivedPacket!= null && receivedPacket.getMessage()!= null) { receivedPacket.setIpAddress(receivedDatagramPacket.getAddress()); // Is it unique? // This over-complex function compares a few things to try to figure this out // // Packet delivery assurance techniques can mean duplicates can happen, but some API calls // return multiple packets per request, so, we try to accommodate that whilst comparing payload // information. boolean unique = true; for (Packet returnedPacket : returnedPackets) { if (receivedPacket.getIpAddress().equals(returnedPacket.getIpAddress())) { if (receivedPacket.getProtocolHeader().getType() == returnedPacket.getProtocolHeader().getType()) { if (returnedPacket.getFrameAddress().getSequence() == sequence) { byte[] receivedPacketMessageBytes = receivedPacket.getMessage().toBytes(); byte[] returnedPacketMessageBytes = returnedPacket.getMessage().toBytes(); // Only some packets are cared about, those have defined toBytes, if not, they will be zero and can be ignored if (receivedPacketMessageBytes.length > 0 && returnedPacketMessageBytes.length > 0) { if (Arrays.equals(receivedPacketMessageBytes, returnedPacketMessageBytes)) { unique = false; break; } } } } } } if (unique) { returnedPackets.add(receivedPacket); // Have we received enough packets? --maxReceiveMessageCount; if (maxReceiveMessageCount == 0) { socket.close(); return returnedPackets; } } } } } catch (SocketTimeoutException socketTimeoutException) { --retry; } catch (IOException exception) { exception.printStackTrace(); } } // Return Received Messages return returnedPackets; } /** * Builds a LIFX Packet from received data * * @param receivedData the received data * * @return the constructed packet (or null if invalid) */ private static Packet buildPacket(byte[] receivedData) { int packetSize = TypeUtil.littleEndianBytesToUint16(receivedData[0], receivedData[1]); if (packetSize < 36) { return null; } try { // Setup Packet Headers FrameHeader frameHeader = new FrameHeader(); FrameAddress frameAddress = new FrameAddress(); ProtocolHeader protocolHeader = new ProtocolHeader(); byte[] frameHeaderBytes = new byte[8]; byte[] frameAddressBytes = new byte[16]; byte[] protocolHeaderBytes = new byte[12]; System.arraycopy(receivedData, 0, frameHeaderBytes, 0, 8); System.arraycopy(receivedData, 8, frameAddressBytes, 0, 16); System.arraycopy(receivedData, 24, protocolHeaderBytes, 0, 12); frameHeader.decodeBytes(frameHeaderBytes); frameAddress.decodeBytes(frameAddressBytes); protocolHeader.decodeBytes(protocolHeaderBytes); // Process Message byte[] messageBytes = new byte[packetSize - 36]; System.arraycopy(receivedData, 36, messageBytes, 0, messageBytes.length); Message message = buildMessage(protocolHeader.getType(), messageBytes); // Return Packet return new Packet(frameHeader, frameAddress, protocolHeader, message); } catch (Exception exception) { exception.printStackTrace(); } return null; } /** * Internal packet builder for packets to be sent, not received. For received packet processing, see the other * buildPacket function * * @param message the message * @param device the targeted device, can be null to represent a broadcast * @param resultRequired if a result is required (only useful for controlling Set requests) * * @return the constructed packet (or null) */ private static Packet buildPacket(Message message, Device device, boolean resultRequired) { FrameHeader frameHeader = new FrameHeader(); FrameAddress frameAddress = new FrameAddress(); ProtocolHeader protocolHeader = new ProtocolHeader(); // Set the headers up protocolHeader.setType(message.getType()); frameAddress.setSequence(getNextPacketSequenceNumber()); // Is this a broadcast? if (message.isBroadcast()) { frameHeader.setTagged(true); frameAddress.setTarget("00:00:00:00:00:00"); } else { frameHeader.setTagged(false); frameAddress.setTarget(device.getMacAddress()); } // Set if we need a result returned, usually true frameAddress.setRes_required(resultRequired); return new Packet(frameHeader, frameAddress, protocolHeader, message); } /** * Builds a LIFX Message * * @param messageType the type of message (packet ID) * @param messageBytes the payload data of the message * * @return the constructed message (or null) */ private static Message buildMessage(int messageType, byte[] messageBytes) { Class<? extends Message> messageClazz = responseMessagesMap.get(messageType); // Sanity check if (messageClazz == null) { return null; } // And now, reflection try { Message message = messageClazz.newInstance(); message.decodeBytes(messageBytes); return message; } catch (Exception e) { e.printStackTrace(); } return null; } /** * Increment the packet sequence in a 0-255 loop. * * @return short the next packet sequence number */ private static short getNextPacketSequenceNumber() { ++sequence; if (sequence > 255) { sequence = 0; } return sequence; } } ======================= File: src/main/java/com/stuntguy3000/lifxlansdk/util/TypeUtil.java ======================= /* * Copyright 2021 <NAME> (stuntguy3000) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
1,531
${WARP_IMAGE} -R ${ROT_REF_IMAGE} ${WARP} ) set_property(TEST ${THIS_TEST_NAME}_WARP APPEND PROPERTY DEPENDS ${THIS_TEST_NAME}) # add_test(NAME ${THIS_TEST_NAME}_WARP_METRIC_0 COMMAND MeasureImageSimilarity 3 0 # ${ROT_REF_IMAGE} ${WARP_IMAGE} # ${OUTPUT_PREFIX}log.txt ${OUTPUT_PREFIX}metric.nii.gz # 35.4473 0.5) # set_property(TEST ${THIS_TEST_NAME}_WARP_METRIC_0 APPEND PROPERTY DEPENDS ${THIS_TEST_NAME}_WARP) add_test(NAME ${THIS_TEST_NAME}_INVERSEWARP COMMAND WarpImageMultiTransform 3 ${ROT_REF_IMAGE} ${INVERSEWARP_IMAGE} -R ${ROT_MOV_IMAGE} ${INVERSEWARP}) set_property(TEST ${THIS_TEST_NAME}_INVERSEWARP APPEND PROPERTY DEPENDS ${THIS_TEST_NAME}) # add_test(NAME ${THIS_TEST_NAME}_INVERSEWARP_METRIC_0 COMMAND MeasureImageSimilarity 3 0 # ${ROT_MOV_IMAGE} ${INVERSEWARP_IMAGE} # ${OUTPUT_PREFIX}log.txt ${OUTPUT_PREFIX}metric.nii.gz # 35.5439 0.5) # set_property(TEST ${THIS_TEST_NAME}_INVERSEWARP_METRIC_0 APPEND PROPERTY DEPENDS ${THIS_TEST_NAME}_INVERSEWARP) ======================= File: CTestConfig.cmake ======================= <reponame>KevinScholtes/ANTsX<filename>CTestConfig.cmake ## This file should be placed in the root directory of your project. ## Then modify the CMakeLists.txt file in the root directory of your ## project to incorporate the testing dashboard. ## # The following are required to uses Dart and the Cdash dashboard ## enable_testing() ## include(CTest) set(CTEST_PROJECT_NAME "ANTS") set(CTEST_NIGHTLY_START_TIME "01:00:00 UTC") set(CTEST_DROP_METHOD "http") set(CTEST_DROP_SITE "my.cdash.org") set(CTEST_DROP_LOCATION "/CDash/submit.php?project=ANTS") set(CTEST_DROP_SITE_CDASH TRUE) ======================= File: ANTS.cmake ======================= include(${CMAKE_CURRENT_LIST_DIR}/Common.cmake) configure_file(${CMAKE_CURRENT_LIST_DIR}/CTestCustom.cmake ${CMAKE_CURRENT_BINARY_DIR}/CTestCustom.cmake COPYONLY) set(CMAKE_MODULE_PATH ${${PROJECT_NAME}_SOURCE_DIR}/CMake ${${PROJECT_NAME}_BINARY_DIR}/CMake ${CMAKE_MODULE_PATH} ) set (CMAKE_INCLUDE_DIRECTORIES_BEFORE ON) #----------------------------------------------------------------------------- # Version information include(Version.cmake) set(${PROJECT_NAME}_VERSION "${${PROJECT_NAME}_VERSION_MAJOR}.${${PROJECT_NAME}_VERSION_MINOR}") if(DEFINED ${PROJECT_NAME}_VERSION_PATCH) set(${PROJECT_NAME}_VERSION "${${PROJECT_NAME}_VERSION}.${${PROJECT_NAME}_VERSION_PATCH}") if(DEFINED ${PROJECT_NAME}_VERSION_TWEAK) set(${PROJECT_NAME}_VERSION "${${PROJECT_NAME}_VERSION}.${${PROJECT_NAME}_VERSION_TWEAK}") endif() endif() if(DEFINED ${PROJECT_NAME}_VERSION_RC) set(${PROJECT_NAME}_VERSION "${${PROJECT_NAME}_VERSION}${${PROJECT_NAME}_VERSION_RC}") endif() if(DEFINED ${PROJECT_NAME}_VERSION_POST) set(${PROJECT_NAME}_VERSION "${${PROJECT_NAME}_VERSION}.post${${PROJECT_NAME}_VERSION_POST}") elseif(DEFINED ${PROJECT_NAME}_VERSION_DEV) set(${PROJECT_NAME}_VERSION "${${PROJECT_NAME}_VERSION}.dev${${PROJECT_NAME}_VERSION_DEV}") endif() option( ${PROJECT_NAME}_BUILD_DISTRIBUTE "Remove '-g#####' from version. ( for official distribution only )" OFF ) mark_as_advanced( ${PROJECT_NAME}_BUILD_DISTRIBUTE ) if( NOT ${PROJECT_NAME}_BUILD_DISTRIBUTE AND NOT ${PROJECT_NAME}_VERSION_HASH STREQUAL "GITDIR-NOTFOUND") set(${PROJECT_NAME}_VERSION "${${PROJECT_NAME}_VERSION}-g${${PROJECT_NAME}_VERSION_HASH}") endif() #----------------------------------------------------------------------------- # CPACK Version # set(CPACK_PACKAGE_NAME "ANTs") set(CPACK_PACKAGE_VENDOR "CMake.org") set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "ANTs - Advanced Normalization Tools") set(CPACK_PACKAGE_VERSION_MAJOR ${${PROJECT_NAME}_VERSION_MAJOR}) set(CPACK_PACKAGE_VERSION_MINOR ${${PROJECT_NAME}_VERSION_MINOR}) set(CPACK_PACKAGE_VERSION_PATCH ${${PROJECT_NAME}_VERSION_PATCH}) set(CPACK_PACKAGE_VERSION ${${PROJECT_NAME}_VERSION}) set(CPACK_PACKAGE_INSTALL_DIRECTORY "ANTS_Install") set(CPACK_BINARY_GENERATORS "DragNDrop TGZ TZ") set(CPACK_PACKAGE_DESCRIPTION_FILE "${CMAKE_CURRENT_SOURCE_DIR}/README.txt") set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "ANTs - robust image registration, segmentation and more") set(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_CURRENT_SOURCE_DIR}/ANTSCopyright.txt") set(CPACK_RESOURCE_FILE_README "${CMAKE_CURRENT_SOURCE_DIR}/README.txt") message(STATUS "Building ${PROJECT_NAME} version \"${${PROJECT_NAME}_VERSION}\"") # Set up ITK find_package(ITK 5.0 REQUIRED) include(${ITK_USE_FILE}) # Set up which ANTs apps to build option(BUILD_ALL_ANTS_APPS "Use All ANTs Apps" ON) # Set up VTK option(USE_VTK "Use VTK Libraries" OFF) if(USE_VTK) find_package(VTK) if(VTK_VERSION_MAJOR GREATER 6) find_package(VTK 8.1.1 COMPONENTS vtkRenderingVolumeOpenGL2 vtkCommonCore vtkCommonDataModel vtkIOGeometry vtkIOXML vtkIOLegacy vtkIOPLY vtkFiltersModeling vtkImagingStencil vtkImagingGeneral vtkRenderingAnnotation ) endif() if(VTK_FOUND) include(${VTK_USE_FILE}) include_directories(${VTK_INCLUDE_DIRS}) set(INIT_VTK_LIBRARIES ${VTK_LIBRARIES}) else() message("Cannot build some programs without VTK. Please set VTK_DIR if you need these programs.") endif() endif() # With MS compilers on Win64, we need the /bigobj switch, else generated # code results in objects with number of sections exceeding object file # format. # see http://msdn.microsoft.com/en-us/library/ms173499.aspx if(CMAKE_CL_64 OR MSVC) add_definitions(/bigobj) endif() option(ITK_USE_FFTWD "Use double precision fftw if found" OFF) option(ITK_USE_FFTWF "Use single precision fftw if found" OFF) option(ITK_USE_SYSTEM_FFTW "Use an installed version of fftw" OFF) if (ITK_USE_FFTWD OR ITK_USE_FFTWF) if(ITK_USE_SYSTEM_FFTW) find_package( FFTW ) link_directories(${FFTW_LIBDIR}) else() link_directories(${ITK_DIR}/fftw/lib) include_directories(${ITK_DIR}/fftw/include) endif() endif() # These are configure time options that specify which # subset of tests should be run option(RUN_SHORT_TESTS "Run the quick unit tests." ON ) option(RUN_LONG_TESTS "Run the time consuming tests. i.e. real world registrations" OFF ) option(OLD_BASELINE_TESTS "Use reported metrics from old tests" OFF ) #----------------------------------------------------------------------------- include(CTest) enable_testing() #Set the global max TIMEOUT for CTest jobs. This is very large for the moment #and should be revisted to reduce based on "LONG/SHORT" test times, set to 1 hr for now set(CTEST_TEST_TIMEOUT 1800 CACHE STRING "Maximum seconds allowed before CTest will kill the test." FORCE) set(DART_TESTING_TIMEOUT ${CTEST_TEST_TIMEOUT} CACHE STRING "Maximum seconds allowed before CTest will kill the test." FORCE) configure_file(${CMAKE_CURRENT_LIST_DIR}/CTestCustom.cmake ${CMAKE_CURRENT_BINARY_DIR}/CTestCustom.cmake COPYONLY) include_directories( ${BOOST_INCLUDE_DIR} ) #Define where to find Boost includes link_directories( ${ITK_LIBRARY_PATH} ) # message("${ITK_LIBRARIES}") #---------------------------------------------------------------------------- # Setup ants build environment set(PICSL_INCLUDE_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/Utilities ${CMAKE_CURRENT_SOURCE_DIR}/ImageRegistration ${CMAKE_CURRENT_SOURCE_DIR}/ImageSegmentation # ${CMAKE_CURRENT_SOURCE_DIR}/GraphTheory ${CMAKE_CURRENT_SOURCE_DIR}/Tensor ${CMAKE_CURRENT_SOURCE_DIR}/Temporary ${CMAKE_CURRENT_SOURCE_DIR}/Examples ${CMAKE_CURRENT_BINARY_DIR} ) include_directories(${PICSL_INCLUDE_DIRS}) configure_file("${CMAKE_CURRENT_SOURCE_DIR}/ANTsVersionConfig.h.in" "${CMAKE_CURRENT_BINARY_DIR}/ANTsVersionConfig.h" @ONLY IMMEDIATE) add_subdirectory(Examples) ======================= File: SuperBuild/External_VTK_patch.cmake ======================= <reponame>KevinScholtes/ANTsX set(vtkDetCFLAGS ${VTKSource}/CMake/vtkDetermineCompilerFlags.cmake) file(READ ${vtkDetCFLAGS} code) string(REPLACE "set(VTK_REQUIRED_C_FLAGS \"\${VTK_REQUIRED_C_FLAGS} -mlong-branch\")" "" code "${code}") string(REPLACE "set(VTK_REQUIRED_CXX_FLAGS \"\${VTK_REQUIRED_CXX_FLAGS} -mlong-branch\")" "" code "${code}") file(WRITE ${vtkDetCFLAGS} "${code}" ) set(ftglCMakeLists_txt ${VTKSource}/Utilities/ftgl/CMakeLists.txt) file(READ ${ftglCMakeLists_txt} code) string(REPLACE " -fpascal-strings" "" code "${code}") file(WRITE ${ftglCMakeLists_txt} "${code}") find_file(vtkVRMLImporter vtkVRMLImporter.cxx HINTS ${VTKSource}/Hybrid ${VTKSource}/IO/IMPORT ) file(READ ${vtkVRMLImporter} code) string(REPLACE "#ifdef __GNUC__ #undef alloca #define alloca __builtin_alloca " "#ifdef __GNUC__ #ifndef __clang__ #undef alloca #define alloca __builtin_alloca #endif " code "${code}") file(WRITE ${vtkVRMLImporter} "${code}" ) ======================= File: Examples/TestSuite/ANTS_ROT_EXP_test.cmake ======================= <reponame>KevinScholtes/ANTsX ##################################################################################### ##################################################################################### set(THIS_TEST_NAME ANTS_ROT_EXP) set(OUTPUT_PREFIX ${CMAKE_BINARY_DIR}/TEST_${THIS_TEST_NAME} ) set(WARP ${OUTPUT_PREFIX}Warp.nii.gz ${OUTPUT_PREFIX}Affine.txt ) set(INVERSEWARP -i ${OUTPUT_PREFIX}Affine.txt ${OUTPUT_PREFIX}InverseWarp.nii.gz ) set(WARP_IMAGE ${CMAKE_BINARY_DIR}/${THIS_TEST_NAME}_warped.nii.gz) set(INVERSEWARP_IMAGE ${CMAKE_BINARY_DIR}/${THIS_TEST_NAME}_inversewarped.nii.gz) add_test(NAME ${THIS_TEST_NAME} COMMAND ANTS 3 -m MSQ[${ROT_REF_IMAGE},${ROT_MOV_IMAGE},1,0] -t Exp[3,2] -i 50x5x1 -r Gauss[3,0.0,32] -o ${OUTPUT_PREFIX}.nii.gz) add_test(NAME ${THIS_TEST_NAME}_WARP COMMAND WarpImageMultiTransform 3 ${ROT_MOV_IMAGE} ${WARP_IMAGE} -R ${ROT_REF_IMAGE} ${WARP} ) set_property(TEST ${THIS_TEST_NAME}_WARP APPEND PROPERTY DEPENDS ${THIS_TEST_NAME}) # add_test(NAME ${THIS_TEST_NAME}_WARP_METRIC_0 COMMAND MeasureImageSimilarity 3 0 # ${ROT_REF_IMAGE} ${WARP_IMAGE} # ${OUTPUT_PREFIX}log.txt ${OUTPUT_PREFIX}metric.nii.gz # 36.3928 0.5) # set_property(TEST ${THIS_TEST_NAME}_WARP_METRIC_0 APPEND PROPERTY DEPENDS ${THIS_TEST_NAME}_WARP) add_test(NAME ${THIS_TEST_NAME}_WARP2 COMMAND WarpImageMultiTransform 3 ${ROT_MOV_IMAGE} ${WARP_IMAGE} -R ${ROT_REF_IMAGE} --ANTS-prefix ${OUTPUT_PREFIX} ) set_property(TEST ${THIS_TEST_NAME}_WARP2 APPEND PROPERTY DEPENDS ${THIS_TEST_NAME}) # add_test(NAME ${THIS_TEST_NAME}_WARP2_METRIC_0_2 COMMAND MeasureImageSimilarity 3 0 ${ROT_REF_IMAGE} # ${WARP_IMAGE} ${OUTPUT_PREFIX}log.txt # ${OUTPUT_PREFIX}metric.nii.gz 36.3928 0.5) # set_property(TEST ${THIS_TEST_NAME}_WARP2_METRIC_0_2 APPEND PROPERTY DEPENDS ${THIS_TEST_NAME}_WARP2) add_test(NAME ${THIS_TEST_NAME}_INVERSEWARP COMMAND WarpImageMultiTransform 3 ${ROT_REF_IMAGE} ${INVERSEWARP_IMAGE} -R ${ROT_MOV_IMAGE} ${INVERSEWARP} ) set_property(TEST ${THIS_TEST_NAME}_INVERSEWARP APPEND PROPERTY DEPENDS ${THIS_TEST_NAME}) # add_test(NAME ${THIS_TEST_NAME}_INVERSEWARP_METRIC_0 COMMAND MeasureImageSimilarity 3 0 ${ROT_MOV_IMAGE} # ${INVERSEWARP_IMAGE} ${OUTPUT_PREFIX}log.txt ${OUTPUT_PREFIX}metric.nii.gz # 34.8184 0.5) # set_property(TEST ${THIS_TEST_NAME}_INVERSEWARP_METRIC_0 APPEND PROPERTY DEPENDS ${THIS_TEST_NAME}_INVERSEWARP) add_test(NAME ${THIS_TEST_NAME}_INVERSEWARP2 COMMAND WarpImageMultiTransform 3 ${ROT_REF_IMAGE} ${INVERSEWARP_IMAGE} -R ${ROT_MOV_IMAGE} --ANTS-prefix-invert ${OUTPUT_PREFIX}) set_property(TEST ${THIS_TEST_NAME}_INVERSEWARP2 APPEND PROPERTY DEPENDS ${THIS_TEST_NAME}_INVERSEWARP) # add_test(NAME ${THIS_TEST_NAME}_INVERSEWARP2_METRIC_0_2 COMMAND MeasureImageSimilarity 3 0 ${ROT_MOV_IMAGE} # ${INVERSEWARP_IMAGE} ${OUTPUT_PREFIX}log.txt # ${OUTPUT_PREFIX}metric.nii.gz # 34.8184 0.5) # set_property(TEST ${THIS_TEST_NAME}_INVERSEWARP2_METRIC_0_2 APPEND PROPERTY DEPENDS ${THIS_TEST_NAME}_INVERSEWARP) ======================= File: Examples/TestSuite/ANTS_CC_3_test.cmake ======================= ##################################################################################### ##################################################################################### set(THIS_TEST_NAME ANTS_CC_3) set(OUTPUT_PREFIX ${CMAKE_BINARY_DIR}/TEST_${THIS_TEST_NAME} ) set(WARP ${OUTPUT_PREFIX}Warp.nii.gz ${OUTPUT_PREFIX}Affine.txt ) set(INVERSEWARP -i ${OUTPUT_PREFIX}Affine.txt ${OUTPUT_PREFIX}InverseWarp.nii.gz ) set(WARP_IMAGE ${CMAKE_BINARY_DIR}/${THIS_TEST_NAME}_warped.nii.gz) set(INVERSEWARP_IMAGE ${CMAKE_BINARY_DIR}/${THIS_TEST_NAME}_inversewarped.nii.gz) add_test(NAME ${THIS_TEST_NAME} COMMAND ANTS 2 -m CC[ ${R16_IMAGE}, ${R64_IMAGE}, 1, 4] -r Gauss[ 3, 0 ] -t SyN[ 0.5 ] -i 50x50x30 -o ${OUTPUT_PREFIX}.nii.gz --go-faster true ) add_test(NAME ${THIS_TEST_NAME}_WARP COMMAND WarpImageMultiTransform 2 ${R64_IMAGE} ${WARP_IMAGE} ${WARP} -R ${R16_IMAGE} ) set_property(TEST ${THIS_TEST_NAME}_WARP APPEND PROPERTY DEPENDS ${THIS_TEST_NAME}) add_test(NAME ${THIS_TEST_NAME}_JPG COMMAND ConvertToJpg ${WARP_IMAGE} ${THIS_TEST_NAME}.jpg) set_property(TEST ${THIS_TEST_NAME}_JPG APPEND PROPERTY DEPENDS ${THIS_TEST_NAME}_WARP) # add_test(NAME ${THIS_TEST_NAME}_WARP_METRIC_0 COMMAND MeasureImageSimilarity 2 0 # ${R16_IMAGE} ${WARP_IMAGE} # ${OUTPUT_PREFIX}log.txt ${OUTPUT_PREFIX}metric.nii.gz # 14.3283 0.05) # set_property(TEST ${THIS_TEST_NAME}_WARP_METRIC_0 APPEND PROPERTY DEPENDS ${THIS_TEST_NAME}_WARP) # # add_test(NAME ${THIS_TEST_NAME}_WARP_METRIC_1 COMMAND MeasureImageSimilarity 2 1 # ${R16_IMAGE} ${WARP_IMAGE} ${OUTPUT_PREFIX}log.txt # ${OUTPUT_PREFIX}metric.nii.gz # 0.996796 0.05) # set_property(TEST ${THIS_TEST_NAME}_WARP_METRIC_1 APPEND PROPERTY DEPENDS ${THIS_TEST_NAME}_WARP) # # add_test(NAME ${THIS_TEST_NAME}_WARP_METRIC_2 COMMAND MeasureImageSimilarity 2 2 # ${R16_IMAGE} ${WARP_IMAGE} ${OUTPUT_PREFIX}log.txt # ${OUTPUT_PREFIX}metric.nii.gz # -1.2204 0.05) # set_property(TEST ${THIS_TEST_NAME}_WARP_METRIC_2 APPEND PROPERTY DEPENDS ${THIS_TEST_NAME}_WARP) add_test(NAME ${THIS_TEST_NAME}_INVERSEWARP COMMAND WarpImageMultiTransform 2 ${R16_IMAGE} ${INVERSEWARP_IMAGE} ${INVERSEWARP} -R ${R16_IMAGE} ) set_property(TEST ${THIS_TEST_NAME}_INVERSEWARP APPEND PROPERTY DEPENDS ${THIS_TEST_NAME}) # add_test(NAME ${THIS_TEST_NAME}_INVERSEWARP_METRIC_0 COMMAND MeasureImageSimilarity 2 0 ${R64_IMAGE} # ${INVERSEWARP_IMAGE} ${OUTPUT_PREFIX}log.txt ${OUTPUT_PREFIX}metric.nii.gz # 50.4483 0.05) # set_property(TEST ${THIS_TEST_NAME}_INVERSEWARP_METRIC_0 APPEND PROPERTY DEPENDS ${THIS_TEST_NAME}_INVERSEWARP) # # add_test(NAME ${THIS_TEST_NAME}_INVERSEWARP_METRIC_1 COMMAND MeasureImageSimilarity 2 1 ${R64_IMAGE} # ${INVERSEWARP_IMAGE} ${OUTPUT_PREFIX}log.txt ${OUTPUT_PREFIX}metric.nii.gz # 1.0 0.05) # set_property(TEST ${THIS_TEST_NAME}_INVERSEWARP_METRIC_1 APPEND PROPERTY DEPENDS ${THIS_TEST_NAME}_INVERSEWARP) # # add_test(NAME ${THIS_TEST_NAME}_INVERSEWARP_METRIC_2 COMMAND MeasureImageSimilarity 2 2 ${R64_IMAGE} # ${INVERSEWARP_IMAGE} ${OUTPUT_PREFIX}log.txt ${OUTPUT_PREFIX}metric.nii.gz # 0.379897 0.05) # set_property(TEST ${THIS_TEST_NAME}_INVERSEWARP_METRIC_2 APPEND PROPERTY DEPENDS ${THIS_TEST_NAME}_INVERSEWARP) ======================= File: Examples/TestSuite/ANTS_SYN_WITH_TIME_test.cmake ======================= <gh_stars>0 ##################################################################################### ##################################################################################### set(THIS_TEST_NAME ANTS_SYN_WITH_TIME) set(OUTPUT_PREFIX ${CMAKE_BINARY_DIR}/TEST_${THIS_TEST_NAME} ) set(WARP ${OUTPUT_PREFIX}Warp.nii.gz ${OUTPUT_PREFIX}Affine.txt ) set(INVERSEWARP -i ${OUTPUT_PREFIX}Affine.txt ${OUTPUT_PREFIX}InverseWarp.nii.gz ) set(WARP_IMAGE ${CMAKE_BINARY_DIR}/${THIS_TEST_NAME}_warped.nii.gz) set(INVERSEWARP_IMAGE ${CMAKE_BINARY_DIR}/${THIS_TEST_NAME}_inversewarped.nii.gz) add_test(NAME ${THIS_TEST_NAME} COMMAND ANTS 2 -m MSQ[${CHALF_IMAGE},${C_IMAGE},1,0] -r Gauss[0.5,0.1] -t SyN[1,10,0.05] -i 150x100x2x2 -o ${OUTPUT_PREFIX} --geodesic 1 --number-of-affine-iterations 0) add_test(NAME ${THIS_TEST_NAME}_WARP COMMAND WarpImageMultiTransform 2 ${C_IMAGE} ${OUTPUT_PREFIX}.nii.gz ${OUTPUT_PREFIX}Warp.nii.gz -R ${CHALF_IMAGE} ) set_property(TEST ${THIS_TEST_NAME}_WARP APPEND PROPERTY DEPENDS ${THIS_TEST_NAME}) # add_test(NAME ${THIS_TEST_NAME}_WARP_METRIC_0 COMMAND MeasureImageSimilarity 2 0 # ${CHALF_IMAGE} ${OUTPUT_PREFIX}.nii.gz # ${OUTPUT_PREFIX}log.txt ${OUTPUT_PREFIX}metric.nii.gz # 0.0943736 0.1) # set_property(TEST ${THIS_TEST_NAME}_WARP_METRIC_0 APPEND PROPERTY DEPENDS ${THIS_TEST_NAME}_WARP) ======================= File: Examples/TestSuite/APOC_OTSU_INIT_test.cmake ======================= <filename>Examples/TestSuite/APOC_OTSU_INIT_test.cmake ## # Apocrita tests ## ExternalData_expand_arguments(${PROJECT_NAME}FetchData R16_MASK DATA{${SMALL_DATA_DIR}/r16mask.nii.gz) ExternalData_expand_arguments(${PROJECT_NAME}FetchData R16_PRIORS DATA{${SMALL_DATA_DIR}/r16priors.nii.gz) #add_test(NAME APOC_OTSU_INIT COMMAND Apocrita 2 -i otsu[${R16_IMAGE},3] -x ${R16_MASK} -n 10 -m [0.3,1x1,0.2,0.1] -o ${OUTPUT_PREFIX}.nii.gz ) #add_test(NAME APOC_OTSU_INIT_RADIUS_2x2 COMMAND Apocrita 2 -i otsu[${R16_IMAGE},3] -x ${R16_MASK} -n 10 -m [0.3,2,0.2,0.1] -o ${OUTPUT_PREFIX}.nii.gz ) #add_test(NAME APOC_KMEANS_INIT COMMAND Apocrita 2 -i kmeans[${R16_IMAGE},3] -x ${R16_MASK} -n 10 -m [0.3,1x1,0.2,0.1] -o [${OUTPUT_PREFIX}.nii.gz,${OUTPUT_PREFIX}_posteriors%d.nii.gz]) #add_test(NAME APOC_PRIORLABELIMAGE_INIT COMMAND Apocrita 2 -i priorlabelimage[${R16_IMAGE},5,${R16_PRIORS},0.5] -x ${R16_MASK} -n 10 -m [0.3,1x1,0.2,0.1] -o [${OUTPUT_PREFIX}.nii.gz,${OUTPUT_PREFIX}_posteriors%d.nii.gz] -l 1[1,0.75] -l 2[1,1.0] -l 3[0.5,0.5] -l 4[1,1]) ======================= File: CMake/ProjectSourceVersion.cmake ======================= # # This CMake code extracts the information from the git repository, # and automatically causes a reconfigure if the git HEAD changes. The # following variable may be defined after execution: # # _GIT_VERSION_HASH - the SHA1 hash of the current HEAD # # Based on the most recent tag starting with the letter "v" for # version, which is expected to be of the form # vN.N[.N[.N][(a|b|c|rc[N])] the following is extracted or undefined: # # _GIT_VERSION_MAJOR # _GIT_VERSION_MINOR # _GIT_VERSION_PATCH # _GIT_VERSION_TWEAK # _GIT_VERSION_RC # # If the current project's version ( defiend by # ${CMAKE_PROJECT_NAME}_VERSION_MAJOR and MINOR and PATCH and TWEAK # match that of the tag, then it'll be considered that the project is # in post release mode otherwise it's considered underdevelopment. # # Only one of the following variables will be defined. # _GIT_VERSION_DEV is defined as number of commits # since the projects Version.cmake file has been modified. While # _GIT_VERSION_POST is defined as the number of commits since the tag. # include(GetGitRevisionDescription) get_git_head_revision(GIT_REFVAR _GIT_VERSION_HASH) # if there is not git directory we should be in a distributed package # we will use version provided in Version.cmake if(_GIT_VERSION_HASH STREQUAL "GITDIR-NOTFOUND") return() endif() if(_GIT_VERSION_HASH MATCHES "[a-fA-F0-9]+") string(SUBSTRING "${_GIT_VERSION_HASH}" 0 5 _GIT_VERSION_HASH) endif() # find the closest anotated tag with the v prefix for version git_describe(_GIT_TAG "--match=v*") git_commits_since("${PROJECT_SOURCE_DIR}/Version.cmake" _GIT_VERSION_COUNT) set(VERSION_REGEX "^v([0-9]+)\\.([0-9]+)+(\\.([0-9]+))?(\\.([0-9]+))?((a|b|c|rc)[0-9]*)?(-[0-9]+)?") string(REGEX MATCH "${VERSION_REGEX}" _out "${_GIT_TAG}") if("${_out}" STREQUAL "") message(WARNING "git tag: \"${_GIT_TAG}\" does not match expected version format!") return() endif() set(_GIT_VERSION_MAJOR "${CMAKE_MATCH_1}") set(_GIT_VERSION_MINOR "${CMAKE_MATCH_2}") if(NOT "${CMAKE_MATCH_4}" STREQUAL "") set(_GIT_VERSION_PATCH "${CMAKE_MATCH_4}") endif() if(NOT "${CMAKE_MATCH_6}" STREQUAL "") set(_GIT_VERSION_TWEAK "${CMAKE_MATCH_6}") endif() if(NOT "${CMAKE_MATCH_7}" STREQUAL "") set(_GIT_VERSION_RC "${CMAKE_MATCH_7}" ) # a,b,rc01 etc endif() if(NOT "${CMAKE_MATCH_9}" STREQUAL "") #trim leading '-' string(SUBSTRING "${CMAKE_MATCH_9}" 1 -1 CMAKE_MATCH_9) set(_GIT_TAG_COUNT "${CMAKE_MATCH_9}") endif() set(_GIT_VERSION "${_GIT_VERSION_MAJOR}.${_GIT_VERSION_MINOR}") if(DEFINED _GIT_VERSION_PATCH) set(_GIT_VERSION "${_GIT_VERSION}.${_GIT_VERSION_PATCH}") if(DEFINED _GIT_VERSION_TWEAK) set(_GIT_VERSION "${_GIT_VERSION}.${_GIT_VERSION_TWEAK}") elseif(DEFINED ${CMAKE_PROJECT_NAME}_VERSION_TWEAK) set(_GIT_VERSION "${_GIT_VERSION}.0") endif() elseif(DEFINED ${CMAKE_PROJECT_NAME}_VERSION_PATCH) set(_GIT_VERSION "${_GIT_VERSION}.0") if(DEFINED ${CMAKE_PROJECT_NAME}_VERSION_TWEAK) set(_GIT_VERSION "${_GIT_VERSION}.0") endif() endif() set(_${CMAKE_PROJECT_NAME}_VERSION "${${CMAKE_PROJECT_NAME}_VERSION_MAJOR}.${${CMAKE_PROJECT_NAME}_VERSION_MINOR}") if(DEFINED ${CMAKE_PROJECT_NAME}_VERSION_PATCH) set(_${CMAKE_PROJECT_NAME}_VERSION "${_${CMAKE_PROJECT_NAME}_VERSION}.${${CMAKE_PROJECT_NAME}_VERSION_PATCH}") if(DEFINED ${CMAKE_PROJECT_NAME}_VERSION_TWEAK) set(_${CMAKE_PROJECT_NAME}_VERSION "${_${CMAKE_PROJECT_NAME}_VERSION}.${${CMAKE_PROJECT_NAME}_VERSION_TWEAK}") endif() endif() if(_GIT_VERSION VERSION_EQUAL _${CMAKE_PROJECT_NAME}_VERSION) if(_GIT_TAG_COUNT) #ignore if 0 set(_GIT_VERSION_POST "${_GIT_TAG_COUNT}") endif() else() # The first commit after a tag should increase the project version # number in Version.cmake and be "dev1" math(EXPR _GIT_VERSION_COUNT "${_GIT_VERSION_COUNT}+1") set(_GIT_VERSION_DEV "${_GIT_VERSION_COUNT}") endif() # save variable in a configuration file in case we have no git directory configure_file("${CMAKE_CURRENT_SOURCE_DIR}/CMake/ProjectSourceVersionVars.cmake.in" "${CMAKE_CURRENT_BINARY_DIR}/ProjectSourceVersionVars.cmake" @ONLY) ======================= File: Examples/TestSuite/ANTS_PSE_MSQ_VTK_test.cmake ======================= <gh_stars>0 ##################################################################################### ##################################################################################### set(THIS_TEST_NAME ANTSPSE_MSQ_VTK) set(OUTPUT_PREFIX ${CMAKE_BINARY_DIR}/TEST_${THIS_TEST_NAME} ) set(WARP ${OUTPUT_PREFIX}Warp.nii.gz ${OUTPUT_PREFIX}Affine.txt ) set(INVERSEWARP -i ${OUTPUT_PREFIX}Affine.txt ${OUTPUT_PREFIX}InverseWarp.nii.gz ) set(WARP_IMAGE ${CMAKE_BINARY_DIR}/${THIS_TEST_NAME}_warped.nii.gz) set(INVERSEWARP_IMAGE ${CMAKE_BINARY_DIR}/${THIS_TEST_NAME}_inversewarped.nii.gz) add_test(NAME ${THIS_TEST_NAME} COMMAND ANTS 2 -i 91x70x55x40x30 -r Gauss[3,0.,32] -t SyN[0.25] -m MSQ[${DEVIL_IMAGE},${ANGEL_IMAGE},1,0] -m PSE[${DEVIL_IMAGE},${ANGEL_IMAGE},${DEVIL_IMAGE_VTK},${ANGEL_IMAGE_VTK},1,0.33,11,1,25] --continue-affine 0 --number-of-affine-iterations 0 -o ${OUTPUT_PREFIX}.nii.gz) ======================= File: Examples/TestSuite/ANTS_PSE_MSQ_TXT_test.cmake ======================= <filename>Examples/TestSuite/ANTS_PSE_MSQ_TXT_test.cmake ##################################################################################### ##################################################################################### set(THIS_TEST_NAME ANTS_PSE_MSQ_TXT) set(OUTPUT_PREFIX ${CMAKE_BINARY_DIR}/TEST_${THIS_TEST_NAME} ) set(WARP ${OUTPUT_PREFIX}Warp.nii.gz ${OUTPUT_PREFIX}Affine.txt ) set(INVERSEWARP -i ${OUTPUT_PREFIX}Affine.txt ${OUTPUT_PREFIX}InverseWarp.nii.gz ) set(WARP_IMAGE ${CMAKE_BINARY_DIR}/${THIS_TEST_NAME}_warped.nii.gz) set(INVERSEWARP_IMAGE ${CMAKE_BINARY_DIR}/${THIS_TEST_NAME}_inversewarped.nii.gz) add_test(NAME ${THIS_TEST_NAME} COMMAND ANTS 2 -i 191x170x155x40x30 -r Gauss[3,0] -t SyN[0.2] -m MSQ[${DEVIL_IMAGE},${ANGEL_IMAGE},1,0] -m PSE[${DEVIL_IMAGE},${ANGEL_IMAGE},${DEVIL_IMAGE_TXT},${ANGEL_IMAGE_TXT},1,0.1,11,1,1] --continue-affine 0 --number-of-affine-iterations 0 -o ${OUTPUT_PREFIX}.nii.gz --use-all-metrics-for-convergence 1 ) ======================= File: Utilities/itkVectorImageFileReader.hxx ======================= <reponame>KevinScholtes/ANTsX /*========================================================================= Program: Advanced Normalization Tools Copyright (c) ConsortiumOfANTS. All rights reserved. See accompanying COPYING.txt or https://github.com/stnava/ANTs/blob/master/ANTSCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef _itkVectorImageFileReader_hxx #define _itkVectorImageFileReader_hxx #include "itkVectorImageFileReader.h" #include "itkObjectFactory.h" #include "itkImageIOFactory.h" #include "itkConvertPixelBuffer.h" #include "itkImageRegion.h" #include "itkPixelTraits.h" #include "itkVectorImage.h" #include "itkImageRegionIterator.h" #include <itksys/SystemTools.hxx> #include <fstream> namespace itk { template <typename TImage, typename TVectorImage, typename ConvertPixelTraits> VectorImageFileReader<TImage, TVectorImage, ConvertPixelTraits> ::VectorImageFileReader() { m_ImageIO = 0; m_FileName = ""; m_UserSpecifiedImageIO = false; m_UseAvantsNamingConvention = true; } template <typename TImage, typename TVectorImage, typename ConvertPixelTraits> VectorImageFileReader<TImage, TVectorImage, ConvertPixelTraits> ::~VectorImageFileReader() { } template <typename TImage, typename TVectorImage, typename ConvertPixelTraits> void VectorImageFileReader<TImage, TVectorImage, ConvertPixelTraits> ::PrintSelf(std::ostream& os, Indent indent) const { Superclass::PrintSelf(os, indent); if( m_ImageIO ) { os << indent << "ImageIO: \n"; m_ImageIO->Print(os, indent.GetNextIndent() ); } else { os << indent << "ImageIO: (null)" << "\n"; } os << indent << "UserSpecifiedImageIO flag: " << m_UserSpecifiedImageIO << "\n"; os << indent << "m_FileName: " << m_FileName << "\n"; } template <typename TImage, typename TVectorImage, typename ConvertPixelTraits> void VectorImageFileReader<TImage, TVectorImage, ConvertPixelTraits> ::SetImageIO( ImageIOBase * imageIO) { itkDebugMacro("setting ImageIO to " << imageIO ); if( this->m_ImageIO!= imageIO ) { this->m_ImageIO = imageIO; this->Modified(); } m_UserSpecifiedImageIO = true; } template <typename TImage, typename TVectorImage, typename ConvertPixelTraits> void VectorImageFileReader<TImage, TVectorImage, ConvertPixelTraits> ::GenerateOutputInformation(void) { typename TVectorImage::Pointer output = this->GetOutput(); itkDebugMacro(<< "Reading file for GenerateOutputInformation()" << m_FileName); // Check to see if we can read the file given the name or prefix // if( m_FileName == "" ) { throw VectorImageFileReaderException(__FILE__, __LINE__, "FileName must be specified", ITK_LOCATION); } // Test if the files exist and if it can be open. // and exception will be thrown otherwise. // std::string tmpFileName = this->m_FileName; // Test if the file exists and if it can be opened. // An exception will be thrown otherwise. // We catch the exception because some ImageIO's may not actually // open a file. Still reports file error if no ImageIO is loaded. try { m_ExceptionMessage = ""; this->TestFileExistanceAndReadability(); } catch( itk::ExceptionObject & err ) { m_ExceptionMessage = err.GetDescription(); } std::string::size_type pos = this->m_FileName.rfind( "." ); std::string extension( this->m_FileName, pos, this->m_FileName.length() - 1 ); std::string filename = std::string( this->m_FileName, 0, pos ); std::string gzExtension( "" ); if( extension == std::string( ".gz" ) ) { gzExtension = extension; std::string::size_type pos2 = filename.rfind( "." ); extension = std::string( filename, pos2, filename.length() - 1 ); filename = std::string( this->m_FileName, 0, pos2 ); } // unsigned int dimension = itk::GetVectorDimension // <VectorImagePixelType>::VectorDimension; // Assume that the first image read contains all the information to generate // the output image. for( unsigned int i = 0; i <= 1; i++ ) { this->m_FileName = filename; if( this->m_UseAvantsNamingConvention ) { switch( i ) { case 0: { this->m_FileName += std::string( "xvec" ); } break; case 1: { this->m_FileName += std::string( "yvec" ); } break; case 2: { this->m_FileName += std::string( "zvec" ); } break; default: { this->m_FileName += std::string( "you_are_screwed_vec" ); } break; } } else { std::ostringstream buf; buf << i; this->m_FileName += ( std::string( "." ) + std::string( buf.str().c_str() ) ); } this->m_FileName += extension; if(!gzExtension.empty() ) { this->m_FileName += std::string( ".gz" ); } if( i == 0 ) { itkDebugMacro( << "Generating output information from the file " << this->m_FileName ); if( m_UserSpecifiedImageIO == false ) // try creating via factory { m_ImageIO = ImageIOFactory::CreateImageIO( m_FileName.c_str(), ImageIOFactory::ReadMode ); } if( m_ImageIO.IsNull() ) { std::ostringstream msg; msg << " Could not create IO object for file " << m_FileName.c_str() << std::endl; if( m_ExceptionMessage.size() ) { msg << m_ExceptionMessage; } else { msg << " Tried to create one of the following:" << std::endl; std::list<LightObject::Pointer> allobjects = ObjectFactoryBase::CreateAllInstance("itkImageIOBase"); for( std::list<LightObject::Pointer>::iterator i = allobjects.begin(); i!= allobjects.end(); ++i ) { ImageIOBase* io = dynamic_cast<ImageIOBase *>(i->GetPointer() ); msg << " " << io->GetNameOfClass() << std::endl; } msg << " You probably failed to set a file suffix, or" << std::endl; msg << " set the suffix to an unsupported type." << std::endl; } VectorImageFileReaderException e(__FILE__, __LINE__, msg.str().c_str(), ITK_LOCATION); throw e; return; } // Got to allocate space for the image. Determine the characteristics of // the image. // m_ImageIO->SetFileName(m_FileName.c_str() ); m_ImageIO->ReadImageInformation(); typename TVectorImage::SizeType dimSize; double spacing[TVectorImage::ImageDimension]; double origin[TVectorImage::ImageDimension]; typename TVectorImage::DirectionType direction; std::vector<double> axis; for( unsigned int k = 0; k < TImage::ImageDimension; k++ ) { if( k < m_ImageIO->GetNumberOfDimensions() ) { dimSize[k] = m_ImageIO->GetDimensions(k); spacing[k] = m_ImageIO->GetSpacing(k); origin[k] = m_ImageIO->GetOrigin(k); // Please note: direction cosines are stored as columns of the // direction matrix axis = m_ImageIO->GetDirection(k); for( unsigned j = 0; j < TImage::ImageDimension; j++ ) { if( j < m_ImageIO->GetNumberOfDimensions() ) { direction[j][k] = axis[j]; } else { direction[j][k] = 0.0; } } } else { // Number of dimensions in the output is more than number of dimensions // in the ImageIO object (the file). Use default values for the size, // spacing, origin and direction for the final (degenerate) dimensions. dimSize[i] = 1; spacing[i] = 1.0; origin[i] = 0.0; for( unsigned j = 0; j < TImage::ImageDimension; j++ ) { if( i == j ) { direction[j][k] = 1.0; } else { direction[j][k] = 0.0; } } } } output->SetSpacing( spacing ); // Set the image spacing output->SetOrigin( origin ); // Set the image origin output->SetDirection( direction ); // Set the image direction cosines // Copy MetaDataDictionary from instantiated reader to output image. output->SetMetaDataDictionary(m_ImageIO->GetMetaDataDictionary() ); this->SetMetaDataDictionary(m_ImageIO->GetMetaDataDictionary() ); this->m_Image->SetSpacing( spacing ); this->m_Image->SetOrigin( origin ); this->m_Image->SetDirection( direction ); this->m_Image->SetMetaDataDictionary(m_ImageIO->GetMetaDataDictionary() ); typedef typename TVectorImage::IndexType IndexType; IndexType start; start.Fill(0); VectorImageRegionType region; region.SetSize(dimSize); region.SetIndex(start); ImageRegionType imageregion; imageregion.SetSize(dimSize); imageregion.SetIndex(start); // If a VectorImage, this requires us to set the // VectorLength before allocate // if( strcmp( output->GetNameOfClass(), "VectorImage" ) == 0 ) // { // typedef typename TImage::AccessorFunctorType AccessorFunctorType; // AccessorFunctorType::SetVectorLength( output, m_ImageIO->GetNumberOfComponents() ); // } output->SetLargestPossibleRegion( region ); this->m_Image->SetLargestPossibleRegion( imageregion ); } } this->m_FileName = tmpFileName; } template <typename TImage, typename TVectorImage, typename ConvertPixelTraits> void VectorImageFileReader<TImage, TVectorImage, ConvertPixelTraits> ::TestFileExistanceAndReadability() { std::string tmpFileName = this->m_FileName; std::string::size_type pos = this->m_FileName.rfind( "." ); std::string extension( this->m_FileName, pos, this->m_FileName.length() - 1 ); std::string filename = std::string( this->m_FileName, 0, pos ); std::string gzExtension( "" ); if( extension == std::string( ".gz" ) ) { gzExtension = extension; std::string::size_type pos2 = filename.rfind( "." ); extension = std::string( filename, pos2, filename.length() - 1 ); filename = std::string( this->m_FileName, 0, pos2 ); } unsigned int dimension = itk::GetVectorDimension <VectorImagePixelType>::VectorDimension; for( unsigned int i = 0; i < dimension; i++ ) { this->m_FileName = filename; if( this->m_UseAvantsNamingConvention ) { switch( i ) { case 0: { this->m_FileName += std::string( "xvec" ); } break; case 1: { this->m_FileName += std::string( "yvec" ); } break; case 2: { this->m_FileName += std::string( "zvec" ); } break; default: { this->m_FileName += std::string( "you_are_screwed_vec" ); } break; } } else { std::ostringstream buf; buf << i; this->m_FileName += ( std::string( "." ) + std::string( buf.str().c_str() ) ); } this->m_FileName += extension; if(!gzExtension.empty() ) { this->m_FileName += std::string( ".gz" ); } itkDebugMacro( << "Checking for the file " << this->m_FileName ); // Test if the file exists. if(!itksys::SystemTools::FileExists( m_FileName.c_str() ) ) { VectorImageFileReaderException e(__FILE__, __LINE__); std::ostringstream msg; msg << "The file doesn't exists. " << std::endl << "Filename = " << m_FileName << std::endl; e.SetDescription(msg.str().c_str() ); throw e; return; } // Test if the file can be open for reading access. std::ifstream readTester; readTester.open( m_FileName.c_str() ); if( readTester.fail() ) { readTester.close(); std::ostringstream msg; msg << "The file couldn't be opened for reading. " << std::endl << "Filename: " << m_FileName << std::endl; VectorImageFileReaderException e(__FILE__, __LINE__, msg.str().c_str(), ITK_LOCATION); throw e; return; } readTester.close(); } this->m_FileName = tmpFileName; } template <typename TImage, typename TVectorImage, typename ConvertPixelTraits> void VectorImageFileReader<TImage, TVectorImage, ConvertPixelTraits> ::EnlargeOutputRequestedRegion(DataObject *output) { typename TVectorImage::Pointer out = dynamic_cast<TVectorImage *>(output); // the ImageIO object cannot stream, then set the RequestedRegion to the // LargestPossibleRegion if(!m_ImageIO->CanStreamRead() ) { if( out ) { out->SetRequestedRegion( out->GetLargestPossibleRegion() ); } else { throw VectorImageFileReaderException(__FILE__, __LINE__, "Invalid output object type"); } } } template <typename TImage, typename TVectorImage, typename ConvertPixelTraits> void VectorImageFileReader<TImage, TVectorImage, ConvertPixelTraits> ::GenerateData() { typename TVectorImage::Pointer output = this->GetOutput(); // allocate the output buffer output->SetBufferedRegion( output->GetRequestedRegion() ); output->Allocate(); this->m_Image->SetBufferedRegion( output->GetRequestedRegion() ); this->m_Image->Allocate(); // Test if the file exist and if it can be open. // and exception will be thrown otherwise. try { m_ExceptionMessage = ""; this->TestFileExistanceAndReadability(); } catch( itk::ExceptionObject & err ) { m_ExceptionMessage = err.GetDescription(); } std::string tmpFileName = this->m_FileName; std::string::size_type pos = this->m_FileName.rfind( "." ); std::string extension( this->m_FileName, pos, this->m_FileName.length() - 1 ); std::string filename = std::string( this->m_FileName, 0, pos ); std::string gzExtension( "" ); if( extension == std::string( ".gz" ) ) { gzExtension = extension; std::string::size_type pos2 = filename.rfind( "." ); extension = std::string( filename, pos2, filename.length() - 1 ); filename = std::string( this->m_FileName, 0, pos2 ); } unsigned int dimension = itk::GetVectorDimension <VectorImagePixelType>::VectorDimension; for( unsigned int i = 0; i < dimension; i++ ) { this->m_FileName = filename; if( this->m_UseAvantsNamingConvention ) { switch( i ) { case 0: { this->m_FileName += std::string( "xvec" ); } break; case 1: { this->m_FileName += std::string( "yvec" ); } break; case 2: { this->m_FileName += std::string( "zvec" ); } break; default: { this->m_FileName += std::string( "you_are_screwed_vec" ); } break; } } else { std::ostringstream buf; buf << i; this->m_FileName += ( std::string( "." ) + std::string( buf.str().c_str() ) ); } this->m_FileName += extension; if(!gzExtension.empty() ) { this->m_FileName += std::string( ".gz" ); } itkDebugMacro( << "Reading image buffer from the file " << this->m_FileName ); // Tell the ImageIO to read the file m_ImageIO->SetFileName(m_FileName.c_str() ); this->m_FileName = tmpFileName; ImageIORegion ioRegion(TImage::ImageDimension); ImageIORegion::SizeType ioSize = ioRegion.GetSize(); ImageIORegion::IndexType ioStart = ioRegion.GetIndex(); typename TImage::SizeType dimSize; for( unsigned int j = 0; j < TImage::ImageDimension; j++ ) { if( j < m_ImageIO->GetNumberOfDimensions() ) { dimSize[j] = m_ImageIO->GetDimensions(j); } else { // Number of dimensions in the output is more than number of dimensions // in the ImageIO object (the file). Use default values for the size, // spacing, and origin for the final (degenerate) dimensions. dimSize[j] = 1; } } for( unsigned int j = 0; j < dimSize.GetSizeDimension(); ++j ) { ioSize[j] = dimSize[j]; } typedef typename TImage::IndexType IndexType; IndexType start; start.Fill(0); for( unsigned int j = 0; j < start.GetIndexDimension(); ++j ) { ioStart[j] = start[j]; } ioRegion.SetSize(ioSize); ioRegion.SetIndex(ioStart); itkDebugMacro(<< "ioRegion: " << ioRegion); m_ImageIO->SetIORegion(ioRegion); char *loadBuffer = 0; // the size of the buffer is computed based on the actual number of // pixels to be read and the actual size of the pixels to be read // (as opposed to the sizes of the output) try { if( /** FIXME */ // m_ImageIO->GetComponentTypeInfo() // != typeid(ITK_TYPENAME ConvertPixelTraits::ComponentType) // || (m_ImageIO->GetNumberOfComponents() != ConvertPixelTraits::GetNumberOfComponents() ) ) { // the pixel types don't match so a type conversion needs to be // performed itkDebugMacro(<< "Buffer conversion required from: " << " FIXME m_ImageIO->GetComponentTypeInfo().name() " << " to: " << typeid(ITK_TYPENAME ConvertPixelTraits::ComponentType).name() ); loadBuffer = new char[m_ImageIO->GetImageSizeInBytes()]; m_ImageIO->Read( static_cast<void *>(loadBuffer) ); // See note below as to why the buffered region is needed and // not actualIOregion this->DoConvertBuffer(static_cast<void *>(loadBuffer), output->GetBufferedRegion().GetNumberOfPixels() ); } else // a type conversion is not necessary { itkDebugMacro(<< "No buffer conversion required."); ImagePixelType *buffer = this->m_Image->GetPixelContainer()->GetBufferPointer(); m_ImageIO->Read( buffer ); } } catch(... ) { // if an exception is thrown catch it if( loadBuffer ) { // clean up delete [] loadBuffer; loadBuffer = 0; } // then rethrow throw; } // clean up if( loadBuffer ) { delete [] loadBuffer; loadBuffer = 0; } ImageRegionIterator<TVectorImage> Id( this->GetOutput(), this->GetOutput()->GetLargestPossibleRegion() ); ImageRegionIterator<TImage> It( this->m_Image, this->m_Image->GetLargestPossibleRegion() ); Id.GoToBegin(); It.GoToBegin(); while(!Id.IsAtEnd() ||!It.IsAtEnd() ) { VectorImagePixelType V = Id.Get(); V[i] = static_cast<typename VectorImagePixelType::ValueType>( It.Get() ); Id.Set( V ); ++Id; ++It; } } } template <typename TImage, typename TVectorImage, typename ConvertPixelTraits> void VectorImageFileReader<TImage, TVectorImage, ConvertPixelTraits> ::DoConvertBuffer(void* inputData, unsigned long numberOfPixels) { // get the pointer to the destination buffer ImagePixelType *imageData = this->m_Image->GetPixelContainer()->GetBufferPointer(); // TODO: // Pass down the PixelType (RGB, VECTOR, etc.) so that any vector to // scalar conversion be type specific. i.e. RGB to scalar would use // a formula to convert to luminance, VECTOR to scalar would use // vector magnitude. // Create a macro as this code is a bit lengthy and repetitive // if the ImageIO pixel type is typeid(type) then use the ConvertPixelBuffer // class to convert the data block to TImage's pixel type // see DefaultConvertPixelTraits and ConvertPixelBuffer // The first else if block applies only to images of type itk::VectorImage // VectorImage needs to copy out the buffer differently.. The buffer is of // type InternalPixelType, but each pixel is really 'k' consecutive pixels. #define ITK_CONVERT_BUFFER_IF_BLOCK(type) \ else if( true /** FIXME m_ImageIO->GetComponentTypeInfo() == typeid(type) ) */ ) \ { \ if( strcmp( this->GetOutput()->GetNameOfClass(), "VectorImage" ) == 0 ) \ { \ ConvertPixelBuffer< \ type, \ ImagePixelType, \ ConvertPixelTraits \ > \ ::ConvertVectorImage( \ static_cast<type *>(inputData), \ m_ImageIO->GetNumberOfComponents(), \ imageData, \ numberOfPixels); \ } \ else \ { \ ConvertPixelBuffer< \ type, \ ImagePixelType, \ ConvertPixelTraits \ > \ ::Convert( \ static_cast<type *>(inputData), \ m_ImageIO->GetNumberOfComponents(), \ imageData, \ numberOfPixels); \ } \ } if( 0 ) { } ITK_CONVERT_BUFFER_IF_BLOCK(unsigned char) ITK_CONVERT_BUFFER_IF_BLOCK(char) ITK_CONVERT_BUFFER_IF_BLOCK(unsigned short) ITK_CONVERT_BUFFER_IF_BLOCK( short) ITK_CONVERT_BUFFER_IF_BLOCK(unsigned int) ITK_CONVERT_BUFFER_IF_BLOCK( int) ITK_CONVERT_BUFFER_IF_BLOCK(unsigned long) ITK_CONVERT_BUFFER_IF_BLOCK( long) ITK_CONVERT_BUFFER_IF_BLOCK(float) ITK_CONVERT_BUFFER_IF_BLOCK( double) else { VectorImageFileReaderException e(__FILE__, __LINE__); std::ostringstream msg; msg << "Couldn't convert component type: " << std::endl << " " << m_ImageIO->GetComponentTypeAsString(m_ImageIO->GetComponentType() ) << std::endl << "to one of: " << std::endl << " " << typeid(unsigned char).name() << std::endl << " " << typeid(char).name() << std::endl << " " << typeid(unsigned short).name() << std::endl << " " << typeid(short).name() << std::endl << " " << typeid(unsigned int).name() << std::endl << " " << typeid(int).name() << std::endl << " " << typeid(unsigned long).name() << std::endl << " " << typeid(long).name() << std::endl << " " << typeid(float).name() << std::endl << " " << typeid(double).name() << std::endl; e.SetDescription(msg.str().c_str() ); e.SetLocation(ITK_LOCATION); throw e; return; } #undef ITK_CONVERT_BUFFER_IF_BLOCK } } // namespace ITK #endif ======================= File: Examples/ANTSIntegrateVectorField.cxx ======================= #include "antsUtilities.h" #include "antsAllocImage.h" #include <algorithm> #include "itkVectorIndexSelectionCastImageFilter.h" #include "itkImageRegionIteratorWithIndex.h" #include "vnl/algo/vnl_determinant.h" #include "itkWarpImageFilter.h" #include "itkImageFileWriter.h" #include "itkRescaleIntensityImageFilter.h" #include "vnl/algo/vnl_determinant.h" #include "itkDiscreteGaussianImageFilter.h" #include "itkVectorLinearInterpolateImageFunction.h" #include "itkGradientRecursiveGaussianImageFilter.h" #include "itkVectorCurvatureAnisotropicDiffusionImageFilter.h" #include "itkLaplacianRecursiveGaussianImageFilter.h" #include "itkGradientRecursiveGaussianImageFilter.h" #include "ReadWriteData.h" namespace ants { template <typename TField, typename TImage> typename TImage::Pointer GetVectorComponent(typename TField::Pointer field, unsigned int index) { // Initialize the Moving to the displacement field typedef TImage ImageType; typename ImageType::Pointer sfield = AllocImage<ImageType>(field); typedef itk::ImageRegionIteratorWithIndex<TField> Iterator; Iterator vfIter( field, field->GetLargestPossibleRegion() ); for( vfIter.GoToBegin();!vfIter.IsAtEnd(); ++vfIter ) { typename TField::PixelType v1 = vfIter.Get(); sfield->SetPixel(vfIter.GetIndex(), v1[index]); } return sfield; } template <typename TImage> typename TImage::Pointer SmoothImage(typename TImage::Pointer image, float sig) { // find min value typedef itk::ImageRegionIteratorWithIndex<TImage> Iterator; Iterator vfIter(image, image->GetLargestPossibleRegion() ); for( vfIter.GoToBegin();!vfIter.IsAtEnd(); ++vfIter ) { typename TImage::PixelType v1 = vfIter.Get(); if( std::isnan(v1) ) { vfIter.Set(0); } } typedef itk::DiscreteGaussianImageFilter<TImage, TImage> dgf; typename dgf::Pointer filter = dgf::New(); filter->SetVariance(sig); filter->SetUseImageSpacingOn(); filter->SetMaximumError(.01f); filter->SetInput(image); filter->Update(); typename TImage::Pointer out = filter->GetOutput(); return out; } template <typename TImage> void SmoothDeformation(typename TImage::Pointer vectorimage, float sig) { typedef itk::Vector<float, 3> VectorType; typedef itk::Image<float, 3> ImageType; typename ImageType::Pointer subimgx = GetVectorComponent<TImage, ImageType>(vectorimage, 0); subimgx = SmoothImage<ImageType>(subimgx, sig); typename ImageType::Pointer subimgy = GetVectorComponent<TImage, ImageType>(vectorimage, 1); subimgy = SmoothImage<ImageType>(subimgy, sig); typename ImageType::Pointer subimgz = GetVectorComponent<TImage, ImageType>(vectorimage, 2); subimgz = SmoothImage<ImageType>(subimgz, sig); typedef itk::ImageRegionIteratorWithIndex<TImage> IteratorType; IteratorType Iterator( vectorimage, vectorimage->GetLargestPossibleRegion().GetSize() ); Iterator.GoToBegin(); while( !Iterator.IsAtEnd() ) { VectorType vec; vec[0] = subimgx->GetPixel(Iterator.GetIndex() ); vec[1] = subimgy->GetPixel(Iterator.GetIndex() ); vec[2] = subimgz->GetPixel(Iterator.GetIndex() ); Iterator.Set(vec); ++Iterator; } return; } template <typename TImage, typename TField, typename TInterp, typename TInterp2> float IntegrateLength( typename TImage::Pointer gmsurf, typename TImage::Pointer /* thickimage */, typename TImage::IndexType velind, typename TField::Pointer lapgrad, float itime, float starttime, const float deltaTime, typename TInterp::Pointer vinterp, typename TImage::SpacingType spacing, float vecsign, float timesign, float gradsign ) { typedef typename TField::PixelType VectorType; typedef typename TField::PointType DPointType; typedef itk::VectorLinearInterpolateImageFunction<TField, float> DefaultInterpolatorType; VectorType zero; zero.Fill(0); VectorType disp; disp.Fill(0); unsigned int ct = 0; DPointType pointIn1; DPointType pointIn2; typename DefaultInterpolatorType::ContinuousIndexType vcontind; DPointType pointIn3; enum { ImageDimension = TImage::ImageDimension }; typedef typename TImage::IndexType IndexType; unsigned int m_NumberOfTimePoints = 2; for( unsigned int jj = 0; jj < ImageDimension; jj++ ) { pointIn1[jj] = velind[jj] * lapgrad->GetSpacing()[jj]; } itime = starttime; bool timedone = false; float totalmag = 0; while(!timedone ) { float scale = 1; // *m_DT[timeind]/m_DS[timeind]; // std::cout << " scale " << scale << std::endl; double itimetn1 = itime - timesign * deltaTime * scale; double itimetn1h = itime - timesign * deltaTime * 0.5 * scale; if( itimetn1h < 0 ) { itimetn1h = 0; } if( itimetn1h > m_NumberOfTimePoints - 1 ) { itimetn1h = m_NumberOfTimePoints - 1; } if( itimetn1 < 0 ) { itimetn1 = 0; } if( itimetn1 > m_NumberOfTimePoints - 1 ) { itimetn1 = m_NumberOfTimePoints - 1; } // first get current position of particle for( unsigned int jj = 0; jj < ImageDimension; jj++ ) { pointIn1[jj] = velind[jj] * lapgrad->GetSpacing()[jj]; } // std::cout << " ind " << index << std::endl; // now index the time varying field at that position. typename DefaultInterpolatorType::OutputType f1; f1.Fill(0); typename DefaultInterpolatorType::OutputType f2; f2.Fill(0); typename DefaultInterpolatorType::OutputType f3; f3.Fill(0); typename DefaultInterpolatorType::OutputType f4; f4.Fill(0); typename DefaultInterpolatorType::ContinuousIndexType Y1; typename DefaultInterpolatorType::ContinuousIndexType Y2; typename DefaultInterpolatorType::ContinuousIndexType Y3; typename DefaultInterpolatorType::ContinuousIndexType Y4; for( unsigned int jj = 0; jj < ImageDimension; jj++ ) { pointIn2[jj] = disp[jj] + pointIn1[jj]; vcontind[jj] = pointIn2[jj] / lapgrad->GetSpacing()[jj]; Y1[jj] = vcontind[jj]; Y2[jj] = vcontind[jj]; Y3[jj] = vcontind[jj]; Y4[jj] = vcontind[jj]; } // Y1[ImageDimension]=itimetn1; // Y2[ImageDimension]=itimetn1h; // Y3[ImageDimension]=itimetn1h; // Y4[ImageDimension]=itime; f1 = vinterp->EvaluateAtContinuousIndex( Y1 ); for( unsigned int jj = 0; jj < ImageDimension; jj++ ) { Y2[jj] += f1[jj] * deltaTime * 0.5; } bool isinside = true; for( unsigned int jj = 0; jj < ImageDimension; jj++ ) { if( Y2[jj] < 1 || Y2[jj] > lapgrad->GetLargestPossibleRegion().GetSize()[jj] - 2 ) { isinside = false; } } if( isinside ) { f2 = vinterp->EvaluateAtContinuousIndex( Y2 ); } for( unsigned int jj = 0; jj < ImageDimension; jj++ ) { Y3[jj] += f2[jj] * deltaTime * 0.5; } isinside = true; for( unsigned int jj = 0; jj < ImageDimension; jj++ ) { if( Y3[jj] < 1 || Y3[jj] > lapgrad->GetLargestPossibleRegion().GetSize()[jj] - 2 ) { isinside = false; } } if( isinside ) { f3 = vinterp->EvaluateAtContinuousIndex( Y3 ); } for( unsigned int jj = 0; jj < ImageDimension; jj++ ) { Y4[jj] += f3[jj] * deltaTime; } isinside = true; for( unsigned int jj = 0; jj < ImageDimension; jj++ ) { if( Y4[jj] < 1 || Y4[jj] > lapgrad->GetLargestPossibleRegion().GetSize()[jj] - 2 ) { isinside = false; } } if( isinside ) { f4 = vinterp->EvaluateAtContinuousIndex( Y4 ); } for( unsigned int jj = 0; jj < ImageDimension; jj++ ) { pointIn3[jj] = pointIn2[jj] + gradsign * vecsign * deltaTime / 6.0 * ( f1[jj] + 2.0 * f2[jj] + 2.0 * f3[jj] + f4[jj] ); } VectorType out; float mag = 0, dmag = 0, voxmag = 0; for( unsigned int jj = 0; jj < ImageDimension; jj++ ) { out[jj] = pointIn3[jj] - pointIn1[jj]; mag += (pointIn3[jj] - pointIn2[jj]) * (pointIn3[jj] - pointIn2[jj]); voxmag += (pointIn3[jj] - pointIn2[jj]) / spacing[jj] * (pointIn3[jj] - pointIn2[jj]) / spacing[jj]; dmag += (pointIn3[jj] - pointIn1[jj]) * (pointIn3[jj] - pointIn1[jj]); disp[jj] = out[jj]; } voxmag = sqrt(voxmag); dmag = sqrt(dmag); totalmag += sqrt(mag); ct++; // if (!propagate) //thislength=dmag;// // thislength += totalmag; itime = itime + deltaTime * timesign; IndexType myind; for( unsigned int qq = 0; qq < ImageDimension; qq++ ) { myind[qq] = (unsigned long)(pointIn3[qq] / spacing[qq] + 0.5); } if( gmsurf->GetPixel(myind) < 1 ) { timedone = true; } if( ct > 1000 ) { std::cout << " stopping b/c exceed 1000 points " << voxmag << std::endl; timedone = true; } if( voxmag < 0.1 ) { timedone = true; } } return totalmag; } template <unsigned int ImageDimension> int IntegrateVectorField(int argc, char *argv[]) { typedef float PixelType; typedef itk::Vector<float, ImageDimension> VectorType; typedef itk::Image<VectorType, ImageDimension> DisplacementFieldType; typedef itk::Image<PixelType, ImageDimension> ImageType; typedef typename ImageType::SpacingType SpacingType; constexpr float deltaTime = 0.001; float gradstep = 1. / deltaTime; // atof(argv[3])*(-1.0); std::string vectorfn = std::string(argv[1]); std::string roifn = std::string(argv[2]); int argct = 3; argct++; std::string lenoutname = std::string(""); if( argc > argct ) { lenoutname = std::string(argv[argct]); } argct++; if( argc > argct ) { gradstep *= atof(argv[argct]); } argct++; typename ImageType::Pointer ROIimage; ReadImage<ImageType>(ROIimage, roifn.c_str() ); typename ImageType::Pointer thickimage; ReadImage<ImageType>(thickimage, roifn.c_str() ); thickimage->FillBuffer(0); typename DisplacementFieldType::Pointer VECimage; ReadImage<DisplacementFieldType>(VECimage, vectorfn.c_str() ); SpacingType spacing = ROIimage->GetSpacing(); typedef itk::ImageRegionIteratorWithIndex<ImageType> IteratorType; IteratorType Iterator( ROIimage, ROIimage->GetLargestPossibleRegion().GetSize() ); double timezero = 0; // 1 double timeone = 1; // (s[ImageDimension]-1-timezero); float starttime = timezero; // timezero; float finishtime = timeone; // s[ImageDimension]-1;//timeone; typename DisplacementFieldType::IndexType velind; float timesign = 1.0; if( starttime > finishtime ) { timesign = -1.0; } typedef DisplacementFieldType TimeVaryingVelocityFieldType; typedef typename DisplacementFieldType::PointType DPointType; typedef itk::VectorLinearInterpolateImageFunction<TimeVaryingVelocityFieldType, float> DefaultInterpolatorType; typename DefaultInterpolatorType::Pointer vinterp = DefaultInterpolatorType::New(); typedef itk::LinearInterpolateImageFunction<ImageType, float> ScalarInterpolatorType; VectorType zero; zero.Fill(0); typedef itk::ImageRegionIteratorWithIndex<DisplacementFieldType> VIteratorType; VIteratorType VIterator( VECimage, VECimage->GetLargestPossibleRegion().GetSize() ); VIterator.GoToBegin(); while( !VIterator.IsAtEnd() ) { VectorType vec = VIterator.Get(); float mag = 0; for( unsigned int qq = 0; qq < ImageDimension; qq++ ) { mag += vec[qq] * vec[qq]; } mag = sqrt(mag); if( mag > 0 ) { vec = vec / mag; } VIterator.Set(vec * gradstep); ++VIterator; } Iterator.GoToBegin(); while( !Iterator.IsAtEnd() ) { velind = Iterator.GetIndex(); float itime = starttime; VectorType disp; disp.Fill(0.0); if( ROIimage->GetPixel(velind) == 2 ) { vinterp->SetInputImage(VECimage); float gradsign = -1.0; double vecsign = -1.0; float len1 = IntegrateLength<ImageType, DisplacementFieldType, DefaultInterpolatorType, ScalarInterpolatorType> (ROIimage, thickimage, velind, VECimage, itime, starttime, deltaTime, vinterp, spacing, vecsign, gradsign, timesign); gradsign = 1.0; vecsign = 1; const float len2 = IntegrateLength<ImageType, DisplacementFieldType, DefaultInterpolatorType, ScalarInterpolatorType> (ROIimage, thickimage, velind, VECimage, itime, starttime, deltaTime, vinterp, spacing, vecsign, gradsign, timesign ); float totalength = len1 + len2; thickimage->SetPixel(velind, totalength); if( (totalength) > 0 ) { std::cout << " len1 " << len1 << " len2 " << len2 << " ind " << velind << std::endl; } } ++Iterator; } WriteImage<ImageType>(thickimage, lenoutname.c_str() ); return EXIT_SUCCESS; } // entry point for the library; parameter 'args' is equivalent to 'argv' in (argc,argv) of commandline parameters to //'main()' int ANTSIntegrateVectorField( std::vector<std::string> args, std::ostream* /*out_stream = nullptr*/ ) { // put the arguments coming in as 'args' into standard (argc,argv) format; // 'args' doesn't have the command name as first, argument, so add it manually; // 'args' may have adjacent arguments concatenated into one argument, // which the parser should handle args.insert( args.begin(), "ANTSIntegrateVectorField" ); int argc = args.size(); char* * argv = new char *[args.size() + 1]; for( unsigned int i = 0; i < args.size(); ++i ) { // allocate space for the string plus a null character argv[i] = new char[args[i].length() + 1]; std::strncpy( argv[i], args[i].c_str(), args[i].length() ); // place the null character in the end argv[i][args[i].length()] = '\0'; } argv[argc] = nullptr; // class to automatically cleanup argv upon destruction class Cleanup_argv { public: Cleanup_argv( char* * argv_, int argc_plus_one_ ) : argv( argv_ ), argc_plus_one( argc_plus_one_ ) { } ~Cleanup_argv() { for( unsigned int i = 0; i < argc_plus_one; ++i ) { delete[] argv[i]; } delete[] argv; } private: char* * argv; unsigned int argc_plus_one; }; Cleanup_argv cleanup_argv( argv, argc + 1 ); // antscout->set_stream( out_stream ); if( argc < 4 ) { std::cout << "Usage: " << argv[0] << " VecImageIN.nii.gz ROIMaskIN.nii.gz FibersOUT.vtk LengthImageOUT.nii.gz " << std::endl; std::cout << " The vector field should have vectors as voxels, the ROI is an integer image, fibers out will be vtk text files.... " << std::endl; std::cout << " ROI-Mask controls where the integration is performed and the start point region... " << std::endl; std::cout << " e.g. the brain will have value 1, the ROI has value 2, then all starting seed points " << std::endl; std::cout << " for the integration will start in the region labeled 2 and be constrained to the region labeled 1. " << std::endl; if( argc >= 2 && ( std::string( argv[1] ) == std::string("--help") || std::string( argv[1] ) == std::string("-h") ) ) { return EXIT_SUCCESS; } return EXIT_FAILURE; } std::string ifn = std::string(argv[1]); itk::ImageIOBase::Pointer imageIO = itk::ImageIOFactory::CreateImageIO(ifn.c_str(), itk::ImageIOFactory::ReadMode); imageIO->SetFileName(ifn.c_str() ); imageIO->ReadImageInformation(); unsigned int dim = imageIO->GetNumberOfDimensions(); switch( dim ) { case 2: { IntegrateVectorField<2>(argc, argv); } break; case 3: { IntegrateVectorField<3>(argc, argv); } break; case 4: { IntegrateVectorField<4>(argc, argv); } break; default: std::cerr << "Unsupported dimension" << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } } // namespace ants ======================= File: Examples/ANTSIntegrateVelocityField.cxx ======================= <filename>Examples/ANTSIntegrateVelocityField.cxx<gh_stars>0 #include "antsUtilities.h" #include "antsAllocImage.h" #include <algorithm> #include "itkVectorIndexSelectionCastImageFilter.h" #include "itkImageRegionIteratorWithIndex.h" #include "vnl/algo/vnl_determinant.h" #include "itkANTSImageRegistrationOptimizer.h" #include "itkTimeVaryingVelocityFieldIntegrationImageFilter.h" #include "itkWarpImageFilter.h" #include "itkTimeVaryingVelocityFieldTransform.h" #include "itkImageFileWriter.h" #include "itkRescaleIntensityImageFilter.h" #include "vnl/algo/vnl_determinant.h" #include "itkDiscreteGaussianImageFilter.h" #include "itkVectorLinearInterpolateImageFunction.h" #include "itkGradientRecursiveGaussianImageFilter.h" #include "itkVectorCurvatureAnisotropicDiffusionImageFilter.h" #include "itkLaplacianRecursiveGaussianImageFilter.h" #include "itkGradientRecursiveGaussianImageFilter.h" #include "ReadWriteData.h" namespace ants { template <unsigned int ImageDimension> int IntegrateVelocityField(int argc, char *argv[]) { int argct = 1; std::string imgfn = std::string(argv[argct]); argct++; std::string vectorfn = std::string(argv[argct]); argct++; std::string outname = std::string(argv[argct]); argct++; typedef float PixelType; PixelType timezero = 0; PixelType timeone = 1; PixelType dT = 0.01; if( argc > argct ) { timezero = atof(argv[argct]); } argct++; if( argc > argct ) { timeone = atof(argv[argct]); } argct++; if( argc > argct ) { dT = atof(argv[argct]); } argct++; std::cout << " time-0 " << timezero << " dt " << dT << " time-1 " << timeone << std::endl; PixelType starttime = timezero; PixelType finishtime = timeone; typedef float PixelType; typedef itk::Vector<PixelType, ImageDimension> VectorType; typedef itk::Image<VectorType, ImageDimension> DisplacementFieldType; typedef itk::Image<VectorType, ImageDimension + 1> TimeVaryingVelocityFieldType; typedef itk::Image<PixelType, ImageDimension> ImageType; typename ImageType::Pointer image; ReadImage<ImageType>(image, imgfn.c_str() ); typedef TimeVaryingVelocityFieldType tvt; typename tvt::Pointer timeVaryingVelocity; ReadImage<tvt>(timeVaryingVelocity, vectorfn.c_str() ); VectorType zero; zero.Fill(0); typename DisplacementFieldType::Pointer deformation = AllocImage<DisplacementFieldType>(image, zero); if(!timeVaryingVelocity ) { std::cerr << " No TV Field " << std::endl; return EXIT_FAILURE; } if( starttime < 0 ) { starttime = 0; } if( starttime > 1 ) { starttime = 1; } if( finishtime < 0 ) { finishtime = 0; } if( finishtime > 1 ) { finishtime = 1; } typedef itk::TimeVaryingVelocityFieldIntegrationImageFilter <TimeVaryingVelocityFieldType, DisplacementFieldType> IntegratorType; typename IntegratorType::Pointer integrator = IntegratorType::New(); integrator->SetInput( timeVaryingVelocity ); integrator->SetLowerTimeBound( starttime ); integrator->SetUpperTimeBound( finishtime ); integrator->SetNumberOfIntegrationSteps( (unsigned int ) 1 / dT ); integrator->Update(); WriteImage<DisplacementFieldType>( integrator->GetOutput(), outname.c_str() ); return 0; } // entry point for the library; parameter 'args' is equivalent to 'argv' in (argc,argv) of commandline parameters to //'main()' int ANTSIntegrateVelocityField( std::vector<std::string> args, std::ostream* /*out_stream = nullptr */) { // put the arguments coming in as 'args' into standard (argc,argv) format; // 'args' doesn't have the command name as first, argument, so add it manually; // 'args' may have adjacent arguments concatenated into one argument, // which the parser should handle args.insert( args.begin(), "ANTSIntegrateVelocityField" ); int argc = args.size(); char* * argv = new char *[args.size() + 1]; for( unsigned int i = 0; i < args.size(); ++i ) { // allocate space for the string plus a null character argv[i] = new char[args[i].length() + 1]; std::strncpy( argv[i], args[i].c_str(), args[i].length() ); // place the null character in the end argv[i][args[i].length()] = '\0'; } argv[argc] = nullptr; // class to automatically cleanup argv upon destruction class Cleanup_argv { public: Cleanup_argv( char* * argv_, int argc_plus_one_ ) : argv( argv_ ), argc_plus_one( argc_plus_one_ ) { } ~Cleanup_argv() { for( unsigned int i = 0; i < argc_plus_one; ++i ) { delete[] argv[i]; } delete[] argv; } private: char* * argv; unsigned int argc_plus_one; }; Cleanup_argv cleanup_argv( argv, argc + 1 ); // antscout->set_stream( out_stream ); if( argc < 4 ) { std::cerr << "Usage: " << argv[0] << " reference_image VelocityIn.mhd DeformationOut.nii.gz time0 time1 dT " << std::endl; if( argc >= 2 && ( std::string( argv[1] ) == std::string("--help") || std::string( argv[1] ) == std::string("-h") ) ) { return EXIT_SUCCESS; } return EXIT_FAILURE; } std::cout << " start " << std::endl; std::string ifn = std::string(argv[1]); itk::ImageIOBase::Pointer imageIO = itk::ImageIOFactory::CreateImageIO(ifn.c_str(), itk::ImageIOFactory::ReadMode); imageIO->SetFileName(ifn.c_str() ); imageIO->ReadImageInformation(); unsigned int dim = imageIO->GetNumberOfDimensions(); std::cout << " dim " << dim << std::endl; switch( dim ) { case 2: { IntegrateVelocityField<2>(argc, argv); } break; case 3: { IntegrateVelocityField<3>(argc, argv); } break; case 4: { IntegrateVelocityField<4>(argc, argv); } break; default: std::cerr << "Unsupported dimension" << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } } // namespace ants ======================= File: Examples/sccan.cxx ======================= #include "antsUtilities.h" #include "antsAllocImage.h" #include <algorithm> #include "antsCommandLineOption.h" #include "antsCommandLineParser.h" #include "itkImage.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkImageRegionIteratorWithIndex.h" #include "itkRecursiveGaussianImageFilter.h" #include "itkDiscreteGaussianImageFilter.h" #include "itkResampleImageFilter.h" #include "itkBSplineInterpolateImageFunction.h" #include <sstream> #include <iostream> #include <string> #include <algorithm> #include <vector> #include <vnl/vnl_random.h> #include <vnl/algo/vnl_qr.h> #include <vnl/algo/vnl_svd.h> #include <vnl/algo/vnl_svd_economy.h> #include <vnl/algo/vnl_symmetric_eigensystem.h> #include <vnl/algo/vnl_real_eigensystem.h> #include <vnl/algo/vnl_generalized_eigensystem.h> #include "antsSCCANObject.h" #include "itkCSVNumericObjectFileWriter.h" #include "itkCSVArray2DDataObject.h" #include "itkCSVArray2DFileReader.h" #include "itkExtractImageFilter.h" #include "ReadWriteData.h" namespace ants { // namespace antssccan { template <typename TComp> double vnl_pearson_corr( vnl_vector<TComp> v1, vnl_vector<TComp> v2 ) { double xysum = 0; for( unsigned int i = 0; i < v1.size(); i++ ) { xysum += v1(i) * v2(i); } double frac = 1.0 / (double)v1.size(); double xsum = v1.sum(), ysum = v2.sum(); double xsqr = v1.squared_magnitude(); double ysqr = v2.squared_magnitude(); double numer = xysum - frac * xsum * ysum; double denom = sqrt( ( xsqr - frac * xsum * xsum) * ( ysqr - frac * ysum * ysum) ); if( denom <= 0 ) { return 0; } return numer / denom; } template <typename TImage, typename TComp> void WriteVectorToSpatialImage( std::string filename, std::string post, vnl_vector<TComp> w_p, typename TImage::Pointer mask ) { std::string::size_type pos = filename.rfind( "." ); std::string filepre = std::string( filename, 0, pos ); std::string extension; if( pos!= std::string::npos ) { extension = std::string( filename, pos, filename.length() - 1); if( extension == std::string(".gz") ) { pos = filepre.rfind( "." ); extension = std::string( filepre, pos, filepre.length() - 1 ) + extension; filepre = std::string( filepre, 0, pos ); } } typedef itk::ants::antsSCCANObject<TImage, TComp> SCCANType; typename SCCANType::Pointer sccanobj = SCCANType::New(); typename TImage::Pointer weights = sccanobj->ConvertVariateToSpatialImage( w_p, mask ); std::string fn1 = filepre + post + extension; WriteImage<TImage>( weights, fn1.c_str() ); } template <typename T> inline std::string sccan_to_string(const T& t) { std::stringstream ss; ss << t; std::string stringout = ss.str(); if( t < 100 ) { std::stringstream ss0; ss0 << 0; std::string extend = ss0.str(); stringout = std::string(extend + stringout); } if( t < 10 ) { std::stringstream ss0; ss0 << 0; std::string extend = ss0.str(); stringout = std::string(extend + stringout); } return stringout; } template <typename TImage, typename TComp> void WriteSortedVariatesToSpatialImage( std::string filename, std::string post, vnl_matrix<TComp> varmat, typename TImage::Pointer mask, vnl_matrix<TComp> data_mat, bool have_mask, vnl_vector<TComp> l_array, vnl_matrix<TComp> prior_mat ) { vnl_matrix<TComp> projections = data_mat * varmat; std::string::size_type pos = filename.rfind( "." ); std::string filepre = std::string( filename, 0, pos ); std::string extension; if( pos!= std::string::npos ) { extension = std::string( filename, pos, filename.length() - 1); if( extension == std::string(".gz") ) { pos = filepre.rfind( "." ); extension = std::string( filepre, pos, filepre.length() - 1 ) + extension; filepre = std::string( filepre, 0, pos ); } } std::string post2; std::ofstream myfile; std::string fnmp1 = filepre + std::string("projections") + post + std::string(".csv"); std::vector<std::string> ColumnHeaders1; for( unsigned int nv = 0; nv < projections.cols(); nv++ ) { std::string colname = std::string("Variate") + sccan_to_string<unsigned int>(nv); ColumnHeaders1.push_back( colname ); } typedef itk::CSVNumericObjectFileWriter<double> WriterType; WriterType::Pointer writer1 = WriterType::New(); writer1->SetFileName( fnmp1.c_str() ); writer1->SetColumnHeaders(ColumnHeaders1); writer1->SetInput( &projections ); try { writer1->Write(); } catch( itk::ExceptionObject& exp ) { // std::cerr << "Exception caught!" << std::endl; // std::cerr << exp << std::endl; return; } // std::cout << data_mat.cols() << prior_mat.cols() << data_mat.rows() << prior_mat.rows() << std::endl; vnl_matrix<TComp> projectionsROI = data_mat * prior_mat.transpose(); std::string::size_type posROI = filename.rfind( "." ); std::string filepreROI = std::string( filename, 0, posROI ); std::string extensionROI; if( posROI!= std::string::npos ) { extensionROI = std::string( filename, posROI, filename.length() - 1); if( extension == std::string(".gz") ) { posROI = filepreROI.rfind( "." ); extensionROI = std::string( filepreROI, posROI, filepreROI.length() - 1 ) + extensionROI; filepreROI = std::string( filepreROI, 0, posROI ); } } // std::string post2; // std::ofstream myfile; std::string fnmp_prior = filepreROI + std::string("projectionsROI") + post + std::string(".csv"); std::vector<std::string> ColumnHeadersROI; for( unsigned int nv = 0; nv < projectionsROI.cols(); nv++ ) { std::string colnameROI = std::string("Variate") + sccan_to_string<unsigned int>(nv); ColumnHeadersROI.push_back( colnameROI ); } typedef itk::CSVNumericObjectFileWriter<double> WriterType; WriterType::Pointer writerROI = WriterType::New(); writerROI->SetFileName( fnmp_prior.c_str() ); writerROI->SetColumnHeaders(ColumnHeadersROI); writerROI->SetInput( &projectionsROI ); try { writerROI->Write(); } catch( itk::ExceptionObject& exp ) { // std::cerr << "Exception caught!" << std::endl; // std::cerr << exp << std::endl; return; } if( have_mask ) { // std::cout << " have_mask WriteSortedVariatesToSpatialImage " << have_mask << std::endl; for( unsigned int vars = 0; vars < varmat.columns(); vars++ ) { post2 = post + sccan_to_string<unsigned int>(l_array.get(vars) ); vnl_vector<TComp> temp = varmat.get_column(l_array.get(vars) ); // // std::cout<<" File Name "<<filename<<" POST "<<l_array.get(vars)<<std::endl; WriteVectorToSpatialImage<TImage, TComp>( filename, post2, temp, mask); } } else { std::vector<std::string> ColumnHeaders; // write out the array2D object std::string fnmp = filepre + std::string("ViewVecs") + std::string(".csv"); for( unsigned int nv = 0; nv < varmat.cols(); nv++ ) { std::string colname = std::string("Variate") + sccan_to_string<unsigned int>(nv); ColumnHeaders.push_back( colname ); } WriterType::Pointer writer = WriterType::New(); writer->SetFileName( fnmp.c_str() ); writer->SetColumnHeaders(ColumnHeaders); writer->SetInput( &varmat ); try { writer->Write(); } catch( itk::ExceptionObject& exp ) { // std::cerr << "Exception caught!" << std::endl; // std::cerr << exp << std::endl; return; } } } template <typename TImage, typename TComp> void WriteVariatesToSpatialImage( std::string filename, std::string post, vnl_matrix<TComp> varmat, typename TImage::Pointer mask, vnl_matrix<TComp> data_mat, bool have_mask, vnl_matrix<TComp> u_mat ) { vnl_matrix<TComp> projections = data_mat * varmat; std::string::size_type pos = filename.rfind( "." ); std::string filepre = std::string( filename, 0, pos ); std::string extension; if( pos!= std::string::npos ) { extension = std::string( filename, pos, filename.length() - 1); if( extension == std::string(".gz") ) { pos = filepre.rfind( "." ); extension = std::string( filepre, pos, filepre.length() - 1 ) + extension; filepre = std::string( filepre, 0, pos ); } } std::string post2; std::ofstream myfile; std::string fnmp = filepre + std::string("projections") + post + std::string(".csv"); std::vector<std::string> ColumnHeaders; for( unsigned int nv = 0; nv < projections.cols(); nv++ ) { std::string colname = std::string("Variate") + sccan_to_string<unsigned int>(nv); ColumnHeaders.push_back( colname ); } typedef itk::CSVNumericObjectFileWriter<double, 1, 1> WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName( fnmp.c_str() ); writer->SetColumnHeaders(ColumnHeaders); writer->SetInput( &projections ); try { writer->Write(); } catch( itk::ExceptionObject& exp ) { // std::cerr << "Exception caught!" << std::endl; // std::cerr << exp << std::endl; return; } if( have_mask ) { // std::cerr << " have_mask " << have_mask << std::endl; for( unsigned int vars = 0; vars < varmat.columns(); vars++ ) { post2 = post + sccan_to_string<unsigned int>(vars); vnl_vector<TComp> temp = varmat.get_column(vars); WriteVectorToSpatialImage<TImage, TComp>( filename, post2, temp, mask); } } else { ColumnHeaders.clear(); // write out the array2D object fnmp = filepre + std::string("_Variate_") + post + std::string(".csv"); for( unsigned int nv = 0; nv < varmat.cols(); nv++ ) { std::string colname = std::string("Variate") + sccan_to_string<unsigned int>(nv); ColumnHeaders.push_back( colname ); } writer = WriterType::New(); writer->SetFileName( fnmp.c_str() ); writer->SetColumnHeaders(ColumnHeaders); writer->SetInput( &varmat ); try { writer->Write(); } catch( itk::ExceptionObject& exp ) { // std::cerr << "Exception caught!" << std::endl; // std::cerr << exp << std::endl; return; } } if( u_mat.size() > 0 ) { // write out the array2D object for U matrix ColumnHeaders.clear(); fnmp = filepre + std::string("_Umatrix_") + post + std::string(".csv"); for( unsigned int nv = 0; nv < varmat.cols(); nv++ ) { std::string colname = std::string("U") + sccan_to_string<unsigned int>(nv); ColumnHeaders.push_back( colname ); } writer = WriterType::New(); writer->SetFileName( fnmp.c_str() ); writer->SetColumnHeaders(ColumnHeaders); writer->SetInput( &u_mat ); try { writer->Write(); } catch( itk::ExceptionObject& exp ) { // std::cerr << "Exception caught!" << std::endl; // std::cerr << exp << std::endl; return; } } } template <typename TImage, typename TComp> vnl_matrix<TComp> CopyImageToVnlMatrix( typename TImage::Pointer p_img ) { typedef vnl_matrix<TComp> vMatrix; typename TImage::SizeType pMatSize = p_img->GetLargestPossibleRegion().GetSize(); vMatrix p(pMatSize[0], pMatSize[1]); // a (size)x(size+1)-matrix of int's for( unsigned long j = 0; j < p.columns(); ++j ) // loop over columns { for( unsigned long i = 0; i < p.rows(); ++i ) // loop over rows { typename TImage::IndexType ind; ind[0] = i; ind[1] = j; TComp val = p_img->GetPixel(ind); p(i, j) = val; // to access matrix coefficients, } } return p; } template <typename TImage, typename TComp> vnl_matrix<TComp> DeleteRow(vnl_matrix<TComp> p_in, unsigned int row) { typedef vnl_matrix<TComp> vMatrix; unsigned int nrows = p_in.rows() - 1; if( row >= nrows ) { nrows = p_in.rows(); } vMatrix p(nrows, p_in.columns() ); unsigned int rowct = 0; for( long i = 0; i < static_cast<long>(p.rows() ); ++i ) // loop over rows { if( i!= static_cast<long>(row) ) { p.set_row(rowct, p_in.get_row(i) ); rowct++; } } return p; } int sccanRandom(int n) { return rand() % n; } template <typename TComp> vnl_matrix<TComp> PermuteMatrix( vnl_matrix<TComp> q, bool doperm = true) { typedef vnl_matrix<TComp> vMatrix; std::vector<unsigned long> permvec; for( unsigned long i = 0; i < q.rows(); i++ ) { permvec.push_back(i); } std::random_shuffle(permvec.begin(), permvec.end(), sccanRandom); // for (unsigned long i=0; i < q.rows(); i++) // // std::cout << " permv " << i << " is " << permvec[i] << std::endl; // for (unsigned long i=0; i < q.rows(); i++) // // std::cout << " permv " << i << " is " << permvec[i] << std::endl; // 1. permute q vMatrix q_perm(q.rows(), q.columns() ); for( unsigned long i = 0; i < q.rows(); i++ ) { unsigned long perm = permvec[i]; if( doperm ) { q_perm.set_row(i, q.get_row(perm) ); } else { q_perm.set_row(i, q.get_row(i) ); } } return q_perm; } template <unsigned int ImageDimension, typename PixelType> int matrixOperation( itk::ants::CommandLineParser::OptionType *option, itk::ants::CommandLineParser::OptionType * /* outputOption */ = nullptr ) { std::string funcName = std::string("matrixOperation"); typedef itk::Image<PixelType, ImageDimension> ImageType; typename ImageType::Pointer outputImage = nullptr; // option->SetUsageOption( 2, "multires_matrix_invert[list.txt,maskhighres.nii.gz,masklowres.nii.gz,matrix.mhd]" ); std::string value = option->GetFunction( 0 )->GetName(); if( strcmp( value.c_str(), "multires_matrix_invert" ) == 0 ) { std::string listfn = option->GetFunction( 0 )->GetParameter( 0 ); std::string maskhfn = option->GetFunction( 0 )->GetParameter( 1 ); std::string masklfn = option->GetFunction( 0 )->GetParameter( 2 ); // vnl_matrix<matPixelType> matrixinv=MultiResMatrixInvert<ImageDimension,matPixelType>( listfn, maskhfn, // masklfn ); } return EXIT_SUCCESS; } template <typename RealType> int CompareMatrixSizes( vnl_matrix<RealType> & p, vnl_matrix<RealType> & q ) { if( p.rows()!= q.rows() ) { // std::cerr << " The number of rows must match!!" << std::endl; // std::cerr << " matrix-1 has " << p.rows() << " rows " << std::endl; // std::cerr << " matrix-2 has " << q.rows() << " rows " << std::endl; // std::cerr << " returning " << EXIT_FAILURE << std::endl; // throw std::exception(); return EXIT_FAILURE; } return 0; } template <typename PixelType> void ReadMatrixFromCSVorImageSet( std::string matname, vnl_matrix<PixelType> & p ) { typedef PixelType Scalar; typedef itk::Image<PixelType, 2> MatrixImageType; typedef itk::ImageFileReader<MatrixImageType> matReaderType; std::string ext = itksys::SystemTools::GetFilenameExtension( matname ); if( strcmp(ext.c_str(), ".csv") == 0 ) { typedef itk::CSVArray2DFileReader<double> ReaderType; typename ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName( matname.c_str() ); reader->SetFieldDelimiterCharacter( ',' ); reader->SetStringDelimiterCharacter( '"' ); reader->HasColumnHeadersOn(); reader->HasRowHeadersOff(); reader->UseStringDelimiterCharacterOff(); try { reader->Update(); } catch( itk::ExceptionObject& exp ) { // std::cerr << "Exception caught!" << std::endl; // std::cerr << exp << std::endl; } typedef itk::CSVArray2DDataObject<double> DataFrameObjectType; DataFrameObjectType::Pointer dfo = reader->GetOutput(); p = dfo->GetMatrix(); return; } else { typename matReaderType::Pointer matreader1 = matReaderType::New(); matreader1->SetFileName( matname.c_str() ); matreader1->Update(); p = CopyImageToVnlMatrix<MatrixImageType, Scalar>( matreader1->GetOutput() ); } return; } template <unsigned int ImageDimension, typename PixelType> itk::Array2D<double> ConvertImageListToMatrix( std::string imagelist, std::string maskfn, std::string outname ) { std::string ext = itksys::SystemTools::GetFilenameExtension( outname ); typedef itk::Array2D<double> MatrixType; std::vector<std::string> ColumnHeaders; MatrixType zmat(1, 1); typedef itk::Image<PixelType, ImageDimension> ImageType; typedef itk::Image<PixelType, 2> MatrixImageType; typedef itk::ImageFileReader<ImageType> ReaderType; typename ImageType::Pointer mask; ReadImage<ImageType>( mask, maskfn.c_str() ); unsigned long voxct = 0; typedef itk::ImageRegionIteratorWithIndex<ImageType> Iterator; Iterator mIter( mask, mask->GetLargestPossibleRegion() ); for( mIter.GoToBegin();!mIter.IsAtEnd(); ++mIter ) { if( mIter.Get() >= 0.5 ) { voxct++; } } std::vector<std::string> image_fn_list; // first, count the number of files constexpr unsigned int maxChar = 512; char lineBuffer[maxChar]; char filenm[maxChar]; unsigned int filecount = 0; { std::ifstream inputStreamA( imagelist.c_str(), std::ios::in ); if(!inputStreamA.is_open() ) { // std::cout << "Can't open image list file: " << imagelist << std::endl; return zmat; } while(!inputStreamA.eof() ) { inputStreamA.getline( lineBuffer, maxChar, '\n' ); if( sscanf( lineBuffer, "%s ", filenm)!= 1 ) { continue; } else { image_fn_list.emplace_back(filenm ); filecount++; } } inputStreamA.close(); } /** declare the output matrix image */ unsigned long xsize = image_fn_list.size(); unsigned long ysize = voxct; typename MatrixImageType::SizeType tilesize; tilesize[0] = xsize; tilesize[1] = ysize; // // std::cout <<" have voxct " << voxct << " and nsub " << filecount << " or " << image_fn_list.size()<< // std::endl; MatrixType matrix(xsize, ysize); matrix.Fill(0); for( unsigned int j = 0; j < image_fn_list.size(); j++ ) { typename ReaderType::Pointer reader2 = ReaderType::New(); reader2->SetFileName( image_fn_list[j] ); reader2->Update(); unsigned long xx = 0, yy = 0, tvoxct = 0; xx = j; for( mIter.GoToBegin();!mIter.IsAtEnd(); ++mIter ) { if( mIter.Get() >= 0.5 ) { yy = tvoxct; matrix[xx][yy] = reader2->GetOutput()->GetPixel(mIter.GetIndex() ); if( j == 0 ) { std::string colname = std::string("V") + sccan_to_string<unsigned long>(tvoxct); ColumnHeaders.push_back( colname ); } tvoxct++; } } } if( strcmp(ext.c_str(), ".csv") == 0 ) { // write out the array2D object typedef itk::CSVNumericObjectFileWriter<double, 1, 1> WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName( outname ); writer->SetInput( &matrix ); writer->SetColumnHeaders( ColumnHeaders ); try { writer->Write(); } catch( itk::ExceptionObject& exp ) { // std::cerr << "Exception caught!" << std::endl; // std::cerr << exp << std::endl; return matrix; } return matrix; } if( strcmp(ext.c_str(), ".mha") == 0 || strcmp(ext.c_str(), ".mhd") == 0 ) { typename MatrixImageType::RegionType region; region.SetSize( tilesize ); typename MatrixImageType::Pointer matimage = AllocImage<MatrixImageType>(region); for( unsigned int j = 0; j < image_fn_list.size(); j++ ) { typename ReaderType::Pointer reader2 = ReaderType::New(); reader2->SetFileName( image_fn_list[j] ); reader2->Update(); unsigned long xx = 0, yy = 0, tvoxct = 0; xx = j; typename MatrixImageType::IndexType mind; for( mIter.GoToBegin();!mIter.IsAtEnd(); ++mIter ) { if( mIter.Get() >= 0.5 ) { yy = tvoxct; mind[0] = xx; mind[1] = yy; matimage->SetPixel(mind, reader2->GetOutput()->GetPixel(mIter.GetIndex() ) ); tvoxct++; } } } typedef itk::ImageFileWriter<MatrixImageType> WriterType; typename WriterType::Pointer writer = WriterType::New(); writer->SetFileName( outname ); writer->SetInput( matimage ); writer->Update(); } return matrix; } template <typename PixelType> int ConvertTimeSeriesImageToMatrix( std::string imagefn, std::string maskfn, std::string outname, double space_smoother, double time_smoother ) { constexpr unsigned int ImageDimension = 4; typedef itk::Image<PixelType, ImageDimension> ImageType; typedef itk::Image<PixelType, ImageDimension - 1> OutImageType; typedef typename OutImageType::IndexType OutIndexType; typedef typename ImageType::IndexType IndexType; typedef double Scalar; std::string ext = itksys::SystemTools::GetFilenameExtension( outname ); if( strcmp(ext.c_str(), ".csv")!= 0 ) { // std::cerr << " must use.csv as output file extension " << std::endl; return EXIT_FAILURE; } typename ImageType::Pointer image1 = nullptr; typename OutImageType::Pointer mask = nullptr; // std::cerr << " imagefn " << imagefn << std::endl; if( imagefn.length() > 3 ) { ReadImage<ImageType>(image1, imagefn.c_str() ); } else { // std::cerr << " cannot read image " << imagefn << std::endl; return 1; } if( space_smoother > 0 ) { typename ImageType::SpacingType spacing = image1->GetSpacing(); typename ImageType::SpacingType spacing2 = image1->GetSpacing(); // basically, don't do any dim-4 smoothing spacing2[3] = sqrt(spacing[0] * spacing[0] + spacing[1] * spacing[1] + spacing[2] * spacing[2]) * 1.e6; image1->SetSpacing(spacing2); typedef itk::DiscreteGaussianImageFilter<ImageType, ImageType> dgf; typename dgf::Pointer filter = dgf::New(); filter->SetVariance(space_smoother); filter->SetUseImageSpacingOn(); filter->SetMaximumError(.01f); filter->SetInput(image1); filter->Update(); image1 = filter->GetOutput(); image1->SetSpacing(spacing); } if( time_smoother > 0 ) { typename ImageType::SpacingType spacing = image1->GetSpacing(); typename ImageType::SpacingType spacing2 = image1->GetSpacing(); // basically, don't do any dim-4 smoothing double bigspace = sqrt(spacing[0] * spacing[0] + spacing[1] * spacing[1] + spacing[2] * spacing[2]) * 1.e6; // basically no spatial smoothing spacing2.Fill(bigspace); spacing2[3] = 1; image1->SetSpacing(spacing2); typedef itk::DiscreteGaussianImageFilter<ImageType, ImageType> dgf; typename dgf::Pointer filter = dgf::New(); filter->SetVariance(time_smoother); filter->SetUseImageSpacingOn(); filter->SetMaximumError(.01f); filter->SetInput(image1); filter->Update(); image1 = filter->GetOutput(); image1->SetSpacing(spacing); } if( maskfn.length() > 3 ) { ReadImage<OutImageType>(mask, maskfn.c_str() ); } else { // std::cerr << " cannot read mask " << maskfn << std::endl; return EXIT_FAILURE; } unsigned int timedims = image1->GetLargestPossibleRegion().GetSize()[ImageDimension - 1]; unsigned long voxct = 0; typedef itk::ExtractImageFilter<ImageType, OutImageType> ExtractFilterType; typedef itk::ImageRegionIteratorWithIndex<OutImageType> SliceIt; SliceIt mIter( mask, mask->GetLargestPossibleRegion() ); typedef std::vector<unsigned int> LabelSetType; unsigned int maxlabel = 0; LabelSetType myLabelSet1; { /** count the labels in the mask image */ for( mIter.GoToBegin();!mIter.IsAtEnd(); ++mIter ) { auto label = static_cast<unsigned int>( mIter.Get() + 0.5 ); if( label > 0 ) { if( find( myLabelSet1.begin(), myLabelSet1.end(), label ) == myLabelSet1.end() ) { myLabelSet1.push_back( label ); if( label > maxlabel ) { maxlabel = label; } } voxct++; } } } if( maxlabel == 0 ) { // std::cerr << "FAILURE: Max label in input mask " << maskfn << " is 0 " << std::endl; return EXIT_FAILURE; } // std::cout << " timedims " << timedims << " n-Labels " << myLabelSet1.size() << std::endl; typename ImageType::RegionType extractRegion = image1->GetLargestPossibleRegion(); extractRegion.SetSize(ImageDimension - 1, 0); unsigned int sub_vol = 0; extractRegion.SetIndex(ImageDimension - 1, sub_vol ); typename ExtractFilterType::Pointer extractFilter = ExtractFilterType::New(); extractFilter->SetInput( image1 ); // extractFilter->SetDirectionCollapseToIdentity(); extractFilter->SetDirectionCollapseToSubmatrix(); extractFilter->SetExtractionRegion( extractRegion ); extractFilter->Update(); typename OutImageType::Pointer outimage = extractFilter->GetOutput(); outimage->FillBuffer(0); typedef itk::ImageRegionIteratorWithIndex<OutImageType> SliceIt; typedef vnl_vector<Scalar> timeVectorType; timeVectorType mSample(timedims, 0); typedef itk::Array2D<double> MatrixType; std::vector<std::string> ColumnHeaders; if( myLabelSet1.size() > 1 ) { /** sort the labels */ std::sort(myLabelSet1.begin(), myLabelSet1.end() ); /** create a map between the roi and its matrix index */ std::map<unsigned int, unsigned int> vectorindexMap; for( unsigned int i = 0; i < myLabelSet1.size(); i++ ) { std::string colname = std::string("Label") + sccan_to_string<unsigned int>( myLabelSet1[i] ); ColumnHeaders.push_back( colname ); vectorindexMap[myLabelSet1[i]] = i; } typedef vnl_vector<unsigned int> countVectorType; countVectorType countVector( myLabelSet1.size(), 0 ); // std::cout << "Will map the image to its ROIs" << std::endl; MatrixType matrix(timedims, myLabelSet1.size() ); matrix.Fill(0); SliceIt vfIter2( outimage, outimage->GetLargestPossibleRegion() ); voxct = 0; for( vfIter2.GoToBegin();!vfIter2.IsAtEnd(); ++vfIter2 ) { OutIndexType ind = vfIter2.GetIndex(); auto label = static_cast<unsigned int>( mask->GetPixel( ind ) + 0.5 ); if( label > 0 ) { unsigned int vind = vectorindexMap[label]; IndexType tind; // first collect all samples for that location for( unsigned int i = 0; i < ImageDimension - 1; i++ ) { tind[i] = ind[i]; } for( unsigned int t = 0; t < timedims; t++ ) { tind[ImageDimension - 1] = t; Scalar pix = image1->GetPixel(tind); mSample(t) = pix; matrix[t][vind] += pix; countVector[vind] += 1; } } // check mask } for( unsigned int i = 0; i < myLabelSet1.size(); i++ ) { matrix.set_column( i, matrix.get_column( i ) / ( double ) countVector[i] ); } typedef itk::CSVNumericObjectFileWriter<double, 1, 1> WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName( outname ); writer->SetInput( &matrix ); writer->SetColumnHeaders( ColumnHeaders ); try { writer->Write(); } catch( itk::ExceptionObject& exp ) { // std::cerr << "Exception caught!" << std::endl; // std::cerr << exp << std::endl; return EXIT_FAILURE; } // std::cout << " done writing " << std::endl; return EXIT_SUCCESS; } MatrixType matrix(timedims, voxct); matrix.Fill(0); SliceIt vfIter2( outimage, outimage->GetLargestPossibleRegion() ); voxct = 0; for( vfIter2.GoToBegin();!vfIter2.IsAtEnd(); ++vfIter2 ) { OutIndexType ind = vfIter2.GetIndex(); if( mask->GetPixel(ind) >= 0.5 ) { IndexType tind; // first collect all samples for that location for( unsigned int i = 0; i < ImageDimension - 1; i++ ) { tind[i] = ind[i]; } for( unsigned int t = 0; t < timedims; t++ ) { tind[ImageDimension - 1] = t; Scalar pix = image1->GetPixel(tind); mSample(t) = pix; matrix[t][voxct] = pix; } std::string colname = std::string("V") + sccan_to_string<unsigned int>(voxct); ColumnHeaders.push_back( colname ); voxct++; } // check mask } typedef itk::CSVNumericObjectFileWriter<double, 1, 1> WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName( outname ); writer->SetInput( &matrix ); writer->SetColumnHeaders( ColumnHeaders ); try { writer->Write(); } catch( itk::ExceptionObject& exp ) { // std::cerr << "Exception caught!" << std::endl; // std::cerr << exp << std::endl; return EXIT_FAILURE; } // std::cout << " done writing " << std::endl; return EXIT_SUCCESS; } template <typename PixelType> int ConvertCSVVectorToImage( std::string csvfn, std::string maskfn, std::string outname, unsigned long rowOrCol ) { typedef PixelType Scalar; typedef vnl_matrix<PixelType> vMatrix; constexpr unsigned int ImageDimension = 3; typedef itk::Image<PixelType, ImageDimension> ImageType; /** read the images */ typename ImageType::Pointer mask = nullptr; ReadImage<ImageType>(mask, maskfn.c_str() ); typename ImageType::Pointer outimage = nullptr; ReadImage<ImageType>(outimage, maskfn.c_str() ); outimage->FillBuffer(0); typedef itk::ImageRegionIteratorWithIndex<ImageType> Iterator; unsigned long mct = 0; Iterator mIter( mask, mask->GetLargestPossibleRegion() ); for( mIter.GoToBegin();!mIter.IsAtEnd(); ++mIter ) { if( mIter.Get() >= 0.5 ) { mct++; } } /** we refer to the two view matrices as P and Q */ vMatrix p; p.fill(0); ReadMatrixFromCSVorImageSet<Scalar>(csvfn, p); if( mct!= p.rows() && mct!= p.cols() ) { // std::cout << " csv-vec rows " << p.rows() << " cols " << p.cols() << " mask non zero elements " << mct << std::endl; throw std::exception(); } if( mct == p.rows() ) { if( rowOrCol > p.cols() - 1 ) { // std::cout << " You are trying to select the " << rowOrCol << "th column but there are only " << p.cols() << " columns " << std::endl; throw std::exception(); } mct = 0; for( mIter.GoToBegin();!mIter.IsAtEnd(); ++mIter ) { if( mIter.Get() >= 0.5 ) { PixelType val = p(mct, rowOrCol); outimage->SetPixel(mIter.GetIndex(), val); mct++; } } } else if( mct == p.cols() ) // map the cols to the vector { if( rowOrCol > p.rows() - 1 ) { // std::cout << " You are trying to select the " << rowOrCol << "th row but there are only " << p.rows() << " rows " << std::endl; throw std::exception(); } mct = 0; for( mIter.GoToBegin();!mIter.IsAtEnd(); ++mIter ) { if( mIter.Get() >= 0.5 ) { PixelType val = p(rowOrCol, mct); outimage->SetPixel(mIter.GetIndex(), val); mct++; } } } typedef itk::ImageFileWriter<ImageType> WriterType; typename WriterType::Pointer writer = WriterType::New(); writer->SetFileName( outname ); writer->SetInput( outimage ); writer->Update(); return EXIT_SUCCESS; } // p.d. template <unsigned int ImageDimension, typename PixelType> void ConvertImageVecListToProjection( std::string veclist, std::string imagelist, std::string outname, bool average ) { // typedef itk::Image<PixelType,ImageDimension> ImageType; typedef itk::Image<PixelType, ImageDimension> ImageType; typedef itk::ImageFileReader<ImageType> ReaderType; std::vector<std::string> image_fn_list; std::vector<std::string> vec_fn_list; // first, count the number of files constexpr unsigned int maxChar = 512; char lineBuffer[maxChar], lineBufferVec[maxChar]; char filenm[maxChar], filenmVec[maxChar]; unsigned int filecount = 0, filecountVec = 0; { std::ifstream inputStreamA( imagelist.c_str(), std::ios::in ); if(!inputStreamA.is_open() ) { // std::cout << "Can't open image list file: " << imagelist << std::endl; return; } while(!inputStreamA.eof() ) { inputStreamA.getline( lineBuffer, maxChar, '\n' ); if( sscanf( lineBuffer, "%s ", filenm)!= 1 ) { continue; } else { image_fn_list.emplace_back(filenm ); filecount++; } } inputStreamA.close(); } { std::ifstream inputStreamVec( veclist.c_str(), std::ios::in ); if(!inputStreamVec.is_open() ) { // std::cout << "Can't open Vec list file: " << veclist << std::endl; return; } while(!inputStreamVec.eof() ) { inputStreamVec.getline( lineBufferVec, maxChar, '\n' ); if( sscanf( lineBufferVec, "%s ", filenmVec)!= 1 ) { continue; } else { vec_fn_list.emplace_back(filenmVec ); filecountVec++; } } inputStreamVec.close(); } std::ofstream myfile; std::string fnmp = outname + std::string(".csv"); myfile.open(fnmp.c_str(), std::ios::out ); typedef itk::ImageRegionIteratorWithIndex<ImageType> Iterator; for(auto & j : image_fn_list) { for( unsigned int k = 0; k < vec_fn_list.size(); k++ ) { double proj = 0, dotSum = 0, dotCounter = 0, dotTotal = 0; typename ReaderType::Pointer reader1 = ReaderType::New(); reader1->SetFileName( j ); reader1->Update(); typename ReaderType::Pointer reader2 = ReaderType::New(); reader2->SetFileName( vec_fn_list[k] ); reader2->Update(); Iterator mIter( reader1->GetOutput(), reader1->GetOutput()->GetLargestPossibleRegion() ); Iterator mIter2( reader2->GetOutput(), reader2->GetOutput()->GetLargestPossibleRegion() ); for( mIter.GoToBegin(), mIter2.GoToBegin();!mIter.IsAtEnd() &&!mIter2.IsAtEnd(); ++mIter, ++mIter2 ) { proj = mIter.Get() * mIter2.Get(); dotSum += proj; if( mIter2.Get() > 0 ) { dotCounter += mIter2.Get(); dotTotal += mIter.Get() * mIter2.Get(); } } if( average && dotCounter > 0 ) { dotSum = dotTotal / dotCounter; } if( k == vec_fn_list.size() - 1 ) { myfile << dotSum; } else { myfile << dotSum << ", "; } } myfile << std::endl; } myfile.close(); } template <unsigned int ImageDimension, typename PixelType> int SVD_One_View( itk::ants::CommandLineParser *sccanparser, unsigned int permct, unsigned int n_evec, unsigned int robustify, unsigned int p_cluster_thresh, unsigned int iterct, unsigned int svd_option, PixelType usel1, PixelType row_sparseness, PixelType smoother, unsigned int covering, bool verbosity, bool getSmall=false ) { // std::cout << "SVD_One_View" << std::endl; typedef itk::Image<PixelType, ImageDimension> ImageType; typedef double Scalar; typedef itk::ants::antsSCCANObject<ImageType, Scalar> SCCANType; typedef typename SCCANType::MatrixType vMatrix; typedef typename SCCANType::VectorType vVector; typename SCCANType::Pointer sccanobj = SCCANType::New(); sccanobj->SetGetSmall( static_cast<bool>(getSmall) ); vMatrix priorROIMat; if( svd_option == 1 ) { // std::cout << " basic-svd " << std::endl; } else { // std::cout << " sparse-svd " << std::endl; // note: 2 (in options) is for svd implementation } itk::ants::CommandLineParser::OptionType::Pointer initOpt = sccanparser->GetOption( "initialization" ); itk::ants::CommandLineParser::OptionType::Pointer maskOpt = sccanparser->GetOption( "mask" ); if(!initOpt || initOpt->GetNumberOfFunctions() == 0 || !maskOpt || maskOpt->GetNumberOfFunctions() == 0 ) { // std::cout << "Warning: no initialization set, will use data-driven approach." << std::endl; } else { std::string maskfn = maskOpt->GetFunction( 0 )->GetName(); std::string imagelistPrior = initOpt->GetFunction( 0 )->GetName(); // std::cout << "you will initialize with " << imagelistPrior << std::endl; std::string outname = "none"; priorROIMat = ConvertImageListToMatrix<ImageDimension, double>( imagelistPrior, maskfn, outname ); // std::cout << priorROIMat.rows() << " " << priorROIMat.cols() << std::endl; sccanobj->SetMatrixPriorROI( priorROIMat); } itk::ants::CommandLineParser::OptionType::Pointer init2Opt = sccanparser->GetOption( "initialization2" ); itk::ants::CommandLineParser::OptionType::Pointer mask2Opt = sccanparser->GetOption( "mask2" ); if(!init2Opt || init2Opt->GetNumberOfFunctions() == 0 || !mask2Opt || mask2Opt->GetNumberOfFunctions() == 0 ) { // std::cout << "Warning: no initialization set, will use data-driven approach." << std::endl; } else { std::string maskfn = mask2Opt->GetFunction( 0 )->GetName(); std::string imagelistPrior = init2Opt->GetFunction( 0 )->GetName(); // std::cout << "you will initialize Q with " << imagelistPrior << std::endl; std::string outname = "none"; priorROIMat = ConvertImageListToMatrix<ImageDimension, double>( imagelistPrior, maskfn, outname ); // std::cout << priorROIMat.rows() << " " << priorROIMat.cols() << std::endl; sccanobj->SetMatrixPriorROI2( priorROIMat ); } itk::ants::CommandLineParser::OptionType::Pointer outputOption = sccanparser->GetOption( "output" ); if(!outputOption || outputOption->GetNumberOfFunctions() == 0 ) { // std::cout << "Warning: no output option set." << std::endl; } itk::ants::CommandLineParser::OptionType::Pointer option = sccanparser->GetOption( "svd" ); PixelType gradstep = itk::Math::abs ( usel1 ); sccanobj->SetCovering( covering ); sccanobj->SetSilent( ! verbosity ); if( usel1 > 0 ) { sccanobj->SetUseL1( true ); } else { sccanobj->SetUseL1( false ); } sccanobj->SetGradStep( gradstep ); sccanobj->SetMaximumNumberOfIterations(iterct); sccanobj->SetRowSparseness( row_sparseness ); sccanobj->SetSmoother( smoother ); /** read the matrix images */ /** we refer to the two view matrices as P and Q */ std::string pmatname = std::string(option->GetFunction( 0 )->GetParameter( 0 ) ); vMatrix p; ReadMatrixFromCSVorImageSet<Scalar>(pmatname, p); typename ImageType::Pointer mask1 = nullptr; bool have_p_mask = false; have_p_mask = ReadImage<ImageType>(mask1, option->GetFunction( 0 )->GetParameter( 1 ).c_str() ); auto FracNonZero1 = sccanparser->Convert<double>( option->GetFunction( 0 )->GetParameter( 2 ) ); vMatrix priorScaleMat; if( svd_option == 7 ) { FracNonZero1 = sccanparser->Convert<double>( option->GetFunction( 0 )->GetParameter( 4 ) ); std::string imagelistPrior = option->GetFunction( 0 )->GetParameter( 2 ); // std::string priorScaleFile = option->GetFunction( 0 )->GetParameter( 3 ); std::string outname = "prior.mhd"; ConvertImageListToMatrix<ImageDimension, double>( imagelistPrior, option->GetFunction( 0 )->GetParameter( 1 ), outname ); ReadMatrixFromCSVorImageSet<Scalar>(outname, priorROIMat); // ReadMatrixFromCSVorImageSet<Scalar>(priorScaleFile, priorScaleMat); } // std::cout << " frac nonzero " << FracNonZero1 << std::endl; if( robustify > 0 ) { // std::cout << " make robust " << std::endl; p = sccanobj->RankifyMatrixColumns(p); } /** the penalties define the fraction of non-zero values for each view */ if( FracNonZero1 < 0 ) { FracNonZero1 = fabs(FracNonZero1); sccanobj->SetKeepPositiveP(false); } /** read the nuisance matrix image */ vMatrix r; if( option->GetFunction( 0 )->GetNumberOfParameters() > 3 ) { std::string nuis_img = option->GetFunction( 0 )->GetParameter( 3 ); if( nuis_img.length() > 3 && svd_option!= 7 ) { // std::cout << " nuis_img " << nuis_img << std::endl; ReadMatrixFromCSVorImageSet<Scalar>(nuis_img, r); if( CompareMatrixSizes<Scalar>( p, r ) == EXIT_FAILURE ) { return EXIT_FAILURE; } itk::ants::CommandLineParser::OptionType::Pointer partialccaOpt = sccanparser->GetOption( "partial-scca-option" ); std::string partialccaoption = std::string("PQ"); if( partialccaOpt ) { // enum SCCANFormulationType{ PQ, PminusRQ, PQminusR, PminusRQminusR, PQR }; if( partialccaOpt->GetNumberOfFunctions() > 0 ) { partialccaoption = sccanparser->Convert<std::string>( partialccaOpt->GetFunction()->GetName() ); } // std::cout << " Partial SCCA option " << partialccaoption << std::endl; if(!partialccaoption.compare( std::string( "PQ" ) ) ) { sccanobj->SetSCCANFormulation( SCCANType::PQ ); } else if(!partialccaoption.compare( std::string( "PminusRQ" ) ) ) { sccanobj->SetSCCANFormulation( SCCANType::PminusRQ ); } else if(!partialccaoption.compare( std::string( "PQminusR" ) ) ) { sccanobj->SetSCCANFormulation( SCCANType::PQminusR ); } else if(!partialccaoption.compare( std::string( "PminusRQminusR" ) ) ) { sccanobj->SetSCCANFormulation( SCCANType::PminusRQminusR ); } } } } else { // std::cout << " No nuisance parameters." << std::endl; } sccanobj->SetFractionNonZeroP(FracNonZero1); sccanobj->SetMinClusterSizeP( p_cluster_thresh ); if( robustify > 0 ) { // std::cout << " make robust " << std::endl; p = sccanobj->RankifyMatrixColumns(p); } sccanobj->SetMatrixP( p ); sccanobj->SetMatrixR( r ); sccanobj->SetMaskImageP( mask1 ); double truecorr = 0; if( svd_option == 1 ) { truecorr = sccanobj->SparseReconHome(n_evec); } else if( svd_option == 3 ) { truecorr = sccanobj->SparseArnoldiSVD(n_evec); // cgsparse } else if( svd_option == 4 ) { truecorr = sccanobj->NetworkDecomposition( n_evec ); } else if( svd_option == 5 ) { truecorr = sccanobj->LASSO( n_evec ); } else if( svd_option == 2 ) { truecorr = sccanobj->CGSPCA(n_evec); // cgspca } else if( svd_option == 6 ) { truecorr = sccanobj->SparseRecon(n_evec); // sparse (default) } else if( svd_option == 7 ) { // sccanobj->SetPriorScaleMat( priorScaleMat); sccanobj->SetMatrixPriorROI( priorROIMat); sccanobj->SetFlagForSort(); sccanobj->SetLambda(sccanparser->Convert<double>( option->GetFunction( 0 )->GetParameter( 3 ) ) ); truecorr = sccanobj->SparseReconPrior(n_evec, true); // Prior } else { truecorr = sccanobj->SparseArnoldiSVDGreedy(n_evec); // sparse (default) } vVector w_p = sccanobj->GetVariateP(0); // std::cout << " true-corr " << sccanobj->GetCanonicalCorrelations() << std::endl; if( outputOption ) { std::string filename = outputOption->GetFunction( 0 )->GetName(); // std::cout << " write " << filename << std::endl; std::string::size_type pos = filename.rfind( "." ); std::string filepre = std::string( filename, 0, pos ); std::string extension = std::string( filename, pos, filename.length() - 1); if( extension == std::string(".gz") ) { pos = filepre.rfind( "." ); extension = std::string( filepre, pos, filepre.length() - 1 ) + extension; filepre = std::string( filepre, 0, pos ); } std::string post = std::string("View1vec"); WriteVariatesToSpatialImage<ImageType, Scalar>( filename, post, sccanobj->GetVariatesP(), mask1, sccanobj->GetMatrixP(), have_p_mask, sccanobj->GetMatrixU() ); // WriteSortedVariatesToSpatialImage<ImageType,Scalar>( filename, post, sccanobj->GetVariatesP(), mask1, // sccanobj->GetMatrixP(), have_p_mask,sccanobj->GetSortFinalLocArray(),priorROIMat ); /** write the eigevalues to the csv file */ std::string fnmp = filepre + std::string("_eigenvalues.csv"); std::vector<std::string> ColumnHeaders; std::string colname = std::string("Eigenvalue"); ColumnHeaders.push_back( colname ); typedef itk::CSVNumericObjectFileWriter<double, 1, 1> CWriterType; CWriterType::Pointer cwriter = CWriterType::New(); cwriter->SetFileName( fnmp.c_str() ); cwriter->SetColumnHeaders(ColumnHeaders); vnl_matrix<double> evals; evals.set_size(sccanobj->GetCanonicalCorrelations().size(), 1); for( unsigned int i = 0; i < sccanobj->GetCanonicalCorrelations().size(); i++ ) { double evil = sccanobj->GetCanonicalCorrelations() (i); evals(i, 0) = evil; } cwriter->SetInput( &evals ); cwriter->Write(); } // permutation test if( ( svd_option == 4 || svd_option == 5 ) && permct > 0 ) { // std::cout << "Begin" << permct << " permutations " << std::endl; unsigned long perm_exceed_ct = 0; for( unsigned long pct = 0; pct <= permct; pct++ ) { // 0. compute permutation for q ( switch around rows ) vMatrix p_perm = PermuteMatrix<Scalar>( sccanobj->GetOriginalMatrixP() ); vMatrix r_perm = PermuteMatrix<Scalar>( sccanobj->GetOriginalMatrixR() ); sccanobj->SetMatrixP( p_perm ); sccanobj->SetMatrixR( r_perm ); double permcorr = 1.e9; // if ( pct > 76 && pct < 79 ) if( svd_option == 4 ) { permcorr = sccanobj->NetworkDecomposition(n_evec); // cgsparse } if( svd_option == 5 ) { permcorr = sccanobj->LASSO( n_evec ); // cgsparse } if( permcorr < truecorr ) { perm_exceed_ct++; } // end solve cca permutation // std::cout << permcorr << " p-value " << (double)perm_exceed_ct // / (pct + 1) << " ct " << pct << " true " << truecorr << " vs " << permcorr << std::endl; } } return EXIT_SUCCESS; } template <unsigned int ImageDimension, typename PixelType> int SCCA_vnl( itk::ants::CommandLineParser *sccanparser, unsigned int permct, unsigned int n_evec, unsigned int newimp, unsigned int robustify, unsigned int p_cluster_thresh, unsigned int q_cluster_thresh, unsigned int iterct, PixelType usel1, PixelType uselong, PixelType row_sparseness, PixelType smoother, unsigned int covering, PixelType priorWeight = 0, unsigned int verbosity = 0 ) { itk::ants::CommandLineParser::OptionType::Pointer outputOption = sccanparser->GetOption( "output" ); bool writeoutput = true; if(!outputOption || outputOption->GetNumberOfFunctions() == 0 ) { // std::cout << "Warning: no output option set." << std::endl; writeoutput = false; } if( newimp > 0 ) { // std::cout << "New imp irrelevant " << std::endl; } itk::ants::CommandLineParser::OptionType::Pointer option = sccanparser->GetOption( "scca" ); typedef itk::Image<PixelType, ImageDimension> ImageType; typedef double Scalar; typedef itk::ants::antsSCCANObject<ImageType, Scalar> SCCANType; typedef typename SCCANType::MatrixType vMatrix; typedef typename SCCANType::VectorType vVector; typename SCCANType::Pointer sccanobj = SCCANType::New(); sccanobj->SetCovering( covering ); sccanobj->SetSilent( ! verbosity ); sccanobj->SetPriorWeight( priorWeight ); sccanobj->SetMaximumNumberOfIterations(iterct); if( uselong > 0 ) { sccanobj->SetUseLongitudinalFormulation( uselong ); } PixelType gradstep = itk::Math::abs ( usel1 ); if( usel1 > 0 ) { sccanobj->SetUseL1( true ); } else { sccanobj->SetUseL1( false ); } vMatrix priorROIMat; vMatrix priorROIMat2; itk::ants::CommandLineParser::OptionType::Pointer initOpt = sccanparser->GetOption( "initialization" ); itk::ants::CommandLineParser::OptionType::Pointer maskOpt = sccanparser->GetOption( "mask" ); if(!initOpt || initOpt->GetNumberOfFunctions() == 0 || !maskOpt || maskOpt->GetNumberOfFunctions() == 0 ) { } else { std::string maskfn = maskOpt->GetFunction( 0 )->GetName(); std::string imagelistPrior = initOpt->GetFunction( 0 )->GetName(); // std::cout << "you will initialize P with " << imagelistPrior << " and " << maskfn << std::endl; std::string outname = "none"; priorROIMat = ConvertImageListToMatrix<ImageDimension, double>( imagelistPrior, maskfn, outname ); // std::cout << priorROIMat.rows() << " " << priorROIMat.cols() << std::endl; sccanobj->SetMatrixPriorROI( priorROIMat); } itk::ants::CommandLineParser::OptionType::Pointer init2Opt = sccanparser->GetOption( "initialization2" ); itk::ants::CommandLineParser::OptionType::Pointer mask2Opt = sccanparser->GetOption( "mask2" ); if(!init2Opt || init2Opt->GetNumberOfFunctions() == 0 || !mask2Opt || mask2Opt->GetNumberOfFunctions() == 0 ) { // itkDebugStatement( std::cerr << "Warning: no Q initialization set, will use data-driven approach." << std::endl ); } else { std::string maskfn = mask2Opt->GetFunction( 0 )->GetName(); std::string imagelistPrior = init2Opt->GetFunction( 0 )->GetName(); // std::cout << "you will initialize Q with " << imagelistPrior << " and " << maskfn << std::endl; std::string outname = "none"; priorROIMat2 = ConvertImageListToMatrix<ImageDimension, double>( imagelistPrior, maskfn, outname ); // std::cout << priorROIMat2.rows() << " " << priorROIMat2.cols() << std::endl; sccanobj->SetMatrixPriorROI2( priorROIMat2 ); } sccanobj->SetGradStep( gradstep ); sccanobj->SetSmoother( smoother ); sccanobj->SetRowSparseness( row_sparseness ); Scalar pinvtoler = 1.e-6; /** read the matrix images */ /** we refer to the two view matrices as P and Q */ std::string pmatname = std::string(option->GetFunction( 0 )->GetParameter( 0 ) ); vMatrix p; // // std::cout <<" read-p "<< std::endl; ReadMatrixFromCSVorImageSet<Scalar>(pmatname, p); std::string qmatname = std::string(option->GetFunction( 0 )->GetParameter( 1 ) ); vMatrix q; // // std::cout <<" read-q "<< std::endl; ReadMatrixFromCSVorImageSet<Scalar>(qmatname, q); // // std::cout << q.get_row(0) << std::endl; // // std::cout << q.mean() << std::endl; if( CompareMatrixSizes<Scalar>( p, q ) == EXIT_FAILURE ) { return EXIT_FAILURE; } typename ImageType::Pointer mask1 = nullptr; std::string mask1fn = option->GetFunction( 0 )->GetParameter( 2 ); bool have_p_mask = false; if ( mask1fn.length() > 5 ) { have_p_mask = ReadImage<ImageType>(mask1, mask1fn.c_str() ); } typename ImageType::Pointer mask2 = nullptr; std::string mask2fn = option->GetFunction( 0 )->GetParameter( 3 ); bool have_q_mask = false; if ( mask2fn.length() > 5 ) { have_q_mask = ReadImage<ImageType>(mask2, mask2fn.c_str() ); } /** the penalties define the fraction of non-zero values for each view */ auto FracNonZero1 = sccanparser->Convert<double>( option->GetFunction( 0 )->GetParameter( 4 ) ); if( FracNonZero1 < 0 ) { FracNonZero1 = fabs(FracNonZero1); sccanobj->SetKeepPositiveP(false); // true if P sparsity > 0 } auto FracNonZero2 = sccanparser->Convert<double>( option->GetFunction( 0 )->GetParameter( 5 ) ); if( FracNonZero2 < 0 ) { FracNonZero2 = fabs(FracNonZero2); sccanobj->SetKeepPositiveQ(false); // true if Q sparsity > 0 } sccanobj->SetFractionNonZeroP(FracNonZero1); sccanobj->SetFractionNonZeroQ(FracNonZero2); sccanobj->SetMinClusterSizeP( p_cluster_thresh ); sccanobj->SetMinClusterSizeQ( q_cluster_thresh ); if( robustify > 0 ) { // std::cout << " make robust " << std::endl; p = sccanobj->RankifyMatrixColumns(p); q = sccanobj->RankifyMatrixColumns(q); } sccanobj->SetMatrixP( p ); sccanobj->SetMatrixQ( q ); sccanobj->SetMaskImageP( mask1 ); sccanobj->SetMaskImageQ( mask2 ); sccanobj->SparsePartialArnoldiCCA(n_evec ); vVector w_p = sccanobj->GetVariateP(0); vVector w_q = sccanobj->GetVariateQ(0); vVector sccancorrs = sccanobj->GetCanonicalCorrelations(); // std::cout << " true-corr " << sccancorrs << std::endl; std::string filename = outputOption->GetFunction( 0 )->GetName(); std::string::size_type pos = filename.rfind( "." ); std::string filepre = std::string( filename, 0, pos ); std::string extension = std::string( filename, pos, filename.length() - 1); if( extension == std::string(".gz") ) { pos = filepre.rfind( "." ); extension = std::string( filepre, pos, filepre.length() - 1 ) + extension; filepre = std::string( filepre, 0, pos ); } std::string post = std::string("View1vec"); if( writeoutput ) { WriteVariatesToSpatialImage<ImageType, Scalar>( filename, post, sccanobj->GetVariatesP(), mask1, sccanobj->GetMatrixP(), have_p_mask, sccanobj->GetMatrixU() ); post = std::string("View2vec"); WriteVariatesToSpatialImage<ImageType, Scalar>( filename, post, sccanobj->GetVariatesQ(), mask2, sccanobj->GetMatrixQ(), have_q_mask, sccanobj->GetMatrixU() ); } /** begin permutation 1. q_pvMatrix CqqInv=vnl_svd_inverse<Scalar>(Cqq); q=q*CqqInv; sermuted ; 2. scca ; 3. test corrs and weights significance */ if( permct > 0 ) { vnl_vector<unsigned long> perm_exceed_ct( sccancorrs.size(), 0 ); vVector w_p_signif_ct(w_p.size(), 0); vVector w_q_signif_ct(w_q.size(), 0); for( unsigned long pct = 0; pct <= permct; pct++ ) { // 0. compute permutation for q ( switch around rows ) sccanobj->SetFractionNonZeroP(FracNonZero1); sccanobj->SetFractionNonZeroQ(FracNonZero2); sccanobj->SetGradStep( gradstep ); sccanobj->SetMatrixP( p ); ReadMatrixFromCSVorImageSet<Scalar>(qmatname, q); vMatrix q_perm = PermuteMatrix<Scalar>( q ); sccanobj->SetMatrixQ( q_perm ); sccanobj->SparsePartialArnoldiCCA(n_evec ); vVector permcorrs = sccanobj->GetCanonicalCorrelations(); // std::cout << " perm-corr " << permcorrs << " ct " << pct << " p-values "; for( unsigned int kk = 0; kk < permcorrs.size(); kk++ ) { if( permcorrs[kk] > sccancorrs[kk] ) { perm_exceed_ct[kk]++; } // std::cout << ( double ) perm_exceed_ct[kk] / (pct + 1) << " "; } // std::cout << std::endl; vVector w_p_perm = sccanobj->GetVariateP(0); vVector w_q_perm = sccanobj->GetVariateQ(0); for( unsigned long j = 0; j < w_p.size(); j++ ) { if( w_p_perm(j) > w_p(j) ) { w_p_signif_ct(j) = w_p_signif_ct(j)++; } } for( unsigned long j = 0; j < w_q.size(); j++ ) { if( w_q_perm(j) > w_q(j) ) { w_q_signif_ct(j) = w_q_signif_ct(j)++; } } // end solve cca permutation if( pct == permct ) { // std::cout << "final_p_values" << ","; for( unsigned int kk = 0; kk < permcorrs.size(); kk++ ) { // std::cout << ( double ) perm_exceed_ct[kk] / (pct + 1) << ","; } // std::cout << "x" << std::endl; std::ofstream myfile; std::string fnmp = filepre + std::string("_summary.csv"); myfile.open(fnmp.c_str(), std::ios::out ); myfile << "TypeOfMeasure" << ","; for( unsigned int kk = 0; kk < permcorrs.size(); kk++ ) { std::string colname = std::string("Variate") + sccan_to_string<unsigned int>(kk); myfile << colname << ","; } myfile << "x" << std::endl; myfile << "final_p_values" << ","; for( unsigned int kk = 0; kk < permcorrs.size(); kk++ ) { myfile << ( double ) perm_exceed_ct[kk] / (pct + 1) << ","; } myfile << "x" << std::endl; myfile << "corrs" << ","; for( unsigned int kk = 0; kk < permcorrs.size(); kk++ ) { myfile << sccancorrs[kk] << ","; } myfile << "x" << std::endl; myfile.close(); } } unsigned long psigct = 0, qsigct = 0; for( unsigned long j = 0; j < w_p.size(); j++ ) { if( w_p(j) > pinvtoler ) { w_p_signif_ct(j) = 1.0 - (double)w_p_signif_ct(j) / (double)(permct); if( w_p_signif_ct(j) > 0.949 ) { psigct++; } } else { w_p_signif_ct(j) = 0; } } for( unsigned long j = 0; j < w_q.size(); j++ ) { if( w_q(j) > pinvtoler ) { w_q_signif_ct(j) = 1.0 - (double)w_q_signif_ct(j) / (double)(permct); if( w_q_signif_ct(j) > 0.949 ) { qsigct++; } } else { w_q_signif_ct(j) = 0; } } if( writeoutput ) { post = std::string("View1pval"); if( have_p_mask ) { WriteVectorToSpatialImage<ImageType, Scalar>( filename, post, w_p_signif_ct, mask1); } post = std::string("View2pval"); if( have_q_mask ) { WriteVectorToSpatialImage<ImageType, Scalar>( filename, post, w_q_signif_ct, mask2); } } } return EXIT_SUCCESS; } template <unsigned int ImageDimension, typename PixelType> int mSCCA_vnl( itk::ants::CommandLineParser *sccanparser, unsigned int permct, bool run_partial_scca = false, unsigned int n_e_vecs = 3, unsigned int newimp = 0, unsigned int robustify = 0, unsigned int p_cluster_thresh = 100, unsigned int q_cluster_thresh = 1, unsigned int iterct = 20 ) { // std::cout << " Entering MSCCA --- computing " << n_e_vecs << " canonical variates by default. " << std::endl; itk::ants::CommandLineParser::OptionType::Pointer outputOption = sccanparser->GetOption( "output" ); if(!outputOption || outputOption->GetNumberOfFunctions() == 0 ) { // std::cout << "Warning: no output option set." << std::endl; } // std::cout << " newimp " << newimp << std::endl; itk::ants::CommandLineParser::OptionType::Pointer option = sccanparser->GetOption( "scca" ); typedef itk::Image<PixelType, ImageDimension> ImageType; typedef double Scalar; typedef itk::ants::antsSCCANObject<ImageType, Scalar> SCCANType; typedef itk::Image<Scalar, 2> MatrixImageType; typename SCCANType::Pointer sccanobj = SCCANType::New(); sccanobj->SetMaximumNumberOfIterations(iterct); typedef typename SCCANType::MatrixType vMatrix; typedef typename SCCANType::VectorType vVector; /** we refer to the two view matrices as P and Q */ typedef itk::Image<PixelType, ImageDimension> ImageType; typedef double Scalar; typedef itk::Image<Scalar, 2> MatrixImageType; /** read the matrix images */ std::string pmatname = std::string(option->GetFunction( 0 )->GetParameter( 0 ) ); vMatrix pin; ReadMatrixFromCSVorImageSet<Scalar>(pmatname, pin); std::string qmatname = std::string(option->GetFunction( 0 )->GetParameter( 1 ) ); vMatrix qin; ReadMatrixFromCSVorImageSet<Scalar>(qmatname, qin); std::string rmatname = std::string(option->GetFunction( 0 )->GetParameter( 2 ) ); vMatrix rin; ReadMatrixFromCSVorImageSet<Scalar>(rmatname, rin); if( CompareMatrixSizes<Scalar>( pin, qin ) == EXIT_FAILURE ) { return EXIT_FAILURE; } if( CompareMatrixSizes<Scalar>( qin, rin ) == EXIT_FAILURE ) { return EXIT_FAILURE; } if( CompareMatrixSizes<Scalar>( pin, rin ) == EXIT_FAILURE ) { return EXIT_FAILURE; } typename ImageType::Pointer mask1 = nullptr; bool have_p_mask = ReadImage<ImageType>(mask1, option->GetFunction( 0 )->GetParameter( 3 ).c_str() ); typename ImageType::Pointer mask2 = nullptr; bool have_q_mask = ReadImage<ImageType>(mask2, option->GetFunction( 0 )->GetParameter( 4 ).c_str() ); typename ImageType::Pointer mask3 = nullptr; /** the penalties define the fraction of non-zero values for each view */ auto FracNonZero1 = sccanparser->Convert<double>( option->GetFunction( 0 )->GetParameter( 6 ) ); if( FracNonZero1 < 0 ) { FracNonZero1 = fabs(FracNonZero1); sccanobj->SetKeepPositiveP(false); } auto FracNonZero2 = sccanparser->Convert<double>( option->GetFunction( 0 )->GetParameter( 7 ) ); if( FracNonZero2 < 0 ) { FracNonZero2 = fabs(FracNonZero2); sccanobj->SetKeepPositiveQ(false); } auto FracNonZero3 = sccanparser->Convert<double>( option->GetFunction( 0 )->GetParameter( 8 ) ); if( FracNonZero3 < 0 ) { FracNonZero3 = fabs(FracNonZero3); sccanobj->SetKeepPositiveR(false); } sccanobj->SetFractionNonZeroP(FracNonZero1); sccanobj->SetFractionNonZeroQ(FracNonZero2); sccanobj->SetFractionNonZeroR(FracNonZero3); for( unsigned int leave_out = pin.rows(); leave_out <= pin.rows(); leave_out++ ) { // std::cout << " Leaving Out " << leave_out << std::endl; vVector p_leave_out; vVector q_leave_out; if( leave_out < pin.rows() ) { p_leave_out = pin.get_row(leave_out); q_leave_out = qin.get_row(leave_out); } vMatrix p = DeleteRow<MatrixImageType, Scalar>( pin, leave_out ); vMatrix q = DeleteRow<MatrixImageType, Scalar>( qin, leave_out ); vMatrix r = DeleteRow<MatrixImageType, Scalar>( rin, leave_out ); sccanobj->SetMinClusterSizeP( p_cluster_thresh ); sccanobj->SetMinClusterSizeQ( q_cluster_thresh ); if( robustify > 0 ) { // std::cout << " make robust " << std::endl; p = sccanobj->RankifyMatrixColumns(p); q = sccanobj->RankifyMatrixColumns(q); r = sccanobj->RankifyMatrixColumns(r); } double truecorr = 0; if( run_partial_scca ) { // std::cout << " begin partial PQ " << std::endl; typename SCCANType::Pointer sccanobjCovar = SCCANType::New(); sccanobjCovar->SetMaximumNumberOfIterations(iterct); sccanobjCovar->SetMatrixP( p ); sccanobjCovar->SetMatrixQ( q ); sccanobjCovar->SetMatrixR( r ); sccanobjCovar->SetMinClusterSizeP( p_cluster_thresh ); sccanobjCovar->SetMinClusterSizeQ( q_cluster_thresh ); itk::ants::CommandLineParser::OptionType::Pointer partialccaOpt = sccanparser->GetOption( "partial-scca-option" ); std::string partialccaoption = std::string("PQ"); if( partialccaOpt ) { // enum SCCANFormulationType{ PQ, PminusRQ, PQminusR, PminusRQminusR, PQR }; if( partialccaOpt->GetNumberOfFunctions() > 0 ) { partialccaoption = sccanparser->Convert<std::string>( partialccaOpt->GetFunction()->GetName() ); } // std::cout << " Partial SCCA option " << partialccaoption << std::endl; if(!partialccaoption.compare( std::string( "PQ" ) ) ) { sccanobjCovar->SetSCCANFormulation( SCCANType::PQ ); } else if(!partialccaoption.compare( std::string( "PminusRQ" ) ) ) { sccanobjCovar->SetSCCANFormulation( SCCANType::PminusRQ ); } else if(!partialccaoption.compare( std::string( "PQminusR" ) ) ) { sccanobjCovar->SetSCCANFormulation( SCCANType::PQminusR ); } else if(!partialccaoption.compare( std::string( "PminusRQminusR" ) ) ) { sccanobjCovar->SetSCCANFormulation( SCCANType::PminusRQminusR ); } } sccanobjCovar->SetFractionNonZeroP(FracNonZero1); sccanobjCovar->SetKeepPositiveP( sccanobj->GetKeepPositiveP() ); sccanobjCovar->SetFractionNonZeroQ(FracNonZero2); sccanobjCovar->SetKeepPositiveQ( sccanobj->GetKeepPositiveQ() ); sccanobjCovar->SetMaskImageP( mask1 ); sccanobjCovar->SetMaskImageQ( mask2 ); if( newimp == 1 ) { truecorr = sccanobjCovar->SparsePartialCCA(n_e_vecs); } else if( newimp == 0 ) { truecorr = sccanobjCovar->SparsePartialArnoldiCCA(n_e_vecs); } // truecorr=sccanobjCovar->RunSCCAN2multiple(n_e_vecs ); // std::cout << " partialed out corr "; for( unsigned int ff = 0; ff < sccanobjCovar->GetCanonicalCorrelations().size(); ff++ ) { // std::cout << " " << sccanobjCovar->GetCanonicalCorrelations()[ff]; } // std::cout << std::endl; if( outputOption ) { std::string filename = outputOption->GetFunction( 0 )->GetName(); std::string::size_type pos = filename.rfind( "." ); std::string filepre = std::string( filename, 0, pos ); std::string extension = std::string( filename, pos, filename.length() - 1); if( extension == std::string(".gz") ) { pos = filepre.rfind( "." ); extension = std::string( filepre, pos, filepre.length() - 1 ) + extension; filepre = std::string( filepre, 0, pos ); } std::string post = std::string("View1vec"); WriteVariatesToSpatialImage<ImageType, Scalar>( filename, post, sccanobjCovar->GetVariatesP(), mask1, sccanobjCovar->GetMatrixP( ), have_p_mask, sccanobj->GetMatrixU() ); post = std::string("View2vec"); WriteVariatesToSpatialImage<ImageType, Scalar>( filename, post, sccanobjCovar->GetVariatesQ(), mask2, sccanobjCovar->GetMatrixQ( ), have_q_mask, sccanobj->GetMatrixU() ); } /** begin permutation 1. q_pvMatrix CqqInv=vnl_svd_inverse<Scalar>(Cqq); q=q*CqqInv; sermuted ; 2. scca ; 3. test corrs and weights significance */ if( permct > 0 ) { unsigned long perm_exceed_ct = 0; vVector w_p_signif_ct(p.cols(), 0); vVector w_q_signif_ct(q.cols(), 0); for( unsigned long pct = 0; pct <= permct; pct++ ) { /** both the new object and the copy object should produce the same results - verified in 1 example!*/ // typename SCCANType::Pointer sccanobjPerm=sccanobjCovar; typename SCCANType::Pointer sccanobjPerm = SCCANType::New(); sccanobjPerm->SetMaximumNumberOfIterations(iterct); sccanobjPerm->SetMinClusterSizeP( p_cluster_thresh ); sccanobjPerm->SetMinClusterSizeQ( q_cluster_thresh ); sccanobjPerm->SetFractionNonZeroP(FracNonZero1); sccanobjPerm->SetKeepPositiveP( sccanobj->GetKeepPositiveP() ); sccanobjPerm->SetKeepPositiveQ( sccanobj->GetKeepPositiveQ() ); sccanobjPerm->SetFractionNonZeroQ(FracNonZero2); sccanobjPerm->SetMaskImageP( mask1 ); sccanobjPerm->SetMaskImageQ( mask2 ); // 0. compute permutation for q ( switch around rows ) vMatrix p_perm = PermuteMatrix<Scalar>( sccanobjCovar->GetMatrixP() ); vMatrix q_perm = PermuteMatrix<Scalar>( sccanobjCovar->GetMatrixQ() ); vMatrix r_perm = PermuteMatrix<Scalar>( r ); sccanobjPerm->SetMatrixP( p_perm ); sccanobjPerm->SetMatrixQ( q_perm ); sccanobjPerm->SetMatrixR( r_perm ); // double permcorr=sccanobjPerm->RunSCCAN2(); sccanobjPerm->SetSCCANFormulation( sccanobjCovar->GetSCCANFormulation() ); sccanobjPerm->SetAlreadyWhitened( false ); double permcorr = 0; if( newimp == 0 ) { permcorr = sccanobjPerm->SparsePartialArnoldiCCA(n_e_vecs); } else if( newimp == 1 ) { permcorr = sccanobjPerm->SparsePartialCCA(n_e_vecs); } // permcorr=sccanobjPerm->RunSCCAN2multiple(n_e_vecs);// // else permcorr= // std::cout << " partialed out corr "; for( unsigned int ff = 0; ff < sccanobjPerm->GetCanonicalCorrelations().size(); ff++ ) { // std::cout << " " << sccanobjPerm->GetCanonicalCorrelations()[ff]; } // std::cout << std::endl; if( permcorr > truecorr ) { perm_exceed_ct++; } /* vVector w_p_perm=sccanobjPerm->GetVariateP(0); vVector w_q_perm=sccanobjPerm->GetVariateQ(0); for (unsigned long j=0; j<p.cols(); j++) if ( w_p_perm(j) > sccanobjCovar->GetVariateP(0)(j)) { w_p_signif_ct(j)=w_p_signif_ct(j)++; } for (unsigned long j=0; j<q.cols(); j++) if ( w_q_perm(j) > sccanobjCovar->GetVariateQ(0)(j) ) { w_q_signif_ct(j)=w_q_signif_ct(j)++; } // end solve cca permutation */ // std::cout << permcorr << " p-value " << (double)perm_exceed_ct // / (pct + 1) << " ct " << pct << " true " << truecorr << std::endl; } unsigned long psigct = 0, qsigct = 0; Scalar pinvtoler = 1.e-6; for( unsigned long j = 0; j < sccanobjCovar->GetVariateP(0).size(); j++ ) { if( sccanobjCovar->GetVariateP(0) (j) > pinvtoler ) { w_p_signif_ct(j) = 1.0 - (double)w_p_signif_ct(j) / (double)(permct); if( w_p_signif_ct(j) > 0.949 ) { psigct++; } } else { w_p_signif_ct(j) = 0; } } for( unsigned long j = 0; j < sccanobjCovar->GetVariateQ(0).size(); j++ ) { if( sccanobjCovar->GetVariateQ(0) (j) > pinvtoler ) { w_q_signif_ct(j) = 1.0 - (double)w_q_signif_ct(j) / (double)(permct); if( w_q_signif_ct(j) > 0.949 ) { qsigct++; } } else { w_q_signif_ct(j) = 0; } } // std::cout << " p-value " << (double)perm_exceed_ct / (permct) << " ct " << permct << std::endl; // std::cout << " p-vox " << (double)psigct / sccanobjCovar->GetVariateP(0).size() << " ct " << permct // << std::endl; // std::cout << " q-vox " << (double)qsigct / sccanobjCovar->GetVariateP(0).size() << " ct " << permct // << std::endl; // // std::cout << "Here in sccan after printing "<<pct<<std::endl; } return EXIT_SUCCESS; } // run_partial_scca // std::cout << " VNL mSCCA " << std::endl; sccanobj->SetMatrixP( p ); sccanobj->SetMatrixQ( q ); sccanobj->SetMatrixR( r ); sccanobj->SetMaskImageP( mask1 ); sccanobj->SetMaskImageQ( mask2 ); sccanobj->SetMaskImageR( mask3 ); truecorr = sccanobj->RunSCCAN3(); vVector w_p = sccanobj->GetPWeights(); vVector w_q = sccanobj->GetQWeights(); vVector w_r = sccanobj->GetRWeights(); // std::cout << " final correlation " << truecorr << std::endl; // // std::cout << " Projection-P " << p*w_p << std::endl; // // std::cout << " Projection-Q " << q*w_q << std::endl; if( leave_out < pin.rows() ) { // std::cout << " Projection-leave-P " << dot_product(p_leave_out, w_p) << std::endl; // std::cout << " Projection-leave-Q " << dot_product(q_leave_out, w_q) << std::endl; } // // std::cout << " r weights " << w_r << std::endl; for( unsigned long j = 0; j < w_r.size(); j++ ) { if( w_r(j) > 0 ) { // std::cout << " r-weight " << j << "," << w_r(j) << std::endl; } } if( outputOption ) { std::string filename = outputOption->GetFunction( 0 )->GetName(); // std::cout << " write " << filename << std::endl; std::string::size_type pos = filename.rfind( "." ); std::string filepre = std::string( filename, 0, pos ); std::string extension = std::string( filename, pos, filename.length() - 1); if( extension == std::string(".gz") ) { pos = filepre.rfind( "." ); extension = std::string( filepre, pos, filepre.length() - 1 ) + extension; filepre = std::string( filepre, 0, pos ); } std::string post = std::string("View1vec"); WriteVariatesToSpatialImage<ImageType, Scalar>( filename, post, sccanobj->GetVariatesP(), mask1, sccanobj->GetMatrixP(), have_p_mask, sccanobj->GetMatrixU() ); post = std::string("View2vec"); WriteVariatesToSpatialImage<ImageType, Scalar>( filename, post, sccanobj->GetVariatesQ(), mask2, sccanobj->GetMatrixQ(), have_q_mask, sccanobj->GetMatrixU() ); } /** begin permutation 1. q_pvMatrix CqqInv=vnl_svd_inverse<Scalar>(Cqq); q=q*CqqInv; sermuted ; 2. scca ; 3. test corrs and weights significance */ unsigned long perm_exceed_ct = 0; if( permct > 0 ) { vVector w_p_signif_ct(w_p.size(), 0); vVector w_q_signif_ct(w_q.size(), 0); vVector w_r_signif_ct(w_r.size(), 0); for( unsigned long pct = 0; pct <= permct; pct++ ) { // 0. compute permutation for q ( switch around rows ) // // std::cout << " dont permute q " << std::endl; vMatrix q_perm = PermuteMatrix<Scalar>( sccanobj->GetMatrixQ() ); vMatrix r_perm = PermuteMatrix<Scalar>( sccanobj->GetMatrixR() ); sccanobj->SetMatrixQ( q_perm ); sccanobj->SetMatrixR( r_perm ); double permcorr = sccanobj->RunSCCAN3(); if( permcorr > truecorr ) { perm_exceed_ct++; } vVector w_p_perm = sccanobj->GetPWeights(); vVector w_q_perm = sccanobj->GetQWeights(); vVector w_r_perm = sccanobj->GetRWeights(); for( unsigned long j = 0; j < w_r.size(); j++ ) { if( w_r_perm(j) > w_r(j) ) { w_r_signif_ct(j) = w_r_signif_ct(j)++; } } // // std::cout << " only testing correlation with biserial predictions " << std::endl; // end solve cca permutation // std::cout << permcorr << " p-value " << (double)perm_exceed_ct // / (pct + 1) << " ct " << pct << " true " << truecorr << std::endl; for( unsigned long j = 0; j < w_r.size(); j++ ) { if( w_r(j) > 0 ) { // std::cout << " r entry " << j << " signif " << (double)w_r_signif_ct(j) / (double)(pct + 1) << std::endl; } } } } // // std::cout << " p-value " << (double)perm_exceed_ct/(permct+1) << " ct " << permct << std::endl; } return EXIT_SUCCESS; } int sccan( itk::ants::CommandLineParser *sccanparser ) { // Define dimensionality constexpr unsigned int ImageDimension = 3; typedef double matPixelType; itk::ants::CommandLineParser::OptionType::Pointer outputOption = sccanparser->GetOption( "output" ); if(!outputOption || outputOption->GetNumberOfFunctions() == 0 ) { // std::cout << "Warning: no output option set." << std::endl; } unsigned int permct = 0; itk::ants::CommandLineParser::OptionType::Pointer permoption = sccanparser->GetOption( "n_permutations" ); if(!permoption || permoption->GetNumberOfFunctions() == 0 ) { } else { permct = sccanparser->Convert<unsigned int>( permoption->GetFunction()->GetName() ); } unsigned int iterct = 20; permoption = sccanparser->GetOption( "iterations" ); if( permoption && permoption->GetNumberOfFunctions() > 0 ) { iterct = sccanparser->Convert<unsigned int>( permoption->GetFunction()->GetName() ); } unsigned int evec_ct = 1; itk::ants::CommandLineParser::OptionType::Pointer evec_option = sccanparser->GetOption( "n_eigenvectors" ); if(!evec_option || evec_option->GetNumberOfFunctions() == 0 ) { } else { evec_ct = sccanparser->Convert<unsigned int>( evec_option->GetFunction()->GetName() ); } matPixelType uselong = 0; itk::ants::CommandLineParser::OptionType::Pointer long_option = sccanparser->GetOption( "uselong" ); if(!long_option || long_option->GetNumberOfFunctions() == 0 ) { } else { uselong = sccanparser->Convert<matPixelType>( long_option->GetFunction()->GetName() ); } unsigned int covering = 1; itk::ants::CommandLineParser::OptionType::Pointer covering_option = sccanparser->GetOption( "covering" ); if(!covering_option || covering_option->GetNumberOfFunctions() == 0 ) { } else { covering = sccanparser->Convert<unsigned int>( covering_option->GetFunction()->GetName() ); } matPixelType usel1 = 0.1; itk::ants::CommandLineParser::OptionType::Pointer l1_option = sccanparser->GetOption( "l1" ); if(!l1_option || l1_option->GetNumberOfFunctions() == 0 ) { } else { usel1 = sccanparser->Convert<matPixelType>( l1_option->GetFunction()->GetName() ); } unsigned int robustify = 0; itk::ants::CommandLineParser::OptionType::Pointer robust_option = sccanparser->GetOption( "robustify" ); if(!robust_option || robust_option->GetNumberOfFunctions() == 0 ) { } else { robustify = sccanparser->Convert<unsigned int>( robust_option->GetFunction()->GetName() ); } unsigned int verbosity = 0; itk::ants::CommandLineParser::OptionType::Pointer verbopt = sccanparser->GetOption( "verbose" ); if(!verbopt || verbopt->GetNumberOfFunctions() == 0 ) { } else { verbosity = sccanparser->Convert<unsigned int>( verbopt->GetFunction()->GetName() ); } itk::ants::CommandLineParser::OptionType::Pointer evecg_option = sccanparser->GetOption( "EvecGradPenalty" ); if(!evecg_option || evecg_option->GetNumberOfFunctions() == 0 ) { } else { sccanparser->Convert<matPixelType>( evecg_option->GetFunction()->GetName() ); } matPixelType smoother = 0; itk::ants::CommandLineParser::OptionType::Pointer smooth_option = sccanparser->GetOption( "smoother" ); if(!smooth_option || smooth_option->GetNumberOfFunctions() == 0 ) { } else { smoother = sccanparser->Convert<matPixelType>( smooth_option->GetFunction()->GetName() ); } matPixelType priorWeight = 0; itk::ants::CommandLineParser::OptionType::Pointer pwoption = sccanparser->GetOption( "prior-weight" ); if(!pwoption || pwoption->GetNumberOfFunctions() == 0 ) { } else { priorWeight = sccanparser->Convert<matPixelType>( pwoption->GetFunction()->GetName() ); } bool getSmall = false; itk::ants::CommandLineParser::OptionType::Pointer getsmallopt = sccanparser->GetOption( "get-small" ); if(!getsmallopt || getsmallopt->GetNumberOfFunctions() == 0 ) { } else { getSmall = sccanparser->Convert<matPixelType>( getsmallopt->GetFunction()->GetName() ); } matPixelType row_sparseness = 0; itk::ants::CommandLineParser::OptionType::Pointer row_option = sccanparser->GetOption( "row_sparseness" ); if(!row_option || row_option->GetNumberOfFunctions() == 0 ) { } else { row_sparseness = sccanparser->Convert<matPixelType>( row_option->GetFunction()->GetName() ); } unsigned int p_cluster_thresh = 1; itk::ants::CommandLineParser::OptionType::Pointer clust_option = sccanparser->GetOption( "PClusterThresh" ); if(!clust_option || clust_option->GetNumberOfFunctions() == 0 ) { } else { p_cluster_thresh = sccanparser->Convert<unsigned int>( clust_option->GetFunction()->GetName() ); } unsigned int q_cluster_thresh = 1; clust_option = sccanparser->GetOption( "QClusterThresh" ); if(!clust_option || clust_option->GetNumberOfFunctions() == 0 ) { } else { q_cluster_thresh = sccanparser->Convert<unsigned int>( clust_option->GetFunction()->GetName() ); } itk::ants::CommandLineParser::OptionType::Pointer positivity_option = sccanparser->GetOption( "PositivityConstraint" ); if(!positivity_option || positivity_option->GetNumberOfFunctions() == 0 ) { } else { sccanparser->Convert<unsigned int>( positivity_option->GetFunction()->GetName() ); } bool eigen_imp = false; itk::ants::CommandLineParser::OptionType::Pointer eigen_option = sccanparser->GetOption( "ridge_cca" ); if(!eigen_option || eigen_option->GetNumberOfFunctions() == 0 ) { } else { eigen_imp = sccanparser->Convert<bool>( eigen_option->GetFunction()->GetName() ); } // operations on individual matrices itk::ants::CommandLineParser::OptionType::Pointer matrixOption = sccanparser->GetOption( "imageset-to-matrix" ); if( matrixOption && matrixOption->GetNumberOfFunctions() > 0 ) { std::string outname = outputOption->GetFunction( 0 )->GetName(); std::string imagelist = matrixOption->GetFunction( 0 )->GetParameter( 0 ); std::string maskfn = matrixOption->GetFunction( 0 )->GetParameter( 1 ); ConvertImageListToMatrix<ImageDimension, double>( imagelist, maskfn, outname ); return EXIT_SUCCESS; } // operations on individual matrices itk::ants::CommandLineParser::OptionType::Pointer matrixOptionTimeSeries = sccanparser->GetOption( "timeseriesimage-to-matrix" ); if( matrixOptionTimeSeries && matrixOptionTimeSeries->GetNumberOfFunctions() > 0 ) { std::string outname = outputOption->GetFunction( 0 )->GetName(); std::string imagefn = matrixOptionTimeSeries->GetFunction( 0 )->GetParameter( 0 ); std::string maskfn = matrixOptionTimeSeries->GetFunction( 0 )->GetParameter( 1 ); double smoother_space = 0; if( matrixOptionTimeSeries->GetFunction( 0 )->GetNumberOfParameters() > 2 ) { smoother_space = sccanparser->Convert<double>( matrixOptionTimeSeries->GetFunction( 0 )->GetParameter( 2 ) ); } double smoother_time = 0; if( matrixOptionTimeSeries->GetFunction( 0 )->GetNumberOfParameters() > 3 ) { smoother_time = sccanparser->Convert<double>( matrixOptionTimeSeries->GetFunction( 0 )->GetParameter( 3 ) ); } ConvertTimeSeriesImageToMatrix<double>( imagefn, maskfn, outname, smoother_space, smoother_time ); // std::cout << " outname done " << outname << std::endl; return EXIT_SUCCESS; } // operations on individual matrices itk::ants::CommandLineParser::OptionType::Pointer matrixOptionV2I = sccanparser->GetOption( "vector-to-image" ); if( matrixOptionV2I && matrixOptionV2I->GetNumberOfFunctions() > 0 ) { std::string outname = outputOption->GetFunction( 0 )->GetName(); std::string csvfn = matrixOptionV2I->GetFunction( 0 )->GetParameter( 0 ); std::string maskfn = matrixOptionV2I->GetFunction( 0 )->GetParameter( 1 ); auto rowOrCol = sccanparser->Convert<unsigned long>( matrixOptionV2I->GetFunction( 0 )->GetParameter( 2 ) ); ConvertCSVVectorToImage<double>( csvfn, maskfn, outname, rowOrCol ); // std::cout << " V2I done " << outname << std::endl; return EXIT_SUCCESS; } // p.d. itk::ants::CommandLineParser::OptionType::Pointer matrixProjectionOption = sccanparser->GetOption( "imageset-to-projections" ); if( matrixProjectionOption && matrixProjectionOption->GetNumberOfFunctions() > 0 ) { std::string outFilename = outputOption->GetFunction( 0 )->GetName(); std::string vecList = matrixProjectionOption->GetFunction( 0 )->GetParameter( 0 ); std::string imageList = matrixProjectionOption->GetFunction( 0 )->GetParameter( 1 ); bool average = sccanparser->Convert<bool>( matrixProjectionOption->GetFunction( 0 )->GetParameter( 2 ) ); // // std::cout <<"here" << outFilename << " " << vecList << " " <<imageList << std::endl; if( average ) { // std::cout << " doing average instead of dot product " << std::endl; } ConvertImageVecListToProjection<ImageDimension, double>(vecList, imageList, outFilename, average ); return EXIT_SUCCESS; } itk::ants::CommandLineParser::OptionType::Pointer svdOption = sccanparser->GetOption( "svd" ); if( svdOption && svdOption->GetNumberOfFunctions() > 0 ) { std::string initializationStrategy = svdOption->GetFunction()->GetName(); if( !initializationStrategy.compare( std::string( "sparse" ) ) ) { SVD_One_View<ImageDimension, double>( sccanparser, permct, evec_ct, robustify, p_cluster_thresh, iterct, 1, usel1, row_sparseness, smoother, covering, verbosity ); return EXIT_SUCCESS; } if( !initializationStrategy.compare( std::string( "cgspca" ) ) ) { SVD_One_View<ImageDimension, double>( sccanparser, permct, evec_ct, robustify, p_cluster_thresh, iterct, 2, usel1, row_sparseness, smoother, covering, verbosity ); return EXIT_SUCCESS; } if( !initializationStrategy.compare( std::string( "network" ) ) ) { SVD_One_View<ImageDimension, double>( sccanparser, permct, evec_ct, robustify, p_cluster_thresh, iterct, 4, usel1, row_sparseness, smoother, covering, verbosity ); return EXIT_SUCCESS; } if( !initializationStrategy.compare( std::string( "lasso" ) ) ) { SVD_One_View<ImageDimension, double>( sccanparser, permct, evec_ct, robustify, p_cluster_thresh, iterct, 5, usel1, row_sparseness, smoother, covering, verbosity ); return EXIT_SUCCESS; } if( !initializationStrategy.compare( std::string( "recon" ) ) ) { SVD_One_View<ImageDimension, double>( sccanparser, permct, evec_ct, robustify, p_cluster_thresh, iterct, 6, usel1, row_sparseness, smoother, covering, verbosity, getSmall ); return EXIT_SUCCESS; } if( !initializationStrategy.compare( std::string( "recon4d" ) ) ) { SVD_One_View<ImageDimension+1, double>( sccanparser, permct, evec_ct, robustify, p_cluster_thresh, iterct, 6, usel1, row_sparseness, smoother, covering, verbosity ); return EXIT_SUCCESS; } if( !initializationStrategy.compare( std::string( "prior" ) ) ) { SVD_One_View<ImageDimension, double>( sccanparser, permct, evec_ct, robustify, p_cluster_thresh, iterct, 7, usel1, row_sparseness, smoother, covering, verbosity ); return EXIT_SUCCESS; } SVD_One_View<ImageDimension, double>( sccanparser, permct, evec_ct, robustify, p_cluster_thresh, iterct, 1, usel1, row_sparseness, smoother, covering, verbosity ); return EXIT_SUCCESS; } // std::cout << " scca-max-iterations " << iterct << " you will assess significance with " << permct << " permutations." << std::endl; // operations on pairs of matrices itk::ants::CommandLineParser::OptionType::Pointer matrixPairOption = sccanparser->GetOption( "scca" ); if( matrixPairOption && matrixPairOption->GetNumberOfFunctions() > 0 ) { if( matrixPairOption && matrixPairOption->GetFunction( 0 )->GetNumberOfParameters() < 2 ) { std::cerr << " Incorrect number of parameters." << std::endl; return EXIT_FAILURE; } std::string initializationStrategy = matrixPairOption->GetFunction()->GetName(); // call RCCA_eigen or RCCA_vnl unsigned int exitvalue = EXIT_FAILURE; if( !initializationStrategy.compare( std::string( "two-view" ) ) ) { exitvalue = SCCA_vnl<ImageDimension, double>( sccanparser, permct, evec_ct, eigen_imp, robustify, p_cluster_thresh, q_cluster_thresh, iterct, usel1, uselong, row_sparseness, smoother, covering, priorWeight, verbosity ); } else if( !initializationStrategy.compare( std::string("three-view") ) ) { // std::cout << " mscca 3-view " << std::endl; exitvalue = mSCCA_vnl<ImageDimension, double>( sccanparser, permct, false, evec_ct, eigen_imp, robustify, p_cluster_thresh, q_cluster_thresh, iterct); } else if(!initializationStrategy.compare( std::string("partial") ) ) { // std::cout << " pscca " << std::endl; exitvalue = mSCCA_vnl<ImageDimension, double>( sccanparser, permct, true, evec_ct, eigen_imp, robustify, p_cluster_thresh, q_cluster_thresh, iterct); } else if(!initializationStrategy.compare( std::string("dynsccan") ) ) { // std::cout << " tscca " << std::endl; exitvalue = SCCA_vnl<ImageDimension+1, double>( sccanparser, permct, evec_ct, eigen_imp, robustify, p_cluster_thresh, q_cluster_thresh, iterct, usel1, uselong, row_sparseness, smoother, covering, verbosity ); } else { std::cerr << " unrecognized option in matrixPairOperation " << std::endl; return exitvalue; } // std::cout << " exit value " << exitvalue << std::endl; return exitvalue; } // matrixPairOption else { std::cerr << " no option specified " << std::endl; } return EXIT_FAILURE; } // entry point for the library; parameter 'args' is equivalent to 'argv' in (argc,argv) of commandline parameters to //'main()' int sccan( std::vector<std::string> args, std::ostream * /*out_stream = nullptr */ ) { // put the arguments coming in as 'args' into standard (argc,argv) format; // 'args' doesn't have the command name as first, argument, so add it manually; // 'args' may have adjacent arguments concatenated into one argument, // which the sccanparser should handle args.insert( args.begin(), "sccan" ); std::remove( args.begin(), args.end(), std::string( "" ) ); int argc = args.size(); char* * argv = new char *[args.size() + 1]; for( unsigned int i = 0; i < args.size(); ++i ) { // allocate space for the string plus a null character argv[i] = new char[args[i].length() + 1]; std::strncpy( argv[i], args[i].c_str(), args[i].length() ); // place the null character in the end argv[i][args[i].length()] = '\0'; } argv[argc] = nullptr; // class to automatically cleanup argv upon destruction class Cleanup_argv { public: Cleanup_argv( char* * argv_, int argc_plus_one_ ) : argv( argv_ ), argc_plus_one( argc_plus_one_ ) { } ~Cleanup_argv() { for( unsigned int i = 0; i < argc_plus_one; ++i ) { delete[] argv[i]; } delete[] argv; } private: char* * argv; unsigned int argc_plus_one; }; Cleanup_argv cleanup_argv( argv, argc + 1 ); // antscout->set_stream( out_stream ); itk::ants::CommandLineParser::Pointer sccanparser = itk::ants::CommandLineParser::New(); sccanparser->SetCommand( argv[0] ); std::string commandDescription = std::string( "A tool for sparse statistical analysis on images : " ) + std::string( " scca, pscca (with options), mscca. Can also convert an imagelist/mask pair to a binary matrix image. " ); sccanparser->SetCommandDescription( commandDescription ); /** in this function, list all the operations you will perform */ typedef itk::ants::CommandLineParser::OptionType OptionType; { std::string description = std::string( "Print the help menu (short version)." ); OptionType::Pointer option = OptionType::New(); option->SetShortName( 'h' ); option->SetDescription( description ); sccanparser->AddOption( option ); } { std::string description = std::string( "Print the help menu (long version)." ); OptionType::Pointer option = OptionType::New(); option->SetLongName( "help" ); option->SetDescription( description ); sccanparser->AddOption( option ); } { std::string description = std::string( "Output dependent on which option is called." ); OptionType::Pointer option = OptionType::New(); option->SetLongName( "output" ); option->SetShortName( 'o' ); option->SetUsageOption( 0, "outputImage" ); option->SetDescription( description ); sccanparser->AddOption( option ); } { std::string description = std::string( "Number of permutations to use in scca." ); OptionType::Pointer option = OptionType::New(); option->SetLongName( "n_permutations" ); option->SetShortName( 'p' ); option->SetUsageOption( 0, "500" ); option->SetDescription( description ); sccanparser->AddOption( option ); } { std::string description = std::string( "Smoothing function for variates" ); OptionType::Pointer option = OptionType::New(); option->SetLongName( "smoother" ); option->SetShortName('s' ); option->SetUsageOption( 0, "0" ); option->SetDescription( description ); sccanparser->AddOption( option ); } { std::string description = std::string( "Row sparseness - if (+) then keep values (+) otherwise allow +/- values --- always L1" ); OptionType::Pointer option = OptionType::New(); option->SetLongName( "row_sparseness" ); option->SetShortName( 'z' ); option->SetUsageOption( 0, "0" ); option->SetDescription( description ); sccanparser->AddOption( option ); } { std::string description = std::string( "Max iterations for scca optimization (min 20)." ); OptionType::Pointer option = OptionType::New(); option->SetLongName( "iterations" ); option->SetShortName( 'i' ); option->SetUsageOption( 0, "20" ); option->SetDescription( description ); sccanparser->AddOption( option ); } { std::string description = std::string( "Number of eigenvectors to compute in scca/spca." ); OptionType::Pointer option = OptionType::New(); option->SetLongName( "n_eigenvectors" ); option->SetShortName( 'n' ); option->SetUsageOption( 0, "2" ); option->SetDescription( description ); sccanparser->AddOption( option ); } { std::string description = std::string( "rank-based scca" ); OptionType::Pointer option = OptionType::New(); option->SetLongName( "robustify" ); option->SetShortName( 'r' ); option->SetUsageOption( 0, "0" ); option->SetDescription( description ); sccanparser->AddOption( option ); } { std::string description = std::string( "try to make the decomposition cover the whole domain, if possible " ); OptionType::Pointer option = OptionType::New(); option->SetLongName( "covering" ); option->SetShortName( 'c' ); option->SetUsageOption( 0, "0" ); option->SetDescription( description ); sccanparser->AddOption( option ); } { std::string description = std::string( "use longitudinal formulation ( > 0 ) or not ( <= 0 ) " ); OptionType::Pointer option = OptionType::New(); option->SetLongName( "uselong" ); option->SetShortName( 'g' ); option->SetUsageOption( 0, "0" ); option->SetDescription( description ); sccanparser->AddOption( option ); } { std::string description = std::string( "use l1 ( > 0 ) or l0 ( < 0 ) penalty, also sets gradient step size e.g. -l 0.5 ( L1 ), -l -0.5 (L0) will set 0.5 grad descent step for either penalty" ); OptionType::Pointer option = OptionType::New(); option->SetLongName( "l1" ); option->SetShortName( 'l' ); option->SetUsageOption( 0, "0" ); option->SetDescription( description ); sccanparser->AddOption( option ); } { std::string description = std::string( "cluster threshold on view P" ); OptionType::Pointer option = OptionType::New(); option->SetLongName( "PClusterThresh" ); option->SetUsageOption( 0, "1" ); option->SetDescription( description ); sccanparser->AddOption( option ); } { std::string description = std::string( "cluster threshold on view Q" ); OptionType::Pointer option = OptionType::New(); option->SetLongName( "QClusterThresh" ); option->SetUsageOption( 0, "1" ); option->SetDescription( description ); sccanparser->AddOption( option ); } { std::string description = std::string( "Ridge cca." ); OptionType::Pointer option = OptionType::New(); option->SetLongName( "ridge_cca" ); option->SetShortName( 'e' ); option->SetUsageOption( 0, "0" ); option->SetDescription( description ); sccanparser->AddOption( option ); } { std::string description = std::string( "Initialization file list for Eigenanatomy - must also pass mask option" ); OptionType::Pointer option = OptionType::New(); option->SetLongName( "initialization" ); option->SetUsageOption( 0, "NA" ); option->SetDescription( description ); sccanparser->AddOption( option ); } { std::string description = std::string( "Initialization file list for SCCAN-Eigenanatomy - must also pass mask option" ); OptionType::Pointer option = OptionType::New(); option->SetLongName( "initialization2" ); option->SetUsageOption( 0, "NA" ); option->SetDescription( description ); sccanparser->AddOption( option ); } { std::string description = std::string( "Mask file for Eigenanatomy initialization" ); OptionType::Pointer option = OptionType::New(); option->SetLongName( "mask" ); option->SetUsageOption( 0, "NA" ); option->SetDescription( description ); sccanparser->AddOption( option ); } { std::string description = std::string( "Mask file for Eigenanatomy initialization 2" ); OptionType::Pointer option = OptionType::New(); option->SetLongName( "mask2" ); option->SetUsageOption( 0, "NA" ); option->SetDescription( description ); sccanparser->AddOption( option ); } { std::string description = std::string( "Choices for pscca: PQ, PminusRQ, PQminusR, PminusRQminusR " ); OptionType::Pointer option = OptionType::New(); option->SetLongName( "partial-scca-option" ); option->SetUsageOption( 0, "PminusRQ" ); option->SetDescription( description ); sccanparser->AddOption( option ); } { std::string description = std::string( "Scalar value weight on prior between 0 (prior is weak) and 1 (prior is strong). Only engaged if initialization is used." ); OptionType::Pointer option = OptionType::New(); option->SetLongName( "prior-weight" ); option->SetUsageOption( 0, "0.0" ); option->SetDescription( description ); sccanparser->AddOption( option ); } { std::string description = std::string( "Find smallest eigenvectors" ); OptionType::Pointer option = OptionType::New(); option->SetLongName( "get-small" ); option->SetUsageOption( 0, "0.0" ); option->SetDescription( description ); sccanparser->AddOption( option ); } { std::string description = std::string( "set whether output is verbose" ); OptionType::Pointer option = OptionType::New(); option->SetLongName( "verbose" ); option->SetShortName( 'v' ); option->SetUsageOption( 0, "0" ); option->SetDescription( description ); sccanparser->AddOption( option ); } { std::string description = std::string( "takes a list of image files names (one per line) " ) + std::string( "and converts it to a 2D matrix / image in binary or csv format depending on the filetype used to define the output." ); OptionType::Pointer option = OptionType::New(); option->SetLongName( "imageset-to-matrix" ); option->SetUsageOption( 0, "[list.txt,mask.nii.gz]" ); option->SetDescription( description ); sccanparser->AddOption( option ); } { std::string description = std::string( "takes a timeseries (4D) image " ) + std::string( "and converts it to a 2D matrix csv format as output." ) + std::string( "If the mask has multiple labels ( more the one ) then the average time series in each label will be computed and put in the csv." ); OptionType::Pointer option = OptionType::New(); option->SetLongName( "timeseriesimage-to-matrix" ); option->SetUsageOption( 0, "[four_d_image.nii.gz,three_d_mask.nii.gz, optional-spatial-smoothing-param-in-spacing-units-default-zero, optional-temporal-smoothing-param-in-time-series-units-default-zero ]" ); option->SetDescription( description ); sccanparser->AddOption( option ); } { std::string description = std::string( "converts the 1st column vector in a csv file back to an image --- currently needs the csv file to have > 1 columns. if the number of entries in the column does not equal the number of entries in the mask but the number of rows does equal the number of entries in the mask, then it will convert the row vector to an image. " ); OptionType::Pointer option = OptionType::New(); option->SetLongName( "vector-to-image" ); option->SetUsageOption( 0, "[vector.csv,three_d_mask.nii.gz, which-row-or-col ]" ); option->SetDescription( description ); sccanparser->AddOption( option ); } // p.d. { std::string description = std::string( "takes a list of image and projection files names (one per line) " ) + std::string( "and writes them to a csv file --- basically computing X*Y (matrices)." ); OptionType::Pointer option = OptionType::New(); option->SetLongName( "imageset-to-projections" ); option->SetUsageOption( 0, "[list_projections.txt,list_images.txt, bool do-average-not-real-projection ]" ); option->SetDescription( description ); sccanparser->AddOption( option ); } { std::string description = std::string( "Matrix-based scca operations for 2 and 3 views." ) + std::string( "For all these options, the FracNonZero terms set the fraction of variables to use in the estimate. E.g. if one sets 0.5 then half of the variables will have non-zero values. If the FracNonZero is (+) then the weight vectors must be positive. If they are negative, weights can be (+) or (-). partial does partial scca for 2 views while partialing out the 3rd view. "); OptionType::Pointer option = OptionType::New(); option->SetLongName( "scca" ); option->SetUsageOption( 0, "two-view[matrix-view1.mhd,matrix-view2.mhd,mask1,mask2,FracNonZero1,FracNonZero2] "); option->SetUsageOption( 1, "three-view[matrix-view1.mhd,matrix-view2.mhd,matrix-view3.mhd,mask1,mask2,mask3,FracNonZero1,FracNonZero2,FracNonZero3]" ); option->SetUsageOption( 2, "partial[matrix-view1.mhd,matrix-view2.mhd,matrix-view3.mhd,mask1,mask2,mask3,FracNonZero1,FracNonZero2,FracNonZero3]" ); option->SetUsageOption( 3, "dynsccan[matrix-view1.mhd,matrix-view2.mhd,mask1,mask2,FracNonZero1,FracNonZero2] "); option->SetDescription( description ); sccanparser->AddOption( option ); } { std::string description = std::string( "a sparse svd implementation --- will report correlation of eigenvector with original data columns averaged over columns with non-zero weights." ); OptionType::Pointer option = OptionType::New(); option->SetLongName( "svd" ); option->SetUsageOption( 0, "sparse[matrix-view1.mhd,mask1,FracNonZero1,nuisance-matrix] --- will only use view1... unless nuisance matrix is specified." ); option->SetUsageOption( 1, "classic[matrix-view1.mhd,mask1,FracNonZero1,nuisance-matrix] --- will only use view1... unless nuisance matrix is specified." ); option->SetUsageOption( 2, "cgspca[matrix-view1.mhd,mask1,FracNonZero1,nuisance-matrix] --- will only use view1... unless nuisance matrix is specified, -i controls the number of sparse approximations per eigenvector, -n controls the number of eigenvectors. total output will then be i*n sparse eigenvectors." ); option->SetUsageOption( 3, "prior[ matrix.mha, mask.nii.gz, PriorList.txt, PriorScale.csv, PriorWeightIn0to1, sparseness ]... if sparseness is set to zero, we take sparseness from the priors." ); option->SetUsageOption( 4, "network[matrix-view1.mhd,mask1,FracNonZero1,guidance-matrix]" ); option->SetUsageOption( 5, "lasso[matrix-view1.mhd,mask1,Lambda,guidance-matrix]" ); option->SetUsageOption( 6, "recon[matrix-view1.mhd,mask1,FracNonZero1,nuisance-matrix]" ); option->SetUsageOption( 7, "recon4d[matrix-view1.mhd,mask1,FracNonZero1,nuisance-matrix]" ); option->SetDescription( description ); sccanparser->AddOption( option ); } if( sccanparser->Parse( argc, argv ) == EXIT_FAILURE ) { return EXIT_FAILURE; } // Print the entire help menu itk::ants::CommandLineParser::OptionType::Pointer shortHelpOption = sccanparser->GetOption( 'h' ); itk::ants::CommandLineParser::OptionType::Pointer longHelpOption = sccanparser->GetOption( "help" ); if( argc < 2 || ( shortHelpOption->GetFunction() && sccanparser->Convert<unsigned int>( shortHelpOption->GetFunction()->GetName() ) == 1 ) ) { sccanparser->PrintMenu( std::cout, 5, true ); if( argc < 2 ) { return EXIT_FAILURE; } return EXIT_SUCCESS; } if( longHelpOption->GetFunction() && sccanparser->Convert<unsigned int>( longHelpOption->GetFunction()->GetName() ) == 1 ) { sccanparser->PrintMenu( std::cout, 5, false ); return EXIT_SUCCESS; } // Print the long help menu for specific items if( longHelpOption && longHelpOption->GetNumberOfFunctions() > 0 && sccanparser->Convert<unsigned int>( longHelpOption->GetFunction()->GetName() )!= 0 ) { itk::ants::CommandLineParser::OptionListType options = sccanparser->GetOptions(); for( unsigned int n = 0; n < longHelpOption->GetNumberOfFunctions(); n++ ) { std::string value = longHelpOption->GetFunction( n )->GetName(); itk::ants::CommandLineParser::OptionListType::const_iterator it; for( it = options.begin(); it!= options.end(); ++it ) { const char *longName = ( ( *it )->GetLongName() ).c_str(); if( strstr( longName, value.c_str() ) == longName ) { sccanparser->PrintMenu( std::cout, 5, false ); } } } return EXIT_FAILURE; } // Call main routine return sccan( sccanparser ); } // now compute covariance matrices // covariance matrix --- Cov(X, Y) = E[XY] - E[X].E[Y] /* input matrix ta<-matrix(c(-1,1,2,2,-2,3,1,1,4,0,3,4),nrow=3,ncol=4) ta<-matrix(c(-1,1,2,-2,3,1,4,0,3),nrow=3,ncol=3) > ta [,1] [,2] [,3] [1,] -1 1 2 [2,] -2 3 1 [3,] 4 0 3 // cov(ta,ta) [,1] [,2] [,3] [1,] 10.333333 -4.166667 3.0 [2,] -4.166667 2.333333 -1.5 [3,] 3.000000 -1.500000 1.0 > cov(a[1,]-mean(a[1,]),a[1,]-mean(a[1,])) [1] 10.33333 v<-a[1,]-mean(a[1,]) > v*v [1] 1.777778 5.444444 13.444444 > sum(v*v) [1] 20.66667 > sum(v*v)/(2) <- sum( v*v ) / ( n - 1 ) = covariance of two vectors... [1] 10.33333 */ /** try q.colwise.sum() to compute mean... */ /** try q.rowwise.sum() to compute mean... eMatrix testM(3,3); testM(0,0)=-1;testM(1,0)=1; testM(2,0)=2; testM(0,1)=-2;testM(1,1)=3; testM(2,1)=1; testM(0,2)= 4;testM(1,2)=0; testM(2,2)=3; p=testM; pMatSize[0]=3; pMatSize[1]=3; */ /* //1.0/(double)q.columns(); //randgen.drand32(); for (unsigned int it=0; it<4; it++) { // // std::cout << " 2norm(v0) " << v_0.two_norm() << std::endl; vVector v_1=(q)*v_0; double vnorm=v_1.two_norm(); // std::cout << " von " << vnorm << std::endl; v_0=v_1/(vnorm); // std::cout << " vo " << v_0 << std::endl; // check if power method works.... vVector Xv=q*v_0; Scalar vdotXv = dot_product(v_0,Xv); // std::cout << " vdotXv " << vdotXv << std::endl; vVector Xv2=Xv-v_0*vdotXv; // this value should be small -- i.e. v_0 is an eigenvector of X // std::cout << " init eigenvector result " << Xv2.squared_magnitude() << std::endl;} */ // // std::cout << v_0 << std::endl; /* function [Up,Sp,Vp] = rank_one_svd_update( U, S, V, a, b, force_orth ) % function [Up,Sp,Vp] = rank_one_svd_update( U, S, V, a, b, force_orth ) % % Given the SVD of % % X = U*S*V' % % update it to be the SVD of % % X + ab' = Up*Sp*Vp' % % that is, implement a rank-one update to the SVD of X. % % Depending on a,b there may be considerable structure that could % be exploited, but which this code does not. % % The subspace rotations involved may not preserve orthogonality due % to numerical round-off errors. To compensate, you can set the % "force_orth" flag, which will force orthogonality via a QR plus % another SVD. In a long loop, you may want to force orthogonality % every so often. % % See <NAME>, "Fast low-rank modifications of the thin % singular value decomposition". % % <NAME> 8/17/2007 % current_rank = size( U, 2 ); % P is an orthogonal basis of the column-space % of (I-UU')a, which is the component of "a" that is % orthogonal to U. m = U' * a; p = a - U*m; Ra = sqrt(p'*p); P = (1/Ra)*p; % XXX this has problems if a is already in the column space of U! % I don't know what to do in that case. if ( Ra < 1e-13 ) fprintf('------> Whoa! No orthogonal component of m!\n'); end; % Q is an orthogonal basis of the column-space % of (I-VV')b. n = V' * b; q = b - V*n; Rb = sqrt(q'*q); Q = (1/Rb)*q; if ( Rb < 1e-13 ) fprintf('------> Whoa! No orthogonal component of n!\n'); end; % % Diagonalize K, maintaining rank % % XXX note that this diagonal-plus-rank-one, so we should be able % to take advantage of the structure! z = zeros( size(m) ); K = [ S z ; z' 0 ] + [ m; Ra ]*[ n; Rb ]'; [tUp,tSp,tVp] = svds( K, current_rank ); % % Now update our matrices! % Sp = tSp; Up = [ U P ] * tUp; Vp = [ V Q ] * tVp; % The above rotations may not preserve orthogonality, so we explicitly % deal with that via a QR plus another SVD. In a long loop, you may % want to force orthogonality every so often. if ( force_orth ) [UQ,UR] = qr( Up, 0 ); [VQ,VR] = qr( Vp, 0 ); [tUp,tSp,tVp] = svds( UR * Sp * VR', current_rank ); Up = UQ * tUp; Vp = VQ * tVp; Sp = tSp; end; return; */ // } // namespace antssccan } // namespace ants ======================= File: Examples/ConvertImage.cxx ======================= <filename>Examples/ConvertImage.cxx #include "antsUtilities.h" #include "ReadWriteData.h" #include "itkCastImageFilter.h" #include "itkNumericTraits.h" #include "itkRescaleIntensityImageFilter.h" #include "itkVectorIndexSelectionCastImageFilter.h" #include <string> namespace ants { template <typename TPixel, unsigned int ImageDimension> int ConvertImage( int argc, char *argv[] ) { typedef TPixel OutputPixelType; if( argc > 4 && std::stoi( argv[4] ) == 9 ) { typedef itk::Vector<OutputPixelType, ImageDimension> VectorType; typedef itk::Image<VectorType, ImageDimension> DisplacementFieldType; typedef itk::Image<OutputPixelType, ImageDimension> ComponentImageType; typename DisplacementFieldType::Pointer displacementField = DisplacementFieldType::New(); for( unsigned int d = 0; d < ImageDimension; d++ ) { std::string filename = std::string( argv[2] ); if( d == 0 ) { filename += std::string( "xvec.nii.gz" ); } else if( d == 1 ) { filename += std::string( "yvec.nii.gz" ); } else if( d == 2 ) { filename += std::string( "zvec.nii.gz" ); } typename ComponentImageType::Pointer inputImage; ReadImage<ComponentImageType>( inputImage, filename.c_str() ); if( d == 0 ) { displacementField->CopyInformation( inputImage ); displacementField->SetRegions( inputImage->GetRequestedRegion() ); displacementField->Allocate(); VectorType V; V.Fill( 0.0 ); displacementField->FillBuffer( V ); } itk::ImageRegionConstIterator<ComponentImageType> It( inputImage, inputImage->GetLargestPossibleRegion() ); itk::ImageRegionIterator<DisplacementFieldType> ItD( displacementField, displacementField->GetLargestPossibleRegion() ); for( It.GoToBegin(), ItD.GoToBegin();!It.IsAtEnd(); ++ItD, ++It ) { VectorType V = ItD.Get(); V[d] = It.Get(); ItD.Set( V ); } } WriteImage<DisplacementFieldType>( displacementField, argv[3] ); } else if( argc > 4 && std::stoi( argv[4] ) == 10 ) { typedef itk::Vector<OutputPixelType, ImageDimension> VectorType; typedef itk::Image<VectorType, ImageDimension> DisplacementFieldType; typedef itk::Image<OutputPixelType, ImageDimension> ComponentImageType; typename DisplacementFieldType::Pointer inputImage; ReadImage<DisplacementFieldType>( inputImage, argv[2] ); for( unsigned int d = 0; d < ImageDimension; d++ ) { typedef itk::VectorIndexSelectionCastImageFilter<DisplacementFieldType, ComponentImageType> SelectorType; typename SelectorType::Pointer selector = SelectorType::New(); selector->SetInput( inputImage ); selector->SetIndex( d ); selector->Update(); std::string filename = std::string( argv[3] ); if( d == 0 ) { filename += std::string( "xvec.nii.gz" ); } else if( d == 1 ) { filename += std::string( "yvec.nii.gz" ); } else if( d == 2 ) { filename += std::string( "zvec.nii.gz" ); } WriteImage<ComponentImageType>( selector->GetOutput(), filename.c_str() ); } } else if( argc > 4 && std::stoi( argv[4] ) == 11 ) { typedef itk::Vector<OutputPixelType, ImageDimension> VectorType; typedef itk::Image<VectorType, ImageDimension+1> VelocityFieldType; typedef itk::Image<OutputPixelType, ImageDimension+1> ComponentImageType; typedef itk::ImageFileReader<VelocityFieldType> ReaderType; typename ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName( argv[2] ); reader->Update(); typename VelocityFieldType::Pointer inputImage; ReadImage<VelocityFieldType>( inputImage, argv[2] ); for( unsigned int d = 0; d < ImageDimension; d++ ) { typedef itk::VectorIndexSelectionCastImageFilter<VelocityFieldType, ComponentImageType> SelectorType; typename SelectorType::Pointer selector = SelectorType::New(); selector->SetInput( reader->GetOutput() ); selector->SetIndex( d ); selector->Update(); std::string filename = std::string( argv[3] ); if( d == 0 ) { filename += std::string( "xvec.nii.gz" ); } else if( d == 1 ) { filename += std::string( "yvec.nii.gz" ); } else if( d == 2 ) { filename += std::string( "zvec.nii.gz" ); } WriteImage<ComponentImageType>( selector->GetOutput(), filename.c_str() ); } } else if( argc > 4 && std::stoi( argv[4] ) == 12 ) { typedef itk::Vector<OutputPixelType, ImageDimension> VectorType; typedef itk::Image<VectorType, ImageDimension> DisplacementFieldType; typename DisplacementFieldType::Pointer displacementField; ReadImage<DisplacementFieldType>( displacementField, argv[2] ); WriteImage<DisplacementFieldType>( displacementField, argv[3] ); } else if( argc == 4 || ( argc > 4 && std::stoi( argv[4] ) < 9 ) ) { typedef typename itk::NumericTraits<OutputPixelType>::RealType RealType; typedef itk::Image<RealType, ImageDimension> InputImageType; typedef itk::Image<OutputPixelType, ImageDimension> OutputImageType; typename InputImageType::Pointer inputImage; ReadImage<InputImageType>( inputImage, argv[2] ); std::vector<std::string> rescaleFileTypes; rescaleFileTypes.emplace_back(".png" ); rescaleFileTypes.emplace_back(".jpeg" ); rescaleFileTypes.emplace_back(".jpg" ); rescaleFileTypes.emplace_back(".tiff" ); rescaleFileTypes.emplace_back(".tif" ); rescaleFileTypes.emplace_back(".bmp" ); bool isRescaleType = false; for(auto & rescaleFileType : rescaleFileTypes) { if( strstr( argv[3], rescaleFileType.c_str() )!= nullptr ) { isRescaleType = true; break; } } if( isRescaleType ) { typedef itk::RescaleIntensityImageFilter<InputImageType, OutputImageType> FilterType; typename FilterType::Pointer filter = FilterType::New(); filter->SetInput( inputImage ); filter->SetOutputMinimum( itk::NumericTraits<OutputPixelType>::min() ); filter->SetOutputMaximum( itk::NumericTraits<OutputPixelType>::max() ); filter->Update(); WriteImage<OutputImageType>( filter->GetOutput(), argv[3] ); } else { typedef itk::CastImageFilter<InputImageType, OutputImageType> CasterType; typename CasterType::Pointer caster = CasterType::New(); caster->SetInput( inputImage ); caster->Update(); WriteImage<OutputImageType>( caster->GetOutput(), argv[3] ); } } return EXIT_SUCCESS; } int ConvertImage( std::vector<std::string> args, std::ostream* /*out_stream = nullptr */ ) { // put the arguments coming in as 'args' into standard (argc,argv) format; // 'args' doesn't have the command name as first, argument, so add it manually; // 'args' may have adjacent arguments concatenated into one argument, // which the parser should handle args.insert( args.begin(), "ConvertImage" ); int argc = args.size(); char* * argv = new char *[args.size() + 1]; for( unsigned int i = 0; i < args.size(); ++i ) { // allocate space for the string plus a null character argv[i] = new char[args[i].length() + 1]; std::strncpy( argv[i], args[i].c_str(), args[i].length() ); // place the null character in the end argv[i][args[i].length()] = '\0'; } argv[argc] = nullptr; // class to automatically cleanup argv upon destruction class Cleanup_argv { public: Cleanup_argv( char* * argv_, int argc_plus_one_ ) : argv( argv_ ), argc_plus_one( argc_plus_one_ ) { } ~Cleanup_argv() { for( unsigned int i = 0; i < argc_plus_one; ++i ) { delete[] argv[i]; } delete[] argv; } private: char* * argv; unsigned int argc_plus_one; }; Cleanup_argv cleanup_argv( argv, argc + 1 ); // antscout->set_stream( out_stream ); if( argc < 4 ) { std::cerr << "Usage: " << argv[0] << " imageDimension " << "inputImage outputImage <pixelType>" << std::endl; std::cerr << "pixelType: 0 -> float (default)" << std::endl << " 1 -> unsigned char" << std::endl << " 2 -> unsigned short" << std::endl << " 3 -> unsigned int" << std::endl << " 4 -> unsigned long" << std::endl << " 5 -> char" << std::endl << " 6 -> short" << std::endl << " 7 -> int" << std::endl << " 8 -> long" << std::endl << " 9 -> component images to a float vector image" << std::endl << " 10 -> vector image to component images" << std::endl << " 11 -> time-varying velocity field image to component images (ImageDimension is the dimensionality of the displacement vector)" << std::endl << " 12 -> float vector image" << std::endl; return EXIT_FAILURE; } switch( std::stoi( argv[1] ) ) { case 2: if( argc > 4 && std::stoi( argv[4] ) == 1 ) { ConvertImage<unsigned char, 2>( argc, argv ); } else if( argc > 4 && std::stoi( argv[4] ) == 2 ) { ConvertImage<unsigned short, 2>( argc, argv ); } else if( argc > 4 && std::stoi( argv[4] ) == 3 ) { ConvertImage<unsigned int, 2>( argc, argv ); } else if( argc > 4 && std::stoi( argv[4] ) == 4 ) { ConvertImage<unsigned long, 2>( argc, argv ); } else if( argc > 4 && std::stoi( argv[4] ) == 5 ) { ConvertImage<char, 2>( argc, argv ); } else if( argc > 4 && std::stoi( argv[4] ) == 6 ) { ConvertImage<short, 2>( argc, argv ); } else if( argc > 4 && std::stoi( argv[4] ) == 7 ) { ConvertImage<int, 2>( argc, argv ); } else if( argc > 4 && std::stoi( argv[4] ) == 8 ) { ConvertImage<long, 2>( argc, argv ); } else { ConvertImage<float, 2>( argc, argv ); } break; case 3: if( argc > 4 && std::stoi( argv[4] ) == 1 ) { ConvertImage<unsigned char, 3>( argc, argv ); } else if( argc > 4 && std::stoi( argv[4] ) == 2 ) { ConvertImage<unsigned short, 3>( argc, argv ); } else if( argc > 4 && std::stoi( argv[4] ) == 3 ) { ConvertImage<unsigned int, 3>( argc, argv ); } else if( argc > 4 && std::stoi( argv[4] ) == 4 ) { ConvertImage<unsigned long, 3>( argc, argv ); } else if( argc > 4 && std::stoi( argv[4] ) == 5 ) { ConvertImage<char, 3>( argc, argv ); } else if( argc > 4 && std::stoi( argv[4] ) == 6 ) { ConvertImage<short, 3>( argc, argv ); } else if( argc > 4 && std::stoi( argv[4] ) == 7 ) { ConvertImage<int, 3>( argc, argv ); } else if( argc > 4 && std::stoi( argv[4] ) == 8 ) { ConvertImage<long, 3>( argc, argv ); } else { ConvertImage<float, 3>( argc, argv ); } break; default: std::cerr << "Unsupported dimension" << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } } // namespace ants ======================= File: Temporary/deprecate_itkFEMElement3DC0LinearTriangular.cxx ======================= /*========================================================================= Program: Insight Segmentation & Registration Toolkit Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ // disable debug warnings in MS compiler #ifdef _MSC_VER #pragma warning(disable: 4786) #endif #include "itkFEMElement3DC0LinearTriangular.h" #include "itkMath.h" #include "vnl/algo/vnl_svd.h" #include "vnl/algo/vnl_qr.h" namespace itk { namespace fem { const Element3DC0LinearTriangular::Float Element3DC0LinearTriangular ::trigGaussRuleInfo[6][7][4] = { // order=0, never used { { 0.0 } }, // order=1 // <-------------------------- point ---------------------------> <-------weight-----> { { 0.33333333333333333, 0.33333333333333333, 0.33333333333333333, 1.00000000000000000 } }, // order=2 { { 0.66666666666666667, 0.16666666666666667, 0.16666666666666667, 0.33333333333333333 }, { 0.16666666666666667, 0.66666666666666667, 0.16666666666666667, 0.33333333333333333 }, { 0.16666666666666667, 0.16666666666666667, 0.66666666666666667, 0.33333333333333333 } }, // order=3, p=-3 in the book { { 0.00000000000000000, 0.50000000000000000, 0.50000000000000000, 0.33333333333333333 }, { 0.50000000000000000, 0.00000000000000000, 0.50000000000000000, 0.33333333333333333 }, { 0.50000000000000000, 0.50000000000000000, 0.00000000000000000, 0.33333333333333333 } }, // order=4, p=6 in the book { { 0.10810301816807023, 0.44594849091596489, 0.44594849091596489, 0.22338158967801147 }, { 0.44594849091596489, 0.10810301816807023, 0.44594849091596489, 0.22338158967801147 }, { 0.44594849091596489, 0.44594849091596489, 0.10810301816807023, 0.22338158967801147 }, { 0.81684757298045851, 0.09157621350977074, 0.09157621350977074, 0.10995174365532187 }, { 0.09157621350977074, 0.81684757298045851, 0.09157621350977074, 0.10995174365532187 }, { 0.09157621350977074, 0.09157621350977074, 0.81684757298045851, 0.10995174365532187 } }, // order=5, p=7 in the book { { 0.33333333333333333, 0.33333333333333333, 0.33333333333333333, 0.22500000000000000 }, { 0.79742698535308732, 0.10128650732345634, 0.10128650732345634, 0.12593918054482715 }, { 0.10128650732345634, 0.79742698535308732, 0.10128650732345634, 0.12593918054482715 }, { 0.10128650732345634, 0.10128650732345634, 0.79742698535308732, 0.12593918054482715 }, { 0.05971587178976982, 0.47014206410511509, 0.47014206410511509, 0.13239415278850618 }, { 0.47014206410511509, 0.05971587178976982, 0.47014206410511509, 0.13239415278850618 }, { 0.47014206410511509, 0.47014206410511509, 0.05971587178976982, 0.13239415278850618 } } }; const unsigned int Element3DC0LinearTriangular ::Nip[6] = { 0, 1, 3, 3, 6, 7 }; void Element3DC0LinearTriangular ::GetIntegrationPointAndWeight(unsigned int i, VectorType& pt, Float& w, unsigned int order) const { // FIXME: range checking // default integration order if( order == 0 || order > 5 ) { order = DefaultIntegrationOrder; } pt.set_size(3); /* * We provide implementation for 5 different integration rules * as defined in chapter 24 - Implementation of Iso-P Truangular * Elements, of http://titan.colorado.edu/courses.d/IFEM.d/. * * Note that the order parameter here does not correspond to the * actual order of integration, but rather the degree of polynomials * that are exactly integrated. In addition, there are two integration * rules for polynomials of 2nd degree. In order to allow using both of * them, we assign the index number 3 to the second one. Note that this * does not mean that the rule is capable of integrating the polynomials * of 3rd degree. It's just an index of a rule. */ pt.copy_in(trigGaussRuleInfo[order][i]); // We scale the weight by 0.5, to take into account // the factor that must be applied when integrating. w = 0.5 * trigGaussRuleInfo[order][i][3]; } unsigned int Element3DC0LinearTriangular ::GetNumberOfIntegrationPoints(unsigned int order) const { // FIXME: range checking // default integration order if( order == 0 ) { order = DefaultIntegrationOrder; } return Nip[order]; } Element3DC0LinearTriangular::VectorType Element3DC0LinearTriangular ::ShapeFunctions( const VectorType& pt ) const { // Linear triangular element has 3 shape functions VectorType shapeF(3); // Shape functions are equal to coordinates shapeF = pt; return shapeF; } void Element3DC0LinearTriangular ::ShapeFunctionDerivatives( const VectorType &, MatrixType& shapeD ) const { // Matrix of shape functions derivatives is an // identity matrix for linear triangular element. shapeD.set_size(3, 3); shapeD.fill(0.0); shapeD[0][0] = 1.0; shapeD[1][1] = 1.0; shapeD[2][2] = 1.0; } bool Element3DC0LinearTriangular ::GetLocalFromGlobalCoordinates( const VectorType& globalPt, VectorType& localPt) const { Float x, x1, x2, x3, y, y1, y2, y3, z, z1, z2, z3, A; localPt.set_size(3); x = globalPt[0]; y = globalPt[1]; z = globalPt[2]; x1 = this->m_node[0]->GetCoordinates()[0]; y1 = this->m_node[0]->GetCoordinates()[1]; x2 = this->m_node[1]->GetCoordinates()[0]; y2 = this->m_node[1]->GetCoordinates()[1]; x3 = this->m_node[2]->GetCoordinates()[0]; y3 = this->m_node[2]->GetCoordinates()[1]; z1 = this->m_node[0]->GetCoordinates()[2]; z2 = this->m_node[1]->GetCoordinates()[2]; z3 = this->m_node[2]->GetCoordinates()[2]; // FIXME! A = x1 * y2 - x2 * y1 + x3 * y1 - x1 * y3 + x2 * y3 - x3 * y2; // localPt[0]=((y2 - y3)*x + (x3 - x2)*y + x2*y3 - x3*y2)/A; // localPt[1]=((y3 - y1)*x + (x1 - x3)*y + x3*y1 - x1*y3)/A; // localPt[2]=((y1 - y2)*x + (x2 - x1)*y + x1*y2 - x2*y1)/A; if( localPt[0] < 0.0 || localPt[0] > 1.0 || localPt[1] < 0.0 || localPt[1] > 1.0 || localPt[2] < 0.0 || localPt[2] > 1.0 ) { return false; } else { return true; } } Element3DC0LinearTriangular::Float Element3DC0LinearTriangular ::JacobianDeterminant( const VectorType& pt, const MatrixType* pJ ) const { // use heron's formula int na = 0; int nb = 1; int nc = 2; VectorType A = this->GetNode(na)->GetCoordinates(); VectorType B = this->GetNode(nb)->GetCoordinates(); VectorType C = this->GetNode(nc)->GetCoordinates(); VectorType BA = B - A; VectorType CA = C - A; VectorType CB = C - B; float L1 = CB.magnitude(); float L2 = CA.magnitude(); float L3 = BA.magnitude(); float s = (L1 + L2 + L3) *.5; Float det = sqrt( s * (s - L1) * (s - L2) * (s - L3) ); /* // use the formula for tri pqr, area is mag( vec(pq) cross vec(pr) ) VectorType a=this->GetNode(2)->GetCoordinates()-this->GetNode(0)->GetCoordinates(); VectorType b=this->GetNode(1)->GetCoordinates()-this->GetNode(0)->GetCoordinates(); VectorType c; c.set_size(3); c[0] = a[1] * b[2] - a[2] * b[1]; c[1] = a[2] * b[0] - a[0] * b[2]; c[2] = a[0] * b[1] - a[1] * b[0]; Float det=0.5*c.magnitude(); */ // ::std::cout << " area " << det << std::endl; return det; } void Element3DC0LinearTriangular ::JacobianInverse( const VectorType& pt, MatrixType& invJ, const MatrixType* pJ ) const { MatrixType* pJlocal = 0; // If Jacobian was not provided, we // need to compute it here if( pJ == 0 ) { pJlocal = new MatrixType(); this->Jacobian( pt, *pJlocal ); pJ = pJlocal; } // invJ=vnl_svd_inverse<Float>(*pJ); invJ = vnl_qr<Float>(*pJ).inverse(); /* // Note that inverse of Jacobian is not quadratic matrix MatrixType invJ2; invJ2.set_size(3,3); invJ2.fill(0); Float idet=1.0/this->JacobianDeterminant( pt, pJ ); invJ2[0][0]=idet*((*pJ)[1][1]-(*pJ)[2][1]); invJ2[0][1]=idet*((*pJ)[2][1]-(*pJ)[0][1]); invJ2[0][2]=idet*((*pJ)[0][1]-(*pJ)[1][1]); invJ2[1][0]=idet*((*pJ)[2][0]-(*pJ)[1][0]); invJ2[1][1]=idet*((*pJ)[0][0]-(*pJ)[2][0]); invJ2[1][2]=idet*((*pJ)[1][0]-(*pJ)[0][0]); ::std::cout << " pJ " << std::endl; ::std::cout << (*pJ) << std::endl; ::std::cout << " invJ " << std::endl; ::std::cout << (invJ) << std::endl; ::std::cout << " invJ2 " << std::endl; ::std::cout << (invJ2) << std::endl;*/ delete pJlocal; } /* * Draw the element on device context pDC. */ #ifdef FEM_BUILD_VISUALIZATION void Element3DC0LinearTriangular ::Draw(CDC* pDC, Solution::ConstPointer sol) const { int x1 = m_node[0]->GetCoordinates()[0] * DC_Scale; int y1 = m_node[0]->GetCoordinates()[1] * DC_Scale; int x2 = m_node[1]->GetCoordinates()[0] * DC_Scale; int y2 = m_node[1]->GetCoordinates()[1] * DC_Scale; int x3 = m_node[2]->GetCoordinates()[0] * DC_Scale; int y3 = m_node[2]->GetCoordinates()[1] * DC_Scale; x1 += sol->GetSolutionValue(this->m_node[0]->GetDegreeOfFreedom(0) ) * DC_Scale; y1 += sol->GetSolutionValue(this->m_node[0]->GetDegreeOfFreedom(1) ) * DC_Scale; x2 += sol->GetSolutionValue(this->m_node[1]->GetDegreeOfFreedom(0) ) * DC_Scale; y2 += sol->GetSolutionValue(this->m_node[1]->GetDegreeOfFreedom(1) ) * DC_Scale; x3 += sol->GetSolutionValue(this->m_node[2]->GetDegreeOfFreedom(0) ) * DC_Scale; y3 += sol->GetSolutionValue(this->m_node[2]->GetDegreeOfFreedom(1) ) * DC_Scale; pDC->MoveTo(x1, y1); pDC->LineTo(x2, y2); pDC->LineTo(x3, y3); pDC->LineTo(x1, y1); } #endif } } // end namespace itk::fem ======================= File: Examples/antsAffineInitializer.cxx ======================= <gh_stars>0 /*========================================================================= Program: Advanced Normalization Tools Copyright (c) ConsortiumOfANTS. All rights reserved. See accompanying COPYING.txt or https://github.com/stnava/ANTs/blob/master/ANTSCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "antsUtilities.h" #include <algorithm> #include <vnl/vnl_inverse.h> #include "antsAllocImage.h" #include "itkImageMaskSpatialObject.h" #include "itkANTSNeighborhoodCorrelationImageToImageMetricv4.h" #include "itkArray.h" #include "itkGradientImageFilter.h" #include "itkBSplineControlPointImageFilter.h" #include "itkBayesianClassifierImageFilter.h" #include "itkBayesianClassifierInitializationImageFilter.h" #include "itkBilateralImageFilter.h" #include "itkCSVNumericObjectFileWriter.h" #include "itkCastImageFilter.h" #include "itkCompositeValleyFunction.h" #include "itkConjugateGradientLineSearchOptimizerv4.h" #include "itkConnectedComponentImageFilter.h" #include "itkConstNeighborhoodIterator.h" #include "itkCorrelationImageToImageMetricv4.h" #include "itkDiscreteGaussianImageFilter.h" #include "itkDistanceToCentroidMembershipFunction.h" #include "itkDanielssonDistanceMapImageFilter.h" #include "itkDemonsImageToImageMetricv4.h" #include "itkExpImageFilter.h" #include "itkExtractImageFilter.h" #include "itkGaussianImageSource.h" #include "itkGradientAnisotropicDiffusionImageFilter.h" #include "itkGradientMagnitudeRecursiveGaussianImageFilter.h" #include "itkHessianRecursiveGaussianImageFilter.h" #include "itkHistogram.h" #include "itkHistogramMatchingImageFilter.h" #include "itkImage.h" #include "itkImageClassifierBase.h" #include "itkImageDuplicator.h" #include "itkImageFileWriter.h" #include "itkImageGaussianModelEstimator.h" #include "itkImageKmeansModelEstimator.h" #include "itkImageMomentsCalculator.h" #include "itkImageRandomConstIteratorWithIndex.h" #include "itkImageRegionIterator.h" #include "itkImageRegionIteratorWithIndex.h" #include "itkMattesMutualInformationImageToImageMetricv4.h" #include "itkKdTree.h" #include "itkKdTreeBasedKmeansEstimator.h" #include "itkLabelContourImageFilter.h" #include "itkLabelStatisticsImageFilter.h" #include "itkLabeledPointSetFileReader.h" #include "itkLabeledPointSetFileWriter.h" #include "itkLaplacianRecursiveGaussianImageFilter.h" #include "itkListSample.h" #include "itkMRFImageFilter.h" #include "itkMRIBiasFieldCorrectionFilter.h" #include "itkMaskImageFilter.h" #include "itkMaximumImageFilter.h" #include "itkMedianImageFilter.h" #include "itkMultiplyImageFilter.h" #include "itkMultivariateLegendrePolynomial.h" #include "itkMultiStartOptimizerv4.h" #include "itkNeighborhood.h" #include "itkNeighborhoodAlgorithm.h" #include "itkNeighborhoodIterator.h" #include "itkNormalVariateGenerator.h" #include "itkOptimizerParameterScalesEstimator.h" #include "itkOtsuThresholdImageFilter.h" #include "itkRGBPixel.h" #include "itkRegistrationParameterScalesFromPhysicalShift.h" #include "itkRelabelComponentImageFilter.h" #include "itkRescaleIntensityImageFilter.h" #include "itkSampleToHistogramFilter.h" #include "itkScalarImageKmeansImageFilter.h" #include "itkShrinkImageFilter.h" #include "itkSimilarity3DTransform.h" #include "itkSimilarity2DTransform.h" #include "itkSize.h" #include "itkSphereSpatialFunction.h" #include "itkSTAPLEImageFilter.h" #include "itkSubtractImageFilter.h" #include "itkTDistribution.h" #include "itkTimeProbe.h" #include "itkTransformFileReader.h" #include "itkTransformFileWriter.h" #include "itkTranslationTransform.h" #include "itkVariableSizeMatrix.h" #include "itkVectorLinearInterpolateImageFunction.h" #include "itkWeightedCentroidKdTreeGenerator.h" #include "vnl/vnl_matrix_fixed.h" #include "itkTransformFactory.h" #include "itkSurfaceImageCurvature.h" #include "itkMultiScaleLaplacianBlobDetectorImageFilter.h" #include "itkEuler2DTransform.h" #include "itkEuler3DTransform.h" #include "itkCenteredAffineTransform.h" #include "itkCompositeTransform.h" #include <fstream> #include <iostream> #include <map> // Here I'm using a map but you could choose even other containers #include <sstream> #include <string> #include "ReadWriteData.h" #include "TensorFunctions.h" #include "antsMatrixUtilities.h" namespace ants { template <typename TComputeType, unsigned int ImageDimension> class SimilarityTransformTraits { // Don't worry about the fact that the default option is the // affine Transform, that one will not actually be instantiated. public: typedef itk::AffineTransform<TComputeType, ImageDimension> TransformType; }; template <> class SimilarityTransformTraits<double, 2> { public: typedef itk::Similarity2DTransform<double> TransformType; }; template <> class SimilarityTransformTraits<float, 2> { public: typedef itk::Similarity2DTransform<float> TransformType; }; template <> class SimilarityTransformTraits<double, 3> { public: typedef itk::Similarity3DTransform<double> TransformType; }; template <> class SimilarityTransformTraits<float, 3> { public: typedef itk::Similarity3DTransform<float> TransformType; }; template <unsigned int ImageDimension> int antsAffineInitializerImp(int argc, char *argv[]) { typedef double RealType; typedef float PixelType; /** Define All Parameters Here */ double pi = itk::Math::pi; // probably a vnl alternative RealType searchfactor = 10; // in degrees, passed by user unsigned int mibins = 32; // for mattes MI metric RealType degtorad = 0.0174532925; // to convert degrees to radians unsigned int localoptimizeriterations = 20; // for local search via conjgrad // piover4 is (+/-) for cross-section of the sphere to multi-start search in increments // of searchfactor ( converted from degrees to radians ). // the search is centered +/- from the principal axis alignment of the images. RealType piover4 = pi / 4; // works in preliminary practical examples in 3D, in 2D use pi. bool useprincaxis = false; typedef typename itk::ImageMaskSpatialObject<ImageDimension>::ImageType maskimagetype; std::string whichMetric=std::string("MI"); unsigned int localSearchIterations = 20; typedef itk::TransformFileWriter TransformWriterType; typedef itk::Vector<float, ImageDimension> VectorType; typedef itk::Image<PixelType, ImageDimension> ImageType; typedef typename itk::ImageMomentsCalculator<ImageType> ImageCalculatorType; typedef itk::AffineTransform<RealType, ImageDimension> AffineType; typedef typename ImageCalculatorType::MatrixType MatrixType; if( argc < 2 ) { return 0; } int argct = 2; std::string fn1 = std::string(argv[argct]); argct++; std::string fn2 = std::string(argv[argct]); argct++; std::string outname = std::string(argv[argct]); argct++; if( argc > argct ) { searchfactor = atof( argv[argct] ); argct++; } if( argc > argct ) { RealType temp = atof( argv[argct] ); argct++; if( temp > 1 ) { temp = 1; } if( temp < 0.01 ) { temp = 0.01; } piover4 = pi * temp; } if( argc > argct ) { useprincaxis = std::stoi( argv[argct] ); argct++; } if( argc > argct ) { localoptimizeriterations = std::stoi( argv[argct] ); argct++; } typename ImageType::Pointer image1 = nullptr; typename ImageType::Pointer image2 = nullptr; typename maskimagetype::Pointer mask = nullptr; ReadImage<ImageType>(image1, fn1.c_str() ); ReadImage<ImageType>(image2, fn2.c_str() ); std::string maskfn = ""; if( argc > argct ) { maskfn = std::string( argv[argct] ); argct++; ReadImage<maskimagetype>(mask, maskfn.c_str() ); } searchfactor *= degtorad; // convert degrees to radians VectorType ccg1; VectorType cpm1; MatrixType cpa1; VectorType ccg2; VectorType cpm2; MatrixType cpa2; typename ImageCalculatorType::Pointer calculator1 = ImageCalculatorType::New(); typename ImageCalculatorType::Pointer calculator2 = ImageCalculatorType::New(); calculator1->SetImage( image1 ); calculator2->SetImage( image2 ); typename ImageCalculatorType::VectorType fixed_center; fixed_center.Fill(0); typename ImageCalculatorType::VectorType moving_center; moving_center.Fill(0); try { calculator1->Compute(); fixed_center = calculator1->GetCenterOfGravity(); ccg1 = calculator1->GetCenterOfGravity(); cpm1 = calculator1->GetPrincipalMoments(); cpa1 = calculator1->GetPrincipalAxes(); try { calculator2->Compute(); moving_center = calculator2->GetCenterOfGravity(); ccg2 = calculator2->GetCenterOfGravity(); cpm2 = calculator2->GetPrincipalMoments(); cpa2 = calculator2->GetPrincipalAxes(); } catch(... ) { std::cerr << " zero image2 error "; fixed_center.Fill(0); } } catch(... ) { std::cerr << " zero image1 error "; } RealType bestscale = calculator2->GetTotalMass() / calculator1->GetTotalMass(); RealType powlev = 1.0 / static_cast<RealType>(ImageDimension); bestscale = std::pow( bestscale, powlev ); bestscale=1; unsigned int eigind1 = 1; unsigned int eigind2 = 1; if( ImageDimension == 3 ) { eigind1 = 2; } vnl_vector<RealType> evec1_2ndary = cpa1.GetVnlMatrix().get_row( eigind2 ); vnl_vector<RealType> evec1_primary = cpa1.GetVnlMatrix().get_row( eigind1 ); vnl_vector<RealType> evec2_2ndary = cpa2.GetVnlMatrix().get_row( eigind2 ); vnl_vector<RealType> evec2_primary = cpa2.GetVnlMatrix().get_row( eigind1 ); /** Solve Wahba's problem --- http://en.wikipedia.org/wiki/Wahba%27s_problem */ vnl_matrix<RealType> B = outer_product( evec2_primary, evec1_primary ); if( ImageDimension == 3 ) { B = outer_product( evec2_2ndary, evec1_2ndary ) + outer_product( evec2_primary, evec1_primary ); } vnl_svd<RealType> wahba( B ); vnl_matrix<RealType> A_solution = wahba.V() * wahba.U().transpose(); A_solution = vnl_inverse( A_solution ); RealType det = vnl_determinant( A_solution ); if( det < 0 ) { std::cerr << " bad det " << det << " v " << vnl_determinant( wahba.V() ) << " u " << vnl_determinant( wahba.U() ) << std::endl; vnl_matrix<RealType> id( A_solution ); id.set_identity(); for( unsigned int i = 0; i < ImageDimension; i++ ) { if( A_solution( i, i ) < 0 ) { id( i, i ) = -1.0; } } A_solution = A_solution * id.transpose(); std::cerr << " bad det " << det << " v " << vnl_determinant( wahba.V() ) << " u " << vnl_determinant( wahba.U() ) << " new " << vnl_determinant( A_solution ) << std::endl; } typename AffineType::Pointer affine1 = AffineType::New(); // translation to center typename AffineType::OffsetType trans = affine1->GetOffset(); itk::Point<double, ImageDimension> trans2; for( unsigned int i = 0; i < ImageDimension; i++ ) { trans[i] = moving_center[i] - fixed_center[i]; trans2[i] = fixed_center[i] * ( 1 ); } affine1->SetIdentity(); affine1->SetOffset( trans ); if( useprincaxis ) { affine1->SetMatrix( A_solution ); } affine1->SetCenter( trans2 ); { typename TransformWriterType::Pointer transformWriter = TransformWriterType::New(); transformWriter->SetInput( affine1 ); transformWriter->SetFileName( outname.c_str() ); #if ITK_VERSION_MAJOR >= 5 transformWriter->SetUseCompression(true); #endif transformWriter->Update(); } if( ImageDimension > 3 ) { return EXIT_SUCCESS; } vnl_vector<RealType> evec_tert; if( ImageDimension == 3 ) { // try to rotate around tertiary and secondary axis evec_tert = vnl_cross_3d( evec1_primary, evec1_2ndary ); } if( ImageDimension == 2 ) { // try to rotate around tertiary and secondary axis evec_tert = evec1_2ndary; evec1_2ndary = evec1_primary; } itk::Vector<RealType, ImageDimension> axis2; itk::Vector<RealType, ImageDimension> axis1; for( unsigned int d = 0; d < ImageDimension; d++ ) { axis1[d] = evec_tert[d]; axis2[d] = evec1_2ndary[d]; } typename AffineType::Pointer affinesearch = AffineType::New(); typedef itk::MultiStartOptimizerv4 OptimizerType; typename OptimizerType::MetricValuesListType metricvalues; typename OptimizerType::Pointer mstartOptimizer = OptimizerType::New(); typedef itk::CorrelationImageToImageMetricv4 <ImageType, ImageType, ImageType> GCMetricType; typedef itk::MattesMutualInformationImageToImageMetricv4 <ImageType, ImageType, ImageType> MetricType; typename MetricType::ParametersType newparams( affine1->GetParameters() ); typename GCMetricType::Pointer gcmetric = GCMetricType::New(); gcmetric->SetFixedImage( image1 ); gcmetric->SetVirtualDomainFromImage( image1 ); gcmetric->SetMovingImage( image2 ); gcmetric->SetMovingTransform( affinesearch ); gcmetric->SetParameters( newparams ); typename MetricType::Pointer mimetric = MetricType::New(); mimetric->SetNumberOfHistogramBins( mibins ); mimetric->SetFixedImage( image1 ); mimetric->SetMovingImage( image2 ); mimetric->SetMovingTransform( affinesearch ); mimetric->SetParameters( newparams ); if( mask.IsNotNull() ) { typename itk::ImageMaskSpatialObject<ImageDimension>::Pointer so = itk::ImageMaskSpatialObject<ImageDimension>::New(); so->SetImage( const_cast<maskimagetype *>( mask.GetPointer() ) ); mimetric->SetFixedImageMask( so ); gcmetric->SetFixedImageMask( so ); } typedef itk::ConjugateGradientLineSearchOptimizerv4 LocalOptimizerType; typename LocalOptimizerType::Pointer localoptimizer = LocalOptimizerType::New(); RealType localoptimizerlearningrate = 0.1; localoptimizer->SetLearningRate( localoptimizerlearningrate ); localoptimizer->SetMaximumStepSizeInPhysicalUnits( localoptimizerlearningrate ); localoptimizer->SetNumberOfIterations( localSearchIterations ); localoptimizer->SetLowerLimit( 0 ); localoptimizer->SetUpperLimit( 2 ); localoptimizer->SetEpsilon( 0.1 ); localoptimizer->SetMaximumLineSearchIterations( 10 ); localoptimizer->SetDoEstimateLearningRateOnce( true ); localoptimizer->SetMinimumConvergenceValue( 1.e-6 ); localoptimizer->SetConvergenceWindowSize( 5 ); if( true ) { typedef typename MetricType::FixedSampledPointSetType PointSetType; typedef typename PointSetType::PointType PointType; typename PointSetType::Pointer pset(PointSetType::New()); unsigned int ind=0; unsigned int ct=0; itk::ImageRegionIteratorWithIndex<ImageType> It(image1, image1->GetLargestPossibleRegion() ); for( It.GoToBegin();!It.IsAtEnd(); ++It ) { // take every N^th point if ( ct % 10 == 0 ) { PointType pt; image1->TransformIndexToPhysicalPoint( It.GetIndex(), pt); pset->SetPoint(ind, pt); ind++; } ct++; } mimetric->SetFixedSampledPointSet( pset ); mimetric->SetUseSampledPointSet( true ); gcmetric->SetFixedSampledPointSet( pset ); gcmetric->SetUseSampledPointSet( true ); } if ( whichMetric.compare("MI") == 0 ) { mimetric->Initialize(); typedef itk::RegistrationParameterScalesFromPhysicalShift<MetricType> RegistrationParameterScalesFromPhysicalShiftType; typename RegistrationParameterScalesFromPhysicalShiftType::Pointer shiftScaleEstimator = RegistrationParameterScalesFromPhysicalShiftType::New(); shiftScaleEstimator->SetMetric( mimetric ); shiftScaleEstimator->SetTransformForward( true ); typename RegistrationParameterScalesFromPhysicalShiftType::ScalesType movingScales( affinesearch->GetNumberOfParameters() ); shiftScaleEstimator->EstimateScales( movingScales ); mstartOptimizer->SetScales( movingScales ); mstartOptimizer->SetMetric( mimetric ); localoptimizer->SetMetric( mimetric ); localoptimizer->SetScales( movingScales ); } if ( whichMetric.compare("MI")!= 0 ) { gcmetric->Initialize(); typedef itk::RegistrationParameterScalesFromPhysicalShift<GCMetricType> RegistrationParameterScalesFromPhysicalShiftType; typename RegistrationParameterScalesFromPhysicalShiftType::Pointer shiftScaleEstimator = RegistrationParameterScalesFromPhysicalShiftType::New(); shiftScaleEstimator->SetMetric( gcmetric ); shiftScaleEstimator->SetTransformForward( true ); typename RegistrationParameterScalesFromPhysicalShiftType::ScalesType movingScales( affinesearch->GetNumberOfParameters() ); shiftScaleEstimator->EstimateScales( movingScales ); mstartOptimizer->SetScales( movingScales ); mstartOptimizer->SetMetric( gcmetric ); localoptimizer->SetMetric( gcmetric ); localoptimizer->SetScales( movingScales ); } typename OptimizerType::ParametersListType parametersList = mstartOptimizer->GetParametersList(); for( double ang1 = ( piover4 * (-1) ); ang1 <= ( piover4 + searchfactor ); ang1 = ang1 + searchfactor ) { if( useprincaxis ) { affinesearch->SetMatrix( A_solution ); } if( ImageDimension == 3 ) { for( double ang2 = ( piover4 * (-1) ); ang2 <= ( piover4 + searchfactor ); ang2 = ang2 + searchfactor ) { affinesearch->SetIdentity(); affinesearch->SetCenter( trans2 ); affinesearch->SetOffset( trans ); if( useprincaxis ) { affinesearch->SetMatrix( A_solution ); } affinesearch->Rotate3D(axis1, ang1, 1); affinesearch->Rotate3D(axis2, ang2, 1); affinesearch->Scale( bestscale ); parametersList.push_back( affinesearch->GetParameters() ); } } if( ImageDimension == 2 ) { affinesearch->SetIdentity(); affinesearch->SetCenter( trans2 ); affinesearch->SetOffset( trans ); if( useprincaxis ) { affinesearch->SetMatrix( A_solution ); } affinesearch->Rotate2D( ang1, 1); affinesearch->Scale( bestscale ); parametersList.push_back( affinesearch->GetParameters() ); } } mstartOptimizer->SetParametersList( parametersList ); if( localSearchIterations > 0 ) { mstartOptimizer->SetLocalOptimizer( localoptimizer ); } mstartOptimizer->StartOptimization(); typename AffineType::Pointer bestaffine = AffineType::New(); bestaffine->SetCenter( trans2 ); bestaffine->SetParameters( mstartOptimizer->GetBestParameters() ); typename TransformWriterType::Pointer transformWriter = TransformWriterType::New(); transformWriter->SetInput( bestaffine ); transformWriter->SetFileName( outname.c_str() ); #if ITK_VERSION_MAJOR >= 5 transformWriter->SetUseCompression(true); #endif transformWriter->Update(); return EXIT_SUCCESS; } // entry point for the library; parameter 'args' is equivalent to 'argv' in (argc,argv) of commandline parameters to //'main()' int antsAffineInitializer( std::vector<std::string> args, std::ostream* /*out_stream = nullptr */ ) { // put the arguments coming in as 'args' into standard (argc,argv) format; // 'args' doesn't have the command name as first, argument, so add it manually; // 'args' may have adjacent arguments concatenated into one argument, // which the parser should handle args.insert( args.begin(), "antsAffineInitializer" ); int argc = args.size(); char* * argv = new char *[args.size() + 1]; for( unsigned int i = 0; i < args.size(); ++i ) { // allocate space for the string plus a null character argv[i] = new char[args[i].length() + 1]; std::strncpy( argv[i], args[i].c_str(), args[i].length() ); // place the null character in the end argv[i][args[i].length()] = '\0'; } argv[argc] = nullptr; // class to automatically cleanup argv upon destruction class Cleanup_argv { public: Cleanup_argv( char* * argv_, int argc_plus_one_ ) : argv( argv_ ), argc_plus_one( argc_plus_one_ ) { } ~Cleanup_argv() { for( unsigned int i = 0; i < argc_plus_one; ++i ) { delete[] argv[i]; } delete[] argv; } private: char* * argv; unsigned int argc_plus_one; }; Cleanup_argv cleanup_argv( argv, argc + 1 ); // antscout->set_stream( out_stream ); if( argc < 3 ) { std::cerr << "\nUsage: " << argv[0] << " ImageDimension <Image1.ext> <Image2.ext> TransformOutput.mat Optional-SearchFactor Optional-Radian-Fraction Optional-bool-UsePrincipalAxes Optional-uint-UseLocalSearch Optional-Image1Mask " << std::endl; std::cerr << " Optional-SearchFactor is in degrees --- e.g. 10 = search in 10 degree increments." << std::endl; std::cerr << " Radian-Fraction should be between 0 and 1 --- will search this arc +/- around principal axis." << std::endl; std::cerr << " Optional-bool-UsePrincipalAxes determines whether the rotation is searched around an initial principal axis alignment. Default = false. " << std::endl; std::cerr << " Optional-uint-UseLocalSearch determines if a local optimization is run at each search point for the set number of iterations. Default = 20." << std::endl; return 0; } switch( std::stoi(argv[1]) ) { case 2: { return antsAffineInitializerImp<2>(argc, argv); } case 3: { return antsAffineInitializerImp<3>(argc, argv); } case 4: return antsAffineInitializerImp<4>(argc, argv); } return antsAffineInitializerImp<2>(argc, argv); } } // namespace ants ======================= File: Examples/ConvertTransformFile.cxx ======================= /*========================================================================= Program: Advanced Normalization Tools Copyright (c) ConsortiumOfANTS. All rights reserved. See accompanying COPYING.txt or https://github.com/stnava/ANTs/blob/master/ANTSCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "antsUtilities.h" #include <algorithm> #include <iostream> #include <sys/stat.h> #include "itksys/SystemTools.hxx" #include <fstream> #include <cstdio> #include "itkTransformFactory.h" #include "itkAffineTransform.h" #include "itkTranslationTransform.h" #include "itkIdentityTransform.h" #include "itkantsReadWriteTransform.h" /* Utility to read in a transform file (presumed to be in binary format) and output * it in one of several different formats, defaulting to legacy text format for human reading. * Options are available to instead output only a transform matrix to a text file, * one row per dimension with space-delimited values. This option works only for * transforms of MatrixOffsetTransformBase or derived, Translation and Identity transforms. */ namespace ants { using namespace std; /* * */ bool FileExists(string strFilename) { struct stat stFileInfo; bool blnReturn; int intStat; // Attempt to get the file attributes intStat = stat(strFilename.c_str(), &stFileInfo); if( intStat == 0 ) { // We were able to get the file attributes // so the file obviously exists. blnReturn = true; } else { // We were not able to get the file attributes. // This may mean that we don't have permission to // access the folder which contains this file. If you // need to do that level of checking, lookup the // return values of stat which will give you // more details on why stat failed. blnReturn = false; } return blnReturn; } /* * */ template <typename TTransform> bool GetMatrix( const typename TTransform::Pointer & transform, typename TTransform::MatrixType & matrix, bool outputRAS ) { const unsigned int ImageDimension = TTransform::InputSpaceDimension; typedef typename TTransform::ScalarType ScalarType; matrix.Fill( itk::NumericTraits<typename TTransform::ScalarType>::ZeroValue() ); bool done = false; // Matrix-offset derived { typedef itk::MatrixOffsetTransformBase<ScalarType, ImageDimension, ImageDimension> CastTransformType; typename CastTransformType::Pointer castTransform = dynamic_cast<CastTransformType *>(transform.GetPointer() ); if( castTransform.IsNotNull() ) { matrix = castTransform->GetMatrix(); done = true; } } // Translation if(!done ) { typedef itk::TranslationTransform<ScalarType, ImageDimension> CastTransformType; typename CastTransformType::Pointer castTransform = dynamic_cast<CastTransformType *>(transform.GetPointer() ); if( castTransform.IsNotNull() ) { for( unsigned int i = 0; i < ImageDimension; i++ ) { matrix(i, i) = itk::NumericTraits<typename TTransform::ScalarType>::OneValue(); } done = true; } } // Identity if(!done ) { typedef itk::IdentityTransform<ScalarType, ImageDimension> CastTransformType; typename CastTransformType::Pointer castTransform = dynamic_cast<CastTransformType *>(transform.GetPointer() ); if( castTransform.IsNotNull() ) { for( unsigned int i = 0; i < ImageDimension; i++ ) { matrix(i, i) = itk::NumericTraits<typename TTransform::ScalarType>::OneValue(); } done = true; } } if(!done ) { // Unsupported transform type return false; } if( outputRAS ) { // Convert to RAS coordinate system. ITK uses LPS. // x and y dimensions are flipped. // This code is from c3d app. vnl_vector<ScalarType> v_lps_to_ras(ImageDimension, 1.0); v_lps_to_ras[0] = -1.0; if( ImageDimension > 1 ) { v_lps_to_ras[1] = -1.0; } vnl_diag_matrix<ScalarType> m_lps_to_ras(v_lps_to_ras); vnl_matrix<ScalarType> mold = matrix.GetVnlMatrix(); matrix.GetVnlMatrix().update(m_lps_to_ras * mold * m_lps_to_ras); } return true; } /* * */ template <typename TTransform, typename TMatrix> bool GetHomogeneousMatrix( const typename TTransform::Pointer & transform, TMatrix & hMatrix, bool outputRAS ) { const unsigned int ImageDimension = TTransform::InputSpaceDimension; typedef typename TTransform::ScalarType ScalarType; hMatrix.Fill( itk::NumericTraits<ScalarType>::ZeroValue() ); bool done = false; // Get the NxN matrix typename TTransform::MatrixType matrix; if(!GetMatrix<TTransform>( transform, matrix, outputRAS ) ) { return false; } for( unsigned int i = 0; i < ImageDimension; i++ ) { for( unsigned int j = 0; j < ImageDimension; j++ ) { hMatrix(i, j) = matrix(i, j); } } // Set the lower-right corner to 1 unsigned int corner = ImageDimension; hMatrix(corner, corner) = itk::NumericTraits<typename TTransform::ScalarType>::OneValue(); // // Get the offset // // Identity { typedef itk::IdentityTransform<ScalarType, ImageDimension> CastTransformType; typename CastTransformType::Pointer castTransform = dynamic_cast<CastTransformType *>(transform.GetPointer() ); if( castTransform.IsNotNull() ) { // Nothing more to do here. return true; } } typename TTransform::OutputVectorType offset; offset.Fill( itk::NumericTraits<typename TTransform::ScalarType>::ZeroValue() ); // Matrix-offset derived { typedef itk::MatrixOffsetTransformBase<ScalarType, ImageDimension, ImageDimension> CastTransformType; typename CastTransformType::Pointer castTransform = dynamic_cast<CastTransformType *>(transform.GetPointer() ); if( castTransform.IsNotNull() ) { offset = castTransform->GetOffset(); done = true; } } // Translation if(!done ) { typedef itk::TranslationTransform<ScalarType, ImageDimension> CastTransformType; typename CastTransformType::Pointer castTransform = dynamic_cast<CastTransformType *>(transform.GetPointer() ); if( castTransform.IsNotNull() ) { offset = castTransform->GetOffset(); done = true; } } if(!done ) { // Unsupported transform type return false; } if( outputRAS ) { // Convert to RAS coordinate system. ITK uses LPS. // x and y dimensions are flipped. // This code is from c3d app. offset[0] *= -1.0; if( ImageDimension > 1 ) { offset[1] *= -1.0; } } for( unsigned int i = 0; i < ImageDimension; i++ ) { hMatrix(i, ImageDimension) = offset[i]; } return true; } /* * */ template <unsigned int ImageDimension> int ConvertTransformFile(int argc, char* argv[]) { int inputFilenamePos = 2; int outFilenamePos = 3; bool outputMatrix = false; bool outputHomogeneousMatrix = false; bool outputAffine = false; bool outputRAS = false; // User options if( argc > 4 ) { for( int n = 4; n < argc; n++ ) { if( strcmp(argv[n], "--matrix") == 0 || strcmp(argv[n], "-m") == 0 ) { // User has requested outputting matrix information only. outputMatrix = true; } else if( strcmp(argv[n], "--homogeneousMatrix") == 0 || strcmp(argv[n], "--hm") == 0 ) { // User has requested outputting homogeneous matrix information only. outputHomogeneousMatrix = true; } else if( strcmp(argv[n], "--convertToAffineType") == 0 ) { outputAffine = true; } else if( strcmp(argv[n], "--RAS") == 0 || strcmp(argv[n], "--ras") == 0 ) { outputRAS = true; } else { std::cout << "Unrecognized option: " << argv[n] << std::endl; return EXIT_FAILURE; } } if( outputRAS &&!outputMatrix &&!outputHomogeneousMatrix ) { std::cout << " '--RAS' option must be used with either of'matrix' or 'homongeneousMatrix' options." << std::endl; return EXIT_FAILURE; } if( (outputMatrix && outputHomogeneousMatrix) || (outputMatrix && outputAffine) || (outputHomogeneousMatrix && outputAffine) ) { std::cout << "Only one primary output option allowed at once." << std::endl; return EXIT_FAILURE; } } // Check the filename std::string inputFilename = std::string( argv[inputFilenamePos] ); if(!FileExists(inputFilename) ) { std::cout << " file " << inputFilename << " does not exist. " << std::endl; return EXIT_FAILURE; } // Get the output filename std::string outFilename = std::string( argv[outFilenamePos] ); // Read the transform typedef itk::Transform<double, ImageDimension, ImageDimension> TransformType; typename TransformType::Pointer transform; typedef itk::MatrixOffsetTransformBase<double, ImageDimension, ImageDimension> baseTransformType; itk::TransformFactory<baseTransformType>::RegisterTransform(); transform = itk::ants::ReadTransform<double, ImageDimension>( inputFilename ); if( transform.IsNull() ) { std::cout << "Error while reading transform file. Did you specify the correct dimension?" << std::endl; return EXIT_FAILURE; } // // Outputs // if( outputMatrix || outputHomogeneousMatrix ) { std::ofstream outputStream; outputStream.open(outFilename.c_str(), std::ios::out); if( outputStream.fail() ) { outputStream.close(); std::cout << "Failed opening the output file " << outFilename << std::endl; return EXIT_FAILURE; } if( outputMatrix ) { typedef itk::Matrix<typename TransformType::ScalarType, ImageDimension, ImageDimension> MatrixType; MatrixType matrix; if( GetMatrix<TransformType>( transform, matrix, outputRAS ) ) { outputStream << matrix; } else {
1,532
hren.", "CanvasZoneAriaWebpartName": "\"{0}\"-Webpart", "ConfirmationDialogYes": "Ja", "ConfirmationDialogNo": "Nein", "DeleteZoneConfirmationDialogMessage": "Möchten Sie diesen Abschnitt mit allen seinen Inhalten löschen?", "DeleteConfirmationDialogTitle": "Löschen bestätigen", "DeleteConfirmationDialogMessage": "Möchten Sie dieses Webpart löschen?", "TextWebPartDisplayName": "Text", "ToolbarNavigationArrowKeys": "Verwenden Sie die Pfeiltasten, um innerhalb der Symbolleiste zu navigieren.", "ToolboxAriaLoadingAlert": "Die Toolbox lädt gerade Webparts.", "ToolboxAriaLoadingFinishedAlert": "Die Toolbox ist mit dem Laden von Webparts fertig.", "ToolboxErrorMessage": "Fehler beim Abrufen der Webparts. Möglicherweise sind nicht alle Webparts verfügbar.", "ToolboxHintTitle": "Neues Webpart hinzufügen", "ToolboxNavigationArrowKeys": "{0} Verwenden Sie zum Navigieren NACH-LINKS oder NACH-RECHTS. Verwenden Sie die EINGABETASTE, um das ausgewählte Webpart hinzuzufügen.", "CanvasItems": "{0} Elemente auf der Symbolleiste.|| {0} Element auf der Symbolleiste.|| {0} Elemente auf der Symbolleiste.", "CanvasItemsInterval": "0||1||2-", "ToolboxSectionHeader": "Abschnittslayout", "ToolboxOneColumnPart": "Eine Spalte", "ToolboxTwoColumnPart": "Zwei Spalten", "ToolboxThreeColumnPart": "Drei Spalten", "ToolboxOneThirdRightColumnPart": "Eine Drittelspalte rechts", "ToolboxOneThirdLeftColumnPart": "Eine Drittelspalte links", "ToolboxFullWidthColumnPart": "Spalte über volle Breite", "ToolboxVerticalColumnPart": "Vertikale Spalte", "ToolboxVerticalColumnToolTipText": "Eine vertikale Spalte kann nicht hinzugefügt werden, weil bereits eine vorhanden ist, oder weil auf der Seite eine Spalte mit voller Breite vorhanden ist.", "ToolboxFullWidthColumnTooltipText": "Eine Spalte mit voller Breite kann nicht hinzugefügt werden, weil auf der Seite eine vertikale Spalte vorhanden ist.", "SectionPropertyPaneTitle": "Abschnitt", "SectionPropertyPaneColumnGroupName": "Layoutoptionen", "ToolbarSelectZone": "Abschnitt auswählen", "DragIconFallbackRTEText": "Text", "DragZoneHandleTitle": "Drücken Sie die EINGABE- oder LEERTASTE, um in den Verschiebemodus zu wechseln.", "DragZoneMoveStarted": "Drücken Sie auf die NACH-OBEN-TASTE, um nach oben zu verschieben, und auf die NACH-UNTEN-TASTE, um nach unten zu verschieben. Drücken Sie die EINGABETASTE, um die Verschiebung zu bestätigen. Drücken Sie ESC, um das Verschieben abzubrechen. ", "DragZoneMoveComplete": "Webpart von {0} nach {1} verschoben. ", "DragZoneMoveCompleteZone": "Abschnitt von {0} nach {1} verschoben.", "DragZoneMoveCancelled": "Verschieben wurde abgebrochen.", "DragZoneMoveNotAllowedAriaLabel": "Weiteres Verschieben in diese Richtung ist nicht möglich, oder das Verschieben in diesen Abschnitt ist nicht zulässig.", "DragZoneMoveNotAllowed": "Verschieben nicht zulässig.", "DragZoneMoveInsideLevelControl": "Position {0}", "DragZoneMoveInsideLevelSection": "Spalte {0}, Position {1}", "DragZoneMoveInsideLevelZone": "Abschnitt {0}, Spalte {1}, Position {2}", "WebPartAriaLabel": "Webpart", "SectionContextualAriaLabel": "{0}, {1}-Abschnitt enthält {2}", "SectionAriaLabel": "Abschnitt", "WebPartsInSectionLabel": "{0}, {1}", "ToolboxHintSectionTitleOnlyLayouts": "Neuen Abschnitt hinzufügen", "ToolboxHintTitleWithLayout": "Neues Webpart in {0} hinzufügen", "ToolboxHintColumnOne": "Spalte 1", "ToolboxHintColumnTwo": "Spalte 2", "ToolboxHintColumnThree": "Spalte 3", "EmptySectionAriaLabel": "Kein Webpart", "SectionPositionAriaLabel": "Abschnitt {0} von {1}", "CloseButtonAriaLabel": "Schließen", "DeleteConfirmationLabel": "{0} wurde gelöscht.", "NarrowModeDialogTitle": "Verbreitern Sie Ihr Browserfenster", "NarrowModeDialogSubtitle": "Bearbeiten ist in einem schmalen Browserfenster nicht verfügbar. Verbreitern Sie das Fenster, um die Bearbeitung fortzusetzen.", "DialogDescription": "Dialogfeld \"{0}\", {1}", "SectionBackgroundPropertyColumnGroupName": "Abschnittshintergrund", "SectionBackgroundNeutralButtonLabel": "Neutral", "SectionBackgroundSoftButtonLabel": "Weich", "SectionBackgroundStrongButtonLabel": "Stark", "SectionBackgroundNoneButtonLabel": "Keine", "CanvasVerticalSectionZoneLabel": "Abschnitt mit vertikalem Spaltenlayout", "YammerHighlightsWebpartTitle": "Das Wichtigste", "ToolbarDuplicateTitle": "Teil duplizieren" }, "_n7GTqRbrtzGOgRYtCYt3Jw": { "FormattingBarMoreButtonTitle": "Mehr", "TextWebPartPlaceholder": "Hier Ihren Text einfügen." }, "_EJ1q3VoG+8ZXJZ4MxzV0eA": { "WebpartToolbarConfigButtonTitle": "Webpart bearbeiten", "WebpartToolbarMoveButtonTitle": "Webpart verschieben", "WebpartToolbarDeleteButtonTitle": "Webpart löschen", "ToolboxHintTitleWithLayout": "Neues Webpart in {0} hinzufügen", "ToolboxHintColumnOne": "Spalte 1", "ToolboxHintColumnTwo": "Spalte 2", "ToolboxHintColumnThree": "Spalte 3" }, "_kfkx9h4IuXbYoZ4SdLEjrQ": { "ZoneToolbarConfigButtonTitle": "Abschnitt bearbeiten", "ZoneToolbarMoveButtonTitle": "Abschnitt verschieben", "ZoneToolbarDeleteButtonTitle": "Abschnitt löschen", "ToolboxNavigationArrowKeys": "{0}. Verwenden Sie zum Navigieren NACH-LINKS oder NACH-RECHTS. Verwenden Sie die EINGABETASTE, um das ausgewählte Webpart hinzuzufügen." }, "_bKMsmDAqUqbOL6h9rxYuIw": { "FormattingBarClearFormattingButtonTitle": "Alle Formatierungen löschen", "FormattingBarNormalTextButtonTitle": "Standardtext", "FormattingBarHeading2ButtonTitle": "Überschrift 1", "FormattingBarHeading3ButtonTitle": "Überschrift 2", "FormattingBarHeading4ButtonTitle": "Überschrift 3", "FormattingBarQuoteButtonTitle": "Textzitat", "ToolbarNavigationArrowKeys": "Verwenden Sie die Pfeiltasten, um innerhalb der Symbolleiste zu navigieren.", "RTESettingsText": "Text- und Tabellenformatierung", "FontDropDownText": "Schriftschnitt", "ParagraphGroupText": "Absatz", "FontSizeDropDownLabel": "Schriftgrad", "TableGroup": "Tabelle", "InsertAndDeleteGroupLabel": "Einfügen und Löschen", "FontColorLabel": "Schriftfarbe", "StandardColorLabel": "Standardfarben", "DefaultColorLabel": "Automatisch", "RedDarkLabel": "Dunkelrot", "RedLabel": "Rot", "YellowLabel": "Gelber", "GreenLightLabel": "Hellgrün", "GreenLabel": "Grün", "GreenDarkLabel": "Dunkelgrün", "BlueLightLabel": "Hellblau", "BlueLabel": "Blau", "BlueDarkLabel": "Dunkelblau", "PurpleLabel": "Lila", "HightlightLabel": "Hervorhebungsfarbe", "HightlightColorsLabel": "Hervorhebungsfarben", "PinkLabel": "Rosa", "OrangeLabel": "Orange", "RemoveHighlightColor": "Keine Farbe", "HyperlinkGroupLabel": "Link", "TealLabel": "Blaugrün", "MagentaLabel": "Magenta", "AquaLabel": "Aquamarin", "MaroonLabel": "Kastanienbraun", "GoldLabel": "Gold", "GreyLabel": "Grau", "DarkGreyLabel": "Dunkelgrau", "BlackLabel": "Schwarz", "ThemeColorGroupLabel": "Designfarben", "ThemeDarkerLabel": "Design dunkler", "ThemeDarkLabel": "Design dunkel", "ThemeDarkAltLabel": "Design dunkel alternativ", "ThemePrimaryLabel": "Design primär", "ThemeSecondaryLabel": "Design sekundär", "NeutralDarkLabel": "Neutral dunkel", "NeutralPrimaryLabel": "Neutral primär", "NeutralPrimaryAltLabel": "Neutral primär alternativ", "NeutralSecondaryLabel": "Neutral sekundär", "NeutralTertiaryLabel": "Neutral tertiär", "TableStylesGroupLabel": "Tabellenformatvorlagen", "AlignTableGroupLabel": "Tabellenausrichtung", "FormattingBarPreButtonTitle": "Monospace" }, "_/GZrHjuQO4erDQbBRI2XSA": { "DialogTitle": "Link einfügen", "UrlTextFieldLabel": "Adresse", "UrlTextFieldAriaLabel": "Webadresse für Verknüpfung", "UrlTextFieldError": "Dieser Linktyp wird nicht unterstützt.", "TitleTextFieldLabel": "Anzuzeigender Text", "RecentPagesLabel": "Jüngste Seiten auf dieser Website", "SearchForPagesLabel": "Seiten auf dieser Website, die Ihrer Suche entsprechen", "RecentSpacesLabel": "Most recent spaces on this site", "SearchForSpacesLabel": "Spaces on this site that match your search", "NoResultLabel": "Keine Elemente entsprechen Ihrer Suche.", "TryAgainLabel": "Anderes Schlüsselwort probieren", "OpenLinkInNewTabLabel": "Link in einer neuen Registerkarte öffnen", "SaveButtonLabel": "Speichern", "CancelButtonLabel": "Abbrechen", "UnlinkButtonLabel": "Link entfernen", "TitleSuggestionsColumnName": "Titel", "EditorSuggestionsColumnName": "Geändert von", "ModifiedSuggestionsColumnName": "Geändert", "PageContentContainsSearchText": "\"{0}\" im Seiteninhalt gefunden.", "CurrentPage": "(aktuelle Seite)", "SearchTextFieldLabel": "Suchen", "SearchPagesTextFieldPlaceholder": "Schlüsselwörter eingeben, um auf dieser Website nach Seiten zu suchen.", "SearchSpacesTextFieldPlaceholder": "Enter keywords to search for spaces on this site", "DialogAriaDescription": "Einfügen eines Links zu einer Seite auf der aktuellen Website oder zu einer Seite auf einer anderen Website.", "SuggestionsListAriaLabel": "Wählen Sie eine Seite aus der Liste \"{0}\" aus. Drücken Sie die NACH-OBEN- und NACH-UNTEN-TASTEN, um auf diesen Seiten zu navigieren. Drücken Sie die LEERTASTE, um eine Seite auszuwählen. Wenn eine Seite ausgewählt ist, wird der Seitenlink im Linkeingabefeld verwendet und, wenn im Eingabefeld \"Anzuzeigender Text\" kein Text vorhanden ist, wird der Seitentitel verwendet.", "SaveButtonDisabledScreenReaderAlert": "Die Schaltfläche \"Speichern\" ist nicht verfügbar, weil eine ungültige Webadresse eingegeben wurde.", "SaveButtonEnabledScreenReaderAlert": "Die Schaltfläche \"Speichern\" ist verfügbar.", "PageIsSelectedScreenReaderAlert": "Die Seite \"{0}\" ist ausgewählt.", "IsSearching": "Wird gesucht...", "SearchResultsShowing": "Suchergebnisse werden angezeigt. Drücken Sie die TAB-TASTE, um zur Suchergebnisliste zu wechseln.", "RecentPagesShowing": "Eine Liste der zuletzt verwendeten Seiten wird angezeigt. Drücken Sie die TAB-TASTE, um zur Liste zuletzt verwendeter Seiten zu wechseln." }, "_4SOrKBlkyRLkXWcT6txoow": { "ToolboxSearchAccessibleLabelTemplate": "Hier eingeben, um nach einem Webpart zu suchen. {0}", "ToolboxSearchEscapeAccessibleLabel": "Drücken Sie ESC, um die vorhandene Suche zu löschen.", "ToolboxSearchLabel": "Suchen" }, "_6tOZemhV08aF1IgNDNeiwQ": { "ToolboxGroupNameFullWidth": "Sie können dieser Spalte mit voller Breite eins dieser Webparts hinzufügen." }, "_NS+5Kf9zpnH1/LStsp+Tfw": { "ToolboxCategoryTextMediaAndContent": "Text, Medien und Inhalt", "ToolboxCategoryDiscovery": "Entdecken", "ToolboxCategoryCommunicationAndCollaboration": "Kommunikation und Zusammenarbeit", "ToolboxCategoryPlanningAndProcess": "Planung und Prozess", "ToolboxCategoryBusinessIntelligence": "Business und Intelligence", "ToolboxCategorySiteTools": "Websitetools", "ToolboxCategoryConnectors": "Verbinder", "ToolboxCategoryOther": "Weitere", "ToolboxGroupNameFeatured": "Empfohlen", "ToolboxGroupNameAlphabetical": "Alle von A bis Z", "ToolboxGroupNameSection": "Abschnittslayout" }, "_RRzf46hnc4+fBX8RHyocNg": { "TextWebPartDisplayName": "Text", "TextWebpartDescription": "Hinzufügen und Formatieren von Text." }, "_2TT4IG31kAjRqhD0h5kPOg": { "ToolboxGroupSeeAllButtonLabel": "Alle anzeigen", "ToolboxGroupSeeAllButtonAriaLabel": "Alle Webparts in \"{0}\" anzeigen", "ToolboxGroupAriaLabel": "{0}-Liste. Verwenden Sie die NACH-LINKS- und NACH-RECHTS-TASTE, um sich innerhalb der Liste zu bewegen." }, "_z2ZwCbA+UxeGBoG5w1HCOA": { "SearchResultAlert": "Die Toolbox enthält {0} Elemente.||Die Toolbox enthält {0} Element.||Die Toolbox enthält {0} Elemente.", "SearchResultAlertIntervals": "0||1||2-" }, "_WVn4QXYnL8WpGCqr2C9ySA": { "ToolboxCategoryAllCategory": "Alle nach Kategorie", "ToolboxCategorySortingCategory": "Alle von A bis Z", "ToolboxCategorySearchResults": "Suchergebnisse", "ToolboxCollapseButtonDescription": "Originalgröße wiederherstellen", "NoResultLabel": "Keine Elemente entsprechen Ihrer Suche.", "TryAgainLabel": "Anderes Schlüsselwort probieren", "LargeToolboxAriaTitle": "Webpart-Toolbox erweitert.", "ToolboxCollapseButtonAriaLabel": "Reduzieren", "DropDownMenuAriaLabel": "Es werden Webparts aus der Kategorie \"{0}\" angezeigt.", "SwitchCategoryAlert": "Geändert in \"{0}\".", "BackButtonAriaLabel": "Zurück zur vorherigen Ansicht wechseln." }, "_CZsUWMvZilAKKAfwQSdzKQ": { "ToolboxExpandButtonTitle": "Erweitern, um weitere Webparts anzuzeigen", "ToolboxNoItemsFound": "Es wurde nichts gefunden, das Ihrer Suche entspricht." }, "_acoNwVeh/QF9PsLoQfUb2A": { "FormattingBarAlignCenterButtonTitle": "Zentrieren", "FormattingBarAlignLeftButtonTitle": "Linksbündig", "FormattingBarAlignRightButtonTitle": "Rechtsbündig", "FormattingBarBoldButtonTitle": "Fett ({0}+F)", "FormattingBarBulletListButtonTitle": "Aufzählung", "FormattingBarClearFormattingButtonTitle": "Alle Formatierungen löschen", "FormattingBarConfirmAction": "Aktion \"{0}\" ausgeführt.", "FormattingBarConfirmActionOnSelection": "Aktion \"{0}\" für den ausgewählten Text ausgeführt: \"{1}\"", "FormattingBarNormalTextButtonTitle": "Standardtext", "FormattingBarHeading2ButtonTitle": "Überschrift 1", "FormattingBarHeading3ButtonTitle": "Überschrift 2", "FormattingBarHeading4ButtonTitle": "Überschrift 3", "FormattingBarQuoteButtonTitle": "Textzitat", "FormattingBarItalicButtonTitle": "Kursiv ({0}+K)", "FormattingBarLinkButtonTitle": "Link ({0}+K)", "FormattingBarNumberedListButtonTitle": "Nummerierte Liste", "FormattingBarUnderlineButtonTitle": "Unterstrichen ({0}+U)", "FormattingBarUnlinkButtonTitle": "Link entfernen", "UndoButtonTitle": "Rückgängig ({0}+Z)", "RedoButtonTitle": "Wiederholen ({0}+Y)", "FormattingBarAccessibleLabel": "Formatierung", "LinkDialogErrorNotSupportedLink": "Dieser Linktyp wird nicht unterstützt.", "LinkDialogTextFieldAriaLabel": "Webadresse für Verknüpfung", "LinkDialogTextFieldLabel": "Webadresse:", "LinkDialogDisplayTextFieldLabel": "Anzuzeigender Text:", "LinkDialogTitle": "Link einfügen", "RichTextEditorAriaLabel": "Text. Verwenden Sie ALT+F10, um zu Symbolleisten zu wechseln.", "RichTextEditorTitle": "Text-Editor", "RichTextEditorIframeTitle": "{0} {1}", "RichTextLinkDialogCancelButtonLabel": "Abbrechen", "RichTextLinkDialogSaveButtonLabel": "Speichern", "RichTextNavigationAltF10Keys": "{0} {1}", "ToolbarNavigationArrowKeys": "Verwenden Sie die Pfeiltasten, um innerhalb der Symbolleiste zu navigieren.", "ToolbarNavigationTabKeys": "Verwenden Sie die TAB-TASTE, um zwischen Symbolleisten zu wechseln.", "ToolbarNavigationShiftTabKey": "Verwenden Sie UMSCHALT+TAB, um zurück zum Textfeld zu navigieren.", "ImagesInTableNotSupported": "Ein Bild kann nicht innerhalb einer Tabelle eingefügt werden. Versuchen Sie, das Bild außerhalb der Tabelle einzufügen.", "MultiImagePasteInIENotSupported": "Bilder, die sich in einer Tabelle befinden oder mit Text umbrochen werden, können nicht eingefügt werden. Kopieren Sie nur das Bild, ohne die Tabelle oder den Text, und versuchen Sie es noch mal.", "CloseWarningText": "Warnung \"{0}\" schließen ", "LoadingText": "Wird eingefügt...", "AddRowAboveText": "Darüber einfügen", "AddRowBelowText": "Darunter einfügen", "DeleteRowText": "Zeile löschen", "AddColumnLeftText": "Links einfügen", "AddColumnRightText": "Rechts einfügen", "AddRowAboveShortcutText": "{0} ({1}+UMSCHALT+A)", "AddRowBelowShortcutText": "{0} ({1}+UMSCHALT+Z)", "DeleteRowShortcutText": "{0} ({1}+UMSCHALT+D)", "StrikeThroughButtonLabel": "Durchgestrichen", "SuperscriptButtonLabel": "Hochgestellt", "SubscriptButtonLabel": "Tiefgestellt", "JustifyButtonLabel": "Blocksatz", "IncreaseIndentButtonLabel": "Einzug vergrößern", "DecreaseIndentButtonLabel": "Einzug verringern", "FontSizeDropDownLabel": "Schriftgrad", "TableTitle": "Tabelle", "TableButtonLabel": "Tabelle einfügen", "InsertRowBeforeButtonLabel": "Darüber einfügen", "InsertRowAfterButtonLabel": "Darunter einfügen", "InsertColumnLeftButtonLabel": "Links einfügen", "InsertColumnRightButtonLabel": "Rechts einfügen", "DeleteRowButtonLabel": "Zeile löschen", "DeleteColumnButtonLabel": "Spalte löschen", "DeleteTableButtonLabel": "Tabelle löschen", "FontColorLabel": "Schriftfarbe", "HightlightLabel": "Hervorhebungsfarbe", "SimpleTableButtonLabel": "Einfach", "TableWithHeaderBorderLabel": "Subtile Kopfzeile", "TableWithFilledHeaderLabel": "Kopfzeile", "TableWithBandedRowsLabel": "Alternierende Zeilen", "TableWithBandedRowsAndColumnsLabel": "Spaltenüberschrift", "SimpleTableButtonThemeLabel": "In einfachen Designfarben", "TableWithHeaderBorderThemeLabel": "Subtile Kopfzeile in Designfarben", "TableWithFilledHeaderThemeLabel": "Kopfzeile in Designfarben", "TableWithBandedRowsThemeLabel": "Alternierende Zeilen in Designfarben", "TableWithBandedRowsAndColumnsThemeLabel": "Spaltenüberschrift in Designfarben", "AlignTableLeftLabel": "Tabelle links ausrichten", "AlignTableCenterLabel": "Tabelle zentriert ausrichten", "AlignTableRightLabel": "Tabelle rechts ausrichten", "RTEPagePickerSaveAction": "Der Link \"{0}\" ist hinzugefügt.", "RTEPagePickerUnlinkAction": "Der Link \"{0}\" ist entfernt.", "FormattingBarPreButtonTitle": "Monospace", "CommandShortcutOnMac": "⌘", "ControlShortcutOnWin": "Strg" }, "_NAR8NFw8cblGJm9t5CjqOw": { "SuccessfullyLoadedText": "Debugmanifeste wurden erfolgreich geladen.", "ErrorLoadingText": "Fehler beim Laden des Debugmanifests: {0}" }, "_vd/LT/qfiQhbHFfeM1GtlA": { "FetchFailedError": "Fetching webpats failed with error \"{0}\". Render of a cached workbench may fail." }, "_8EVKOH1av6NjR/ZNfdafrw": { "WebPartData": "Web Part Data", "ClassicPages": "Klassische Seiten", "ModernPages": "Moderne Seiten", "Close": "Schließen", "WebPartDataHelpInfoLink": "Learn about provisioning SharePoint assets from your SharePoint client-side web part" }, "_FQya7ZjwIyrOEutOa+omIA": { "Title": "Warnung", "SubText": "Ihr Webpart wird nicht in der Toolbox angezeigt. Stellen Sie sicher, dass \"gulp serve\" in einem Webpartprojekt ausgeführt wird. Aktualisieren Sie die Seite, sobald \"gulp serve\" ausgeführt wird.", "OkButtonText": "OK", "ClickHerePrefix": "Klicken ", "ClickHereLink": "hier", "ClickHereSuffix": " um weitere Informationen zu erhalten." }, "_1JArBGDet5Uj9pJOV/9sFw": { "UrlTextBoxPlaceholder": "Geben Sie eine URL ein, um im mobilen Vorschautool anzuzeigen.", "ScreenReaderMobilePreviewEntered": "Sie haben das mobile Vorschautool geöffnet. Wenn Sie die Vorschau einer anderen Seite anzeigen möchten, geben Sie die URL in das Textfeld \"URL\" ein. Um das Tool zu schließen und zur Workbench zurückzukehren, drücken Sie ESC.", "ScreenReaderDevicePickerEntered": "Verwenden Sie die NACH-LINKS- und NACH-RECHTS-TASTE, um ein Gerät auszuwählen, um die Bildschirmgröße der Vorschau zu ändern.", "ScreenReaderDevicePickerSelectionChanged": "Drücken Sie die EINGABETASTE, um dieses Gerät auszuwählen.", "Width": "Breite", "Height": "Höhe" }, "_IusqdbcSoVYQiit3+QRSxw": { "Office365Title": "Office 365", "SharePointWorkbenchTitle": "SharePoint-Workbench", "ScreenReaderDisplayModeSwitchToEditMode": "Aus dem Vorschaumodus in den Bearbeitungsmodus gewechselt.", "ScreenReaderDisplayModeSwitchToReadMode": "Aus dem Bearbeitungsmodus in den Vorschaumodus gewechselt." }, "_nCtJlVOXBHa59LgYtajnjA": { "Save": "Speichern", "SaveAltText": "Zum Speichern des aktuellen Zustands der Workbench verwenden.", "Discard": "Verwerfen", "DiscardAltText": "Zum Verwerfen des aktuellen Zustands der Workbench verwenden.", "Mobile": "Mobiltelefon", "MobleAltText": "Zum Öffnen des mobilen Vorschautools für ein Mobiltelefon verwenden.", "Tablet": "Tablet", "TabletAltText": "Zum Öffnen des mobilen Vorschautools für einen Tablet verwenden.", "Preview": "Vorschau", "PreviewAltText": "Zum Wechseln aus dem Bearbeitungsmodus in den Vorschaumodus verwenden.", "Edit": "Bearbeiten", "EditAltText": "Zum Wechseln in den Bearbeitungsmodus verwenden.", "WebPartData": "Web part data", "WebPartDataAltText": "Display the serialized web part data." } }; strings.default = strings; return strings; }); ======================= File: node_modules/office-ui-fabric-react/lib/PersonaCoin.js ======================= export * from './components/Persona/index'; //# sourceMappingURL=PersonaCoin.js.map ======================= File: node_modules/office-ui-fabric-react/lib-amd/components/ColorPicker/ColorSlider/ColorSlider.js ======================= <reponame>GhostMachineSoftware/SPFx_Connect2List define(["require", "exports", "../../../Utilities", "./ColorSlider.base", "./ColorSlider.styles"], function (require, exports, Utilities_1, ColorSlider_base_1, ColorSlider_styles_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ColorSlider = Utilities_1.styled(ColorSlider_base_1.ColorSliderBase, ColorSlider_styles_1.getStyles, undefined, { scope: 'ColorSlider' }); }); //# sourceMappingURL=ColorSlider.js.map ======================= File: node_modules/office-ui-fabric-react/lib/components/Dialog/examples/Dialog.LargeHeader.Example.js ======================= <gh_stars>1-10 import * as tslib_1 from "tslib"; import * as React from'react'; import { Dialog, DialogType, DialogFooter } from 'office-ui-fabric-react/lib/Dialog'; import { PrimaryButton, DefaultButton } from 'office-ui-fabric-react/lib/Button'; import { ChoiceGroup } from 'office-ui-fabric-react/lib/ChoiceGroup'; var DialogLargeHeaderExample = /** @class */ (function (_super) { tslib_1.__extends(DialogLargeHeaderExample, _super); function DialogLargeHeaderExample(props) { var _this = _super.call(this, props) || this; _this._showDialog = function () { _this.setState({ hideDialog: false }); }; _this._closeDialog = function () { _this.setState({ hideDialog: true }); }; _this.state = { hideDialog: true }; return _this; } DialogLargeHeaderExample.prototype.render = function () { return (React.createElement("div", null, React.createElement(DefaultButton, { secondaryText: "Opens the Sample Dialog", onClick: this._showDialog, text: "Open Dialog" }), React.createElement(Dialog, { hidden: this.state.hideDialog, onDismiss: this._closeDialog, dialogContentProps: { type: DialogType.largeHeader, title: 'All emails together', subText: 'Your Inbox has changed. No longer does it include favorites, it is a singular destination for your emails.' }, modalProps: { isBlocking: false, containerClassName:'ms-dialogMainOverride' } }, React.createElement(ChoiceGroup, { options: [ { key: 'A', text: 'Option A' }, { key: 'B', text: 'Option B', checked: true }, { key: 'C', text: 'Option C', disabled: true } ], onChange: this._onChoiceChanged }), React.createElement(DialogFooter, null, React.createElement(PrimaryButton, { onClick: this._closeDialog, text: "Save" }), React.createElement(DefaultButton, { onClick: this._closeDialog, text: "Cancel" }))))); }; DialogLargeHeaderExample.prototype._onChoiceChanged = function () { console.log('Choice option change'); }; return DialogLargeHeaderExample; }(React.Component)); export { DialogLargeHeaderExample }; //# sourceMappingURL=Dialog.LargeHeader.Example.js.map ======================= File: node_modules/office-ui-fabric-react/lib/components/Tooltip/TooltipHost.js ======================= import { styled } from '../../Utilities'; import { TooltipHostBase } from './TooltipHost.base'; import { getStyles } from './TooltipHost.styles'; export var TooltipHost = styled(TooltipHostBase, getStyles, undefined, { scope: 'TooltipHost' }); //# sourceMappingURL=TooltipHost.js.map ======================= File: node_modules/@uifabric/utilities/lib-commonjs/dom/setPortalAttribute.js ======================= "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.DATA_PORTAL_ATTRIBUTE = 'data-portal-element'; /** * Identify element as a portal by setting an attribute. * @param element - Element to mark as a portal. */ function setPortalAttribute(element) { element.setAttribute(exports.DATA_PORTAL_ATTRIBUTE, 'true'); } exports.setPortalAttribute = setPortalAttribute; //# sourceMappingURL=setPortalAttribute.js.map ======================= File: node_modules/office-ui-fabric-react/lib-amd/components/ContextualMenu/ContextualMenuItem.base.js ======================= define(["require", "exports", "tslib", "react", "../../utilities/contextualMenu/index", "../../Utilities", "../../Icon"], function (require, exports, tslib_1, React, index_1, Utilities_1, Icon_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var renderItemIcon = function (props) { var item = props.item, hasIcons = props.hasIcons, classNames = props.classNames; var iconProps = item.iconProps; if (!hasIcons) { return null; } if (item.onRenderIcon) { return item.onRenderIcon(props); } return React.createElement(Icon_1.Icon, tslib_1.__assign({}, iconProps, { className: classNames.icon })); }; var renderCheckMarkIcon = function (_a) { var onCheckmarkClick = _a.onCheckmarkClick, item = _a.item, classNames = _a.classNames; var isItemChecked = index_1.getIsChecked(item); if (onCheckmarkClick) { // Ensures that the item is passed as the first argument to the checkmark click callback. var onClick = function (e) { return onCheckmarkClick(item, e); }; return React.createElement(Icon_1.Icon, { iconName: isItemChecked? 'CheckMark' : '', className: classNames.checkmarkIcon, onClick: onClick }); } return null; }; var renderItemName = function (_a) { var item = _a.item, classNames = _a.classNames; if (item.text || item.name) { return React.createElement("span", { className: classNames.label }, item.text || item.name); } return null; }; var renderSecondaryText = function (_a) { var item = _a.item, classNames = _a.classNames; if (item.secondaryText) { return React.createElement("span", { className: classNames.secondaryText }, item.secondaryText); } return null; }; var renderSubMenuIcon = function (_a) { var item = _a.item, classNames = _a.classNames; if (index_1.hasSubmenu(item)) { return React.createElement(Icon_1.Icon, tslib_1.__assign({ iconName: Utilities_1.getRTL()? 'ChevronLeft' : 'ChevronRight' }, item.submenuIconProps, { className: classNames.subMenuIcon })); } return null; }; var ContextualMenuItemBase = /** @class */ (function (_super) { tslib_1.__extends(ContextualMenuItemBase, _super); function ContextualMenuItemBase() { var _this = _super!== null && _super.apply(this, arguments) || this; _this.openSubMenu = function () { var _a = _this.props, item = _a.item, openSubMenu = _a.openSubMenu, getSubmenuTarget = _a.getSubmenuTarget; if (getSubmenuTarget) { var submenuTarget = getSubmenuTarget(); if (index_1.hasSubmenu(item) && openSubMenu && submenuTarget) { openSubMenu(item, submenuTarget); } } }; _this.dismissSubMenu = function () { var _a = _this.props, item = _a.item, dismissSubMenu = _a.dismissSubMenu; if (index_1.hasSubmenu(item) && dismissSubMenu) { dismissSubMenu(); } }; _this.dismissMenu = function (dismissAll) { var dismissMenu = _this.props.dismissMenu; if (dismissMenu) { dismissMenu(undefined /* ev */, dismissAll); } }; return _this; } ContextualMenuItemBase.prototype.render = function () { var _a = this.props, item = _a.item, classNames = _a.classNames; return (React.createElement("div", { className: item.split? classNames.linkContentMenu : classNames.linkContent }, renderCheckMarkIcon(this.props), renderItemIcon(this.props), renderItemName(this.props), renderSecondaryText(this.props), renderSubMenuIcon(this.props))); }; return ContextualMenuItemBase; }(Utilities_1.BaseComponent)); exports.ContextualMenuItemBase = ContextualMenuItemBase; }); //# sourceMappingURL=ContextualMenuItem.base.js.map ======================= File: node_modules/@uifabric/styling/lib-amd/styles/DefaultEffects.js ======================= define(["require", "exports"], function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.DefaultEffects = { // commented values are the defaults for Fluent elevation4: '0 0 5px 0 rgba(0,0,0,.4)', elevation8: '0 0 5px 0 rgba(0,0,0,.4)', elevation16: '0 0 5px 0 rgba(0,0,0,.4)', elevation64: '0 0 5px 0 rgba(0,0,0,.4)', roundedCorner2: '0px' // 2 }; }); //# sourceMappingURL=DefaultEffects.js.map ======================= File: node_modules/office-ui-fabric-react/lib-amd/components/SearchBox/examples/SearchBox.Disabled.Example.js ======================= define(["require", "exports", "tslib", "react", "office-ui-fabric-react/lib/SearchBox", "./SearchBox.Examples.scss"], function (require, exports, tslib_1, React, SearchBox_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); // tslint:disable:jsx-no-lambda var SearchBoxDisabledExample = /** @class */ (function (_super) { tslib_1.__extends(SearchBoxDisabledExample, _super); function SearchBoxDisabledExample() { return _super!== null && _super.apply(this, arguments) || this; } SearchBoxDisabledExample.prototype.render = function () { return (React.createElement("div", { className: "ms-SearchBoxExample" }, React.createElement(SearchBox_1.SearchBox, { placeholder: "Search", onFocus: function () { return console.log('onFocus called'); }, onBlur: function () { return console.log('onBlur called'); }, disabled: true }), React.createElement(SearchBox_1.SearchBox, { placeholder: "Search", onFocus: function () { return console.log('onFocus called'); }, onBlur: function () { return console.log('onBlur called'); }, underlined: true, disabled: true }))); }; return SearchBoxDisabledExample; }(React.Component)); exports.SearchBoxDisabledExample = SearchBoxDisabledExample; }); //# sourceMappingURL=SearchBox.Disabled.Example.js.map ======================= File: node_modules/office-ui-fabric-react/lib/components/SearchBox/SearchBox.js ======================= import { styled } from '../../Utilities'; import { SearchBoxBase } from './SearchBox.base'; import { getStyles } from './SearchBox.styles'; export var SearchBox = styled(SearchBoxBase, getStyles, undefined, { scope: 'SearchBox' }); //# sourceMappingURL=SearchBox.js.map ======================= File: node_modules/@uifabric/styling/lib/styles/index.js ======================= export { AnimationStyles, AnimationVariables } from './AnimationStyles'; export { DefaultPalette } from './DefaultPalette'; export { DefaultFontStyles, registerDefaultFontFaces } from './DefaultFontStyles'; export { FontSizes, FontWeights, IconFontSizes, createFontStyles } from './fonts'; export { getFocusStyle, focusClear } from './getFocusStyle'; export { hiddenContentStyle } from './hiddenContentStyle'; export { PulsingBeaconAnimationStyles } from './PulsingBeaconAnimationStyles'; export { getGlobalClassNames } from './getGlobalClassNames'; export * from './scheme'; export { ThemeSettingName, getTheme, loadTheme, createTheme, registerOnThemeChangeCallback, removeOnThemeChangeCallback } from './theme'; export * from './CommonStyles'; export * from './GeneralStyles'; export * from './getFadedOverflowStyle'; export * from './zIndexes'; //# sourceMappingURL=index.js.map ======================= File: node_modules/office-ui-fabric-react/lib-amd/components/ProgressIndicator/examples/ProgressIndicator.Indeterminate.Example.js ======================= define(["require", "exports", "tslib", "react", "office-ui-fabric-react/lib/ProgressIndicator"], function (require, exports, tslib_1, React, ProgressIndicator_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ProgressIndicatorIndeterminateExample = /** @class */ (function (_super) { tslib_1.__extends(ProgressIndicatorIndeterminateExample, _super); function ProgressIndicatorIndeterminateExample(props) { return _super.call(this, props) || this; } ProgressIndicatorIndeterminateExample.prototype.render = function () { return React.createElement(ProgressIndicator_1.ProgressIndicator, { label: "Example title", description: "Example description" }); }; return ProgressIndicatorIndeterminateExample; }(React.Component)); exports.ProgressIndicatorIndeterminateExample = ProgressIndicatorIndeterminateExample; }); //# sourceMappingURL=ProgressIndicator.Indeterminate.Example.js.map ======================= File: node_modules/office-ui-fabric-react/lib-commonjs/components/Button/examples/Button.Basic.Example.styles.js ======================= "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function getStyles(props) { return { example: [ 'ms-BasicButtonsExample', { selectors: { '.ms-Button': { margin: '10px 0' } } } ], twoup: [ 'ms-BasicButtonsTwoUp', { display: 'flex', selectors: { '& > *': { flexGrow: 1 }, '.ms-Label': { marginBottom: '10px' } } } ] }; } exports.getStyles = getStyles; //# sourceMappingURL=Button.Basic.Example.styles.js.map ======================= File: node_modules/office-ui-fabric-react/lib-amd/components/pickers/index.js ======================= <gh_stars>0 define(["require", "exports", "tslib", "./Suggestions/Suggestions", "./Suggestions/Suggestions.types", "./Suggestions/SuggestionsItem", "./Suggestions/SuggestionsController", "./AutoFill/BaseAutoFill", "./BasePicker", "./BasePicker.types", "./PeoplePicker/PeoplePicker", "./PeoplePicker/PeoplePickerItems/PeoplePickerItem", "./PeoplePicker/PeoplePickerItems/PeoplePickerItemSuggestion", "./TagPicker/TagPicker", "./TagPicker/TagItem", "./TagPicker/TagItemSuggestion"], function (require, exports, tslib_1, Suggestions_1, Suggestions_types_1, SuggestionsItem_1, SuggestionsController_1, BaseAutoFill_1, BasePicker_1, BasePicker_types_1, PeoplePicker_1, PeoplePickerItem_1, PeoplePickerItemSuggestion_1, TagPicker_1, TagItem_1, TagItemSuggestion_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); tslib_1.__exportStar(Suggestions_1, exports); tslib_1.__exportStar(Suggestions_types_1, exports); tslib_1.__exportStar(SuggestionsItem_1, exports); tslib_1.__exportStar(SuggestionsController_1, exports); tslib_1.__exportStar(BaseAutoFill_1, exports); tslib_1.__exportStar(BasePicker_1, exports); tslib_1.__exportStar(BasePicker_types_1, exports); tslib_1.__exportStar(PeoplePicker_1, exports); tslib_1.__exportStar(PeoplePickerItem_1, exports); tslib_1.__exportStar(PeoplePickerItemSuggestion_1, exports); tslib_1.__exportStar(TagPicker_1, exports); tslib_1.__exportStar(TagItem_1, exports); tslib_1.__exportStar(TagItemSuggestion_1, exports); }); //# sourceMappingURL=index.js.map ======================= File: node_modules/office-ui-fabric-react/lib/components/Pivot/examples/Pivot.OnChange.Example.js ======================= import * as tslib_1 from "tslib"; import * as React from'react'; import { Pivot, PivotItem, PivotLinkFormat, PivotLinkSize } from 'office-ui-fabric-react/lib/Pivot'; import { Label } from 'office-ui-fabric-react/lib/Label'; var PivotOnChangeExample = /** @class */ (function (_super) { tslib_1.__extends(PivotOnChangeExample, _super); function PivotOnChangeExample() { return _super!== null && _super.apply(this, arguments) || this; } PivotOnChangeExample.prototype.render = function () { return (React.createElement("div", null, React.createElement(Pivot, { linkSize: PivotLinkSize.large, linkFormat: PivotLinkFormat.tabs, onLinkClick: this.onLinkClick }, React.createElement(PivotItem, { headerText: "Foo" }, React.createElement(Label, null, "Pivot #1")), React.createElement(PivotItem, { headerText: "Bar" }, React.createElement(Label, null, "Pivot #2")), React.createElement(PivotItem, { headerText: "Bas" }, React.createElement(Label, null, "Pivot #3")), React.createElement(PivotItem, { headerText: "Biz" }, React.createElement(Label, null, "Pivot #4"))))); }; PivotOnChangeExample.prototype.onLinkClick = function (item) { alert(item.props.headerText); }; return PivotOnChangeExample; }(React.Component)); export { PivotOnChangeExample }; //# sourceMappingURL=Pivot.OnChange.Example.js.map ======================= File: node_modules/office-ui-fabric-react/lib-commonjs/components/MessageBar/MessageBar.styles.js ======================= "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var Styling_1 = require("../../Styling"); var MessageBar_types_1 = require("./MessageBar.types"); var GlobalClassNames = { root:'ms-MessageBar', error:'ms-MessageBar--error', blocked:'ms-MessageBar--blocked', severeWarning:'ms-MessageBar--severeWarning', success:'ms-MessageBar--success', warning:'ms-MessageBar--warning', multiline:'ms-MessageBar-multiline', singleline:'ms-MessageBar-singleline', dismissalSingleLine:'ms-MessageBar-dismissalSingleLine', expandingSingleLine:'ms-MessageBar-expandingSingleLine', content:'ms-MessageBar-content', iconContainer:'ms-MessageBar-icon', text:'ms-MessageBar-text', innerText:'ms-MessageBar-innerText', dismissSingleLine:'ms-MessageBar-dismissSingleLine', expandSingleLine:'ms-MessageBar-expandSingleLine', dismissal:'ms-MessageBar-dismissal', expand:'ms-MessageBar-expand', actions:'ms-MessageBar-actions', actionsSingleline:'ms-MessageBar-actionsSingleLine' }; // Returns the background color of the MessageBar root element based on the type of MessageBar. var getRootBackground = function (messageBarType, palette, semanticColors) { switch (messageBarType) { case MessageBar_types_1.MessageBarType.error: case MessageBar_types_1.MessageBarType.blocked: return semanticColors.errorBackground; case MessageBar_types_1.MessageBarType.severeWarning: return semanticColors.blockingBackground; case MessageBar_types_1.MessageBarType.success: return semanticColors.successBackground; case MessageBar_types_1.MessageBarType.warning: return semanticColors.warningBackground; } return palette.neutralLighter; }; // Returns the icon color based on the type of MessageBar. var getIconColor = function (messageBarType, palette, semanticColors) { switch (messageBarType) { case MessageBar_types_1.MessageBarType.error: case MessageBar_types_1.MessageBarType.blocked: case MessageBar_types_1.MessageBarType.severeWarning: return semanticColors.errorText; case MessageBar_types_1.MessageBarType.success: return palette.green; case MessageBar_types_1.MessageBarType.warning: return semanticColors.warningText; } return palette.neutralSecondary; }; exports.getStyles = function (props) { var theme = props.theme, className = props.className, messageBarType = props.messageBarType, onDismiss = props.onDismiss, actions = props.actions, truncated = props.truncated, isMultiline = props.isMultiline, expandSingleLine = props.expandSingleLine; var semanticColors = theme.semanticColors, palette = theme.palette, fonts = theme.fonts; var SmallScreenSelector = Styling_1.getScreenSelector(0, Styling_1.ScreenWidthMaxSmall); var classNames = Styling_1.getGlobalClassNames(GlobalClassNames, theme); var dismissalAndExpandIconStyle = { fontSize: 12, height: 12, lineHeight: '12px', color: palette.neutralPrimary, selectors: (_a = {}, _a[Styling_1.HighContrastSelector] = { MsHighContrastAdjust: 'none', color: 'window' }, _a) }; var dismissalAndExpandSingleLineStyle = { display: 'flex', selectors: { '&.ms-Button-icon': dismissalAndExpandIconStyle } }; var dismissalAndExpandStyle = { flexShrink: 0, margin: 8, marginLeft: 0, selectors: (_b = { '&.ms-Button-icon': dismissalAndExpandIconStyle }, _b[SmallScreenSelector] = { margin: '0px 0px 0px 8px' }, _b) }; var focusStyle = Styling_1.getFocusStyle(theme, 0,'relative', undefined, palette.black); return { root: [ classNames.root, theme.fonts.medium, messageBarType === MessageBar_types_1.MessageBarType.error && classNames.error, messageBarType === MessageBar_types_1.MessageBarType.blocked && classNames.blocked, messageBarType === MessageBar_types_1.MessageBarType.severeWarning && classNames.severeWarning, messageBarType === MessageBar_types_1.MessageBarType.success && classNames.success, messageBarType === MessageBar_types_1.MessageBarType.warning && classNames.warning, isMultiline? classNames.multiline : classNames.singleline, !isMultiline && onDismiss && classNames.dismissalSingleLine, !isMultiline && truncated && classNames.expandingSingleLine, { background: getRootBackground(messageBarType, palette, semanticColors), color: palette.neutralPrimary, minHeight: 32, width: '100%', boxSizing: 'border-box', display: 'flex', position:'relative', wordBreak: 'break-word', selectors: (_c = { '&.ms-Link': tslib_1.__assign({ color: palette.themeDark }, fonts.small) }, _c[Styling_1.HighContrastSelector] = { background: 'windowText' }, _c) }, isMultiline && { flexDirection: 'column' }, !isMultiline && { selectors: (_d = {}, _d[SmallScreenSelector] = { flexDirection: 'column' }, _d) }, truncated && { flexDirection: 'column', selectors: { '&.ms-Button-icon': dismissalAndExpandIconStyle } }, className ], content: [ classNames.content, { display: 'flex', lineHeight: 'normal', width: '100%', boxSizing: 'border-box', selectors: { '&:before': { pointerEvents: 'none', position: 'absolute', right: 0, bottom: 0, left: 0, top: 0, margin: 0, selectors: (_e = {}, _e[Styling_1.HighContrastSelector] = { background: 'WindowText', color: 'Window', content:'' }, _e) } } }, !isMultiline && { selectors: (_f = {}, _f[SmallScreenSelector] = { flexDirection: 'row' }, _f) }, (truncated || isMultiline) && { flexDirection: 'row' } ], iconContainer: [ classNames.iconContainer, { fontSize: 16, minWidth: 16, minHeight: 16, display: 'flex', color: palette.neutralSecondary, flexShrink: 0, margin: 16, marginRight: 0, selectors: (_g = {}, _g[SmallScreenSelector] = { margin: '8px 0px 8px 8px' }, _g) } ], icon: { color: getIconColor(messageBarType, palette, semanticColors), selectors: (_h = {}, _h[Styling_1.HighContrastSelector] = { MsHighContrastAdjust: 'none', color: 'window' }, _h) }, text: [ classNames.text, tslib_1.__assign({ minWidth: 0, display: 'flex', flexGrow: 1, margin: '16px 8px' }, fonts.small, { selectors: (_j = {}, _j[SmallScreenSelector] = { margin: '8px 0px 8px 8px' }, _j[Styling_1.HighContrastSelector] = { MsHighContrastAdjust: 'none', color: 'window' }, _j) }), !onDismiss && { marginRight: 16, selectors: (_k = {}, _k[SmallScreenSelector] = { marginRight: 8 }, _k) }, isMultiline && actions && { marginBottom: 8, selectors: (_l = {}, _l[SmallScreenSelector] = { marginBottom: 0 }, _l) }, !isMultiline && actions && { selectors: (_m = {}, _m[SmallScreenSelector] = { marginBottom: 0 }, _m) } ], innerText: [ classNames.innerText, { lineHeight: 16, selectors: { '& span': { selectors: { '& a': { paddingLeft: 4 } } } } }, truncated && { overflow: 'visible', whiteSpace: 'pre-wrap' }, !isMultiline && { overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }, !isMultiline && !truncated && { selectors: (_o = {}, _o[SmallScreenSelector] = { overflow: 'visible', whiteSpace: 'pre-wrap' }, _o) }, expandSingleLine && { overflow: 'visible', whiteSpace: 'pre-wrap' } ], dismissSingleLine: [classNames.dismissSingleLine, dismissalAndExpandSingleLineStyle], expandSingleLine: [classNames.expandSingleLine, dismissalAndExpandSingleLineStyle], dismissal: [classNames.dismissal, dismissalAndExpandStyle, focusStyle], expand: [classNames.expand, dismissalAndExpandStyle, focusStyle], actions: [ isMultiline? classNames.actions : classNames.actionsSingleline, { display: 'flex', flexGrow: 0, flexShrink: 0, flexBasis: 'auto', flexDirection: 'row-reverse', alignItems: 'center', margin: '8px 8px 8px 0', selectors: { '& button:nth-child(n+2)': { marginLeft: 8 } } }, isMultiline && { margin: '0px 12px 12px 0', selectors: { '& button:nth-child(n+2)': { marginLeft: 12 } } } ] }; var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o; }; //# sourceMappingURL=MessageBar.styles.js.map ======================= File: node_modules/office-ui-fabric-react/lib/components/Button/SplitButton/SplitButton.classNames.js ======================= import { memoizeFunction } from '../../../Utilities'; import { mergeStyles } from '../../../Styling'; export var getClassNames = memoizeFunction(function (styles, disabled, expanded, checked) { return { root: mergeStyles(styles.splitButtonMenuButton, expanded && [styles.splitButtonMenuButtonExpanded], disabled && [styles.splitButtonMenuButtonDisabled], checked &&!disabled && [styles.splitButtonMenuButtonChecked]), splitButtonContainer: mergeStyles(styles.splitButtonContainer, checked && !disabled && [ styles.splitButtonContainerChecked, { selectors: { ':hover': styles.splitButtonContainerCheckedHovered } } ],!disabled && !checked && [ { selectors: { ':hover': styles.splitButtonContainerHovered, ':focus': styles.splitButtonContainerFocused } } ], disabled && styles.splitButtonContainerDisabled), icon: mergeStyles(styles.splitButtonMenuIcon, disabled && styles.splitButtonMenuIconDisabled), flexContainer: mergeStyles(styles.splitButtonFlexContainer), divider: mergeStyles(styles.splitButtonDivider) }; }); //# sourceMappingURL=SplitButton.classNames.js.map ======================= File: node_modules/@microsoft/sp-loader/lib/resx-strings/sl-si.js ======================= define([], function() { var strings = { "_nQNACBeQ34aV6bVwtFBayA": { "loaderUserFriendlyError": "Aplikacije ni mogoče naložiti na tej strani. Poskusite znova z gumbom »Nazaj« v brskalniku. Če težave ne morete odpraviti, se obrnite na skrbnika spletnega mesta in mu posredujte informacije iz razdelka s tehničnimi podrobnostmi.", "platformFailedToLoadError": "Platform failed to load. Id: \"{0}\", name: \"{1}\"", "platformFailedToLoadWithMessageError": "Platform failed to load. Id: \"{0}\", name: \"{1}\".\r\nError: {2}", "applicationFailedToInitializeError": "Error initializing application. Error: {0}", "invalidPreloadedDataError": "Invalid preloaded data.", "manifestNotFoundByIdError": "Manifest not found for component id \"{0}\".", "manifestNotFoundError": "Manifest not found for component id \"{0}\" and version \"{1}\".", "systemConfigDisabledError": "System.config() is not supported. Use a manifest to specify the configuration.", "loadComponentLog": "Loading component \"{0}\" ({1}).", "loadComponentEndLog": "Component \"{0}\" ({1}) loaded.", "loadComponentRetryLog": "Loading component \"{0}\" ({1}). Attempt {2} of {3}.", "loadComponentError": "Failed to load component \"{0}\" ({1}).\r\nOriginal error: {2}", "loadComponentMaxRetriesError": "Attempted to load component \"{0}\" ({1}) {2} times without success.", "loadComponentDependencyError": "Failed to load component dependency \"{0}\" from component \"{1}\" ({2}).\r\nOriginal error: {3}", "loadComponentDependencyFailoverPathError": "Failed to load component dependency \"{0}\" with failover path \"{1}\" from component \"{2}\" ({3}).\r\nOriginal error: {4}", "loadPathDependencyLog": "Loading path dependency \"{0}\" from component \"{1}\" ({2})", "loadPathDependencyError": "Failed to load path dependency \"{0}\" from component \"{1}\" ({2}).\r\nOriginal error: {3}", "loadPathDependencyBlockedByAnotherDependencyError": "Failed to load path dependency \"{0}\" from component \"{1}\" ({2}) due to another dependency that failed to load.", "loadEntryPointError": "Failed to load entry point from component \"{0}\" ({1}).\r\nOriginal error: {2}", "loadComponentReturnsEmptyError": "loadComponent() returned an empty object for component \"{0}\" ({1}).", "loadComponentReturnsDefaultEmptyError": "loadComponent() returned an object with an empty default property for component \"{0}\" ({1}).", "moduleHasUndeclaredDependencyError": "The entry point for component \"{0}\" ({1}) has a dependency on \"{2}\" that is not declared in the manifest.", "loadScriptWithStringError": "loadScript function doesn't allow a string as 2nd parameter. Use ILoadScriptOptions instead.", "tooManyManifestsError": "{0} manifests (versions {1}) found for component \"{2}\".", "tooManyCompatibleVersionsError": "{0} compatible versions ({1}) found for component \"{2}\" version \"{3}\".", "tooManyComponentsError": "Too many components found for id \"{0}\".", "noComponentFoundError": "No component found for id \"{0}\".", "deleteComponentLog": "Deleting component \"{0}\" version \"{1}\" from the store.", "browserNotSupportedError": "This version of your browser is not supported.\r\nPlease update your browser to the latest version.", "ie9OrOlderNotSupportedError": "This page does not support Internet Explorer releases older than version 10. Please update your web browser.", "firefox43OrOlderNotSupportedError": "This page does not support Mozilla Firefox releases older than version 44. Please update your web browser.", "resourceNotFoundError": "Resource \"{0}\" not found in loader configuration of manifest for component \"{1}\" ({2}).", "noFailoverPathError": "Cannot call resolveAddress() on a component with no failover path", "urlStatusLocalhostFileNotFoundError": "Failed to load URL '{3}' for resource '{2}' in component '{0}' ({1}). The file was not found in the server.\r\nMake sure that you are running 'gulp serve'.", "urlStatusFileNotFoundError": "Failed to load URL '{3}' for resource '{2}' in component '{0}' ({1}). The file was not found in the server.", "urlStatusForbiddenError": "Failed to load URL '{3}' for resource '{2}' in component '{0}' ({1}). The access to the file is forbidden.", "urlStatusClientErrorError": "Failed to load URL '{3}' for resource '{2}' in component '{0}' ({1}). There was an error requesting the file.", "urlStatusServerErrorError": "Failed to load URL '{3}' for resource '{2}' in component '{0}' ({1}). There was a problem in the server.", "urlStatusLocalhostNetworkErrorError": "Failed to load URL '{3}' for resource '{2}' in component '{0}' ({1}). There was a network problem.\r\nMake sure that you are running 'gulp serve' and you have run 'gulp trust-dev-cert'.", "urlStatusHttpsNetworkErrorError": "Failed to load URL '{3}' for resource '{2}' in component '{0}' ({1}). There was a network problem.\r\nThis may be a problem with a HTTPS certificate. Make sure you have the right certificate.", "urlStatusNetworkErrorError": "Failed to load URL '{3}' for resource '{2}' in component '{0}' ({1}). There was a network problem.", "urlStatusUndefinedError": "Failed to load URL '{3}' for resource '{2}' in component '{0}' ({1}) because of unknown problems.", "isUndefinedValidateError": "The value for \"{0}\" must not be undefined", "failedToCreateGlobalVariableError": "Failed to create global variable \"{0}\" from script \"{1}\"", "dependencyLoadError": "Failed to load module '{0}' because dependency {1} was not loaded", "missingPathDependencyError": "Missing path dependency \"{0}\" from component \"{1}\" ({2}). Existing path dependencies: {3}", "listSeparator": ", " }, "_FmFyAWZ1md7Z1R+V8t2S2Q": { "errorLoadingDebugScriptHTTPS": "Med nalaganjem iskanja napak v skriptu je prišlo do napake. Preverite, ali strežnik deluje in ali je URL parametra »{0}« pravilen.", "errorLoadingDebugScriptHTTP": "Med nalaganjem iskanja napak v skriptu je prišlo do napake. Preverite, ali strežnik deluje, ali je URL parametra »{0}« pravilen in ali je dovoljeno nalaganje nevarnih skriptov. Uporabite lahko tudi potrdilo o razvoju in podajanju skriptov za iskanje prek protokola HTTPS.", "errorLoadingDebugScriptMalformed": "Med nalaganjem iskanja napak v skriptu je prišlo do napake. Videti je, da je URL ({0}), vključen v iskanje napak, poškodovan.", "errorLoadingDebugScriptUnknown": "Med nalaganjem iskanja napak v skriptu je prišlo do neznane napake.", "errorLoadingDebugLoaderTitle": "Med nalaganjem iskanja napak v nalagalniku je prišlo do napake.", "errorLoadingDebugManifestTitle": "Med nalaganjem iskanja napak v manifestu je prišlo do napake.", "errorLoadingUnknownTitle": "Med nalaganjem iskanja napak v skriptih je prišlo do napake." }, "_RPELcTeq3ZByqi3N5dt18w": { "missingDeveloperToolsTabInitFunctionError": "Manjkajo komponente ali funkcija inicializatorja.", "closeDeveloperToolsAriaLabel": "Zapri orodja za razvijalce." }, "_fwMQe6Xe08yEeCPNxngd+g": { "warningHeading": "Opozorilo!", "warningLine1": "Če uporabite to orodje, ste izpostavljeni morebitnim varnostnim grožnjam, zaradi katerih lahko drugi dobijo dostop do osebnih podatkov v storitvi Office 365 (dokumenti, e-pošte, pogovori in veliko drugega). Pred nadaljevanjem preverite, ali je oseba ali organizacija, ki vas je prosila za dostop, vredna zaupanja.", "warningLine2": "Več informacij je na voljo tukaj: {0}" }, "_upo3vfLFBbnbzl2hKy2TwA": { "allowDebugManifestsTitle": "Ali želite dovoliti iskanje napak v skriptih?", "allowDebugLoaderTitle": "Ali dovolite iskanje napak v nalagalniku?", "allowDebugLoaderAndManifestsTitle": "Ali želite dovoliti iskanje napak v nalagalniku in skriptih?", "debugManifestLoadingWarning": "OPOZORILO: Na tej strani so nevarni skripti. Če jih naložite, bi lahko potencialno škodovali vašemu računalniku! Ne nadaljujte postopka, razen če zaupate razvijalcu in razumete tveganja.", "debugManifestLoadingWarning2": "Če niste prepričani, kliknite {0}.", "debugManifestLoadingConfirm": "Naloži skripte za iskanje napak", "debugManifestLoadingCancel": "Ne naloži skriptov za iskanje napak", "debugManifestLoadingCalloutText": "Če ne veste, kaj bi naredili, kliknite tukaj." }, "_mraBnnuq2J9WjrAcnw9QNA": { "debugManifestErrorDetail": "Med nalaganjem iskanja v manifestu napak je prišlo do napake.", "debugManifestErrorDismissButtonText": "Opusti" }, "_SxImp5ewsUToxeAHBkB+pw": { "developerToolsTabLoadingText": "Nalaganje...", "developerToolsTabLoadingUnknownError": "Med nalaganjem modula orodij za razvijalce je prišlo do napake." }, "_gqinlPQb8HZprTeCpwNz2w": { "TabTitle": "Sled", "EmptyTraceData": "Nobena sled ni naložena.", "ExportCSVButtonLabel": "Izvozi v CSV", "LevelHeaderLabel": "Raven", "MessageHeaderLabel": "Sporočilo", "ScopeHeaderLabel": "Obseg", "SourceHeaderLabel": "Vir", "TimestampHeaderLabel": "Časovni žig", "TimestampFormat": "{0}/{1}/{2} {3}:{4}:{5}.{6}" }, "_sovI4qDAUPMnD4jg3Vsyfg": { "tabTitle": "Manifesti", "noManifestSelected": "Noben manifest ni izbran" }, "_g7G0QHJ5bQYlxe+lk+DcxA": { "TabTitle": "Učinkovitost delovanja", "ErrorAccessingPerfDataErrorMessage": "Ni mogoče pridobiti podatkov o učinkovitosti delovanja: predmet je ničeln ali pa ni določen.", "ErrorAccessingRedirectDataErrorMessage": "Pri dostopu do podatkov o učinkovitosti preusmeritve HTTP je prišlo do težave.", "ErrorParsingPercievedLatencyErrorMessage": "Pri razčlenjevanju podatkov o zaznani zakasnitvi je prišlo do napake.", "ErrorParsingApiDataErrorMessage": "Pri razčlenjevanju podatkov vmesnika API je prišlo do napake.", "UnkownPerformanceDataErrorMessage": "Prišlo je do neznane napake: {0}", "DefaultWebPartName": "Spletni gradnik", "ServerResponseLabel": "Odgovor strežnika", "ApplicationInitializationLabel": "Inicializacija aplikacije", "ScriptFetchEvalLabel": "Dobivanje in ocena scenarija", "SpLoaderStartLabel": "Inicializacija SPFx", "PageRenderLabel": "Upodabljalnik strani", "LeftNavRenderLabel": "Levi upodabljalnik krmarjenja", "CanvasRenderLabel": "Upodabljalnik platna", "LayoutRenderLabel": "Upodabljalnik postavitve", "RedirectResponseLabel": "Preusmeri odgovor", "AppLoadLabel": "Nalaganje aplikacije", "RenderWebPartsLabel": "Upodabljalnik spletnih gradnikov", "TotalRenderTimeLabel": "Skupaj", "GeneralErrorMessage": "Pri pridobivanju podatkov o učinkovitosti delovanja je prišlo do napake.", "ErrorMessagePrefix": "Sporočilo o napaki: {0}", "PerformanceDataHint": "Opomba: ko dodate ali odstranite spletni gradnik, osvežite stran, da si ogledate posodobljene podatke o učinkovitosti delovanja.", "ModulesLoadedLegendLabel": "Naloženi moduli", "InitializationLegendLabel": "Inicializacija", "RenderTimeLegendLabel": "Čas upodabljanja", "InitializationTimeLabel": "Čas inicializacije", "ModuleLoadingTimeLabel": "Čas nalaganja modula", "ModuleLazyLoadingDelayLabel": "Zakasnitev nalaganja modula", "DataFetchTimeLabel": "Čas pridobivanja podatkov", "DataFetchLegendLabel": "Pridobivanje podatkov", "ItemsColumnHeader": "Elementi", "DurationColumnHeader": "Trajanje", "MillisecondsUnitLabel": "{0} ms", "NAPlaceholder": "Ni na voljo" } }; strings.default = strings; return strings; }); ======================= File: node_modules/@microsoft/sp-http/lib/aadHttpClient/AadHttpClient.js ======================= <reponame>GhostMachineSoftware/SPFx_Connect2List<gh_stars>0 import { Validate } from '@microsoft/sp-core-library'; import { fetchProviderServiceKey } from '../httpClient/FetchProvider'; import HttpClientResponse from '../httpClient/HttpClientResponse'; import AadTokenProviders from '../oauthTokenProvider/AadTokenProviders'; import HttpClientHelper from '../httpClient/HttpClientHelper'; import { predefinedConfigurations } from './AadHttpClientConfiguration'; var AadHttpClient = (function () { function AadHttpClient(serviceScope, resourceEndpoint, options) { var _this = this; Validate.isNotNullOrUndefined(serviceScope,'serviceScope'); Validate.isNotNullOrUndefined(resourceEndpoint,'resourceUrl'); this._resourceUrl = resourceEndpoint; this._serviceScope = serviceScope; this._aadTokenProvider = options && options.tokenProvider || AadTokenProviders.configurable; this._aadTokenConfiguration = options && options.configuration; serviceScope.whenFinished(function () { _this._fetchProvider = serviceScope.consume(fetchProviderServiceKey); }); } AadHttpClient.prototype.fetch = function (url, configuration, options) { var _this = this; var tokenFetchPromise = this._aadTokenConfiguration? this._aadTokenProvider._getTokenInternal(this._resourceUrl, this._aadTokenConfiguration) : this._aadTokenProvider.getToken(this._resourceUrl); return tokenFetchPromise.then(function (token) { if (!options.headers) { options.headers = new Headers(); } else { options.headers = new Headers(options.headers); } options.headers.append('Authorization', 'Bearer'+ token); return HttpClientHelper.fetchCore(configuration, new Request(url, options), _this._serviceScope, _this._fetchProvider, AadHttpClient._className); }).then(function (value) { return new HttpClientResponse(value); }); }; AadHttpClient.prototype.get = function (url, configuration, options) { return this.fetch(url, configuration, HttpClientHelper.overrideHttpMethod(options, 'GET')); }; AadHttpClient.prototype.post = function (url, configuration, options) { return this.fetch(url, configuration, HttpClientHelper.overrideHttpMethod(options, 'POST')); }; AadHttpClient.configurations = predefinedConfigurations; AadHttpClient._className = 'AadHttpClient'; return AadHttpClient; }()); export default AadHttpClient; ======================= File: node_modules/office-ui-fabric-react/lib/components/Button/IconButton/IconButton.styles.js ======================= import { concatStyleSets, HighContrastSelector } from '../../../Styling'; import { memoizeFunction } from '../../../Utilities'; import { getStyles as getBaseButtonStyles } from '../BaseButton.styles'; import { getStyles as getSplitButtonStyles } from '../SplitButton/SplitButton.styles'; export var getStyles = memoizeFunction(function (theme, customStyles) { var baseButtonStyles = getBaseButtonStyles(theme); var splitButtonStyles = getSplitButtonStyles(theme); var palette = theme.palette, semanticColors = theme.semanticColors; var iconButtonStyles = { root: { padding: '0 4px', width: '32px', height: '32px', backgroundColor: 'transparent', border: 'none', color: semanticColors.actionLink }, rootHovered: { color: semanticColors.actionLinkHovered, selectors: (_a = {}, _a[HighContrastSelector] = { borderColor: 'Highlight', color: 'Highlight' }, _a) }, rootPressed: { color: palette.themePrimary }, rootExpanded: { color: palette.themePrimary }, rootChecked: { backgroundColor: semanticColors.buttonBackgroundChecked }, rootCheckedHovered: { backgroundColor: semanticColors.buttonBackgroundHovered }, rootDisabled: { color: semanticColors.disabledText } }; return concatStyleSets(baseButtonStyles, iconButtonStyles, splitButtonStyles, customStyles); var _a; }); //# sourceMappingURL=IconButton.styles.js.map ======================= File: node_modules/office-ui-fabric-react/lib/utilities/keytips/KeytipManager.js ======================= <gh_stars>1-10 import * as tslib_1 from "tslib"; import { arraysEqual, replaceElement, findIndex, find, EventGroup, getId } from '../../Utilities'; import { KeytipEvents } from '../../utilities/keytips/KeytipConstants'; /** * This class is responsible for handling registering, updating, and unregistering of keytips */ var KeytipManager = /** @class */ (function () { function KeytipManager() { this.keytips = []; this.persistedKeytips = []; // This is (and should be) updated and kept in sync // with the inKeytipMode in KeytipLayer. this.inKeytipMode = false; // Boolean that gets checked before entering keytip mode by the KeytipLayer // Used for an override in special cases (e.g. Disable entering keytip mode when a modal is shown) this.shouldEnterKeytipMode = true; } /** * Static function to get singleton KeytipManager instance * * @returns {KeytipManager} Singleton KeytipManager instance */ KeytipManager.getInstance = function () { return this._instance; }; /** * Registers a keytip * * @param keytipProps - Keytip to register * @param persisted - T/F if this keytip should be persisted, default is false * @returns {string} Unique ID for this keytip */ KeytipManager.prototype.register = function (keytipProps, persisted) { if (persisted === void 0) { persisted = false; } var props = keytipProps; if (!persisted) { // Add the overflowSetSequence if necessary props = this.addParentOverflow(keytipProps); } // Create a unique keytip var uniqueKeytip = this._getUniqueKtp(props); // Add to array persisted? this.persistedKeytips.push(uniqueKeytip) : this.keytips.push(uniqueKeytip); var event = persisted? KeytipEvents.PERSISTED_KEYTIP_ADDED : KeytipEvents.KEYTIP_ADDED; EventGroup.raise(this, event, { keytip: props, uniqueID: uniqueKeytip.uniqueID }); return uniqueKeytip.uniqueID; }; /** * Update a keytip * * @param keytipProps - Keytip to update * @param uniqueID - Unique ID of this keytip */ KeytipManager.prototype.update = function (keytipProps, uniqueID) { var newKeytipProps = this.addParentOverflow(keytipProps); var uniqueKeytip = this._getUniqueKtp(newKeytipProps, uniqueID); var keytipIndex = findIndex(this.keytips, function (ktp) { return ktp.uniqueID === uniqueID; }); if (keytipIndex >= 0) { // Update everything except 'visible' uniqueKeytip.keytip.visible = this.keytips[keytipIndex].keytip.visible; // Update keytip in this.keytips this.keytips = replaceElement(this.keytips, uniqueKeytip, keytipIndex); // Raise event EventGroup.raise(this, KeytipEvents.KEYTIP_UPDATED, { keytip: uniqueKeytip.keytip, uniqueID: uniqueKeytip.uniqueID }); } }; /** * Unregisters a keytip * * @param keytipToRemove - IKeytipProps of the keytip to remove * @param uniqueID - Unique ID of this keytip * @param persisted - T/F if this keytip should be persisted, default is false */ KeytipManager.prototype.unregister = function (keytipToRemove, uniqueID, persisted) { if (persisted === void 0) { persisted = false; } if (persisted) { // Remove keytip from this.persistedKeytips this.persistedKeytips = this.persistedKeytips.filter(function (uniqueKtp) { return uniqueKtp.uniqueID!== uniqueID; }); } else { // Remove keytip from this.keytips this.keytips = this.keytips.filter(function (uniqueKtp) { return uniqueKtp.uniqueID!== uniqueID; }); } var event = persisted? KeytipEvents.PERSISTED_KEYTIP_REMOVED : KeytipEvents.KEYTIP_REMOVED; EventGroup.raise(this, event, { keytip: keytipToRemove, uniqueID: uniqueID }); }; /** * Manual call to enter keytip mode */ KeytipManager.prototype.enterKeytipMode = function () { EventGroup.raise(this, KeytipEvents.ENTER_KEYTIP_MODE); }; /** * Manual call to exit keytip mode */ KeytipManager.prototype.exitKeytipMode = function () { EventGroup.raise(this, KeytipEvents.EXIT_KEYTIP_MODE); }; /** * Gets all IKeytipProps from this.keytips * * @returns {IKeytipProps[]} All keytips stored in the manager */ KeytipManager.prototype.getKeytips = function () { return this.keytips.map(function (uniqueKeytip) { return uniqueKeytip.keytip; }); }; /** * Adds the overflowSetSequence to the keytipProps if its parent keytip also has it * * @param keytipProps - Keytip props to add overflowSetSequence to if necessary * @returns {IKeytipProps} - Modified keytip props, if needed to be modified */ KeytipManager.prototype.addParentOverflow = function (keytipProps) { var fullSequence = keytipProps.keySequences.slice(); fullSequence.pop(); if (fullSequence.length!== 0) { var parentKeytip = find(this.getKeytips(), function (keytip) { return arraysEqual(fullSequence, keytip.keySequences); }); if (parentKeytip && parentKeytip.overflowSetSequence) { return tslib_1.__assign({}, keytipProps, { overflowSetSequence: parentKeytip.overflowSetSequence }); } } return keytipProps; }; /** * Public function to bind for overflow items that have a submenu * * @param overflowButtonSequences * @param keytipSequences */ KeytipManager.prototype.menuExecute = function (overflowButtonSequences, keytipSequences) { EventGroup.raise(this, KeytipEvents.PERSISTED_KEYTIP_EXECUTE, { overflowButtonSequences: overflowButtonSequences, keytipSequences: keytipSequences }); }; /** * Creates an IUniqueKeytip object * * @param keytipProps - IKeytipProps * @param uniqueID - Unique ID, will default to the next unique ID if not passed * @returns {IUniqueKeytip} IUniqueKeytip object */ KeytipManager.prototype._getUniqueKtp = function (keytipProps, uniqueID) { if (uniqueID === void 0) { uniqueID = getId(); } return { keytip: tslib_1.__assign({}, keytipProps), uniqueID: uniqueID }; }; KeytipManager._instance = new KeytipManager(); return KeytipManager; }()); export { KeytipManager }; //# sourceMappingURL=KeytipManager.js.map ======================= File: node_modules/@microsoft/sp-http/lib/resx-strings/bs-latn-ba.js ======================= <reponame>GhostMachineSoftware/SPFx_Connect2List define([], function() { var strings = { "_+tvmKa3YEOqWGKKXzwjtaw": { "additionalCredentialsWarning": "Za pravilan prikaz stranice neophodni su dodatni akreditivi.", "servicePrincipalNotAvaliableError": "Principal usluge web aplikacije sistema SharePoint Online još nije dodijeljen. Obratite se administratoru zakupca.", "graphClientInitializationError": "MSGraphClient se ne može biti konstruirati zbog nepoznate greške" } }; strings.default = strings; return strings; }); ======================= File: node_modules/office-ui-fabric-react/lib/components/Shimmer/index.js ======================= export * from './Shimmer'; export * from './Shimmer.base'; export * from './Shimmer.types'; export * from './ShimmerLine/ShimmerLine'; export * from './ShimmerLine/ShimmerLine.base'; export * from './ShimmerCircle/ShimmerCircle'; export * from './ShimmerCircle/ShimmerCircle.base'; export * from './ShimmerGap/ShimmerGap'; export * from './ShimmerGap/ShimmerGap.base'; export * from './ShimmerElementsGroup/ShimmerElementsGroup'; export * from './ShimmerElementsGroup/ShimmerElementsGroup.base'; //# sourceMappingURL=index.js.map ======================= File: node_modules/office-ui-fabric-react/lib/components/Facepile/FacepileButton.js ======================= <gh_stars>1-10 import * as tslib_1 from "tslib"; import * as React from'react'; import { BaseButton } from '../../Button'; import { BaseComponent, customizable, nullRender } from '../../Utilities'; import { getStyles } from './FacepileButton.styles'; var FacepileButton = /** @class */ (function (_super) { tslib_1.__extends(FacepileButton, _super); function FacepileButton() { var _this = _super!== null && _super.apply(this, arguments) || this; /** * Tell BaseComponent to bypass resolution of componentRef. */ _this._skipComponentRefResolution = true; return _this; } FacepileButton.prototype.render = function () { var _a = this.props, className = _a.className, styles = _a.styles, rest = tslib_1.__rest(_a, ["className", "styles"]); var customStyles = getStyles(this.props.theme, className, styles); return React.createElement(BaseButton, tslib_1.__assign({}, rest, { variantClassName: "ms-Button--facepile", styles: customStyles, onRenderDescription: nullRender })); }; FacepileButton = tslib_1.__decorate([ customizable('FacepileButton', ['theme','styles'], true) ], FacepileButton); return FacepileButton; }(BaseComponent)); export { FacepileButton }; //# sourceMappingURL=FacepileButton.js.map ======================= File: node_modules/office-ui-fabric-react/lib-amd/components/DocumentCard/DocumentCardStatus.styles.js ======================= define(["require", "exports", "../../Styling"], function (require, exports, Styling_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var GlobalClassNames = { root:'ms-DocumentCardStatus' }; exports.getStyles = function (props) { var className = props.className, theme = props.theme; var palette = theme.palette, fonts = theme.fonts; var classNames = Styling_1.getGlobalClassNames(GlobalClassNames, theme); return { root: [ classNames.root, fonts.medium, { margin: '8px 16px', color: palette.neutralPrimary, backgroundColor: palette.neutralLighter, height: '32px' }, className ] }; }; }); //# sourceMappingURL=DocumentCardStatus.styles.js.map ======================= File: node_modules/@microsoft/sp-core-library/lib/url/UrlUtilities.js ======================= <filename>node_modules/@microsoft/sp-core-library/lib/url/UrlUtilities.js<gh_stars>0 import * as lodash from '@microsoft/sp-lodash-subset'; import Validate from '../Validate'; var URL_PROTOCOL_REGEX = /^\w+\:\/\//; var BASE64_IMAGE_REGEX = /^data:(\w+\/\w+)?(;charset=[\w-]+)?(;base64)?,.*/i; var UrlUtilities = (function () { function UrlUtilities() { } UrlUtilities.resolve = function (url, baseUrl) { Validate.isNonemptyString(url, 'url'); Validate.isNonemptyString(baseUrl, 'baseUrl'); var isRelativeUrl = UrlUtilities.isRelativeUrl(url); if (isRelativeUrl) { return UrlUtilities.removeEndSlash(baseUrl) + "/" + UrlUtilities.removeLeadingSlash(url); } else { return url; } }; UrlUtilities.removeEndSlash = function (url) { return lodash.trimEnd(url, '/'); }; UrlUtilities.removeLeadingSlash = function (url) { return lodash.trimStart(url, '/'); }; UrlUtilities.convertToODataStringLiteral = function (value) { Validate.isNotNullOrUndefined(value, 'value'); value = value.replace(/'/g, "''"); value = "'" + value + "'"; return value; }; UrlUtilities.isDataUrl = function (url) { Validate.isNotNullOrUndefined(url, 'url'); return!!url.match(BASE64_IMAGE_REGEX); }; UrlUtilities.isRelativeUrl = function (url) { return!url.match(URL_PROTOCOL_REGEX); }; return UrlUtilities; }()); export default UrlUtilities; ======================= File: node_modules/office-ui-fabric-react/lib-commonjs/components/Toggle/Toggle.base.js ======================= "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var React = require("react"); var Utilities_1 = require("../../Utilities"); var Label_1 = require("../../Label"); var KeytipData_1 = require("../../KeytipData"); var getClassNames = Utilities_1.classNamesFunction(); var ToggleBase = /** @class */ (function (_super) { tslib_1.__extends(ToggleBase, _super); function ToggleBase(props) { var _this = _super.call(this, props) || this; _this._toggleButton = React.createRef(); _this._onClick = function (ev) { var _a = _this.props, disabled = _a.disabled, checkedProp = _a.checked, onChange = _a.onChange, onChanged = _a.onChanged, onClick = _a.onClick; var checked = _this.state.checked; if (!disabled) { // Only update the state if the user hasn't provided it. if (checkedProp === undefined) { _this.setState({ checked:!checked }); } if (onChange) { onChange(ev,!checked); } if (onChanged) { onChanged(!checked); } if (onClick) { onClick(ev); } } }; _this._warnMutuallyExclusive({ checked: 'defaultChecked' }); _this._warnDeprecations({ onAriaLabel: 'ariaLabel', offAriaLabel: undefined, onChanged: 'onChange' }); _this.state = { checked:!!(props.checked || props.defaultChecked) }; _this._id = props.id || Utilities_1.getId('Toggle'); return _this; } Object.defineProperty(ToggleBase.prototype, "checked", { /** * Gets the current checked state of the toggle. */ get: function () { return this.state.checked; }, enumerable: true, configurable: true }); ToggleBase.prototype.componentWillReceiveProps = function (newProps) { if (newProps.checked!== undefined) { this.setState({ checked:!!newProps.checked // convert null to false }); } }; ToggleBase.prototype.render = function () { var _this = this; var _a = this.props, _b = _a.as, RootType = _b === void 0? 'div' : _b, className = _a.className, theme = _a.theme, disabled = _a.disabled, keytipProps = _a.keytipProps, label = _a.label, ariaLabel = _a.ariaLabel, onAriaLabel = _a.onAriaLabel, offAriaLabel = _a.offAriaLabel, offText = _a.offText, onText = _a.onText, styles = _a.styles, inlineLabel = _a.inlineLabel; var checked = this.state.checked; var stateText = checked? onText : offText; var badAriaLabel = checked? onAriaLabel : offAriaLabel; var toggleNativeProps = Utilities_1.getNativeProps(this.props, Utilities_1.inputProperties, ['defaultChecked']); var classNames = getClassNames(styles, { theme: theme, className: className, disabled: disabled, checked: checked, inlineLabel: inlineLabel, onOffMissing:!onText &&!offText }); return (React.createElement(RootType, { className: classNames.root, hidden: toggleNativeProps.hidden }, label && (React.createElement(Label_1.Label, { htmlFor: this._id, className: classNames.label }, label)), React.createElement("div", { className: classNames.container }, React.createElement(KeytipData_1.KeytipData, { keytipProps: keytipProps, ariaDescribedBy: toggleNativeProps['aria-describedby'], disabled: disabled }, function (keytipAttributes) { return (React.createElement("button", tslib_1.__assign({}, toggleNativeProps, keytipAttributes, { className: classNames.pill, disabled: disabled, id: _this._id, type: "button", role: "switch" // ARIA 1.1 definition; "checkbox" in ARIA 1.0 , ref: _this._toggleButton, "aria-disabled": disabled, "aria-checked": checked, "aria-label": ariaLabel? ariaLabel : badAriaLabel, "data-is-focusable": true, onChange: _this._noop, onClick: _this._onClick }), React.createElement("div", { className: classNames.thumb }))); }), stateText && React.createElement(Label_1.Label, { className: classNames.text }, stateText)))); }; ToggleBase.prototype.focus = function () { if (this._toggleButton.current) { this._toggleButton.current.focus(); } }; ToggleBase.prototype._noop = function () { /* no-op */ }; return ToggleBase; }(Utilities_1.BaseComponent)); exports.ToggleBase = ToggleBase; //# sourceMappingURL=Toggle.base.js.map ======================= File: node_modules/@microsoft/api-extractor/lib/generators/ExcerptBuilder.js ======================= <reponame>GhostMachineSoftware/SPFx_Connect2List "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. Object.defineProperty(exports, "__esModule", { value: true }); const ts = require("typescript"); const Span_1 = require("../analyzer/Span"); class ExcerptBuilder { static build(options) { const span = new Span_1.Span(options.startingNode); const tokenRangesByNode = new Map(); for (const excerpt of options.nodesToCapture || []) { if (excerpt.node) { tokenRangesByNode.set(excerpt.node, excerpt.tokenRange); } } const excerptTokens = []; ExcerptBuilder._buildSpan(excerptTokens, span, { nodeToStopAt: options.nodeToStopAt, tokenRangesByNode, disableMergingForNextToken: false }); return excerptTokens; } static createEmptyTokenRange() { return { startIndex: 0, endIndex: 0 }; } static _buildSpan(excerptTokens, span, state) { if (state.nodeToStopAt && span.kind === state.nodeToStopAt) { return false; } if (span.kind === ts.SyntaxKind.JSDocComment) { // Discard any comments return true; } // Can this node start a excerpt? const capturedTokenRange = state.tokenRangesByNode.get(span.node); let excerptStartIndex = 0; if (capturedTokenRange) { // We will assign capturedTokenRange.startIndex to be the index of the next token to be appended excerptStartIndex = excerptTokens.length; state.disableMergingForNextToken = true; } if (span.prefix) { if (span.kind === ts.SyntaxKind.Identifier) { ExcerptBuilder._appendToken(excerptTokens, "Reference" /* Reference */, span.prefix, state); } else { ExcerptBuilder._appendToken(excerptTokens, "Content" /* Content */, span.prefix, state); } } for (const child of span.children) { if (!this._buildSpan(excerptTokens, child, state)) { return false; } } if (span.suffix) { ExcerptBuilder._appendToken(excerptTokens, "Content" /* Content */, span.suffix, state); } if (span.separator) { ExcerptBuilder._appendToken(excerptTokens, "Content" /* Content */, span.separator, state); } // Are we building a excerpt? If so, set its range if (capturedTokenRange) { capturedTokenRange.startIndex = excerptStartIndex; // We will assign capturedTokenRange.startIndex to be the index after the last token that was appended so far capturedTokenRange.endIndex = excerptTokens.length; state.disableMergingForNextToken = true; } return true; } static _appendToken(excerptTokens, excerptTokenKind, text, state) { if (text.length === 0) { return; } if (excerptTokenKind!== "Content" /* Content */) { excerptTokens.push({ kind: excerptTokenKind, text: text }); state.disableMergingForNextToken = false; } else { // If someone referenced this index, then we need to start a new token if (excerptTokens.length > 0 &&!state.disableMergingForNextToken) { // Otherwise, can we merge with the previous token? const previousToken = excerptTokens[excerptTokens.length - 1]; if (previousToken.kind === excerptTokenKind) { previousToken.text += text; return; } } excerptTokens.push({ kind: excerptTokenKind, text: text }); state.disableMergingForNextToken = false; } } } exports.ExcerptBuilder = ExcerptBuilder; //# sourceMappingURL=ExcerptBuilder.js.map ======================= File: node_modules/@microsoft/sp-component-base/lib/chunks/legacy-third-party-fabric-core/fabric-core-sass/Fabric.scss.js ======================= <gh_stars>0 require("./Fabric.css"); ======================= File: node_modules/office-ui-fabric-react/lib/components/Sticky/index.js ======================= <gh_stars>1-10 export * from './Sticky'; export * from './Sticky.types'; //# sourceMappingURL=index.js.map ======================= File: node_modules/office-ui-fabric-react/lib/components/MessageBar/index.js ======================= <gh_stars>1-10 export * from './MessageBar'; export * from './MessageBar.base'; export * from './MessageBar.types'; //# sourceMappingURL=index.js.map ======================= File: node_modules/office-ui-fabric-react/lib/utilities/groupedList/GroupedListUtility.js ======================= /** * Takes an array of groups and returns a count of the groups and all descendant groups. * @param groups - The array of groups to count. */ export var GetGroupCount = function (groups) { var total = 0; if (groups) { var remainingGroups = groups.slice(); var currentGroup = void 0; while (remainingGroups && remainingGroups.length > 0) { ++total; currentGroup = remainingGroups.pop(); if (currentGroup && currentGroup.children) { remainingGroups.push.apply(remainingGroups, currentGroup.children); } } } return total; }; //# sourceMappingURL=GroupedListUtility.js.map ======================= File: node_modules/office-ui-fabric-react/lib-amd/utilities/selection/interfaces.js ======================= define(["require", "exports"], function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.SELECTION_CHANGE = 'change'; var SelectionMode; (function (SelectionMode) { SelectionMode[SelectionMode["none"] = 0] = "none"; SelectionMode[SelectionMode["single"] = 1] = "single"; SelectionMode[SelectionMode["multiple"] = 2] = "multiple"; })(SelectionMode = exports.SelectionMode || (exports.SelectionMode = {})); var SelectionDirection; (function (SelectionDirection) { SelectionDirection[SelectionDirection["horizontal"] = 0] = "horizontal"; SelectionDirection[SelectionDirection["vertical"] = 1] = "vertical"; })(SelectionDirection = exports.SelectionDirection || (exports.SelectionDirection = {})); }); //# sourceMappingURL=interfaces.js.map ======================= File: node_modules/office-ui-fabric-react/lib/components/TeachingBubble/index.js ======================= <reponame>GhostMachineSoftware/SPFx_Connect2List export * from './TeachingBubble'; export * from './TeachingBubble.base'; export * from './TeachingBubbleContent'; export * from './TeachingBubbleContent.base'; //# sourceMappingURL=index.js.map ======================= File: node_modules/office-ui-fabric-react/lib-commonjs/Dialog.js ======================= <filename>node_modules/office-ui-fabric-react/lib-commonjs/Dialog.js "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); tslib_1.__exportStar(require("./components/Dialog/index"), exports); var index_1 = require("./components/Dialog/index"); exports.default = index_1.Dialog; //# sourceMappingURL=Dialog.js.map ======================= File: node_modules/office-ui-fabric-react/lib-amd/components/DocumentCard/DocumentCardPreview.js ======================= <filename>node_modules/office-ui-fabric-react/lib-amd/components/DocumentCard/DocumentCardPreview.js define(["require", "exports", "../../Utilities", "./DocumentCardPreview.base", "./DocumentCardPreview.styles"], function (require, exports, Utilities_1, DocumentCardPreview_base_1, DocumentCardPreview_styles_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.DocumentCardPreview = Utilities_1.styled(DocumentCardPreview_base_1.DocumentCardPreviewBase, DocumentCardPreview_styles_1.getStyles, undefined, { scope: 'DocumentCardPreview' }); }); //# sourceMappingURL=DocumentCardPreview.js.map ======================= File: node_modules/office-ui-fabric-react/lib/components/ContextualMenu/ContextualMenuItemWrapper/index.js ======================= export * from './ContextualMenuAnchor'; export * from './ContextualMenuButton'; export * from './ContextualMenuSplitButton'; export * from './ContextualMenuItemWrapper'; //# sourceMappingURL=index.js.map ======================= File: node_modules/office-ui-fabric-react/lib/components/Pivot/index.js ======================= export * from './Pivot'; export * from './Pivot.base'; export { PivotItem } from './PivotItem'; export * from './Pivot.types'; //# sourceMappingURL=index.js.map ======================= File: node_modules/@microsoft/api-extractor/lib/api/CompilerState.js ======================= "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. Object.defineProperty(exports, "__esModule", { value: true }); const path = require("path"); const ts = require("typescript"); const colors = require("colors"); const node_core_library_1 = require("@microsoft/node-core-library"); const ExtractorConfig_1 = require("./ExtractorConfig"); const TypeScriptMessageFormatter_1 = require("../analyzer/TypeScriptMessageFormatter"); /** * This class represents the TypeScript compiler state. This allows an optimization where multiple invocations * of API Extractor can reuse the same TypeScript compiler analysis. * * @public */ class CompilerState { constructor(properties) { this.program = properties.program; } /** * Create a compiler state for use with the specified `IExtractorInvokeOptions`. */ static create(extractorConfig, options) { let tsconfig = extractorConfig.overrideTsconfig; if (!tsconfig) { // If it wasn't overridden, then load it from disk tsconfig = node_core_library_1.JsonFile.load(extractorConfig.tsconfigFilePath); } const commandLine = ts.parseJsonConfigFileContent(tsconfig, ts.sys, extractorConfig.projectFolder); if (!commandLine.options.skipLibCheck && extractorConfig.skipLibCheck) { commandLine.options.skipLibCheck = true; console.log(colors.cyan('API Extractor was invoked with skipLibCheck. This is not recommended and may cause'+ 'incorrect type analysis.')); } CompilerState._updateCommandLineForTypescriptPackage(commandLine, options); const inputFilePaths = commandLine.fileNames.concat(extractorConfig.mainEntryPointFilePath); if (options && options.additionalEntryPoints) { inputFilePaths.push(...options.additionalEntryPoints); } // Append the entry points and remove any non-declaration files from the list const analysisFilePaths = CompilerState._generateFilePathsForAnalysis(inputFilePaths); const program = ts.createProgram(analysisFilePaths, commandLine.options); if (commandLine.errors.length > 0) { const errorText = TypeScriptMessageFormatter_1.TypeScriptMessageFormatter.format(commandLine.errors[0].messageText); throw new Error(`Error parsing tsconfig.json content: ${errorText}`); } return new CompilerState({ program }); } /** * Given a list of absolute file paths, return a list containing only the declaration * files. Duplicates are also eliminated. * * @remarks * The tsconfig.json settings specify the compiler's input (a set of *.ts source files, * plus some *.d.ts declaration files used for legacy typings). However API Extractor * analyzes the compiler's output (a set of *.d.ts entry point files, plus any legacy * typings). This requires API Extractor to generate a special file list when it invokes * the compiler. * * Duplicates are removed so that entry points can be appended without worrying whether they * may already appear in the tsconfig.json file list. */ static _generateFilePathsForAnalysis(inputFilePaths) { const analysisFilePaths = []; const seenFiles = new Set(); for (const inputFilePath of inputFilePaths) { const inputFileToUpper = inputFilePath.toUpperCase(); if (!seenFiles.has(inputFileToUpper)) { seenFiles.add(inputFileToUpper); if (!path.isAbsolute(inputFilePath)) { throw new Error('Input file is not an absolute path:'+ inputFilePath); } if (ExtractorConfig_1.ExtractorConfig.hasDtsFileExtension(inputFilePath)) { analysisFilePaths.push(inputFilePath); } } } return analysisFilePaths; } /** * Update the parsed command line to use paths from the specified TS compiler folder, if * a TS compiler folder is specified. */ static _updateCommandLineForTypescriptPackage(commandLine, options) { const DEFAULT_BUILTIN_LIBRARY = 'lib.d.ts'; const OTHER_BUILTIN_LIBRARIES = ['lib.es5.d.ts', 'lib.es6.d.ts']; if (options && options.typescriptCompilerFolder) { commandLine.options.noLib = true; const compilerLibFolder = path.join(options.typescriptCompilerFolder, 'lib'); let foundBaseLib = false; const filesToAdd = []; for (const libFilename of commandLine.options.lib || []) { if (libFilename === DEFAULT_BUILTIN_LIBRARY) { // Ignore the default lib - it'll get added later continue; } if (OTHER_BUILTIN_LIBRARIES.indexOf(libFilename)!== -1) { foundBaseLib = true; } const libPath = path.join(compilerLibFolder, libFilename); if (!node_core_library_1.FileSystem.exists(libPath)) { throw new Error(`lib ${libFilename} does not exist in the compiler specified in typescriptLibPackage`); } filesToAdd.push(libPath); } if (!foundBaseLib) { // If we didn't find another version of the base lib library, include the default filesToAdd.push(path.join(compilerLibFolder, 'lib.d.ts')); } if (!commandLine.fileNames) { commandLine.fileNames = []; } commandLine.fileNames.push(...filesToAdd); commandLine.options.lib = undefined; } } } exports.CompilerState = CompilerState; //# sourceMappingURL=CompilerState.js.map ======================= File: node_modules/office-ui-fabric-react/lib-amd/components/Persona/PersonaPresence/PersonaPresence.js ======================= define(["require", "exports", "../../../Utilities", "./PersonaPresence.base", "./PersonaPresence.styles"], function (require, exports, Utilities_1, PersonaPresence_base_1, PersonaPresence_styles_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * PersonaPresence is used to render an individual's presence. */ exports.PersonaPresence = Utilities_1.styled(PersonaPresence_base_1.PersonaPresenceBase, PersonaPresence_styles_1.getStyles, undefined, { scope: 'PersonaPresence' }); }); //# sourceMappingURL=PersonaPresence.js.map ======================= File: node_modules/office-ui-fabric-react/lib/components/Pivot/Pivot.js ======================= <reponame>GhostMachineSoftware/SPFx_Connect2List import { styled } from '../../Utilities'; import { PivotBase } from './Pivot.base'; import { getStyles } from './Pivot.styles'; /** * The Pivot control and related tabs pattern are used for navigating frequently accessed, * distinct content categories. Pivots allow for navigation between two or more content * views and relies on text headers to articulate the different sections of content. */ export var Pivot = styled(PivotBase, getStyles, undefined, { scope: 'Pivot' }); //# sourceMappingURL=Pivot.js.map ======================= File: node_modules/@microsoft/sp-webpart-workbench/lib/resx-strings/ro-ro.js ======================= define([], function() { var strings = { "_jP9TaPNRkCXWU4OplNcN+w": { "AriaWebPartOrSectionEnterTemplate": "{0}. Apăsați pe Enter pentru a naviga în {1}. Odată intrat, utilizați Alt+F10 pentru a accesa bara de instrumente, utilizați Alt+P pentru a muta focalizarea pe panoul de proprietăți și utilizați tasta Esc pentru a ieși din {1}. ", "CanvasZoneAriaGoToToolbar": "Apăsați pe Enter pentru a focaliza în interiorul părții web. După ce vă aflați în partea web, apăsați tasta Esc pentru a reveni la bara de instrumente.", "CanvasZoneAriaGoToWebPart": "Apăsați pe Enter pentru a accesa bara de instrumente a părții web. Apoi puteți apăsa tasta Esc pentru a reveni aici.", "CanvasZoneAriaWebpartName": "Parte web {0}", "ConfirmationDialogYes": "Da", "ConfirmationDialogNo": "Nu", "DeleteZoneConfirmationDialogMessage": "Sigur ștergeți această secțiune și tot ce se află în ea?", "DeleteConfirmationDialogTitle": "Confirmare ștergere", "DeleteConfirmationDialogMessage": "Sigur ștergeți această parte web?", "TextWebPartDisplayName": "Text", "ToolbarNavigationArrowKeys": "Utilizați tastele săgeată pentru a naviga în interiorul barei de instrumente.", "ToolboxAriaLoadingAlert": "Caseta de instrumente încarcă părțile web.", "ToolboxAriaLoadingFinishedAlert": "Caseta de instrumente a terminat de încărcat părțile web.", "ToolboxErrorMessage": "A apărut o eroare la preluarea părților web. Este posibil ca unele părți web să nu fie disponibile.", "ToolboxHintTitle": "Adăugați o parte web nouă", "ToolboxNavigationArrowKeys": "{0} Utilizați tastele săgeată la stânga sau la dreapta pentru a naviga. Utilizați tasta Enter pentru a adăuga partea web selectată.", "CanvasItems": "{0} elemente în bara de instrumente.||{0} element în bara de instrumente.||{0} de elemente în bara de instrumente.", "CanvasItemsInterval": "0,2-19,*02-*19||1||*00,*01,*20-99", "ToolboxSectionHeader": "Aspect secțiune", "ToolboxOneColumnPart": "O coloană", "ToolboxTwoColumnPart": "Două coloane", "ToolboxThreeColumnPart": "Trei coloane", "ToolboxOneThirdRightColumnPart": "Coloană cu o treime la dreapta", "ToolboxOneThirdLeftColumnPart": "Coloană cu o treime la stânga", "ToolboxFullWidthColumnPart": "Coloană cu lățime completă", "ToolboxVerticalColumnPart": "Coloană verticală", "ToolboxVerticalColumnToolTipText": "Nu se poate adăuga o coloană verticală, deoarece există deja una sau există o coloană cu lățime completă pe pagină.", "ToolboxFullWidthColumnTooltipText": "Nu se poate adăuga o coloană cu lățime completă, deoarece există o coloană verticală pe pagină.", "SectionPropertyPaneTitle": "Secțiune", "SectionPropertyPaneColumnGroupName": "Opțiuni de aspect", "ToolbarSelectZone": "Selectați secțiunea", "DragIconFallbackRTEText": "Text", "DragZoneHandleTitle": "Apăsați pe Enter sau bara de spațiu pentru a intra în modul de mutare", "DragZoneMoveStarted": "Apăsați tasta săgeată în sus pentru a vă deplasa în sus și tasta săgeată în jos pentru a vă deplasa în jos. Apăsați pe Esc pentru a anula deplasarea. ", "DragZoneMoveComplete": "Partea web a fost mutată de la {0} la {1}. ", "DragZoneMoveCompleteZone": "Secțiunea a fost mutată de la {0} la {1}", "DragZoneMoveCancelled": "Mutarea a fost anulată.", "DragZoneMoveNotAllowedAriaLabel": "Nu se poate muta mai departe în această direcție sau mutarea nu este permisă la această secțiune", "DragZoneMoveNotAllowed": "Mutare nepermisă", "DragZoneMoveInsideLevelControl": "Poziția {0}", "DragZoneMoveInsideLevelSection": "Coloana {0}, poziția {1}", "DragZoneMoveInsideLevelZone": "Secțiunea {0}, coloana {1}, poziția {2}", "WebPartAriaLabel": "parte web", "SectionContextualAriaLabel": "{0}, secțiunea {1} care conține {2}", "SectionAriaLabel": "secțiune", "WebPartsInSectionLabel": "{0}, {1}", "ToolboxHintSectionTitleOnlyLayouts": "Adăugați o nouă secțiune", "ToolboxHintTitleWithLayout": "Adăugați o parte web nouă în {0}", "ToolboxHintColumnOne": "coloana unu", "ToolboxHintColumnTwo": "coloana doi", "ToolboxHintColumnThree": "coloana trei", "EmptySectionAriaLabel": "nicio parte web", "SectionPositionAriaLabel": "Secțiunea {0} din {1}", "CloseButtonAriaLabel": "Închidere", "DeleteConfirmationLabel": "{0} a fost ștearsă.", "NarrowModeDialogTitle": "Lărgiți fereastra browserului", "NarrowModeDialogSubtitle": "Editarea nu este disponibilă într-o fereastră de browser îngustă. Lărgiți fereastra pentru a continua editarea.", "DialogDescription": "Casetă de dialog {0} {1}", "SectionBackgroundPropertyColumnGroupName": "Fundal secțiune", "SectionBackgroundNeutralButtonLabel": "Neutru", "SectionBackgroundSoftButtonLabel": "Moale", "SectionBackgroundStrongButtonLabel": "Robust", "SectionBackgroundNoneButtonLabel": "Fără", "CanvasVerticalSectionZoneLabel": "Secțiune cu aspect de coloană verticală", "YammerHighlightsWebpartTitle": "Evidențieri", "ToolbarDuplicateTitle": "Dublați partea" }, "_n7GTqRbrtzGOgRYtCYt3Jw": { "FormattingBarMoreButtonTitle": "Mai multe", "TextWebPartPlaceholder": "Adăugați textul aici." }, "_EJ1q3VoG+8ZXJZ4MxzV0eA": { "WebpartToolbarConfigButtonTitle": "Editați partea web", "WebpartToolbarMoveButtonTitle": "Mutați partea web", "WebpartToolbarDeleteButtonTitle": "Ștergeți partea web", "ToolboxHintTitleWithLayout": "Adăugați o parte web nouă în {0}", "ToolboxHintColumnOne": "coloana unu", "ToolboxHintColumnTwo": "coloana doi", "ToolboxHintColumnThree": "coloana trei" }, "_kfkx9h4IuXbYoZ4SdLEjrQ": { "ZoneToolbarConfigButtonTitle": "Editați secțiunea", "ZoneToolbarMoveButtonTitle": "Mutați secțiunea", "ZoneToolbarDeleteButtonTitle": "Ștergeți secțiunea", "ToolboxNavigationArrowKeys": "{0} Utilizați tastele săgeată la stânga sau la dreapta pentru a naviga. Utilizați tasta Enter pentru a adăuga partea web selectată." }, "_bKMsmDAqUqbOL6h9rxYuIw": { "FormattingBarClearFormattingButtonTitle": "Ștergeți toată formatarea", "FormattingBarNormalTextButtonTitle": "Text normal", "FormattingBarHeading2ButtonTitle": "Titlu 1", "FormattingBarHeading3ButtonTitle": "Titlu 2", "FormattingBarHeading4ButtonTitle": "Titlu 3", "FormattingBarQuoteButtonTitle": "Citat extras", "ToolbarNavigationArrowKeys": "Utilizați tastele săgeată pentru a naviga în interiorul barei de instrumente.", "RTESettingsText": "Formatarea textului și tabelului", "FontDropDownText": "Stil font", "ParagraphGroupText": "Paragraf", "FontSizeDropDownLabel": "Dimensiune font", "TableGroup": "Tabel", "InsertAndDeleteGroupLabel": "Inserare și ștergere", "FontColorLabel": "Culoare font", "StandardColorLabel": "Culori standard", "DefaultColorLabel": "Automat", "RedDarkLabel": "Bordo", "RedLabel": "Roșu", "YellowLabel": "Galben", "GreenLightLabel": "Verde deschis", "GreenLabel": "Verde", "GreenDarkLabel": "Verde închis", "BlueLightLabel": "Albastru deschis", "BlueLabel": "Albastru", "BlueDarkLabel": "Albastru închis", "PurpleLabel": "Mov", "HightlightLabel": "Culoare de evidențiere", "HightlightColorsLabel": "Evidențiere culori", "PinkLabel": "Roz", "OrangeLabel": "Portocaliu", "RemoveHighlightColor": "Fără culoare", "HyperlinkGroupLabel": "Hyperlink", "TealLabel": "Albastru verzui", "MagentaLabel": "Fucsia", "AquaLabel": "Bleu", "MaroonLabel": "Bordo", "GoldLabel": "Auriu", "GreyLabel": "Gri", "DarkGreyLabel": "Gri închis", "BlackLabel": "Negru", "ThemeColorGroupLabel": "Culori temă", "ThemeDarkerLabel": "Temă mai întunecat", "ThemeDarkLabel": "Temă întunecat", "ThemeDarkAltLabel": "Temă alternant întunecat", "ThemePrimaryLabel": "Temă principală", "ThemeSecondaryLabel": "Temă secundară", "NeutralDarkLabel": "Întunecat neutru", "NeutralPrimaryLabel": "Principal neutru", "NeutralPrimaryAltLabel": "Alternativă neutră - principal", "NeutralSecondaryLabel": "Secundar neutru", "NeutralTertiaryLabel": "Terțiar neutru", "TableStylesGroupLabel": "Stiluri tabel", "AlignTableGroupLabel": "Aliniere tabel", "FormattingBarPreButtonTitle": "Monospațiat" }, "_/GZrHjuQO4erDQbBRI2XSA": { "DialogTitle": "Inserare link", "UrlTextFieldLabel": "Adresă", "UrlTextFieldAriaLabel": "Adresa web la care se creează linkul", "UrlTextFieldError": "Acest tip de link nu este acceptat.", "TitleTextFieldLabel": "Text de afișat", "RecentPagesLabel": "Cele mai recente pagini de pe acest site", "SearchForPagesLabel": "Paginile acestui site care se potrivesc căutării dvs.", "RecentSpacesLabel": "Most recent spaces on this site", "SearchForSpacesLabel": "Spaces on this site that match your search", "NoResultLabel": "Niciun element nu corespunde căutării dvs.", "TryAgainLabel": "Încercați alt cuvânt cheie", "OpenLinkInNewTabLabel": "Deschideți linkul într-o filă nouă", "SaveButtonLabel": "Salvare", "CancelButtonLabel": "Anulare", "UnlinkButtonLabel": "Eliminare link", "TitleSuggestionsColumnName": "Titlu", "EditorSuggestionsColumnName": "Modificat de", "ModifiedSuggestionsColumnName": "Modificat", "PageContentContainsSearchText": "„{0}” găsit în conținutul paginii", "CurrentPage": "(pagina curentă)", "SearchTextFieldLabel": "Căutare", "SearchPagesTextFieldPlaceholder": "Introduceți cuvinte cheie pentru a căuta pagini de pe acest site", "SearchSpacesTextFieldPlaceholder": "Enter keywords to search for spaces on this site", "DialogAriaDescription": "Inserați un link la o pagină din site-ul curent sau la o pagină dintr-un alt site.", "SuggestionsListAriaLabel": "Selectați o pagină din lista {0}. Apăsați tastele săgeată în sus și în jos pentru a naviga printre pagini. Apăsați tasta spațiu pentru a selecta o pagină. Când este selectată o pagină, linkul la pagină va fi utilizat în caseta de intrare Link și, dacă nu există text în caseta de intrare Text de afișat, va fi utilizat titlul de pagină.", "SaveButtonDisabledScreenReaderAlert": "Butonul Salvare nu este disponibil, deoarece s-a introdus o adresă web nevalidă.", "SaveButtonEnabledScreenReaderAlert": "Butonul Salvare este disponibil.", "PageIsSelectedScreenReaderAlert": "Pagina {0} este selectată.", "IsSearching": "Se caută...", "SearchResultsShowing": "Rezultatele căutării sunt afișate. Apăsați pe Tab pentru a accesa lista cu rezultatele de căutare.", "RecentPagesShowing": "Se afișează o listă de pagini recente. Apăsați pe Tab pentru a accesa lista Pagini recente." }, "_4SOrKBlkyRLkXWcT6txoow": { "ToolboxSearchAccessibleLabelTemplate": "Tastați aici pentru a căuta o parte web. {0}", "ToolboxSearchEscapeAccessibleLabel": "Apăsați pe Escape pentru a goli căutarea existentă.", "ToolboxSearchLabel": "Căutare" }, "_6tOZemhV08aF1IgNDNeiwQ": { "ToolboxGroupNameFullWidth": "Puteți adăuga una dintre aceste părți web la această coloană cu lățime completă" }, "_NS+5Kf9zpnH1/LStsp+Tfw": { "ToolboxCategoryTextMediaAndContent": "Text, media și conținut", "ToolboxCategoryDiscovery": "Descoperire", "ToolboxCategoryCommunicationAndCollaboration": "Comunicare și colaborare", "ToolboxCategoryPlanningAndProcess": "Planificare și proces", "ToolboxCategoryBusinessIntelligence": "Afaceri si inteligență", "ToolboxCategorySiteTools": "Instrumente site", "ToolboxCategoryConnectors": "Conectori", "ToolboxCategoryOther": "Altele", "ToolboxGroupNameFeatured": "Deosebite", "ToolboxGroupNameAlphabetical": "Toate de la A la Z", "ToolboxGroupNameSection": "Aspect secțiune" }, "_RRzf46hnc4+fBX8RHyocNg": { "TextWebPartDisplayName": "Text", "TextWebpartDescription": "Adăugați și formatați textul" }, "_2TT4IG31kAjRqhD0h5kPOg": { "ToolboxGroupSeeAllButtonLabel": "Vedeți tot", "ToolboxGroupSeeAllButtonAriaLabel": "Vedeți toate părțile web din {0}.", "ToolboxGroupAriaLabel": "Lista {0}. Utilizați tastele săgeată la stânga și la dreapta pentru a vă deplasa în listă." }, "_z2ZwCbA+UxeGBoG5w1HCOA": { "SearchResultAlert": "Există {0} elemente în caseta de instrumente.||Există {0} element în caseta de instrumente.||Există {0} de elemente în caseta de instrumente.", "SearchResultAlertIntervals": "0,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,*02,*03,*04,*05,*06,*07,*08,*09,*10,*11,*12,*13,*14,*15,*16,*17,*18,*19||1|-" }, "_WVn4QXYnL8WpGCqr2C9ySA": { "ToolboxCategoryAllCategory": "Toate după categorie", "ToolboxCategorySortingCategory": "Toate de la A la Z", "ToolboxCategorySearchResults": "Rezultate căutare", "ToolboxCollapseButtonDescription": "Restaurați la dimensiunea originală", "NoResultLabel": "Niciun element nu se potrivește căutării", "TryAgainLabel": "Încercați un alt cuvânt cheie", "LargeToolboxAriaTitle": "Caseta de instrumente pentru părți web extinsă.", "ToolboxCollapseButtonAriaLabel": "Restrângere.", "DropDownMenuAriaLabel": "Se afișează părțile web de la categoria {0}.", "SwitchCategoryAlert": "Schimbat cu {0}.", "BackButtonAriaLabel": "Reveniți la vizualizarea precedentă." }, "_CZsUWMvZilAKKAfwQSdzKQ": { "ToolboxExpandButtonTitle": "Extindeți pentru a vedea mai multe părți web", "ToolboxNoItemsFound": "Nu am găsit nimic care să corespundă căutării dvs." }, "_acoNwVeh/QF9PsLoQfUb2A": { "FormattingBarAlignCenterButtonTitle": "Centru", "FormattingBarAlignLeftButtonTitle": "Aliniere la stânga", "FormattingBarAlignRightButtonTitle": "Aliniere la dreapta", "FormattingBarBoldButtonTitle": "Aldin ({0}+B)", "FormattingBarBulletListButtonTitle": "Listă cu marcatori", "FormattingBarClearFormattingButtonTitle": "Ștergeți toată formatarea", "FormattingBarConfirmAction": "S-a efectuat acțiunea {0}.", "FormattingBarConfirmActionOnSelection": "S-a efectuat acțiunea {0} pe textul selectat: {1}", "FormattingBarNormalTextButtonTitle": "Text normal", "FormattingBarHeading2ButtonTitle": "Titlu 1", "FormattingBarHeading3ButtonTitle": "Titlu 2", "FormattingBarHeading4ButtonTitle": "Titlu 3", "FormattingBarQuoteButtonTitle": "Citat extras", "FormattingBarItalicButtonTitle": "Cursiv ({0}+I)", "FormattingBarLinkButtonTitle": "Hyperlink ({0}+K)", "FormattingBarNumberedListButtonTitle": "Listă numerotată", "FormattingBarUnderlineButtonTitle": "Subliniere ({0}+U)", "FormattingBarUnlinkButtonTitle": "Eliminare link", "UndoButtonTitle": "Anulare ({0}+Z)", "RedoButtonTitle": "Refacere ({0}+Y)", "FormattingBarAccessibleLabel": "Formatare", "LinkDialogErrorNotSupportedLink": "Acest tip de link nu este acceptat.", "LinkDialogTextFieldAriaLabel": "Adresa web pentru care se creează linkul", "LinkDialogTextFieldLabel": "Adresa web:", "LinkDialogDisplayTextFieldLabel": "Text de afișat:", "LinkDialogTitle": "Inserare link", "RichTextEditorAriaLabel": "Editor text. Utilizați Alt+F10 pentru a accesa barele de instrumente.", "RichTextEditorTitle": "Editor text", "RichTextEditorIframeTitle": "{0} {1}", "RichTextLinkDialogCancelButtonLabel": "Anulare", "RichTextLinkDialogSaveButtonLabel": "Salvare", "RichTextNavigationAltF10Keys": "{0} {1}", "ToolbarNavigationArrowKeys": "Utilizați tastele săgeată pentru a naviga în interiorul barei de instrumente.", "ToolbarNavigationTabKeys": "Utilizați tasta Tab pentru a comuta între barele de instrumente.", "ToolbarNavigationShiftTabKey": "Utilizați shift + tab pentru a naviga înapoi la caseta text", "ImagesInTableNotSupported": "Nu puteți insera o imagine în interiorul unui tabel. Încercați să lipiți imaginea în afara tabelului.", "MultiImagePasteInIENotSupported": "Nu se pot lipi imagini care se află într-un tabel sau învelite cu text. Copiați doar imaginea, fără tabel sau text și încercați din nou.", "CloseWarningText": "Închideți avertizarea {0} ", "LoadingText": "Se lipește...", "AddRowAboveText": "Inserare deasupra", "AddRowBelowText": "Inserare dedesubt", "DeleteRowText": "Ștergere rând", "AddColumnLeftText": "Inserare la stânga", "AddColumnRightText": "Inserare la dreapta", "AddRowAboveShortcutText": "{0} ({1}+Shift+A)", "AddRowBelowShortcutText": "{0} ({1}+Shift+Z)", "DeleteRowShortcutText": "{0} ({1}+Shift+D)", "StrikeThroughButtonLabel": "Tăiere text cu o linie", "SuperscriptButtonLabel": "Exponent", "SubscriptButtonLabel": "Indice", "JustifyButtonLabel": "Aliniere stânga-dreapta", "IncreaseIndentButtonLabel": "Măriți indentul", "DecreaseIndentButtonLabel": "Micșorați indentul", "FontSizeDropDownLabel": "Dimensiune font", "TableTitle": "Tabel", "TableButtonLabel": "Inserare tabel", "InsertRowBeforeButtonLabel": "Inserare deasupra", "InsertRowAfterButtonLabel": "Inserare dedesubt", "InsertColumnLeftButtonLabel": "Inserare la stânga", "InsertColumnRightButtonLabel": "Inserare la dreapta", "DeleteRowButtonLabel": "Ștergere rând", "DeleteColumnButtonLabel": "Ștergere coloană", "DeleteTableButtonLabel": "Ștergere tabel", "FontColorLabel": "Culoare font", "HightlightLabel": "Culoare de evidențiere", "SimpleTableButtonLabel": "Simplu", "TableWithHeaderBorderLabel": "Antet subtil", "TableWithFilledHeaderLabel": "Antet", "TableWithBandedRowsLabel": "Rânduri alternante", "TableWithBandedRowsAndColumnsLabel": "Antet coloană", "SimpleTableButtonThemeLabel": "Simplu, având culori tematice", "TableWithHeaderBorderThemeLabel": "Antet subtil având culori tematice", "TableWithFilledHeaderThemeLabel": "Antet având culori tematice", "TableWithBandedRowsThemeLabel": "Rânduri alternante având culori tematice", "TableWithBandedRowsAndColumnsThemeLabel": "Antet de coloană având culori tematice", "AlignTableLeftLabel": "Aliniere tabel la stânga", "AlignTableCenterLabel": "Aliniere la centru tabel", "AlignTableRightLabel": "Aliniere tabel la dreapta", "RTEPagePickerSaveAction": "Linkul {0} este adăugat.", "RTEPagePickerUnlinkAction": "Linkul {0} este eliminat.", "FormattingBarPreButtonTitle": "Monospațiat", "CommandShortcutOnMac": "⌘", "ControlShortcutOnWin": "Ctrl" }, "_NAR8NFw8cblGJm9t5CjqOw": { "SuccessfullyLoadedText": "Manifestele de depanare au fost încărcate cu succes.", "ErrorLoadingText": "Nu a reușit încărcarea manifestelor de depanare: {0}" }, "_vd/LT/qfiQhbHFfeM1GtlA": { "FetchFailedError": "Fetching webpats failed with error \"{0}\". Render of a cached workbench may fail." }, "_8EVKOH1av6NjR/ZNfdafrw": { "WebPartData": "Web Part Data", "ClassicPages": "Pagini clasice", "ModernPages": "Pagini moderne", "Close": "Închidere", "WebPartDataHelpInfoLink": "Learn about provisioning SharePoint assets from your SharePoint client-side web part" }, "_FQya7ZjwIyrOEutOa+omIA": { "Title": "Avertisment", "SubText": "Partea web nu va apărea în caseta de instrumente. Asigurați-vă că „gulp serve” rulează într-un proiect de parte web. Reîmprospătați pagina după ce „gulp serve” rulează.", "OkButtonText": "OK", "ClickHerePrefix": "Faceți clic ", "ClickHereLink": "aici", "ClickHereSuffix": " pentru mai multe informații." }, "_1JArBGDet5Uj9pJOV/9sFw": { "UrlTextBoxPlaceholder": "Introduceți un URL pentru a vizualiza instrumentul Previzualizare mobilă.", "ScreenReaderMobilePreviewEntered": "Ați accesat instrumentul Previzualizare mobilă. Dacă doriți să previzualizați o altă pagină, introduceți adresa URL în câmpul de text URL. Pentru a închide instrumentul și a reveni la bancul de lucru, apăsați pe Escape.", "ScreenReaderDevicePickerEntered": "Utilizați tastele săgeată la stânga și la dreapta pentru a alege un dispozitiv pentru a modifica dimensiunea ecranului de previzualizare.", "ScreenReaderDevicePickerSelectionChanged": "Apăsați pe Enter pentru a alege acest dispozitiv.", "Width": "Lățime", "Height": "Înălțime" }, "_IusqdbcSoVYQiit3+QRSxw": { "Office365Title": "Office 365", "SharePointWorkbenchTitle": "Banc de lucru SharePoint", "ScreenReaderDisplayModeSwitchToEditMode": "S-a comutat de la modul de previzualizare la modul de editare.", "ScreenReaderDisplayModeSwitchToReadMode": "S-a comutat de la modul de editare la modul de previzualizare." }, "_nCtJlVOXBHa59LgYtajnjA": { "Save": "Salvare", "SaveAltText": "Se utilizează pentru a salva starea actuală a bancului de lucru.", "Discard": "Renunțare", "DiscardAltText": "Se utilizează pentru a renunța la starea actuală a bancului de lucru.", "Mobile": "Mobil", "MobleAltText": "Se utilizează pentru a deschide instrumentul de previzualizare mobilă pentru un telefon mobil.", "Tablet": "Tabletă", "TabletAltText": "Se utilizează pentru a deschide instrumentul de previzualizare mobilă pentru o tabletă.", "Preview": "Previzualizare", "PreviewAltText": "Se utilizează pentru a comuta de la modul de editare la modul de previzualizare.", "Edit": "Editare", "EditAltText": "Se utilizează pentru a comuta la modul de editare.", "WebPartData": "Web part data", "WebPartDataAltText": "Display the serialized web part data." } }; strings.default = strings; return strings; }); ======================= File: node_modules/office-ui-fabric-react/lib-amd/components/Coachmark/Beak/Beak.js ======================= define(["require", "exports", "tslib", "react", "../../../Utilities", "./Beak.styles", "../../../utilities/positioning"], function (require, exports, tslib_1, React, Utilities_1, Beak_styles_1, positioning_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.BEAK_HEIGHT = 10; exports.BEAK_WIDTH = 18; var Beak = /** @class */ (function (_super) { tslib_1.__extends(Beak, _super); function Beak(props) { return _super.call(this, props) || this; } Beak.prototype.render = function () { var _a = this.props, left = _a.left, top = _a.top, bottom = _a.bottom, right = _a.right, color = _a.color, _b = _a.direction, direction = _b === void 0? positioning_1.RectangleEdge.top : _b; var svgHeight; var svgWidth; if (direction === positioning_1.RectangleEdge.top || direction === positioning_1.RectangleEdge.bottom) { svgHeight = exports.BEAK_HEIGHT; svgWidth = exports.BEAK_WIDTH; } else { svgHeight = exports.BEAK_WIDTH; svgWidth = exports.BEAK_HEIGHT; } var pointOne; var pointTwo; var pointThree; var transform; switch (direction) { case positioning_1.RectangleEdge.top: default: pointOne = exports.BEAK_WIDTH / 2 + ", 0"; pointTwo = exports.BEAK_WIDTH + ", " + exports.BEAK_HEIGHT; pointThree = "0, " + exports.BEAK_HEIGHT; transform = 'translateY(-100%)'; break; case positioning_1.RectangleEdge.right: pointOne = "0, 0"; pointTwo = exports.BEAK_HEIGHT + ", " + exports.BEAK_HEIGHT; pointThree = "0, " + exports.BEAK_WIDTH; transform = 'translateX(100%)'; break; case positioning_1.RectangleEdge.bottom: pointOne = "0, 0"; pointTwo = exports.BEAK_WIDTH + ", 0"; pointThree = exports.BEAK_WIDTH / 2 + ", " + exports.BEAK_HEIGHT; transform = 'translateY(100%)'; break; case positioning_1.RectangleEdge.left: pointOne = exports.BEAK_HEIGHT + ", 0"; pointTwo = "0, " + exports.BEAK_HEIGHT; pointThree = exports.BEAK_HEIGHT + ", " + exports.BEAK_WIDTH; transform = 'translateX(-100%)'; break; } var getClassNames = Utilities_1.classNamesFunction(); var classNames = getClassNames(Beak_styles_1.getStyles, { left: left, top: top, bottom: bottom, right: right, height: svgHeight + "px", width: svgWidth + "px", transform: transform, color: color }); return (React.createElement("div", { className: classNames.root, role: "presentation" }, React.createElement("svg", { height: svgHeight, width: svgWidth, className: classNames.beak }, React.createElement("polygon", { points: pointOne +'' + pointTwo +'' + pointThree })))); }; return Beak; }(Utilities_1.BaseComponent)); exports.Beak = Beak; }); //# sourceMappingURL=Beak.js.map ======================= File: node_modules/office-ui-fabric-react/lib/index.js ======================= <filename>node_modules/office-ui-fabric-react/lib/index.js export * from './ActivityItem'; export * from './Autofill'; export * from './Breadcrumb'; export * from './Button'; export * from './Calendar'; export * from './Callout'; export * from './Check'; export * from './Checkbox'; export * from './ChoiceGroup'; export * from './ChoiceGroupOption'; export * from './Coachmark'; export * from './Color'; export * from './ColorPicker'; export * from './ComboBox'; export * from './CommandBar'; export * from './ContextualMenu'; export * from './DatePicker'; export * from './DetailsList'; export * from './Dialog'; export * from './Divider'; export * from './DocumentCard'; export * from './Dropdown'; export * from './ExtendedPicker'; export * from './Fabric'; export * from './Facepile'; export * from './FloatingPicker'; export * from './FocusTrapZone'; export * from './FocusZone'; export * from './Grid'; export * from './GroupedList'; export * from './HoverCard'; export * from './Icon'; export * from './Icons'; export * from './Image'; export * from './Keytip'; export * from './KeytipData'; export * from './KeytipLayer'; export * from './Label'; export * from './Layer'; export * from './Link'; export * from './List'; export * from './MarqueeSelection'; export * from './MessageBar'; export * from './Modal'; export * from './Nav'; export * from './OverflowSet'; export * from './Overlay'; export * from './Panel'; export * from './Persona'; export * from './PersonaCoin'; // export * from './PersonaPresence'; (Exported as part of Persona) export * from './Pickers'; export * from './Pivot'; export * from './Popup'; export * from './PositioningContainer'; export * from './ProgressIndicator'; export * from './Rating'; export * from './ResizeGroup'; export * from './ScrollablePane'; export * from './SearchBox'; export * from './SelectableOption'; export * from './SelectedItemsList'; export * from './Selection'; export * from './Shimmer'; export * from './ShimmeredDetailsList'; export * from './Slider'; export * from './SpinButton'; export * from './Spinner'; export * from './Stack'; export * from './Sticky'; export * from './Styling'; export * from './SwatchColorPicker'; export * from './TeachingBubble'; export * from './TextField'; export * from './ThemeGenerator'; export * from './Toggle'; export * from './Tooltip'; export * from './Utilities'; import './version'; //# sourceMappingURL=index.js.map ======================= File: node_modules/office-ui-fabric-react/lib/components/SearchBox/examples/SearchBox.Examples.scss.js ======================= /* tslint:disable */ import { loadStyles } from '@microsoft/load-themed-styles'; loadStyles([{ "rawString": ".ms-SearchBoxExample.ms-SearchBox{margin:0 0 10px 0}\n" }]); //# sourceMappingURL=SearchBox.Examples.scss.js.map ======================= File: node_modules/@microsoft/sp-dynamic-data/lib/DynamicDataManager.js ======================= import { ServiceKey, SPEvent, Text, Validate, _SPEventManager } from '@microsoft/sp-core-library'; import { _LogSource, _TraceLogger, _QosMonitor } from '@microsoft/sp-diagnostics'; import strings from './loc/Strings.resx'; var ANY_PROPERTY_EVENT_PREFIX = 'DynamicData_AnyPropertyChanged'; var PROPERTY_EVENT_PREFIX = 'DynamicData_PropertyChanged'; var ALL_PROPERTIES_EVENT_PREFIX = 'DynamicData_AllPropertiesChanged'; var SOURCES_CHANGED_EVENT_NAME = 'DynamicData_SourcesChanged'; var EVENT_NAME_SEPARATOR = '_'; var QOS_MONITOR_PREFIX = 'DynamicData.DynamicDataManager'; var LOG_SOURCE = _LogSource.create('DynamicDataManager'); var DynamicDataManager = (function () { function DynamicDataManager(serviceScope) { this._sources = new Map(); this._sourcesChangedEvent = new SPEvent(SOURCES_CHANGED_EVENT_NAME); this._getPropertyChangedEventName = this._getPropertyChangedEventName.bind(this); } Object.defineProperty(DynamicDataManager.prototype, "sourcesChangedEvent", { get: function () { return this._sourcesChangedEvent; }, enumerable: true, configurable: true }); DynamicDataManager.prototype.notifySourceChanged = function (sourceId) { var qosMonitor = new _QosMonitor(QOS_MONITOR_PREFIX + '.notifySourceChanged'); try { Validate.isNonemptyString(sourceId,'sourceId'); _SPEventManager.instance.raiseEvent(this._getAllPropertiesChangedEventName(sourceId), {}); _SPEventManager.instance.raiseEvent(this._getAnyPropertyChangedEventName(sourceId), {}); qosMonitor.writeSuccess(); } catch (e) { qosMonitor.writeUnexpectedFailure(e); throw e; } }; DynamicDataManager.prototype.notifyPropertyChanged = function (sourceId, propertyId) { var qosMonitor = new _QosMonitor(QOS_MONITOR_PREFIX + '.notifyPropertyChanged'); try { Validate.isNonemptyString(sourceId,'sourceId'); Validate.isNonemptyString(propertyId, 'propertyId'); _SPEventManager.instance.raiseEvent(this._getPropertyChangedEventName(sourceId, propertyId), {}); _SPEventManager.instance.raiseEvent(this._getAnyPropertyChangedEventName(sourceId), {}); qosMonitor.writeSuccess(); } catch (e) { qosMonitor.writeUnexpectedFailure(e); throw e; } }; DynamicDataManager.prototype.registerSourceChanged = function (sourceId, observer, callback) { var qosMonitor = new _QosMonitor(QOS_MONITOR_PREFIX + '.registerSourceChanged'); try { Validate.isNonemptyString(sourceId,'sourceId'); Validate.isNotNullOrUndefined(observer, 'observer'); Validate.isNotNullOrUndefined(callback, 'callback'); if (!this._sources.has(sourceId)) { throw new Error(Text.format(strings.dynamicDataManagerSourceDoesntExist, sourceId)); } _SPEventManager.instance.registerEvent(this._getAllPropertiesChangedEventName(sourceId), observer, callback); _SPEventManager.instance.registerEvent(this._getAnyPropertyChangedEventName(sourceId), observer, callback); qosMonitor.writeSuccess(); } catch (e) { qosMonitor.writeUnexpectedFailure(e); throw e; } }; DynamicDataManager.prototype.unregisterSourceChanged = function (sourceId, observer, callback) { var qosMonitor = new _QosMonitor(QOS_MONITOR_PREFIX + '.unregisterSourceChanged'); try { Validate.isNonemptyString(sourceId,'sourceId'); Validate.isNotNullOrUndefined(observer, 'observer'); Validate.isNotNullOrUndefined(callback, 'callback'); if (!this._sources.has(sourceId)) { throw new Error(Text.format(strings.dynamicDataManagerSourceDoesntExist, sourceId)); } _SPEventManager.instance.unregisterEvent(this._getAllPropertiesChangedEventName(sourceId), observer, callback); _SPEventManager.instance.unregisterEvent(this._getAnyPropertyChangedEventName(sourceId), observer, callback); qosMonitor.writeSuccess(); } catch (e) { qosMonitor.writeUnexpectedFailure(e); throw e; } }; DynamicDataManager.prototype.registerPropertyChanged = function (sourceId, propertyId, observer, callback) { var qosMonitor = new _QosMonitor(QOS_MONITOR_PREFIX + '.registerPropertyChanged'); try { Validate.isNonemptyString(sourceId,'sourceId'); Validate.isNonemptyString(propertyId, 'propertyId'); Validate.isNotNullOrUndefined(observer, 'observer'); Validate.isNotNullOrUndefined(callback, 'callback'); if (!this._sources.has(sourceId)) { throw new Error(Text.format(strings.dynamicDataManagerSourceDoesntExist, sourceId)); } _SPEventManager.instance.registerEvent(this._getPropertyChangedEventName(sourceId, propertyId), observer, callback); _SPEventManager.instance.registerEvent(this._getAllPropertiesChangedEventName(sourceId), observer, callback); qosMonitor.writeSuccess(); } catch (e) { qosMonitor.writeUnexpectedFailure(e); throw e; } }; DynamicDataManager.prototype.unregisterPropertyChanged = function (sourceId, propertyId, observer, callback) { var qosMonitor = new _QosMonitor(QOS_MONITOR_PREFIX + '.unregisterPropertyChanged'); try { Validate.isNonemptyString(sourceId,'sourceId'); Validate.isNonemptyString(propertyId, 'propertyId'); Validate.isNotNullOrUndefined(observer, 'observer'); Validate.isNotNullOrUndefined(callback, 'callback'); if (!this._sources.has(sourceId)) { throw new Error(Text.format(strings.dynamicDataManagerSourceDoesntExist, sourceId)); } _SPEventManager.instance.unregisterEvent(this._getPropertyChangedEventName(sourceId, propertyId), observer, callback); _SPEventManager.instance.unregisterEvent(this._getAllPropertiesChangedEventName(sourceId), observer, callback); qosMonitor.writeSuccess(); } catch (e) { qosMonitor.writeUnexpectedFailure(e); throw e; } }; DynamicDataManager.prototype.getSources = function () { var sources = []; this._sources.forEach(function (source) { return sources.push(source); }); return sources; }; DynamicDataManager.prototype.tryGetSource = function (sourceId) { Validate.isNotNullOrUndefined(sourceId,'sourceId'); return this._sources.get(sourceId); }; DynamicDataManager.prototype.addSource = function (source) { var qosMonitor = new _QosMonitor(QOS_MONITOR_PREFIX + '.addSource'); try { this._validateSource(source); if (this._sources.has(source.id)) { _TraceLogger.logVerbose(LOG_SOURCE, Text.format(strings.dynamicDataManagerSourceAlreadyExists, source.id)); } this._sources.set(source.id, source); this._raiseSourcesChangedEvent(); qosMonitor.writeSuccess(); } catch (e) { qosMonitor.writeUnexpectedFailure(e); throw e; } }; DynamicDataManager.prototype.removeSource = function (sourceId) { var qosMonitor = new _QosMonitor(QOS_MONITOR_PREFIX + '.removeSource'); try { Validate.isNonemptyString(sourceId,'sourceId'); if (this._sources.has(sourceId)) { _SPEventManager.instance.removeEvent(this._getAllPropertiesChangedEventName(sourceId)); _SPEventManager.instance.removeEvent(this._getAnyPropertyChangedEventName(sourceId)); _SPEventManager.instance.removeEventsByPrefix(this._getPropertyChangedEventPrefix(sourceId)); this._sources.delete(sourceId); this._raiseSourcesChangedEvent(); } qosMonitor.writeSuccess(); } catch (e) { qosMonitor.writeUnexpectedFailure(e); throw e; } }; DynamicDataManager.prototype._validateSource = function (source) { Validate.isNotNullOrUndefined(source,'source'); if (source.id.indexOf(EVENT_NAME_SEPARATOR) > -1) { throw new Error("Source id contains invalid characters, like \"" + EVENT_NAME_SEPARATOR + "\". Id: \"" + source.id + "\"."); } var regex = /^[a-zA-Z0-9\-_]+$/; source.getPropertyDefinitions().forEach(function (def) { if (!regex.test(def.id)) { throw new Error("Source contains invalid property \"" + def.id + "\"."); } }); }; DynamicDataManager.prototype._raiseSourcesChangedEvent = function () { _SPEventManager.instance.raiseStickyEvent(SOURCES_CHANGED_EVENT_NAME, {}); }; DynamicDataManager.prototype._getAllPropertiesChangedEventName = function (sourceId) { return [ALL_PROPERTIES_EVENT_PREFIX, sourceId].join(EVENT_NAME_SEPARATOR); }; DynamicDataManager.prototype._getAnyPropertyChangedEventName = function (sourceId) { return [ANY_PROPERTY_EVENT_PREFIX, sourceId].join(EVENT_NAME_SEPARATOR); }; DynamicDataManager.prototype._getPropertyChangedEventPrefix = function (sourceId) { return [PROPERTY_EVENT_PREFIX, sourceId].join(EVENT_NAME_SEPARATOR); }; DynamicDataManager.prototype._getPropertyChangedEventName = function (sourceId, propertyId) { return [this._getPropertyChangedEventPrefix(sourceId), propertyId].join(EVENT_NAME_SEPARATOR); }; DynamicDataManager.serviceKey = ServiceKey.create('sp-core-library:DynamicDataManager', DynamicDataManager); return DynamicDataManager; }()); export default DynamicDataManager; ======================= File: lib/webparts/connect2List/Connect2ListWebPart.module.scss.js ======================= <gh_stars>0 /* tslint:disable */ require("./Connect2ListWebPart.module.css"); var styles = { connect2List: 'connect2List_1f40a34b', container: 'container_1f40a34b', row: 'row_1f40a34b', column: 'column_1f40a34b', 'ms-Grid':'ms-Grid_1f40a34b', title: 'title_1f40a34b', subTitle:'subTitle_1f40a34b', description: 'description_1f40a34b', button: 'button_1f40a34b', label: 'label_1f40a34b', }; export default styles; /* tslint:enable */ //# sourceMappingURL=Connect2ListWebPart.module.scss.js.map ======================= File: node_modules/office-ui-fabric-react/lib-commonjs/components/Button/CommandButton/CommandButton.js ======================= "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ActionButton_1 = require("../ActionButton/ActionButton"); exports.CommandButton = ActionButton_1.ActionButton; //# sourceMappingURL=CommandButton.js.map ======================= File: node_modules/@microsoft/sp-http/lib/resx-strings/ga-ie.js ======================= define([], function() { var strings = { "_+tvmKa3YEOqWGKKXzwjtaw": { "additionalCredentialsWarning": "Teastaíonn faisnéis aitheantas breise chun an leathanach seo a thaispeáin i gceart.", "servicePrincipalNotAvaliableError": "Níor soláthraíodh prionsabal seirbhíse fheidhmchlár Gréasáin SharePoint Online go fóill. Déan teagmháil le riarthóir an tionónta.", "graphClientInitializationError": "Ní féidir MSGraphClient a thógáil de bharr teipe neamhaitheanta" } }; strings.default = strings; return strings; }); ======================= File: node_modules/office-ui-fabric-react/lib-commonjs/components/Divider/Divider.doc.js ======================= <filename>node_modules/office-ui-fabric-react/lib-commonjs/components/Divider/Divider.doc.js<gh_stars>1-10 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var React = require("react"); var VerticalDivider_Basic_Example_1 = require("./examples/VerticalDivider.Basic.Example"); var VerticalDivider_Custom_Example_1 = require("./examples/VerticalDivider.Custom.Example"); var Divider_checklist_1 = require("./Divider.checklist"); var VerticalDividerBasicExampleCode = require('!raw-loader!office-ui-fabric-react/src/components/Divider/examples/VerticalDivider.Basic.Example.tsx'); var VerticalDividerCustomExampleCode = require('!raw-loader!office-ui-fabric-react/src/components/Divider/examples/VerticalDivider.Custom.Example.tsx'); exports.DividerPageProps = { title: 'Divider', componentName: 'Divider', componentUrl: 'https://github.com/OfficeDev/office-ui-fabric-react/tree/master/packages/office-ui-fabric-react/src/components/Divider', componentStatus: Divider_checklist_1.DividerStatus, examples: [ { title: 'Vertical Divider', code: VerticalDividerBasicExampleCode, view: React.createElement(VerticalDivider_Basic_Example_1.VerticalDividerBasicExample, null) }, { title: 'Custom Vertical Divider', code: VerticalDividerCustomExampleCode, view: React.createElement(VerticalDivider_Custom_Example_1.VerticalDividerCustomExample, null) } ], propertiesTablesSources: [require('!raw-loader!office-ui-fabric-react/src/components/Divider/VerticalDivider.types.ts')], overview: require('!raw-loader!office-ui-fabric-react/src/components/Divider/docs/DividerOverview.md'), bestPractices: require('!raw-loader!office-ui-fabric-react/src/components/Divider/docs/DividerBestPractices.md'), dos: require('!raw-loader!office-ui-fabric-react/src/components/Divider/docs/DividerDos.md'), donts: require('!raw-loader!office-ui-fabric-react/src/components/Divider/docs/DividerDonts.md'), isHeaderVisible: true, isFeedbackVisible: true }; //# sourceMappingURL=Divider.doc.js.map ======================= File: node_modules/@microsoft/api-extractor/lib/enhancers/ValidationEnhancer.js ======================= "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. Object.defineProperty(exports, "__esModule", { value: true }); const path = require("path"); const ts = require("typescript"); const AstSymbol_1 = require("../analyzer/AstSymbol"); const api_extractor_model_1 = require("@microsoft/api-extractor-model"); class ValidationEnhancer { static analyze(collector) { const alreadyWarnedSymbols = new Set(); for (const entity of collector.entities) { if (entity.astEntity instanceof AstSymbol_1.AstSymbol) { if (entity.exported) { entity.astEntity.forEachDeclarationRecursive((astDeclaration) => { ValidationEnhancer._checkReferences(collector, astDeclaration, alreadyWarnedSymbols); }); ValidationEnhancer._checkForInternalUnderscore(collector, entity, entity.astEntity); } } } } static _checkForInternalUnderscore(collector, collectorEntity, astSymbol) { const astSymbolMetadata = collector.fetchMetadata(astSymbol); if (astSymbolMetadata.releaseTag === api_extractor_model_1.ReleaseTag.Internal &&!astSymbolMetadata.releaseTagSameAsParent) { for (const exportName of collectorEntity.exportNames) { if (exportName[0]!== '_') { collector.messageRouter.addAnalyzerIssue("ae-internal-missing-underscore" /* InternalMissingUnderscore */, `The name ${exportName} should be prefixed with an underscore` + ` because the declaration is marked as "@internal"`, astSymbol, { exportName }); } } } } static _checkReferences(collector, astDeclaration, alreadyWarnedSymbols) { const astSymbolMetadata = collector.fetchMetadata(astDeclaration.astSymbol); const astSymbolReleaseTag = astSymbolMetadata.releaseTag; for (const referencedEntity of astDeclaration.referencedAstEntities) { if (referencedEntity instanceof AstSymbol_1.AstSymbol) { // If this is e.g. a member of a namespace, then we need to be checking the top-level scope to see // whether it's exported. // // TODO: Technically we should also check each of the nested scopes along the way. const rootSymbol = referencedEntity.rootAstSymbol; if (!rootSymbol.isExternal) { const collectorEntity = collector.tryGetCollectorEntity(rootSymbol); if (collectorEntity && collectorEntity.exported) { const referencedMetadata = collector.fetchMetadata(referencedEntity); const referencedReleaseTag = referencedMetadata.releaseTag; if (api_extractor_model_1.ReleaseTag.compare(astSymbolReleaseTag, referencedReleaseTag) > 0) { collector.messageRouter.addAnalyzerIssue("ae-incompatible-release-tags" /* IncompatibleReleaseTags */, `The symbol "${astDeclaration.astSymbol.localName}"` + ` is marked as ${api_extractor_model_1.ReleaseTag.getTagName(astSymbolReleaseTag)},` + ` but its signature references "${referencedEntity.localName}"` + ` which is marked as ${api_extractor_model_1.ReleaseTag.getTagName(referencedReleaseTag)}`, astDeclaration); } } else { const entryPointFilename = path.basename(collector.workingPackage.entryPointSourceFile.fileName); if (!alreadyWarnedSymbols.has(referencedEntity)) { alreadyWarnedSymbols.add(referencedEntity); // The main usage scenario for ECMAScript symbols is to attach private data to a JavaScript object, // so as a special case, we do NOT report them as forgotten exports. if (!ValidationEnhancer._isEcmaScriptSymbol(referencedEntity)) { collector.messageRouter.addAnalyzerIssue("ae-forgotten-export" /* ForgottenExport */, `The symbol "${rootSymbol.localName}" needs to be exported` + ` by the entry point ${entryPointFilename}`, astDeclaration); } } } } } } } // Detect an AstSymbol that refers to an ECMAScript symbol declaration such as: // // const mySymbol: unique symbol = Symbol('mySymbol'); static _isEcmaScriptSymbol(astSymbol) { if (astSymbol.astDeclarations.length!== 1) { return false; } // We are matching a form like this: // // - VariableDeclaration: // - Identifier: pre=[mySymbol] // - ColonToken: pre=[:] sep=[ ] // - TypeOperator: // - UniqueKeyword: pre=[unique] sep=[ ] // - SymbolKeyword: pre=[symbol] const astDeclaration = astSymbol.astDeclarations[0]; if (ts.isVariableDeclaration(astDeclaration.declaration)) { const variableTypeNode = astDeclaration.declaration.type; if (variableTypeNode) { for (const token of variableTypeNode.getChildren()) { if (token.kind === ts.SyntaxKind.SymbolKeyword) { return true; } } } } return false; } } exports.ValidationEnhancer = ValidationEnhancer; //# sourceMappingURL=ValidationEnhancer.js.map ======================= File: node_modules/office-ui-fabric-react/lib-commonjs/components/Layer/Layer.js ======================= "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var Utilities_1 = require("../../Utilities"); var Layer_base_1 = require("./Layer.base"); var Layer_styles_1 = require("./Layer.styles"); exports.Layer = Utilities_1.styled(Layer_base_1.LayerBase, Layer_styles_1.getStyles, undefined, { scope: 'Layer', fields: ['hostId', 'theme','styles'] }); //# sourceMappingURL=Layer.js.map ======================= File: node_modules/@uifabric/utilities/lib-commonjs/dom.js ======================= <gh_stars>0 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); tslib_1.__exportStar(require("./dom/elementContains"), exports); tslib_1.__exportStar(require("./dom/elementContainsAttribute"), exports); tslib_1.__exportStar(require("./dom/findElementRecursive"), exports); tslib_1.__exportStar(require("./dom/getChildren"), exports); tslib_1.__exportStar(require("./dom/getDocument"), exports); tslib_1.__exportStar(require("./dom/getParent"), exports); tslib_1.__exportStar(require("./dom/getRect"), exports); tslib_1.__exportStar(require("./dom/getVirtualParent"), exports); tslib_1.__exportStar(require("./dom/getWindow"), exports); tslib_1.__exportStar(require("./dom/isVirtualElement"), exports); tslib_1.__exportStar(require("./dom/on"), exports); tslib_1.__exportStar(require("./dom/portalContainsElement"), exports); tslib_1.__exportStar(require("./dom/raiseClick"), exports); tslib_1.__exportStar(require("./dom/setPortalAttribute"), exports); tslib_1.__exportStar(require("./dom/setVirtualParent"), exports); //# sourceMappingURL=dom.js.map ======================= File: node_modules/@microsoft/rush-lib/node_modules/@microsoft/ts-command-line/lib/test/CommandLineParser.test.js ======================= "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. Object.defineProperty(exports, "__esModule", { value: true }); const CommandLineAction_1 = require("../CommandLineAction"); const CommandLineParser_1 = require("../CommandLineParser"); class TestAction extends CommandLineAction_1.CommandLineAction { constructor() { super({ actionName: 'do-job', summary: 'does the job', documentation: 'a longer description' }); this.done = false; } onExecute() { expect(this._flag.value).toEqual(true); this.done = true; return Promise.resolve(); } onDefineParameters() { this._flag = this.defineFlagParameter({ parameterLongName: '--flag', description: 'The flag' }); } } class TestCommandLine extends CommandLineParser_1.CommandLineParser { constructor() { super({ toolFilename: 'example', toolDescription: 'An example project' }); this.addAction(new TestAction()); } onDefineParameters() { // no parameters } } describe('CommandLineParser', () => { it('executes an action', () => { const commandLineParser = new TestCommandLine(); return commandLineParser.execute(['do-job', '--flag']).then(() => { expect(commandLineParser.selectedAction).toBeDefined(); expect(commandLineParser.selectedAction.actionName).toEqual('do-job'); const action = commandLineParser.selectedAction; expect(action.done).toBe(true); }); }); }); //# sourceMappingURL=CommandLineParser.test.js.map ======================= File: node_modules/@uifabric/utilities/lib/resources.js ======================= var _baseUrl = ''; /** Sets the current base url used for fetching images. */ export function getResourceUrl(url) { return _baseUrl + url; } /** Gets the current base url used for fetching images. */ export function setBaseUrl(baseUrl) { _baseUrl = baseUrl; } //# sourceMappingURL=resources.js.map ======================= File: node_modules/office-ui-fabric-react/lib/components/Shimmer/ShimmerGap/ShimmerGap.base.js ======================= import * as tslib_1 from "tslib"; import * as React from'react'; import { BaseComponent, classNamesFunction } from '../../../Utilities'; var getClassNames = classNamesFunction(); var ShimmerGapBase = /** @class */ (function (_super) { tslib_1.__extends(ShimmerGapBase, _super); function ShimmerGapBase(props) { return _super.call(this, props) || this; } ShimmerGapBase.prototype.render = function () { var _a = this.props, height = _a.height, styles = _a.styles, width = _a.width, borderStyle = _a.borderStyle, theme = _a.theme; this._classNames = getClassNames(styles, { theme: theme, height: height, borderStyle: borderStyle }); return (React.createElement("div", { style: { width: width? width : '10px', minWidth: typeof width === 'number'? width + "px" : 'auto' }, className: this._classNames.root })); }; return ShimmerGapBase; }(BaseComponent)); export { ShimmerGapBase }; //# sourceMappingURL=ShimmerGap.base.js.map ======================= File: node_modules/office-ui-fabric-react/lib-commonjs/components/Coachmark/Coachmark.doc.js ======================= "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var React = require("react"); var Coachmark_Basic_Example_1 = require("./examples/Coachmark.Basic.Example"); var CoachmarkBasicExampleCode = require('!raw-loader!office-ui-fabric-react/src/components/Coachmark/examples/Coachmark.Basic.Example.tsx'); exports.CoachmarkPageProps = { title: 'Coachmark', componentName: 'Coachmark', componentUrl: 'https://github.com/OfficeDev/office-ui-fabric-react/tree/master/packages/office-ui-fabric-react/src/components/Coachmark', examples: [ { title: 'Coachmark Basic', code: CoachmarkBasicExampleCode, view: React.createElement(Coachmark_Basic_Example_1.CoachmarkBasicExample, null), isScrollable: false } ], propertiesTablesSources: [require('!raw-loader!office-ui-fabric-react/src/components/Coachmark/Coachmark.types.ts')], overview: require('!raw-loader!office-ui-fabric-react/src/components/Coachmark/docs/CoachmarkOverview.md'), bestPractices: '', dos: require('!raw-loader!office-ui-fabric-react/src/components/Coachmark/docs/CoachmarkDos.md'), donts: require('!raw-loader!office-ui-fabric-react/src/components/Coachmark/docs/CoachmarkDonts.md'), isHeaderVisible: true, isFeedbackVisible: true }; //# sourceMappingURL=Coachmark.doc.js.map ======================= File: node_modules/@microsoft/sp-property-pane/lib/propertyPaneDynamicData/DynamicDataWidget.module.scss.js ======================= require("./DynamicDataWidget.module.css"); var styles = { dynamicDataWidget: 'dynamicDataWidget_bfd3a4d2', entryLabel: 'entryLabel_bfd3a4d2', }; export default styles; ======================= File: node_modules/@microsoft/sp-http/lib/resx-strings/ca-es.js ======================= <filename>node_modules/@microsoft/sp-http/lib/resx-strings/ca-es.js define([], function() { var strings = { "_+tvmKa3YEOqWGKKXzwjtaw": { "additionalCredentialsWarning": "Cal especificar credencials addicionals per poder mostrar aquesta pàgina correctament.", "servicePrincipalNotAvaliableError": "L'entitat de seguretat de servei de l'aplicació web del SharePoint Online encara no s'ha proveït. Contacteu amb l'administrador d'inquilins.", "graphClientInitializationError": "No es pot construir MSGraphClient a causa d'un error desconegut." } }; strings.default = strings; return strings; }); ======================= File: node_modules/office-ui-fabric-react/lib/components/Shimmer/examples/Shimmer.LoadData.Example.js ======================= <reponame>GhostMachineSoftware/SPFx_Connect2List<gh_stars>0 // @codepen import * as tslib_1 from "tslib"; import * as React from'react'; import { Shimmer, ShimmerElementsGroup, ShimmerElementType as ElemType } from 'office-ui-fabric-react/lib/Shimmer'; import { Persona, PersonaSize, PersonaPresence } from 'office-ui-fabric-react/lib/Persona'; import { Toggle } from 'office-ui-fabric-react/lib/Toggle'; import { mergeStyles } from 'office-ui-fabric-react/lib/Styling'; var wrapperClass = mergeStyles({ padding: 2, selectors: { '& > *': { margin: '10px 0' } } }); var ShimmerLoadDataExample = /** @class */ (function (_super) { tslib_1.__extends(ShimmerLoadDataExample, _super); function ShimmerLoadDataExample(props) { var _this = _super.call(this, props) || this; _this._getContentOne = function (ev, checked) { var isDataLoadedOne = _this.state.isDataLoadedOne; _this.setState({ isDataLoadedOne: checked, contentOne:!isDataLoadedOne? 'Congratulations!!! You have successfully loaded the content.': '' }); }; _this._getContentTwo = function (ev, checked) { var isDataLoadedTwo = _this.state.isDataLoadedTwo; _this.setState({ isDataLoadedTwo: checked, examplePersona:!isDataLoadedTwo ? { imageUrl: 'https://static2.sharepointonline.com/files/fabric/office-ui-fabric-react-assets/persona-female.png', imageInitials: 'AL', primaryText: '<NAME>', secondaryText: 'Software Engineer' } : {} }); }; _this._getCustomElements = function () { return (React.createElement("div", { style: { display: 'flex' } }, React.createElement(ShimmerElementsGroup, { shimmerElements: [{ type: ElemType.circle, height: 40 }, { type: ElemType.gap, width: 16, height: 40 }] }), React.createElement(ShimmerElementsGroup, { flexWrap: true, width: "100%", shimmerElements: [ { type: ElemType.line, width: '100%', height: 10, verticalAlign: 'bottom' }, { type: ElemType.line, width: '90%', height: 8 }, { type: ElemType.gap, width: '10%', height: 20 } ] }))); }; _this.state = { isDataLoadedOne: false, isDataLoadedTwo: false, contentOne: '', examplePersona: {} }; return _this; } ShimmerLoadDataExample.prototype.render = function () { var _a = this.state, isDataLoadedOne = _a.isDataLoadedOne, isDataLoadedTwo = _a.isDataLoadedTwo, contentOne = _a.contentOne, examplePersona = _a.examplePersona; return (React.createElement("div", { className: wrapperClass }, React.createElement(Toggle, { checked: isDataLoadedOne, onChange: this._getContentOne, onText: "Toggle to show shimmer", offText: "Toggle to load content" }), React.createElement(Shimmer, { isDataLoaded: isDataLoadedOne, ariaLabel: "Loading content" }, React.createElement("div", { style: { overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', lineHeight: '1', minHeight: '16px' // Default height of Shimmer when no elements being provided. } }, contentOne, contentOne, contentOne)), React.createElement(Toggle, { checked: isDataLoadedTwo, onChange: this._getContentTwo, onText: "Toggle to show shimmer", offText: "Toggle to load content" }), React.createElement(Shimmer, { customElementsGroup: this._getCustomElements(), width: 300, isDataLoaded: isDataLoadedTwo }, React.createElement(Persona, tslib_1.__assign({}, examplePersona, { size: PersonaSize.size40, presence: PersonaPresence.away }))))); }; return ShimmerLoadDataExample; }(React.Component)); export { ShimmerLoadDataExample }; //# sourceMappingURL=Shimmer.LoadData.Example.js.map ======================= File: node_modules/@uifabric/utilities/lib/initializeDir.js ======================= <reponame>GhostMachineSoftware/SPFx_Connect2List<filename>node_modules/@uifabric/utilities/lib/initializeDir.js import { getWindow } from './dom/getWindow'; export function initializeDir(window) { var win = (window || getWindow()); if (win &&!win.__hasInitializedDir__) { win.__hasInitializedDir__ = true; // Ensure that the documentElement has a 'dir' attribute. var documentElement = win.document.documentElement; if (!documentElement.hasAttribute('dir')) { documentElement.setAttribute('dir', 'ltr'); } } } //# sourceMappingURL=initializeDir.js.map ======================= File: node_modules/@microsoft/gulp-core-build-sass/lib/SassTask.js ======================= "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. Object.defineProperty(exports, "__esModule", { value: true }); const path = require("path"); const os_1 = require("os"); const gulp_core_build_1 = require("@microsoft/gulp-core-build"); const load_themed_styles_1 = require("@microsoft/load-themed-styles"); const node_core_library_1 = require("@microsoft/node-core-library"); const glob = require("glob"); const nodeSass = require("node-sass"); const postcss = require("postcss"); const CleanCss = require("clean-css"); const autoprefixer = require("autoprefixer"); const cssModules = require("postcss-modules"); const crypto = require("crypto"); const _classMaps = {}; class SassTask extends gulp_core_build_1.GulpTask { constructor() { super('sass', { preamble: '/* tslint:disable */', postamble: '/* tslint:enable */', sassMatch: [ 'src/**/*.scss', 'src/**/*.sass' ], useCSSModules: false, warnOnCssInvalidPropertyName: true, dropCssFiles: false, warnOnNonCSSModules: false }); this.cleanMatch = [ 'src/**/*.sass.ts', 'src/**/*.scss.ts' ]; this._postCSSPlugins = [ autoprefixer({ browsers: ['> 1%', 'last 2 versions', 'ie >= 10'] }) ]; this._modulePostCssAdditionalPlugins = [ cssModules({ getJSON: this._generateModuleStub.bind(this), generateScopedName: this._generateScopedName.bind(this) }) ]; } loadSchema() { return node_core_library_1.JsonFile.load(path.join(__dirname,'sass.schema.json')); } executeTask(gulp) { if (!this.taskConfig.sassMatch) { return Promise.reject(new Error('taskConfig.sassMatch must be defined')); } return this._globAll(...this.taskConfig.sassMatch).then((matches) => { return Promise.all(matches.map((match) => this._processFile(match))); }).then(() => { }); } _generateModuleStub(cssFileName, json) { _classMaps[cssFileName] = json; } _generateScopedName(name, fileName, css) { return name + '_' + crypto.createHmac('sha1', fileName).update(css).digest('hex').substring(0, 8); } _processFile(filePath) { // Ignore files that start with underscores if (path.basename(filePath).match(/^\_/)) { return Promise.resolve(); } const isFileModuleCss =!!filePath.match(/\.module\.s(a|c)ss/); const processAsModuleCss = isFileModuleCss ||!!this.taskConfig.useCSSModules; if (!isFileModuleCss &&!this.taskConfig.useCSSModules && this.taskConfig.warnOnNonCSSModules) { // If the file doesn't end with.module.scss and we don't treat all files as module-scss, warn const relativeFilePath = path.relative(this.buildConfig.rootPath, filePath); this.logWarning(`${relativeFilePath}: filename should end with module.sass or module.scss`); } let cssOutputPath = undefined; let cssOutputPathAbsolute = undefined; if (this.taskConfig.dropCssFiles) { const srcRelativePath = path.relative(path.join(this.buildConfig.rootPath, this.buildConfig.srcFolder), filePath); cssOutputPath = path.join(this.buildConfig.libFolder, srcRelativePath); cssOutputPath = cssOutputPath.replace(/\.s(c|a)ss$/, '.css'); cssOutputPathAbsolute = path.join(this.buildConfig.rootPath, cssOutputPath); } return node_core_library_1.LegacyAdapters.convertCallbackToPromise(nodeSass.render, { file: filePath, importer: (url) => ({ file: this._patchSassUrl(url) }), sourceMap: this.taskConfig.dropCssFiles, sourceMapContents: true, omitSourceMapUrl: true, outFile: cssOutputPath }).catch((error) => { this.fileError(filePath, error.line, error.column, error.name, error.message); throw new Error(error.message); }).then((result) => { const options = { from: filePath }; if (result.map &&!this.buildConfig.production) { options.map = { prev: result.map.toString() // Pass the source map through to postcss }; } const plugins = [ ...this._postCSSPlugins, ...(processAsModuleCss? this._modulePostCssAdditionalPlugins : []) ]; return postcss(plugins).process(result.css.toString(), options); }).then((result) => { let cleanCssOptions = { level: 1, returnPromise: true }; if (!!this.taskConfig.cleanCssOptions) { cleanCssOptions = Object.assign({}, this.taskConfig.cleanCssOptions, { returnPromise: true }); } cleanCssOptions.sourceMap =!!result.map; const cleanCss = new CleanCss(cleanCssOptions); return cleanCss.minify(result.css.toString(), result.map? result.map.toString() : undefined); }).then((result) => { if (cssOutputPathAbsolute) { const generatedFileLines = [ result.styles.toString() ]; if (result.sourceMap &&!this.buildConfig.production) { const encodedSourceMap = Buffer.from(result.sourceMap.toString()).toString('base64'); generatedFileLines.push(...[ `/*# sourceMappingURL=data:application/json;base64,${encodedSourceMap} */` ]); } node_core_library_1.FileSystem.writeFile(cssOutputPathAbsolute, generatedFileLines.join(os_1.EOL), { ensureFolderExists: true }); } const scssTsOutputPath = `${filePath}.ts`; const classNames = _classMaps[filePath]; let exportClassNames = ''; const content = result.styles; if (classNames) { const classNamesLines = [ 'const styles = {' ]; const classKeys = Object.keys(classNames); classKeys.forEach((key, index) => { const value = classNames[key]; let line = ''; if (key.indexOf('-')!== -1) { const message = `The local CSS class '${key}' is not camelCase and will not be type-safe.`; this.taskConfig.warnOnCssInvalidPropertyName? this.logWarning(message) : this.logVerbose(message); line = ` '${key}': '${value}'`; } else { line = ` ${key}: '${value}'`; } if ((index + 1) <= classKeys.length) { line += ','; } classNamesLines.push(line); }); let exportString = 'export default styles;'; if (this.taskConfig.moduleExportName === '') { exportString = 'export = styles;'; } else if (!!this.taskConfig.moduleExportName) { // exportString = `export const ${this.taskConfig.moduleExportName} = styles;`; } classNamesLines.push('};', '', exportString); exportClassNames = classNamesLines.join(os_1.EOL); } let lines = []; lines.push(this.taskConfig.preamble || ''); if (cssOutputPathAbsolute) { lines = lines.concat([ `require(${JSON.stringify(`./${path.basename(cssOutputPathAbsolute)}`)});`, exportClassNames ]); } else if (!!content) { lines = lines.concat([ 'import { loadStyles } from \'@microsoft/load-themed-styles\';', '', exportClassNames, '', `loadStyles(${JSON.stringify(load_themed_styles_1.splitStyles(content))});` ]); } lines.push(this.taskConfig.postamble || ''); const generatedTsFile = (lines .join(os_1.EOL) .replace(new RegExp(`(${os_1.EOL}){3,}`, 'g'), `${os_1.EOL}${os_1.EOL}`) .replace(new RegExp(`(${os_1.EOL})+$`,'m'), os_1.EOL)); node_core_library_1.FileSystem.writeFile(scssTsOutputPath, generatedTsFile); }); } _globAll(...patterns) { return Promise.all(patterns.map((pattern) => node_core_library_1.LegacyAdapters.convertCallbackToPromise(glob, path.isAbsolute(pattern)? pattern : path.join(this.buildConfig.rootPath, pattern)))).then((matchSets) => { const result = {}; for (const matchSet of matchSets) { for (const match of matchSet) { const normalizedMatch = path.resolve(match); result[normalizedMatch] = true; } } return Object.keys(result); }); } _patchSassUrl(url) { if (url[0] === '~') { url = 'node_modules/' + url.substr(1); } else if (url ==='stdin') { url = ''; } return url; } } exports.SassTask = SassTask; //# sourceMappingURL=SassTask.js.map ======================= File: node_modules/@microsoft/rush-lib/lib/cli/actions/PublishAction.js ======================= "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. Object.defineProperty(exports, "__esModule", { value: true }); const colors = require("colors"); const os_1 = require("os"); const path = require("path"); const node_core_library_1 = require("@microsoft/node-core-library"); const ChangeManagement_1 = require("../../api/ChangeManagement"); const Npm_1 = require("../../utilities/Npm"); const PublishUtilities_1 = require("../../logic/PublishUtilities"); const ChangelogGenerator_1 = require("../../logic/ChangelogGenerator"); const PrereleaseToken_1 = require("../../logic/PrereleaseToken"); const ChangeManager_1 = require("../../logic/ChangeManager"); const BaseRushAction_1 = require("./BaseRushAction"); const PublishGit_1 = require("../../logic/PublishGit"); const VersionControl_1 = require("../../utilities/VersionControl"); const PolicyValidator_1 = require("../../logic/policy/PolicyValidator"); class PublishAction extends BaseRushAction_1.BaseRushAction { constructor(parser) { super({ actionName: 'publish', summary: 'Reads and processes package publishing change requests generated by "rush change".', documentation: 'Reads and processes package publishing change requests generated by "rush change". This will perform a'+ 'read-only operation by default, printing operations executed to the console. To commit'+ 'changes and publish packages, you must use the --commit flag and/or the --publish flag.', parser }); } onDefineParameters() { this._apply = this.defineFlagParameter({ parameterLongName: '--apply', parameterShortName: '-a', description: 'If this flag is specified, the change requests will be applied to package.json files.' }); this._targetBranch = this.defineStringParameter({ parameterLongName: '--target-branch', parameterShortName: '-b', argumentName: 'BRANCH', description: 'If this flag is specified, applied changes and deleted change requests will be' + 'committed and merged into the target branch.' }); this._publish = this.defineFlagParameter({ parameterLongName: '--publish', parameterShortName: '-p', description: 'If this flag is specified, applied changes will be published to npm.' }); this._addCommitDetails = this.defineFlagParameter({ parameterLongName: '--add-commit-details', parameterShortName: undefined, description: 'Adds commit author and hash to the changelog.json files for each change.' }); this._regenerateChangelogs = this.defineFlagParameter({ parameterLongName: '--regenerate-changelogs', parameterShortName: undefined, description: 'Regenerates all changelog files based on the current JSON content.' }); // NPM registry related parameters this._registryUrl = this.defineStringParameter({ parameterLongName: '--registry', parameterShortName: '-r', argumentName: 'REGISTRY', description: `Publishes to a specified NPM registry. If this is specified, it will prevent the current commit will not be ` + 'tagged.' }); this._npmAuthToken = this.defineStringParameter({ parameterLongName: '--npm-auth-token', parameterShortName: '-n', argumentName: 'TOKEN', description: 'Provide the default scope NPM auth token to be passed into npm publish for global package publishing.' }); this._npmTag = this.defineStringParameter({ parameterLongName: '--tag', parameterShortName: '-t', argumentName: 'TAG', description: `The tag option to pass to npm publish. By default NPM will publish using the 'latest' tag, even if ` + `the package is older than the current latest, so in publishing workflows for older releases, providing ` + `a tag is important. When hotfix changes are made, this parameter defaults to 'hotfix'.` }); // NPM pack tarball related parameters this._pack = this.defineFlagParameter({ parameterLongName: '--pack', description: `Packs projects into tarballs instead of publishing to npm repository. It can only be used when ` + `--include-all is specified. If this flag is specified, NPM registry related parameters will be ignored.` }); this._releaseFolder = this.defineStringParameter({ parameterLongName: '--release-folder', argumentName: 'FOLDER', description: `This parameter is used with --pack parameter to provide customized location for the tarballs instead of ` + `the default value. ` }); this._releaseType = this.defineStringParameter({ parameterLongName: '--release-type', argumentName: 'RELEASE_TYPE', description: `This parameter is used with --pack parameter to provide release type for the generated tarballs. ` + `The default value is 'internal'. The valid values include 'public', 'beta', 'internal'` }); // End of NPM pack tarball related parameters this._includeAll = this.defineFlagParameter({ parameterLongName: '--include-all', parameterShortName: undefined, description: 'If this flag is specified, all packages with shouldPublish=true in rush.json'+ 'or with a specified version policy'+ 'will be published if their version is newer than published version.' }); this._versionPolicy = this.defineStringParameter({ parameterLongName: '--version-policy', argumentName: 'POLICY', description: 'Version policy name. Only projects with this version policy will be published if used'+ 'with --include-all.' }); this._prereleaseName = this.defineStringParameter({ parameterLongName: '--prerelease-name', argumentName: 'NAME', description: 'Bump up to a prerelease version with the provided prerelease name. Cannot be used with --suffix' }); this._suffix = this.defineStringParameter({ parameterLongName: '--suffix', argumentName: 'SUFFIX', description: 'Append a suffix to all changed versions. Cannot be used with --prerelease-name.' }); this._force = this.defineFlagParameter({ parameterLongName: '--force', parameterShortName: undefined, description: 'If this flag is specified with --publish, packages will be published with --force on npm' }); } /** * Executes the publish action, which will read change request files, apply changes to package.jsons, */ run() { return Promise.resolve().then(() => { PolicyValidator_1.PolicyValidator.validatePolicy(this.rushConfiguration, false); const allPackages = this.rushConfiguration.projectsByName; if (this._regenerateChangelogs.value) { console.log('Regenerating changelogs'); ChangelogGenerator_1.ChangelogGenerator.regenerateChangelogs(allPackages, this.rushConfiguration); return Promise.resolve(); } this._validate(); if (this._includeAll.value) { this._publishAll(allPackages); } else { this._prereleaseToken = new PrereleaseToken_1.PrereleaseToken(this._prereleaseName.value, this._suffix.value); this._publishChanges(allPackages); } console.log(os_1.EOL + colors.green('Rush publish finished successfully.')); }); } /** * Validate some input parameters */ _validate() { if (this._pack.value &&!this._includeAll.value) { throw new Error('--pack can only be used with --include-all'); } if (this._releaseFolder.value &&!this._pack.value) { throw new Error(`--release-folder can only be used with --pack`); } if (this._releaseType.value &&!this._pack.value) { throw new Error(`--release-type can only be used with --pack`); } if (this._registryUrl.value && this._pack.value) { throw new Error(`--registry cannot be used with --pack`); } } _publishChanges(allPackages) { const changeManager = new ChangeManager_1.ChangeManager(this.rushConfiguration); changeManager.load(this.rushConfiguration.changesFolder, this._prereleaseToken, this._addCommitDetails.value); if (changeManager.hasChanges()) { const orderedChanges = changeManager.changes; const git = new PublishGit_1.PublishGit(this._targetBranch.value); const tempBranch = 'publish-' + new Date().getTime(); // Make changes in temp branch. git.checkout(tempBranch, true); // Make changes to package.json and change logs. changeManager.apply(this._apply.value); changeManager.updateChangelog(this._apply.value); if (VersionControl_1.VersionControl.hasUncommittedChanges()) { // Stage, commit, and push the changes to remote temp branch. git.addChanges(); git.commit(); git.push(tempBranch); // Override tag parameter if there is a hotfix change. for (const change of orderedChanges) { if (change.changeType === ChangeManagement_1.ChangeType.hotfix) { this._hotfixTagOverride = 'hotfix'; break; } } // npm publish the things that need publishing. for (const change of orderedChanges) { if (change.changeType && change.changeType > ChangeManagement_1.ChangeType.dependency) { const project = allPackages.get(change.packageName); if (project) { if (!this._packageExists(project)) { this._npmPublish(change.packageName, project.projectFolder); } else { console.log(`Skip ${change.packageName}. Package exists.`); } } else { console.log(`Skip ${change.packageName}. Failed to find its project.`); } } } // Create and push appropriate Git tags. this._gitAddTags(git, orderedChanges); git.push(tempBranch); // Now merge to target branch. git.checkout(this._targetBranch.value); git.pull(); git.merge(tempBranch); git.push(this._targetBranch.value); git.deleteBranch(tempBranch); } else { git.checkout(this._targetBranch.value); git.deleteBranch(tempBranch, false); } } } _publishAll(allPackages) { console.log(`Rush publish starts with includeAll and version policy ${this._versionPolicy.value}`); let updated = false; const git = new PublishGit_1.PublishGit(this._targetBranch.value); allPackages.forEach((packageConfig, packageName) => { if (packageConfig.shouldPublish && (!this._versionPolicy.value || this._versionPolicy.value === packageConfig.versionPolicyName)) { if (this._pack.value) { // packs to tarball instead of publishing to NPM repository this._npmPack(packageName, packageConfig); } else if (this._force.value ||!this._packageExists(packageConfig)) { // Publish to npm repository this._npmPublish(packageName, packageConfig.projectFolder); git.addTag(!!this._publish.value &&!this._registryUrl.value, packageName, packageConfig.packageJson.version); updated = true; } else { console.log(`Skip ${packageName}. Not updated.`); } } }); if (updated) { git.push(this._targetBranch.value); } } _gitAddTags(git, orderedChanges) { for (const change of orderedChanges) { if (change.changeType && change.changeType > ChangeManagement_1.ChangeType.dependency && this.rushConfiguration.projectsByName.get(change.packageName).shouldPublish) { git.addTag(!!this._publish.value &&!this._registryUrl.value, change.packageName, change.newVersion); } } } _npmPublish(packageName, packagePath) { const env = PublishUtilities_1.PublishUtilities.getEnvArgs(); const args = ['publish']; if (this.rushConfiguration.projectsByName.get(packageName).shouldPublish) { let registry = '//registry.npmjs.org/'; if (this._registryUrl.value) { const registryUrl = this._registryUrl.value; env['npm_config_registry'] = registryUrl; // tslint:disable-line:no-string-literal registry = registryUrl.substring(registryUrl.indexOf('//')); } if (this._npmAuthToken.value) { args.push(`--${registry}:_authToken=${this._npmAuthToken.value}`); } if (this._npmTag.value) { args.push(`--tag`, this._npmTag.value); } else if (this._hotfixTagOverride) { args.push(`--tag`, this._hotfixTagOverride); } if (this._force.value) { args.push(`--force`); } // TODO: Yarn's "publish" command line is fairly different from NPM and PNPM. The right thing to do here // would be to remap our options to the Yarn equivalents. But until we get around to that, we'll simply invoke // whatever NPM binary happens to be installed in the global path. const packageManagerToolFilename = this.rushConfiguration.packageManager === 'yarn' ? 'npm' : this.rushConfiguration.packageManagerToolFilename; PublishUtilities_1.PublishUtilities.execCommand(!!this._publish.value, packageManagerToolFilename, args, packagePath, env); } } _packageExists(packageConfig) { const env = PublishUtilities_1.PublishUtilities.getEnvArgs(); if (this._registryUrl.value) { env['npm_config_registry'] = this._registryUrl.value; // tslint:disable-line:no-string-literal } const publishedVersions = Npm_1.Npm.publishedVersions(packageConfig.packageName, packageConfig.projectFolder, env); return publishedVersions.indexOf(packageConfig.packageJson.version) >= 0; } _npmPack(packageName, project) { const args = ['pack']; const env = PublishUtilities_1.PublishUtilities.getEnvArgs(); if (this._releaseType.value && this._releaseType.value!== 'internal') { // a temporary workaround. Will replace it with npm or rush hooks. if (this._releaseType.value!== 'public' && this._releaseType.value!== 'beta') { throw new Error(`Invalid release type "${this._releaseType.value}"`); } this._updateAPIFile(packageName, project); } PublishUtilities_1.PublishUtilities.execCommand(!!this._publish.value, this.rushConfiguration.packageManagerToolFilename, args, project.projectFolder, env); if (!!this._publish.value) { // Copy the tarball the release folder const tarballName = this._calculateTarballName(project); const tarballPath = path.join(project.projectFolder, tarballName); const destFolder = this._releaseFolder.value? this._releaseFolder.value : path.join(this.rushConfiguration.commonTempFolder, 'artifacts', 'packages'); node_core_library_1.FileSystem.move({ sourcePath: tarballPath, destinationPath: path.join(destFolder, tarballName), overwrite: true }); } } _updateAPIFile(packageName, project) { const apiConfigPath = path.join(project.projectFolder, 'config', 'api-extractor.json'); if (node_core_library_1.FileSystem.exists(apiConfigPath)) { // Read api-extractor.json file const apiConfig = node_core_library_1.JsonFile.load(apiConfigPath); /* tslint:disable:no-string-literal */ if (!!apiConfig['generateDtsRollup'] &&!!apiConfig['dtsRollupTrimming']) { // copy all files from publishFolderForPublic or publishFolderForBeta to publishFolderForInternal const toApiFolder =!!apiConfig['publishFolderForInternal']? apiConfig['publishFolderForInternal'] : './dist'; let fromApiFolder = undefined; if (this._releaseType.value === 'public') { fromApiFolder =!!apiConfig['publishFolderForPublic']? apiConfig['publishFolderForPublic'] : './dist/public'; } else if (this._releaseType.value === 'beta') { fromApiFolder =!!apiConfig['publishFolderForBeta']? apiConfig['publishFolderForBeta'] : './dist/beta'; } if (fromApiFolder) { const fromApiFolderPath = path.join(project.projectFolder, fromApiFolder); const toApiFolderPath = path.join(project.projectFolder, toApiFolder); if (node_core_library_1.FileSystem.exists(fromApiFolderPath) && node_core_library_1.FileSystem.exists(toApiFolderPath)) { node_core_library_1.FileSystem.readFolder(fromApiFolderPath).forEach(fileName => { node_core_library_1.FileSystem.copyFile({ sourcePath: path.join(fromApiFolderPath, fileName), destinationPath: path.join(toApiFolderPath, fileName) }); console.log(`Copied file ${fileName} from ${fromApiFolderPath} to ${toApiFolderPath}`); }); } } } /* tslint:enable:no-string-literal */ } } _calculateTarballName(project) { // Same logic as how npm forms the tarball name const packageName = project.packageName; const name = packageName[0] === '@'? packageName.substr(1).replace(/\//g, '-') : packageName; return `${name}-${project.packageJson.version}.tgz`; } } exports.PublishAction = PublishAction; //# sourceMappingURL=PublishAction.js.map ======================= File: node_modules/office-ui-fabric-react/lib/components/ResizeGroup/examples/ResizeGroup.Example.scss.js ======================= /* tslint:disable */ import { loadStyles } from '@microsoft/load-themed-styles'; loadStyles([{ "rawString": ".root_296de9bb{display:block}.resizeIsShort_296de9bb{width:400px}.buttonGroup_296de9bb{margin-bottom:40px}.buttonGroup_296de9bb button{margin-right:20px}.settingsGroup_296de9bb{padding-top:20px}.itemCountDropdown_296de9bb{width:180px}\n" }]); export var root = "root_296de9bb"; export var resizeIsShort = "resizeIsShort_296de9bb"; export var buttonGroup = "buttonGroup_296de9bb"; export var settingsGroup = "settingsGroup_296de9bb"; export var itemCountDropdown = "itemCountDropdown_296de9bb"; //# sourceMappingURL=ResizeGroup.Example.scss.js.map ======================= File: node_modules/office-ui-fabric-react/lib-amd/components/ContextualMenu/ContextualMenuItemWrapper/index.js ======================= define(["require", "exports", "tslib", "./ContextualMenuAnchor", "./ContextualMenuButton", "./ContextualMenuSplitButton", "./ContextualMenuItemWrapper"], function (require, exports, tslib_1, ContextualMenuAnchor_1, ContextualMenuButton_1, ContextualMenuSplitButton_1, ContextualMenuItemWrapper_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); tslib_1.__exportStar(ContextualMenuAnchor_1, exports); tslib_1.__exportStar(ContextualMenuButton_1, exports); tslib_1.__exportStar(ContextualMenuSplitButton_1, exports); tslib_1.__exportStar(ContextualMenuItemWrapper_1, exports); }); //# sourceMappingURL=index.js.map ======================= File: node_modules/@microsoft/sp-webpart-workbench/lib/resx-strings/eu-es.js ======================= define([], function() { var strings = { "_jP9TaPNRkCXWU4OplNcN+w": { "AriaWebPartOrSectionEnterTemplate": "{0}. Sakatu Sartu {1} atalean ibiltzeko. Barruan zaudenean, erabili Alt+F10 tresna-barrara joateko, erabili Alt+P propietateen panelera joateko eta sakatu Ihes {1} ataletik irteteko. ", "CanvasZoneAriaGoToToolbar": "Sakatu Sartu web zatian sartzeko. Barruan zaudenean, sakatu Ihes tresna-barrara itzultzeko.", "CanvasZoneAriaGoToWebPart": "Web zatiaren tresna-barrara joateko, sakatu Sartu, eta hona itzultzeko, sakatu Ihes.", "CanvasZoneAriaWebpartName": "{0} web zatia", "ConfirmationDialogYes": "Bai", "ConfirmationDialogNo": "Ez", "DeleteZoneConfirmationDialogMessage": "Ziur atala eta bertan dagoen guztia ezabatu nahi duzula?", "DeleteConfirmationDialogTitle": "Ezabatzeko berrespena", "DeleteConfirmationDialogMessage": "Ziur web zati hau ezabatu nahi duzula?", "TextWebPartDisplayName": "Testua", "ToolbarNavigationArrowKeys": "Erabili gezi-teklak tresna-barran nabigatzeko.", "ToolboxAriaLoadingAlert": "Web zatiak kargatzen ari dira tresnak.", "ToolboxAriaLoadingFinishedAlert": "Kargatu dituzte web zatiak tresnek.", "ToolboxErrorMessage": "Errore bat gertatu da web zatiak eskuratzean. Agian ez dira web zati guztiak egongo erabilgarri.", "ToolboxHintTitle": "Gehitu web zati bat", "ToolboxNavigationArrowKeys": "{0} Erabili Ezkerrera edo Eskuinera gezi-teklak nabigatzeko. Sakatu Sartu hautatutako web zatia gehitzeko.", "CanvasItems": "{0} elementu daude tresna-barran.||{0} elementu dago tresna-barran.||{0} elementu daude tresna-barran.", "CanvasItemsInterval": "0||1||2-", "ToolboxSectionHeader": "Atalaren diseinua", "ToolboxOneColumnPart": "Zutabe bat", "ToolboxTwoColumnPart": "Bi zutabe", "ToolboxThreeColumnPart": "Hiru zutabe", "ToolboxOneThirdRightColumnPart": "Eskuineko zutabearen herena", "ToolboxOneThirdLeftColumnPart": "Ezkerreko zutabearen herena", "ToolboxFullWidthColumnPart": "Zabalera osoko zutabea", "ToolboxVerticalColumnPart": "Zutabe bertikala", "ToolboxVerticalColumnToolTipText": "Ezin da gehitu zutabe bertikala, badagoelako beste bat dagoeneko edo zabalera osoko zutabe bat dagoelako orrian.", "ToolboxFullWidthColumnTooltipText": "Ezin da gehitu zabalera osoko zutabea, orriak zutabe bertikal bat duelako.", "SectionPropertyPaneTitle": "Atala", "SectionPropertyPaneColumnGroupName": "Diseinu-aukerak", "ToolbarSelectZone": "Hautatu atala", "DragIconFallbackRTEText": "Testua", "DragZoneHandleTitle": "Eramateko modua zehazteko, sakatu Sartu edo zuriune-tekla", "DragZoneMoveStarted": "Sakatu Gora gora joateko eta Behera behera joateko. Ondoren, sakatu Sartu norabide horretara joatea berresteko edo Ihes ez joateko. ", "DragZoneMoveComplete": "{0} kokapenetik {1} kokapenera eraman da web zatia. ", "DragZoneMoveCompleteZone": "Atala eraman da {0} kokapenetik {1} kokapenera", "DragZoneMoveCancelled": "Bertan behera utzi da joateko ekintza.", "DragZoneMoveNotAllowedAriaLabel": "Ezin da joan urrunago norabide horretan, edo atal horretan ez da onartzen inora joatea", "DragZoneMoveNotAllowed": "Ez da onartzen tokiz aldatzea", "DragZoneMoveInsideLevelControl": "{0}. posizioa", "DragZoneMoveInsideLevelSection": "{0}. zutabea, {1}. posizioa", "DragZoneMoveInsideLevelZone": "{0}. atala, {1}. zutabea, {2}. posizioa", "WebPartAriaLabel": "web zatia", "SectionContextualAriaLabel": "{0}, {1} ataleko web zatiak: {2}", "SectionAriaLabel": "atala", "WebPartsInSectionLabel": "{0}, {1}", "ToolboxHintSectionTitleOnlyLayouts": "Gehitu atal berri bat", "ToolboxHintTitleWithLayout": "Gehitu web zati bat {0}", "ToolboxHintColumnOne": "lehenengo zutabean", "ToolboxHintColumnTwo": "bigarren zutabean", "ToolboxHintColumnThree": "hirugarren zutabean", "EmptySectionAriaLabel": "ez dago web-zatirik", "SectionPositionAriaLabel": "{0}/{1} atala", "CloseButtonAriaLabel": "Itxi", "DeleteConfirmationLabel": "{0} ezabatu egin da.", "NarrowModeDialogTitle": "Handitu leihoaren zabalera", "NarrowModeDialogSubtitle": "Ezin da editatu arakatzaile-leiho estuetan. Editatzen jarraitzeko, handitu leihoaren zabalera.", "DialogDescription": "{0} leihoa: {1}", "SectionBackgroundPropertyColumnGroupName": "Atalaren atzeko planoa", "SectionBackgroundNeutralButtonLabel": "Neutroa", "SectionBackgroundSoftButtonLabel": "Leuna", "SectionBackgroundStrongButtonLabel": "Lodia", "SectionBackgroundNoneButtonLabel": "Bat ere ez", "CanvasVerticalSectionZoneLabel": "Zutabe bertikalen diseinuko atala", "YammerHighlightsWebpartTitle": "Aipagarrienak", "ToolbarDuplicateTitle": "Zati bikoiztua" }, "_n7GTqRbrtzGOgRYtCYt3Jw": { "FormattingBarMoreButtonTitle": "Gehiago", "TextWebPartPlaceholder": "Idatzi testua hemen." }, "_EJ1q3VoG+8ZXJZ4MxzV0eA": { "WebpartToolbarConfigButtonTitle": "Editatu web zatia", "WebpartToolbarMoveButtonTitle": "Eraman web zatia", "WebpartToolbarDeleteButtonTitle": "Ezabatu web zatia", "ToolboxHintTitleWithLayout": "Gehitu web zati bat {0}", "ToolboxHintColumnOne": "lehenengo zutabean", "ToolboxHintColumnTwo": "bigarren zutabean", "ToolboxHintColumnThree": "hirugarren zutabean" }, "_kfkx9h4IuXbYoZ4SdLEjrQ": { "ZoneToolbarConfigButtonTitle": "Editatu atala", "ZoneToolbarMoveButtonTitle": "Eraman atala", "ZoneToolbarDeleteButtonTitle": "Ezabatu atala", "ToolboxNavigationArrowKeys": "{0} Erabili Ezkerrera edo Eskuinera gezi-teklak nabigatzeko. Sakatu Sartu hautatutako web zatia gehitzeko." }, "_bKMsmDAqUqbOL6h9rxYuIw": { "FormattingBarClearFormattingButtonTitle": "Garbitu formatu guztiak", "FormattingBarNormalTextButtonTitle": "Testu normala", "FormattingBarHeading2ButtonTitle": "1. izenburua", "FormattingBarHeading3ButtonTitle": "2. izenburua", "FormattingBarHeading4ButtonTitle": "3. izenburua", "FormattingBarQuoteButtonTitle": "Aipua", "ToolbarNavigationArrowKeys": "Erabili gezi-teklak tresna-barran nabigatzeko.", "RTESettingsText": "Testuaren eta taulen formatua", "FontDropDownText": "Letra-tipoaren estiloa", "ParagraphGroupText": "Paragrafoa", "FontSizeDropDownLabel": "Letra-tamaina", "TableGroup": "Taula", "InsertAndDeleteGroupLabel": "Txertatu eta ezabatu", "FontColorLabel": "Letra-kolorea", "StandardColorLabel": "Kolore estandarrak", "DefaultColorLabel": "Automatikoa", "RedDarkLabel": "Gorri iluna", "RedLabel": "Gorria", "YellowLabel": "Horia", "GreenLightLabel": "Berde argia", "GreenLabel": "Berdea", "GreenDarkLabel": "Berde iluna", "BlueLightLabel": "Urdin argia", "BlueLabel": "Urdina", "BlueDarkLabel": "Urdin iluna", "PurpleLabel": "Morea", "HightlightLabel": "Nabarmentzeko kolorea", "HightlightColorsLabel": "Nabarmentze-koloreak", "PinkLabel": "Arrosa", "OrangeLabel": "Laranja", "RemoveHighlightColor": "Kolorerik ez", "HyperlinkGroupLabel": "Hiperesteka", "TealLabel": "Urdin berdexka", "MagentaLabel": "Magenta", "AquaLabel": "Urdin-berdea", "MaroonLabel": "Granatea", "GoldLabel": "Urre-kolorea", "GreyLabel": "Grisa", "DarkGreyLabel": "Gris iluna", "BlackLabel": "Beltza", "ThemeColorGroupLabel": "Gaiaren koloreak", "ThemeDarkerLabel": "Gai ilunagoa", "ThemeDarkLabel": "Gai iluna", "ThemeDarkAltLabel": "Ordezko gai iluna", "ThemePrimaryLabel": "Gai nagusia", "ThemeSecondaryLabel": "Bigarren mailako gaia", "NeutralDarkLabel": "Kolore neutro iluna", "NeutralPrimaryLabel": "Kolore neutro nagusia", "NeutralPrimaryAltLabel": "Ordezko kolore neutro nagusia", "NeutralSecondaryLabel": "Bigarren mailako kolore neutroa", "NeutralTertiaryLabel": "Hirugarren mailako kolore neutroa", "TableStylesGroupLabel": "Taula-estiloak", "AlignTableGroupLabel": "Taularen lerrokatzea", "FormattingBarPreButtonTitle": "Tarte bakarrekoa" }, "_/GZrHjuQO4erDQbBRI2XSA": { "DialogTitle": "Txertatu esteka", "UrlTextFieldLabel": "Helbidea", "UrlTextFieldAriaLabel": "Estekatu beharreko web-helbidea", "UrlTextFieldError": "Ez dira onartzen mota horretako estekak.", "TitleTextFieldLabel": "Bistaratu beharreko testua", "RecentPagesLabel": "Guneko azken orriak", "SearchForPagesLabel": "Bilaketarekin bat datozen orriak gune honetan", "RecentSpacesLabel": "Most recent spaces on this site", "SearchForSpacesLabel": "Spaces on this site that match your search", "NoResultLabel": "Ez dago bilaketarekin bat datorren ezer", "TryAgainLabel": "Saiatu beste gako-hitz batekin", "OpenLinkInNewTabLabel": "Ireki beste fitxa batean", "SaveButtonLabel": "Gorde", "CancelButtonLabel": "Utzi", "UnlinkButtonLabel": "Kendu esteka", "TitleSuggestionsColumnName": "Izena", "EditorSuggestionsColumnName": "Aldaketen egilea", "ModifiedSuggestionsColumnName": "Aldatze-data", "PageContentContainsSearchText": "Eduki-orrietan aurkitu da \"{0}\"", "CurrentPage": "(uneko orria)", "SearchTextFieldLabel": "Bilatu", "SearchPagesTextFieldPlaceholder": "Idatzi guneko orriak bilatzeko gako-hitzak", "SearchSpacesTextFieldPlaceholder": "Enter keywords to search for spaces on this site", "DialogAriaDescription": "Txertatu uneko guneko edo beste gune bateko orri baterako esteka.", "SuggestionsListAriaLabel": "Hautatu {0} zerrendako orri bat. Sakatu Gora eta Behera gezi-teklak orrietan ibiltzeko. Sakatu zuriune-tekla orri bat hautatzeko. Orri bat hautatutakoan, orrirako esteka erabiliko da esteka idazteko koadroan. Ez badago testurik bistaratu beharreko testuaren koadroan, orriaren izena erabiliko da.", "SaveButtonDisabledScreenReaderAlert": "Gordetzeko botoia ez dago erabilgarri idatzitako web-helbideak ez duelako balio.", "SaveButtonEnabledScreenReaderAlert": "Gordetzeko botoia erabilgarri dago.", "PageIsSelectedScreenReaderAlert": "{0} orria hautatu da.", "IsSearching": "Bilatzen...", "SearchResultsShowing": "Ikusgai daude bilaketa-emaitzak. Bilaketa-emaitzen zerrendara joateko, sakatu tabuladorea.", "RecentPagesShowing": "Azken orrien zerrenda dago ikusgai. Azken orrien zerrendara joateko, sakatu tabuladorea." }, "_4SOrKBlkyRLkXWcT6txoow": { "ToolboxSearchAccessibleLabelTemplate": "Web zatia bilatzeko, idatzi hemen. {0}", "ToolboxSearchEscapeAccessibleLabel": "Lehendik dagoen bilaketa garbitzeko, sakatu Ihes.", "ToolboxSearchLabel": "Bilatu" }, "_6tOZemhV08aF1IgNDNeiwQ": { "ToolboxGroupNameFullWidth": "Web zati hauetako bat gehi dezakezu zabalera osoko zutabean" }, "_NS+5Kf9zpnH1/LStsp+Tfw": { "ToolboxCategoryTextMediaAndContent": "Testua, multimedia-elementuak eta edukia", "ToolboxCategoryDiscovery": "Ezagutu", "ToolboxCategoryCommunicationAndCollaboration": "Komunikazioa eta lankidetza", "ToolboxCategoryPlanningAndProcess": "Plangintza eta prozesuak", "ToolboxCategoryBusinessIntelligence": "Enpresa eta informazioa", "ToolboxCategorySiteTools": "Gunearen tresnak", "ToolboxCategoryConnectors": "Konektoreak", "ToolboxCategoryOther": "Beste batzuk", "ToolboxGroupNameFeatured": "Nagusiak", "ToolboxGroupNameAlphabetical": "Guztiak, A-Z", "ToolboxGroupNameSection": "Atalaren diseinua" }, "_RRzf46hnc4+fBX8RHyocNg": { "TextWebPartDisplayName": "Testua", "TextWebpartDescription": "Gehitu testua eta eman iezaiozu formatua" }, "_2TT4IG31kAjRqhD0h5kPOg": { "ToolboxGroupSeeAllButtonLabel": "Ikusi guztiak", "ToolboxGroupSeeAllButtonAriaLabel": "Ikusi {0} taldeko web zatiak.", "ToolboxGroupAriaLabel": "{0} zerrenda. Zerrendan ibiltzeko, erabili Eskuinera eta Ezkerrera gezi-teklak." }, "_z2ZwCbA+UxeGBoG5w1HCOA": { "SearchResultAlert": "{0} elementu daude tresnetan.||{0} elementu dago tresnetan.||{0} elementu daude tresnetan.", "SearchResultAlertIntervals": "0||1||2-" }, "_WVn4QXYnL8WpGCqr2C9ySA": { "ToolboxCategoryAllCategory": "Guztiak, kategoriaren arabera", "ToolboxCategorySortingCategory": "Guztiak, A-Z", "ToolboxCategorySearchResults": "Bilaketa-emaitzak", "ToolboxCollapseButtonDescription": "Aldatu tresna handiak tresna txikiengatik", "NoResultLabel": "Ez dago bilaketarekin bat datorren elementurik", "TryAgainLabel": "Erabili beste gako-hitz bat", "LargeToolboxAriaTitle": "Web zati honen tresnak ireki dira.", "ToolboxCollapseButtonAriaLabel": "Tolestu.", "DropDownMenuAriaLabel": "{0} kategoriako web zatiak daude ikusgai.", "SwitchCategoryAlert": "{0} kategoriara aldatu da.", "BackButtonAriaLabel": "Itzuli aurreko ikuspegira." }, "_CZsUWMvZilAKKAfwQSdzKQ": { "ToolboxExpandButtonTitle": "Zabaldu hau web zati gehiago ikusteko", "ToolboxNoItemsFound": "Ez dugu aurkitu zure bilaketarekin bat datorren ezer." }, "_acoNwVeh/QF9PsLoQfUb2A": { "FormattingBarAlignCenterButtonTitle": "Zentratu", "FormattingBarAlignLeftButtonTitle": "Lerrokatu ezkerrean", "FormattingBarAlignRightButtonTitle": "Lerrokatu eskuinean", "FormattingBarBoldButtonTitle": "Lodia ({0}+B)", "FormattingBarBulletListButtonTitle": "Buletdun zerrenda", "FormattingBarClearFormattingButtonTitle": "Garbitu formatu guztiak", "FormattingBarConfirmAction": "{0} egin da.", "FormattingBarConfirmActionOnSelection": "{0} egin da hautatutako testu honetan: {1}", "FormattingBarNormalTextButtonTitle": "Testu normala", "FormattingBarHeading2ButtonTitle": "1. izenburua", "FormattingBarHeading3ButtonTitle": "2. izenburua", "FormattingBarHeading4ButtonTitle": "3. izenburua", "FormattingBarQuoteButtonTitle": "Aipua", "FormattingBarItalicButtonTitle": "Etzana ({0}+I)", "FormattingBarLinkButtonTitle": "Hiperesteka ({0}+K)", "FormattingBarNumberedListButtonTitle": "Zenbakidun zerrenda", "FormattingBarUnderlineButtonTitle": "Azpimarra ({0}+U)", "FormattingBarUnlinkButtonTitle": "Kendu esteka", "UndoButtonTitle": "Desegin ({0}+Z)", "RedoButtonTitle": "Berregin ({0}+Y)", "FormattingBarAccessibleLabel": "Formatua", "LinkDialogErrorNotSupportedLink": "Ez dira onartzen mota horretako estekak.", "LinkDialogTextFieldAriaLabel": "Estekatu beharreko web-helbidea", "LinkDialogTextFieldLabel": "Web-helbidea:", "LinkDialogDisplayTextFieldLabel": "Bistaratzeko testua:", "LinkDialogTitle": "Txertatu esteka", "RichTextEditorAriaLabel": "Testu-editorea. Sakatu Alt+F10 tresna-barretara joateko.", "RichTextEditorTitle": "Testu-editorea", "RichTextEditorIframeTitle": "{0} {1}", "RichTextLinkDialogCancelButtonLabel": "Utzi", "RichTextLinkDialogSaveButtonLabel": "Gorde", "RichTextNavigationAltF10Keys": "{0} {1}", "ToolbarNavigationArrowKeys": "Erabili gezi-teklak tresna-barran nabigatzeko.", "ToolbarNavigationTabKeys": "Erabili tabuladorea tresna-barra batetik bestera aldatzeko.", "ToolbarNavigationShiftTabKey": "Sakatu Maius + tabuladorea testu-koadrora itzultzeko", "ImagesInTableNotSupported": "Ezin da itsatsi irudia taularen barruan. Itsatsi irudia taulatik kanpo.", "MultiImagePasteInIENotSupported": "Ezin dira itsatsi taula barruan edo testuz inguratuta dauden irudiak. Kopiatu irudia bakarrik, taula edo testua gabe, eta saiatu berriro.", "CloseWarningText": "Itxi abisu hau: {0} ", "LoadingText": "Itsasten...", "AddRowAboveText": "Txertatu gainean", "AddRowBelowText": "Txertatu azpian", "DeleteRowText": "Ezabatu errenkada", "AddColumnLeftText": "Txertatu ezkerrean", "AddColumnRightText": "Txertatu eskuinean", "AddRowAboveShortcutText": "{0} ({1}+Maius+A)", "AddRowBelowShortcutText": "{0} ({1}+Maius+Z)", "DeleteRowShortcutText": "{0} ({1}+Maius+D)", "StrikeThroughButtonLabel": "Marratua", "SuperscriptButtonLabel": "Goi-indizea", "SubscriptButtonLabel": "Azpiindizea", "JustifyButtonLabel": "Justifikatu", "IncreaseIndentButtonLabel": "Handitu koska", "DecreaseIndentButtonLabel": "Txikitu koska", "FontSizeDropDownLabel": "Letra-tamaina", "TableTitle": "Taula", "TableButtonLabel": "Txertatu taula", "InsertRowBeforeButtonLabel": "Txertatu gainean", "InsertRowAfterButtonLabel": "Txertatu azpian", "InsertColumnLeftButtonLabel": "Txertatu ezkerrean", "InsertColumnRightButtonLabel": "Txertatu eskuinean", "DeleteRowButtonLabel": "Ezabatu errenkada", "DeleteColumnButtonLabel": "Ezabatu zutabea", "DeleteTableButtonLabel": "Ezabatu taula", "FontColorLabel": "Letra-kolorea", "HightlightLabel": "Nabarmentzeko kolorea", "SimpleTableButtonLabel": "Arrunta", "TableWithHeaderBorderLabel": "Goiburu mehea", "TableWithFilledHeaderLabel": "Goiburua", "TableWithBandedRowsLabel": "Txandakako errenkadak", "TableWithBandedRowsAndColumnsLabel": "Zutabe-goiburua", "SimpleTableButtonThemeLabel": "Gaiaren kolorea duen taula arrunta", "TableWithHeaderBorderThemeLabel": "Gaiaren kolorea duen goiburu mehea", "TableWithFilledHeaderThemeLabel": "Gaiaren kolorea duen goiburua", "TableWithBandedRowsThemeLabel": "Gaiaren kolorea duen txandakako errenkada", "TableWithBandedRowsAndColumnsThemeLabel": "Gaiaren kolorea duen zutabe-goiburua", "AlignTableLeftLabel": "Lerrokatu taula ezkerrean", "AlignTableCenterLabel": "Lerrokatu taula erdian", "AlignTableRightLabel": "Lerrokatu taula eskuinean", "RTEPagePickerSaveAction": "Gehitu da {0} esteka.", "RTEPagePickerUnlinkAction": "Kendu da {0} esteka.", "FormattingBarPreButtonTitle": "Tarte bakarrekoa", "CommandShortcutOnMac": "⌘", "ControlShortcutOnWin": "Ktrl" }, "_NAR8NFw8cblGJm9t5CjqOw": { "SuccessfullyLoadedText": "Kargatu dira arazte-manifestuak.", "ErrorLoadingText": "Ezin izan dira kargatu arazte-manifestu hauek: {0}" }, "_vd/LT/qfiQhbHFfeM1GtlA": { "FetchFailedError": "Fetching webpats failed with error \"{0}\". Render of a cached workbench may fail." }, "_8EVKOH1av6NjR/ZNfdafrw": { "WebPartData": "Web Part Data", "ClassicPages": "Orri klasikoak", "ModernPages": "Orri modernoak", "Close": "Itxi", "WebPartDataHelpInfoLink": "Learn about provisioning SharePoint assets from your SharePoint client-side web part" }, "_FQya7ZjwIyrOEutOa+omIA": { "Title": "Abisua", "SubText": "Web zatiak ez dira agertuko tresnetan. Ziurtatu \"gulp serve\" exekutatzen ari dela web zatiaren proiektuan. Freskatu orria \"gulp serve\" exekutatzen hasten denean.", "OkButtonText": "Ados", "ClickHerePrefix": "Egin klik ", "ClickHereLink": "hemen", "ClickHereSuffix": " informazio gehiago lortzeko." }, "_1JArBGDet5Uj9pJOV/9sFw": { "UrlTextBoxPlaceholder": "Idatzi URLa mugikorretarako aurrebistaren tresnan ikusteko.", "ScreenReaderMobilePreviewEntered": "Mugikorretarako aurrebistaren tresnan sartu zara. Beste orri bat aurreikusi nahi baduzu, idatzi URLa URLen testu-eremuan. Tresna itxi eta lan-eremura itzultzeko, sakatu Ihes.", "ScreenReaderDevicePickerEntered": "Erabili Eskuinera eta Ezkerrera teklak pantailaren aurrebistaren tamaina aldatzeko erabili nahi duzun gailua aukeratzeko.", "ScreenReaderDevicePickerSelectionChanged": "Sakatu Sartu gailua aukeratzeko.", "Width": "Zabalera", "Height": "Altuera" }, "_IusqdbcSoVYQiit3+QRSxw": { "Office365Title": "Office 365", "SharePointWorkbenchTitle": "SharePoint Workbench", "ScreenReaderDisplayModeSwitchToEditMode": "Aurrebista modutik editatze modura aldatu da.", "ScreenReaderDisplayModeSwitchToReadMode": "Editatze modutik aurrebista modura aldatu da." }, "_nCtJlVOXBHa59LgYtajnjA": { "Save": "Gorde", "SaveAltText": "Erabili uneko lan-eremuaren egoera gordetzeko.", "Discard": "Baztertu", "DiscardAltText": "Erabili uneko lan-eremuaren egoera baztertzeko.", "Mobile": "Mugikorra", "MobleAltText": "Erabili telefono mugikorretarako aurrebistaren tresna mugikorretarako irekitzeko.", "Tablet": "Tableta", "TabletAltText": "Erabili mugikorretarako aurrebistaren tresna tabletetarako irekitzeko.", "Preview": "Aurrebista", "PreviewAltText": "Erabili editatze modutik aurrebista modura aldatzeko.", "Edit": "Editatu", "EditAltText": "Erabili editatze moduan sartzeko.", "WebPartData": "Web part data", "WebPartDataAltText": "Display the serialized web part data." } }; strings.default = strings; return strings; }); ======================= File: node_modules/@microsoft/sp-loader/lib/DeveloperTools/BrowserDeveloperToolsWarning/BrowserDeveloperToolsWarning.scss.js ======================= require("./BrowserDeveloperToolsWarning.css"); ======================= File: node_modules/office-ui-fabric-react/lib-amd/components/ChoiceGroup/index.js ======================= define(["require", "exports", "tslib", "./ChoiceGroup", "./ChoiceGroup.base", "./ChoiceGroupOption/index"], function (require, exports, tslib_1, ChoiceGroup_1, ChoiceGroup_base_1, index_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); tslib_1.__exportStar(ChoiceGroup_1, exports); tslib_1.__exportStar(ChoiceGroup_base_1, exports); tslib_1.__exportStar(index_1, exports); }); //# sourceMappingURL=index.js.map ======================= File: node_modules/office-ui-fabric-react/lib/components/TextField/examples/TextField.AllErrorMessage.Example.js ======================= import * as tslib_1 from "tslib"; import * as React from'react'; import { TextField } from 'office-ui-fabric-react/lib/TextField'; import './TextField.Examples.scss'; var TextFieldAllErrorMessageExample = /** @class */ (function (_super) { tslib_1.__extends(TextFieldAllErrorMessageExample, _super); function TextFieldAllErrorMessageExample() { return _super!== null && _super.apply(this, arguments) || this; } TextFieldAllErrorMessageExample.prototype.render = function () { return (React.createElement("div", { className: "docs-TextFieldExample" }, React.createElement(TextField, { errorMessage: "Error message", label: "Default with error message" }), React.createElement(TextField, { errorMessage: "Error message", placeholder: "Placeholder with error message" }), React.createElement(TextField, { errorMessage: "Error message", label: "Underlined with error message:", underlined: true }), React.createElement(TextField, { errorMessage: "Error message", label: "Multiline with error message", multiline: true, rows: 4 }))); }; return TextFieldAllErrorMessageExample; }(React.Component)); export { TextFieldAllErrorMessageExample }; //# sourceMappingURL=TextField.AllErrorMessage.Example.js.map ======================= File: node_modules/office-ui-fabric-react/lib/components/GroupedList/GroupedListSection.js ======================= import * as tslib_1 from "tslib"; import * as React from'react'; import { BaseComponent } from '../../Utilities'; import { SELECTION_CHANGE } from '../../utilities/selection/index'; import { GroupHeader } from './GroupHeader'; import { GroupShowAll } from './GroupShowAll'; import { GroupFooter } from './GroupFooter'; import { List } from '../../List'; import { assign, css, getId } from '../../Utilities'; var DEFAULT_DROPPING_CSS_CLASS = 'is-dropping'; var GroupedListSection = /** @class */ (function (_super) { tslib_1.__extends(GroupedListSection, _super); function GroupedListSection(props) { var _this = _super.call(this, props) || this; _this._root = React.createRef(); _this._list = React.createRef(); _this._onRenderGroupHeader = function (props) { return React.createElement(GroupHeader, tslib_1.__assign({}, props)); }; _this._onRenderGroupShowAll = function (props) { return React.createElement(GroupShowAll, tslib_1.__assign({}, props)); }; _this._onRenderGroupFooter = function (props) { return React.createElement(GroupFooter, tslib_1.__assign({}, props)); }; _this._renderSubGroup = function (subGroup, subGroupIndex) { var _a = _this.props, dragDropEvents = _a.dragDropEvents, dragDropHelper = _a.dragDropHelper, eventsToRegister = _a.eventsToRegister, getGroupItemLimit = _a.getGroupItemLimit, groupNestingDepth = _a.groupNestingDepth, groupProps = _a.groupProps, items = _a.items, headerProps = _a.headerProps, showAllProps = _a.showAllProps, footerProps = _a.footerProps, listProps = _a.listProps, onRenderCell = _a.onRenderCell, selection = _a.selection, selectionMode = _a.selectionMode, viewport = _a.viewport, onRenderGroupHeader = _a.onRenderGroupHeader, onRenderGroupShowAll = _a.onRenderGroupShowAll, onRenderGroupFooter = _a.onRenderGroupFooter, onShouldVirtualize = _a.onShouldVirtualize, group = _a.group, compact = _a.compact; return!subGroup || subGroup.count > 0 || (groupProps && groupProps.showEmptyGroups)? (React.createElement(GroupedListSection, { ref:'subGroup_' + subGroupIndex, key: _this._getGroupKey(subGroup, subGroupIndex), dragDropEvents: dragDropEvents, dragDropHelper: dragDropHelper, eventsToRegister: eventsToRegister, footerProps: footerProps, getGroupItemLimit: getGroupItemLimit, group: subGroup, groupIndex: subGroupIndex, groupNestingDepth: groupNestingDepth, groupProps: groupProps, headerProps: headerProps, items: items, listProps: listProps, onRenderCell: onRenderCell, selection: selection, selectionMode: selectionMode, showAllProps: showAllProps, viewport: viewport, onRenderGroupHeader: onRenderGroupHeader, onRenderGroupShowAll: onRenderGroupShowAll, onRenderGroupFooter: onRenderGroupFooter, onShouldVirtualize: onShouldVirtualize, groups: group.children, compact: compact })) : null; }; /** * collect all the data we need to enable drag/drop for a group */ _this._getGroupDragDropOptions = function () { var _a = _this.props, group = _a.group, groupIndex = _a.groupIndex, dragDropEvents = _a.dragDropEvents, eventsToRegister = _a.eventsToRegister; var options = { eventMap: eventsToRegister, selectionIndex: -1, context: { data: group, index: groupIndex, isGroup: true }, canDrag: function () { return false; }, canDrop: dragDropEvents.canDrop, updateDropState: _this._updateDroppingState }; return options; }; /** * update groupIsDropping state based on the input value, which is used to change style during drag and drop * * @private * @param {boolean} newValue (new isDropping state value) * @param {DragEvent} event (the event trigger dropping state change which can be dragenter, dragleave etc) */ _this._updateDroppingState = function (newIsDropping, event) { var isDropping = _this.state.isDropping; var dragDropEvents = _this.props.dragDropEvents; if (!isDropping) { if (dragDropEvents && dragDropEvents.onDragLeave) { dragDropEvents.onDragLeave(event, undefined); } } else { if (dragDropEvents && dragDropEvents.onDragEnter) { dragDropEvents.onDragEnter(event, undefined); } } if (isDropping!== newIsDropping) { _this.setState({ isDropping: newIsDropping }); } }; var selection = props.selection, group = props.group; _this._id = getId('GroupedListSection'); _this.state = { isDropping: false, isSelected: selection && group? selection.isRangeSelected(group.startIndex, group.count) : false }; return _this; } GroupedListSection.prototype.componentDidMount = function () { var _a = this.props, dragDropHelper = _a.dragDropHelper, selection = _a.selection; if (dragDropHelper && this._root.current) { this._dragDropSubscription = dragDropHelper.subscribe(this._root.current, this._events, this._getGroupDragDropOptions()); } if (selection) { this._events.on(selection, SELECTION_CHANGE, this._onSelectionChange); } }; GroupedListSection.prototype.componentWillUnmount = function () { if (this._dragDropSubscription) { this._dragDropSubscription.dispose(); } }; GroupedListSection.prototype.componentDidUpdate = function (previousProps) { if (this.props.group!== previousProps.group || this.props.groupIndex!== previousProps.groupIndex || this.props.dragDropHelper!== previousProps.dragDropHelper) { if (this._dragDropSubscription) { this._dragDropSubscription.dispose(); delete this._dragDropSubscription; } if (this.props.dragDropHelper && this._root.current) { this._dragDropSubscription = this.props.dragDropHelper.subscribe(this._root.current, this._events, this._getGroupDragDropOptions()); } } }; GroupedListSection.prototype.render = function () { var _a = this.props, getGroupItemLimit = _a.getGroupItemLimit, group = _a.group, groupIndex = _a.groupIndex, headerProps = _a.headerProps, showAllProps = _a.showAllProps, footerProps = _a.footerProps, viewport = _a.viewport, selectionMode = _a.selectionMode, _b = _a.onRenderGroupHeader, onRenderGroupHeader = _b === void 0? this._onRenderGroupHeader : _b, _c = _a.onRenderGroupShowAll, onRenderGroupShowAll = _c === void 0? this._onRenderGroupShowAll : _c, _d = _a.onRenderGroupFooter, onRenderGroupFooter = _d === void 0? this._onRenderGroupFooter : _d, onShouldVirtualize = _a.onShouldVirtualize, groupedListClassNames = _a.groupedListClassNames, groups = _a.groups, compact = _a.compact; var isSelected = this.state.isSelected; var renderCount = group && getGroupItemLimit? getGroupItemLimit(group) : Infinity; var isShowAllVisible = group &&!group.children &&!group.isCollapsed &&!group.isShowingAll && (group.count > renderCount || group.hasMoreData); var hasNestedGroups = group && group.children && group.children.length > 0; var dividerProps = { group: group, groupIndex: groupIndex, groupLevel: group? group.level : 0, isSelected: isSelected, viewport: viewport, selectionMode: selectionMode, groups: groups, compact: compact }; var ariaControlsProps = { groupedListId: this._id }; var groupHeaderProps = assign({}, headerProps, dividerProps, ariaControlsProps); var groupShowAllProps = assign({}, showAllProps, dividerProps); var groupFooterProps = assign({}, footerProps, dividerProps); return (React.createElement("div", { ref: this._root, className: css(groupedListClassNames && groupedListClassNames.group, this._getDroppingClassName()), role: "presentation" }, onRenderGroupHeader(groupHeaderProps, this._onRenderGroupHeader), group && group.isCollapsed? null : hasNestedGroups? (React.createElement(List, { role: "presentation", ref: this._list, items: group.children, onRenderCell: this._renderSubGroup, getItemCountForPage: this._returnOne, onShouldVirtualize: onShouldVirtualize, id: this._id })) : (this._onRenderGroup(renderCount)), group && group.isCollapsed? null : isShowAllVisible && onRenderGroupShowAll(groupShowAllProps, this._onRenderGroupShowAll), onRenderGroupFooter(groupFooterProps, this._onRenderGroupFooter))); }; GroupedListSection.prototype.forceUpdate = function () { _super.prototype.forceUpdate.call(this); this.forceListUpdate(); }; GroupedListSection.prototype.forceListUpdate = function () { var group = this.props.group; if (this._list.current) { this._list.current.forceUpdate(); if (group && group.children && group.children.length > 0) { var subGroupCount = group.children.length; for (var i = 0; i < subGroupCount; i++) { var subGroup = this._list.current.refs['subGroup_' + String(i)]; if (subGroup) { subGroup.forceListUpdate(); } } } } else { var subGroup = this.refs['subGroup_' + String(0)]; if (subGroup) { subGroup.forceListUpdate(); } } }; GroupedListSection.prototype._onSelectionChange = function () { var _a = this.props, group = _a.group, selection = _a.selection; var isSelected = selection.isRangeSelected(group.startIndex, group.count); if (isSelected!== this.state.isSelected) { this.setState({ isSelected: isSelected }); } }; GroupedListSection.prototype._onRenderGroupCell = function (onRenderCell, groupNestingDepth) { return function (item, itemIndex) { return onRenderCell(groupNestingDepth, item, itemIndex); }; }; GroupedListSection.prototype._onRenderGroup = function (renderCount) { var _a = this.props, group = _a.group, items = _a.items, onRenderCell = _a.onRenderCell, listProps = _a.listProps, groupNestingDepth = _a.groupNestingDepth, onShouldVirtualize = _a.onShouldVirtualize; var count = group? group.count : items.length; var startIndex = group? group.startIndex : 0; return (React.createElement(List, tslib_1.__assign({ role: "grid", items: items, onRenderCell: this._onRenderGroupCell(onRenderCell, groupNestingDepth), ref: this._list, renderCount: Math.min(count, renderCount), startIndex: startIndex, onShouldVirtualize: onShouldVirtualize, id: this._id }, listProps))); }; GroupedListSection.prototype._returnOne = function () { return 1; }; GroupedListSection.prototype._getGroupKey = function (group, index) { return 'group-' + (group && group.key? group.key : String(group.level) + String(index)); }; /** * get the correct css class to reflect the dropping state for a given group * * If the group is the current drop target, return the default dropping class name * Otherwise, return ''; * */ GroupedListSection.prototype._getDroppingClassName = function () { var isDropping = this.state.isDropping; var _a = this.props, group = _a.group, groupedListClassNames = _a.groupedListClassNames; isDropping =!!(group && isDropping); return css(isDropping && DEFAULT_DROPPING_CSS_CLASS, isDropping && groupedListClassNames && groupedListClassNames.groupIsDropping); }; return GroupedListSection; }(BaseComponent)); export { GroupedListSection }; //# sourceMappingURL=GroupedListSection.js.map ======================= File: node_modules/office-ui-fabric-react/lib/utilities/positioning.js ======================= export * from './positioning/index'; //# sourceMappingURL=positioning.js.map ======================= File: node_modules/office-ui-fabric-react/lib-amd/components/DetailsList/examples/DetailsList.DragDrop.Example.js ======================= // @codepen define(["require", "exports", "tslib", "react", "office-ui-fabric-react/lib/Link", "office-ui-fabric-react/lib/DetailsList", "office-ui-fabric-react/lib/MarqueeSelection", "office-ui-fabric-react/lib/utilities/exampleData", "office-ui-fabric-react/lib/TextField", "office-ui-fabric-react/lib/Toggle", "office-ui-fabric-react/lib/Styling"], function (require, exports, tslib_1, React, Link_1, DetailsList_1, MarqueeSelection_1, exampleData_1, TextField_1, Toggle_1, Styling_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var theme = Styling_1.getTheme(); var margin = '0 30px 20px 0'; var dragEnterClass = Styling_1.mergeStyles({ backgroundColor: theme.palette.neutralLight }); var controlWrapperClass = Styling_1.mergeStyles({ display: 'flex', flexWrap: 'wrap' }); var textFieldStyles = { root: { margin: margin }, fieldGroup: { maxWidth: '100px' } }; var DetailsListDragDropExample = /** @class */ (function (_super) { tslib_1.__extends(DetailsListDragDropExample, _super); function DetailsListDragDropExample(props) { var _this = _super.call(this, props) || this; _this._handleColumnReorder = function (draggedIndex, targetIndex) { var draggedItems = _this.state.columns[draggedIndex]; var newColumns = _this.state.columns.slice(); // insert before the dropped item newColumns.splice(draggedIndex, 1); newColumns.splice(targetIndex, 0, draggedItems); _this.setState({ columns: newColumns }); }; _this._onChangeStartCountText = function (event, text) { _this.setState({ frozenColumnCountFromStart: text }); }; _this._onChangeEndCountText = function (event, text) { _this.setState({ frozenColumnCountFromEnd: text }); }; _this._onChangeColumnReorderEnabled = function (ev, checked) { _this.setState({ isColumnReorderEnabled: checked }); }; _this._onItemInvoked = function (item) { alert("Item invoked: " + item.name); }; _this._onRenderItemColumn = function (item, index, column) { var key = column.key; if (key === 'name') { return React.createElement(Link_1.Link, { "data-selection-invoke": true }, item[key]); } return String(item[key]); }; _this._selection = new DetailsList_1.Selection(); _this._dragDropEvents = _this._getDragDropEvents(); _this._draggedIndex = -1; var items = exampleData_1.createListItems(10, 0); _this.state = { items: items, columns: DetailsList_1.buildColumns(items, true), isColumnReorderEnabled: true, frozenColumnCountFromStart: '1', frozenColumnCountFromEnd: '0' }; return _this; } DetailsListDragDropExample.prototype.render = function () { var _a = this.state, items = _a.items, columns = _a.columns, isColumnReorderEnabled = _a.isColumnReorderEnabled, frozenColumnCountFromStart = _a.frozenColumnCountFromStart, frozenColumnCountFromEnd = _a.frozenColumnCountFromEnd; return (React.createElement("div", null, React.createElement("div", { className: controlWrapperClass }, React.createElement(Toggle_1.Toggle, { label: "Enable column reorder", checked: isColumnReorderEnabled, onChange: this._onChangeColumnReorderEnabled, onText: "Enabled", offText: "Disabled", styles: { root: { margin: margin } } }), React.createElement(TextField_1.TextField, { label: "Number of left frozen columns", onGetErrorMessage: this._validateNumber, value: frozenColumnCountFromStart, onChange: this._onChangeStartCountText, styles: textFieldStyles }), React.createElement(TextField_1.TextField, { label: "Number of right frozen columns", onGetErrorMessage: this._validateNumber, value: frozenColumnCountFromEnd, onChange: this._onChangeEndCountText, styles: textFieldStyles })), React.createElement(MarqueeSelection_1.MarqueeSelection, { selection: this._selection }, React.createElement(DetailsList_1.DetailsList, { setKey: "items", items: items, columns: columns, selection: this._selection, selectionPreservedOnEmptyClick: true, onItemInvoked: this._onItemInvoked, onRenderItemColumn: this._onRenderItemColumn, dragDropEvents: this._dragDropEvents, columnReorderOptions: this.state.isColumnReorderEnabled? this._getColumnReorderOptions() : undefined, ariaLabelForSelectionColumn: "Toggle selection", ariaLabelForSelectAllCheckbox: "Toggle selection for all items" })))); }; DetailsListDragDropExample.prototype._getColumnReorderOptions = function () { return { frozenColumnCountFromStart: parseInt(this.state.frozenColumnCountFromStart, 10), frozenColumnCountFromEnd: parseInt(this.state.frozenColumnCountFromEnd, 10), handleColumnReorder: this._handleColumnReorder }; }; DetailsListDragDropExample.prototype._validateNumber = function (value) { return isNaN(Number(value))? "The value should be a number, actual is " + value + "." : ''; }; DetailsListDragDropExample.prototype._getDragDropEvents = function () { var _this = this; return { canDrop: function (dropContext, dragContext) { return true; }, canDrag: function (item) { return true; }, onDragEnter: function (item, event) { // return string is the css classes that will be added to the entering element. return dragEnterClass; }, onDragLeave: function (item, event) { return; }, onDrop: function (item, event) { if (_this._draggedItem) { _this._insertBeforeItem(item); } }, onDragStart: function (item, itemIndex, selectedItems, event) { _this._draggedItem = item; _this._draggedIndex = itemIndex; }, onDragEnd: function (item, event) { _this._draggedItem = undefined; _this._draggedIndex = -1; } }; }; DetailsListDragDropExample.prototype._insertBeforeItem = function (item) { var draggedItems = this._selection.isIndexSelected(this._draggedIndex) ? this._selection.getSelection() : [this._draggedItem]; var items = this.state.items.filter(function (itm) { return draggedItems.indexOf(itm) === -1; }); var insertIndex = items.indexOf(item); // if dragging/dropping on itself, index will be 0. if (insertIndex === -1) { insertIndex = 0; } items.splice.apply(items, [insertIndex, 0].concat(draggedItems)); this.setState({ items: items }); }; return DetailsListDragDropExample; }(React.Component)); exports.DetailsListDragDropExample = DetailsListDragDropExample; }); //# sourceMappingURL=DetailsList.DragDrop.Example.js.map ======================= File: node_modules/@microsoft/sp-webpart-base/lib/chunks/IframedWebPartController/IframedPropertyPane.module.scss.js ======================= require("./IframedPropertyPane.module.css"); var styles = { spIFramePropertyPaneContainer:'spIFramePropertyPaneContainer_276e3f6e', showPane:'showPane_276e3f6e', hidePane: 'hidePane_276e3f6e', shrinkContent:'shrinkContent_276e3f6e', iframeWebPart: 'iframeWebPart_276e3f6e', iframePropertyPane: 'iframePropertyPane_276e3f6e', }; export default styles; ======================= File: node_modules/@uifabric/utilities/lib-amd/warn/warnConditionallyRequiredProps.js ======================= define(["require", "exports", "./warn"], function (require, exports, warn_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * Warns when props are required if a condition is met. * * @public * @param componentName - The name of the component being used. * @param props - The props passed into the component. * @param requiredProps - The name of the props that are required when the condition is met. * @param conditionalPropName - The name of the prop that the condition is based on. * @param condition - Whether the condition is met. */ function warnConditionallyRequiredProps(componentName, props, requiredProps, conditionalPropName, condition) { if (condition === true && typeof process!== 'undefined' && process.env.NODE_ENV!== 'production') { for (var _i = 0, requiredProps_1 = requiredProps; _i < requiredProps_1.length; _i++) { var requiredPropName = requiredProps_1[_i]; if (!(requiredPropName in props)) { warn_1.warn(componentName + " property '" + requiredPropName + "' is required when '" + conditionalPropName + "' is used.'"); } } } } exports.warnConditionallyRequiredProps = warnConditionallyRequiredProps; }); //# sourceMappingURL=warnConditionallyRequiredProps.js.map ======================= File: node_modules/office-ui-fabric-react/lib/components/pickers/AutoFill/BaseAutoFill.js ======================= <reponame>GhostMachineSoftware/SPFx_Connect2List // Deprecated, import directly from the component folder now. export * from '../../Autofill/Autofill'; //# sourceMappingURL=BaseAutoFill.js.map ======================= File: node_modules/office-ui-fabric-react/lib/components/Button/MessageBarButton/MessageBarButton.styles.js ======================= import { concatStyleSets } from '../../../Styling'; import { memoizeFunction } from '../../../Utilities'; import { getStyles as getBaseButtonStyles } from '../BaseButton.styles'; export var getStyles = memoizeFunction(function (theme, customStyles, focusInset, focusColor) { var baseButtonStyles = getBaseButtonStyles(theme); var messageBarButtonStyles = { root: { backgroundColor: theme.palette.neutralQuaternaryAlt, color: theme.palette.neutralPrimary }, rootHovered: { backgroundColor: theme.palette.neutralTertiaryAlt, color: theme.palette.neutralDark }, rootPressed: { backgroundColor: theme.palette.neutralTertiary, color: theme.palette.neutralDark } }; return concatStyleSets(baseButtonStyles, messageBarButtonStyles, customStyles); }); //# sourceMappingURL=MessageBarButton.styles.js.map ======================= File: node_modules/@microsoft/sp-loader/lib/DeveloperTools/Components/DeveloperModules/TraceDisplay/TraceList/TraceListHeader/TraceListHeader.module.scss.js ======================= <reponame>GhostMachineSoftware/SPFx_Connect2List require("./TraceListHeader.module.css"); var styles = { container: 'container_8984886b', displayNone: 'displayNone_8984886b', displayBlock: 'displayBlock_8984886b', filterRow: 'filterRow_8984886b', filterButton: 'filterButton_8984886b', filterOverlay: 'filterOverlay_8984886b', headerText: 'headerText_8984886b', levelFilterOverlay: 'levelFilterOverlay_8984886b', level: 'level_8984886b', message:'message_8984886b', source:'source_8984886b', scope:'scope_8984886b', timestamp: 'timestamp_8984886b', }; export default styles; ======================= File: node_modules/@uifabric/utilities/lib-commonjs/mobileDetector.js ======================= "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * Returns true if and only if the user is on a iOS device. * Used to determine whether iOS-specific behavior should be applied. */ exports.isIOS = function () { if (!window ||!window.navigator ||!window.navigator.userAgent) { return false; } return /iPad|iPhone|iPod/i.test(window.navigator.userAgent); }; //# sourceMappingURL=mobileDetector.js.map ======================= File: node_modules/office-ui-fabric-react/lib/components/Label/Label.base.js ======================= <filename>node_modules/office-ui-fabric-react/lib/components/Label/Label.base.js import * as tslib_1 from "tslib"; import * as React from'react'; import { BaseComponent, divProperties, getNativeProps } from '../../Utilities'; import { classNamesFunction } from '../../Utilities'; var getClassNames = classNamesFunction(); var LabelBase = /** @class */ (function (_super) { tslib_1.__extends(LabelBase, _super); function LabelBase() { return _super!== null && _super.apply(this, arguments) || this; } LabelBase.prototype.render = function () { var _a = this.props, _b = _a.as, RootType = _b === void 0? 'label' : _b, children = _a.children, className = _a.className, disabled = _a.disabled, styles = _a.styles, required = _a.required, theme = _a.theme; var classNames = getClassNames(styles, { className: className, disabled: disabled, required: required, theme: theme }); return (React.createElement(RootType, tslib_1.__assign({}, getNativeProps(this.props, divProperties), { className: classNames.root }), children)); }; return LabelBase; }(BaseComponent)); export { LabelBase }; //# sourceMappingURL=Label.base.js.map ======================= File: node_modules/office-ui-fabric-react/lib-amd/components/Link/Link.js ======================= <reponame>GhostMachineSoftware/SPFx_Connect2List define(["require", "exports", "../../Utilities", "./Link.base", "./Link.styles"], function (require, exports, Utilities_1, Link_base_1, Link_styles_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Link = Utilities_1.styled(Link_base_1.LinkBase, Link_styles_1.getStyles, undefined, { scope: 'Link' }); }); //# sourceMappingURL=Link.js.map ======================= File: node_modules/office-ui-fabric-react/lib/utilities/color/colors.js ======================= import * as tslib_1 from "tslib"; import { COLOR_VALUES } from './colorValues'; export var MAX_COLOR_SATURATION = 100; export var MAX_COLOR_HUE = 359; export var MAX_COLOR_VALUE = 100; export var MAX_COLOR_RGB = 255; /** @deprecated Use MAX_COLOR_RGB (255) or MAX_COLOR_ALPHA (100) */ export var MAX_COLOR_RGBA = MAX_COLOR_RGB; export var MAX_COLOR_ALPHA = 100; /** * Converts a valid CSS color string to an RGB color. * Note that hex colors *must* be prefixed with # to be considered valid. * Alpha in returned color defaults to 100. */ export function cssColor(color) { if (!color) { return undefined; } return _named(color) || _hex3(color) || _hex6(color) || _rgba(color) || _hsla(color); } /** Converts RGB components to a hex color string (without # prefix). */ export function rgb2hex(r, g, b) { return [_rgbToPaddedHex(r), _rgbToPaddedHex(g), _rgbToPaddedHex(b)].join(''); } /** Converts HSV components to a hex color string (without # prefix). */ export function hsv2hex(h, s, v) { var _a = hsv2rgb(h, s, v), r = _a.r, g = _a.g, b = _a.b; return rgb2hex(r, g, b); } /** Converts RGB components to an HSV color. */ export function rgb2hsv(r, g, b) { var h = NaN; var s; var v; var max = Math.max(r, g, b); var min = Math.min(r, g, b); var delta = max - min; // hue if (delta === 0) { h = 0; } else if (r === max) { h = ((g - b) / delta) % 6; } else if (g === max) { h = (b - r) / delta + 2; } else if (b === max) { h = (r - g) / delta + 4; } h = Math.round(h * 60); if (h < 0) { h += 360; } // saturation s = Math.round((max === 0? 0 : delta / max) * 100); // value v = Math.round((max / MAX_COLOR_RGB) * 100); return { h: h, s: s, v: v }; } /** Converts HSL components to an HSV color. */ export function hsl2hsv(h, s, l) { s *= (l < 50? l : 100 - l) / 100; var v = l + s; return { h: h, s: v === 0? 0 : ((2 * s) / v) * 100, v: v }; } /** Converts HSV components to an HSL color. */ export function hsv2hsl(h, s, v) { s /= MAX_COLOR_SATURATION; v /= MAX_COLOR_VALUE; var l = (2 - s) * v; var sl = s * v; sl /= l <= 1? l : 2 - l; sl = sl || 0; l /= 2; return { h: h, s: sl * 100, l: l * 100 }; } /** Converts HSL components to an RGB color. Does not set the alpha value. */ export function hsl2rgb(h, s, l) { var hsv = hsl2hsv(h, s, l); return hsv2rgb(hsv.h, hsv.s, hsv.v); } /** Converts HSV components to an RGB color. Does not set the alpha value. */ export function hsv2rgb(h, s, v) { s = s / 100; v = v / 100; var rgb = []; var c = v * s; var hh = h / 60; var x = c * (1 - Math.abs((hh % 2) - 1)); var m = v - c; switch (Math.floor(hh)) { case 0: rgb = [c, x, 0]; break; case 1: rgb = [x, c, 0]; break; case 2: rgb = [0, c, x]; break; case 3: rgb = [0, x, c]; break; case 4: rgb = [x, 0, c]; break; case 5: rgb = [c, 0, x]; break; } return { r: Math.round(MAX_COLOR_RGB * (rgb[0] + m)), g: Math.round(MAX_COLOR_RGB * (rgb[1] + m)), b: Math.round(MAX_COLOR_RGB * (rgb[2] + m)) }; } /** * Converts a CSS color string to a color object. * Note that hex colors *must* be prefixed with # to be considered valid. * * `inputColor` will be used unmodified as the `str` property of the returned object. * Alpha defaults to 100 if not specified in `inputColor`. * Returns undefined if the color string is invalid/not recognized. */ export function getColorFromString(inputColor) { var color = cssColor(inputColor); if (!color) { return; } return tslib_1.__assign({}, getColorFromRGBA(color), { str: inputColor }); } /** Converts an RGBA color to a color object (alpha defaults to 100). */ export function getColorFromRGBA(rgba) { var _a = rgba.a, a = _a === void 0? MAX_COLOR_ALPHA : _a, b = rgba.b, g = rgba.g, r = rgba.r; var _b = rgb2hsv(r, g, b), h = _b.h, s = _b.s, v = _b.v; var hex = rgb2hex(r, g, b); var str = _rgbaOrHexString(r, g, b, a, hex); return { a: a, b: b, g: g, h: h, hex: hex, r: r, s: s, str: str, v: v }; } /** * Converts an HSV color (and optional alpha value) to a color object. * If `a` is not given, a default of 100 is used. * Hex in the returned value will *not* be prefixed with #. * If `a` is unspecified or 100, the result's `str` property will contain a hex value * (*not* prefixed with #) */ export function getColorFromHSV(hsv, a) { var h = hsv.h, s = hsv.s, v = hsv.v; a = typeof a === 'number'? a : MAX_COLOR_ALPHA; var _a = hsv2rgb(h, s, v), r = _a.r, g = _a.g, b = _a.b; var hex = hsv2hex(h, s, v); var str = _rgbaOrHexString(r, g, b, a, hex); return { a: a, b: b, g: g, h: h, hex: hex, r: r, s: s, str: str, v: v }; } /** * Converts a color hue to an HTML color string (with # prefix). * This implementation ignores all components of `color` except hue. */ export function getFullColorString(color) { return "#" + hsv2hex(color.h, MAX_COLOR_SATURATION, MAX_COLOR_VALUE); } /** * Gets a color with the same hue as `color` and other components updated to match the given * saturation and value. * * Does not modify the original `color` and does not supply a default alpha value. */ export function updateSV(color, s, v) { var _a = hsv2rgb(color.h, s, v), r = _a.r, g = _a.g, b = _a.b; var hex = rgb2hex(r, g, b); return { a: color.a, b: b, g: g, h: color.h, hex: hex, r: r, s: s, str: _rgbaOrHexString(r, g, b, color.a, hex), v: v }; } /** * Gets a color with the same saturation and value as `color` and the other components updated * to match the given hue. * * Does not modify the original `color` and does not supply a default alpha value. */ export function updateH(color, h) { var _a = hsv2rgb(h, color.s, color.v), r = _a.r, g = _a.g, b = _a.b; var hex = rgb2hex(r, g, b); return { a: color.a, b: b, g: g, h: h, hex: hex, r: r, s: color.s, str: _rgbaOrHexString(r, g, b, color.a, hex), v: color.v }; } /** * Gets a color with a single RGBA component updated to a new value. * Does not modify the original `color`. Alpha defaults to 100 if not set. */ export function updateRGB(color, component, value) { return getColorFromRGBA((_a = { r: color.r, g: color.g, b: color.b, a: color.a }, _a[component] = value, _a)); var _a; } /** * Gets a color with the given alpha value and the same other components as `color`. * Does not modify the original color. */ export function updateA(color, a) { return tslib_1.__assign({}, color, { a: a, str: _rgbaOrHexString(color.r, color.g, color.b, a, color.hex) }); } /** Corrects an RGB color to fall within the valid range. */ export function correctRGB(color) { return { r: clamp(color.r, MAX_COLOR_RGB), g: clamp(color.g, MAX_COLOR_RGB), b: clamp(color.b, MAX_COLOR_RGB), a: typeof color.a === 'number'? clamp(color.a, MAX_COLOR_ALPHA) : color.a }; } /** Corrects an HSV color to fall within the valid range. */ export function correctHSV(color) { return { h: clamp(color.h, MAX_COLOR_HUE), s: clamp(color.s, MAX_COLOR_SATURATION), v: clamp(color.v, MAX_COLOR_VALUE) }; } /** Clamp a value to ensure it falls within a given range. */ export function clamp(value, max, min) { if (min === void 0) { min = 0; } return value < min? min : value > max? max : value; } /** Converts an RGB component to a 0-padded hex component of length 2. */ function _rgbToPaddedHex(num) { num = clamp(num, MAX_COLOR_RGB); var hex = num.toString(16); return hex.length === 1? '0' + hex : hex; } /** * If `str` is a valid HTML color name, returns an RGB color (with alpha 100). * Otherwise returns undefined. */ function _named(str) { var c = COLOR_VALUES[str.toLowerCase()]; if (c) { return { r: c[0], g: c[1], b: c[2], a: MAX_COLOR_ALPHA }; } } /** * If `str` is in valid `rgb()` or `rgba()` format, returns an RGB color (alpha defaults to 100). * Otherwise returns undefined. */ function _rgba(str) { var match = str.match(/^rgb(a?)\(([\d., ]+)\)$/); if (match) { var hasAlpha =!!match[1]; var expectedPartCount = hasAlpha? 4 : 3; var parts = match[2].split(/ *, */).map(Number); if (parts.length === expectedPartCount) { return { r: parts[0], g: parts[1], b: parts[2], a: hasAlpha? parts[3] * 100 : MAX_COLOR_ALPHA }; } } } /** * If `str` is in valid 6-digit hex format *with* # prefix, returns an RGB color (with alpha 100). * Otherwise returns undefined. */ function _hex6(str) { if ('#' === str[0] && 7 === str.length && /^#[\da-fA-F]{6}$/.test(str)) { return { r: parseInt(str.slice(1, 3), 16), g: parseInt(str.slice(3, 5), 16), b: parseInt(str.slice(5, 7), 16), a: MAX_COLOR_ALPHA }; } } /** * If `str` is in valid 3-digit hex format *with* # prefix, returns an RGB color (with alpha 100). * Otherwise returns undefined. */ function _hex3(str) { if ('#' === str[0] && 4 === str.length && /^#[\da-fA-F]{3}$/.test(str)) { return { r: parseInt(str[1] + str[1], 16), g: parseInt(str[2] + str[2], 16), b: parseInt(str[3] + str[3], 16), a: MAX_COLOR_ALPHA }; } } /** * If `str` is in `hsl()` or `hsla()` format, returns an RGB color (alpha defaults to 100). * Otherwise returns undefined. */ function _hsla(str) { var match = str.match(/^hsl(a?)\(([\d., ]+)\)$/); if (match) { var hasAlpha =!!match[1]; var expectedPartCount = hasAlpha? 4 : 3; var parts = match[2].split(/ *, */).map(Number); if (parts.length === expectedPartCount) { var rgba = hsl2rgb(parts[0], parts[1], parts[2]); rgba.a = hasAlpha? parts[3] * 100 : MAX_COLOR_ALPHA; return rgba; } } } /** * Get a CSS color string from some color components. * If `a` is specified and not 100, returns an `rgba()` string. * Otherwise returns `hex` prefixed with #. */ function _rgbaOrHexString(r, g, b, a, hex) { return a === MAX_COLOR_ALPHA || typeof a!== 'number'? "#" + hex : "rgba(" + r + ", " + g + ", " + b + ", " + a / MAX_COLOR_ALPHA + ")"; } //# sourceMappingURL=colors.js.map ======================= File: node_modules/office-ui-fabric-react/lib-commonjs/components/Layer/Layer.doc.js ======================= <filename>node_modules/office-ui-fabric-react/lib-commonjs/components/Layer/Layer.doc.js "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var React = require("react"); var Layer_Basic_Example_1 = require("./examples/Layer.Basic.Example"); var Layer_Hosted_Example_1 = require("./examples/Layer.Hosted.Example"); var Layer_Customized_Example_1 = require("./examples/Layer.Customized.Example"); var Layer_NestedLayers_Example_1 = require("./examples/Layer.NestedLayers.Example"); var Layer_checklist_1 = require("./Layer.checklist"); var LayerBasicExampleCode = require('!raw-loader!office-ui-fabric-react/src/components/Layer/examples/Layer.Basic.Example.tsx'); var LayerHostedExampleCode = require('!raw-loader!office-ui-fabric-react/src/components/Layer/examples/Layer.Hosted.Example.tsx'); var LayerCustomizedExampleCode = require('!raw-loader!office-ui-fabric-react/src/components/Layer/examples/Layer.Customized.Example.tsx'); var LayerNestedLayersExampleCode = require('!raw-loader!office-ui-fabric-react/src/components/Layer/examples/Layer.NestedLayers.Example.tsx'); exports.LayerPageProps = { title: 'Layer', componentName: 'Layer', componentUrl: 'https://github.com/OfficeDev/office-ui-fabric-react/tree/master/packages/office-ui-fabric-react/src/components/Layer', componentStatus: Layer_checklist_1.LayerStatus, examples: [ { title: 'Basic layered content', code: LayerBasicExampleCode, view: React.createElement(Layer_Basic_Example_1.LayerBasicExample, null) }, { title: 'Using LayerHost to control projection', code: LayerHostedExampleCode, view: React.createElement(Layer_Hosted_Example_1.LayerHostedExample, null) }, { title: 'Using Customizer to control the default layer behavior', code: LayerCustomizedExampleCode, view: React.createElement(Layer_Customized_Example_1.LayerCustomizedExample, null) }, { title: 'Nested Layers Example', code: LayerNestedLayersExampleCode, view: React.createElement(Layer_NestedLayers_Example_1.LayerNestedLayersExample, null) } ], propertiesTablesSources: [require('!raw-loader!office-ui-fabric-react/src/components/Layer/Layer.types.ts')], overview: require('!raw-loader!office-ui-fabric-react/src/components/Layer/docs/LayerOverview.md'), bestPractices: '', dos: require('!raw-loader!office-ui-fabric-react/src/components/Layer/docs/LayerDos.md'), donts: require('!raw-loader!office-ui-fabric-react/src/components/Layer/docs/LayerDonts.md'), isHeaderVisible: true, isFeedbackVisible: true }; //# sourceMappingURL=Layer.doc.js.map ======================= File: node_modules/office-ui-fabric-react/lib/components/Spinner/Spinner.base.js ======================= import * as tslib_1 from "tslib"; import * as React from'react'; import { SpinnerType, SpinnerSize } from './Spinner.types'; import { BaseComponent, classNamesFunction, DelayedRender, getNativeProps, divProperties } from '../../Utilities'; var getClassNames = classNamesFunction(); var SpinnerBase = /** @class */ (function (_super) { tslib_1.__extends(SpinnerBase, _super); function SpinnerBase() { return _super!== null && _super.apply(this, arguments) || this; } SpinnerBase.prototype.render = function () { var _a = this.props, type = _a.type, size = _a.size, ariaLabel = _a.ariaLabel, ariaLive = _a.ariaLive, styles = _a.styles, label = _a.label, theme = _a.theme, className = _a.className, labelPosition = _a.labelPosition; var statusMessage = ariaLabel || label; var nativeProps = getNativeProps(this.props, divProperties, ['size']); // SpinnerType is deprecated. If someone is still using this property, rather than putting the SpinnerType into the ISpinnerStyleProps, // we'll map SpinnerType to its equivalent SpinnerSize and pass that in. Once SpinnerType finally goes away we should delete this. var styleSize = size; if (styleSize === undefined && type!== undefined) { styleSize = type === SpinnerType.large? SpinnerSize.large : SpinnerSize.medium; } var classNames = getClassNames(styles, { theme: theme, size: styleSize, className: className, labelPosition: labelPosition }); return (React.createElement("div", tslib_1.__assign({}, nativeProps, { className: classNames.root }), React.createElement("div", { className: classNames.circle }), label && React.createElement("div", { className: classNames.label }, label), statusMessage && (React.createElement("div", { role: "status", "aria-live": ariaLive }, React.createElement(DelayedRender, null, React.createElement("div", { className: classNames.screenReaderText }, statusMessage)))))); }; SpinnerBase.defaultProps = { size: SpinnerSize.medium, ariaLive: 'polite', labelPosition: 'bottom' }; return SpinnerBase; }(BaseComponent)); export { SpinnerBase }; //# sourceMappingURL=Spinner.base.js.map ======================= File: node_modules/@microsoft/sp-webpart-base/lib/core/BaseWebPart.js ======================= <reponame>GhostMachineSoftware/SPFx_Connect2List<filename>node_modules/@microsoft/sp-webpart-base/lib/core/BaseWebPart.js 'use strict'; import * as tslib_1 from "tslib"; import { virtual } from '@microsoft/decorators'; import { BaseComponent, DynamicProperty } from '@microsoft/sp-component-base'; import { DisplayMode, Text, Validate, Version } from '@microsoft/sp-core-library'; import { _EngagementLogger, _LogEntry, _LogSource, _LogType, _TraceLogger } from '@microsoft/sp-diagnostics'; import * as lodash from '@microsoft/sp-lodash-subset'; import { executeAndReThrow } from '../utils/ExecuteAndReThrow'; import { deepFreeze } from '../utils/Object'; import KillSwitches from './../common/KillSwitches'; import { PropertyPaneFieldType } from '../SPPropertyPane'; import { SPWebPartError, SPWebPartErrorCode } from './error/SPWebPartError'; import strings from './loc/Strings.resx'; var BaseWebPart = (function (_super) { tslib_1.__extends(BaseWebPart, _super); function BaseWebPart() { var _this = _super.call(this) || this; _this._initialized = false; _this._baseLogSource = _LogSource.create('BaseWebPart'); _this._hasEditLogged = false; _this._emptyResolvedPromise = Promise.resolve(); _this._disposeDynamicPropertiesIfRequired = _this._disposeDynamicPropertiesIfRequired.bind(_this); if (_this.constructor['name'] === 'BaseWebPart') { throw SPWebPartError.create(SPWebPartErrorCode.BaseConstructError); } return _this; } Object.defineProperty(BaseWebPart.prototype, "dataVersion", { get: function () { return Version.parse('1.0'); }, enumerable: true, configurable: true }); Object.defineProperty(BaseWebPart.prototype, "displayMode", { get: function () { return this._displayMode; }, enumerable: true, configurable: true }); Object.defineProperty(BaseWebPart.prototype, "properties", { get: function () { if (this._initialized) { return this._properties; } else { throw SPWebPartError.create(SPWebPartErrorCode.NotInitializedError); } }, enumerable: true, configurable: true }); Object.defineProperty(BaseWebPart.prototype, "propertiesMetadata", { get: function () { return undefined; }, enumerable: true, configurable: true }); Object.defineProperty(BaseWebPart.prototype, "disableReactivePropertyChanges", { get: function () { return false; }, enumerable: true, configurable: true }); Object.defineProperty(BaseWebPart.prototype, "previewImageUrl", { get: function () { return undefined; }, enumerable: true, configurable: true }); Object.defineProperty(BaseWebPart.prototype, "accessibleTitle", { get: function () { return this._getDefaultAccessibleTitle(); }, enumerable: true, configurable: true }); Object.defineProperty(BaseWebPart.prototype, "title", { get: function () { return this._title; }, enumerable: true, configurable: true }); Object.defineProperty(BaseWebPart.prototype, "description", { get: function () { return this._description; }, enumerable: true, configurable: true }); Object.defineProperty(BaseWebPart.prototype, "persistedProperties", { get: function () { return (this.disableReactivePropertyChanges && this._backupProperties)? this._backupProperties : this.properties; }, enumerable: true, configurable: true }); BaseWebPart.prototype._getPropertyPaneData = function () { var _this = this; return this._loadPropertyPaneResources().then(function () { var configuration = _this.getPropertyPaneConfiguration(); _this._fixUpDynamicDataConfiguration(configuration); return { webPartId: _this.context.instanceId, title: _this.title, isReactive:!_this.disableReactivePropertyChanges, configuration: configuration, properties: _this._cloneProperties(_this.properties), onPropertyPaneFieldChanged: undefined, onConfigurationEvent: undefined, onRendered: _this.onPropertyPaneRendered, dynamicConfiguration: { defaultCallback: (function () { _this._dynamicPropertyRefresh(); }).bind(_this), dynamicDataProvider: _this.context.dynamicDataProvider } }; }); }; BaseWebPart.prototype._loadPropertyPaneResources = function () { if (!this._loadPropertyPaneResourcesPromise) { this._loadPropertyPaneResourcesPromise = this.loadPropertyPaneResources(); } return this._loadPropertyPaneResourcesPromise; }; BaseWebPart.prototype._onPropertyPaneFieldChanged = function (propertyPath, newValue, fieldType) { var _this = this; if (KillSwitches.isAvoidingUnnecesaryWebPartRenderKillSwitchActivated()) { if (this.disableReactivePropertyChanges &&!this._backupProperties) { this._backupProperties = this._cloneProperties(this.properties); } var oldValue = lodash.get(this._properties, propertyPath); var newDynamicProperty = new DynamicProperty( this.context.dynamicDataProvider, (function () { _this._dynamicPropertyRefresh(); }).bind(this)); if (oldValue instanceof DynamicProperty &&!(newValue instanceof DynamicProperty)) { newDynamicProperty.setValue(newValue); newValue = newDynamicProperty; } this._updateProperty(propertyPath, newValue); this.onPropertyPaneFieldChanged(propertyPath, oldValue, newValue); this._afterPropertyUpdated(!this.disableReactivePropertyChanges); } else { var oldValue = lodash.get(this._properties, propertyPath); if (!lodash.isEqual(oldValue, newValue) || fieldType === PropertyPaneFieldType.Button || fieldType === PropertyPaneFieldType.Custom) { if (this.disableReactivePropertyChanges &&!this._backupProperties) { this._backupProperties = this._cloneProperties(this.properties); } if (oldValue instanceof DynamicProperty &&!(newValue instanceof DynamicProperty)) { var newDynamicProperty = new DynamicProperty( this.context.dynamicDataProvider, (function () { _this._dynamicPropertyRefresh(); }).bind(this)); newDynamicProperty.setValue(newValue); newValue = newDynamicProperty; } this._updateProperty(propertyPath, newValue); this.onPropertyPaneFieldChanged(propertyPath, oldValue, newValue); this._afterPropertyUpdated(!this.disableReactivePropertyChanges); } } }; BaseWebPart.prototype._onPropertyPaneLifeCycleEvent = function (event) { var _this = this; if (this.context.host.propertyPaneLifeCycleEventCallback) { this.context.host.propertyPaneLifeCycleEventCallback(event, { webPartData: this._internalSerialize(), isPropertyPaneReactive: this._isPropertyPaneReactive() }); } switch (event) { case 1 : this._loadPropertyPaneResources().then(function () { return _this.onPropertyPaneConfigurationStart(); }); break; case 2 : if (this.disableReactivePropertyChanges && this._backupProperties) { this._properties = this._backupProperties; this._backupProperties = undefined; } this.onPropertyPaneConfigurationComplete(); break; case 5 : this._backupProperties = this.properties; this.onAfter
1,533
兵都是容易的。抗日的财源十分困难,动员了民众,则财政也不成问题,岂有如此广土众民的国家而患财穷之理?军队须和民众打成一片,使军队在民众眼睛中看成是自己的军队,这个军队便无敌于天下,个把日本帝国主义是不够打的。 - (一一五)很多人对于官兵关系、军民关系弄不好,以为是方法不对,我总告诉他们是根本态度(或根本宗旨)问题,这态度就是尊重士兵和尊重人民。从这态度出发,于是有各种的政策、方法、方式。离了这态度,政策、方法、方式也一定是错的,官兵之间、军民之间的关系便决然弄不好。军队政治工作的三大原则:第一是官兵一致,第二是军民一致,第三是瓦解敌军。这些原则要实行有效,都须从尊重士兵、尊重人民和尊重已经放下武器的敌军俘虏的人格这种根本态度出发。那些认为不是根本态度问题而是技术问题的人,实在是想错了,应该加以改正才对。 - (一一六)当此保卫武汉等地成为紧急任务之时,发动全军全民的全部积极性来支持战争,是十分严重的任务。保卫武汉等地的任务,毫无疑义必须认真地提出和执行。然而究竟能否确定地保卫不失,不决定于主观的愿望,而决定于具体的条件。政治上动员全军全民起来奋斗,是最重要的具体的条件之一。不努力于争取一切必要的条件,甚至必要条件有一不备,势必重蹈南京等地失陷之覆辙。中国的马德里在什么地方,看什么地方具备马德里的条件。过去是没有过一个马德里的,今后应该争取几个,然而全看条件如何。条件中的最基本条件,是全军全民的广大的政治动员。 - (一一七)在一切工作中,应该坚持抗日民族统一战线的总方针。因为只有这种方针才能坚持抗战,坚持持久战,才能普遍地深入地改善官兵关系、军民关系,才能发动全军全民的全部积极性,为保卫一切未失地区、恢复一切已失地区而战,才能争取最后胜利。 - (一一八)这个政治上动员军民的问题,实在太重要了。我们之所以不惜反反复复地说到这一点,实在是没有这一点就没有胜利。没有许多别的必要的东西固然也没有胜利,然而这是胜利的最基本的条件。抗日民族统一战线是全军全民的统一战线,决不仅仅是几个党派的党部和党员们的统一战线;动员全军全民参加统一战线,才是发起抗日民族统一战线的根本目的。 - [42](42.md)([wz_42_188](wz_42_188.md))〕国民党政府扩军的一种办法,是派军警四处捉拿人民去当兵,捉来的兵用绳捆索绑,形同囚犯。略为有钱的人,就向国民党政府的官吏行贿,出钱买人代替。 ### 结论 - (一一九)结论是什么呢?结论就是:“在什么条件下,中国能战胜并消灭日本帝国主义的实力呢?要有三个条件:第一是中国抗日统一战线的完成;第二是国际抗日统一战线的完成;第三是日本国内人民和日本殖民地人民的革命运动的兴起。就中国人民的立场来说,三个条件中,中国人民的大联合是主要的。”“这个战争要延长多久呢?要看中国抗日统一战线的实力和中日两国其他许多决定的因素如何而定。”“如果这些条件不能很快实现,战争就要延长。但结果还是一样,日本必败,中国必胜。只是牺牲会大,要经过一个很痛苦的时期。”“我们的战略方针,应该是使用我们的主力在很长的变动不定的战线上作战。中国军队要胜利,必须在广阔的战场上进行高度的运动战。”“除了调动有训练的军队进行运动战之外,还要在农民中组织很多的游击队。”“在战争的过程中……使中国军队的装备逐渐加强起来。因此,中国能够在战争的后期从事阵地战,对于日本的占领地进行阵地的攻击。这样,日本在中国抗战的长期消耗下,它的经济行将崩溃;在无数战争的消磨中,它的士气行将颓靡。中国方面,则抗战的潜伏力一天一天地奔腾高涨,大批的革命民众不断地倾注到前线去,为自由而战争。所有这些因素和其他的因素配合起来,就使我们能够对日本占领地的堡垒和根据地,作最后的致命的攻击,驱逐日本侵略军出中国。”(一九三六年七月与斯诺谈话)“中国的政治形势从此开始了一个新阶段,……这一阶段的最中心的任务是:动员一切力量争取抗战的胜利。”“争取抗战胜利的中心关键,在使已经发动的抗战发展为全面的全民族的抗战。只有这种全面的全民族的抗战,才能使抗战得到最后的胜利。”“由于当前的抗战还存在着严重的弱点,所以在今后的抗战过程中,可能发生许多挫败、退却,内部的分化、叛变,暂时和局部的妥协等不利的情况。因此,应该看到这一抗战是艰苦的持久战。但我们相信,已经发动的抗战,必将因为我党和全国人民的努力,冲破一切障碍物而继续地前进和发展。”(一九三七年八月《中共中央关于目前形势与党的任务的决定》)这些就是结论。亡国论者看敌人如神物,看自己如草芥,速胜论者看敌人如草芥,看自己如神物,这些都是错误的。我们的意见相反:抗日战争是持久战,最后胜利是中国的——这就是我们的结论。 - (一二○)我的讲演至此为止。伟大的抗日战争正在开展,很多人希望总结经验,以便争取全部的胜利。我所说的,只是十个月经验中的一般的东西,也算一个总结吧。这个问题值得引起广大的注意和讨论,我所说的只是一个概论,希望诸位研究讨论,给以指正和补充。 ## 中国共产党在民族战争中的地位[(1)]((1).md)([jz_0_195](jz_0_195.md)) - (一九三八年十月十四日) - 同志们! 我们有一个光明的前途;我们必须战胜日本帝国主义,必须建设新中国,也一定能够达到这些目的。但是由现在到这个光明前途的中间,存在着一段艰难的路程。为着一个光明的中国而斗争的中国共产党和全国人民,必须有步骤地同日寇作斗争;而要打败它,只有经过长期的战争。关于这个战争的各方面问题,我们已经说得很多。抗战以来的经验,我们也总结了;当前的形势,我们也估计了;全民族的紧急任务,我们也提出了;用长期的抗日民族统一战线支持长期的战争的理由和方法,我们也说明了;国际形势,我们也分析了。那末,还有什么问题呢?同志们,还有一个问题,这就是中国共产党在民族战争中处于何种地位的问题,这就是共产党员应该怎样认识自己、加强自己、团结自己,才能领导这次战争达到胜利而不致失败的问题。 - [(1)]((1).md)([jz_0_195](jz_0_195.md))* 这是毛泽东在中国共产党第六届中央委员会扩大的第六次全体会议上的政治报告《论新阶段》的一部分。这个报告是在一九三八年十月十二日至十四日作的,这一部分是十四日讲的。这次会议批准了以毛泽东为首的党中央政治局的路线,是一次很重要的会议。毛泽东在报告中提出“中国共产党在民族战争中的地位”这一问题,便是为的使全党同志明确地知道并认真地负起中国共产党领导抗日战争的重大历史责任。全会确定了坚持抗日民族统一战线的方针,同时指出了在统一战线中有团结又有斗争,“一切经过统一战线”的提法对于中国情况是不适合的,这样就批判了关于统一战线问题上的迁就主义的错误;毛泽东在这次会议的结论中所讲的“统一战线中的独立自主问题”,就是关于这方面的问题。全会同时又确定了全党从事组织人民的抗日武装斗争的极端重要性,决定党的主要工作方面是战区和敌后,而批判了那种把战胜日本帝国主义的希望寄托于国民党军队以及把人民的命运寄托于国民党反动派统治下的合法运动等项错误思想;毛泽东在结论中所讲的“战争和战略问题”,就是关于这一方面的问题。 ### 爱国主义和国际主义 - 国际主义者的共产党员,是否可以同时又是一个爱国主义者呢?我们认为不但是可以的,而且是应该的。爱国主义的具体内容,看在什么样的历史条件之下来决定。有日本侵略者和希特勒的“爱国主义”,有我们的爱国主义。对于日本侵略者和希特勒的所谓“爱国主义”,共产党员是必须坚决地反对的。日本共产党人和德国共产党人都是他们国家的战争的失败主义者。用一切方法使日本侵略者和希特勒的战争归于失败,就是日本人民和德国人民的利益;失败得越彻底,就越好。日本共产党人和德国共产党人都应该这样做,他们也正在这样做。这是因为日本侵略者和希特勒的战争,不但是损害世界人民的,也是损害其本国人民的。中国的情况则不同,中国是被侵略的国家。因此,中国共产党人必须将爱国主义和国际主义结合起来。我们是国际主义者,我们又是爱国主义者,我们的口号是为保卫祖国反对侵略者而战。对于我们,失败主义是罪恶,争取抗日胜利是责无旁贷的。因为只有为着保卫祖国而战才能打败侵略者,使民族得到解放。只有民族得到解放,才有使无产阶级和劳动人民得到解放的可能。中国胜利了,侵略中国的帝国主义者被打倒了,同时也就是帮助了外国的人民。因此,爱国主义就是国际主义在民族解放战争中的实施。为此理由,每一个共产党员必须发挥其全部的积极性,英勇坚决地走上民族解放战争的战场,拿枪口瞄准日本侵略者。为此理由,我们的党从九一八事变[1](1.md)([wz_1_197](wz_1_197.md))开始,就提出了用民族自卫战争反抗日本侵略者的号召;后来又提出了抗日民族统一战线的主张,命令红军改编为抗日的国民革命军开赴前线作战,命令自己的党员站在抗日战争的最前线,为保卫祖国流最后一滴血。这些爱国主义的行动,都是正当的,都正是国际主义在中国的实现,一点也没有违背国际主义。只有政治上糊涂的人,或者别有用心的人,才会瞎说我们做得不对,瞎说我们抛弃了国际主义。 - [1](1.md)([wz_1_197](wz_1_197.md))见本书第一卷《论反对日本帝国主义的策略》注〔4〕。 ### 共产党员在民族战争中的模范作用 - 根据上述理由,共产党员应在民族战争中表现其高度的积极性;而这种积极性,应使之具体地表现于各方面,即应在各方面起其先锋的模范的作用。我们的战争,是在困难环境之中进行的。广大人民群众的民族觉悟、民族自尊心和自信心的不足,大多数民众的无组织,军力的不坚强,经济的落后,政治的不民主,腐败现象和悲观情绪的存在,统一战线内部的不团结、不巩固等等,形成了这种困难环境。因此,共产党员不能不自觉地担负起团结全国人民克服各种不良现象的重大的责任。在这里,共产党员的先锋作用和模范作用是十分重要的。共产党员在八路军和新四军中,应该成为英勇作战的模范,执行命令的模范,遵守纪律的模范,政治工作的模范和内部团结统一的模范。共产党员在和友党友军发生关系的时候,应该坚持团结抗日的立场,坚持统一战线的纲领,成为实行抗战任务的模范;应该言必信,行必果,不傲慢,诚心诚意地和友党友军商量问题,协同工作,成为统一战线中各党相互关系的模范。共产党员在政府工作中,应该是十分廉洁、不用私人、多做工作、少取报酬的模范。共产党员在民众运动中,应该是民众的朋友,而不是民众的上司,是诲人不倦的教师,而不是官僚主义的政客。共产党员无论何时何地都不应以个人利益放在第一位,而应以个人利益服从于民族的和人民群众的利益。因此,自私自利,消极怠工,贪污腐化,风头主义等等,是最可鄙的;而大公无私,积极努力,克己奉公,埋头苦干的精神,才是可尊敬的。共产党员应和党外一切先进分子协同一致,为着团结全国人民克服各种不良现象而努力。必须懂得,共产党员不过是全民族中的一小部分,党外存在着广大的先进分子和积极分子,我们必须和他们协同工作。那种以为只有自己好、别人都不行的想法,是完全不对的。共产党员对于落后的人们的态度,不是轻视他们,看不起他们,而是亲近他们,团结他们,说服他们,鼓励他们前进。共产党员对于在工作中犯过错误的人们,除了不可救药者外,不是采取排斥态度,而是采取规劝态度,使之翻然改进,弃旧图新。共产党员应是实事求是的模范,又是具有远见卓识的模范。因为只有实事求是,才能完成确定的任务;只有远见卓识,才能不失前进的方向。因此,共产党员又应成为学习的模范,他们每天都是民众的教师,但又每天都是民众的学生。只有向民众学习,向环境学习,向友党友军学习,了解了他们,才能对于工作实事求是,对于前途有远见卓识。在长期战争和艰难环境中,只有共产党员协同友党友军和人民大众中的一切先进分子,高度地发挥其先锋的模范的作用,才能动员全民族一切生动力量,为克服困难、战胜敌人、建设新中国而奋斗。 ### 团结全民族和反对民族中的奸细分子 - 为要克服困难,战胜敌人,建设新中国,只有巩固和扩大抗日民族统一战线,发动全民族中的一切生动力量,这是唯一无二的方针。但是我们的民族统一战线中已经存在着起破坏作用的奸细分子,这就是那些汉奸、托派[2](2.md)([wz_2_199](wz_2_199.md))、亲日派分子。共产党员应该随时注意那些奸细分子,用真凭实据揭发他们的罪恶,劝告人民不要上他们的当。共产党员必须提高对于民族奸细分子的政治警觉性。共产党员必须明白,揭发和清除奸细,是和扩大和巩固民族统一战线不能分离的。只顾一方面,忘记另一方面,是完全错误的。 - [2](2.md)([wz_2_199](wz_2_199.md))见本卷《论持久战》注〔9〕。 ### 扩大共产党和防止奸细混入 - 为了克服困难,战胜敌人,建设新中国,共产党必须扩大自己的组织,向着真诚革命、信仰党的主义、拥护党的政策、并愿意服从纪律、努力工作的广大工人、农民和青年积极分子开门,使党成为一个伟大的群众性的党。在这里,关门主义倾向是不能容许的。但是在同时,对于奸细混入的警觉性也决不可少。日本帝国主义的特务机关,时刻企图破坏我们的党,时刻企图利用暗藏的汉奸、托派、亲日派、腐化分子、投机分子,装扮积极面目,混入我们的党里来。对于这些分子的警惕和严防,一刻也不应该放松。不可因为怕奸细而把自己的党关起门来,大胆地发展党是我们已经确定了的方针。但是在同时,又不可因为大胆发展而疏忽对于奸细分子和投机分子乘机侵入的警戒。只顾一方面,忘记另一方面,就会犯错误。“大胆发展而又不让一个坏分子侵入”,这才是正确的方针。 ### 坚持统一战线和坚持党的独立性 - 坚持民族统一战线才能克服困难,战胜敌人,建设新中国,这是毫无疑义的。但是在同时,必须保持加入统一战线中的任何党派在思想上、政治上和组织上的独立性,不论是国民党也好,共产党也好,其他党派也好,都是这样。三民主义[3](3.md)([wz_3_200](wz_3_200.md))中的民权主义,在党派问题上说来,就是容许各党派互相联合,又容许各党派独立存在。如果只谈统一性,否认独立性,就是背弃民权主义,不但我们共产党不能同意,任何党派也是不能同意的。没有问题,统一战线中的独立性,只能是相对的,而不是绝对的;如果认为它是绝对的,就会破坏团结对敌的总方针。但是决不能抹杀这种相对的独立性,无论在思想上也好,在政治上也好,在组织上也好,各党必须有相对的独立性,即是说有相对的自由权。如果被人抹杀或自己抛弃这种相对的自由权,那就也会破坏团结对敌的总方针。这是每个共产党员,同时也是每个友党党员,应该明白的。 - 阶级斗争和民族斗争的关系也是这样。在抗日战争中,一切必须服从抗日的利益,这是确定的原则。因此,阶级斗争的利益必须服从于抗日战争的利益,而不能违反抗日战争的利益。但是阶级和阶级斗争的存在是一个事实;有些人否认这种事实,否认阶级斗争的存在,这是错误的。企图否认阶级斗争存在的理论是完全错误的理论。我们不是否认它,而是调节它。我们提倡的互助互让政策,不但适用于党派关系,也适用于阶级关系。为了团结抗日,应实行一种调节各阶级相互关系的恰当的政策,既不应使劳苦大众毫无政治上和生活上的保证,同时也应顾到富有者的利益,这样去适合团结对敌的要求。只顾一方面,不顾另一方面,都将不利于抗日。 - [3](3.md)([wz_3_200](wz_3_200.md))见本书第一卷《湖南农民运动考察报告》注〔8〕。 ### 照顾全局,照顾多数及和同盟者一道工作 - 共产党员在领导群众同敌人作斗争的时候,必须有照顾全局,照顾多数及和同盟者一道工作的观点。共产党员必须懂得以局部需要服从全局需要这一个道理。如果某项意见在局部的情形看来是可行的,而在全局的情形看来是不可行的,就应以局部服从全局。反之也是一样,在局部的情形看来是不可行的,而在全局的情形看来是可行的,也应以局部服从全局。这就是照顾全局的观点。共产党员决不可脱离群众的多数,置多数人的情况于不顾,而率领少数先进队伍单独冒进;必须注意组织先进分子和广大群众之间的密切联系。这就是照顾多数的观点。在一切有愿意和我们合作的民主党派和民主人士存在的地方,共产党员必须采取和他们一道商量问题和一道工作的态度。那种独断专行,把同盟者置之不理的态度,是不对的。一个好的共产党员,必须善于照顾全局,善于照顾多数,并善于和同盟者一道工作。我们过去在这些方面存在着很大的缺点,必须注意改进。 ### 干部政策 - 中国共产党是在一个几万万人的大民族中领导伟大革命斗争的党,没有多数才德兼备的领导干部,是不能完成其历史任务的。十七年来,我们党已经培养了不少的领导人材,军事、政治、文化、党务、民运各方面,都有了我们的骨干,这是党的光荣,也是全民族的光荣。但是,现有的骨干还不足以支撑斗争的大厦,还须广大地培养人材。在中国人民的伟大的斗争中,已经涌出并正在继续涌出很多的积极分子,我们的责任,就在于组织他们,培养他们,爱护他们,并善于使用他们。政治路线确定之后,干部就是决定的因素[4](4.md)([wz_4_202](wz_4_202.md))。因此,有计划地培养大批的新干部,就是我们的战斗任务。 - 不但要关心党的干部,还要关心非党的干部。党外存在着很多的人材,共产党不能把他们置之度外。去掉孤傲习气,善于和非党干部共事,真心诚意地帮助他们,用热烈的同志的态度对待他们,把他们的积极性组织到抗日和建国的伟大事业中去,这是每一个共产党员的责任。 - 必须善于识别干部。不但要看干部的一时一事,而且要看干部的全部历史和全部工作,这是识别干部的主要方法。 - 必须善于使用干部。领导者的责任,归结起来,主要地是出主意、用干部两件事。一切计划、决议、命令、指示等等,都属于“出主意”一类。使这一切主意见之实行,必须团结干部,推动他们去做,属于“用干部”一类。在这个使用干部的问题上,我们民族历史中从来就有两个对立的路线:一个是“任人唯贤”的路线,一个是“任人唯亲”的路线。前者是正派的路线,后者是不正派的路线。共产党的干部政策,应是以能否坚决地执行党的路线,服从党的纪律,和群众有密切的联系,有独立的工作能力,积极肯干,不谋私利为标准,这就是“任人唯贤”的路线。过去张国焘的干部政策与此相反,实行“任人唯亲”,拉拢私党,组织小派别,结果叛党而去,这是一个大教训。鉴于张国焘的和类似张国焘的历史教训,在干部政策问题上坚持正派的公道的作风,反对不正派的不公道的作风,借以巩固党的统一团结,这是中央和各级领导者的重要的责任。 - 必须善于爱护干部。爱护的办法是:第一,指导他们。这就是让他们放手工作,使他们敢于负责;同时,又适时地给以指示,使他们能在党的政治路线下发挥其创造性。第二,提高他们。这就是给以学习的机会,教育他们,使他们在理论上在工作能力上提高一步。第三,检查他们的工作,帮助他们总结经验,发扬成绩,纠正错误。有委托而无检查,及至犯了严重的错误,方才加以注意,不是爱护干部的办法。第四,对于犯错误的干部,一般地应采取说服的方法,帮助他们改正错误。只有对犯了严重错误而又不接受指导的人们,才应当采取斗争的方法。在这里,耐心是必要的;轻易地给人们戴上“机会主义”的大帽子,轻易地采用“开展斗争”的方法,是不对的。第五,照顾他们的困难。干部有疾病、生活、家庭等项困难问题者,必须在可能限度内用心给以照顾。这些就是爱护干部的方法。 - [4](4.md)([wz_4_202](wz_4_202.md))一九三四年一月斯大林《在党的第十七次代表大会上关于联共(布)中央工作的总结报告》中说:“在正确的政治路线提出以后,组织工作就决定一切,其中也决定政治路线本身的命运,即决定它的实现或失败。”斯大林在这里说到了正确挑选人才的问题。一九三五年五月斯大林《在克里姆林宫举行的红军学院学员毕业典礼上的讲话》中,提出和说明了“干部决定一切”的口号。(《斯大林选集》下卷,人民出版社1979年版,第343、371页) ### 党的纪律 - 鉴于张国焘严重地破坏纪律的行为,必须重申党的纪律:(一)个人服从组织;(二)少数服从多数;(三)下级服从上级;(四)全党服从中央。谁破坏了这些纪律,谁就破坏了党的统一。经验证明:有些破坏纪律的人,是由于他们不懂得什么是党的纪律;有些明知故犯的人,例如张国焘,则利用许多党员的无知以售其奸。因此,必须对党员进行有关党的纪律的教育,既使一般党员能遵守纪律,又使一般党员能监督党的领袖人物也一起遵守纪律,避免再发生张国焘事件。为使党内关系走上正轨,除了上述四项最重要的纪律外,还须制定一种较详细的党内法规,以统一各级领导机关的行动。 ### 党的民主 - 处在伟大斗争面前的中国共产党,要求整个党的领导机关,全党的党员和干部,高度地发挥其积极性,才能取得胜利。所谓发挥积极性,必须具体地表现在领导机关、干部和党员的创造能力,负责精神,工作的活跃,敢于和善于提出问题、发表意见、批评缺点,以及对于领导机关和领导干部从爱护观点出发的监督作用。没有这些,所谓积极性就是空的。而这些积极性的发挥,有赖于党内生活的民主化。党内缺乏民主生活,发挥积极性的目的就不能达到。大批能干人材的创造,也只有在民主生活中才有可能。由于我们的国家是一个小生产的家长制占优势的国家,又在全国范围内至今还没有民主生活,这种情况反映到我们党内,就产生了民主生活不足的现象。这种现象,妨碍着全党积极性的充分发挥。同时,也就影响到统一战线中、民众运动中民主生活的不足。为此缘故,必须在党内施行有关民主生活的教育,使党员懂得什么是民主生活,什么是民主制和集中制的关系,并如何实行民主集中制。这样才能做到:一方面,确实扩大党内的民主生活;又一方面,不至于走到极端民主化,走到破坏纪律的自由放任主义。 - 在我们军队中的党组织,也须增加必要的民主生活,以便提高党员的积极性,增强军队的战斗力。但是军队党组织的民主应少于地方党组织的民主。无论在军队或在地方,党内民主都应是为着巩固纪律和增强战斗力,而不是削弱这种纪律和战斗力。 - 扩大党内民主,应看作是巩固党和发展党的必要的步骤,是使党在伟大斗争中生动活跃,胜任愉快,生长新的力量,突破战争难关的一个重要的武器。 ### 我们的党已经从两条战线斗争中巩固和壮大起来 - 十七年来,我们的党,一般地已经学会了使用马克思列宁主义的思想斗争的武器,从两方面反对党内的错误思想,一方面反对右倾机会主义,又一方面反对“左”倾机会主义。 - 在党的六届五中全会以前[5](5.md)([wz_5_206](wz_5_206.md)),我们党反对了陈独秀的右倾机会主义[6](6.md)([wz_6_206](wz_6_206.md))和李立三同志的“左”倾机会主义[7](7.md)([wz_7_206](wz_7_206.md))。由于这两次党内斗争的胜利,使党获得了伟大的进步。五中全会以后,又有过两次有历史意义的党内斗争,这就是在遵义会议[8](8.md)([wz_8_206](wz_8_206.md))上的斗争和开除张国焘出党的斗争。 - 遵义会议纠正了在第五次反“围剿”斗争中所犯的“左”倾机会主义性质的严重的原则错误,团结了党和红军,使得党中央和红军主力胜利地完成了长征,转到了抗日的前进阵地,执行了抗日民族统一战线的新政策。由于巴西会议[9](9.md)([wz_9_206](wz_9_206.md))和延安会议[10](10.md)([wz_10_206](wz_10_206.md))(反对张国焘路线的斗争是从巴西会议开始而在延安会议完成的)反对了张国焘的右倾机会主义,使得全部红军会合一起,全党更加团结起来,进行了英勇的抗日斗争。这两种机会主义错误都是在国内革命战争中产生的,它们的特点是在战争中的错误。 - 这两次党内斗争所得的教训在什么地方呢?在于:(一)由于不认识中国革命战争中的特点而产生的、表现于第五次反“围剿”斗争中的严重的原则错误,包含着不顾主客观条件的“左”的急性病倾向,这种倾向极端地不利于革命战争,同时也不利于任何革命运动。(二)张国焘的机会主义,则是革命战争中的右倾机会主义,其内容是他的退却路线、军阀主义和反党行为的综合。只有克服了它,才使得本质很好而且作了长期英勇斗争的红军第四方面军的广大的干部和党员,从张国焘的机会主义统制之下获得解放,转到中央的正确路线方面来。(三)十年土地革命战争时期的伟大的组织工作,不论是军事建设工作也好,政府工作也好,民众工作也好,党的建设工作也好,是有大的成绩的,没有这种组织工作和前线的英勇战斗相配合,要支持当时的残酷的反对蒋介石的斗争是不可能的。然而在后一个时期内,党的干部政策和组织政策方面,是犯了严重的原则性的错误的,这表现在宗派倾向、惩办主义和思想斗争中的过火政策。这是过去立三路线的残余未能肃清的结果,也是当时政治上的原则错误的结果。这些错误,也因遵义会议得到了纠正,使党转到了正确的干部政策和正确的组织原则方面来了。至于张国焘的组织路线,则是完全离开了共产党的一切原则,破坏了党的纪律,从小组织活动一直发展到反党反中央反国际的行为。中央对于张国焘的罪恶的路线错误和反党行为,曾经尽了一切可能的努力去克服它,并企图挽救张国焘本人。但是到了张国焘不但坚持地不肯改正他的错误,采取了两面派的行为,而且在后来实行叛党,投入国民党的怀抱的时候,党就不得不坚决地开除他的党籍。这一处分,不但获得了全党的拥护,而且获得了一切忠实于民族解放事业的人们的拥护。共产国际也批准了这一处分,并指出:张国焘是一个逃兵和叛徒。 - 以上这些教训和成功,给了我们今后团结全党,巩固思想上、政治上和组织上的一致,胜利地进行抗日战争的必要的前提。我们的党已经从两条战线斗争中巩固和壮大起来了。 - [5](5.md)([wz_5_206](wz_5_206.md))指从一九二七年八月七日中共中央紧急会议到一九三四年一月中共六届五中全会以前这一段时间。 - [6](6.md)([wz_6_206](wz_6_206.md))见本书第一卷《中国革命战争的战略问题》注〔4〕。 - [7](7.md)([wz_7_206](wz_7_206.md))见本书第一卷《中国革命战争的战略问题》注〔5〕。 - [8](8.md)([wz_8_206](wz_8_206.md))见本书第一卷《中国革命战争的战略问题》注〔7〕。 - [9](9.md)([wz_9_206](wz_9_206.md))巴西会议是一九三五年九月九日由毛泽东、周恩来、张闻天、秦邦宪和王稼祥在巴西(今属四川省若尔盖县)召开的紧急会议。当时,红军一、四方面军正在长征途中,张国焘拒绝执行中央的北上方针,并企图危害中央。毛泽东等在这次会议上决定脱离危险区域,率领一部分红军先行北上。张国焘则率领另一部分被他欺骗的红军从阿坝地区南下天全、芦山等地,另立“中央”,揭出反党分裂的旗帜。 - [10](10.md)([wz_10_206](wz_10_206.md)) 〕延安会议是一九三七年三月在延安召开的中共中央政治局扩大会议。这次会议讨论了当时国内政治形势和党的任务,并着重批评了张国焘的错误。在会议作出的《关于张国焘同志错误的决定》中,对于张国焘的机会主义、军阀主义和反党行为,进行了系统的批判和总结。张国焘本人参加了这次会议,表面上表示接受对他的批判,实际上准备最后叛党。参见本书第一卷《论反对日本帝国主义的策略》注〔24〕。 ### 当前的两条战线斗争 - 在今后的抗日形势中,从政治上反对右的悲观主义,将是头等重要的;但是在同时,反对“左”的急性病,也仍然要注意。在统一战线问题上,在党的组织问题上和在民众的组织问题上,则须继续反对“左”的关门主义倾向,以便实现和各抗日党派的合作,发展共产党和发展民众运动;但是在同时,无条件的合作,无条件的发展,这种右倾机会主义的倾向也要注意反对,否则也就会妨碍合作,妨碍发展,而变为投降主义的合作和无原则的发展了。 - 两条战线的思想斗争必须切合于具体对象的情况,决不应主观地看问题,决不应使过去那种“乱戴帽子”的坏习惯继续存在。 - 在反倾向的斗争中,反对两面派的行为,是值得严重地注意的。因为两面派行为的最大的危险性,在于它可能发展到小组织行动;张国焘的历史就是证据。阳奉阴违,口是心非,当面说得好听,背后又在捣鬼,这就是两面派行为的表现。必须提高干部和党员对于两面派行为的注意力,才能巩固党的纪律。 ### 学习 - 一般地说,一切有相当研究能力的共产党员,都要研究马克思、恩格斯、列宁、斯大林的理论,都要研究我们民族的历史,都要研究当前运动的情况和趋势;并经过他们去教育那些文化水准较低的党员。特殊地说,干部应当着重地研究这些,中央委员和高级干部尤其应当加紧研究。指导一个伟大的革命运动的政党,如果没有革命理论,没有历史知识,没有对于实际运动的深刻的了解,要取得胜利是不可能的。 - 马克思、恩格斯、列宁、斯大林的理论,是“放之四海而皆准”的理论。不应当把他们的理论当作教条看待,而应当看作行动的指南。不应当只是学习马克思列宁主义的词句,而应当把它当成革命的科学来学习。不但应当了解马克思、恩格斯、列宁、斯大林他们研究广泛的真实生活和革命经验所得出的关于一般规律的结论,而且应当学习他们观察问题和解决问题的立场和方法。我们党的马克思列宁主义的修养,现在已较过去有了一些进步,但是还很不普遍,很不深入。我们的任务,是领导一个几万万人口的大民族,进行空前的伟大的斗争。所以,普遍地深入地研究马克思列宁主义的理论的任务,对于我们,是一个亟待解决并须着重地致力才能解决的大问题。我希望从我们这次中央全会之后,来一个全党的学习竞赛,看谁真正地学到了一点东西,看谁学的更多一点,更好一点。在担负主要领导责任的观点上说,如果我们党有一百个至二百个系统地而不是零碎地、实际地而不是空洞地学会了马克思列宁主义的同志,就会大大地提高我们党的战斗力量,并加速我们战胜日本帝国主义的工作。 - 学习我们的历史遗产,用马克思主义的方法给以批判的总结,是我们学习的另一任务。我们这个民族有数千年的历史,有它的特点,有它的许多珍贵品。对于这些,我们还是小学生。今天的中国是历史的中国的一个发展;我们是马克思主义的历史主义者,我们不应当割断历史。从孔夫子到孙中山,我们应当给以总结,承继这一份珍贵的遗产。这对于指导当前的伟大的运动,是有重要的帮助的。共产党员是国际主义的马克思主义者,但是马克思主义必须和我国的具体特点相结合并通过一定的民族形式才能实现。马克思列宁主义的伟大力量,就在于它是和各个国家具体的革命实践相联系的。对于中国共产党说来,就是要学会把马克思列宁主义的理论应用于中国的具体的环境。成为伟大中华民族的一部分而和这个民族血肉相联的共产党员,离开中国特点来谈马克思主义,只是抽象的空洞的马克思主义。因此,使马克思主义在中国具体化,使之在其每一表现中带着必须有的中国的特性,即是说,按照中国的特点去应用它,成为全党亟待了解并亟须解决的问题。洋八股[11](11.md)([wz_11_210](wz_11_210.md))必须废止,空洞抽象的调头必须少唱,教条主义必须休息,而代之以新鲜活泼的、为中国老百姓所喜闻乐见的中国作风和中国气派。把国际主义的内容和民族形式分离起来,是一点也不懂国际主义的人们的做法,我们则要把二者紧密地结合起来。在这个问题上,我们队伍中存在着的一些严重的错误,是应该认真地克服的。 - 当前的运动的特点是什么?它有什么规律性?如何指导这个运动?这些都是实际的问题。直到今天,我们还没有懂得日本帝国主义的全部,也还没有懂得中国的全部。运动在发展中,又有新的东西在前头,新东西是层出不穷的。研究这个运动的全面及其发展,是我们要时刻注意的大课题。如果有人拒绝对于这些作认真的过细的研究,那他就不是一个马克思主义者。 - 学习的敌人是自己的满足,要认真学习一点东西,必须从不自满开始。对自己,“学而不厌”,对人家,“诲人不倦”,我们应取这种态度。 - [11](11.md)([wz_11_210](wz_11_210.md)) 〕参见本书第三卷《反对党八股》一文中关于洋八股的说明。 ### 团结和胜利 - 中国共产党内部的团结,是团结全国人民争取抗日胜利和建设新中国的最基本的条件。经过了十七年锻炼的中国共产党,已经学到了如何团结自己的许多方法,已经老练得多了。这样,我们就能在全国人民中形成一个坚强的核心,争取抗日的胜利和建设一个新中国。同志们,只要我们能团结,这个目的就一定能够达到。 ## 统一战线中的独立自主问题[(1)]((1).md)([jz_0_213](jz_0_213.md)) - (一九三八年十一月五日) - [(1)]((1).md)([jz_0_213](jz_0_213.md))* 这是毛泽东在中国共产党第六届中央委员会扩大的第六次全体会议上所作的结论的一部分。结论是在一九三八年十一月五日和六日作的,这一部分是在五日讲的。统一战线中的独立自主问题,是当时毛泽东同陈绍禹在抗日民族统一战线问题上意见分歧的突出问题之一。这在本质上就是统一战线中无产阶级领导权的问题。关于这种意见分歧,毛泽东在一九四七年十二月二十五日的报告《目前形势和我们的任务》中曾作了以下简要的总结:“抗日战争时期,我党反对了和这种投降主义思想(编者按:指第一次国内革命战争时期陈独秀的投降主义思想)相类似的思想,即是对于国民党的反人民政策让步,信任国民党超过信任人民群众,不敢放手发动群众斗争,不敢在日本占领地区扩大解放区和扩大人民的军队,将抗日战争的领导权送给国民党。我党对于这样一种软弱无能的腐朽的违背马克思列宁主义原则的思想,进行了坚决的斗争,坚决地执行了‘发展进步势力,争取中间势力,孤立顽固势力’的政治路线,坚决地扩大了解放区和人民解放军。这样,就不但保证了我党在日本帝国主义侵略时期能够战胜日本帝国主义,而且保证了我党在日本投降以后蒋介石举行反革命战争时期,能够顺利地不受损失地转变到用人民革命战争反对蒋介石反革命战争的轨道上,并在短时期内取得了伟大的胜利。这些历史教训,全党同志都要牢记。” ### 帮助和让步应该是积极的,不应该是消极的 - 为了长期合作,统一战线中的各党派实行互助互让是必需的,但应该是积极的,不是消极的。我们必须巩固和扩大我党我军,同时也应赞助友党友军的巩固和扩大;人民要求政府满足自己的政治经济要求,同时给政府以一切可能的利于抗日的援助;工人要求厂主改良待遇,同时积极作工以利抗日;地主应该减租减息,同时农民应该交租交息,团结对外。这些都是互助的原则和方针,是积极的方针,不是消极的片面的方针。互让也是如此。彼此不挖墙脚,彼此不在对方党政军内组织秘密支部;在我们方面,就是不在国民党及其政府、军队内组织秘密支部,使国民党安心,利于抗日。“有所不为而后可以有为”[1](1.md)([wz_1_214](wz_1_214.md)),正是这种情形。没有红军的改编,红色区域的改制,暴动政策的取消,就不能实现全国的抗日战争。让了前者就得了后者,消极的步骤达到了积极的目的。“为了更好的一跃而后退”[2](2.md)([wz_2_214](wz_2_214.md)),正是列宁主义。把让步看作纯消极的东西,不是马克思列宁主义所许可的。纯消极的让步是有过的,那就是第二国际的劳资合作论[3](3.md)([wz_3_214](wz_3_214.md)),把一个阶级一个革命都让掉了。中国前有陈独秀[4](4.md)([wz_4_214](wz_4_214.md)),后有张国焘[5](5.md)([wz_5_214](wz_5_214.md)),都是投降主义者;我们应该大大地反对投降主义。我们的让步、退守、防御或停顿,不论是向同盟者或向敌人,都是当作整个革命政策的一部分看的,是联系于总的革命路线而当作不可缺少的一环看的,是当作曲线运动的一个片断看的。一句话,是积极的。 - [1](1.md)([wz_1_214](wz_1_214.md))见《孟子·离娄下》。原文是:“人有不为也,而后可以有为。” - [2](2.md)([wz_2_214](wz_2_214.md))见列宁《黑格尔〈哲学史讲演录〉一书摘要》(《列宁全集》第55卷,人民出版社1990年版,第239页)。 - [3](3.md)([wz_3_214](wz_3_214.md))“劳资合作论”,是第二国际主张在资本主义国家内,无产阶级与资产阶级合作,反对用革命手段推翻资产阶级统治以建立无产阶级专政的一种反动理论。 - [4](4.md)([wz_4_214](wz_4_214.md))见本书第一卷《中国革命战争的战略问题》注〔4〕。 - [5](5.md)([wz_5_214](wz_5_214.md))见本书第一卷《论反对日本帝国主义的策略》注〔24〕。 ### 民族斗争和阶级斗争的一致性 - 用长期合作支持长期战争,就是说使阶级斗争服从于今天抗日的民族斗争,这是统一战线的根本原则。在此原则下,保存党派和阶级的独立性,保存统一战线中的独立自主;不是因合作和统一而牺牲党派和阶级的必要权利,而是相反,坚持党派和阶级的一定限度的权利;这才有利于合作,也才有所谓合作。否则就是将合作变成了混一,必然牺牲统一战线。在民族斗争中,阶级斗争是以民族斗争的形式出现的,这种形式,表现了两者的一致性。一方面,阶级的政治经济要求在一定的历史时期内以不破裂合作为条件;又一方面,一切阶级斗争的要求都应以民族斗争的需要(为着抗日)为出发点。这样便把统一战线中的统一性和独立性、民族斗争和阶级斗争,一致起来了。 ### “一切经过统一战线”是不对的 - 国民党是当权的党,它至今不许有统一战线的组织形式。刘少奇同志说的很对,如果所谓“一切经过”就是经过蒋介石和阎锡山,那只是片面的服从,无所谓“经过统一战线”。在敌后,只有根据国民党已经许可的东西(例如《抗战建国纲领》[6](6.md)([wz_6_215](wz_6_215.md))),独立自主地去做,无法“一切经过”。或者估计国民党可能许可的,先斩后奏。例如设置行政专员,派兵去山东之类,先“经过”则行不通。听说法国共产党曾经提出过这个口号,那大概是因为法国有了各党的共同委员会,而对于共同决定的纲领,社会党方面不愿照做,依然干他们自己的,故共产党有提此口号以限制社会党之必要,并不是提此口号以束缚自己。中国的情形是国民党剥夺各党派的平等权利,企图指挥各党听它一党的命令。我们提这个口号,如果是要求国民党“一切”都要“经过”我们同意,是做不到的,滑稽的。如果想把我们所要做的“一切”均事先取得国民党同意,那末,它不同意怎么办?国民党的方针是限制我们发展,我们提出这个口号,只是自己把自己的手脚束缚起来,是完全不应该的。在现时,有些应该先得国民党同意,例如将三个师的番号扩编为三个军的番号,这叫做先奏后斩。有些则造成既成事实再告诉它,例如发展二十余万军队,这叫做先斩后奏。有些则暂时斩而不奏,估计它现时不会同意,例如召集边区议会之类。有些则暂时不斩不奏,例如那些如果做了就要妨碍大局的事情。总之,我们一定不要破裂统一战线,但又决不可自己束缚自己的手脚,因此不应提出“一切经过统一战线”的口号。“一切服从统一战线”,如果解释为“一切服从”蒋介石和阎锡山,那也是错误的。我们的方针是统一战线中的独立自主,既统一,又独立。 - [6](6.md)([wz_6_215](wz_6_215.md))见本卷《陕甘宁边区政府、第八路军后方留守处布告》注〔3〕。 ## 战争和战略问题[(1)]((1).md)([jz_0_217](jz_0_217.md)) - (一九三八年十一月六日) - [(1)]((1).md)([jz_0_217](jz_0_217.md))* 这是毛泽东在中国共产党第六届中央委员会扩大的第六次全体会议上所作的结论的一部分。结论是在一九三八年十一月五日和六日作的,这一部分是六日讲的。毛泽东在《抗日游击战争的战略问题》和《论持久战》两文中,已经解决了党领导抗日战争的问题。犯右倾机会主义错误的同志否认统一战线中的独立自主,因此对于党在战争和战略问题上的方针,也采取了怀疑和反对的态度。为着克服党内这种右倾机会主义,而使全党更明确地了解战争和战略问题在中国革命问题上的首要地位,并动员全党认真地从事这项工作,毛泽东在六届六中全会上又从中国政治斗争的历史方面着重地说明这个问题,同时说明我们的军事工作的发展和战略方针的具体变化的过程,从而取得了全党在领导思想上和工作上的一致。 ### 一 中国的特点和革命战争 - 革命的中心任务和最高形式是武装夺取政权,是战争解决问题。这个马克思列宁主义的革命原则是普遍地对的,不论在中国在外国,一概都是对的。 - 但是在同一个原则下,就无产阶级政党在各种条件下执行这个原则的表现说来,则基于条件的不同而不一致。在资本主义各国,在没有法西斯和没有战争的时期内,那里的条件是国家内部没有了封建制度,有的是资产阶级的民主制度;外部没有民族压迫,有的是自己民族压迫别的民族。基于这些特点,资本主义各国的无产阶级政党的任务,在于经过长期的合法斗争,教育工人,生息力量,准备最后地推翻资本主义。在那里,是长期的合法斗争,是利用议会讲坛,是经济的和政治的罢工,是组织工会和教育工人。那里的组织形式是合法的,斗争形式是不流血的(非战争的)。在战争问题上,那里的共产党是反对自己国家的帝国主义战争;如果这种战争发生了,党的政策是使本国反动政府败北。自己所要的战争只是准备中的国内战争[1](1.md)([wz_1_218](wz_1_218.md))。但是这种战争,不到资产阶级处于真正无能之时,不到无产阶级的大多数有了武装起义和进行战争的决心之时,不到农民群众已经自愿援助无产阶级之时,起义和战争是不应该举行的。到了起义和战争的时候,又是首先占领城市,然后进攻乡村,而不是与此相反。所有这些,都是资本主义国家的共产党所曾经这样做,而在俄国的十月革命中证实了的。 - 中国则不同。中国的特点是:不是一个独立的民主的国家,而是一个半殖民地的半封建的国家;在内部没有民主制度,而受封建制度压迫;在外部没有民族独立,而受帝国主义压迫。因此,无议会可以利用,无组织工人举行罢工的合法权利。在这里,共产党的任务,基本地不是经过长期合法斗争以进入起义和战争,也不是先占城市后取乡村,而是走相反的道路。 - 对于中国共产党,在帝国主义没有武装进攻的时候,或者是和资产阶级一道,进行反对军阀(帝国主义的走狗)的国内战争,例如一九二四年至一九二七年的广东战争[2](2.md)([wz_2_218](wz_2_218.md))和北伐战争;或者是联合农民和城市小资产阶级,进行反对地主阶级和买办资产阶级(同样是帝国主义的走狗)的国内战争,例如一九二七年至一九三六年的土地革命战争。在帝国主义举行武装进攻的时候,则是联合国内一切反对外国侵略者的阶级和阶层,进行对外的民族战争,例如现在的抗日战争。 - 所有这些,表示了中国和资本主义国家的不同。在中国,主要的斗争形式是战争,而主要的组织形式是军队。其他一切,例如民众的组织和民众的斗争等等,都是非常重要的,都是一定不可少,一定不可忽视,但都是为着战争的。在战争爆发以前的一切组织和斗争,是为了准备战争的,例如五四运动(一九一九年)至五卅运动(一九二五年)那一时期。在战争爆发以后的一切组织和斗争,则是直接或间接地配合战争的,例如北伐战争时期,革命军后方的一切组织和斗争是直接地配合战争的,北洋军阀统治区域内的一切组织和斗争是间接地配合战争的。又如土地革命战争时期,红色区域内部的一切组织和斗争是直接地配合战争的,红色区域外部的一切组织和斗争是间接地配合战争的。再如现在抗日战争时期,抗日军后方的和敌军占领地的一切组织和斗争,也同样是直接或间接地配合战争的。 - “在中国,是武装的革命反对武装的反革命。这是中国革命的特点之一,也是中国革命的优点之一。”[3](3.md)([wz_3_219](wz_3_219.md))斯大林同志的这一论断是完全正确的;无论是对于北伐战争说来,对于土地革命战争说来,对于今天的抗日战争说来,都是正确的。这些战争都是革命战争,战争所反对的对象都是反革命,参加战争的主要成分都是革命的人民;不同的只在或者是国内战争,或者是民族战争;或者是共产党单独进行的战争,或者是国共两党联合进行的战争。当然,这些区别是重要的。这些表示了战争主体有广狭的区别(工农联合,或工农资产阶级联合),战争对象有内外的区别(反对国内敌人,或反对国外敌人;国内敌人又分北洋军阀或国民党),表示了中国革命战争在其历史进程的各个时期中有不相同的内容。然而都是武装的革命反对武装的反革命,都是革命战争,都表示了中国革命的特点和优点。革命战争“是中国革命的特点之一,也是中国革命的优点之一”,这一论断,完全适合于中国的情况。中国无产阶级政党的主要的和差不多开始就面对着的任务,是联合尽可能多的同盟军,组织武装斗争,依照情况,反对内部的或外部的武装的反革命,为争取民族的和社会的解放而斗争。在中国,离开了武装斗争,就没有无产阶级和共产党的地位,就不能完成任何的革命任务。 - 在这一点上,我们党从一九二一年成立直至一九二六年参加北伐战争的五六年内,是认识不足的。那时不懂得武装斗争在中国的极端的重要性,不去认真地准备战争和组织军队,不去注重军事的战略和战术的研究。在北伐过程中,忽视了军队的争取,片面地着重于民众运动,其结果,国民党一旦反动,一切民众运动都塌台了。一九二七年以后的一个长时期中,许多同志把党的中心任务仍旧放在准备城市起义和白区工作方面[4](4.md)([wz_4_220](wz_4_220.md))。一些同志在这个问题上的根本的转变,是在一九三一年反对敌人的第三次“围剿”胜利之后。但也还没有全党的转变,有些同志仍旧没有如同现在我们这样想。 - 经验告诉我们,中国的问题离开武装就不能解决。认识这一点,对于今后进行胜利的抗日战争是有利益的。抗日战争中全民武装反抗的具体事实,将教育全党进一步地认识这个问题的重要性,每个党员都要时刻准备武装上前线。我们这次会议又决定党的主要工作方面是在战区和敌后,更给了一个明确的方针。这对于有些党员愿作党的组织工作,愿作民众运动的工作,而不愿研究战争和参加战争,有些学校没有注意鼓励学生上前线,等等现象,还是一剂对症的良药。大部分中国领土内党的组织工作和民众运动工作是直接联系于武装斗争的,没有也不能有单独的孤立的党的工作或民众运动。一部分距离战区较远的后方(如云南、贵州、四川)和一部分敌人控制的地区(如北平、天津、南京、上海),党的组织工作和民众运动也是配合战争的,只能也只应服从前线的要求。一句话,全党都要注重战争,学习军事,准备打仗。 - [1](1.md)([wz_1_218](wz_1_218.md))参见列宁《战争和俄国社会民主党》、《俄国社会民主工党国外支部代表会议》、《关于自己的政府在帝国主义战争中的失败》(《列宁全集》第26卷,人民出版社1988年版,第12—19、163—169、297—303页)和《俄国的战败和革命危机》(《列宁全集》第27卷,人民出版社1990年版,第31—35页)。列宁这些著作是在一九一四年至一九一五年间针对着当时的帝国主义战争而写的。并参见《联共(布)党史简明教程》第六章第三节《布尔什维克党在战争、和平与革命问题上的理论和策略》(人民出版社1975年版,第185—192页)。 - [2](2.md)([wz_2_218](wz_2_218.md))指第一次国内革命战争时期国共合作的革命军讨伐广东境内军阀买办势力的革命战争。一九二四年十月,革命军歼灭了勾结英帝国主义在广州发动叛乱的买办豪绅武装——“商团”。一九二五年二月至三月,革命军从广州东征,打败了盘据东江的军阀陈炯明部队的主力。六月,回师消灭了盘据广州的滇桂军阀杨希闵、刘震寰的部队。十月至十一月,举行第二次东征,最后消灭了陈炯明的军队。同时,革命军分兵南征,讨伐盘据广东西南部的军阀邓本殷。在上述这些战役中,中国共产党党员和共产主义青年团团员都英勇地站在战斗的前列,并且发动广大工农群众热烈地支援革命军。这些战役的胜利造成了当时广东统一的局面,为北伐战争建立了后方基地。 - [3](3.md)([wz_3_219](wz_3_219.md))见斯大林《论中国革命的前途》(《斯大林选集》上卷,人民出版社1979年版,第487页)。 - [4](4.md)([wz_4_220](wz_4_220.md))参见本书第三卷《学习和时局》一文的附录《关于若干历史问题的决议》第四部分。 ### 二 中国国民党的战争史 - 我们来看一看国民党的历史,看一看它是如何地注意于战争,是有益处的。 - 从孙中山组织革命的小团体起,他就进行了几次反清的武装起义[5](5.md)([wz_5_221](wz_5_221.md))。到了同盟会时期,更充满了武装起义的事迹[6](6.md)([wz_6_221](wz_6_221.md)),直至辛亥革命[7](7.md)([wz_7_221](wz_7_221.md)),武装推翻了清朝。中华革命党时期,进行了武装的反袁运动[8](8.md)([wz_8_221](wz_8_221.md))。后来的海军南下[9](9.md)([wz_9_221](wz_9_221.md)),桂林北伐[10](10.md)([wz_10_221](wz_10_221.md))和创设黄埔[11](11.md)([wz_11_221](wz_11_221.md)),都是孙中山的战争事业。 - 蒋介石代替孙中山,创造了国民党的全盛的军事时代。他看军队如生命,经历了北伐、内战和抗日三个时期。过去十年的蒋介石是反革命的。为了反革命,他创造了一个庞大的“中央军”。有军则有权,战争解决一切,这个基点,他是抓得很紧的。对于这点,我们应向他学习。在这点上,孙中山和蒋介石都是我们的先生。 - 辛亥革命后,一切军阀,都爱兵如命,他们都看重了“有军则有权”的原则。 - 谭延闿[12](12.md)([wz_12_222](wz_12_222.md))是一个聪明的官僚,他在湖南几起几覆,从来不做寡头省长,要做督军兼省长。他后来做了广东和武汉的国民政府主席,还是兼了第二军军长。中国有很多这样的军阀,他们都懂得中国的特点。 - 中国也有些不要军队的政党,其中主要的一个是进步党[13](13.md)([wz_13_222](wz_13_222.md)),但是它也懂得必须靠一个军阀才有官做。袁世凯[14](14.md)([wz_14_222](wz_14_222.md))、段祺瑞[15](15.md)([wz_15_222](wz_15_222.md))、蒋介石(附蒋的是进步党之一部转变而成的政学系[16](16.md)([wz_16_222](wz_16_222.md)))就成了它的靠山。 - 历史不长的几个小党,如青年党[17](17.md)([wz_17_222](wz_17_222.md))等,没有军队,因此就闹不出什么名堂来。 - 外国的资产阶级政党不需要各自直接管领一部分军队。中国则不同,由于封建的分割,地主或资产阶级的集团或政党,谁有枪谁就有势,谁枪多谁就势大。处在这样环境中的无产阶级政党,应该看清问题的中心。 - 共产党员不争个人的兵权(决不能争,再也不要学张国焘),但要争党的兵权,要争人民的兵权。现在是民族抗战,还要争民族的兵权。在兵权问题上患幼稚病,必定得不到一点东西。劳动人民几千年来上了反动统治阶级的欺骗和恐吓的老当,很不容易觉悟到自己掌握枪杆子的重要性。日本帝国主义的压迫和全民抗战,把劳动人民推上了战争的舞台,共产党员应该成为这个战争的最自觉的领导者。每个共产党员都应懂得这个真理:“枪杆子里面出政权”。我们的原则是党指挥枪,而决不容许枪指挥党。但是有了枪确实又可以造党,八路军在华北就造了一个大党。还可以造干部,造学校,造文化,造民众运动。延安的一切就是枪杆子造出来的。枪杆子里面出一切东西。从马克思主义关于国家学说的观点看来,军队是国家政权的主要成分。谁想夺取国家政权,并想保持它,谁就应有强大的军队。有人笑我们是“战争万能论”,对,我们是革命战争万能论者,这不是坏的,是好的,是马克思主义的。俄国共产党的枪杆子造了一个社会主义。我们要造一个民主共和国。帝国主义时代的阶级斗争的经验告诉我们:工人阶级和劳动群众,只有用枪杆子的力量才能战胜武装的资产阶级和地主;在这个意义上,我们可以说,整个世界只有用枪杆子才可能改造。我们是战争消灭论者,我们是不要战争的;但是只能经过战争去消灭战争,不要枪杆子必须拿起枪杆子。 - [5](5.md)([wz_5_221](wz_5_221.md))一八九四年,孙中山在美国檀香山组织了一个资产阶级性质的革命小团体,叫做兴中会。一八九五年清朝政府在中日战争中失败以后,孙中山依靠兴中会联络民间秘密团体会党的力量,在广东组织过两次反对清朝统治的武装起义,即一八九五年的广州之役和一九○○年的惠州之役。 - [6](6.md)([wz_6_221](wz_6_221.md))一九○五年,兴中会同其他的反清团体华兴会等在日本东京联合组成中国资产阶级革命团体同盟会,采用了孙中山提出的“驱除鞑虏,恢复中华,创立民国,平均地权”的资产阶级革命的政纲。在同盟会的领导与影响下,革命党人联合会党、新军发动了多次武装起义,其中主要的是:一九○六年的萍乡浏阳醴陵之役,一九○七年的潮州黄冈之役、惠州之役、钦(州)廉(州)之役和镇南关(今广西友谊关)之役,一九○八年钦(州)廉(州)上思之役和云南河口之役,一九一○年的广州之役,一九一一年的广州之役和武昌起义。 - [7](7.md)([wz_7_221](wz_7_221.md))见本书第一卷《湖南农民运动考察报告》注〔3〕。 - [8](8.md)([wz_8_221](wz_8_221.md))一九一二年,同盟会改组为国民党,同当时北洋军阀袁世凯的统治实行妥协。一九一三年,袁世凯派军队南下,企图消灭在江西、安徽、广东等省的国民党势力,孙中山曾经发动武装的反抗,但是不久就失败了。一九一四年,孙中山鉴于对袁世凯妥协的失策,在日本东京另行组织中华革命党,以表示同当时的国民党相区别。中华革命党是资产阶级革命政党,它积极开展武装的反袁运动,主要的有:一九一四年湖南郴县、桂阳等地的起义,广东惠州、顺德等地的起义和一九一五年上海肇和军舰的起义。一九一五年十二月袁世凯称帝,蔡锷等反袁势力在云南发动讨袁战争。孙中山是当时武装反袁的积极鼓吹者和活动者,他领导的中华革命党人又在广东、山东等地发动了反袁的武装起义。 - [9](9.md)([wz_9_221](wz_9_221.md))一九一七年孙中山和在他影响下的海军由上海到广州,以广东为根据地,联合当时反对北洋军阀段祺瑞的西南军阀,组织反段的军政府。 - [10](10.md)([wz_10_221](wz_10_221.md))〕一九二一年,孙中山在广西桂林进行北伐的准备工作。一九二二年移驻广东韶关,正式出师北伐。由于部下陈炯明勾结北洋军阀举行叛变,这次北伐没有取得成果。 - [11](11.md)([wz_11_221](wz_11_221.md))〕一九二四年,孙中山在中国共产党和苏联的帮助下,在广州东郊的黄埔建立陆军军官学校,一九二六年改组为中央军事政治学校,通称黄埔军校。在一九二七年蒋介石背叛革命以前,这是一所国共合作的革命军校。孙中山兼任军校总理,廖仲恺任校党代表,蒋介石任校长。中国共产党人周恩来、恽代英、萧楚女、熊雄、聂荣臻以及其他同志,曾经先后在这个学校担任政治工作和其他工作,以革命精神为当时的革命军队培养了大批骨干,其中包括不少的共产党员和共产主义青年团员。 - [12](12.md)([wz_12_222](wz_12_222.md))〕谭延闿(一八八○——一九三○),湖南茶陵人,清末翰林。原主张君主立宪,后附和辛亥革命。他在一九一二年参加国民党的阵营,反映了湖南地方势力同北洋军阀之间的矛盾。在一九一一年至一九二○年期间,他先后当过湖南省的都督,省长兼署督军,督军、省长兼湘军总司令等职。 - [13](13.md)([wz_13_222](wz_13_222.md))〕进步党是一九一三年梁启超、汤化龙等组织的政党,当时它在政治上依附当权的袁世凯,曾经组织过内阁。一九一六年,进步党演变为“研究系”,又依附当权的段祺瑞,在一九一七年参加了段祺瑞组织的内阁。 - [14](14.md)([wz_14_222](wz_14_222.md))见本书第一卷《论反对日本帝国主义的策略》注〔1〕。 - [15](15.md)([wz_15_222](wz_15_222.md))段祺瑞(一八六五——一九三六),安徽合肥人,北洋军阀皖系首领。他是袁世凯的老部下,在袁世凯死后曾经几度把持北洋军阀的中央政权。 - [16](16.md)([wz_16_222](wz_16_222.md))政学系原是对一九一六年由一部分国民党右翼分子及进步党分子组成的官僚政客集团—— 政学会的通称。在北洋军阀统治时期,它勾结南北军阀,反对孙中山。一九二七年南京国民党政府成立前后,该系一部分成员先后投靠蒋介石,帮助蒋介石建立和维持反革命统治,又成为国民党内的派系之一,其主要成员有黄郛、杨永泰、张群、熊式辉等。 - [17](17.md)([wz_17_222](wz_17_222.md))〕青年党,即“国家主义派”的中国青年党。见本书第一卷《中国社会各阶级的分析》注〔1〕。 ### 三 中国共产党的战争史 - 我们党虽然在一九二一年(中国共产党成立)至一九二四年(国民党第一次全国代表大会)的三四年中,不懂得直接准备战争和组织军队的重要性;一九二四年至一九二七年,乃至在其以后的一个时期,对此也还认识不足;但是从一九二四年参加黄埔军事学校开始,已进到了新的阶段,开始懂得军事的重要了。经过援助国民党的广东战争和北伐战争,党已掌握了一部分军队[18](18.md)([wz_18_224](wz_18_224.md))。革命失败,得了惨痛的教训,于是有了南昌起义[19](19.md)([wz_19_224](wz_19_224.md))、秋收起义[20](20.md)([wz_20_224](wz_20_224.md))和广州起义[21](21.md)([wz_21_224](wz_21_224.md)),进入了创造红军的新时期。这个时期是我们党彻底地认识军队的重要性的极端紧要的时期。没有这一时期的红军及其所进行的战争,即是说,假如共产党采取了陈独秀的取消主义的话,今天的抗日战争及其长期支持是不能设想的。 - 一九二七年八月七日党中央的紧急会议[22](22.md)([wz_22_224](wz_22_224.md))反对了政治上的右倾机会主义,使党大进了一步。一九三一年一月的六届四中全会[23](23.md)([wz_23_224](wz_23_224.md)),在名义上反对政治上的“左”倾机会主义,在实际上重新犯了“左”倾机会主义的错误。这两个会议的内容和历史作用是不一样的,但是这两个会议都没有着重地涉及战争和战略的问题,这是当时党的工作重心还没有放在战争上面的反映。一九三三年党的中央迁至红色区域以后,情形有了根本的改变,但对于战争问题(以及一切主要问题),又犯了原则性的错误,致使革命战争遭受了严重的损失[24](24.md)([wz_24_224](wz_24_224.md))。一九三五年的遵义会议,则主要地是反对战争中的机会主义,把战争问题放在第一位,这是战争环境的反映。到今天为止,我们可以自信地说,中国共产党在十七年的斗争中,不但锻炼出来了一条坚强的马克思主义的政治路线,而且锻炼出来了一条坚强的马克思主义的军事路线。我们不但会运用马克思主义去解决政治问题,而且会运用马克思主义去解决战争问题;不但造就了一大批会治党会治国的有力的骨干,而且造就了一大批会治军的有力的骨干。这是无数先烈的热血浇灌出来的革命的鲜花,不但是中国共产党和中国人民的光荣,而且是世界共产党和世界人民的光荣。在世界范围内,还只有苏联、中国、西班牙三国共产党所领导的三个军队,是属于无产阶级和劳动人民方面的,其他各国的党都还没有军事经验,所以我们的军队和军事经验特别值得宝贵。 - 为了胜利地进行今天的抗日战争,扩大和巩固八路军、新四军和一切我党所领导的游击队,是非常重要的。在此原则下,党应派遣最好的和足够数量的党员和干部上前线。一切为了前线的胜利,组织任务须服从于政治任务。 - [18](18.md)([wz_18_224](wz_18_224.md))〕这里主要是指以共产党员叶挺为首的独立团(见本书第一卷《井冈山的斗争》注〔18〕),以贺龙为首的第二十军,朱德领导的第三军军官教育团,中央军事政治学校武汉分校。 - [19](19.md)([wz_19_224](wz_19_224.md))〕见本书第一卷《中国革命战争的战略问题》注〔37〕。 - [20](20.md)([wz_20_224](wz_20_224.md))〕见本书第一卷《中国革命战争的战略问题》注〔39〕。 - [21](21.md)([wz_21_224](wz_21_224.md))〕参见本书第一卷《中国的红色政权为什么能够存在?》注〔8〕。 - [22](22.md)([wz_22_224](wz_22_224.md))〕指中共中央在汉口召开的紧急会议。这次会议总结了第一次国内革命战争失败的经验教训,结束了陈独秀右倾投降主义在中央的统治,确定了土地革命和武装反抗国民党反动派统治的总方针,并把发动农民举行秋收起义作为当时党的最主要的任务。 - [23](23.md)([wz_23_224](wz_23_224.md))〕指一九三一年一月七日在上海召开的中国共产党第六届中央委员会第四次全体会议。陈绍禹等人在共产国际及其代表米夫的支持下,通过这次会议取得了在中共中央的领导地位,开始了长达四年之久的“左”倾冒险主义在党内的统治。 - [24](24.md)([wz_24_224](wz_24_224.md))〕参见本书第一卷《中国革命战争的战略问题》和本书第三卷《学习和时局》一文的附录《关于若干历史问题的决议》第四部分。 ### 四 国内战争和民族战争中党的军事战略的转变 - 我们党的军事战略的变化问题,值得给以研究。分为国内战争和民族战争两个过程来说。 - 国内战争的过程,大体上可以分为前后两个战略时期。在前期,主要的是游击战争;在后期,主要的是正规战争。但所谓正规战争是中国型的,只表现在集中兵力打运动战和指挥上、组织上的某种程度的集中性和计划性方面,其他则仍是游击性的,低级的,不能和外国军队一概而论,也和国民党的军队有些不同。因此,这种正规战,在某种意义上,是提高了的游击战。 - 在抗日战争的过程中,就我党的军事任务说来,也将大体上分为两个战略时期。在前期(包括战略防御和战略相持两个阶段),主要的是游击战争;在后期(战略反攻阶段),主要的将是正规战争。但抗日战争前期的游击战争,和国内战争前期的游击战争有许多不同的内容,因为是用正规性(某种程度上)的八路军去分散执行游击任务;抗日战争后期的正规战争也将不同于国内战争后期的正规战争,这是设想在装备了新式武器之后,军队和作战将要起一个大的变革而说的。这时的军队将获得高度的集中性和组织性,作战将获得高度的正规性,大大减少其游击性,低级的将变到高级的,中国型的将变到世界型的。这将是战略反攻阶段中的事业。 - 由此看来,国内战争和抗日战争两个过程和四个战略时期之间,共存在着三个战略的转变。第一个,国内游击战争和国内正规战争之间的转变。第二个,国内正规战争和抗日游击战争之间的转变。第三个,抗日游击战争和抗日正规战争之间的转变。 - 三个转变中,第一个转变曾经遇到很大的困难。这里有两方面的任务。一方面,要反对沉溺于游击性而不愿向正规性转变的右的地方主义和游击主义的倾向,这是由于干部对已经变化的敌情和任务估计不足而发生的。这一方面,拿中央红色区域来说,曾经作了艰苦的教育工作,才使之逐渐地转变过来。又一方面,则要反对过分地重视正规化的“左”的集中主义和冒险主义的倾向,这是由于一部分领导干部对敌情和任务估计过分,并且不看实情,机械地搬用外国经验而发生的。这一方面,在中央红色区域,曾经在三年的长时间内(遵义会议以前),付出了极大的牺牲,然后才从血的教训中纠正过来。这种纠正是遵义会议的成绩[25](25.md)([wz_25_226](wz_25_226.md))。 - 第二个转变是处于两个不同的战争过程之间的,这是一九三七年秋季(卢沟桥事变后)的事情。这时,敌人是新的,即日本帝国主义,友军是过去的敌人国民党(它对我们仍然怀着敌意),战场是地域广大的华北(暂时的我军正面,但不久就会变为长期的敌人后方)。我们的战略转变,是在这些特殊情况之下进行的一个极其严重的转变。在这些特殊的情况下,必须把过去的正规军和运动战,转变成为游击军(说的是分散使用,不是说的组织性和纪律性)和游击战,才能同敌情和任务相符合。但是这样的一个转变,便在现象上表现为一个倒退的转变,因此这个转变应该是非常困难的。这时可能发生的,一方面是轻敌倾向,又一方面是恐日病,这些在国民党中都是发生了的。国民党当它从国内战争的战场向民族战争的战场转变时,主要由于轻敌,同时也存在着一种恐日病(以韩复榘、刘峙[26](26.md)([wz_26_227](wz_26_227.md))为代表),而遭受了很多不应有的损失。然而我们却相当顺利地执行了这个转变,不但未遭挫败,反而大大地胜利了。这是由于广大的干部适时地接受了中央的正确指导和灵活地观察情况而获得的,虽然曾经在中央和一部分军事干部之间发生过严重的争论。这一转变关系于整个抗日战争的坚持、发展和胜利,关系于中国共产党的前途非常之大,只要想一想抗日游击战争在中国民族解放命运上的历史意义,就会知道的。中国的抗日游击战争,就其特殊的广大性和长期性说来,不但在东方是空前的,在整个人类历史上也可能是空前的。 - 至于由抗日游击战争到抗日正规战争的第三个转变,则属于战争发展的将来,估计那时又将发生新的情况和新的困难,现在可以不去说它。 - [25](25.md)([wz_25_226](wz_25_226.md))参见本书第三卷《学习和时局》一文的附录《关于若干历史问题的决议》第三部分。 - [26](26.md)([wz_26_227](wz_26_227.md))〕韩复榘,原来是长期统治山东的国民党军阀,抗日战争爆发后任第五战区副司令长官、第三集团军总司令。刘峙,蒋介石的嫡系,原来在河南,抗日战争爆发后任第一战区副司令长官、第二集团军总司令,负责防御河北省境内平汉铁路沿线地区。这两人在日本侵略军进攻的时候都不战而逃。韩复榘于一九三八年一月被蒋介石以失地误国罪处死。 ### 五 抗日游击战争的战略地位 - 在抗日战争的全体上说来,正规战争是主要的,游击战争是辅助的,因为抗日战争的最后命运,只有正规战争才能解决。就全国来说,在抗日战争全过程的三个战略阶段(防御、相持、反攻)中,首尾两阶段,都是正规战争为主,辅之以游击战争。中间阶段,由于敌人保守占领地、我虽准备反攻但尚不能实行反攻的情况,游击战争将表现为主要形态,而辅之以正规战;但这在全战争中只是三个阶段中的一个阶段,虽然其时间可能最长。故在全体上说来,正规战争是主要的,游击战争是辅助的。不认识这一情况,不懂得正规战争是解决战争最后命运的关键,不注意正规军的建设和正规战的研究和指导,就不能战胜日本。这是一方面。 - 但游击战争是在全战争中占着一个重要的战略地位的。没有游击战争,忽视游击队和游击军的建设,忽视游击战的研究和指导,也将不能战胜日本。原因是大半个中国将变为敌人的后方,如果没有最广大的和最坚持的游击战争,而使敌人安稳坐占,毫无后顾之忧,则我正面主力损伤必大,敌之进攻必更猖狂,相持局面难以出现,继续抗战可能动摇,即若不然,则我反攻力量准备不足,反攻之时没有呼应,敌之消耗可能取得补偿等等不利情况,也都要发生。假如这些情况出现,而不及时地发展广大的和坚持的游击战争去克服它,要战胜日本也是不可能的。因此,游击战争虽在战争全体上居于辅助地位,但实占据着极其重要的战略地位。抗日而忽视游击战争,无疑是非常错误的。这是又一方面。 - 游击战争的可能,只要具备大国这个条件就存在的,因此古代也有游击战争。但是游击战争的坚持,却只有在共产党领导之下才能出现。故古代的游击战争大都是失败的游击战争,只有现代有了共产党的大国,如像内战时期的苏联和中国这样的国家,才有胜利的游击战争。在战争问题上,抗日战争中国共两党的分工,就目前和一般的条件说来,国民党担任正面的正规战,共产党担任敌后的游击战,是必须的,恰当的,是互相需要、互相配合、互相协助的。 - 由此可以懂得,我们党的军事战略方针,由国内战争后期的正规战争转变为抗日战争前期的游击战争,是何等重要和必要的了。综合其利,有如下十八项:(一)缩小敌军的占领地;(二)扩大我军的根据地;(三)防御阶段,配合正面作战,拖住敌人;(四)相持阶段,坚持敌后根据地,利于正面整军;(五)反攻阶段,配合正面,恢复失地;(六)最迅速最有效地扩大军队;(七)最普遍地发展共产党,每个农村都可组织支部;(八)最普遍地发展民众运动,全体敌后人民,除了敌人的据点以外,都可组织起来;(九)最普遍地建立抗日的民主政权;(十)最普遍地发展抗日的文化教育;(十一)最普遍地改善人民的生活;(十二)最便利于瓦解敌人的军队;(十三)最普遍最持久地影响全国的人心,振奋全国的士气;(十四)最普遍地推动友军友党进步;(十五)适合敌强我弱条件,使自己少受损失,多打胜仗;(十六)适合敌小我大的条件,使敌人多受损失,少打胜仗;(十七)最迅速最有效地创造出大批的领导干部;(十八)最便利于解决给养问题。 - 在长期奋斗中,游击队和游击战争应不停止于原来的地位,而向高级阶段发展,逐渐地变为正规军和正规战争,这也是没有疑义的。我们将经过游击战争,积蓄力量,把自己造成为粉碎日本帝国主义的决定因素之一。 ### 六 注意研究军事问题 - 两军敌对的一切问题依靠战争去解决,中国的存亡系于战争的胜负。因此,研究军事的理论,研究战略和战术,研究军队政治工作,不可或缓。战术的研究虽然不足,但十年来从事军事工作的同志们已有很多的成绩,已有很多根据中国条件而提出的新东西,缺点在于没有总结起来。战略问题和战争理论问题的研究,至今还只限于极少数人的工作。政治工作的研究有第一等的成绩,其经验之丰富,新创设之多而且好,全世界除了苏联就要算我们了,但缺点在于综合性和系统性的不足。为了全党和全国的需要,军事知识的通俗化,成为迫切的任务。所有这些,今后都应该注意,而战争和战略的理论则是一切的骨干。从军事理论的研究,引起兴趣,唤起全党注意于军事问题的研究,我认为是必要的。 ## 五四运动[(1)]((1).md)([jz_0_234](jz_0_234.md)) - (一九三九年五月一日) - 二十年前的五四运动[1](1.md)([wz_1_234](wz_1_234.md)),表现中国反帝反封建的资产阶级民主革命已经发展到了一个新阶段。五四运动的成为文化革新运动,不过是中国反帝反封建的资产阶级民主革命的一种表现形式。由于那个时期新的社会力量的生长和发展,使中国反帝反封建的资产阶级民主革命出现一个壮大了的阵营,这就是中国的工人阶级、学生群众和新兴的民族资产阶级所组成的阵营。而在“五四”时期,英勇地出现于运动先头的则有数十万的学生。这是五四运动比较辛亥革命进了一步的地方。 - 中国资产阶级民主革命的过程,如果要从它的准备时期说起的话,那它就已经过了鸦片战争[2](2.md)([wz_2_234](wz_2_234.md))、太平天国战争[3](3.md)([wz_3_234](wz_3_234.md))、甲午中日战争[4](4.md)([wz_4_234](wz_4_234.md))、戊戌维新[5](5.md)([wz_5_234](wz_5_234.md))、义和团运动[6](6.md)([wz_6_234](wz_6_234.md))、辛亥革命[7](7.md)([wz_7_234](wz_7_234.md))、五四运动、北伐战争、土地革命战争等好几个发展阶段。今天的抗日战争是其发展的又一个新的阶段,也是最伟大、最生动、最活跃的一个阶段。直至国外帝国主义势力和国内封建势力基本上被推翻而建立独立的民主国家之时,才算资产阶级民主革命的成功。从鸦片战争以来,各个革命发展阶段各有若干特点。其中最重要的区别就在于共产党出现以前及其以后。然而就其全体看来,无一不是带了资产阶级民主革命的性质。这种民主革命是为了建立一个在中国历史上所没有过的社会制度,即民主主义的社会制度,这个社会的前身是封建主义的社会(近百年来成为半殖民地半封建的社会),它的后身是社会主义的社会。若问一个共产主义者为什么要首先为了实现资产阶级民主主义的社会制度而斗争,然后再去实现社会主义的社会制度,那答复是:走历史必由之路。 - 中国民主革命的完成依靠一定的社会势力。这种社会势力是:工人阶级、农民阶级、知识分子和进步的资产阶级,就是革命的工、农、兵、学、商,而其根本的革命力量是工农,革命的领导阶级是工人阶级。如果离开了这种根本的革命力量,离开了工人阶级的领导,要完成反帝反封建的民主革命是不可能的。在今天,革命的根本敌人是日本帝国主义和汉奸,革命的根本政策是抗日民族统一战线,这个统一战线的组织成分是一切抗日的工、农、兵、学、商。抗日战争最后胜利的取得,将是在工、农、兵、学、商的统一战线大大地巩固和发展的时候。 - 在中国的民主革命运动中,知识分子是首先觉悟的成分。辛亥革命和五四运动都明显地表现了这一点,而五四运动时期的知识分子则比辛亥革命时期的知识分子更广大和更觉悟。然而知识分子如果不和工农民众相结合,则将一事无成。革命的或不革命的或反革命的知识分子的最后的分界,看其是否愿意并且实行和工农民众相结合。他们的最后分界仅仅在这一点,而不在乎口讲什么三民主义或马克思主义。真正的革命者必定是愿意并且实行和工农民众相结合的。 - 五四运动到现在已有了二十个周年,抗日战争也快到两周年了。全国的青年和文化界对于民主革命和抗日战争负有大的责任。我希望他们认识中国革命的性质和动力,把自己的工作和工农民众结合起来,到工农民众中去,变为工农民众的宣传者和组织者。全国民众奋起之日,就是抗日战争胜利之时。全国青年们,努力啊! - [(1)]((1).md)([jz_0_234](jz_0_234.md))* 这是毛泽东为延安出版的中共中央机关报《解放》写的纪念五四运动二十周年的文章。 - [1](1.md)([wz_1_234](wz_1_234.md))见本书第一卷《实践论》注〔6〕。 - [2](2.md)([wz_2_234](wz_2_234.md))见本书第一卷《论反对日本帝国主义的策略》注〔35〕。 - [3](3.md)([wz_3_234](wz_3_234.md))见本书第一卷《论反对日本帝国主义的策略》注〔36〕。 - [4](4.md)([wz_4_234](wz_4_234.md))见本书第一卷《矛盾论》注〔22〕。 - [5](5.md)([wz_5_234](wz_5_234.md))见本卷《论持久战》注〔12〕。 - [6](6.md)([wz_6_234](wz_6_234.md))见本书第一卷《论反对日本帝国主义的策略》注〔37〕。 - [7](7.md)([wz_7_234](wz_7_234.md))见本书第一卷《湖南农民运动考察报告》注〔3〕。 ## 青年运动的方向[(1)]((1).md)([jz_0_237](jz_0_237.md)) - (一九三九年五月四日) - 今天是五四运动[1](1.md)([wz_1_237](wz_1_237.md))的二十周年纪念日,我们延安的全体青年在这里开这个纪念大会,我就来讲一讲关于中国青年运动的方向的几个问题。 - 第一,现在定了五月四日为中国青年节,这是很对的[2](2.md)([wz_2_237](wz_2_237.md))。“五四”至今已有二十年,今年才在全国定为青年节,这件事含着一个重要的意义。就是说,它表示我们中国反对帝国主义和封建主义的人民民主革命,快要进到一个转变点了。几十年来反帝反封建的人民民主革命屡次地失败了,这种情形,现在要来一个转变,不是再来一次失败,而是要转变到胜利的方面去了。现在中国的革命正在前进着,正在向着胜利前进。历史上多次失败的情形,不能再继续了,也决不能让它再继续了,而要使它转变为胜利。那末,现在已经转变了没有呢?没有。这一个转变,现在还没有到来,现在我们还没有胜利。但是胜利是可以争取到来的。抗日战争就要努力达到这个由失败到胜利的转变点。五四运动所反对的是卖国政府,是勾结帝国主义出卖民族利益的政府,是压迫人民的政府。这样的政府要不要反对呢?假使不要反对的话,那末,五四运动就是错的。这是很明白的,这样的政府一定要反对,卖国政府应该打倒。你们看,孙中山先生远在五四运动以前,就是当时政府的叛徒,他反对了清朝政府,并且推翻了清朝政府。他做的对不对呢?我以为是很对的。因为他所反对的不是反抗帝国主义的政府,而是勾结帝国主义的政府,不是革命的政府,而是压迫革命的政府。五四运动正是做了反对卖国政府的工作,所以它是革命的运动。全中国的青年,应该这样去认识五四运动。现当全国人民奋起抗日的时候,大家鉴于过去革命失败的经验,下决心一定要把日本帝国主义打败,并且不容许再有卖国贼,不容许革命再失败。全国的青年除了一部分人之外,大家都觉悟起来,都具备这种必胜的决心,规定“五四”为青年节就表示了这一点。我们正向胜利的路上前进,只要全国人民一齐努力,中国革命一定要在抗日过程中得到胜利。 - 第二,中国的革命,它反对的是什么东西?革命的对象是什么呢?大家知道,一个是帝国主义,一个是封建主义。现在的革命对象是什么?一个是日本帝国主义,再一个是汉奸。要革命一定要打倒日本帝国主义,一定要打倒汉奸。革命是什么人去干呢?革命的主体是什么呢?就是中国的老百姓。革命的动力,有无产阶级,有农民阶级,还有其他阶级中一切愿意反帝反封建的人,他们都是反帝反封建的革命力量。但是这许多人中间,什么人是根本的力量,是革命的骨干呢?就是占全国人口百分之九十的工人农民。中国革命的性质是什么?我们现在干的是什么革命呢?我们现在干的是资产阶级性的民主主义的革命,我们所做的一切,不超过资产阶级民主革命的范围。现在还不应该破坏一般资产阶级的私有财产制,要破坏的是帝国主义和封建主义,这就叫做资产阶级性的民主主义的革命。但是这个革命,资产阶级已经无力完成,必须靠无产阶级和广大人民的努力才能完成。这个革命要达到的目的是什么呢?目的就是打倒帝国主义和封建主义,建立一个人民民主的共和国。这种人民民主主义的共和国,就是革命的三民主义的共和国。它比起现在这种半殖民地半封建的状态来是不相同的,它跟将来的社会主义制度也不相同。在社会主义的社会制度中是不要资本家的;在这个人民民主主义的制度中,还应当容许资本家存在。中国是否永远要资本家呢?不是的,将来一定不要。不但中国如此,全世界也是如此。英国也好,美国也好,法国也好,日本也好,德国也好,意大利也好,将来都统统不要资本家,中国也不能例外。苏联是建设了社会主义的国家,将来全世界统统要跟它走,那是没有疑义的。中国将来一定要发展到社会主义去,这样一个定律谁都不能推翻。但是我们在目前的阶段上不是实行社会主义,而是破坏帝国主义和封建主义,改变中国现在的这个半殖民地半封建的地位,建立人民民主主义的制度。全国青年应当为此而努力。 - 第三,过去中国革命的经验教训怎么样呢?这也是青年要懂得的一个重要问题。中国反帝反封建的资产阶级民主革命,正规地说起来,是从孙中山先生开始的,已经五十多年了;至于资本主义外国侵略中国,则差不多有了一百年。一百年来,中国的斗争,从鸦片战争[3](3.md)([wz_3_239](wz_3_239.md))反对英国侵略起,后来有太平天国的战争[4](4.md)([wz_4_239](wz_4_239.md)),有甲午战争[5](5.md)([wz_5_239](wz_5_239.md)),有戊戌维新[6](6.md)([wz_6_239](wz_6_239.md)),有义和团运动[7](7.md)([wz_7_239](wz_7_239.md)),有辛亥革命[8](8.md)([wz_8_239](wz_8_239.md)),有五四运动,有北伐战争,有红军战争,这些虽然情形各不相同,但都是为了反抗外敌,或改革现状的。但是从孙中山先生开始,才有比较明确的资产阶级民主革命。从孙先生开始的革命,五十年来,有它胜利的地方,也有它失败的地方。你们看,辛亥革命把皇帝赶跑,这不是胜利了吗?说它失败,是说辛亥革命只把一个皇帝赶跑,中国仍旧在帝国主义和封建主义的压迫之下,反帝反封建的革命任务并没有完成。五四运动是干什么的呢?也是为着反帝反封建,但是也失败了,中国仍然在帝国主义和封建主义的统治之下。北伐战争的革命也是一样,它胜利了,但又失败了。国民党反共[9](9.md)([wz_9_240](wz_9_240.md))以来,中国又是帝国主义和封建主义的天下。于是不得不有十年的红军战争。但是这十年的奋斗,也只完成了局部的革命任务,还没有完成全国的革命任务。如果我们把过去几十年的革命做一个总结,那便是只得到了暂时的部分的胜利,没有永久的全国的胜利。正如孙中山先生说过的话:“革命尚未成功,同志仍须努力。”现在要问:中国革命干了几十年,为什么至今尚未达到目的呢?原因在什么地方呢?我以为原因在两个地方:第一是敌人的力量太强;第二是自己的力量太弱。一个强了,一个弱了,所以革命没有胜利。所谓敌人的力量太强,是说帝国主义(这是主要的)和封建主义的力量太强。所谓自己的力量太弱,有军事、政治、经济、文化各方面表现的弱点,但是主要的是因为占全国人口百分之九十的工农劳动群众还没有动员起来,所以表现了弱,所以不能完成反帝反封建的任务。如果要把几十年来的革命做一个总结,那就是全国人民没有充分地动员起来,并且反动派总是反对和摧残这种动员。而要打倒帝国主义和封建主义,只有把占全国人口百分之九十的工农大众动员起来,组织起来,才有可能。孙中山先生在他的遗嘱里说:“余致力国民革命凡四十年,其目的在求中国之自由平等。积四十年之经验,深知欲达到此目的,必须唤起民众及联合世界上以平等待我之民族共同奋斗。”这位老先生死了十多年了,连同他说的四十年,共有五十多年,这五十多年来的革命的经验教训是什么呢?根本就是“唤起民众”这一条道理。你们应该好好地研究一下,全国青年都应该好生研究。青年们一定要知道,只有动员占全国人口百分之九十的工农大众,才能战胜帝国主义,才能战胜封建主义。现在我们要达到战胜日本建立新中国的目的,不动员全国的工农大众,是不可能的。 - 第四,我再讲到青年运动。在二十年前的今天,由学生们参加的历史上叫做五四运动的大事件,在中国发生了,这是一个有重大意义的运动。“五四”以来,中国青年们起了什么作用呢?起了某种先锋队的作用,这是全国除开顽固分子以外,一切的人都承认的。什么叫做先锋队的作用?就是带头作用,就是站在革命队伍的前头。中国反帝反封建的人民队伍中,有由中国知识青年们和学生青年们组成的一支军队。这支军队是相当的大,死了的不算,在目前就有几百万。这支几百万人的军队,是反帝反封建的一个方面军,而且是一个重要的方面军。但是光靠这个方面军是不够的,光靠了它是不能打胜敌人的,因为它还不是主力军。主力军是谁呢?就是工农大众。中国的知识青年们和学生青年们,一定要到工农群众中去,把占全国人口百分之九十的工农大众,动员起来,组织起来。没有工农这个主力军,单靠知识青年和学生青年这支军队,要达到反帝反封建的胜利,是做不到的。所以全国知识青年和学生青年一定要和广大的工农群众结合在一块,和他们变成一体,才能形成一支强有力的军队。这是一支几万万人的军队啊!有了这支大军,才能攻破敌人的坚固阵地,才能攻破敌人的最后堡垒。拿这个观点来看过去的青年运动,就应该指出一种错误的倾向,这就是在过去几十年的青年运动中,有一部分青年,他们不愿意和工农大众相联合,他们反对工农运动,这是青年运动潮流中的一股逆流。他们实在太不高明,跟占全国人口百分之九十的工农大众不联合,并且根本反对工农。这样一个潮流好不好呢?我看是不好的,因为他们反对工农,就是反对革命,所以说,它是青年运动中的一股逆流。这样的青年运动,是没有好结果的。早几天,我作了一篇短文[10](10.md)([wz_10_242](wz_10_242.md)),我在那里说过这样一句话:“革命的或不革命的或反革命的知识分子的最后的分界,看其是否愿意并且实行和工农民众相结合。”我在这里提出了一个标准,我认为是唯一的标准。看一个青年是不是革命的,拿什么做标准呢?拿什么去辨别他呢?只有一个标准,这就是看他愿意不愿意、并且实行不实行和广大的工农群众结合在一块。愿意并且实行和工农结合的,是革命的,否则就是不革命的,或者是反革命的。他今天把自己结合于工农群众,他今天是革命的;但是如果他明天不去结合了,或者反过来压迫老百姓,那就是不革命的,或者是反革命的了。有些青年,仅仅在嘴上大讲其信仰三民主义[11](11.md)([wz_11_242](wz_11_242.md)),或者信仰马克思主义,这是不算数的。你们看,希特勒不是也讲“信仰社会主义”吗?墨索里尼在二十年前也还是一个“社会主义者”呢!他们的“社会主义”到底是什么东西呢?原来就是法西斯主义!陈独秀不是也“信仰”过马克思主义吗?他后来干了什么呢?他跑到反革命那里去了。张国焘不是也“信仰”过马克思主义吗?他现在到哪里去了呢?他一小差就开到泥坑里去了。有些人自己对自己加封为“三民主义信徒”,而且是老牌的三民主义者,可是他们做了些什么呢?原来他们的民族主义,就是勾结帝国主义;他们的民权主义,就是压迫老百姓;他们的民生主义呢,那就是拿老百姓身上的血来喝得越多越好。这是口是心非的三民主义者。所以我们看人的时候,看他是一个假三民主义者还是一个真三民主义者,是一个假马克思主义者还是一个真马克思主义者,只要看他和广大的工农群众的关系如何,就完全清楚了。只有这一个辨别的标准,没有第二个标准。我希望全国的青年切记不要堕入那股黑暗的逆流之中,要认清工农是自己的朋友,向光明的前途进军。 - 第五,现在的抗日战争,是中国革命的一个新阶段,而且是最伟大、最活跃、最生动的一个新阶段。青年们在这个阶段里,是负担了重大的责任的。我们中国几十年来的革命运动,经过了许多的奋斗阶段,但是没有一次像现在的抗日战争这样广大的。我们认为现在的中国革命有和过去不同的特点,它将从失败转变到胜利,就是指的中国的广大的人民进步了,青年的进步就是明证。因此,这次抗日战争是一定要胜利的,非胜利不可。大家知道,抗日战争的根本政策,是抗日民族统一战线,它的目的是打倒日本帝国主义,打倒汉奸,变旧中国为新中国,使全民族从半殖民地半封建的地位解放出来。现在中国青年运动的不统一,是一个很大的缺点。你们应该继续要求统一,因为统一才有力量。你们要使全国青年知道现在的形势,实行团结,抗日到底。 - 最后,第六,我要说到延安的青年运动。延安的青年运动是全国青年运动的模范。延安的青年运动的方向,就是全国的青年运动的方向。为什么?因为延安的青年运动的方向是正确的。你们看,在统一方面,延安的青年们不但做了,而且做得很好。延安的青年们是团结的,是统一的。延安的知识青年、学生青年、工人青年、农民青年,大家都是团结的。全国各地,远至海外的华侨中间,大批的革命青年都来延安求学。今天到会的人,大多数来自千里万里之外,不论姓张姓李,是男是女,作工务农,大家都是一条心。这还不算全国的模范吗?延安的青年们不但本身团结,而且和工农群众相结合,这一点更加是全国的模范。延安的青年们干了些什么呢?他们在学习革命的理论,研究抗日救国的道理和方法。他们在实行生产运动,开发了千亩万亩的荒地。开荒种地这件事,连孔夫子也没有做过。孔子办学校的时候,他的学生也不少,“贤人七十,弟子三千”[12](12.md)([wz_12_244](wz_12_244.md)),可谓盛矣。但是他的学生比起延安来就少得多,而且不喜欢什么生产运动。他的学生向他请教如何耕田,他就说:“不知道,我不如农民。”又问如何种菜,他又说:“不知道,我不如种菜的。”中国古代在圣人那里读书的青年们,不但没有学过革命的理论,而且不实行劳动。现在全国广大地方的学校,革命理论不多,生产运动也不讲。只有我们延安和各敌后抗日根据地的青年们根本不同,他们真是抗日救国的先锋,因为他们的政治方向是正确的,工作方法也是正确的。所以我说,延安的青年运动是全国青年运动的模范。 - 今天的大会很有意思。我要讲的都讲过了。希望大家把五十年来的中国革命经验研究一下,把好的地方发挥起来,把错误去掉,使全国青年和全国人民结合起来,使革命由失败转变到胜利。到了全国青年和全国人民都发动起来、组织起来、团结起来的一天,就是日本帝国主义被打倒的一天。每个青年都要担负这个责任。每个青年现在必须和过去不同,一定要下一个大决心,把全国的青年团结起来,把全国的人民组织起来,一定要把日本帝国主义打倒,一定要把旧中国改造为新中国。这就是我所希望于你们的。 - [(1)]((1).md)([jz_0_237](jz_0_237.md))* 这是毛泽东在延安青年群众举行的五四运动二十周年纪念会上的讲演。毛泽东在这个讲演中发展了关于中国革命问题的思想。 - [1](1.md)([wz_1_237](wz_1_237.md))见本书第一卷《实践论》注〔6〕。 - [2](2.md)([wz_2_237](wz_2_237.md))一九三九年三月,陕甘宁边区的青年组织规定以五月四日为中国青年节。那时国民党在广大青年群众的爱国高潮的压力下,也同意了这个规定。后来国民党畏惧青年学习“五四”的革命精神,觉得这个规定很危险,又改定以三月二十九日(一九一一年在广州起义中牺牲后来葬在黄花岗的革命烈士的纪念日)为青年节。但在共产党领导的革命根据地内则继续以五月四日为青年节。中华人民共和国成立以后,中央人民政府政务院在一九四九年十二月正式宣布以五月四日为中国青年节。 - [3](3.md)([wz_3_239](wz_3_239.md))见本书第一卷《论反对日本帝国主义的策略》注〔35〕。 - [4](4.md)([wz_4_239](wz_4_239.md))见本书第一卷《论反对日本帝国主义的策略》注〔36〕。 - [5](5.md)([wz_5_239](wz_5_239.md))见本书第一卷《矛盾论》注〔22〕。 - [6](6.md)([wz_6_239](wz_6_239.md))见本卷《论持久战》注〔12〕。 - [7](7.md)([wz_7_239](wz_7_239.md))见本书第一卷《论反对日本帝国主义的策略》注〔37〕。 - [8](8.md)([wz_8_239](wz_8_239.md))见本书第一卷《湖南农民运动考察报告》注〔3〕。 - [9](9.md)([wz_9_240](wz_9_240.md))指一九二七年蒋介石在上海、南京和汪精卫在武汉所发动的反革命政变。 - [10](10.md)([wz_10_242](wz_10_242.md))指本卷《五四运动》。 - [11](11.md)([wz_11_242](wz_11_242.md))见本书第一卷《湖南农民运动考察报告》注〔8〕。 - [12](12.md)([wz_12_244](wz_12_244.md))司马迁《史记·孔子世家》记载:“孔子以诗书礼乐教,弟子盖三千焉,身通六艺者七十有二人。” ## 反对投降活动[(1)]((1).md)([jz_0_246](jz_0_246.md)) - (一九三九年六月三十日) - 中华民族在日本侵略者面前,历来存在的劈头第一个大问题,就是战不战的问题。自“九一八”[1](1.md)([wz_1_246](wz_1_246.md))到卢沟桥事变[2](2.md)([wz_2_246](wz_2_246.md))之间,这个问题争论得很严重。“战则存,不战则亡”——这是一切爱国党派和一切爱国同胞的结论;“战则亡,不战则存”——这是一切投降主义者的结论。卢沟桥抗战的炮声,把这个争论暂时地解决了。它宣告:第一个结论是对的,第二个结论是错了。但是卢沟桥的炮声,为什么仅仅暂时地解决这个问题而没有最后地解决这个问题呢?这是由于日本帝国主义的诱降政策,由于国际投降主义者[3](3.md)([wz_3_246](wz_3_246.md))的妥协企图,由于中国抗日阵线中一部分人的动摇性。现时人们就把这个问题改变了一点词句,变为所谓“和战问题”,又提出来了。在中国内部,因而就掀起了主战派和主和派之争。他们的论点依然是一样,“战则存,和则亡”——主战派的结论;“和则存,战则亡”——主和派的结论。但是,主战派,乃是包括一切爱国党派,一切爱国同胞,全民族的大多数;主和派,即投降派,按其人数说来,则仅仅是抗日阵线中的一部分的动摇分子。因此,所谓主和派,就不得不进行其欺骗宣传,而第一就是反共。于是雪片一样地制造所谓“共产党捣乱”,“八路军、新四军游而不击,不听指挥”,“陕甘宁边区实行割据,向外扩展”,“共产党阴谋推翻政府”,乃至“苏联阴谋侵略中国”等等的假消息、假报告、假文件、假决议,用以蒙蔽事实的真相,企图造成舆论,达其主和即投降之目的。主和派即投降派之所以这样做,因为共产党是抗日民族统一战线的发起者和坚持者,不反对它,就不能破坏国共合作,就不能分裂抗日民族统一战线,就不能投降。其次,就是寄其希望于日本帝国主义的让步。他们认为日本已经不行了,它将改变其根本政策,自动地退出华中、华南甚至华北,中国可以不要再打而取得胜利。再其次,就是寄其希望于国际的压力。许多所谓主和派分子,他们不但希望各大国出来对日本压一压,迫使日本让步,以便讲和,而且还希望各国向中国政府的头上压一压,以便向主战派说:“你们看,国际空气如此,只得和吧!”“太平洋国际会议[4](4.md)([wz_4_247](wz_4_247.md))是有益于中国的,这不是什么慕尼黑[5](5.md)([wz_5_247](wz_5_247.md)),这是复兴中国的步骤!”这些,就是中国主和派即投降派的整套观点,整套做法,整套阴谋[6](6.md)([wz_6_247](wz_6_247.md))。这一套,不但汪精卫在演出,更严重的就是还有许多的张精卫、李精卫,他们暗藏在抗日阵线内部,也在和汪精卫里应外合地演出,有些唱双簧[7](7.md)([wz_7_247](wz_7_247.md)),有些装红白脸[8](8.md)([wz_8_247](wz_8_247.md))。 - 我们共产党人公开宣称:我们是始终站在主战派方面的,我们坚决地反对那些主和派。我们仅仅愿意和全国一切爱国党派、爱国同胞一道,巩固团结,巩固抗日民族统一战线,巩固国共合作,实行三民主义[9](9.md)([wz_9_247](wz_9_247.md)),抗战到底,打到鸭绿江边,收复一切失地[10](10.md)([wz_10_247](wz_10_247.md)),而不知其他。我们坚决地斥责那些公开的汪精卫和暗藏的汪精卫辈制造反共空气、挑拨国共磨擦[11](11.md)([wz_11_248](wz_11_248.md))、甚至企图再来挑动一次国共内战的阴谋。我们向他们说:你们这种分裂阴谋的实质,不过是你们实行投降的准备步骤,而你们的投降政策和分裂政策不过是出卖民族利益、图谋少数人私利的整个计划的表现;每个人民都有眼睛,你们的阴谋会被人民揭穿的。我们坚决地斥责那些认为太平洋会议并非东方慕尼黑的无稽之谈。所谓太平洋会议,就是东方慕尼黑,就是准备把中国变成捷克。我们坚决地斥责那些认为日本帝国主义能够觉悟、能够让步的空谈。日本帝国主义灭亡中国的根本方针是决不会变的。武汉失陷后日本的甜言蜜语,例如放弃其所谓“不以国民政府为对手”的方针[12](12.md)([wz_12_248](wz_12_248.md)),转而承认以国民政府为对手,例如所谓华中、华南撤兵的条件,乃是诱鱼上钓取而烹之的阴险政策,谁要上钓谁就准备受烹。国际投降主义者引诱中国投降,同样是他们的阴险政策。他们纵容日本侵略中国,自己“坐山观虎斗”,以待时机一到,就策动所谓太平洋调停会议,借收渔人之利。如果寄希望于这些阴谋家,同样将大上其当。 - 战或不战的问题,如今改成了战或和的问题,但性质还是一样,这是一切问题中的第一个大问题,最根本的问题。半年以来,由于日本诱降政策的加紧执行,国际投降主义者的积极活动,主要地还是在中国抗日阵线中一部分人的更加动摇,所谓和战问题竟闹得甚嚣尘上,投降的可能就成了当前政治形势中的主要危险;而反共,即分裂国共合作,分裂抗日团结,就成了那班投降派准备投降的首要步骤。在这种情形下,全国一切爱国党派,一切爱国同胞,必须睁大眼睛注视那班投降派的活动,必须认识当前形势中投降是主要危险、反共即准备投降这一个主要的特点,而用一切努力去反对投降和分裂。用全民族的血肉和日本帝国主义打了两个周年的战争,决不容许一部分人的动摇和叛卖。用全民族的努力所结成的抗日民族统一战线,决不容许一部分人的破坏和分裂。 - 战下去,团结下去,——中国必存。 - 和下去,分裂下去,——中国必亡。 - 何去何从?国人速择。 - 我们共产党人是一定要战下去,团结下去的。 - 全国一切爱国党派,一切爱国同胞,也是一定要战下去,团结下去的。 - 投降派的投降阴谋和分裂阴谋即使一时得势,最后也必被人民揭穿而受到制裁。中华民族的历史任务是团结抗战以求解放,投降派欲反其道而行之,无论他们如何得势,如何兴高采烈,以为天下“莫予毒也”,然而他们的命运是最后一定要受到全国人民的制裁的。 - 反对投降和分裂——这就是全国一切爱国党派、一切爱国同胞的当前紧急任务。 - 全国人民团结起来,坚持抗战和团结,把投降阴谋和分裂阴谋镇压下去啊! - [(1)]((1).md)([jz_0_246](jz_0_246.md))* 这是毛泽东为纪念抗日战争两周年写的文章。 - [1](1.md)([wz_1_246](wz_1_246.md))见本书第一卷《论反对日本帝国主义的策略》注〔4〕。 - [2](2.md)([wz_2_246](wz_2_246.md))见本卷《反对日本进攻的方针、办法和前途》注〔1〕。 - [3](3.md)([wz_3_246](wz_3_246.md))国际投降主义者,指当时阴谋牺牲中国、对日妥协的英美帝国主义者。 - [4](4.md)([wz_4_247](wz_4_247.md))当时,英、美、法帝国主义者和中国主和派阴谋召开所谓太平洋国际会议,同日本帝国主义妥协,出卖中国。这一阴谋被称为“远东慕尼黑”或者“东方慕尼黑”。毛泽东在本文中所斥责的那种认为太平洋国际会议并非东方慕尼黑的无稽之谈,是指当时蒋介石的说法。 - [5](5.md)([wz_5_247](wz_5_247.md))一九三八年九月,英、法、德、意四国政府首脑在德国的慕尼黑举行会议,签订了慕尼黑协定,英法将捷克斯洛伐克出卖给德国,作为德国向苏联进攻的交换条件。在一九三八年和一九三九年间,英美帝国主义曾经几次酝酿出卖中国来换取同日本帝国主义的妥协。一九三九年六月,即毛泽东作此文时,英日正在进行谈判,重新酝酿这种阴谋。这种阴谋同英、法、德、意在慕尼黑制造的阴谋类似,所以人们把它叫做“东方慕尼黑”。 - [6](6.md)([wz_6_247](wz_6_247.md))毛泽东这里所说的“中国主和派即投降派的整套观点,整套做法,整套阴谋”,就是指当时蒋介石的观点、做法和阴谋。当时汪精卫是公开的投降派的主要头目;蒋介石是暗藏在抗日阵线内部的投降派的主要头目。 - [7](7.md)([wz_7_247](wz_7_247.md))毛泽东这里指蒋介石和汪精卫彼此间的活动有如唱双簧的关系。 - [8](8.md)([wz_8_247](wz_8_247.md))当时以蒋介石为首的国民党主和派采取两面派的活动,一面还装着抗战的样子,另一面又用各种形式去进行投降的活动,就好像中国古典戏剧中的演员,有的化装红脸,有的化装白脸一样。 - [9](9.md)([wz_9_247](wz_9_247.md))见本书第一卷《湖南农民运动考察报告》注〔8〕。 - [10](10.md)([wz_10_247](wz_10_247.md))〕一九三九年一月,蒋介石在国民党五届五中全会上说出他的所谓抗战到底的“底”,是恢复卢沟桥事变以前的状态。毛泽东因此特别提出抗战到底的界说,是“打到鸭绿江边,收复一切失地”,以对抗蒋介石的投降政策。 - [11](11.md)([wz_11_248](wz_11_248.md))〕“磨擦”是当时流行的一个名词,指国民党反动派破坏抗日民族统一战线、反对共产党和进步势力的各种反动行为。 - [12](12.md)([wz_12_248](wz_12_248.md))一九三七年十二月十三日,日本侵略军占领南京。一九三八年一月十六日,日本政府发表声明,宣称“今后将不以国民政府为对手,期望真正与帝国合作的新兴中国政权的成立和发展”。同年十月,日军占领广州和武汉。日本政府利用蒋介石对于抗战的动摇,改取诱蒋投降为主的方针,在十一月三日又发表声明,宣称“如果国民政府抛弃以往的指导方针,更换人事,改弦易辙,参加新秩序的建设,我方亦不拒绝”。 ## 必须制裁反动派[(1)]((1).md)([jz_0_251](jz_0_251.md)) - (一九三九年八月一日) - 今天是八月一日,我们在这里开追悼大会。为什么要开这样的追悼会呢?因为反动派杀死了革命的同志,杀死了抗日的战士。现在应该杀死什么人?应该杀死汉奸,杀死日本帝国主义者。但是,中国和日本帝国主义者打了两年仗,还没有分胜负。汉奸还是很活跃,杀死的也很少。革命的同志,抗日的战士,却被杀死了。什么人杀死的?军队杀死的。军队为什么杀死了抗日战士?军队是执行命令,有人指使军队去杀的。什么人指使军队去杀?反动派在那里指使[1](1.md)([wz_1_251](wz_1_251.md))。同志们!照理说,什么人要杀抗日战士呢?第一是日本帝国主义者要杀他们,第二是汪精卫[2](2.md)([wz_2_251](wz_2_251.md))等汉奸卖国贼要杀他们。但是现在杀人的地方不是在上海、北平、天津、南京,不是在日寇汉奸占领的地方,而是在平江这个地方,在抗战的后方,被杀死的是新四军平江通讯处的负责同志涂正坤、罗梓铭等。很明显,是那班中国反动派接受了日本帝国主义和汪精卫的命令来杀人的。这些反动派,他们是准备投降的,所以恭恭敬敬地执行了日本人和汪精卫的命令,先把最坚决的抗日分子杀死。这件事非同小可,我们一定要反对,我们一定要抗议! - 现在全国抗日,全国人民在抗日的目标之下结成一个大团结。在这个大团结里面,有一部分人是反动派,是投降派。他们干什么呢?就是杀抗日分子,压制进步,勾结日寇汉奸,准备投降。 - 这样一件杀死抗日同志的大事,有谁出来过问呢?自从六月十二日下午三时杀了人之后,到今天是八月一日了,我们看见有人出来过问没有呢?没有。这件事应该由谁出来过问呢?应该由中国的法律出来过问,由法官出来过问。如果在陕甘宁边区发生了这样的事情,我们的高等法院早就出来过问了。但是,平江惨案快两个月了,法律和法官并没有出来过问。这是什么缘故呢?这是因为中国不统一[3](3.md)([wz_3_252](wz_3_252.md))。 - 中国应该统一,不统一就不能胜利。但是什么叫统一呢?统一就是要大家抗日,要大家团结,要大家进步,要有赏有罚。应该赏什么人呢?应该赏抗日的人,赏团结的人,赏进步的人。应该罚什么人呢?应该罚破坏抗日、团结、进步的汉奸和反动派。现在统一了没有呢?没有。平江惨案就是证据。从这件事情就可以看出,应该统一的没有统一。我们早就要求全国统一。第一个,统一于抗战。现在涂正坤、罗梓铭等抗日同志不但没有受赏,反被惨杀了;而那些坏蛋,他们反对抗战,准备投降,实行杀人,却没有受处罚。这就是不统一。我们要反对这些坏蛋,反对这些投降分子,捉拿这些杀人凶手。第二个,统一于团结。赞成团结的应该受赏,破坏团结的应该受罚。但是现在赞成团结的涂正坤、罗梓铭等同志,他们倒受了处罚,被人惨杀了;而那些破坏团结的坏人却没有受到一点处罚。这就是不统一。第三个,统一于进步。要全国进步,要落后的人向进步的人看齐,决不能拉进步的人向落后的人看齐。平江惨案的那些刽子手,他们把进步分子杀了。抗战以来,被暗杀的共产党员和爱国志士已经不下几十几百,平江惨案不过是最近的一件事。这样下去,中国就不得了,抗日的人可以统统被杀。杀抗日的人,这是什么意思?这就是说:中国的反动派执行了日本帝国主义和汪精卫的命令,准备投降,所以先杀抗日军人,先杀共产党员,先杀爱国志士。这样的事如果不加制止,中国就会在这些反动派手里灭亡。所以这件事是全国的事,是很大的事,我们必须要求国民政府严办那些反动派。 - 同志们还要懂得,近来日本帝国主义的捣乱更加厉害了,国际帝国主义帮助日本也更加积极了[4](4.md)([wz_4_253](wz_4_253.md)),中国内部的汉奸,公开的汪精卫和暗藏的汪精卫,他们破坏抗战,破坏团结,向后倒退,也更加积极了。他们想使中国大部投降,内部分裂,国内打仗。现在国内流行一种秘密办法,叫做什么《限制异党活动办法》[5](5.md)([wz_5_253](wz_5_253.md)),其内容全部是反动的,是帮助日本帝国主义的,是不利于抗战,不利于团结,不利于进步的。什么是“异党”?日本帝国主义是异党,汪精卫是异党,汉奸是异党。共产党和一切抗日的党派,一致团结抗日,这是“异党”吗?现在偏偏有那些投降派、反动派、顽固派,在抗战的队伍中闹磨擦,闹分裂,这种行为对不对呢?完全不对的。(全场鼓掌)“限制”,现在要限制什么人?要限制日本帝国主义者,要限制汪精卫,要限制反动派,要限制投降分子。(全场鼓掌)为什么要限制最抗日最革命最进步的共产党呢?这是完全不对的。我们延安的人民表示坚决的反对,坚决的抗议。(全场鼓掌)我们要反对所谓《限制异党活动办法》,这种办法就是破坏团结的种种罪恶行为的根源。我们今天开这个大会,就是为了继续抗战,继续团结,继续进步。为了这个,就要取消《限制异党活动办法》,就要制裁那些投降派、反动派,就要保护一切革命的同志、抗日的同志、抗日的人民。(热烈鼓掌,高呼口号) - [(1)]((1).md)([jz_0_251](jz_0_251.md))* 这是毛泽东在延安人民追悼平江惨案死难烈士大会上的演说。 - [1](1.md)([wz_1_251](wz_1_251.md))一九三九年六月十二日,根据蒋介石的秘密命令,国民党第二十七集团军派兵包围新四军驻湖南平江嘉义镇的通讯处,惨杀新四军参议涂正坤、八路军少校副官罗梓铭等六人。这个惨杀事件,激起了各抗日根据地的人民和国民党统治区的正义人士的公愤。毛泽东在这篇演说中所抨击的反动派,就是指的这次惨杀事件的指使者蒋介石和他的党徒。 - [2](2.md)([wz_2_251](wz_2_251.md))见本书第一卷《论反对日本帝国主义的策略》注〔31〕。 - [3](3.md)([wz_3_252](wz_3_252.md))毛泽东在这里所解释的“统一”,是针对国民党反动派企图利用“统一”的名义,以消灭共产党领导的抗日武装和抗日根据地的阴谋而提出的。自从国共两党重新合作共同抗日之日起,国民党在政治上用以打击共产党的主要武器就是“统一”这个口号,他们诬蔑共产党标新立异,妨碍统一,不利抗日。一九三九年一月国民党五届五中全会原则通过《防制异党活动办法》以后,这种反动叫嚣就更加猖狂了。毛泽东在这里把“统一”这个口号从国民党反动派手里夺取过来,变为革命的口号,用以反对国民党的反人民反民族的分裂行动。 - [4](4.md)([wz_4_253](wz_4_253.md))参见本卷《反对投降活动》。一九三八年十月武汉失守以后,日本帝国主义对国民党采取以政治诱降为主的方针,英美等帝国主义也不断劝蒋介石同日本帝国主义“议和”。一九三八年十一月,英国首相张伯伦表示愿意实行英日经济合作,共同参加所谓“远东建设”。一九三九年,英美帝国主义企图牺牲中国以便同日本侵略者妥协的阴谋活动更加露骨。这一年的四月,英国驻华大使卡尔往返于蒋介石和日本之间,企图拉拢中日“议和”。六月,美国示意国民党政府外交官员,要中国出面提议召开国际会议,解决中日问题。七月,英日达成协议,英国完全承认日本侵略中国所造成的“实际局势”。 - [5](5.md)([wz_5_253](wz_5_253.md))一九三八年十月武汉失守后,国民党逐渐加紧反共活动。一九三九年春,国民党中央秘密颁布《防制异党活动办法》,随后又秘密颁布《异党问题处理办法》、《处理异党问题实施方案》。在这些反动的文件里,规定采用法西斯统治的方法,限制共产党人和一切进步分子的思想、言论和行动,破坏一切抗日的群众组织;在国民党反动派所认为的“异党活动最烈之区域”,实行“联保连坐法”,在保甲组织中建立“通讯网”,即建立反革命的特务组织,以便随时监视和限制人民的活动;在华中、华北各地,布置对共产党的政治压迫和军事进攻。 ## 关于国际新形势对新华日报[1](1.md)([wz_1_256](wz_1_256.md))记者的谈话 - (一九三九年九月一日) - 记者问:苏德互不侵犯协定的订立[2](2.md)([wz_2_256](wz_2_256.md)),其意义如何? - 毛答:苏德互不侵犯协定是苏联社会主义力量增长和苏联政府坚持和平政策的结果。这个协定打破了张伯伦、达拉第[3](3.md)([wz_3_256](wz_3_256.md))等国际反动资产阶级挑动苏德战争的阴谋,打破了德意日反共集团对于苏联的包围,巩固了苏德两国间的和平,保障了苏联社会主义建设的发展。在东方,则打击了日本,援助了中国,增强了中国抗战派的地位,打击了中国的投降派。在这一切上面,就安置了援助全世界人民争取自由解放的基础。这就是苏德互不侵犯协定的全部政治意义。 - 问:人们还不明了苏德互不侵犯协定是英法苏谈判破裂的结果,反而以为英法苏谈判的破裂是苏德协定的结果。请你说明一下英法苏谈判为什么没有成功。 - 答:英法苏三国谈判所以没有成功,完全由于英法政府没有诚意。近年来,世界反动资产阶级首先是英法的反动资产阶级,对于德意日法西斯的侵略,一贯地执行了一种反动的政策,即所谓“不干涉”政策。这个政策的目的,在于纵容侵略战争,自己从中取利。因此,英法根本拒绝苏联历来提出的组织真正的反侵略阵线的建议,而采取“不干涉”的立场,纵容德意日侵略,自己站在一边看。其目的在于使战争的双方互相消耗,然后自己出台干涉。在执行这个反动政策的过程中,曾经牺牲了半个中国给日本,牺牲了整个阿比西尼亚、整个西班牙、整个奥国、整个捷克给德意[4](4.md)([wz_4_257](wz_4_257.md))。这一次又想牺牲苏联。这种阴谋,在这次英法苏三国的谈判中已经明显地暴露出来了。这个谈判,从四月十五日到八月二十三日,进行了四个多月,在苏联方面尽到了一切的忍耐。英法则始终不赞成平等互惠原则,只要求苏联保证它们的安全,它们却不肯保证苏联的安全,不肯保证波罗的海诸小国的安全,以便开一个缺口让德国进兵,并且不让苏联军队通过波兰去反对侵略者。这就是谈判破裂的原因。在这个期间,德国愿意停止反苏,愿意放弃所谓《防共协定》[5](5.md)([wz_5_257](wz_5_257.md)),承认了苏联边疆的不可侵犯,苏德互不侵犯协定就订立了。国际反动派,首先是英法反动派的这种“不干涉”政策,乃是“坐山观虎斗”的政策,是完全损人利己的帝国主义的政策。它从张伯伦上台开始,到去年九月慕尼黑协定[6](6.md)([wz_6_257](wz_6_257.md))发展到了顶点,到此次英法苏谈判就最后破产。往后的时间,就不得不变成英法和德意两大帝国主义集团直接冲突的局面。我一九三八年十月在中共六届六中全会上曾经说过:“搬起石头打自己的脚,这就是张伯伦政策的必然结果。”张伯伦以损人的目的开始,以害己的结果告终。这将是一切反动政策的发展规律。 - 问:据你看,目前的时局将要如何发展? - 答:目前的国际时局已处在新的形势中。早已开始了的第二次帝国主义战争的片面性状态,即是说,由于“不干涉”政策而发生的一方进攻、一方坐视的局面,就欧洲方面说来,今后势必由全面性的战争起而代之。第二次帝国主义战争已进到新的阶段。 - 在欧洲方面,德意帝国主义集团和英法帝国主义集团之间,为了争夺对殖民地人民统治权的帝国主义大战,是迫在眉睫了。在战争中,为了欺骗人民,为了动员舆论,战争的双方都将不顾羞耻地宣称自己是正义的,而称对方是非正义的。其实,这只是一种欺骗。因为,双方的目的都是帝国主义的目的,都是为了争夺对殖民地半殖民地和势力范围的统治权,都是掠夺性的战争。在目前,就是为了争夺波兰,争夺巴尔干半岛和地中海沿岸。这样的战争完全不是正义的。世界上只有非掠夺性的谋解放的战争,才是正义的战争。共产党决不赞助任何掠夺战争。共产党对于一切正义的非掠夺的谋解放的战争,则将挺身出而赞助,并站在斗争的最前线。第二国际所属的社会民主党,在张伯伦、达拉第的威迫利诱之下,正在发生分化,一部分上层反动分子正在蹈袭第一次大战时的覆辙,准备赞助新的帝国主义战争。但另一部分,则将和共产党一道建立反战反法西斯的人民阵线。目前张伯伦、达拉第正在模仿德意,一步一步地反动化,正在利用战争动员将国家组织法西斯化,将经济组织战争化。总之,两大帝国主义集团正在狂热地准备战争,大屠杀的危险临到千百万人民的头上。这种情形,毫无疑义地将激起广大人民的反抗运动。无论在德意,无论在英法,无论在欧洲和世界其他地方,人民如果不愿充当帝国主义的炮灰,他们就一定会起来用各种方式去反对帝国主义战争。 - 在资本主义世界,除了上述两大集团之外,还有第三个集团,这就是以美国为首的包括中美洲南美洲许多国家在内的集团。这个集团,为了自己的利益,暂时还不至于转入战争。美国帝国主义想在中立的名义之下,暂时不参加战争的任何一方,以便在将来出台活动,争取资本主义世界的领导地位。美国资产阶级暂时还不准备在国内取消民主政治和平时的经济生活,这一点对于世界的和平运动是有利益的。 - 日本帝国主义受了苏德协定的严重打击,它的前途将更加困难。它的外交政策,正在两派斗争中。军阀想和德意建立联盟,达到独占中国,侵略南洋,排斥英美法出东方的目的;但一部分资产阶级则主张对英美法让步,把目标集中于掠夺中国。目前和英国妥协的趋势甚大。英国反动派将以共同瓜分中国和在财政上经济上帮助日本为条件,换得日本充当英国利益的东方警犬,镇压中国的民族解放运动,牵制苏联。因此,不管怎样,日本灭亡中国的根本目的是决不会变更的。日本对中国正面大规模军事进攻的可能性,或者不很大了;但是,它将更厉害地进行其“以华制华”[7](7.md)([wz_7_259](wz_7_259.md))的政治进攻和“以战养战”[8](8.md)([wz_8_259](wz_8_259.md))的经济侵略,而在其占领地则将继续疯狂的军事“扫荡”[9](9.md)([wz_9_259](wz_9_259.md));并想经过英国压迫中国投降。在某种适合于日本的时机,日本将发起东方慕尼黑,以某种较大的让步为钓饵,诱胁中国订立城下之盟,用以达其灭亡中国的目的。日本的这种帝国主义的目的,在日本人民革命没有起来之前,不管日本统治阶级掉换什么内阁,都是不会变更的。 - 在整个资本主义世界之外,另一个光明世界,就是社会主义的苏联。苏德协定增加了苏联帮助世界和平运动的可能,增加了它援助中国抗日的可能。 - 这些就是我对于国际形势的估计。 - 问:在这种形势下,中国的前途将如何? - 答:中国的前途有两个:一个是坚持抗战、坚持团结、坚持进步的前途,这就是复兴的前途。一个是实行妥协、实行分裂、实行倒退的前途,这就是亡国的前途。 - 在新的国际环境中,在日本更加困难和我国绝不妥协的条件之下,我国的战略退却阶段便已完结,而战略相持阶段便已到来。所谓战略相持阶段,即是准备反攻的阶段。 - 但是,正面相持和敌后相持是成反比例的,正面相持的局面出现,敌后斗争的局面就要紧张。所以,从武汉失守后开始的敌人在沦陷区(主要是在华北)举行的大规模的军事“扫荡”,今后不但还会继续,而且还会加紧起来。更因敌人目前的主要政策是“以华制华”的政治进攻和“以战养战”的经济侵略,英国的东方政策是远东慕尼黑,这就极大地加重了中国大部投降和内部分裂的危险。至于我国国力和敌人对比,还是相差很远,要准备实行反攻的力量,非全国一致,艰苦奋斗,是不可能的。 - 因此,我国坚持抗战的任务还是一个非常严重的任务,千万不要丝毫大意。 - 因此,毫无疑义,中国万万不可放弃现在的时机,万万不可打错主意,而应该采取坚定的政治立场。 - 这就是:第一,坚持抗战的立场,反对任何的妥协运动。不论是公开的汪精卫和暗藏的汪精卫,都应该给以坚决的打击。不论是日本的引诱和英国的引诱,都应该给以坚决的拒绝,中国决不能参加东方慕尼黑。 - 第二,坚持团结的立场,反对任何的分裂运动。也不论是从日本帝国主义方面来的,从其他外国方面来的,从国内投降派方面来的,都应该充分警戒。任何不利于抗战的内部磨擦,都必须用严正的态度加以制止。 - 第三,坚持进步的立场,反对任何的倒退运动。不论是军事方面的、政治方面的、财政经济方面的、党务方面的、文化教育方面的和民众运动方面的,一切不利于抗战的思想、制度和办法,都要来一个重新考虑和切实改进,以利抗战。 - 果能如此,中国就能好好地准备反攻的力量。 - 从现时起,全国应以“准备反攻”为抗战的总任务。 - 在现时,一方面,应当严正地支持正面的防御,有力地援助敌后的战争;另一方面,应当实行政治、军事等各种改革,聚积巨大的力量,以便等候时机一到,就倾注全力,大举反攻,收复失地。 - [1](1.md)([wz_1_256](wz_1_256.md))《新华日报》是中国共产党在国民党统治区公开出版的机关报。一九三八年一月十一日在汉口创刊,同年十月二十五日迁到重庆继续出版。一九四七年三月被国民党政府强迫停刊。 - [2](2.md)([wz_2_256](wz_2_256.md))苏德互不侵犯条约订立于一九三九年八月二十三日。 - [3](3.md)([wz_3_256](wz_3_256.md))张伯伦是当时英国政府的首相,达拉第是当时法国政府的总理。他们一贯纵容德、意、日法西斯发动侵略战争,企图把这种侵略战争的矛头引向苏联。但是,同他们的愿望相反,帝国主义之间的矛盾日益尖锐,在一九三九年九月,德国法西斯首先向英法和它们的同盟国发动了战争。 - [4](4.md)([wz_4_257](wz_4_257.md))一九三五年十月,意大利开始武装侵略阿比西尼亚(埃塞俄比亚),于一九三六年五月将埃塞俄比亚占领。一九三六年七月,德国和意大利共同武装干涉西班牙内政,支持佛朗哥法西斯势力反叛西班牙人民阵线政府。人民阵线政府领导西班牙人民进行了长期的抗战,于一九三九年三月失败。一九三八年三月德国出兵占领奥地利,同年十月又出兵侵占捷克斯洛伐克的苏台德区,于一九三九年三月完全占领了捷克斯洛伐克。德意法西斯这些疯狂的侵略行动,都是在当时英法政府“不干涉”政策的纵容和鼓励之下进行并且获得成功的。 - [5](5.md)([wz_5_257](wz_5_257.md))一九三六年十一月,德日订立《反共产国际协定》和《反共产国际协定附属议定书》,同时还制定了一个直接反对苏联的秘密附件。一九三七年十一月,意大利也参加了这个协定。 - [6](6.md)([wz_6_257](wz_6_257.md))参见本卷《反对投降活动》注〔5〕。 - [7](7.md)([wz_7_259](wz_7_259.md))“以华制华”是日本帝国主义侵略中国的一种阴谋毒计。向来,日本帝国主义总是在中国培植可以供它利用的力量,以便分裂中国内部而达到它的侵略目的。抗日战争爆发以后,它不仅利用国民党中汪精卫派公开的亲日分子,而且利用蒋介石派的力量来牵制抗战最坚决的中国共产党。从一九三九年起,日本帝国主义对蒋介石军队停止大规模的战略进攻,着重从政治上鼓励他进行反共活动,正是这种“以华制华”政策的实施。 - [8](8.md)([wz_8_259](wz_8_259.md))日本帝国主义在中国的占领区内实行残暴的经济掠夺,用以供给它进行侵略战争的需要。日本军阀把这种政策叫做“以战养战”。 - [9](9.md)([wz_9_259](wz_9_259.md))一九三八年十月武汉失守后,日本帝国主义逐渐集中主要兵力进犯敌后抗日根据地。他们所到之处,极其野蛮地实行烧光、杀光和抢光的政策。敌人把这种疯狂的军事进犯叫做“扫荡”。 ## 和中央社、扫荡报、新民报[1](1.md)([wz_1_263](wz_1_263.md))三记者的谈话 - (一九三九年九月十六日) - 记者问:有几个问题请教。今天在《新中华报》[2](2.md)([wz_2_263](wz_2_263.md))上看了毛先生九月一日的谈话,有些问题已经说到了,有些尚请毛先生补充。问题分三部分,就是写在纸上的,请逐一赐教。 - 毛答:可以根据先生们的问题表,分别来讲。 - 先生们提到抗战的相持阶段是否到来的问题。我以为,相持阶段是有条件地到来了。就是说,在国际新形势之下,在日本更加困难和中国绝不妥协的条件之下,可以说已经到来了。这里并不否认敌人还可能有比较大的战役进攻,例如进攻北海、长沙,甚至进攻西安,都是可能的。说敌人的大规模战略进攻和我们的战略退却在一定条件下基本上已经停止,并不是说一切进攻的可能和一切退却的可能都没有了。至于新阶段的具体内容,就是准备反攻,一切都可以包括在这一概念之中。这就是说,中国要在相持阶段中准备一切力量,以备将来的反攻。说准备反攻,并不是立即反攻,条件不够是不能反攻的。而且这讲的是战略的反攻,不是战役的反攻。战役上的反攻,例如对付敌人在晋东南的军事“扫荡”,我们把他打退,这样的战役反攻不但会有,而且是必不可少的。但是战略上的大举反攻时期,现在还没有到,现在是对于这种大举反攻作积极准备的时期。在这个时期内,还要打退正面敌人一些可能的战役进攻。 - 如果把新阶段的任务分别来讲,那末,在敌人后方,一定要坚持游击战争,粉碎敌人的“扫荡”,破坏敌人的经济侵略;在正面,一定要巩固军事防御,打退敌人可能的战役进攻;在大后方[3](3.md)([wz_3_264](wz_3_264.md)),主要的是积极改革政治。这许多,都是准备反攻的具体内容。 - 改革国内政治之所以非常重要,是因为敌人在目前,主要的是政治进攻,我们就要特别加强政治抵抗。这就是说,民主政治的问题,应当快点解决,才能加强政治上的抵抗力,才能准备军事力量。中国抗战主要地依靠自力更生。如果过去也讲自力更生,那末,在新的国际环境下,自力更生就更加重要。自力更生的主要内容,就是民主政治。 - 问:刚才毛先生说,为了自力更生达到抗战胜利,民主政治是必要的,那末,在现在的环境下,用什么方法来实现这个制度? - 答:军政、训政、宪政三个时期的划分[4](4.md)([wz_4_264](wz_4_264.md)),原是孙中山先生说的。但孙先生在逝世前的《北上宣言》[5](5.md)([wz_5_264](wz_5_264.md))里,就没有讲三个时期了,那里讲到中国要立即召开国民会议。可见孙先生的主张,在他自己,早就依据情势,有了变动。现在在抗战这种严重的局面之下,要避免亡国惨祸,并把敌人打出去,必须快些召集国民大会,实行民主政治。关于这个问题,有各种不同的议论。有些人说:老百姓没有知识,不能实行民主政治。这是不对的。在抗战中间,老百姓进步甚快,加上有领导,有方针,一定可以实行民主政治。例如在华北,已经实行了民主政治。在那里,区长、乡长、保甲长,多是民选的。县长,有些也是民选的了,许多先进的人物和有为的青年,被选出来当县长了。这样的问题,应该提出让大家讨论。 - 先生们提出的第二部分问题里,有关于所谓“限制异党”的问题,就是说,关于各地磨擦的问题。先生们关心这件事是很对的。关于这件事,近来情况虽然比较好一点,但是根本上没有什么变化。 - 问:共产党对这个问题的态度,曾向中央政府表示过没有? - 答:我们已经提出抗议。 - 问:用什么方式提出的? - 答:还是在七月间,我们党的代表周恩来同志,已经写信给蒋委员长。八月一日,延安各界又打了电报给蒋委员长和国民政府,要求取消那个秘密流行成为各地磨擦根源的所谓《限制异党活动办法》[6](6.md)([wz_6_265](wz_6_265.md))。 - 问:中央政府有无答复? - 答:没有答复。听说这个东西,国民党里面也有一些人不赞成。你们知道,共同抗日的军队叫做友军,不叫做“异军”,那末,共同抗日的党派就是友党,不是“异党”。抗战中间有许多党派,党派的力量有大小,但是大家同在抗战,完全应该互相团结,而决不应该互相“限制”。什么是异党?日本走狗汪精卫[7](7.md)([wz_7_265](wz_7_265.md))的汉奸党是异党,因为它和抗日党派在政治上没有丝毫共同之点,这样的党,就应该限制。国民党、共产党,在政治上是有共同之点的,这就是抗日。所以现在是如何集中全力反日防日和反汪防汪的问题,而不是集中全力反共防共的问题。口号只能是这样提。现在汪精卫有三个口号:反蒋、反共、亲日。汪精卫是国共两党和全国人民的共同敌人。共产党却不是国民党的敌人,国民党也不是共产党的敌人,不应该互相反对,互相“限制”,而应该互相团结,互相协助。我们的口号一定要和汪精卫的口号有区别,一定要和汪精卫的口号对立起来,而决不能和他相混同。他要反蒋,我们就要拥蒋;他要反共,我们就要联共;他要亲日,我们就要抗日。凡是敌人反对的,我们就要拥护;凡是敌人拥护的,我们就要反对。现在许多人的文章上常常有一句话,说是“无使亲痛仇快”。这句话出于东汉时刘秀的一位将军叫朱浮的写给渔阳太守彭宠的一封信,那信上说:“凡举事无为亲厚者所痛,而为见仇者所快。”朱浮这句话提出了一个明确的政治原则,我们千万不可忘记。 - 先生们的问题表中还问到共产党对待所谓磨擦的态度。我可以率直地告诉你们,我们根本反对抗日党派之间那种互相对消力量的磨擦。但是,任何方面的横逆如果一定要来,如果欺人太甚,如果实行压迫,那末,共产党就必须用严正的态度对待之。这态度就是:人不犯我,我不犯人;人若犯我,我必犯人。但我们是站在严格的自卫立场上的,任何共产党员不许超过自卫原则。 - 问:华北的磨擦问题怎样? - 答:那里的张荫梧、秦启荣[8](8.md)([wz_8_266](wz_8_266.md)),是两位磨擦专家。张荫梧在河北,秦启荣在山东,简直是无法无天,和汉奸的行为很少区别。他们打敌人的时候少,打八路军的时候多。有许多铁的证据,如像张荫梧给其部下进攻八路军的命令等,我们已送给蒋委员长了。 - 问:新四军方面有无磨擦? - 答:也是有的,平江惨案[9](9.md)([wz_9_267](wz_9_267.md))就是惊动全国的大事件。 - 问:有些人说,统一战线是重要的,但是按照统一,边区政府就应该取消。关于这,先生以为如何? - 答:各种胡言乱语到处都有,如所谓取消边区,即是一例。陕甘宁边区是民主的抗日根据地,是全国政治上最进步的区域,取消的理由何在?何况边区是蒋委员长早已承认了的,国民政府行政院也早在民国二十六年冬天就正式通过了。中国确实需要统一,但是应该统一于抗战,统一于团结,统一于进步。如果向相反的方面统一,那中国就会亡国。 - 问:由于对于统一的了解不同,国共是否有分裂的可能? - 答:如果只说到可能性的话,那末,团结和分裂两种可能性都有,要看国共两党的态度如何,尤其要看全国人民的态度如何来决定。我们共产党方面,关于合作的方针,早经讲过,我们不但希望长期合作,而且努力争取这种合作。听说蒋委员长在国民党五中全会中也说过,国内问题不能用武力来解决。大敌当前,国共两党又都有了过去的经验,大家一定要长期合作,一定要避免分裂。但是要给长期合作找到政治保证,分裂的可能性才能彻底避免,这就是坚持抗战到底和实行民主政治。如果能这样做,那末,就能继续团结而避免分裂,这是要靠两党和全国人民共同努力的,也是一定要这样努力的。“坚持抗战、反对投降”,“坚持团结、反对分裂”,“坚持进步、反对倒退”,这是我们党在今年的《七七宣言》里提出来的三大政治口号。我们认为只有这样做,中国才能避免亡国,并把敌人打出去;除此没有第二条路好走。 - [1](1.md)([wz_1_263](wz_1_263.md))中央社是国民党的中央通讯社。《扫荡报》是国民党政府军事系统的报纸。《新民报》是代表民族资产阶级的一种报纸。 - [2](2.md)([wz_2_263](wz_2_263.md))《新中华报》的前身是中华苏维埃共和国中央政府机关报《红色中华》,一九三七年一月二十九日改为此名,在延安出版。同年九月九日改为陕甘宁边区政府的机关报。一九三九年二月七日起改组为中国共产党中央委员会的机关报。一九四一年五月十五日终刊。 - [3](3.md)([wz_3_264](wz_3_264.md))指国民党统治区。抗日战争时期,人们习惯称未被日本侵略军占领而在国民党统治下的中国西南部和西北部的广大地区为“大后方”。 - [4](4.md)([wz_4_264](wz_4_264.md))孙中山在《建国大纲》中,曾经将“建国”程序划分为“军政”、“训政”、“宪政”三个时期。以蒋介石为首的国民党反动派,长期利用“军政”、“训政”的说法,作为实行反革命专政和剥夺人民一切自由权利的借口。 - [5](5.md)([wz_5_264](wz_5_264.md))一九二四年十月,直系军阀在第二次直奉战争中失败,它控制的北京中央政权垮台,冯玉祥等北方实力派电请孙中山入京,共商国是。孙中山于十一月十三日应邀北上。在离开广州前,孙中山发表《北上宣言》,重申反对帝国主义和军阀的主张,号召召集国民会议。这个宣言受到全国人民的欢迎。 - [6](6.md)([wz_6_265](wz_6_265.md))见本卷《必须制裁反动派》注〔5〕。 - [7](7.md)([wz_7_265](wz_7_265.md))见本书第一卷《论反对日本帝国主义的策略》注〔31〕。 - [8](8.md)([wz_8_266](wz_8_266.md))见本卷《团结一切抗日力量,反对反共顽固派》注〔5〕和注〔6〕。 - [9](9.md)([wz_9_267](wz_9_267.md))见本卷《必须制裁反动派》注〔1〕。 ## 苏联利益和人类利益的一致 - (一九三九年九月二十八日) - 当着伟大的十月社会主义革命二十二周年纪念快要到来的时候,中苏文化协会要我写一篇文章。我想根据我的观察,说明几个和苏联和中国都有关系的问题。因为这些问题目前正在中国广大人民中间议论着,似乎还没有得到确定的结论。我想乘此时机,对这些问题提出一点意见,贡献给关心欧洲大战和中苏关系的人们,作为参考,或者不是无益的。 - 有些人说:苏联利于爆发世界大战,而不要求世界和平的继续;这次大战的爆发,就是由苏联不同英法订立互助条约而同德国订立互不侵犯条约[1](1.md)([wz_1_269](wz_1_269.md))所促成的。这种意见,我以为是不正确的。因为在过去很长的时期中,苏联的对外政策是一贯的和平政策,这种和平政策就是以苏联的利益和世界人类大多数的利益互相联系着的。在过去,苏联不但为了自己建设社会主义需要和平,需要巩固苏联和世界各国间的和平关系,不使发生反苏战争;而且需要制止各法西斯国家的侵略,制止各所谓民主国家挑拨战争的行为,需要尽量地延缓帝国主义世界大战的爆发,争取世界范围内的和平。多年以来,苏联对于世界的和平事业,尽了很大的努力。例如,它加入了国际联盟[2](2.md)([wz_2_269](wz_2_269.md)),同法国同捷克都订立了互助协定[3](3.md)([wz_3_269](wz_3_269.md)),竭力想同英国及一切愿意和平的国家订立保障安全的条约。当德意联合侵略西班牙,而英美法采取名义上“不干涉”实际上放任德意侵略的政策的时候,苏联就积极地援助西班牙政府军反抗德意,而反对英美法的“不干涉”政策。当日本侵略中国,英美法采取同样的“不干涉”政策的时候,苏联就不但同中国订立了互不侵犯条约,而且积极地援助了中国的抗日。当英法两国牺牲奥国和捷克纵容希特勒侵略的时候,苏联就竭力揭穿慕尼黑政策[4](4.md)([wz_4_270](wz_4_270.md))的黑幕,向英法提议制止侵略的进一步的发展。当今年春夏波兰问题紧张、世界大战一触即发的时候,不管张伯伦、达拉第[5](5.md)([wz_5_270](wz_5_270.md))如何没有诚意,苏联还是同英法进行了四个多月的谈判,企图订立一个英法苏互助条约,制止大战的爆发。无如这一切,都被英法政府的帝国主义政策,纵容战争、挑拨战争、扩大战争的政策所障碍,世界和平事业就遭受了最后的挫折,帝国主义的世界大战终于爆发了。英、美、法各国政府,并无诚意制止大战的爆发;相反,它们是促成了大战的爆发。因为它们拒绝同苏联妥协,拒绝同苏联订立真正有效的建立在平等互惠基础之上的互助条约,这就证明它们只愿意战争,不愿意和平。谁也知道,在现在这个世界上,拒绝了苏联,就是拒绝了和平。这一点,就是英国的路易乔治,这个资产阶级的代表人物,也是知道的[6](6.md)([wz_6_270](wz_6_270.md))。在这种状态下,在这个时候,德国愿意停止反苏,放弃《防共协定》[7](7.md)([wz_7_270](wz_7_270.md)),承认苏联边疆的不可侵犯,苏德互不侵犯条约就订立了。英美法的计划是:推动德国进攻苏联,它们自己“坐山观虎斗”,让苏、德打得精疲力竭之后,它们出来收拾时局。这种阴谋,被苏德互不侵犯条约击破了。国人不去注意此种阴谋,不去注意英法帝国主义的纵容战争、挑拨战争和促进世界大战爆发的阴谋,实在是上了这些阴谋家的甜蜜宣传的当。这些阴谋家,在西班牙问题上,在中国问题上,在奥地利和捷克的问题上,不但并无丝毫制止侵略的意思,而且相反,纵容侵略,挑拨战争,使人为鹬蚌,己为渔人,美其名曰“不干涉”,实则是“坐山观虎斗”。世界上多少人被张伯伦及其伙伴的甜蜜演说所蒙蔽,而不知道他们笑里藏刀的可怕,而不知道在张伯伦、达拉第决心拒绝苏联,决心进行帝国主义战争的时候,苏德才订立了互不侵犯条约;现在这些人应该觉悟过来了。苏联这样地维持世界和平到最后的一刻,这就是苏联的利益和人类大多数的利益互相一致的表现。这就是我要说的第一个问题。 - 有些人说:第二次帝国主义世界大战既然爆发了,苏联或者会参加战争的一方,就是说,苏联红军似乎即将参加德国帝国主义的战线。这种意见,我以为是不正确的。现在爆发的战争,无论在英法方面,或德国方面,都是非正义的、掠夺的、帝国主义的战争。世界各国的共产党,世界各国的人民,都应该起来反对这种战争,都应该揭穿战争双方的帝国主义性质,即仅仅有害于世界人民而丝毫也不利于世界人民的这种性质,都应该揭穿社会民主党拥护帝国主义战争背叛无产阶级利益的罪恶的行为。苏联是社会主义的国家,是共产党当权的国家,它对于战争的态度必然是鲜明的两种态度:(1)坚决地不参加非正义的、掠夺的、帝国主义的战争,对于战争的双方,严守中立。因此,苏联红军决不会无原则地参加帝国主义战线。(2)积极地援助正义的、非掠夺的、谋解放的战争。例如,十三年以前,援助中国人民的北伐战争;一年以前,援助西班牙人民的反抗德意的战争;两年以来,援助中国人民的抗日战争;几个月以来,援助蒙古人民的抗日战争;以及还必然地会援助将来其他国家其他民族中间可能发生的人民解放的战争和民族解放的战争,还必然地会援助有利于保卫和平的战争。关于这一点,苏联过去二十二年的历史已经证明了,今后的历史还将继续证明。有些人把苏联根据苏德商务协定同德国做生意一件事,看作是苏联参加德国战线的行动,这种意见也是不正确的,这是把通商和参战混为一谈的缘故。不但不能把通商和参战混为一谈,也不能把通商和援助混为一谈。例如在西班牙战争中,苏联是同德、意两国通商的,但世人不说苏联援助德意侵略西班牙,而说苏联援助西班牙反抗德意的侵略,这是因为苏联确实地援助了西班牙的缘故。又如在中日战争中,苏联也是同日本通商的,世人也不说苏联援助日本侵略中国,而说它援助中国反抗日本的侵略,这是因为苏联确实地援助了中国的缘故。现在世界大战的双方都和苏联有通商关系,这种事实,对于双方都说不到援助,更说不到参战。除非战争的性质有了变化,某一国或某几国的战争经过一定的必要的变化之后,对于苏联和世界人民有利的时候,那时才有援助或参战的可能;否则是没有这种可能的。至于依据交战各国对苏联的态度是亲苏或反苏的分别,使苏联对它们的通商不得不有多有少,有厚有薄,这是各交战国自己态度的问题,不是苏联的问题。但是即使某一国家或某些国家采取了反苏态度,只要它们还愿维持外交关系,订立通商条约,而不向苏联宣战,例如八月二十三日以前的德国那样,苏联也不会同它们断绝通商关系的。这种通商关系,不是援助,更不是参战,这是应该认识清楚的。这就是我要说的第二个问题。 - 国内许多的人,对于苏联进兵波兰[8](8.md)([wz_8_273](wz_8_273.md))的问题,糊涂起来了。波兰问题,应该分为德国方面,英法方面,波兰政府方面,波兰人民方面和苏联方面几个方面来看。在德国方面,它是为了掠夺波兰人民而进行战争的,是为了击破英法帝国主义战线的一翼而进行战争的。这种战争的性质,是帝国主义的,是不能同情的,是应当反对的。在英法方面,是把波兰作为英法财政资本掠夺的对象之一,是为了在世界范围内拒绝德国帝国主义重分它们的赃物而去利用波兰的,是把波兰当做自己帝国主义战线的一翼来看待的,所以英法的战争是帝国主义战争,英法的所谓援助波兰不过是同德国争夺对波兰的统治权,同样是不能同情的,是应当反对的。在波兰政府方面,它是一个法西斯政府,是波兰地主资产阶级的反动政府,它残酷地剥削工农,压迫波兰的民主主义者;它又是一个大波兰主义的政府,因为它在波兰民族以外的许多少数民族中,即在乌克兰人、白俄罗斯人、犹太人、日耳曼人、立陶宛人等等一千余万人口的非波兰民族中,施行残酷的民族压迫,它本身是一个帝国主义的政府。在这次战争中,波兰反动政府甘愿驱使波兰人民充当英法财政资本的炮灰,甘愿充当国际财政资本反动战线的一个组成部分。二十年来,波兰政府一贯地反对苏联,在英法苏谈判中,坚决地拒绝苏联军队的援助。而这个政府又是一个十分无能的政府,一百五十万以上的大军,不堪一击,仅仅在两个星期的时间中,就葬送了自己的国家,使波兰人民遭受德国帝国主义的蹂躏。所有这一切,都是波兰政府的滔天罪恶,如果我们同情这样的政府,那是不对的。在波兰人民方面,他们是牺牲者,他们应该起来反对德国法西斯的压迫,反对自己的反动的地主资产阶级,建立独立的自由的波兰民主国家。毫无疑义的,我们的同情应该寄在波兰人民方面。在苏联方面,则是采取了完全正义的行动。当时摆在苏联面前的问题有下面的两个。第一个问题是:让整个波兰处在德国帝国主义的统治下面呢,还是让东部波兰少数民族得到解放呢?在这个问题上,苏联选择了第二条路。在那白俄罗斯民族和乌克兰民族居住的一大块土地,还是在一九一八年订立布列斯特条约[9](9.md)([wz_9_274](wz_9_274.md))的时候,就被当时的德国帝国主义从幼年的苏联手里强迫地割去,而后来又被凡尔赛条约强迫地放到波兰反动政府的统治下面。苏联现在不过是把过去失掉的土地收回来,把被压迫的白俄罗斯民族和乌克兰民族解放出来,并使免受德国的压迫。这几天的电讯,指明这些少数民族是怎样地箪食壶浆以迎红军,把红军看做他们的救星;而在德军占领的西部波兰地方,法军占领的西部德国地方,则丝毫也没有这种消息。这就是表明,苏联的战争是正义的、非掠夺的、谋解放的战争,是援助弱小民族解放、援助人民解放的战争。而德国的战争,英法的战争,则都是非正义的、掠夺的、帝国主义的战争,是压迫他国民族、压迫他国人民的战争。除此以外,在苏联面前,还有第二个问题,这就是张伯伦企图继续他的反对苏联的老政策。张伯伦的政策是:一方面大举封锁德国的西面,压迫德国的西部;一方面企图联合美国,收买意大利,收买日本,收买北欧各国,使它们站在自己方面,以孤立德国;再一方面,则拿波兰,甚至还准备拿匈牙利,拿罗马尼亚,作为礼物,以引诱德国。总之,用威迫利诱种种办法,推动德国放弃苏德互不侵犯条约,使之倒转枪口,进攻苏联。这种阴谋,不但过去和现在是存在着,而且将来也还会继续的。苏联大军的进入波兰东部,是为了收复自己国土,解放弱小民族,同时也是制止德国侵略势力向东扩展,击破张伯伦阴谋的一个具体步骤。从这几天的消息看来,苏联的这一方针,是极大地成功了。这就是苏联的利益和世界人类大多数的利益互相一致,和波兰反动统治下被压迫人民的利益互相一致的具体表现。这就是我要说的第三个问题。 - 苏德互不侵犯条约订立之后的整个形势,大大地打击了日本,援助了中国,加强了中国抗战派的地位,打击了投降派。中国人民,对于这个协定表示欢迎,是很正确的。但当诺蒙坎停战协定[10](10.md)([wz_10_275](wz_10_275.md))订立之后,英、美通讯社纷传日苏互不侵犯协定行将订立的消息,中国人民中间就发生一种忧虑,有些人认为苏联或者将不援助中国了。这种观察,我以为是不正确的。诺蒙坎停战协定的性质,和过去张高峰停战协定[11](11.md)([wz_11_275](wz_11_275.md))是一样的,就是说,在日本屈膝之下,日本军阀承认了苏蒙边疆的不可侵犯。这种停战协定,将使苏联增加对于中国援助的可能,而不是减少其援助。至于所谓日苏互不侵犯条约,在过去多年之前,苏联就要求日本签订,日本始终拒绝。现在日本统治阶级内部的一派,要求苏联订立这种条约,而苏联是否愿意订立,须看这个条约是否合乎苏联利益和世界人类大多数利益这一个基本原则而定。具体地说,就是要看这个条约是否不和中国民族解放战争的利益相冲突。据我看,根据斯大林今年三月十日在苏联共产党第十八次代表大会上的报告,根据莫洛托夫今年五月三十日在苏联最高议会上的演说,苏联是不会变更这个基本原则的。即使日苏互不侵犯条约有订立的可能,苏联也决不会在条约中限制自己援助中国的行动。苏联的利益和中国民族解放的利益决不会互相冲突,而将是永久互相一致。这一点,我认为绝对没有疑义。那些有反苏成见的人,借着诺蒙坎停战协定的订立和日苏互不侵犯条约的传闻,掀风鼓浪,挑拨中苏两大民族间的感情。这种情形,在英美法的阴谋家中,在中国的投降派中,都是存在的,这是一种严重的危险,应该彻底地揭穿其黑幕。中国的外交政策,很明显的,应该是抗日的外交政策。这个政策以自力更生为主,同时不放弃一切可能争取的外援。而所谓外援,在帝国主义世界大战爆发的情况之下,主要地是在下列的三方面:(1)社会主义的苏联;(2)世界各资本主义国家内的人民;(3)世界各殖民地、半殖民地的被压迫民族。只有这些才是可靠的援助者。此外的所谓外援,即使还有可能,也只能看作是部分的和暂时的。当然,这些部分的暂时的外援,也是应该争取的,但决不可过于依赖,不可看作可靠的援助。对于帝国主义战争的交战各国,中国应该严守中立,不参加任何的一方。那种主张中国应该参加英法帝国主义战线的意见,乃是投降派的意见,不利于抗日和不利于中华民族独立解放的意见,是应该根本拒绝的。这就是我要说的第四个问题。 - 上述的这些问题,都是当前国人议论纷纷的问题。国人注意国际问题的研究,注意帝国主义世界大战和中国抗日战争的关系,注意苏联和中国的关系,而其目的是为了中国抗日的胜利,这是很好的现象。我现在提出我对于上述各问题的一些基本观点,是否有当,希望读者不吝指教。 - [1](1.md)([wz_1_269](wz_1_269.md))见本卷《关于国际新形势对新华日报记者的谈话》注〔2〕。 - [2](2.md)([wz_2_269](wz_2_269.md))国际联盟是第一次世界大战以后,英、法、日等国为了协商宰割世界和暂时调节相互之间的矛盾而成立的国际组织。一九三一年日本占领中国东北以后,为了扩大侵略行动的便利,于一九三三年宣告退出国联;一九三三年德国法西斯党执政,为了准备侵略战争的便利,也退出了国联。就在法西斯侵略战争的威胁日益扩大的时期,苏联为了使国联变成揭露侵略者、争取世界和平的场所,于一九三四年加入了国际联盟。 - [3](3.md)([wz_3_269](wz_3_269.md))苏法和苏捷两个互助条约都是在一九三五年五月订立的。 - [4](4.md)([wz_4_270](wz_4_270.md))见本卷《反对投降活动》注〔5〕。 - [5](5.md)([wz_5_270](wz_5_270.md))见本卷《关于国际新形势对新华日报记者的谈话》注〔3〕。 - [6](6.md)([wz_6_270](wz_6_270.md))路易乔治,即劳合·乔治,英国资产阶级自由党领袖之一。一九三八年冬,英法政府准备同德意法西斯政府举行协商,十一月九日劳合·乔治在议会中说:拒绝苏联参加协商,就不可能取得和平。 - [7](7.md)([wz_7_270](wz_7_270.md))见本卷《关于国际新形势对新华日报记者的谈话》注〔5〕。 - [8](8.md)([wz_8_273](wz_8_273.md))一九三九年九月一日,德国出兵侵入波兰,占领了波兰的大部分土地。十七日波兰政府逃亡国外。苏联为了防止德国法西斯的东侵,于九月十七日进兵波兰东部。 - [9](9.md)([wz_9_274](wz_9_274.md))见本书第一卷《中国革命战争的战略问题》注〔23〕。 - [10](10.md)([wz_10_275](wz_10_275.md))自一九三九年五月开始,日“满”(伪满洲国)军在“满”蒙边境诺蒙坎地方,向苏联和蒙古人民共和国的军队进攻。在苏蒙军的自卫反击下,日“满”军遭到惨败,向苏联要求停战。九月十六日,诺蒙坎停战协定在莫斯科签订,主要内容是:一、双方立即停战;二、苏蒙和日“满”双方各派代表二人组织委员会,以勘定“满”蒙发生冲突地带的界线。 - [11](11.md)([wz_11_275](wz_11_275.md))张高峰,即张鼓峰。一九三八年七月底八月初,日军在中国、苏联交界处的张鼓峰地方,向苏军挑衅。在苏军的有力回击下,日军失败求和。八月十日,苏日在莫斯科订立张鼓峰停战协定,规定双方立即停战,发生冲突地带的双方界线的最后标定,由苏联代表二人、日“满”代表二人组织混合委员会调查处理。 ## 《共产党人》发刊词 - (一九三九年十月四日) - 中央很早就计划出版一个党内的刊物,现在算是实现了。为了建设一个全国范围的、广大群众性的、思想上政治上组织上完全巩固的布尔什维克化的中国共产党,这样一个刊物是必要的。在当前的时机中,这种必要性更加明显。当前时机中的特点,一方面,是抗日民族统一战线中的投降危险、分裂危险和倒退危险日益发展着;又一方面,是我们党已经走出了狭隘的圈子,变成了全国性的大党。而党的任务是动员群众克服投降危险、分裂危险和倒退危险,并准备对付可能的突然事变,使党和革命不在可能的突然事变中,遭受出乎意料的损失。在这种时机,这样一个党内刊物的出版,实在是十分必要的了。 - 这个党内刊物定名为《共产党人》。它的任务是什么呢?它将写些什么东西呢?它和别的党报有些什么不同呢? - 它的任务就是:帮助建设一个全国范围的、广大群众性的、思想上政治上组织上完全巩固的布尔什维克化的中国共产党。为了中国革命的胜利,迫切地需要建设这样一个党,建设这样一个党的主观客观条件也已经大体具备,这件伟大的工程也正在进行之中。帮助进行这件伟大的工程,不是一般党报所能胜任的,必须有专门的党报,这就是《共产党人》出版的原因。 - 在某种程度上说来,我们的党已经是一个全国性的党,也已经是一个群众性的党;而且就其领导骨干说来,就其党员的某些成分说来,就其总路线说来,就其革命工作说来,也已经是一个思想上、政治上、组织上都巩固的和布尔什维克化的党。 - 那末,现在提出新的任务的理由何在呢? - 理由就在:我们现在有大批的新党员所形成的很多的新组织,这些新组织还不能说是广大群众性的,还不是思想上、政治上、组织上都巩固的,还不是布尔什维克化的。同时,对于老党员,也发生了提高水平的问题,对于老组织,也发生了在思想上、政治上、组织上进一步巩固和进一步布尔什维克化的问题。党所处的环境,党所负的任务,现在和过去国内革命战争时期有很大的不同,现在的环境是复杂得多,现在的任务是艰巨得多了。 - 现在是民族统一战线的时期,我们同资产阶级建立了统一战线;现在是抗日战争的时期,我们党的武装在前线上配合友军同敌人进行残酷的战争;现在是我们党发展成为全国性的大党的时期,党已经不是从前的样子了。如果把这些情况联系起来看,就懂得我们提出“建设一个全国范围的、广大群众性的、思想上政治上组织上完全巩固的布尔什维克化的中国共产党”,是怎样一个光荣而又严重的任务了。 - 我们现在要建设这样一个党,究竟应该怎样进行呢?解决这个问题,是同我们党的历史,是同我们党的十八年斗争史,不能分离的。 - 我们党的历史,从一九二一年第一次全国代表大会那个时候起,到现在,已经整整十八年了。十八年中,党经历了许多伟大的斗争。党员、党的干部、党的组织,在这些伟大斗争中,锻炼了自己。他们经历过伟大的革命胜利,也经历过严重的革命失败。同资产阶级建立过民族统一战线,又由于这种统一战线的破裂,同大资产阶级及其同盟者进行过严重的武装斗争。最近三年,则又处于同资产阶级建立民族统一战线的时期中。中国革命和中国共产党的发展道路,是在这样同中国资产阶级的复杂关联中走过的。这是一个历史的特点,殖民地半殖民地革命过程中的特点,而为任何资本主义国家的革命史中所没有的。再则,由于中国是半殖民地半封建的国家,政治、经济、文化各方面发展不平衡的国家,半封建经济占优势而又土地广大的国家,这就不但规定了中国现阶段革命的性质是资产阶级民主革命的性质,革命的主要对象是帝国主义和封建主义,基本的革命的动力是无产阶级、农民阶级和城市小资产阶级,而在一定的时期中,一定的程度上,还有民族资产阶级的参加,并且规定了中国革命斗争的主要形式是武装斗争。我们党的历史,可以说就是武装斗争的历史。斯大林同志说过:“在中国,是武装的革命反对武装的反革命。这是中国革命的特点之一,也是中国革命的优点之一。”[1](1.md)([wz_1_280](wz_1_280.md))这是说得非常之对的。这一特点,这一半殖民地的中国的特点,也是各个资本主义国家的共产党领导的革命史中所没有的,或是同那些国家不相同的。这样:(一)无产阶级同资产阶级建立或被迫分裂革命的民族统一战线,(二)主要的革命形式是武装斗争,——就成了中国资产阶级民主革命过程中的两个基本特点。这里,我们没有把党同农民阶级和党同城市小资产阶级的关系作为基本特点,这是因为:第一,这种关系,世界各国的共产党原则上都是一样的;第二,在中国,只要一提到武装斗争,实质上即是农民战争,党同农民战争的密切关系即是党同农民的关系。 - 由于这两个基本特点,恰是由于这些基本特点,我们党的建设过程,我们党的布尔什维克化的过程,就处在特殊的情况中。党的失败和胜利,党的后退和前进,党的缩小和扩大,党的发展和巩固,都不能不联系于党同资产阶级的关系和党同武装斗争的关系。当我们党的政治路线是正确地处理同资产阶级建立统一战线或被迫着分裂统一战线的问题时,我们党的发展、巩固和布尔什维克化就前进一步;而如果是不正确地处理同资产阶级的关系时,我们党的发展、巩固和布尔什维克化就会要后退一步。同样,当我们党正确地处理革命武装斗争问题时,我们党的发展、巩固和布尔什维克化就前进一步;而如果是不正确地处理这个问题时,那末,我们党的发展、巩固和布尔什维克化也就会要后退一步。十八年来,党的建设过程,党的布尔什维克化的过程,是这样同党的政治路线密切地联系着,是这样同党对于统一战线问题、武装斗争问题之正确处理或不正确处理密切地联系着的。这一论断,很明显地,已经被十八年党的历史所证明了。倒转来说,党更加布尔什维克化,党就能、党也才能更正确地处理党的政治路线,更正确地处理关于统一战线问题和武装斗争问题。这一论断,也是很明显地被十八年来的党的历史所证明了。 - 所以,统一战线问题,武装斗争问题,党的建设问题,是我们党在中国革命中的三个基本问题。正确地理解了这三个问题及其相互关系,就等于正确地领导了全部中国革命。而在十八年党的历史中,凭借我们丰富的经验,失败和成功、后退和前进、缩小和发展的深刻的和丰富的经验,我们已经能够对这三个问题做出正确的结论来了。就是说,我们已经能够正确地处理统一战线问题,又正确地处理武装斗争问题,又正确地处理党的建设问题。也就是说,十八年的经验,已使我们懂得:统一战线,武装斗争,党的建设,是中国共产党在中国革命中战胜敌人的三个法宝,三个主要的法宝。这是中国共产党的伟大成绩,也是中国革命的伟大成绩。 - 在这里,让我们对于这三个法宝,三个问题,分别地大略地说一下吧。 - 十八年中,中国无产阶级同中国资产阶级和其他阶级的统一战线,是在三种不同的情况、三个不同的阶段中间发展着的,这就是一九二四年至一九二七年第一次大革命的阶段,一九二七年至一九三七年土地革命战争的阶段和今天的抗日战争的阶段。三个阶段的历史,证明了下列的规律:(一)由于中国最大的压迫是民族压迫,在一定的时期中,一定的程度上,中国民族资产阶级是能够参加反帝国主义和反封建军阀的斗争的。因此,无产阶级在这种一定的时期内,应该同民族资产阶级建立统一战线,并尽可能地保持之。(二)又由于中国民族资产阶级在经济上、政治上的软弱性,在另一种历史环境下,它就会动摇变节。因此,中国革命统一战线的内容不能始终一致,而是要发生变化的。在某一时期有民族资产阶级参加在内,而在另一时期则民族资产阶级并不参加在内。(三)中国的带买办性的大资产阶级,是直接为帝国主义服务并为它们所豢养的阶级。因此,中国的带买办性的大资产阶级历来都是革命的对象。但是,由于中国的带买办性的大资产阶级的各个集团是以不同的帝国主义为背景的,在各个帝国主义间的矛盾尖锐化的时候,在革命的锋芒主要地是反对某一个帝国主义的时候,属于别的帝国主义系统的大资产阶级集团也可能在一定程度上和一定时期内参加反对某一个帝国主义的斗争。在这种一定的时期内,中国无产阶级为了削弱敌人和加强自己的后备力量,可以同这样的大资产阶级集团建立可能的统一战线,并在有利于革命的一定条件下尽可能地保持之。(四)在买办性的大资产阶级参加统一战线并和无产阶级一道向共同敌人进行斗争的时候,它仍然是很反动的,它坚决地反对无产阶级及其政党在思想上、政治上、组织上的发展,而要加以限制,而要采取欺骗、诱惑、“溶解”和打击等等破坏政策,并以这些政策作为它投降敌人和分裂统一战线的准备。(五)无产阶级的坚固的同盟者是农民。(六)城市小资产阶级也是可靠的同盟者。这些规律的正确性,不但在第一次大革命时期和土地革命时期证明了,而且在目前的抗日战争中也在证明着。因此,无产阶级的政党在同资产阶级(尤其是大资产阶级)组织统一战线的问题上,必须实行坚决的、严肃的两条战线斗争。一方面,要反对忽视资产阶级在一定时期中一定程度上参加革命斗争的可能性的错误。这种错误,把中国的资产阶级和资本主义国家的资产阶级看做一样,因而忽视同资产阶级建立统一战线并尽可能保持这个统一战线的政策,这就是“左”倾关门主义。另一方面,则要反对把无产阶级和资产阶级的纲领、政策、思想、实践等等看做一样的东西,忽视它们之间的原则差别的错误。这种错误,忽视资产阶级(尤其是大资产阶级)不但在极力影响小资产阶级和农民,而且还在极力影响无产阶级和共产党,力求消灭无产阶级和共产党在思想上、政治上、组织上的独立性,力求把无产阶级和共产党变成资产阶级及其政党的尾巴,力求使革命果实归于资产阶级的一群一党的事实;忽视资产阶级(尤其是大资产阶级)一到革命同他们一群一党的私利相冲突时,他们就实行叛变革命的事实。如果忽视了这一方面,这就是右倾机会主义。过去陈独秀右倾机会主义[2](2.md)([wz_2_284](wz_2_284.md))的特点,就是引导无产阶级适合资产阶级一群一党的私利,这也就是第一次大革命失败的主观原因。中国资产阶级在资产阶级民主革命中的这种二重性,对于中国共产党的政治路线和党的建设的影响是非常之大的,不了解中国资产阶级的这种二重性,就不能了解中国共产党的政治路线和党的建设。中国共产党的政治路线的重要一部分,就是同资产阶级联合又同它斗争的政治路线。中国共产党的党的建设的重要一部分,就是在同资产阶级联合又同它斗争的中间发展起来和锻炼出来的。这里所谓联合,就是同资产阶级的统一战线。所谓斗争,在同资产阶级联合时,就是在思想上、政治上、组织上的“和平”的“不流血”的斗争;而在被迫着同资产阶级分裂时,就转变为武装斗争。如果我们党不知道在一定时期中同资产阶级联合,党就不能前进,革命就不能发展;如果我们党不知道在联合资产阶级时又同资产阶级进行坚决的、严肃的“和平”斗争,党在思想上、政治上、组织上就会瓦解,革命就会失败;又如果我们党在被迫着同资产阶级分裂时不同资产阶级进行坚决的、严肃的武装斗争,同样党也就会瓦解,革命也就会失败。所有这些,都是在过去十八年的历史中证明了的。 - 中国共产党的武装斗争,就是在无产阶级领导之下的农民战争。它的历史,也可以分为三个阶段。第一阶段,是参加北伐战争。这时,我们党虽已开始懂得武装斗争的重要性,但还没有彻底了解其重要性,还没有了解武装斗争是中国革命的主要斗争形式。第二阶段,是土地革命战争。这时,我们党已经建立了独立的武装队伍,已经学会了独立的战争艺术,已经建立了人民政权和根据地。我们党已经能够把武装斗争这个主要斗争形式同其他许多的必要的斗争形式直接或间接地配合起来,就是说,把武装斗争同工人的斗争,同农民的斗争(这是主要的),同青年的、妇女的、一切人民的斗争,同政权的斗争,同经济战线上的斗争,锄奸战线上的斗争,思想战线上的斗争,等等斗争形式,在全国范围内或者直接地或者间接地配合起来。而这种武装斗争,就是在无产阶级领导之下的农民土地革命斗争。第三个阶段,就是现在的抗日战争阶段。在这个阶段中,我们能够运用过去第一阶段中尤其是第二阶段中的武装斗争的经验,能够运用武装斗争形式和其他各种必要的斗争形式互相配合的经验。这种武装斗争的总概念,在目前就是游击战争[3](3.md)([wz_3_285](wz_3_285.md))。游击战争是什么呢?它就是在落后的国家中,在半殖民地的大国中,在长时期内,人民武装队伍为了战胜武装的敌人、创造自己的阵地所必须依靠的因而也是最好的斗争形式。到目前为止,我们党的政治路线和党的建设,是密切地联系于这一斗争形式的。离开了武装斗争,离开了游击战争,就不能了解我们的政治路线,也就不能了解我们的党的建设。我们的政治路线的重要一部分就是武装斗争。十八年来,我们党是逐步学会了并坚持了武装斗争。我们懂得,在中国,离开了武装斗争,就没有无产阶级的地位,就没有人民的地位,就没有共产党的地位,就没有革命的胜利。十八年来,我们党的发展、巩固和布尔什维克化,是在革命战争中进行的,没有武装斗争,就不会有今天的共产党。这个拿血换来的经验,全党同志都不要忘记。 - 党的建设的过程,党的发展、巩固和布尔什维克化的过程,也同样是有三个阶段的特点的。第一阶段是党的幼年时期。在这个阶段的初期和中期,党的路线是正确的,党员群众和党的干部的革命积极性是非常之高的,因此获得了第一次大革命的胜利。然而这时的党终究还是幼年的党,是在统一战线、武装斗争和党的建设三个基本问题上都没有经验的党,是对于中国的历史状况和社会状况、中国革命的特点、中国革命的规律都懂得不多的党,是对于马克思列宁主义的理论和中国革命的实践还没有完整的、统一的了解的党。因此,党的领导机关中占统治地位的成分,在这一阶段的末期,在这一阶段的紧要关头中,没有能够领导全党巩固革命的胜利,受了资产阶级的欺骗,而使革命遭到失败。在这一阶段中,党的组织是发展了,但是没有巩固,没有能够使党员、党的干部在思想上、政治上坚定起来。新党员非常之多,但是没有给予必要的马克思列宁主义的教育。工作经验也不少,但是不能够很好地总结起来。党内混入了大批的投机分子,但是没有清洗出去。党处于敌人和同盟者的阴谋诡计的包围中,但是没有警觉性。党内涌出了很多的活动分子,但是没有来得及造成党的中坚骨干。党的手里有了一批革命武装,但是不能掌握住。所有这些情形,都是由于没有经验,缺乏深刻的革命认识,还不善于将马克思列宁主义的理论和中国革命的实践相结合。这就是党的建设的第一阶段。第二阶段,即土地革命战争的阶段。由于有了第一阶段的经验,由于对于中国的历史状况和社会状况、中国革命的特点、中国革命的规律的进一步的了解,由于我们的干部更多地领会了马克思列宁主义的理论,更多地学会了将马克思列宁主义的理论和中国革命的实践相结合,我们党就能够进行了胜利的十年土地革命斗争。资产阶级虽然叛变了,但是党能够紧紧地依靠着农民。党的组织不但重新发展了,而且得到了巩固。敌人虽然天天在暗害我们的党,但是党驱逐了暗害分子。大批干部重新在党内涌出,而且变成了党的中心骨干。党开辟了人民政权的道路,因此也就学会了治国安民的艺术。党创造了坚强的武装部队,因此也就学会了战争的艺术。所有这些,都是党的重大进步和重大成功。然而,一部分同志曾在这个伟大斗争中跌下了或跌下过机会主义的泥坑,这仍然是因为他们不去虚心领会过去的经验,对于中国的历史状况和社会状况、中国革命的特点、中国革命的规律不了解,对于马克思列宁主义的理论和中国革命的实践没有统一的理解而来的。因此,党的领导机关的一部分人,没有能够在这一整个阶段中掌握住正确的政治路线和组织路线。党和革命在一个时期遭受过李立三同志“左”倾机会主义[4](4.md)([wz_4_287](wz_4_287.md))的危害,而在另一个时期,又遭受过革命战争中的“左”倾机会主义和白区工作中的“左”倾机会主义的危害。只在到了遵义会议[5](5.md)([wz_5_287](wz_5_287.md))(一九三五年一月在贵州遵义召开的中央政治局会议)以后,党才彻底地走上了布尔什维克化的道路,奠定了后来战胜张国焘右倾机会主义[6](6.md)([wz_6_288](wz_6_288.md))和建立抗日民族统一战线的基础。这就是党的发展过程的第二个阶段。党的发展过程的第三个阶段,就是抗日民族统一战线的阶段。这个阶段,已经过去了三年,这三年的斗争,是有非常伟大的意义的。党凭借着过去两个革命阶段中的经验,凭借着党的组织力量和武装力量,凭借着党在全国人民中间的很高的政治信仰,凭借着党对于马克思列宁主义的理论和中国革命的实践之更加深入的更加统一的理解,就不但建立了抗日民族统一战线,而且进行了伟大的抗日战争。党的组织已经从狭小的圈子中走了出来,变成了全国性的大党。党的武装力量,也在同日寇的斗争中重新壮大起来和进一步坚强起来了。党在全国人民中的影响,更加扩大了。这些都是伟大的成功。然而,大批的新党员还没有受到教育,很多的新组织还没有巩固,他们同老党员和老组织之间,还存在着很大的区别。大批的新党员、新干部还没有足够的革命经验。他们对于中国的历史状况和社会状况、中国革命的特点、中国革命的规律还不懂得或懂得不多。他们对于马克思列宁主义的理论和中国革命的实践之完全的统一的理解,还相距很远。在过去发展党的组织的工作中,虽然中央着重地提出了“大胆发展而又不让一个坏分子侵入”的口号,但实际上是混进了许多投机分子和敌人的暗害分子。统一战线虽然建立了并坚持了三年之久,可是资产阶级特别是大资产阶级却时时刻刻在企图破坏我们的党,大资产阶级投降派和顽固派所指挥的严重的磨擦斗争在全国进行着,反共之声喧嚣不已。大资产阶级投降派和顽固派,并想以此作为投降日本帝国主义、分裂统一战线和拉了中国向后倒退的准备。大资产阶级在思想上企图“溶解”共产主义,在政治上、组织上企图取消共产党,取消边区,取消党的武装力量。在这种情况之下,我们的任务,无疑是克服这种投降、分裂和倒退的危险,尽可能地保持民族统一战线,保持国共合作,而争取继续抗日、继续团结和继续进步;同时,准备对付可能的突然事变,使党和革命不在可能的突然事变中遭受意外的损失。为达此目的,就要巩固党的组织,巩固党的武装力量,并动员全国人民,进行反投降、反分裂、反倒退的坚决的斗争。这种任务的完成,依靠全党的努力,依靠全体党员、党的干部、党的各地各级组织实行不屈不挠再接再厉的斗争。我们相信,有了十八年经验的中国共产党,在它的有经验的老党员、老干部和带着新鲜血液富有朝气的新党员、新干部相互协力的情况下,在它的经历过风浪的布尔什维克化的中央和地方组织相互协力的情况下,在它的坚强的武装力量和进步的人民群众相互协力的情况下,是可能达到这些目的的。 - 这就是我们党在十八个年头中的主要的经历和主要的问题。 - 十八年的经验告诉我们,统一战线和武装斗争,是战胜敌人的两个基本武器。统一战线,是实行武装斗争的统一战线。而党的组织,则是掌握统一战线和武装斗争这两个武器以实行对敌冲锋陷阵的英勇战士。这就是三者的相互关系。 - 我们今天要怎样建设我们的党?要怎样才能建设一个“全国范围的、广大群众性的、思想上政治上组织上完全巩固的布尔什维克化的中国共产党”?这个问题,考察一下我们党的历史,就会懂得;把党的建设问题同统一战线问题、同武装斗争问题联系起来看一下,把党的建设问题同联合资产阶级又同它作斗争的问题、同八路军新四军坚持抗日游击战争和建立抗日根据地的问题联系起来看一下,就会懂得。 - 根据马克思列宁主义的理论和中国革命的实践之统一的理解,集中十八年的经验和当前的新鲜经验传达到全党,使党铁一样地巩固起来,而避免历史上曾经犯过的错误——这就是我们的任务。 - [1](1.md)([wz_1_280](wz_1_280.md))见斯大林《论中国革命的前途》(《斯大林选集》上卷,人民出版社1979年版,第487页)。 - [2](2.md)([wz_2_284](wz_2_284.md))见本书第一卷《中国革命战争的战略问题》注〔4〕。 - [3](3.md)([wz_3_285](wz_3_285.md))毛泽东在这里说中国革命的武装斗争的总概念在目前就是游击战争,是总结了第二次国内革命战争和抗日战争初期的中国革命战争的经验。在第二次国内革命战争时期的长时间内,中国共产党所领导的武装斗争都是游击战争。这个时期的后一阶段,随着红军力量的成长,游击战曾经转变为带游击性的运动战(这种运动战,按照毛泽东的说法,是提高了的游击战争)。但在抗日战争期间,根据敌情的变化,这种带游击性的运动战又基本上转变为游击战争。在抗日战争的初期,党内犯右倾机会主义错误的同志轻视党所领导的游击战争,而把自己的希望寄托于国民党军队的作战。毛泽东曾在《抗日游击战争的战略问题》、《论持久战》和《战争和战略问题》等著作中,驳斥了这种观点,并在本文中把长时期内中国革命的武装斗争采取游击战争形式的经验,作了理论上的总结。中国共产党所领导的武装斗争,到了抗日战争的后期,特别是第三次国内革命战争时期,由于革命力量的新成长和敌情的新变化,战争的主要形式就由游击战争转变为正规战争;而在第三次国内革命战争的后期,更发展为使用大量重武器并包括攻坚战的大兵团作战了。 - [4](4.md)([wz_4_287](wz_4_287.md))见本书第一卷《中国革命战争的战略问题》注〔5〕。 - [5](5.md)([wz_5_287](wz_5_287.md))见本书第一卷《中国革命战争的战略问题》注〔7〕。 - [6](6.md)([wz_6_288](wz_6_288.md))参见本书第一卷《论反对日本帝国主义的策略》注〔23〕和注〔24〕。 ## 目前形势和党的任务[(1)]((1).md)([jz_0_291](jz_0_291.md)) - (一九三九年十月十日) - (一)帝国主义世界大战的爆发,是由于各帝国主义国家企图解脱新的经济危机和政治危机。战争的性质,无论在德国或英法方面,都是非正义的掠夺的帝国主义战争。全世界共产党都应该坚决反对这种战争,反对社会民主党拥护这种战争叛卖无产阶级的罪恶行为。社会主义的苏联依然坚持其和平政策,对战争的双方严守中立,用出兵波兰的行动制止德国侵略势力向东扩展,巩固东欧和平,解放被波兰统治者所压迫的西部乌克兰和白俄罗斯的兄弟民族。苏联和其周围各国订立了各种条约,以预防国际反动势力的可能的袭击,并为世界和平的恢复而奋斗。 - (二)日本帝国主义在国际新形势下的政策是专力进攻中国,企图解决中国问题,以准备将来扩大其对国际的冒险行动。其企图用以解决中国问题的方针是: - 一、对于占领区域,是加以确保,作为灭亡全中国的准备。为达此目的,它需要“扫荡”抗日游击根据地,需要进行经济开发和建立伪政权,需要消灭中国人的民族精神。 - 二、对于我后方,是以政治进攻为主,而以军事进攻为辅。所谓政治进攻,就是着重于分化抗日统一战线,分裂国共合作,引诱国民党政府投降,而不是着重于大规模的军事进攻。 - 在现在时期,敌人如同过去进攻武汉那样的大规模战略进攻行动,由于他所受中国过去二年余的英勇抗战的打击,由于他的兵力不足和财力不足,其可能性已经不大了。在这种意义上,抗战的战略相持阶段基本上已经到来。这种战略相持阶段,即是准备反攻阶段。但是第一,我们说相持局面基本上已经到来,并不否认敌人还有某些战役进攻的可能;敌人现在正在进攻长沙,将来还可能进攻其他若干地区。第二,随着正面相持的可能之增多,敌人将加重其对于我游击根据地的“扫荡”战争。第三,如果中国不能破坏敌人占领地,让其达到确保占领地、经营占领地的目的;又如果中国不能打退敌人的政治进攻,不能坚持抗战,坚持团结,坚持进步,以准备反攻力量,或者国民党政府竟自动投降;那末,在将来,敌人就仍有大举进攻的可能。就是说,已经到来的相持局面仍有被敌人和投降派破坏的可能。 - (三)抗日统一战线中的投降危险、分裂危险和倒退危险仍然是当前时局中的最大危险,目前的反共现象和倒退现象仍然是大地主大资产阶级准备投降的步骤。我们的任务,仍然是协同全国一切爱国分子,动员群众,切实执行我党《七七宣言》中“坚持抗战、反对投降”,“坚持团结、反对分裂”,“坚持进步、反对倒退”三大政治口号,以准备反攻力量。为达此目的,在敌后方,必须坚持游击战争,战胜敌人的“扫荡”,破坏敌人的占领地,实行激进的有利于广大抗日民众的政治改革和经济改革。在正面,必须支持军事防御,打退敌人可能的任何战役进攻。在我后方,必须迅速地认真地实行政治改革,结束国民党一党专政,召集真正代表民意的有权力的国民大会,制定宪法,实行宪政。任何的动摇和懈怠,任何与此相反的方针,都是绝对错误的。同时,我党各级领导机关和全体同志,应该提高对当前时局的警觉性,用全力从思想上、政治上、组织上巩固我们的党,巩固党所领导的军队和政权,以准备对付可能的危害中国革命的突然事变,使党和革命在可能的突然事变中不致遭受意外的损失。 - [(1)]((1).md)([jz_0_291](jz_0_291.md))* 这是毛泽东为中共中央起草的决定。 ## 大量吸收知识分子[(1)]((1).md)([jz_0_294](jz_0_294.md)) - (一九三九年十二月一日) - 一、在长期的和残酷的民族解放战争中,在建立新中国的伟大斗争中,共产党必须善于吸收知识分子,才能组织伟大的抗战力量,组织千百万农民群众,发展革命的文化运动和发展革命的统一战线。没有知识分子的参加,革命的胜利是不可能的。 - 二、三年以来,我党我军在吸收知识分子方面,已经尽了相当的努力,吸收了大批革命知识分子参加党,参加军队,参加政府工作,进行文化运动和民众运动,发展了统一战线,这是一个大的成绩。但许多军队中的干部,还没有注意到知识分子的重要性,还存着恐惧知识分子甚至排斥知识分子的心理。许多我们办的学校,还不敢放手地大量地招收青年学生。许多地方党部,还不愿意吸收知识分子入党。这种现象的发生,是由于不懂得知识分子对于革命事业的重要性,不懂得殖民地半殖民地国家的知识分子和资本主义国家的知识分子的区别,不懂得为地主资产阶级服务的知识分子和为工农阶级服务的知识分子的区别,不懂得资产阶级政党正在拚命地同我们争夺知识分子,日本帝国主义也在利用各种方法收买和麻醉中国知识分子的严重性,尤其不懂得我们的党和军队已经造成了中坚骨干,有了掌握知识分子的能力这种有利的条件。 - 三、因此,今后应该注意:(1)一切战区的党和一切党的军队,应该大量吸收知识分子加入我们的军队,加入我们的学校,加入政府工作。只要是愿意抗日的比较忠实的比较能吃苦耐劳的知识分子,都应该多方吸收,加以教育,使他们在战争中在工作中去磨练,使他们为军队、为政府、为群众服务,并按照具体情况将具备了入党条件的一部分知识分子吸收入党。对于不能入党或不愿入党的一部分知识分子,也应该同他们建立良好的共同工作关系,带领他们一道工作。(2)在这种大量吸收政策之下,毫无疑义应该充分注意拒绝敌人和资产阶级政党派遣进来的分子,拒绝不忠实的分子。对于这类分子的拒绝,应取严肃的态度。这类分子已经混进我们的党、我们的军队和政府者,则应依靠真凭实据,坚决地有分别地洗刷出去。但不要因此而怀疑那些比较忠实的知识分子;要严防反革命分子陷害好人。(3)对于一切多少有用的比较忠实的知识分子,应该分配适当的工作,应该好好地教育他们,带领他们,在长期斗争中逐渐克服他们的弱点,使他们革命化和群众化,使他们同老党员老干部融洽起来,使他们同工农党员融洽起来。(4)对于一部分反对知识分子参加工作的干部,尤其是主力部队中的某些干部,则应该切实地说服他们,使他们懂得吸收知识分子参加工作的必要。同时切实地鼓励工农干部加紧学习,提高他们的文化水平,使工农干部的知识分子化和知识分子的工农群众化,同时实现起来。(5)在国民党统治区和日寇占领区,基本上适用上述原则,但吸收知识分子入党时,应更多注意其忠实的程度,以保证党的组织更加严密。对于广大的同情我们的党外知识分子,则应该同他们建立适当的联系,把他们组织到抗日和民主的伟大斗争中去,组织到文化运动中去,组织到统一战线的工作中去。 - 四、全党同志必须认识,对于知识分子的正确的政策,是革命胜利的重要条件之一。我们党在土地革命时期,许多地方许多军队对于知识分子的不正确态度,今后决不应重复;而无产阶级自己的知识分子的造成,也决不能离开利用社会原有知识分子的帮助。中央盼望各级党委和全党同志,严重地注意这个问题。 - [(1)]((1).md)([jz_0_294](jz_0_294.md))* 这是毛泽东为中共中央起草的决定。 ## 中国革命和中国共产党[(1)]((1).md)([jz_0_297](jz_0_297.md)) - (一九三九年十二月) - [(1)]((1).md)([jz_0_297](jz_0_297.md))* 《中国革命和中国共产党》,是一九三九年冬季,由毛泽东和其他几个在延安的同志合作写作的一个课本。第一章《中国社会》,是其他几个同志起草,经过毛泽东修改的。第二章《中国革命》,是毛泽东自己写的。第三章,准备写《党的建设》,因为担任写作的同志没有完稿而停止。但是这两章,特别是第二章,在中国共产党和中国人民中仍然起了很大的教育作用。毛泽东在这个小册子的第二章中关于新民主主义的观点,在一九四○年一月他所写的《新民主主义论》中大为发展了。 ### 第一章 中国社会 - 第一节 中华民族 - 我们中国是世界上最大国家之一,它的领土和整个欧洲的面积差不多相等。在这个广大的领土之上,有广大的肥田沃地,给我们以衣食之源;有纵横全国的大小山脉,给我们生长了广大的森林,贮藏了丰富的矿产;有很多的江河湖泽,给我们以舟楫和灌溉之利;有很长的海岸线,给我们以交通海外各民族的方便。从很早的古代起,我们中华民族的祖先就劳动、生息、繁殖在这块广大的土地之上。 - 现在中国的国境:在东北、西北和西方的一部,和苏维埃社会主义共和国联盟接壤。正北面,和蒙古人民共和国接壤。西方的一部和西南方,和阿富汗、印度、不丹、尼泊尔接壤。南方,和缅甸、越南接壤。东方,和朝鲜接壤,和日本、菲律宾邻近。这个地理上的国际环境,给予中国人民革命造成了外部的有利条件和困难条件。有利的是:和苏联接壤,和欧美各主要帝国主义国家隔离较远,在其周围的国家中有许多是殖民地半殖民地国家。困难的是:日本帝国主义利用其和中国接近的关系,时刻都在迫害着中国各民族的生存,迫害着中国人民的革命。 - 我们中国现在拥有四亿五千万人口,差不多占了全世界人口的四分之一。在这四亿五千万人口中,十分之九以上为汉人。此外,还有蒙人、回人、藏人、维吾尔人、苗人、彝人、壮人、仲家[1](1.md)([wz_1_298](wz_1_298.md))人、朝鲜人等,共有数十种少数民族,虽然文化发展的程度不同,但是都已有长久的历史。中国是一个由多数民族结合而成的拥有广大人口的国家。 - 中华民族的发展(这里说的主要地是汉族的发展),和世界上别的许多民族同样,曾经经过了若干万年的无阶级的原始公社的生活。而从原始公社崩溃,社会生活转入阶级生活那个时代开始,经过奴隶社会、封建社会,直到现在,已有了大约四千年之久。在中华民族的开化史上,有素称发达的农业和手工业,有许多伟大的思想家、科学家、发明家、政治家、军事家、文学家和艺术家,有丰富的文化典籍。在很早的时候,中国就有了指南针的发明[2](2.md)([wz_2_298](wz_2_298.md))。还在一千八百年前,已经发明了造纸法[3](3.md)([wz_3_298](wz_3_298.md))。在一千三百年前,已经发明了刻版印刷[4](4.md)([wz_4_298](wz_4_298.md))。在八百年前,更发明了活字印刷[5](5.md)([wz_5_298](wz_5_298.md))。火药的应用[6](6.md)([wz_6_298](wz_6_298.md)),也在欧洲人之前。所以,中国是世界文明发达最早的国家之一,中国已有了将近四千年的有文字可考的历史。 - 中华民族不但以刻苦耐劳著称于世,同时又是酷爱自由、富于革命传统的民族。以汉族的历史为例,可以证明中国人民是不能忍受黑暗势力的统治的,他们每次都用革命的手段达到推翻和改造这种统治的目的。在汉族的数千年的历史上,有过大小几百次的农民起义,反抗地主和贵族的黑暗统治。而多数朝代的更换,都是由于农民起义的力量才能得到成功的。中华民族的各族人民都反对外来民族的压迫,都要用反抗的手段解除这种压迫。他们赞成平等的联合,而不赞成互相压迫。在中华民族的几千年的历史中,产生了很多的民族英雄和革命领袖。所以,中华民族又是一个有光荣的革命传统和优秀的历史遗产的民族。 - [1](1.md)([wz_1_298](wz_1_298.md))仲家,布依族的一种旧称。 - [2](2.md)([wz_2_298](wz_2_298.md))指南针的发明,在中国是很早的。公元前三世纪战国时代,《吕氏春秋》上有“慈石召铁”的话,可见当时中国人已经知道磁石能吸铁。公元一世纪,东汉王充的《论衡》说磁勺柄指南,可见当时已经发现了磁石的指极性。根据宋代文献记载,在十一世纪,中国人已经发明了用人造磁针制造的指南针。到十二世纪初,即宋徽宗时,朱彧的《萍洲可谈》和徐兢的《宣和奉使高丽图经》,都说到航海用指南针,可见当时指南针的使用已经相当普遍。 - [3](3.md)([wz_3_298](wz_3_298.md))根据中国古代文献记载,公元二世纪初,东汉宦官蔡伦集中前人的经验,用树皮、麻头、破布和破鱼网造纸。此后,这种造纸法便在全国逐步推广开来。人们把这种纸称作“蔡侯纸”。 - [4](4.md)([wz_4_298](wz_4_298.md))中国的刻版印刷术,约创始于公元七世纪,即唐初年间。 - [5](5.md)([wz_5_298](wz_5_298.md))宋仁宗庆历(一○四一—— 一○四八)年间,毕升发明了活字印刷。 - [6](6.md)([wz_6_298](wz_6_298.md))中国火药的发明,大约在公元九世纪。到了宋朝初年,即公元十世纪后半期至十一世纪初,中国已经使用火药制造火炮、火箭等武器,供战争之用。 - 第二节 古代的封建社会 - 中国虽然是一个伟大的民族国家,虽然是一个地广人众、历史悠久而又富于革命传统和优秀遗产的国家;可是,中国自从脱离奴隶制度进到封建制度以后,其经济、政治、文化的发展,就长期地陷在发展迟缓的状态中。这个封建制度,自周秦以来一直延续了三千年左右。 - 中国封建时代的经济制度和政治制度,是由以下的各个主要特点构成的: - 一、自给自足的自然经济占主要地位。农民不但生产自己需要的农产品,而且生产自己需要的大部分手工业品。地主和贵族对于从农民剥削来的地租,也主要地是自己享用,而不是用于交换。那时虽有交换的发展,但是在整个经济中不起决定的作用。 - 二、封建的统治阶级——地主、贵族和皇帝,拥有最大部分的土地,而农民则很少土地,或者完全没有土地。农民用自己的工具去耕种地主、贵族和皇室的土地,并将收获的四成、五成、六成、七成甚至八成以上,奉献给地主、贵族和皇室享用。这种农民,实际上还是农奴。 - 三、不但地主、贵族和皇室依靠剥削农民的地租过活,而且地主阶级的国家又强迫农民缴纳贡税,并强迫农民从事无偿的劳役,去养活一大群的国家官吏和主要地是为了镇压农民之用的军队。 - 四、保护这种封建剥削制度的权力机关,是地主阶级的封建国家。如果说,秦以前的一个时代是诸侯割据称雄的封建国家,那末,自秦始皇统一中国以后,就建立了专制主义的中央集权的封建国家;同时,在某种程度上仍旧保留着封建割据的状态。在封建国家中,皇帝有至高无上的权力,在各地方分设官职以掌兵、刑、钱、谷等事,并依靠地主绅士作为全部封建统治的基础。 - 中国历代的农民,就在这种封建的经济剥削和封建的政治压迫之下,过着贫穷困苦的奴隶式的生活。农民被束缚于封建制度之下,没有人身的自由。地主对农民有随意打骂甚至处死之权,农民是没有任何政治权利的。地主阶级这样残酷的剥削和压迫所造成的农民的极端的穷苦和落后,就是中国社会几千年在经济上和社会生活上停滞不前的基本原因。 - 封建社会的主要矛盾,是农民阶级和地主阶级的矛盾。 - 而在这样的社会中,只有农民和手工业工人是创造财富和创造文化的基本的阶级。 - 地主阶级对于农民的残酷的经济剥削和政治压迫,迫使农民多次地举行起义,以反抗地主阶级的统治。从秦朝的陈胜、吴广、项羽、刘邦[7](7.md)([wz_7_301](wz_7_301.md))起,中经汉朝的新市、平林、赤眉、铜马[8](8.md)([wz_8_301](wz_8_301.md))和黄巾[9](9.md)([wz_9_301](wz_9_301.md)),隋朝的李密、窦建德[10](10.md)([wz_10_301](wz_10_301.md)),唐朝的王仙芝、黄巢[11](11.md)([wz_11_301](wz_11_301.md)),宋朝的宋江、方腊[12](12.md)([wz_12_301](wz_12_301.md)),元朝的朱元璋[13](13.md)([wz_13_301](wz_13_301.md)),明朝的李自成[14](14.md)([wz_14_301](wz_14_301.md)),直至清朝的太平天国[15](15.md)([wz_15_301](wz_15_301.md)),总计大小数百次的起义,都是农民的反抗运动,都是农民的革命战争。中国历史上的农民起义和农民战争的规模之大,是世界历史上所仅见的。在中国封建社会里,只有这种农民的阶级斗争、农民的起义和农民的战争,才是历史发展的真正动力。因为每一次较大的农民起义和农民战争的结果,都打击了当时的封建统治,因而也就多少推动了社会生产力的发展。只是由于当时还没有新的生产力和新的生产关系,没有新的阶级力量,没有先进的政党,因而这种农民起义和农民战争得不到如同现在所有的无产阶级和共产党的正确领导,这样,就使当时的农民革命总是陷于失败,总是在革命中和革命后被地主和贵族利用了去,当作他们改朝换代的工具。这样,就在每一次大规模的农民革命斗争停息以后,虽然社会多少有些进步,但是封建的经济关系和封建的政治制度,基本上依然继续下来。 - 这种情况,直至近百年来,才发生新的变化。 - [7](7.md)([wz_7_301](wz_7_301.md))陈胜、吴广是秦末农民大起义的领袖。公元前二○九年,即秦二世元年,陈胜、吴广往戍地途中在蕲县大泽乡(今安徽省宿县东南)率领同行戍卒九百人起义,反抗秦朝的残暴统治。全国各地纷起响应。项羽和他的叔父项梁在吴(今江苏省吴县)起兵,刘邦在沛(今江苏省沛县)起兵。陈胜、吴广起义失败以后,项羽、刘邦两军成了当时反秦的主要力量。项军消灭了秦军的主力,刘军攻占了关中和秦的都城咸阳。秦朝灭亡后,刘项双方相争数年,项羽败死,刘邦做了皇帝,建立了汉朝。 - [8](8.md)([wz_8_301](wz_8_301.md))新市、平林、赤眉、铜马都是王莽时代农民起义军的名称。西汉末年,各地农民不断进行反抗活动和武装起义。公元八年,王莽代汉以后,实行“改制”,企图缓和农民的反抗。但是,由于社会阶级矛盾的日益尖锐,加之天灾频繁,各地农民的反抗斗争终于发展为大规模的武装起义。公元十七年,新市(今湖北省京山县东北)人王匡、王凤领导饥民起义,以绿林山为基地,称为“绿林军”。后绿林军一部在王匡、王凤率领下北入南阳,称“新市兵”。另一部由王常等率领进入南郡(今湖北省江陵县),称“下江兵”。新市兵进入随县,平林(今湖北省随县东北)人陈牧等千余人起义响应,号称“平林兵”。公元十八年,山东琅琊人樊崇在莒县(今山东省莒县)领导农民起义。起义军用红色涂眉,号称“赤眉军”,主要活动于山东、江苏、河南、陕西等地,是当时最大的一支农民起义军。同时,在黄河以北的广大地区,还有大小数十支农民起义军,铜马是其中较大的一支,主要活动于河北、山东交界地区。 - [9](9.md)([wz_9_301](wz_9_301.md))公元一八四年,即东汉灵帝中平元年,张角等领导河北、河南、山东、安徽等地的农民数十万人同时举行起义。起义军头戴黄巾为标志,因此被称为“黄巾军”。 - [10](10.md)([wz_10_301](wz_10_301.md))公元七世纪初,即隋朝末年,农民纷纷起义。李密、窦建德是当时两支主要起义军的首领。李密领导的河南瓦岗军和窦建德领导的河北起义军,在推翻隋朝统治的斗争中,起了重要作用。 - [11](11.md)([wz_11_301](wz_11_301.md))王仙芝、黄巢是唐末农民起义军的领袖。公元八七四年(唐僖宗乾符元年),王仙芝在山东起义,次年黄巢聚众响应。参见本书第一卷《关于纠正党内的错误思想》注〔4〕。 - [12](12.md)([wz_12_301](wz_12_301.md))宋江和方腊分别是公元十二世纪初即北宋末年北方和南方农民起义的有名首领。宋江率领的起义队伍,主要活动于山东、河北、河南、江苏一带;方腊率领的起义队伍,主要活动于浙江、安徽一带。 - [13](13.md)([wz_13_301](wz_13_301.md))公元一三五一年,即元顺帝至正十一年,各地人民纷纷起义。一三五二年,安徽凤阳人朱元璋投入北方红巾军郭子兴部起义军。郭死,朱元璋成为该军的首领。一三六八年,他领导的部队推翻了在各地人民起义的打击下已经摇摇欲坠的元朝的统治,成为明朝的开国皇帝。 - [14](14.md)([wz_14_301](wz_14_301.md))见本书第一卷《关于纠正党内的错误思想》注〔5〕。 - [15](15.md)([wz_15_301](wz_15_301.md))见本书第一卷《论反对日本帝国主义的策略》注〔36〕。 - 第三节 现代的殖民地、半殖民地和半封建社会 - 中国过去三千年来的社会是封建社会,前面已经说明了。那末,中国现在的社会是否还是完全的封建社会呢?不是,中国已经变化了。自从一八四○年的鸦片战争[16](16.md)([wz_16_302](wz_16_302.md))以后,中国一步一步地变成了一个半殖民地半封建的社会。自从一九三一年九一八事变[17](17.md)([wz_17_302](wz_17_302.md))日本帝国主义武装侵略中国以后,中国又变成了一个殖民地、半殖民地和半封建的社会。现在我们就来说明这种变化的过程。 - 如第二节所述,中国的封建社会继续了三千年左右。直到十九世纪的中叶,由于外国资本主义的侵入,这个社会的内部才发生了重大的变化。 - 中国封建社会内的商品经济的发展,已经孕育着资本主义的萌芽,如果没有外国资本主义的影响,中国也将缓慢地发展到资本主义社会。外国资本主义的侵入,促进了这种发展。外国资本主义对于中国的社会经济起了很大的分解作用,一方面,破坏了中国自给自足的自然经济的基础,破坏了城市的手工业和农民的家庭手工业;又一方面,则促进了中国城乡商品经济的发展。 - 这些情形,不仅对中国封建经济的基础起了解体的作用,同时又给中国资本主义生产的发展造成了某些客观的条件和可能。因为自然经济的破坏,给资本主义造成了商品的市场,而大量农民和手工业者的破产,又给资本主义造成了劳动力的市场。 - 事实上,由于外国资本主义的刺激和封建经济结构的某些破坏,还在十九世纪的下半期,还在六十年前,就开始有一部分商人、地主和官僚投资于新式工业。到了同世纪末年和二十世纪初年,到了四十年前,中国民族资本主义便开始了初步的发展。到了二十年前,即第一次帝国主义世界大战的时期,由于欧美帝国主义国家忙于战争,暂时放松了对于中国的压迫,中国的民族工业,主要是纺织业和面粉业,又得到了进一步的发展。 - 中国民族资本主义发生和发展的过程,就是中国资产阶级和无产阶级发生和发展的过程。如果一部分的商人、地主和官僚是中国资产阶级的前身,那末,一部分的农民和手工业工人就是中国无产阶级的前身了。中国的资产阶级和无产阶级,作为两个特殊的社会阶级来看,它们是新产生的,它们是中国历史上没有过的阶级。它们从封建社会脱胎而来,构成了新的社会阶级。它们是两个互相关联又互相对立的阶级,它们是中国旧社会(封建社会)产出的双生子。但是,中国无产阶级的发生和发展,不但是伴随中国民族资产阶级的发生和发展而来,而且是伴随帝国主义在中国直接地经营企业而来。所以,中国无产阶级的很大一部分较之中国资产阶级的年龄和资格更老些,因而它的社会力量和社会基础也更广大些。 - 可是,上面所述的这一资本主义的发生和发展的新变化,只是帝国主义侵入中国以来所发生的变化的一个方面。还有和这个变化同时存在而阻碍这个变化的另一个方面,这就是帝国主义勾结中国封建势力压迫中国资本主义的发展。 - 帝国主义列强侵入中国的目的,决不是要把封建的中国变成资本主义的中国。帝国主义列强的目的和这相反,它们是要把中国变成它们的半殖民地和殖民地。 - 帝国主义列强为了这个目的,曾经对中国采用了并且还正在继续地采用着如同下面所说的一切军事的、政治的、经济的和文化的压迫手段,使中国一步一步地变成了半殖民地和殖民地: - 一、向中国举行多次的侵略战争,例如一八四○年的英国鸦片战争,一八五七年的英法联军战争[18](18.md)([wz_18_304](wz_18_304.md)),一八八四年的中法战争[19](19.md)([wz_19_304](wz_19_304.md)),一八九四年的中日战争[20](20.md)([wz_20_304](wz_20_304.md)),一九○○年的八国联军战争[21](21.md)([wz_21_304](wz_21_304.md))。用战争打败了中国之后,帝国主义列强不但占领了中国周围的许多原由中国保护的国家,而且抢去了或“租借”去了中国的一部分领土。例如日本占领了台湾和澎湖列岛,“租借”了旅顺,英国占领了香港,法国“租借”了广州湾。割地之外,又索去了巨大的赔款。这样,就大大地打击了中国这个庞大的封建帝国。 - 二、帝国主义列强强迫中国订立了许多不平等条约,根据这些不平等条约,取得了在中国驻扎海军和陆军的权利,取得了领事裁判权[22](22.md)([wz_22_304](wz_22_304.md)),并把全中国划分为几个帝国主义国家的势力范围[23](23.md)([wz_23_304](wz_23_304.md))。 - 三、帝国主义列强根据不平等条约,控制了中国一切重要的通商口岸,并把许多通商口岸划出一部分土地作为它们直接管理的租界[24](24.md)([wz_24_304](wz_24_304.md))。它们控制了中国的海关和对外贸易,控制了中国的交通事业(海上的、陆上的、内河的和空中的)。因此它们便能够大量地推销它们的商品,把中国变成它们的工业品的市场,同时又使中国的农业生产服从于帝国主义的需要。 - 四、帝国主义列强还在中国经营了许多轻工业和重工业的企业,以便直接利用中国的原料和廉价的劳动力,并以此对中国的民族工业进行直接的经济压迫,直接地阻碍中国生产力的发展。 - 五、帝国主义列强经过借款给中国政府,并在中国开设银行,垄断了中国的金融和财政。因此,它们就不但在商品竞争上压倒了中国的民族资本主义,而且在金融上、财政上扼住了中国的咽喉。 - 六、帝国主义列强从中国的通商都市直至穷乡僻壤,造成了一个买办的和商业高利贷的剥削网,造成了为帝国主义服务的买办阶级和商业高利贷阶级,以便利其剥削广大的中国农民和其他人民大众。 - 七、于买办阶级之外,帝国主义列强又使中国的封建地主阶级变为它们统治中国的支柱。它们“首先和以前的社会制度的统治阶级——封建地主、商业和高利贷资产阶级联合起来,以反对占大多数的人民。帝国主义到处致力于保持资本主义前期的一切剥削形式(特别是在乡村),并使之永久化,而这些形式则是它的反动的同盟者生存的基础”[25](25.md)([wz_25_305](wz_25_305.md))。“帝国主义及其在中国的全部财政军事的势力,乃是一种支持、鼓舞、栽培、保存封建残余及其全部官僚军阀上层建筑的力量。”[26](26.md)([wz_26_305](wz_26_305.md)) - 八、为了造成中国军阀混战和镇压中国人民,帝国主义列强供给中国反动政府以大量的军火和大批的军事顾问。 - 九、帝国主义列强在所有上述这些办法之外,对于麻醉中国人民的精神的一个方面,也不放松,这就是它们的文化侵略政策。传教,办医院,办学校,办报纸和吸引留学生等,就是这个侵略政策的实施。其目的,在于造就服从它们的知识干部和愚弄广大的中国人民。 - 十、从一九三一年“九一八”以后,日本帝国主义的大举进攻,更使已经变成半殖民地的中国的一大块土地沦为日本的殖民地。 - 上述这些情形,就是帝国主义侵入中国以后的新的变化的又一个方面,就是把一个封建的中国变为一个半封建、半殖民地和殖民地的中国的血迹斑斑的图画。 - 由此可以明白,帝国主义列强侵略中国,在一方面促使中国封建社会解体,促使中国发生了资本主义因素,把一个封建社会变成了一个半封建的社会;但是在另一方面,它们又残酷地统治了中国,把一个独立的中国变成了一个半殖民地和殖民地的中国。 - 将这两个方面的情形综合起来说,我们这个殖民地、半殖民地、半封建的社会,有如下的几个特点: - 一、封建时代的自给自足的自然经济基础是被破坏了;但是,封建剥削制度的根基——地主阶级对农民的剥削,不但依旧保持着,而且同买办资本和高利贷资本的剥削结合在一起,在中国的社会经济生活中,占着显然的优势。 - 二、民族资本主义有了某些发展,并在中国政治的、文化的生活中起了颇大的作用;但是,它没有成为中国社会经济的主要形式,它的力量是很软弱的,它的大部分是对于外国帝国主义和国内封建主义都有或多或少的联系的。 - 三、皇帝和贵族的专制政权是被推翻了,代之而起的先是地主阶级的军阀官僚的统治,接着是地主阶级和大资产阶级联盟的专政。在沦陷区,则是日本帝国主义及其傀儡的统治。 - 四、帝国主义不但操纵了中国的财政和经济的命脉,并且操纵了中国的政治和军事的力量。在沦陷区,则一切被日本帝国主义所独占。 - 五、由于中国是在许多帝国主义国家的统治或半统治之下,由于中国实际上处于长期的不统一状态,又由于中国的土地广大,中国的经济、政治和文化的发展,表现出极端的不平衡。 - 六、由于帝国主义和封建主义的双重压迫,特别是由于日本帝国主义的大举进攻,中国的广大人民,尤其是农民,日益贫困化以至大批地破产,他们过着饥寒交迫的和毫无政治权利的生活。中国人民的贫困和不自由的程度,是世界所少见的。 - 这些就是殖民地、半殖民地、半封建的中国社会的特点。 - 决定这种情况的,主要地是日本帝国主义和其他帝国主义的势力,是外国帝国主义和国内封建主义相结合的结果。 - 帝国主义和中华民族的矛盾,封建主义和人民大众的矛盾,这些就是近代中国社会的主要的矛盾。当然还有别的矛盾,例如资产阶级和无产阶级的矛盾,反动统治阶级内部的矛盾。而帝国主义和中华民族的矛盾,乃是各种矛盾中的最主要的矛盾。这些矛盾的斗争及其尖锐化,就不能不造成日益发展的革命运动。伟大的近代和现代的中国革命,是在这些基本矛盾的基础之上发生和发展起来的。 - [16](16.md)([wz_16_302](wz_16_302.md))见本书第一卷《论反对日本帝国主义的策略》注〔35〕。 - [17](17.md)([wz_17_302](wz_17_302.md))见本书第一卷《论反对日本帝国主义的策略》注〔4〕。 - [18](18.md)([wz_18_304](wz_18_304.md))一八五七年的英法联军战争,又称第二次鸦片战争。一八五六年,英国侵略军在广州向中国方面挑衅。一八五七年英法两国组成联合侵略军,对中国发动侵略战争。美国和沙俄不仅积极帮助他们,而且直接插手,乘机攫取中国的权利。当时清朝政府正以全力镇压太平天国农民革命,对外国侵略者采取消极抵抗政策。一八五七年至一八六○年,英法联军先后攻陷广州、天津、北京等重要城市,劫掠并焚毁北京圆明园,迫使清朝政府订立了《天津条约》和《北京条约》。这些条约主要规定将天津、牛庄(后改为营口)、登州(后改为烟台)、台湾(台南)、淡水、潮州(后改为汕头)、琼州、南京、镇江、九江、汉口等处开辟为商埠;承认外国人有在中国内地自由传教和游历通商的特权,外国商船有在中国内河航行的特权。从此,外国侵略势力不但扩大到中国沿海各省,同时还深入了内地。 - [19](19.md)([wz_19_304](wz_19_304.md))一八八二年至一八八三年,法国侵略者侵犯越南北部。一八八四年至一八八五年,又把侵略战争扩大到中国的广西、台湾、福建、浙江等地。中国军队在冯子材等率领下,奋起抵抗,并且屡获胜利。但是,腐朽的清朝政府在战争胜利之后,反而签订了屈辱的《天津条约》,允许在云南、广西两省的中越边界开埠通商,使法国侵略势力得以伸入中国西南地区。 - [20](20.md)([wz_20_304](wz_20_304.md))见本书第一卷《矛盾论》注〔22〕。 - [21](21.md)([wz_21_304](wz_21_304.md))一九○○年,英、美、德、法、俄、日、意、奥八个帝国主义国家,为了镇压义和团的反侵略运动,联合出兵进攻中国,中国人民进行了英勇的抵抗。战争中,侵略军先后攻陷大沽、天津、北京等地。同时,沙俄又单独出兵侵入中国东北。清政府接受了帝国主义的条件,于一九○一年九月七日在条件极为苛刻的《辛丑条约》上签字。这个条约的主要内容是:中国向八国赔偿银四亿五千万两,承认帝国主义国家有在北京和北京至天津、山海关一带地区驻兵的特权。 - [22](22.md)([wz_22_304](wz_22_304.md))领事裁判权,是帝国主义国家强迫旧中国政府缔结的不平等条约中所规定的特权之一,开始于一八四三年的中英《虎门条约》和一八四四年的中美《望厦条约》。凡是享有这种特权的国家在中国的侨民,如果成为民刑诉讼的被告时,中国法庭无权裁判,只能由各该国的领事或者法庭裁判。 - [23](23.md)([wz_23_304](wz_23_304.md))从十九世纪末起,侵略中国的各帝国主义国家,按照他们各自在中国的经济和军事的势力,曾经将中国的某些地区划为自己的势力范围。例如,当时长江流域各省被划为英国的势力范围,云南、广西、广东被划为法国的势力范围,山东被划为德国的势力范围,福建被划为日本的势力范围,东三省原划为沙俄的势力范围,一九○五年日俄战争后,东三省南部又成为日本的势力范围。 - [24](24.md)([wz_24_304](wz_24_304.md))帝国主义国家在强迫清朝政府开放了沿江沿海的许多地方为通商口岸后,于一八四五年开始在这些地方强占一定的地区作为“租界”。最初,租界是外国人居留、贸易的特定地区。中国政府对租界内的行政、司法等有干预权,并保有租界内的领土主权。后来,帝国主义国家在租界内,逐渐实行完全独立于中国行政系统和法律制度以外的一套殖民地统治制度。它们以租界为据点,在政治上和经济上直接或者间接地控制中国的封建买办阶级的统治。一九二四年至一九二七年,在中国共产党的领导下,中国人民曾进行收回租界的斗争,并于一九二七年一月,一度收回了汉口和九江的英租界。但是,在蒋介石发动反革命政变以后,帝国主义在中国各地的租界仍然被保留下来。 - [25](25.md)([wz_25_305](wz_25_305.md))见共产国际第六次代表大会《关于殖民地和半殖民地国家革命运动的提纲》。 - [26](26.md)([wz_26_305](wz_26_305.md))见斯大林一九二七年五月二十四日在共产国际执行委员会第八次全会第十次会议
1,534
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. */ module.exports = function (grunt) { require('matchdep').filterAll('grunt-*').forEach(grunt.loadNpmTasks); var pkgJson = require('./package.json'); var releaseDirectory = 'wiki/releases/' + pkgJson.version; var releaseFile = releaseDirectory + '/Documentation-' + pkgJson.version + '.md'; grunt.initConfig({ copy: { assets: { expand: true, cwd: 'wiki', src: 'assets/**', dest: releaseDirectory } }, json_generator: { markdown: { dest:'markdown.json', options: { build: releaseFile, files: [ 'DocumentationTemplate.md' ] } } } }); grunt.registerTask('markdown-compile', 'Compiles markdown', function() { var done = this.async(); var fs = require('fs-extra'); /* This is synchronous function that checks whether specified directory exists and creates it if it doesn't exist. It is required here since the markdown-include package produces error if target directory doesn't exist. */ fs.ensureDirSync(releaseDirectory); var markdownInclude = require('markdown-include'); markdownInclude.compileFiles('markdown.json').then(function (data) { done(); }); setTimeout(function() { done(); }, 5000); }); grunt.registerTask('build', ['json_generator','markdown-compile', 'copy']); }; ======================= File: report/src/main/webapp/app/components/compareScreens.directive.js ======================= <filename>report/src/main/webapp/app/components/compareScreens.directive.js /* * AET * * Copyright (C) 2013 Cognifide Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ define(['angularAMD'], function (angularAMD) { 'use strict'; angularAMD.directive('aetCompareScreens', compareScreensDirective); function compareScreensDirective() { return { restrict: 'A', link: linkFunc }; } function linkFunc(scope) { scope.advancedScreenComparison = function () { var tab = document.querySelector('.test-tabs >.tab-content >.tab-pane.ng-scope.active'); var wrapper = tab.querySelector('.page-main.layout-compare'); var initedClass ='screen-comparison-active'; var arrangeTimeout = 0; var infoMsg = document.createElement('div'); var button = document.querySelector('.advanced-screen-comparison'); var tabContent = document.querySelector('.tab-content'); var items = wrapper.querySelectorAll('.layout-compare-item.img-responsive:not(.mask)'); function prepareMarkup(wrapper) { wrapper.innerHTML = '</div><div class="difs"></div><div class="customMasks"><div class="customMask maskAtop"></div><div class="customMask maskAbot"></div><div class="customMask maskBtop"></div><div class="customMask maskBbot"></div><div class="customLabel labelA"><div class="ruler"></div><div class="text"></div></div><div class="customLabel labelB"><div class="ruler"></div><div class="text"></div></div></div><div class="canvas-wrapper"></div>'; } if (!wrapper) { console.warn('Can\'t find wrapper'); return; } else if (wrapper.classList.contains(initedClass)) { console.warn('Screen comparison already has already been initialized'); return; } else { wrapper.classList.add(initedClass); } prepareMarkup(wrapper); var img = { imgA: items[0].src, imgB: items[1].src, }; var canvas = { canvasWrapper: wrapper.querySelector('.canvas-wrapper'), canvasA: document.createElement('canvas'), canvasB: document.createElement('canvas'), }; var label = { labelA: wrapper.querySelector('.labelA'), labelB: wrapper.querySelector('.labelB'), }; var ruler = { rulerA: label.labelA.querySelector('.ruler'), rulerB: label.labelB.querySelector('.ruler'), }; var mask = { maskA: { top: wrapper.querySelector('.maskAtop'), bot: wrapper.querySelector('.maskAbot'), }, maskB: { top: wrapper.querySelector('.maskBtop'), bot: wrapper.querySelector('.maskBbot'), }, customMask: wrapper.querySelector('.customMasks'), maskSize: null, }; var context = { contextA: canvas.canvasA.getContext('2d'), contextB: canvas.canvasB.getContext('2d'), }; var imgSize = { imgSizeA: null, imgSizeB: null, }; var simplifiedImage = { simpleA: null, simpleB: null, }; var cursor = { cursorA: 0, cursorB: 0, cursorBstart: 0, }; var difs = { main: wrapper.querySelector('.difs'), difsA: [], difsB: [], }; var invertedGroups = { invertedGroupsA: [], invertedGroupsB: [], }; var differenceGroups = []; var differenceGroup = []; markComparisonStarted(infoMsg, button, tabContent, items); loadImage(img.imgA, imgSize.imgSizeA, canvas.canvasA, context.contextA, simplifiedImage.simpleA, function (returnedSimple, returnedImgSize) { simplifiedImage.simpleA = returnedSimple; imgSize.imgSizeA = returnedImgSize; }); loadImage(img.imgB, imgSize.imgSizeB, canvas.canvasB, context.contextB, simplifiedImage.simpleB, function (returnedSimple, returnedImgSize) { simplifiedImage.simpleB = returnedSimple; imgSize.imgSizeB = returnedImgSize; button.classList.remove('button-disabled'); tabContent.removeChild(infoMsg); arrangeMasks(mask, difs, canvas, arrangeTimeout, arrangeMaskCallback); }); function arrangeMaskCallback(maskSize) { mask.maskSize = maskSize; onImagesReady(mask, imgSize, simplifiedImage, label, ruler, invertedGroups, difs, wrapper); processLines(cursor, simplifiedImage, differenceGroup, differenceGroups); invertGroups(simplifiedImage, differenceGroups, invertedGroups); drawDifferences(difs, imgSize, invertedGroups, simplifiedImage, context); } canvas.canvasWrapper.appendChild(canvas.canvasA); canvas.canvasWrapper.appendChild(canvas.canvasB); }; function markComparisonStarted(infoMsg, button, tabContent, items) { button.classList.add('button-disabled'); infoMsg.innerHTML = '<div class="info-msg">Advanced screen comparison in progress - please wait</div>'; tabContent = document.querySelector('.tab-content'); tabContent.appendChild(infoMsg); if (items.length!== 2) { return; } } function drawDifferences(difs, imgSize, invertedGroups, simplifiedImage, context) { var maxHeight = Math.max(imgSize.imgSizeA.height, imgSize.imgSizeB.height); var proc = 100 / maxHeight; var newDiffBLeft = '52%'; for (var i = 0; i < invertedGroups.invertedGroupsA.length; i++) { var newDifferenceA = document.createElement('canvas'); var newDifferenceContextA = newDifferenceA.getContext('2d'); var newDifferenceB = document.createElement('canvas'); var newDifferenceContextB = newDifferenceB.getContext('2d'); var sizes = getGroupsSizes(i, invertedGroups, simplifiedImage); if (sizes) { var heightA = sizes.aTo - sizes.aFrom; var heightB = sizes.bTo - sizes.bFrom; newDifferenceA.width = newDifferenceB.width = newDifferenceContextA.width = newDifferenceContextB.width = imgSize.imgSizeA.width; newDifferenceA.height = newDifferenceContextA.height = heightA; newDifferenceB.height = newDifferenceContextB.height = heightB; newDifferenceB.style.left = newDiffBLeft; difs.main.appendChild(newDifferenceA); difs.main.appendChild(newDifferenceB); newDifferenceA.style.top = sizes.aFrom * proc + '%'; newDifferenceB.style.top = sizes.bFrom * proc + '%'; newDifferenceA.style.height = (sizes.aTo - sizes.aFrom) * proc + '%'; newDifferenceB.style.height = (sizes.bTo - sizes.bFrom) * proc + '%'; var dataA = context.contextA.getImageData(0, sizes.aFrom, imgSize.imgSizeA.width, Math.max(heightA, 1)); var dataB = context.contextB.getImageData(0, sizes.bFrom, imgSize.imgSizeA.width, Math.max(heightB, 1)); var imageData; if (dataA.height > dataB.height) { imageData = convertDifferenceData(dataA, dataB); } else { imageData = convertDifferenceData(dataB, dataA); } newDifferenceContextA.putImageData(imageData, 0, 0, 0, 0, imgSize.imgSizeA.width, heightA); if (heightB > 0) { newDifferenceContextB.putImageData(imageData, 0, 0, 0, 0, imgSize.imgSizeA.width, heightB); } difs.difsA.push(newDifferenceA); difs.difsB.push(newDifferenceB); } } } function convertDifferenceData(firstImgData, secondImgData) { for (var index = 0; index < firstImgData.data.length; index += 4) { if (typeof secondImgData.data[index]!== 'undefined') { if (firstImgData.data[index]!== secondImgData.data[index] || firstImgData.data[index + 1]!== secondImgData.data[index + 1] || firstImgData.data[index + 2]!== secondImgData.data[index + 2]) { firstImgData = dataToRGB(firstImgData, index, [255, 0, 0, 127]); } else { firstImgData = dataToRGB(firstImgData, index, [0, 0, 0, 0]); } } else { firstImgData = dataToRGB(firstImgData, index, [255, 0, 0, 127]); } } return firstImgData; } function dataToRGB(imgData, index, colors) { imgData.data[index] = colors[0]; imgData.data[index + 1] = colors[1]; imgData.data[index + 2] = colors[2]; imgData.data[index + 3] = colors[3]; return imgData; } function loadImage(url, imgSize, canvas, context, simplifiedImage, callbackOnSuccess) { var image = new Image(); image.setAttribute('crossOrigin', ''); image.src = url; image.onload = function () { imgSize = { width: image.naturalWidth, height: image.naturalHeight, }; canvas.width = context.width = imgSize.width; canvas.height = context.height = imgSize.height; context.drawImage(image, 0, 0); simplifiedImage = simplifyImage(context.getImageData(0, 0, imgSize.width, imgSize.height)); callbackOnSuccess(simplifiedImage, imgSize); }; image.onerror = function () { return false; }; } function rgb2hex(r, g, b) { return ('0' + r.toString(16)).slice(-2) + ('0' + g.toString(16)).slice(-2) + ('0' + b.toString(16)).slice(-2); } function simplifyImage(imageData) { var imageWidth = imageData.width; var offset = 0; var data = imageData.data; var simplifiedList = []; var previousLine; var valuesPerColor = 4; for (var y = 0; y < data.length / (imageWidth * valuesPerColor); y++) { var previousElement = simplifiedList.length? simplifiedList[simplifiedList.length - 1] : {}; var previousColor = ''; var simplifiedLine = ''; var encounters = 0; for (var x = 0; x < imageWidth; x++) { var index = y * imageWidth * valuesPerColor + x * valuesPerColor; var currentColor = rgb2hex(data[index + 0], data[index + 1], data[index + 2]); if (currentColor!== previousColor) { if (encounters > 0) { simplifiedLine += ',' + encounters + '|'; } simplifiedLine += currentColor; previousColor = currentColor; } encounters++; } if (encounters > 0) { simplifiedLine += ',' + encounters; } if (previousLine) { if (previousLine === simplifiedLine) { if (previousElement && previousElement.type ==='space' && previousElement.value === previousLine) { simplifiedList[simplifiedList.length - 1].size++; } else { addNewSpace(simplifiedLine, simplifiedList, offset); } offset++; } else { if (previousElement && previousElement.type === 'block') { previousElement.size++; previousElement.content.push(simplifiedLine); } else { addNewBlock(simplifiedLine, simplifiedList, offset); } offset++; } } previousLine = simplifiedLine; } simplifiedList.push({ type: 'block', content: [], size: 0, offset: offset + 1 }); return simplifiedList; } function addNewSpace(simplifiedLine, simplifiedList, offset) { var newElement = { type:'space', value: simplifiedLine, size: 2, offset: offset }; simplifiedList.push(newElement); } function addNewBlock(simplifiedLine, simplifiedList, offset) { var newElement = { type: 'block', content: [simplifiedLine], size: 1, offset: offset? offset + 1 : 0 }; simplifiedList.push(newElement); } function processLines(cursor, simplifiedImage, differenceGroup, differenceGroups) { if (cursor.cursorA === (simplifiedImage.simpleA.length - 1)) { pushGroups(); return; } else if (cursor.cursorB === (simplifiedImage.simpleB.length - 1)) { cursor.cursorB = cursor.cursorBstart; cursor.cursorA++; pushGroups(); } else { var lastBlockMatchA; var lastBlockMatchB; if (simplifiedImage.simpleA[cursor.cursorA].type === simplifiedImage.simpleB[cursor.cursorB].type) { if (simplifiedImage.simpleA[cursor.cursorA].type ==='space') { handleSpaceLineProcessing(); } else { handleBlockLineProcessing(); } } else { cursor.cursorB++; } } processLines(cursor, simplifiedImage, differenceGroup, differenceGroups); function handleSpaceLineProcessing() { if (simplifiedImage.simpleA[cursor.cursorA].color === simplifiedImage.simpleB[cursor.cursorB].color) { if (simplifiedImage.simpleA[cursor.cursorA].size === simplifiedImage.simpleB[cursor.cursorB].size) { if (simplifiedImage.simpleA[cursor.cursorA].match!== cursor.cursorB) { changeCursor('space'); } else { cursor.cursorB = cursor.cursorBstart; cursor.cursorA++; pushGroups(); } } else { cursor.cursorB = cursor.cursorBstart; cursor.cursorA++; pushGroups(); } } else { cursor.cursorB++; } } function handleBlockLineProcessing() { if (simplifiedImage.simpleA[cursor.cursorA].size === simplifiedImage.simpleB[cursor.cursorB].size) { if (simplifiedImage.simpleA[cursor.cursorA].content.join(',') === simplifiedImage.simpleB[cursor.cursorB].content.join(',')) { if (simplifiedImage.simpleA[cursor.cursorA].match!== cursor.cursorB) { changeCursor('block'); } else { cursor.cursorB++; } } else { cursor.cursorB++; } } else { cursor.cursorB++; } } function changeCursor(lineType) { simplifiedImage.simpleA[cursor.cursorA].match = cursor.cursorB; simplifiedImage.simpleB[cursor.cursorB].match = cursor.cursorA; if (lineType ==='space') { lastBlockMatchA = cursor.cursorA; lastBlockMatchB = cursor.cursorB; } differenceGroup.push(cursor.cursorA); cursor.cursorB++; cursor.cursorBstart = cursor.cursorB; cursor.cursorA++; } function pushGroups() { if (differenceGroup.length) { differenceGroups.push(differenceGroup.slice()); differenceGroup = []; } } } function invertGroups(simplifiedImage, differenceGroups, invertedGroups) { var lastGroup = differenceGroups[differenceGroups.length - 1]; var lastElementA = lastGroup[lastGroup.length - 1]; var lastElementB = lastElementA.match; var firstGroup = []; var secondGroup = []; if (differenceGroups[0][0] > 0) { for (var a = 0; a < differenceGroups[0][0]; a++) { firstGroup.push(a); } invertedGroups.invertedGroupsA.push(firstGroup); } if (simplifiedImage.simpleA[differenceGroups[0][0]].match > 0) { firstGroup = []; for (var b = 0; b < simpleA[differenceGroups[0][0]].match; b++) { firstGroup.push(b); } invertedGroups.invertedGroupsB.push(firstGroup); } firstGroup = []; for (var i = 0; i < (differenceGroups.length - 1); i++) { firstGroup = differenceGroups[i]; secondGroup = differenceGroups[i + 1]; var firstGroupLastElementA = firstGroup[firstGroup.length - 1]; var secondGroupFirstElementA = secondGroup[0]; var firstGroupLastElementB = simplifiedImage.simpleA[firstGroupLastElementA].match; var secondGroupFirstElementB = simplifiedImage.simpleA[secondGroupFirstElementA].match; var newGroupA = []; var newGroupB = []; for (var j = firstGroupLastElementA + 1; j < secondGroupFirstElementA; j++) { newGroupA.push(j); } for (var k = firstGroupLastElementB + 1; k < secondGroupFirstElementB; k++) { newGroupB.push(k); } invertedGroups.invertedGroupsA.push(newGroupA); invertedGroups.invertedGroupsB.push(newGroupB); } pushGroupsIntoInverted(lastElementA, simplifiedImage.simpleA); pushGroupsIntoInverted(lastElementB, simplifiedImage.simpleB); function pushGroupsIntoInverted(lastElement, simpleParam) { if (lastElement < simpleParam.length) { var lastGroup = []; for (var i = lastElement + 1; i < simpleParam.length; i++) { lastGroup.push(i); } invertedGroups.invertedGroupsB.push(lastGroup); } } } function arrangeMasks(masks, difs, canvas, arrangeTimeout, maskCallback) { masks.customMask.style.display = difs.main.style.display = 'none'; clearTimeout(arrangeTimeout); arrangeTimeout = setTimeout(function () { masks.customMask.style.display = difs.main.style.display = 'block'; var maskSize = { width: canvas.canvasA.offsetWidth * 2 + canvas.canvasWrapper.offsetWidth * 0.04, height: canvas.canvasWrapper.offsetHeight }; difs.main.style.width = masks.customMask.style.width = maskSize.width + 'px'; difs.main.style.height = masks.customMask.style.height = maskSize.height + 'px'; difs.main.style.top = masks.customMask.style.top = canvas.canvasA.offsettop + 'px'; maskCallback(maskSize); }, 500); } function getElementByPosition(list, position) { for (var i = 0; i < list.length; i++) { if (list[i].offset < position && list[i].offset + list[i].size > position) { return i; } } } function getInvertedGroupByElement(index, isA, invertedGroups) { if (isA) { for (var i = 0; i < invertedGroups.invertedGroupsA.length; i++) { var groupA = invertedGroups.invertedGroupsA[i]; if (groupA.indexOf(index)!== -1) { return i; } } } else { for (var j = 0; j < invertedGroups.invertedGroupsB.length; j++) { var groupB = invertedGroups.invertedGroupsB[j]; if (groupB.indexOf(index)!== -1) { return j; } } } } function lightMask(selectFrom, selectTo, imgSize, maskParam, maskSizeParam, labelParam, rulerParam) { var maxHeight = Math.max(imgSize.imgSizeA.height, imgSize.imgSizeB.height); var proc = 100 / maxHeight; var scale = maskSizeParam.height / maxHeight; var height = selectTo - selectFrom; maskParam.top.style.height = selectFrom * proc + '%'; maskParam.bot.style.top = selectTo * proc + '%'; maskParam.bot.style.height = (imgSize.imgSizeB.height - selectTo) * proc + '%'; labelParam.style.top = (selectFrom + height / 2) * proc + '%'; labelParam.querySelector('.text').innerText = (selectTo - selectFrom) + 'px'; rulerParam.style.height = height * scale + 'px'; labelParam.style.display = 'block'; } function getGroupsSizes(index, invertedGroups, simplifiedImage) { var groupA = invertedGroups.invertedGroupsA[index]; var indexFromA = groupA[0]; var indexToA = groupA[groupA.length - 1]; if (typeof invertedGroups.invertedGroupsB[index]!== 'undefined' && invertedGroups.invertedGroupsB[index].length > 0) { var groupB = invertedGroups.invertedGroupsB[index]; var indexFromB = groupB[0]; var indexToB = groupB[groupB.length - 1]; return { aFrom: simplifiedImage.simpleA[indexFromA].offset, aTo: simplifiedImage.simpleA[indexToA].offset + simplifiedImage.simpleA[indexToA].size, bFrom: simplifiedImage.simpleB[indexFromB].offset, bTo: simplifiedImage.simpleB[indexToB].offset + simplifiedImage.simpleB[indexToB].size }; } else { var bPosition = 0; if (simplifiedImage.simpleA[indexFromA - 1]) { bPosition = simplifiedImage.simpleB[simplifiedImage.simpleA[indexFromA - 1].match].offset + simplifiedImage.simpleB[simplifiedImage.simpleA[indexFromA - 1].match].size; } else if (simplifiedImage.simpleA[indexToA + 1]) { bPosition = simplifiedImage.simpleB[simplifiedImage.simpleA[indexToA + 1].match].offset; } return { aFrom: simplifiedImage.simpleA[indexFromA].offset, aTo: simplifiedImage.simpleA[indexToA].offset + simplifiedImage.simpleA[indexToA].size, bFrom: bPosition, bTo: bPosition }; } } function showAllDifs(wrapper) { var hoverElements = wrapper.querySelectorAll('.hover'); for (var i = 0; i < hoverElements.length; i++) { hoverElements[i].classList.remove('hover'); } } function selectGroup(index, isA, difs, wrapper) { document.querySelectorAll('.customLabel').forEach(function(element) { element.style.display = 'block'; }); showAllDifs(wrapper); if (isA) { if (difs.difsA[index]) { difs.difsA[index].classList.add('hover'); } } else { if (difs.difsB[index]) { difs.difsB[index].classList.add('hover'); } } } function deselectGroups(wrapper) { document.querySelectorAll('.customLabel').forEach(function(element) { element.style.display = 'none'; }); showAllDifs(wrapper); } function getAbsoluteOffset(element) { var offset = { x: element.offsetLeft, y: element.offsetTop }; var parentElement = element.offsetParent; for (var i = 0; i < 100 && parentElement; i++) { offset.x += parentElement.offsetLeft; offset.y += parentElement.offsetTop; parentElement = parentElement.offsetParent; } return offset; } function onImagesReady(mask, imgSize, simplifiedImage, label, ruler, invertedGroups, difs, wrapper) { mask.customMask.onmousemove = function (e) { var masksOffset = getAbsoluteOffset(mask.customMask); var relativePosition = { x: e.clientX - masksOffset.x, y: e.clientY - masksOffset.y }; var isA = relativePosition.x < 0; var ratio = Math.max(imgSize.imgSizeA.height, imgSize.imgSizeB.height) / mask.maskSize.height; var element; if (isA) { element = getElementByPosition(simplifiedImage.simpleA, (relativePosition.y + window.pageYOffset) * ratio); } else { element = getElementByPosition(simplifiedImage.simpleB, (relativePosition.y + window.pageYOffset) * ratio); } if (element!== undefined) { var selectedGroup = getInvertedGroupByElement(element, isA, invertedGroups); if (selectedGroup >= 0 && typeof selectedGroup!= 'undefined') { var sizes = getGroupsSizes(selectedGroup, invertedGroups, simplifiedImage); lightMask(sizes.aFrom, sizes.aTo, imgSize, mask.maskA, mask.maskSize, label.labelA, ruler.rulerA); lightMask(sizes.aFrom, sizes.aTo, imgSize, mask.maskB, mask.maskSize, label.labelB, ruler.rulerB); selectGroup(selectedGroup, isA, difs, wrapper); } } }; mask.customMask.onmouseleave = function () { lightMask(0, imgSize.imgSizeA.height, imgSize, mask.maskA, mask.maskSize, label.labelA, ruler.rulerA); lightMask(0, imgSize.imgSizeB.height, imgSize, mask.maskB, mask.maskSize, label.labelB, ruler.rulerB); deselectGroups(wrapper); }; } } }); ======================= File: report/src/main/webapp/app/app.config.js ======================= <filename>report/src/main/webapp/app/app.config.js /* * AET * * Copyright (C) 2013 Cognifide Limited * * 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. */ require.config({ baseUrl: 'app/', paths: { // **** LIBRARIES **** 'jquery': '../assets/libs/jquery/dist/jquery', 'bootstrap': '../assets/libs/bootstrap-sass-twbs/assets/javascripts/bootstrap', 'angular': '../assets/libs/angular/angular', 'angular-ui-router': '../assets/libs/angular-ui-router/release/angular-ui-router', 'angularAMD': '../assets/libs/angularAMD/angularAMD', 'lodash': '../assets/libs/lodash/dist/lodash', 'angular-bootstrap': '../assets/libs/angular-bootstrap/ui-bootstrap-tpls', 'snowfall': '../assets/js/snowfall/snowfall.min', // **************** AET custom ******************** //components 'testSearchFilter': 'components/testSearch.filter', 'testStatusFilter': 'components/testStatus.filter', 'urlSearchFilter': 'components/urlSearch.filter', 'urlStatusFilter': 'components/urlStatus.filter', 'keyboardShortcutsDirective': 'components/keyboardShortcuts.directive', 'hidePopoversDirective': 'components/hidePopovers.directive', 'compareScreensDirective': 'components/compareScreens.directive', 'winterEdition': 'themes/winterEdition.directive', //services 'endpointConfiguration':'services/endpointConfiguration.service', 'artifactsService':'services/artifacts.service', 'metadataEndpointService':'services/metadataEndpoint.service', 'metadataLoaderService':'services/metadataLoader.service', 'localStorageService':'services/localStorage.service', 'requestParametersService':'services/requestParameters.service', 'metadataCacheService':'services/metadataCache.service', 'metadataService':'services/metadata.service', 'metadataAccessService':'services/metadataAccess.service', 'notesService':'services/notes.service', 'historyService':'services/history.service', 'suiteInfoService':'services/suiteInfo.service', 'patternsService':'services/patterns.service', 'userSettingsService':'services/userSettings.service', 'viewModeService':'services/viewMode.service', //toolbarTop 'toolbarTopController': 'layout/toolbar/toolbarTop.controller', //toolbarBottom 'toolbarBottomController': 'layout/toolbar/toolbarBottom.controller', //sidepanel 'sidepanelDirective': 'layout/sidepanel/sidepanel.directive', 'sidepanelStatusFilterDirective': 'layout/sidepanel/sidepanelStatusFilter.directive', 'sidepanelSearchDirective': 'layout/sidepanel/sidepanelSearch.directive', 'sidepanelToggleLinkDirective': 'layout/sidepanel/toggleLink.directive', 'sidepanelSaveChangesDirective': 'layout/sidepanel/saveChanges.directive', 'sidepanelTruncateUrlsDirective': 'layout/sidepanel/truncateUrls.directive', 'sidepanelController': 'layout/sidepanel/sidepanel.controller', //main 'suiteController': 'layout/main/suite/mainView.suite.controller', 'testController': 'layout/main/test/mainView.test.controller', 'urlController': 'layout/main/url/mainView.url.controller', 'caseFactory': 'layout/main/url/caseFactory.service', 'expandablePanelDirective': 'layout/main/url/expandablePanel.directive', 'filterInformationDirective': 'layout/main/url/filterInformation/filterInformation.directive', 'includedCommentPopoverDirective': 'layout/main/url/includedCommentPopover.directive', //modals 'unsavedChangesModalController': 'layout/modal/unsavedChanges/unsavedChangesModal.controller', 'noteModalController': 'layout/modal/note/noteModal.controller', 'historyModalController': 'layout/modal/history/historyModal.controller' }, shim: { jquery: { exports: '$' }, angular: { exports: 'angular' }, bootstrap: { deps: ['jquery'] }, lodash: { exports: '_' }, 'angular-bootstrap': ['angular'], 'angular-ui-router': ['angular'], 'angularAMD': ['angular'] }, deps: ['app.module'], waitSeconds: 0 }); ======================= File: core/worker/firefox/content/overlay.js ======================= /* * AET * * Copyright (C) 2013 Cognifide Limited * * 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. */ var JSErrorCollector = new function() { var list = []; this.collectedErrors = { push: function (jsError) { list.push(jsError); }, pump: function() { var resp = []; for (var i=0; i<list.length; ++i) { var scriptError = list[i]; resp[i] = { errorMessage: scriptError.errorMessage, sourceName: scriptError.sourceName, lineNumber: scriptError.lineNumber, console: scriptError.console }; } list = []; return resp; }, toString: function() { var s = ""; for (var i=0; i<list.length; ++i) { s += i + ": " + list[i] + "\n"; } return s; } }; this.onLoad = function(event) { // initialization code this.initialize(event); this.initialized = true; }; this.initialize = function(event) { var windowContent = window.getBrowser(); var consoleService = Components.classes["@mozilla.org/consoleservice;1"].getService().QueryInterface(Components.interfaces.nsIConsoleService); if (consoleService) { consoleService.registerListener(JSErrorCollector_ErrorConsoleListener); } var onPageLoad = function(aEvent) { var doc = aEvent.originalTarget; var win = doc.defaultView; if (win) { win.wrappedJSObject.JSErrorCollector_errorsList = Components.utils.cloneInto(JSErrorCollector.collectedErrors.pump(), win.wrappedJSObject); // since firefox 38.6.0 ESR invoking window.JSErrorCollector_errors.pump() always return empty array, lines above is workaround and line below is left intentionally win.wrappedJSObject.JSErrorCollector_errors = Components.utils.cloneInto(JSErrorCollector.collectedErrors,win.wrappedJSObject,{cloneFunctions: true}); } }; windowContent.addEventListener("load", onPageLoad, true); }; this.addError = function(error) { this.collectedErrors.push(error); var labelField = document.getElementById("JSErrorCollector-nb"); labelField.nb = labelField.nb || 0; labelField.nb++; labelField.value = labelField.nb; } }; //Error console listener var JSErrorCollector_ErrorConsoleListener = { observe: function(consoleMessage) { if (document && consoleMessage) { // Try to convert the error to a script error try { var scriptError = consoleMessage.QueryInterface(Components.interfaces.nsIScriptError); var errorCategory = scriptError.category; var sourceName = scriptError.sourceName; if (sourceName.indexOf("about:") == 0 || sourceName.indexOf("chrome:") == 0) { return; // not interested in internal errors } // We're just looking for content JS errors (see https://developer.mozilla.org/en/XPCOM_Interface_Reference/nsIScriptError#Categories) if (errorCategory == "content javascript") { var consoleContent = null; // try to get content from Firebug's console if it exists try { if (window.Firebug && window.Firebug.currentContext) { var doc = Firebug.currentContext.getPanel("console").document; // console.log("doc", doc.body.innerHTML, doc) var logNodes = doc.querySelectorAll(".logRow.logContent span"); var consoleLines = []; for (var i=0; i<logNodes.length; ++i) { var logNode = logNodes[i]; if (!logNode.JSErrorCollector_extracted) { consoleLines.push(logNodes[i].textContent); logNode.JSErrorCollector_extracted = true; } } consoleContent = consoleLines.join("\n"); } } catch (e) { consoleContent = "Error extracting content of Firebug console: " + e.message; } var err = { errorMessage: scriptError.errorMessage, sourceName: scriptError.sourceName, lineNumber: scriptError.lineNumber, console: consoleContent }; console.log("collecting JS error", err) JSErrorCollector.addError(err); } } catch (exception) { // ignore } } return false; } }; window.addEventListener("load", function(e) { JSErrorCollector.onLoad(e); }, false); ======================= File: report/src/main/webapp/app/layout/modal/history/historyModal.controller.js ======================= /* * AET * * Copyright (C) 2013 Cognifide Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ define(['angularAMD'], function (angularAMD) { 'use strict'; angularAMD.controller('historyModalController', historyModalController); function historyModalController($uibModalInstance) { var vm = this; init(); /*************************************** *********** Private methods ********* ***************************************/ function init() { vm.hideSuiteHistory = function() { hideHistory(); }; } function hideHistory() { $uibModalInstance.close(); } } }); ======================= File: report/src/main/webapp/app/layout/sidepanel/sidepanelSearch.directive.js ======================= <reponame>jwadolowski/aet /* * AET * * Copyright (C) 2013 Cognifide Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ define(['angularAMD'], function (angularAMD) { 'use strict'; angularAMD.directive('aetSidepanelSearch', SidepanelSearch); function SidepanelSearch($rootScope, $timeout) { return { restrict: 'AE', link: function (scope, $element) { $element.on('input', onInput); }, controller: function ($scope) { $scope.clearSearch = clearSearchPhrase; } }; function onInput() { $timeout(refreshSearchScope); } function clearSearchPhrase() { $timeout(function () { $rootScope.searchText = ''; refreshSearchScope(); }); } function refreshSearchScope() { updateSearchIcon($rootScope.searchText); $rootScope.$apply(); $rootScope.$broadcast('filter:applied'); } function updateSearchIcon(searchPhrase) { var iconSearch = $('.sidepanel-search-section.glyphicon-search'), iconCancel = $('.sidepanel-search-section.glyphicon-remove'); if (searchPhrase && searchPhrase.length > 0) { iconSearch.hide(); iconCancel.show(); } else { iconSearch.show(); iconCancel.hide(); } } } }); ======================= File: report/src/main/webapp/app/layout/sidepanel/toggleLink.directive.js ======================= /* * AET * * Copyright (C) 2013 Cognifide Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ define(['angularAMD'], function (angularAMD) { 'use strict'; angularAMD.directive('aetToggleLink', [function () { return { restrict: 'AE', scope: { 'type': '@' }, link: function (scope, $element) { var parent = $element.parent(); $element.on('click', function (event) { var targetClass = $(event.target).attr('class'); if (targetClass == 'glyphicon glyphicon-chevron-down') { event.preventDefault(); } if (scope.type == 'test-name') { parent.toggleClass('is-expanded'); } }); } }; }]); }); ======================= File: report/src/main/webapp/app/layout/sidepanel/sidepanelStatusFilter.directive.js ======================= <reponame>jwadolowski/aet<filename>report/src/main/webapp/app/layout/sidepanel/sidepanelStatusFilter.directive.js /* * AET * * Copyright (C) 2013 Cognifide Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ define(['angularAMD'], function (angularAMD) { 'use strict'; angularAMD.directive('aetSidepanelStatusFilter', ['$rootScope', '$timeout', SidepanelStatusFilterDirective]); function SidepanelStatusFilterDirective($rootScope, $timeout) { return { restrict: 'AE', link: init, controller: function ($scope) { $scope.clearFilters = clearActiveFilters; } }; function init(scope, $element) { if (!$rootScope.activeFilters) { $rootScope.activeFilters = []; } $element.popover({ placement: 'bottom', trigger: 'click', content: function () { return $element.find('.dropdown-menu').html(); }, html: true }).on('click', onFilterLabelClick) .parent().on('click', 'input', onFilterChoice); } function onFilterLabelClick() { if (!_.isEmpty($('.filters.popover'))) { var $popoverContent = $('.popover-content'); $rootScope.activeFilters.forEach(function (filter) { $popoverContent .find('p[data-attribute="' + filter + '"]') .siblings() .prop('checked',''); }); } } function onFilterChoice(event) { $timeout(function () { updateActiveFilters(extractActiveFilters(event)); }); } function extractActiveFilters(event) { var activeFilters = angular.copy($rootScope.activeFilters); var $elem = $(event.target), $link = $elem.siblings('p'), toggleStatus = $link.data('attribute'); if (_.indexOf(activeFilters, toggleStatus)!== -1) { _.pull(activeFilters, toggleStatus); } else { activeFilters.push(toggleStatus); } return activeFilters; } function clearActiveFilters() { $timeout(function () { updateActiveFilters([]); }); } function updateActiveFilters(currentFilters) { $rootScope.activeFilters = currentFilters; updateFiltersLabel($rootScope.activeFilters); $rootScope.$apply(); $rootScope.$broadcast('filter:applied'); } function updateFiltersLabel(activeFilters) { var titleElement = $('.filter-list-title p '), iconApply = $('.filter-list-title.apply-filters'), iconCancel = $('.filter-list-title.clear-filters'); if (!_.isEmpty(activeFilters)) { var labelText = ''; activeFilters.forEach(function (filter, index) { labelText +='' + filter.toLowerCase(); if (activeFilters.length - 1 > index) { labelText += ', '; } }); titleElement.html('Filters:'+ labelText); iconApply.hide(); iconCancel.show(); } else { titleElement.html('No filters applied'); iconApply.show(); iconCancel.hide(); } } } }); ======================= File: report/src/main/webapp/app/services/artifacts.service.js ======================= <filename>report/src/main/webapp/app/services/artifacts.service.js /* * AET * * Copyright (C) 2013 Cognifide Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ define(['angularAMD', 'endpointConfiguration','requestParametersService'], function (angularAMD) { 'use strict'; angularAMD.factory('artifactsService', ArtifactsService); /** * Service responsible for fetching artifacts. */ function ArtifactsService($q, $http, endpointConfiguration, requestParametersService) { var service = { getArtifactUrl: getArtifactUrl, getArtifact: getArtifact, getArtifactAsTextUrl: getArtifactAsTextUrl }, requestParams = requestParametersService.get(), endpoint = endpointConfiguration.getEndpoint(); return service; function getArtifactUrl(artifactId) { return endpoint.getUrl + 'artifact?' + 'company=' + requestParams.company + '&project=' + requestParams.project + '&id=' + artifactId; } function getArtifactAsTextUrl(artifactId) { return getArtifactUrl(artifactId) + '&type=text/plain'; } function getArtifact(artifactId) { var deferred = $q.defer(), url = getArtifactUrl(artifactId); return $http({ method: 'GET', url: url, headers: { 'Content-Type': 'text/plain' } }).then(function (data) { deferred.resolve(data.data); return deferred.promise; }).catch(function (exception) { handleFailed('Failed to load artifact'+ artifactId, exception); }); } /*************************************** *********** Private methods ********* ***************************************/ function handleFailed(text, exception) { console.error(text, requestParams, exception); alert(text); } } }); ======================= File: report/src/main/webapp/gulpfile.babel.js ======================= /* * AET * * Copyright (C) 2013 Cognifide Limited * * 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. */ import gulp from 'gulp'; import browserify from 'browserify'; import babelify from 'babelify'; import source from 'vinyl-source-stream'; import buffer from 'vinyl-buffer'; import uglify from 'gulp-uglify'; import sourceMaps from 'gulp-sourcemaps'; import concat from 'gulp-concat'; import glob from 'glob'; import sass from 'gulp-sass'; import cleanCSS from 'gulp-clean-css'; import browserSync from 'browser-sync'; import jshint from 'gulp-jshint'; import csslint from 'gulp-csslint'; import jshintSummary from 'jshint-summary'; import bower from 'gulp-bower'; gulp.task("parseSCSS", ["installLibs"], () => { gulp.src('./assets/sass/*.scss') .pipe(sourceMaps.init()) .pipe(sass()) .pipe(concat('main.css')) .pipe(cleanCSS()) .pipe(sourceMaps.write('./')) .pipe(gulp.dest('./assets/css')) .pipe(browserSync.reload({stream:true})); }); //this task is kinda useless now, but may come handy in the future gulp.task('parseJS', () => { const files = glob.sync('./app/*.js'); return browserify({entries: files, debug: true}) .transform("babelify", { presets: ["es2015"] }) .bundle() .pipe(source('bundle.js')) .pipe(buffer()) .pipe(sourceMaps.init()) .pipe(uglify()) .pipe(sourceMaps.write('./')) .pipe(gulp.dest('./dist/js')) .pipe(browserSync.reload({stream:true})); }); gulp.task('lintJS', function() { return gulp.src('./app/**/*.js') .pipe(jshint('.jshintrc')) .pipe(jshint.reporter('jshint-summary', { verbose: true, reasonCol: 'cyan,bold' })); }); gulp.task('installLibs', function() { return bower({ directory: 'assets/libs'}); }) gulp.task('lintCSS', function() { gulp.src('./assets/css/main.css') .pipe(csslint()) .pipe(csslint.formatter()); }); gulp.task('watch', ['parseSCSS', 'lintJS'], () => { browserSync.init({ port: 9000, server: { baseDir: "./", } }); gulp.watch('./assets/sass/*.scss', ['parseSCSS']); gulp.watch('./app/**/*.js', ['lintJS']).on('change', browserSync.reload); }); gulp.task('default',['watch']); gulp.task('build', ['installLibs', 'parseSCSS', 'lintJS']); ======================= File: report/src/main/webapp/app/services/metadataLoader.service.js ======================= <reponame>jwadolowski/aet /* * AET * * Copyright (C) 2013 Cognifide Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ define(['angularAMD','metadataService','metadataEndpointService'], function (angularAMD) { 'use strict'; angularAMD.factory('metadataLoaderService', MetadataLoaderService); /** * Service fetches metadata and inits metadata service. */ function MetadataLoaderService($rootScope, $q, metadataService, metadataEndpointService) { var deferred = null; return { setup: function () { if (deferred === null) { $rootScope.metadataLoadingStatus = 'IN_PROGRESS'; deferred = $q.defer(); metadataEndpointService.getMetadata() .then(function (aetMetadataResponse) { metadataService.ingestData(aetMetadataResponse); $rootScope.metadataLoadingStatus = 'SUCCESS'; deferred.resolve(); }) .catch(handleFailed); } return deferred.promise; } }; /*************************************** *********** Private methods ********* ***************************************/ function handleFailed(exception) { console.error('Can\'t setup suite metadata!', exception); $rootScope.metadataLoadingStatus = 'FAILED'; alert('Failed to load report data!'); } } }); ======================= File: integration-tests/sample-site/src/main/webapp/assets/snippets/change-bg-snippet.js ======================= <gh_stars>100-1000 document.body.style.background = 'blue'; ======================= File: report/src/main/webapp/app/layout/main/url/mainView.url.controller.js ======================= <filename>report/src/main/webapp/app/layout/main/url/mainView.url.controller.js /* * AET * * Copyright (C) 2013 Cognifide Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ define([], function () { 'use strict'; return ['$rootScope', '$stateParams', '$uibModal','metadataAccessService', 'viewModeService', 'notesService', 'patternsService', 'userSettingsService', 'caseFactory', MainViewUrlController]; function MainViewUrlController($rootScope, $stateParams, $uibModal, metadataAccessService, viewModeService, notesService, patternsService, userSettingsService, caseFactory) { var vm = this; $rootScope.$on('metadata:changed', updateUrlView); $('[data-toggle="popover"]').popover({ placement: 'bottom' }); setupUrlView(); /*************************************** *********** Private methods ********* ***************************************/ function setupUrlView() { vm.displayCommentModal = displayCommentModal; vm.acceptCase = acceptCase; vm.revertCase = revertCase; vm.toggleMask = toggleMask; vm.toggleFullSource = toggleFullSource; vm.cases = getUrlCases($stateParams.test, $stateParams.url); vm.urlName = $stateParams.url; } function updateUrlView() { _.forEach(vm.cases, function (testcase) { testcase.update(); }); } function getUrlCases(testName, urlName) { var urlSteps = metadataAccessService.getUrlSteps(testName, urlName); var cases = []; _.forEach(urlSteps, function (step) { _.forEach(step.comparators, function (comparator, index) { cases.push(caseFactory.getCase(step, comparator, index)); }); }); return cases; } function acceptCase(currentCase) { patternsService.updateCase($stateParams.test, $stateParams.url, currentCase.step.index, currentCase.index); } function revertCase(currentCase) { patternsService.revertCase($stateParams.test, $stateParams.url, currentCase.step.index, currentCase.index); } function displayCommentModal(currentCase) { $uibModal.open({ animation: true, templateUrl: 'app/layout/modal/note/noteModal.view.html', controller: 'noteModalController', controllerAs: 'noteModal', resolve: { model: function () { return currentCase; }, viewMode: function () { return viewModeService.COMPARATOR; }, notesService: function () { return notesService; } } }); } function toggleMask() { $rootScope.maskVisible = userSettingsService.toggleScreenshotMask(); } function toggleFullSource() { $rootScope.fullSourceVisible = userSettingsService.toggleFullSource(); } } }); ======================= File: report/src/main/webapp/app/services/patterns.service.js ======================= <filename>report/src/main/webapp/app/services/patterns.service.js /* * AET * * Copyright (C) 2013 Cognifide Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ define(['angularAMD','metadataService','metadataAccessService'], function (angularAMD) { 'use strict'; angularAMD.factory('patternsService', PatternsService); /** * Service responsible for controlling metadata patterns. */ function PatternsService(metadataService, metadataAccessService) { var service = { updateSuite: updateSuite, revertSuite: revertSuite, updateTest: updateTest, revertTest: revertTest, updateUrl: updateUrl, revertUrl: revertUrl, updateCase: updateCase, revertCase: revertCase }; return service; function updateSuite() { var suite = metadataAccessService.getSuite(); _.forEach(suite.tests, function (test) { updateTest(test.name, false); }); notifyMetadataUpdated(true); } function revertSuite() { var suite = metadataAccessService.getSuite(); _.forEach(suite.tests, function (test) { revertTest(test.name, false); }); notifyMetadataUpdated(true); } function updateTest(testName, shouldNotify) { var test = metadataAccessService.getTest(testName); _.forEach(test.urls, function (url) { updateUrl(testName, url.name, false); }); notifyMetadataUpdated(shouldNotify); } function revertTest(testName, shouldNotify) { var test = metadataAccessService.getTest(testName); _.forEach(test.urls, function (url) { revertUrl(testName, url.name, false); }); notifyMetadataUpdated(shouldNotify); } function updateUrl(testName, urlName, shouldNotify) { var url = metadataAccessService.getUrl(testName, urlName); _.filter(url.steps, isCollectorWithPattern).forEach(function (step) { _.forEach(step.comparators, function (comparator) { updateComparator(step, comparator, false); }); }); notifyMetadataUpdated(shouldNotify); } function revertUrl(testName, urlName, shouldNotify) { var url = metadataAccessService.getUrl(testName, urlName); _.filter(url.steps, isCollectorWithPattern).forEach(function (step) { _.forEach(step.comparators, function (comparator) { revertComparator(step, comparator, false); }); }); notifyMetadataUpdated(shouldNotify); } function updateCase(testName, urlName, stepIndex, comparatorIndex) { var step = metadataAccessService.getStep(testName, urlName, stepIndex), result = false; if (isCollectorWithPattern(step)) { result = updateComparator(step, step.comparators[comparatorIndex], true); } return result; } function revertCase(testName, urlName, stepIndex, comparatorIndex) { var step = metadataAccessService.getStep(testName, urlName, stepIndex), result = false; if (isCollectorWithPattern(step)) { result = revertComparator(step, step.comparators[comparatorIndex], true); } return result; } /*************************************** *********** Private methods ********* ***************************************/ function updateComparator(step, comparator, shouldNotify) { var result = false; if (isCollectorWithPattern(step) && isStepComparatorRebaseable( comparator)) { result =!comparator.stepResult.previousStatus; if (result) { step.updatePatternStatistics(); step.oldPattern = step.pattern; step.pattern = step.stepResult.artifactId; comparator.hasNotSavedChanges = true; } notifyMetadataUpdated(shouldNotify); } return result; } function revertComparator(step, comparator, shouldNotify) { var result = false; if (isCollectorWithPattern(step) && isStepComparatorRebaseable( comparator)) { if (comparator.stepResult.wasAcceptable) { step.revertPatternStatistics(); step.pattern = step.oldPattern; delete step.oldPattern; delete comparator.hasNotSavedChanges; } notifyMetadataUpdated(shouldNotify); } return result; } function isCollectorWithPattern(step) { return step && step.comparators && step.pattern; } function isStepComparatorRebaseable(comparator) { return comparator && comparator.stepResult && comparator.stepResult.rebaseable; } function notifyMetadataUpdated(shouldNotify) { if (shouldNotify) { metadataService.notifyMetadataChanged(); metadataService.saveChangesLocally(); } } } }); ======================= File: report/src/main/webapp/app/services/history.service.js ======================= <reponame>jwadolowski/aet /* * AET * * Copyright (C) 2013 Cognifide Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ define(['angularAMD', 'endpointConfiguration','suiteInfoService'], function (angularAMD) { 'use strict'; angularAMD.factory('historyService', historyService); /** * Service responsible for fetching suite's history */ function historyService($rootScope, $http, endpointConfiguration, suiteInfoService) { var suiteHeaders; var endpointUrl = endpointConfiguration.getEndpoint().getUrl; var service = { getNextVersion: getNextVersion, getPreviousVersion: getPreviousVersion, fetchHistory: fetchHistory, }; return service; function fetchHistory(currentVersion, fetchCallback) { $rootScope.selectedVersion = currentVersion; getSuiteHistory(endpointUrl, suiteHeaders, suiteInfoService, $rootScope, $http, function () { fetchCallback(); }); } function buildApiPath(endpointUrl, $allParametersList) { return endpointUrl + 'history' + '?' + $allParametersList[0] + '&' + $allParametersList[1] + '&' + $allParametersList[2]; } function getPreviousVersion(currentVersion) { var prevVersion = null; $rootScope.suiteHeaders.forEach(function(suiteHeader, index) { if(suiteHeader.version === currentVersion) { if($rootScope.suiteHeaders[index + 1]) { prevVersion = $rootScope.suiteHeaders[index + 1].version; } } }); return prevVersion; } function getNextVersion(currentVersion) { var nextVersion = null; $rootScope.suiteHeaders.forEach(function(suiteHeader, index) { if(suiteHeader.version === currentVersion) { if($rootScope.suiteHeaders[index - 1]) { nextVersion = $rootScope.suiteHeaders[index - 1].version; } } }); return nextVersion; } function getSuiteHistory(endpointUrl, suiteHeaders, suiteInfoService, $rootScope, $http, historyCallback) { $rootScope.data = 'test'; var cUrl = new URL(window.location.href); var company = cUrl.searchParams.get('company'); var project = cUrl.searchParams.get('project'); var suite = cUrl.searchParams.get('suite'); if (suite === null) { var suiteInfo = suiteInfoService.getInfo(); suite = suiteInfo.name; } var allParametersList = ['company=' + company, 'project=' + project,'suite=' + suite]; return $http({ method: 'GET', url: buildApiPath(endpointUrl, allParametersList), headers: { 'Content-Type': 'text/plain' } }).then(function (response) { $rootScope.data = response.data; suiteHeaders = response.data; for (var i = 0; i < suiteHeaders.length; i++) { var correlationIdPart = suiteHeaders[i].correlationId.split('-'); var version = suiteHeaders[i].version; var company = company; var project = project; var suite = suite; var timestamp = correlationIdPart[correlationIdPart.length - 1]; suiteHeaders[i] = { company: company, project: project, suite: suite, version: version, timestamp: timestamp, selectedVersion: null, isRebased: false, }; if (typeof suiteHeaders[i - 1]!== 'undefined') { if (suiteHeaders[i].timestamp === suiteHeaders[i - 1].timestamp) { suiteHeaders[i - 1].isRebased = true; } } } $rootScope.suiteHeaders = suiteHeaders; var reportPath = window.location.href; var reportUrl = new URL(reportPath); var currentVersion = reportUrl.searchParams.get('version'); if (currentVersion === null) { $rootScope.reportPath = location.protocol + '//' + location.host + location.pathname + window.location.search; } else { reportPath = window.location.search.split('&'); reportPath = reportPath[0] + '&' + reportPath[1] + '&' + reportPath[2]; $rootScope.reportPath = location.protocol + '//' + location.host + location.pathname + reportPath; } if(reportUrl.searchParams.get('correlationId')) { reportPath = '?' + allParametersList[0] + '&' + allParametersList[1] + '&' + allParametersList[2]; $rootScope.reportPath = location.protocol + '//' + location.host + location.pathname + reportPath; } historyCallback(); }, function errorCallback(response) { $rootScope.fullSuiteName = response.data.message; }); } } }); ======================= File: integration-tests/sample-site/src/main/webapp/assets/secured/change-bg-snippet.js ======================= <gh_stars>100-1000 document.body.style.background = 'yellow'; ======================= File: integration-tests/sample-site/src/main/webapp/sanity/comparators/cookie/failed.jsp ======================= <%-- AET Copyright (C) 2013 Cognifide Limited 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. --%> <% java.text.SimpleDateFormat dt = new java.text.SimpleDateFormat("EEEdMMMyyyyHHmmssSSSZ",java.util.Locale.ENGLISH); java.util.Date date = new java.util.Date(); Cookie dynamicCookieValue = new Cookie("DynamicSampleCookieName",dt.format(date)); Cookie dynamicCookieName = new Cookie(dt.format(date),"staticCookieValue"); dynamicCookieValue.setMaxAge(60*60*24); // expire cookie after 60 second in order to have it cleared for next run dynamicCookieName.setMaxAge(60); response.addCookie( dynamicCookieValue ); response.addCookie( dynamicCookieName ); %> <%@ include file="/includes/basePage.jsp" %> ======================= File: integration-tests/sample-site/src/main/webapp/sanity/comparators/clientsideperformance/success.jsp ======================= <%-- AET Copyright (C) 2013 Cognifide Limited 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. --%> <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <meta charset="utf-8"/> <title>Client Side Performance</title> </head> <body> <h1>Hello World!</h1> <p>This is sample test page</p> </body> </html> ======================= File: integration-tests/sample-site/src/main/webapp/sanity/comparators/w3c/failed_no_ignore_warnings.jsp ======================= <%-- AET Copyright (C) 2013 Cognifide Limited Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --%> <%@ include file="/includes/header.jsp" %> <%@ include file="/includes/bodyContent.jsp" %> <ul class="nav navbar-nav"> <li class="dropdown"><a class="dropdown-toggle" data-toggle="dropdown" href="#" id="themes">Dropdown <span class="caret"></span></a> <ul class="dropdown-menu" aria-labelledby="dropdown"> <li><a href="#">Default</a></li> <li class="divider"></li> <li><a href="#">Option</a></li> <li><a href="#">Second option</a></li> <li><a href="#/">Last option</a></li> </ul></li> <li><a href="#">Help</a></li> <li><a href="http://news.bootswatch.com">Blog</a></li> </ul> <%@ include file="/includes/footer.jsp" %> ======================= File: integration-tests/sample-site/src/main/webapp/sanity/comparators/source/failed.jsp ======================= <gh_stars>100-1000 <%-- AET Copyright (C) 2013 Cognifide Limited Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --%> <%@ include file="/includes/header.jsp"%> <% java.text.SimpleDateFormat dt = new java.text.SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss.SSSZ",java.util.Locale.ENGLISH); java.util.Date date = new java.util.Date(); %> <div class="panel panel-default" id="date-panel"> <div class="panel-body"> The time is now <%= dt.format(date) %> </div> </div> <%@ include file="/includes/bodyContent.jsp"%> <%@ include file="/includes/footer.jsp"%> ======================= File: integration-tests/sample-site/src/main/webapp/sanity/comparators/layout/long_expanding_page.jsp ======================= <reponame>jwadolowski/aet <%-- AET Copyright (C) 2013 Cognifide Limited 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. --%> <%-- This page simulates a page that takes a long time to load. The final height of the page is above 12k pixels. --%> <script> window.onload = function () { var counter = 0; var looper = setInterval(function() { counter++; console.log("Counter is: " + counter); var emptyDiv = document.createElement("div"); emptyDiv.style = "height: 1000px"; var src = document.getElementById("enclosingDiv"); src.appendChild(emptyDiv); if (counter >= 12) { clearInterval(looper); } }, 100); <%-- TODO: Change 12 iterations to 30 when (https://github.com/Cognifide/aet/pull/387) is merged. --%> }; </script> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@ include file="/includes/header.jsp" %> <div id="enclosingDiv"></div> <%@ include file="dynamic_content.jsp" %> ======================= File: integration-tests/sample-site/src/main/webapp/includes/accessibility/footer.jsp ======================= <filename>integration-tests/sample-site/src/main/webapp/includes/accessibility/footer.jsp <%-- AET Copyright (C) 2013 Cognifide Limited 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. --%> <!-- Footer --> <footer> <div class="row"> <div class="col-lg-12"> <p> Made by <a href="http://thomaspark.me" rel="nofollow">Thomas Park</a>. </p> <p> Contact him at <a href="mailto:<EMAIL>"><EMAIL></a>. </p> <p> Code released under the <a href="https://github.com/thomaspark/bootswatch/blob/gh-pages/LICENSE">MIT License</a>. </p> <p> Based on <a href="http://getbootstrap.com" rel="nofollow">Bootstrap</a>. </p> <p> Icons from <a href="http://fortawesome.github.io/Font-Awesome/" rel="nofollow">Font Awesome</a>. </p> <p> Web fonts from <a href="http://www.google.com/webfonts" rel="nofollow">Google</a>. </p> </div> </div> </footer> </div> <!-- /.container --> <!-- Bootstrap core JavaScript ================================================== --> <!-- Placed at the end of the document so the pages load faster --> <script src="/sample-site/assets/demo_files/jquery.min.js"></script> <script src="/sample-site/assets/demo_files/bootstrap.min.js"></script> <!-- IE10 viewport hack for Surface/desktop Windows 8 bug --> <script src="/sample-site/assets/demo_files/ie10-viewport-bug-workaround.js"></script> </body> </html> ======================= File: integration-tests/sample-site/src/main/webapp/sanity/comparators/source/random-empty-lines.jsp ======================= <filename>integration-tests/sample-site/src/main/webapp/sanity/comparators/source/random-empty-lines.jsp <%-- AET Copyright (C) 2013 Cognifide Limited Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --%> <%@ include file="/includes/header.jsp" %> <!--[if IE]> <% long tmp = System.currentTimeMillis(); do { out.print("\r\n-\r\n"); for (byte i = 0; i < tmp % 10; ++i) { out.print("\n"); } out.print("\r\n-\r\n"); for (byte i = 0; i < tmp % 10; ++i) { out.print("\r"); } tmp /= 10; } while (tmp > 0); %> <![endif]--> <%@ include file="/includes/bodyContent.jsp" %> <%@ include file="/includes/footer.jsp" %> ======================= File: integration-tests/sample-site/src/main/webapp/includes/bodyContent.jsp ======================= <%-- AET Copyright (C) 2013 Cognifide Limited 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. --%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <div class="navbar navbar-default navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <a href="#" class="navbar-brand">Navbar</a> <button class="navbar-toggle" type="button" data-toggle="collapse" data-target="#navbar-main"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> </div> <div class="navbar-collapse collapse" id="navbar-main"> <ul class="nav navbar-nav"> <li class="dropdown"><a class="dropdown-toggle" data-toggle="dropdown" href="#" id="themes">Dropdown <span class="caret"></span></a> <ul class="dropdown-menu"> <li><a href="#">Default</a></li> <li class="divider"></li> <li><a href="#">Option</a></li> <li><a href="#">Second option</a></li> <li><a href="#">Last option</a></li> </ul></li> <li><a href="#">Help</a></li> <li><a href="#">Blog</a></li> </ul> <ul class="nav navbar-nav navbar-right"> <li><a href="#" target="_blank">Some fun</a></li> </ul> </div> </div> </div> <div class="container"> <div class="page-header" id="banner"> <div class="row"> <div class="col-lg-8 col-md-7 col-sm-6"> <h1>AET Demo Page</h1> <p class="lead">for sanity tests</p> <p class="lead"> build with <a href="http://getbootstrap.com/">Bootstrap</a> and <a href="http://bootswatch.com/">Bootswatch</a> </p> </div> <div class="col-lg-4 col-md-5 col-sm-6"> <div class="sponsor"> <img src="/sample-site/assets/demo_files/logo.png" alt="Bootswatch" /> </div> </div> </div> </div> <div class="bs-docs-section"> <div class="row"> <p class="lead">AET is a tool that can be used to automate testing developed by Cognifide.</p> <p class="lead">The application allows to create regression tests easily and quickly and then to analyze their results (layout comparison, potential JavaScript and W3C validation errors, HTTP status codes).</p> </div> </div> <!-- Typography --> <div class="bs-docs-section"> <div class="row"> <div class="col-lg-12"> <div class="page-header"> <h1 id="type">Typography</h1> </div> </div> </div> <!-- Headings --> <div class="row"> <div class="col-lg-4"> <div class="bs-component"> <h1>Heading 1</h1> <h2>Heading 2</h2> <h3>Heading 3</h3> <h4>Heading 4</h4> <h5>Heading 5</h5> <h6>Heading 6</h6> <p class="lead">Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.</p> </div> </div> <div class="col-lg-4"> <div class="bs-component"> <h2>Example body text</h2> <p> Nullam quis risus eget <a href="#">urna mollis ornare</a> vel eu leo. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nullam id dolor id nibh ultricies vehicula. </p> <p> <small>This line of text is meant to be treated as fine print.</small> </p> <p> The following snippet of text is <strong>rendered as bold text</strong>. </p> <p> The following snippet of text is <em>rendered as italicized text</em>. </p> <p> An abbreviation of the word attribute is <abbr title="attribute">attr</abbr>. </p> </div> </div> <div class="col-lg-4"> <div class="bs-component"> <h2>Emphasis classes</h2> <p class="text-muted">Fusce dapibus, tellus ac cursus commodo, tortor mauris nibh.</p> <p class="text-primary">Nullam id dolor id nibh ultricies vehicula ut id elit.</p> <p class="text-warning">Etiam porta sem malesuada magna mollis euismod.</p> <p class="text-danger">Donec ullamcorper nulla non metus auctor fringilla.</p> <p class="text-success">Duis mollis, est non commodo luctus, nisi erat porttitor ligula.</p> <p class="text-info">Maecenas sed diam eget risus varius blandit sit amet non magna.</p> </div> </div> </div> <!-- Blockquotes --> <div class="row"> <div class="col-lg-12"> <h2 id="type-blockquotes">Blockquotes</h2> </div> </div> <div class="row"> <div class="col-lg-6"> <div class="bs-component"> <blockquote> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer posuere erat a ante.</p> <small>Someone famous in <cite title="Source Title">Source Title</cite></small> </blockquote> </div> </div> <div class="col-lg-6"> <div class="bs-component"> <blockquote class="pull-right"> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer posuere erat a ante.</p> <small>Someone famous in <cite title="Source Title">Source Title</cite></small> </blockquote> </div> </div> </div> </div> <!-- Forms --> <div class="bs-docs-section"> <div class="row"> <div class="col-lg-12"> <div class="page-header"> <h1 id="forms">Forms</h1> </div> </div> </div> <div class="row"> <div class="col-lg-6"> <div class="well bs-component"> <form class="form-horizontal"> <fieldset> <legend>Legend</legend> <div class="form-group"> <label for="inputEmail" class="col-lg-2 control-label">Email</label> <div class="col-lg-10"> <input type="email" class="form-control" id="inputEmail" placeholder="Email" /> </div> </div> <div class="form-group"> <label for="inputPassword" class="col-lg-2 control-label">Password</label> <div class="col-lg-10"> <input type="password" class="form-control" id="inputPassword" placeholder="Password" /> <div class="checkbox"> <label> <input type="checkbox" /> Checkbox </label> </div> </div> </div> <div class="form-group"> <label for="textArea" class="col-lg-2 control-label">Textarea</label> <div class="col-lg-10"> <textarea class="form-control" rows="3" id="textArea"></textarea> <span class="help-block">A longer block of help text that breaks onto a new line and may extend beyond one line.</span> </div> </div> <div class="form-group"> <label class="col-lg-2 control-label">Radios</label> <div class="col-lg-10"> <div class="radio"> <label> <input type="radio" name="optionsRadios" id="optionsRadios1" value="option1" checked="" /> Option one is this </label> </div> <div class="radio"> <label> <input type="radio" name="optionsRadios" id="optionsRadios2" value="option2" /> Option two can be something else </label> </div> </div> </div> <div class="form-group"> <div class="col-lg-10 col-lg-offset-2"> <button class="btn btn-default">Cancel</button> <button type="submit" class="btn btn-primary">Submit</button> </div> </div> </fieldset> </form> </div> </div> <div class="col-lg-4 col-lg-offset-1"> <form class="bs-component"> <div class="form-group"> <label class="control-label" for="focusedInput">Focused input</label> <input class="form-control" id="focusedInput" type="text" value="This is focused..." /> </div> <div class="form-group"> <label class="control-label" for="disabledInput">Disabled input</label> <input class="form-control" id="disabledInput" type="text" placeholder="Disabled input here..." disabled="" /> </div> <div class="form-group has-warning"> <label class="control-label" for="inputWarning">Input warning</label> <input type="text" class="form-control" id="inputWarning" /> </div> <div class="form-group has-error"> <label class="control-label" for="inputError">Input error</label> <input type="text" class="form-control" id="inputError" /> </div> <div class="form-group has-success"> <label class="control-label" for="inputSuccess">Input success</label> <input type="text" class="form-control" id="inputSuccess" /> </div> <div class="form-group"> <label class="control-label" for="inputLarge">Large input</label> <input class="form-control input-lg" type="text" id="inputLarge" /> </div> <div class="form-group"> <label class="control-label" for="inputDefault">Default input</label> <input type="text" class="form-control" id="inputDefault" /> </div> <div class="form-group"> <label class="control-label" for="inputSmall">Small input</label> <input class="form-control input-sm" type="text" id="inputSmall" /> </div> <div class="form-group"> <label class="control-label">Input addons</label> <div class="input-group"> <span class="input-group-addon">$</span> <input type="text" class="form-control" /> <span class="input-group-btn"> <button class="btn btn-default" type="button">Button</button> </span> </div> </div> </form> </div> </div> </div> <!-- Footer --> <footer> <div class="row"> <div class="col-lg-12"> <p> Made by <a href="http://thomaspark.me" rel="nofollow">Thomas Park</a>. Contact him at <a href="mailto:<EMAIL>"><EMAIL></a>. </p> <p> Code released under the <a href="https://github.com/thomaspark/bootswatch/blob/gh-pages/LICENSE">MIT License</a>. </p> <p> Based on <a href="http://getbootstrap.com" rel="nofollow">Bootstrap</a>. Icons from <a href="http://fortawesome.github.io/Font-Awesome/" rel="nofollow">Font Awesome</a>. Web fonts from <a href="http://www.google.com/webfonts" rel="nofollow">Google</a>. </p> </div> </div> </footer> </div> <!-- /.container --> <!-- Bootstrap core JavaScript ================================================== --> <!-- Placed at the end of the document so the pages load faster --> <c:choose> <c:when test="${combineJs}"> <script src="/sample-site/assets/demo_files/combined.js"></script> </c:when> <c:otherwise> <script src="/sample-site/assets/demo_files/jquery.min.js"></script> <script src="/sample-site/assets/demo_files/bootstrap.min.js"></script> <!-- IE10 viewport hack for Surface/desktop Windows 8 bug --> <script src="/sample-site/assets/demo_files/ie10-viewport-bug-workaround.js"></script> </c:otherwise> </c:choose> ======================= File: integration-tests/sample-site/src/main/webapp/includes/header.jsp ======================= <%-- AET Copyright (C) 2013 Cognifide Limited 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. --%> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="icon" href="/sample-site/assets/demo_files/favicon.ico" /> <title>AET Demo Page</title> <!-- Bootstrap core CSS --> <link rel="stylesheet" href="/sample-site/assets/demo_files/bootstrap.css" media="screen" /> <link rel="stylesheet" href="/sample-site/assets/demo_files/bootswatch.min.css" /> </head> <body> ======================= File: integration-tests/sample-site/src/main/webapp/sanity/modifiers/wait-for-page-loaded/delay.jsp ======================= <gh_stars>100-1000 <%-- AET Copyright (C) 2013 Cognifide Limited 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. --%> <% java.text.SimpleDateFormat dt = new java.text.SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss.SSSZ", java.util.Locale.ENGLISH); java.util.Date date = new java.util.Date(); %> <div class="panel-body" id="changeAfterDelay"> The time is now <%= dt.format(date) %> </div> <div class="bs-docs-section"> <div class="row"> <div class="col-lg-12"> <div class="bs-component"> <blockquote> <p id="texts"></p> </blockquote> </div> </div> </div> </div> <script> var list = document.getElementById("texts"); var elementToChange = document.getElementById("changeAfterDelay"); var TIMEOUT_LIMIT = 10; var MIDDLE_OF_TIMEOUT_LIMIT = 5; var COUNTER = 0; function addElements(n) { for (var i = 0; i < n; i++) { var paragraph = document.createElement("p"); var text = document.createTextNode("AET "); paragraph.appendChild(text); list.appendChild(paragraph); } } addElements(5); for (var t = 1; t <= TIMEOUT_LIMIT; ++t) { setTimeout(function () { addElements(5); if (COUNTER == (MIDDLE_OF_TIMEOUT_LIMIT)) { elementToChange.innerHTML = 'Final Text That is displayed after timeout while page elements are still loading.'; } ++COUNTER; }, t * 1000); } </script> ======================= File: integration-tests/sample-site/src/main/webapp/sanity/modifiers/cookie/page.jsp ======================= <gh_stars>100-1000 <%-- AET Copyright (C) 2013 Cognifide Limited Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --%> <%@ include file="/includes/header.jsp" %> <% Cookie[] cookies = request.getCookies(); boolean foundCookie = false; for(int i = 0; i < cookies.length; i++) { Cookie c = cookies[i]; if (c.getName().equals("sampleCookieName")) { foundCookie = true; } } if (!foundCookie) { java.util.Date date = new java.util.Date(); out.println(date); } %> <%@ include file="/includes/bodyContent.jsp" %> <%@ include file="/includes/footer.jsp" %> ======================= File: integration-tests/sample-site/src/main/webapp/sanity/modifiers/login/loginForm.jsp ======================= <%-- AET Copyright (C) 2013 Cognifide Limited Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --%> <%@ include file="/includes/header.jsp" %> <h1>LoginForm:</h1> <form name="login" method="POST" > <input id="input-username" type="text" name="j_username" > <input id="input-password" type="password" name="j_password" > <input id="input-submit" type="submit" value="Submit" /> </form> <br/> <h1>Just show posted values:</h1> <ul> <li><p><b>Login:</b> <%= request.getParameter("j_username")%> </p></li> <li><p><b>Pass:</b> <%= request.getParameter("j_password")%> </p></li> </ul> <%-- set cookie based on posta parameters --%> <% String user = request.getParameter("j_username"); String pass = request.getParameter("j_password"); Cookie loginToken = new Cookie("login-token", user+"_"+pass); response.addCookie(loginToken); %> <%-- set static cookie --%> <% Cookie staticCookie = new Cookie("static-cookie", "cookievalue"); response.addCookie(staticCookie); %> <%@ include file="/includes/footer.jsp" %> ======================= File: documentation/src/main/resources/templates/package.json ======================= { "name": "aet-documentation", "description": "AET Documentation", "version": "${project.version}", "scripts": { "doctoc": "node node_modules/doctoc/doctoc.js --github --maxlevel 3./wiki/releases/${project.version}/Documentation-${project.version}.md" }, "devDependencies": { "doctoc": "^1.3.0", "fs-extra": "^0.30.0", "grunt": "^0.4.5", "grunt-cli": "^1.2.0", "grunt-contrib-copy": "^1.0.0", "grunt-json-generator": "^0.1.0", "markdown-include": "^0.4.3", "matchdep": "^1.0.1" } } ======================= File: core/jobs/src/test/resources/mock/SourceComparator/expected-result.json ======================= <gh_stars>0 { "deltas": [], "sourceCompareType": "ALL", "status": "SUCCESS", "properties": { "comparatorTitle": "", "testName": "", "url": "", "urlName": "", "collectorModule": "", "collectorModuleName": "", "comparatorModule": "", "comparatorModuleName": "" }, "hasPattern": true } ======================= File: core/jobs/src/test/resources/mock/StatusCodesComparator/not-existing-page-404-result.json ======================= { "statusCodes": [ { "code": 404, "url": "http://aet-vagrant/sample-site/sanity/comparators/statuscodes/noneexistingPage404.jsp", "excluded": false }, { "code": 0, "url": "http://aet-vagrant/favicon.ico", "excluded": false } ], "filteredStatusCodes": [ { "code": 404, "url": "http://aet-vagrant/sample-site/sanity/comparators/statuscodes/noneexistingPage404.jsp", "excluded": false } ], "excludedStatusCodes": [] } ======================= File: core/jobs/src/test/resources/mock/JsErrorsComparator/data-result.json ======================= [ { "errorMessage": "ReferenceError: nonExistingVariable is not defined", "sourceName": "http://anotherbuggypage.com", "lineNumber": 387 }, { "errorMessage": "ReferenceError: nonExistingJsFunction is not defined", "sourceName": "http://somebuggypage.com", "lineNumber": 20 } ] ======================= File: core/jobs/src/test/resources/mock/StatusCodesComparator/default-range-400-600-errors-result.json ======================= <filename>core/jobs/src/test/resources/mock/StatusCodesComparator/default-range-400-600-errors-result.json { "statusCodes": [ { "code": 400, "url": "http://aet-vagrant/sample-site/sanity/comparators/statuscodes/noneexistingPage404.jsp", "excluded": false }, { "code": 600, "url": "https://www.google.com/", "excluded": false } ], "filteredStatusCodes": [ { "code": 400, "url": "http://aet-vagrant/sample-site/sanity/comparators/statuscodes/noneexistingPage404.jsp", "excluded": false }, { "code": 600, "url": "https://www.google.com/", "excluded": false } ], "excludedStatusCodes": [] } ======================= File: documentation/src/main/wiki/JSErrorsDataFilter.md ======================= #### JS Errors Data Filter Js Errors Data Filter filters JS Errors Collector result - it marks filtered errors as ignored and attaches data about applied filters. This filter can be only applied to `js-errors` comparator tag in test case. When more than one parameter is provided then only fully matched errors are filtered. If some XML-specific charactes (e.g. `&`) are in parameter's value, then they must be escaped. Module name: **js-errors-filter** Resource name: js-errors ##### Parameters | Parameter | Value | Description | Mandatory | | --------- | ----- | ----------- | --------- | |`error`|string error|Exact error message|At least one of parameter is required| |`source`|JavaScript filename suffix (see notes) below|Source file name in which error occurred|At least one of parameter is required| |`sourcePattern`|JavaScript filename pattern|Regular expression that matches source file name in which error occurred|At least one of parameter is required| |`errorPattern` | pattern error text | Regular expression that matches message text of issue to be filter out|At least one parameter is required| |`line` integer line number|Line number in file in which error occurred| |At least one of parameter is required| *Note:* - filter will check if value of `source` param is a suffix of JS error source. So we can use `"/jquery-1.8.3.js"` to filter errors from all JQuery files regardless of path or even filter errors from all JavaScript files with `".js"`. - `error` param will be overridden by `errorPattern` if set - If some XML-specific charactes (e.g. `&`) are in parameter's value, then they have to be escaped. Suite should be valid XML document: ```xml <js-errors-filter source="http://www.example.com/jquery-1.8.3.js?q=1&amp;p=2" /> ``` ##### Example Usage In this sample exact match of js error from file "[http://w.iplsc.com/external/jquery/jquery-1.8.3.js](http://w.iplsc.com/external/jquery/jquery-1.8.3.js)", line 2 with message "Error: Syntax error, unrecognized expression:.iwa_block=pasek-ding" will be ignored. That is to say, it will be marked in report as ignored and it will have associated information about the applied filter. In this case, about filter specified in first `js-errors-filter` node below. ```xml <?xml version="1.0" encoding="UTF-8"?> <suite name="test-suite" company="cognifide" project="project">     <test name="js-errors-filter-test">         <collect>             ...             <open/>             ...             <js-errors/>             ...         </collect>         <compare>             ...             <js-errors>                 <js-errors-filter error="Error: Syntax error, unrecognized expression:.iwa_block=pasek-ding" line="2" source="http://w.iplsc.com/external/jquery/jquery-1.8.3.js" />                 <js-errors-filter source="/some/path/to/custom.js" />                 <js-errors-filter errorPattern="^.*Syntax error, unrecognized expression.*$" />             </js-errors>             ...         </compare>         <urls>             ...         </urls>     </test>     ...     <reports>         ...     </reports> </suite> ``` There can be more than one `js-errors-filter` tag in `js-errors` comparator eg: ```xml <js-errors> <js-errors-filter error="Error: Syntax error, unrecognized expression:.iwa_block=pasek-ding" /> <js-errors-filter source="http://w.iplsc.com/external/jquery/jquery-1.8.3.js" line="2" /> </js-errors> ``` ======================= File: core/jobs/README.md ======================= ![Cognifide logo](http://cognifide.github.io/images/cognifide-logo.png) # AET <p align="center"> <img src="https://github.com/Cognifide/aet/blob/master/misc/img/aet-logo-black.png?raw=true" alt="AET Logo"/> </p> ## Job Common Module Contains implementations for `Modifiers`, `Collectors`, `Data Filters` and `Comparators`: - Accessibility Collector, - Client Side Performance Collector, - Cookie Collector, - JS Errors Collector, - Screen Collector, - Source Collector, - Status Codes Collector, - Click Modifier, - Cookie Modifier, - Header Modifier, - Hide Modifier, - Login Modifier, - Resolution Modifier, - Sleep Modifier, - Wait For Page Loaded Modifier, - Accessibility Comparator, - Client Side Performance Comparator, - Cookie Comparator, - JS Errors Comparator, - Layout Comparator, - Source Comparator, - Status Codes Comparator, - W3C Comparator, - W3C HTML5 Comparator, - Accessibility Data Filter, - Extract Element Data Filter, - JS Errors Data Filter, - Remove Lines Data Filter, - Remove Nodes Data Filter, - Remove Regex Data Filter, - Status Codes Data Filters, - W3c Filter. ======================= File: documentation/src/main/wiki/DefiningSuite.md ======================= <filename>documentation/src/main/wiki/DefiningSuite.md ## Defining Suite ### Test suite In general the test suite is an XML document that defines tests conducted on a collection of web pages. This chapter covers the test suite API, with a description of its each element. ### Sample test suite ```xml <?xml version="1.0" encoding="UTF-8"?> <!-- Each test suite consists of one suite --> <suite name="test-suite" company="cognifide" project="project"> <!-- The First test of Test Suite --> <!-- The flow is [collect] [compare] [urls] --> <test name="first-test" useProxy="rest"> <!-- Description of the collect phase --> <collect> <open/> <resolution width="800" height="600" /> <!-- sleep 1500 ms before next steps - used on every url defined in urls --> <sleep duration="1500"/> <screen/> <source/> <status-codes/> <js-errors/> </collect> <!-- Description of compare phase, says what collected data should be compared to the patterns, can also define the exact comparator. If none chosen, the default one is taken. --> <compare xmlns="http://www.cognifide.com/aet/compare/"> <screen comparator="layout"/> <source comparator="w3c-html5"/> <status-codes filterRange="400,600"/> <js-errors> <js-errors-filter source="http://w.iplsc.com/external/jquery/jquery-1.8.3.js" line="2" /> </js-errors> </compare> <!-- List of urls which will be taken into tests --> <urls> <url href="http://www.cognifide.com"/> </urls> </test> </suite> ``` The root element of the test suite definition is the `suite` element. ### suite |! Important | |:----------- | | When defining the suite the user should think of the following three mandatory parameters properly: `name, company, project`. These parameters are used by the AET System to identify the suite. <br/><br/> Any change in one of these parameter values in the future will occur in treating the suite as a completely new one which will in effect gather all patterns from scratch. | The Root element for the xml definition, each test suite definition consists of exactly one `suite` tag. | Attribute name | Description |Mandatory | | -------------- | ----------- | --------- | | `name` | Name of the test suite. It should contain lowercase letters, digits and/or characters: `-`, `_` only. | yes | | `company` | Name of the company. It should contain lowercase letters, digits and/or characters: `-` only.| yes | | `project` | Name of the project. It should contain lowercase letters, digits and/or characters: `-` only.| yes | | `domain` | General domain name consistent for all urls considered. Every url link is built as a concatenation of the *domain* name and the *href* attribute of it. If the `domain` property is not set, then the `href` value in the `url` definition should contain a full valid url. See more in the [[Urls]] section. | no | The `suite` element contains one or more **[[test|SuiteStructure#test]]** elements. ======================= File: documentation/src/main/wiki/Home.md ======================= <reponame>jwadolowski/aet<gh_stars>100-1000 ![AET](/Cognifide/aet/wiki/assets/misc/aet-logo.png) # Getting Started ## What is AET AET is a testing tool which aids front end client side layout regression testing of websites and portfolios. It allows to ensure that a change in one part of the software did not introduce any defects in other parts of application. AET is a flexible application that can be adapted and tailored to the requirements of a given project. ## Why AET The aim of AET is to ensure a better software quality. This goal is achieved by a couple of factors. AET allows to create and maintain automated tests as well as to analyze their results easily and quickly. Test automation has a strong influence on test coverage because AET is able to cover a bigger part of software when compared to manual testing (it saves time needed for manual regression). Automation also helps to eliminate human errors. Finally, AET supports software continuous integration. ======================= File: documentation/src/main/wiki/W3CHTML5Comparator.md ======================= <reponame>jwadolowski/aet<gh_stars>100-1000 #### W3C HTML5 Comparator W3C HTML5 Comparator is responsible for validating the collected page source against w3c standards using [validator.nu](https://validator.nu/). HTML5 is supported by this library. The W3C HTML5 feature does not allow to collect patterns, so it does not compare results with any patterns either - the rebase action is also not available. Module name: **w3c-html5** Resource name: source ##### Parameters | Parameter | Value | Description | Mandatory | | --------- | ----- | ----------- | --------- | | `ignore-warnings` | boolean (default: true) | If `ignore-warnings="true"` the test status does not depend on the warnings amount. Otherwise warnings count as w3c errors when computing the testcase status. | no | | `errors-only` | boolean(default: true) | **This parameter will be removed from the 1.5 AET Version!**<br/> It has the same result as the `ignore-warnings` parameter. | no | |! Mandatory parameter | |:--------------------- | | Please remember, that using the parameter `comparator="w3c-html5"` is mandatory while defining this comparator. More information about this parameter can be found in the [[Comparators]] section. | ##### Example Usage ```xml <?xml version="1.0" encoding="UTF-8"?> <suite name="test-suite" company="cognifide" project="project"> <test name="w3c-html5-test"> <collect> ... <open /> ... <source /> ... </collect> <compare> ... <source comparator="w3c-html5" /> ... </compare> <urls> ... </urls> </test> ... <reports> ... </reports> </suite> ``` ======================= File: documentation/src/main/wiki/RemoveNodesDataFilter.md ======================= <filename>documentation/src/main/wiki/RemoveNodesDataFilter.md #### Remove Nodes Data Filter Remove Nodes Data Filter allows to delete some node(s) from html tree. Node(s) are defined by xpath selector. |! Important information | |:----------------------- | | Html source has to be valid xml document | Name: **remove-nodes** Resource name: source ##### Parameters | Parameter | Value | Description | Mandatory | | --------- | ----- | ----------- | --------- | | `xpath` | xpath_to_node| Xpath selector for nodes to remove | yes | ##### Example Usage ```xml <?xml version="1.0" encoding="UTF-8"?> <suite name="test-suite" company="Cognifide" project="project">     <test name="remove-nodes-test">         <collect>             ...             <open/>             ...             <source/>             ...         </collect>         <compare>             ...             <source comparator="source">                 <remove-nodes xpath="//*[@id='blueBarNAXAnchor']/div/div/div/a/i"/>             </source>             ...         </compare>         <urls>             ...         </urls>     </test>     <reports>         ...     </reports> </suite> ``` ======================= File: integration-tests/sample-site/src/main/webapp/sanity/modifiers/slow/conference.md ======================= <filename>integration-tests/sample-site/src/main/webapp/sanity/modifiers/slow/conference.md<gh_stars>100-1000 # Readme for bigTestImage.jpg This image was downloaded from [Flickr](https://www.flickr.com/photos/pfaseal/32677857605/in/photolist-GRcCrW-QvTigN-RdSFxo-QvggVo-RMCyA2-RcBWLW-QupsZh-RLo3oc-QwAc7v-RwuHW9-QtwpkL-RGpVS7-RaXyiw-RaXjab-RvWYQw-Qvxr5c-Rysjb4-Rys3on-RvKobo-QsTGAS-QvA5Hp-QvvD8e-QsxoS5-RaHVVN-RFvSkS-Rydjgn-RK31nV-RvvmxS-RK2NE6-Ryamnc-QvdAwr-Qvcttv-Qvctke-Qvct6r-RFn1Kq-RvrwfA-Qstvjb-Qsez43-RxTn1P-RHRUCK-R9gm11-RtYVpS-QrXPZC-QrMrmG-QubEBR-Rx7Bog-Rup4Zj-Rup3ZU-Rx7wHp-RtXYjG/) where it was published under permissive license of [Public Domain](https://creativecommons.org/publicdomain/mark/1.0/). ## No Copyright This work has been identified as being free of known restrictions under copyright law, including all related and neighboring rights. You can copy, modify, distribute and perform the work, even for commercial purposes, all without asking permission. See Other Information below. ## Other Information The work may not be free of known copyright restrictions in all jurisdictions. Persons may have other rights in or related to the work, such as patent or trademark rights, and others may have rights in how the work is used, such as publicity or privacy rights. In some jurisdictions moral rights of the author may persist beyond the term of copyright. These rights may include the right to be identified as the author and the right to object to derogatory treatments. Unless expressly stated otherwise, the person who identified the work makes no warranties about the work, and disclaims liability for all uses of the work, to the fullest extent permitted by applicable law. When using or citing the work, you should not imply endorsement by the author or the person who identified the work. ======================= File: documentation/src/main/wiki/SharedPatterns.md ======================= ## Shared Patterns When running AET suite it is possible to use patterns from different suite. Example use case of this feature is when you have a `stable` environment where you collect the patterns and then check on `develop` environments what changes were done with new features/fixes. There is very simple and important assumption when using shared pattern feature: * your suite and `master` suite must have the same structure. This mean that your suite have the same tests [[Suite Structure|SuiteStructure#test]] (`name` parameter is important here). It is also possible to share patterns only within same project and company (this mean, that `company` and `project` parameters should have the same value as in `master` suite). ## Using shared patterns Let's consider following suite as `master` suite: ```xml <?xml version="1.0" encoding="UTF-8"?> <suite name="master" company="company" project="project"> <test name="first-test"> <collect> <open/> <resolution width="800" height="600" /> <sleep duration="1500"/> <screen/> </collect> <compare> <screen comparator="layout"/> </compare> <urls> <url href="http://www.cognifide.com/"/> </urls> </test> <test name="second-test"> <collect> <open/> <resolution width="800" height="600" /> <sleep duration="1500"/> <screen/> </collect> <compare> <screen comparator="layout"/> </compare> <urls> <url href="https://www.google.com/"/> </urls> </test> </suite> ``` When you define your own suite, you should consider the same structure (order is not important). However, you may use different set of [[Modifiers|Modifiers]]: ```xml <?xml version="1.0" encoding="UTF-8"?> <suite name="green" company="company" project="project"> <test name="first-test"> <collect> <open/> <resolution width="800" height="600" /> <executejavascript cmd="document.body.style.background = 'green';"/> <sleep duration="1500"/> <screen/> </collect> <compare> <screen comparator="layout"/> </compare> <urls> <url href="http://www.cognifide.com/"/> </urls> </test> <test name="second-test"> <collect> <open/> <resolution width="800" height="600" /> <executejavascript cmd="document.body.style.background = 'green';"/> <sleep duration="1500"/> <screen/> </collect> <compare> <screen comparator="layout"/> </compare> <urls> <url href="https://www.google.com/"/> </urls> </test> </suite> ``` When you run `green` suite use [[following command|ClientApplication#parameters]] to use suite pattern from **master** suite execution. `mvn aet:run -DtestSuite=green.xml -DpatternSuite=master` This option will enforce AET to use patterns from latest version of `master` suite. Alternatively, if you want to use patterns from a specific version (i.e. correlation ID) of `master` suite, use: `mvn aet:run -DtestSuite=green.xml -Dpattern=company-project-master-1495191612345` **Remember that `master` suite must be run before running `green` suite with `pattern` or `patternSuite` option.** In other case, running `green` suite will be treated as running it for the first time. ======================= File: documentation/src/main/wiki/StatusCodesDataFilters.md ======================= #### Status Codes Data Filters There might be a need to ignore some of the collected status codes. We can exclude them so that they no longer affect our test case. Data filters will be applied only for codes contained in logic sum of the `filterRange` and the `filterCodes`. If the `filterRange` isn't provided, default range will be used. ##### Exclude Filter Exclude Filter removes from reports Status Codes results that match specified parameters. Name: **exclude** Resource name: status-codes ###### Parameters | Parameter | Value | Description | Mandatory | | --------- | ----- | ----------- | --------- | | `url` | String url | Exact url to be excluded from results. | At least one of parameter is required. | | `pattern` | String regex pattern| Regex pattern that urls should match to be excluded from results. | | If both parameters are provided then result is removed when it matches at least one of the parameters. ###### Example Usage In this sample result with url http://www.external.com/_optional.js or urls that match pattern **^.\*js$** will be excluded. ```xml <?xml version="1.0" encoding="UTF-8"?> <suite name="test-suite" company="Cognifide" project="project"> <test name="exclude-test" useProxy="rest"> <collect> ... <open/> ... <status-codes/> ... </collect> <compare> ... <status-codes filterRange="200,999"> <exclude url="http://www.external.com/_optional.js" pattern="^.*js$"/> </status-codes> ... </compare> <urls> ... </urls> </test> <reports> ... </reports> </suite> ``` There can be more than one `exclude` tags in `status-codes` comparator. They are processed in turns. Example below is equivalent to previous one: ```xml <status-codes> <exclude url="http://www.external.com/_optional.js"/> <exclude pattern="^.*js$"/> </status-codes> ``` In this case both results with url http://www.external.com/_optional.js and urls that match pattern **^.\*js$** (ending with `js`) will not be displayed on reports. ##### Include Filter Include Filter excludes from reports Status Codes results that **do not** match specified parameters. Name: **include** Resource name: status-codes ###### Parameters | Parameter | Value | Description | Mandatory | | --------- | ----- | ----------- | --------- | | `url` | String url | Exact url to be included in reports. Results that do not match will be excluded. | At least one of parameter is required. | | `pattern` | String regex pattern | Regex pattern that urls should match to be included in reports. Results that do not match will be excluded. | | If both parameters are provided then result is only included in the report when it matches both of the parameters. ###### Example Usage In example below **only** result with url http://www.cognifide.com/main.js will be included in report. ```xml <?xml version="1.0" encoding="UTF-8"?> <suite name="test-suite" company="Cognifide" project="project" environment="win7-ff16"> <test name="include-test" useProxy="rest"> <collect> ... <open/> ... <status-codes/> ... </collect> <compare> ... <status-codes filterRange="200,999"> <include url="http://www.cognifide.com/main.js"/> </status-codes> ... </compare> <urls> ... </urls> </test> <reports> ... </reports> </suite> ``` There can be more than one `include` tags in `status-codes` comparator. They are processed in turns. Example: ```xml <status-codes> <include pattern="^.*js$"/> <include url="http://www.cognifide.com/main.js"/> </status-codes> ``` In this case only http://www.cognifide.com/main.js url will be included on reports: first all results that do not match **^.\*js$** pattern (ending with `js`) are excluded. Then within that result all urls different from "http://www.cognifide.com/main.js" are excluded. In example above, first `<include>` can be omitted and result will be the same. ##### Include and Exclude **Include** and **exclude** modifiers can be both applied to **status-codes comparator**. They are processed in turns. Example: ```xml <status-codes> <include pattern="^.*js$"/> <exclude url="http://www.external.com/_optional.js"/> </status-codes> ``` In example above we include URLs that match **^.\*js$**, so any other URL will be excluded. Then we exclude http://www.external.com/_optional.js. Therefore only urls ending with `js` except http://www.external.com/_optional.js will be included in reports. ======================= File: documentation/src/main/wiki/SuiteReportLayoutCase.md ======================= #### Screen - layout ##### Description For layout tests the results are presented as compared screenshots ![Layout failure](assets/suiteReport/layout-failure.png) 1. Test case's name (red font means failure). 2. "Accept test case" button (available only when differences have been detected). 3. "Show mask" switch - when the mask is on, differences are marked in a red colour over the collected screenshot, otherwise a raw screenshot is presented. 4. Pattern - a screen which the "view" is compared to (if there is no pattern, the first collected screenshot is saved as the pattern). 5. View - a screen that was taken during the test and it is compared to the pattern. 6. Example of difference area. 7. Date of obtaining current pattern. ##### Yellow color Yellow color in mask is introduced when there is a change in test definition. The yellow color shows that we have different resolutions for pattern and collected view. In this example pattern has resolution *800x600*, but then test definition for view has been increased using resolution modifier: ``` <resolution width="1024" height="768" /> ``` ![Yellow mask](assets/suiteReport/layout-yellow-mask.png) ##### Success Test case's result is marked as successful when there is no difference between view and pattern (see screenshot below). ![Layout success](assets/suiteReport/layout-success.png) ##### Conditionally passed Test case's result is marked as conditionally passed when there is difference between view and pattern (see screenshot below) but the difference is below threshold - here `percentageThreshold="5"`. The test is pass so you can't accept it, therefore "Accept test case" button isn't available and the test has green color (but with different icon to be perceptible) but images are different so you can see a mask. ![Layout conditionally passed](assets/suiteReport/layout-conditionally-passed.png) ##### What vulnerabilities it discovers * Differences found in page screenshots may indicate undesired changes in the page layout (css, html structure) e.g. when a new functionality was implemented in a system it may have an impact on another system component(s). This may show itself as a changed page layout. * Content changes can be divided into two groups: wanted (are intended) and unwanted (a result of a mistake or an error). An example of a change that is not a defect (wanted) is: the carousel component with the latest news items displayed or the twitter component displaying latest tweets. In order to avoid detecting these sorts of changes in these dynamic components, the user can use the [[Hide Modifier|HideModifier]] feature in the suite definition. Another example of the ‘wanted’ dynamic content is a cookies policy popup that may be hidden using the [[Cookie Modifier|CookieModifier]]. ======================= File: documentation/src/main/wiki/Troubleshooting.md ======================= <reponame>jwadolowski/aet<filename>documentation/src/main/wiki/Troubleshooting.md # Troubleshooting This section contains tips and ways to repair AET instances. If all the tips from the list failed or you have discovered a new one, please raise a ticket using [Issues Tool](https://github.com/Cognifide/aet/issues) or create a Pull Request with change to [this file](https://github.com/Cognifide/aet/blob/master/documentation/src/main/wiki/Troubleshooting.md). - [Karaf](#karaf) - [Karaf can't find some dependencies or configurations - clearing the cache](#karaf-cant-find-some-dependencies-or-configurations---clearing-the-cache) - [ActiveMQ](#activemq) - [Messages serialization issue](#messages-serialization-issue) - [MongoDB](#mongodb) - [Make sure that you have indexed `metadata` collection in the project db.](#make-sure-that-you-have-indexed-metadata-collection-in-the-project-db) - [Report app](#report-app) - [Failed to load report data](#failed-to-load-report-data) ## Karaf ### Karaf can't find some dependencies or configurations - clearing the cache This may help in multiple situations, e.g. new version of AET was deployed or Karaf can't find some dependencies or configurations. To clear bundles cache, stop Karaf, clear `$KARAF_HOME/data` and start Karaf. If you want to backup existing logs, copy `$KARAF_HOME/data/logs` to backup location before clearing `$KARAF_HOME/data`. Example command to clear the cache (without logs backup): ``` sudo service karaf stop sudo rm -fr /opt/aet/karaf/current/data/* sudo service karaf start ``` ## ActiveMQ ### Messages serialization issue Make sure that no unfinished tasks are available on the ActiveMQ. You may check it using console `http://<active-mq-host>:8161/admin/queues.jsp` (default credentials are `<PASSWORD>/<PASSWORD>`). Column `Number Of Pending Messages` should display `0` in all `AET` queues. If there is a positive number of messages pending, use `Purge` option. Run tests again. ## MongoDB ### Check if Mongo is running Navigate to `http://<mongo-db-host>:27017` with your browser. Mongo is OK if you see message about trying to access Mongo with HTTP protocol. ### Make sure that you have indexed `metadata` collection in the project db. Manually created databases require manually created indexes. To create indexes run [this script](https://github.com/Cognifide/aet/blob/master/misc/mongodb/create-indexes.js) in your MongoDB database. You may update all existing databases at once using [this script](https://github.com/Cognifide/aet/blob/master/misc/mongodb/create-indexes-for-all-dbs.js). ## Report app ### Failed to load report data When you see the alert `Failed to load report data!` it may mean several things. First one is a problem with connectivity between report app and AET Web Services. Open browser developer's console and check the status of a request to `<aet-web-api-endpoint>/api/metadata?...`. Make sure that your report instance is not trying to do Cross-Origin resource call which is blocked by most of popular browsers. Configuration of an endpoint for AET reports can be found in [`/webapp/app/services/endpointConfiguration.service.js`](https://github.com/Cognifide/aet/blob/master/report/src/main/webapp/app/services/endpointConfiguration.service.js) file. ======================= File: documentation/src/main/wiki/W3CHTML5IssuesFilter.md ======================= #### W3C HTML5 Issues Filter W3C HTML5 Issues Filter allows to exclude some W3C HTML5 issues from the result. The issues excluded will appear at the bottom of a table with issues and won't be taken into account when calculating the status. Name: **w3c-filter** Resource name: source Comparators: **w3c-html5** ### Parameters | Parameter | Value | Description | Mandatory | | --------- | ----- | ----------- | --------- | | `message` | string | Exact message text of the issue to be filtered out. *see notes below | At least one of params should be used and all the params used should be not empty. | | `messagePattern` | regexp | A regular expression that matches message text of the issue to be filtered out. *see notes below | At least one of params should be used and all of the params used should be not empty. | | `line` | integer | A line in the source file where the issue appears. | | | `column` | integer | A column in the source file where the issue appears. | | *Note:* - `message` will be overridden by `messagePattern` if set. - If there are some XML-specific characters (e.g. `&`) in the parameter value, they have to be escaped. The suite should be a valid XML document. ##### Sample usage of w3c-html5 comparator ```xml <?xml version="1.0" encoding="UTF-8"?> <suite name="test-suite" company="Cognifide" project="project" environment="win7-ff16"> <test name="remove-nodes-test"> <collect> ... <open/> ... <source/> ... </collect> <compare> ... <source comparator="w3c-html5" errors-only="false"> <w3c-filter messagePattern = "The first occurrence of.*" /> <w3c-filter message="A slash was not immediately followed by “&gt;”."/> <w3c-filter message="Element “img” is missing required attribute “src”."/> <w3c-filter line="1" column="119"/> <w3c-filter line="390" message="End tag for “html” seen, but there were unclosed elements."/> </source> ... </compare> <urls> ... </urls> </test> <reports> ... </reports> </suite> ``` ======================= File: documentation/src/main/wiki/ExtractElementDataFilter.md ======================= #### Extract Element Data Filter Extract Element Data Filter allows to extract an element from the html source (collected by [Source Collector](SourceCollector)) by providing an id attribute or a class attribute. Only the extracted source of the element is processed by the comparator. Module name: **extract-element** Resource name: source ##### Parameters | Parameter | Value | Description | Mandatory | | --------- | ----- | ----------- | --------- | | `elementId` | HTML id | Id for the element to extract | See the note below | | `class` | HTML class | Class name for the element to extract | See the note below | |! Note | |:------ | | One of these parameters is required. Only one parameter (either the `elementId` attribute or the `class` attribute) can be provided. If `class`attribute will be provided AET will extract markup for all elements with given class using JSoup [getElementsByClass](https://jsoup.org/apidocs/org/jsoup/nodes/Element.html#getElementsByClass-java.lang.String-) method | ##### Example Usage ```xml <?xml version="1.0" encoding="UTF-8"?> <suite name="test-suite" company="cognifide" project="project">     <test name="extract-element-test">         <collect>             ...             <open/>             ...             <source/>             ...         </collect>         <compare>             ...             <source comparator="source">                 <extract-element elementId="login_form"/>             <!-- OR -->                 <extract-element class="class_form"/>             </source>             ...         </compare>         <urls>             ...         </urls>     </test>     ...     <reports>         ...     </reports> </suite> ``` ======================= File: documentation/src/main/wiki/CookieComparator.md ======================= <gh_stars>100-1000 #### Cookie Comparator Cookie Comparator is responsible for processing collected cookies. This can be simply listing of collected cookies, verifying if a cookie exists or comparing a collected cookie to the pattern. The cookie feature allows to collect patterns and can be rebased from the report only in the compare action mode. Module name: **cookie** Resource name: cookie ##### Parameters | Parameter | Value | Description | Mandatory | | --------- | ----- | ----------- | --------- | | `action` | list<br/><br/> test<br/><br/> compare | Displays a list of cookies<br/><br/> Tests if a cookie with a given name and value exists<br/><br/> Compares the current data to the pattern (compares only cookie names, values are ignored) | no<br/><br/> If the `action` parameter is not provided, the default `list` action is performed | | `cookie-name` | | The name of the cookie to test, applicable only for the test action | yes, if `action` set to `test` | | `cookie-value` | | The value of a cookie to test, applicable only for the test action | no | | `showMatched` | boolean<br/> (default: `true`) | **Works only in the compare mode.** The flag that says if matched cookies should be displayed in the report or not. By default set to `true`. | no | ##### Sample Usage ```xml <?xml version="1.0" encoding="UTF-8"?> <suite name="test-suite" company="cognifide" project="project"> <test name="cookie-test"> <collect> ... <cookie /> ... </collect> <compare> ... <cookie /> ... </compare> <urls> ... </urls> </test> ... <reports> ... </reports> </suite> ``` ======================= File: documentation/src/main/wiki/TrackingProgress.md ======================= ### Tracking Progress #### How to read AET Reports and real time progress AET execution progress is updated on real time basis and can be viewed in the console (also e.g. in the preview of the any CI tool that schedules running AET suite). During test processing detailed information about the actual progress is displayed as in the following example: ``` ... [14:24:29.010]: COLLECTED: [success: 0, total: 4] ::: COMPARED: [success: 0, total: 0] [14:24:46.036]: COLLECTED: [success: 1, total: 4] ::: COMPARED: [success: 1, total: 1] [14:24:50.039]: COLLECTED: [success: 2, total: 4] ::: COMPARED: [success: 1, total: 2] [14:24:51.042]: COLLECTED: [success: 2, total: 4] ::: COMPARED: [success: 2, total: 2] [14:24:53.059]: COLLECTED: [success: 3, total: 4] ::: COMPARED: [success: 2, total: 3] [14:24:54.047]: COLLECTED: [success: 3, total: 4] ::: COMPARED: [success: 3, total: 3] [14:24:55.050]: COLLECTED: [success: 4, total: 4] ::: COMPARED: [success: 3, total: 4] ... ``` where: **COLLECTED** - shows results of collectors' work - how many artifacts have been successfully collected and what is the total number of all artifacts to be collected, **COMPARED** - shows results of comparators' work - how many artifacts have been successfully compared and what is the total number of all artifacts to be compared. The total number of artifacts to be compared depends on collectors' work progress - increases when the number of successfully collected artifacts increases. If there are problems during processing, warning information with some description of processing step and its parameters is displayed: ``` CollectionStep: source named source with parameters: {} thrown exception. TestName: comparator-Source-Long-Response-FAILED UrlName: comparators/source/failed_long_response.jsp Url: http://192.168.123.100:9090/sample-site/sanity/comparators/source/failed_long_response.jsp ``` In this example the source collector failed to collect necessary artifacts. This information is subsequently reflected in the progress log: ``` ... [06:36:44.832]: COLLECTED: [success: 46, failed: 1, total: 72] ::: COMPARED: [success: 46, total: 46] [06:36:50.837]: COLLECTED: [success: 47, failed: 1, total: 72] ::: COMPARED: [success: 47, total: 47] [06:36:52.840]: COLLECTED: [success: 48, failed: 1, total: 72] ::: COMPARED: [success: 47, total: 48] ... ``` In the example above one artifact has failed during the collection phase. #### When tests successfully finish - command line When the AET test processing completes the information about available reports and processing status is shown in the console - as shown below: ``` Suite processing finished Report url: http://aet-report/report.html?company=cognifide&project=docker&correlationId=cognifide-docker-browsers-1535552618224 Test failures: 2 ``` `Test failures` - the number of tests that ended with `FAILED` status #### xUnit support You may want to use the xUnit report format to validate suite processing status immediately in your CI tool (e.g. with [Jenkins xUnit plugin](https://wiki.jenkins.io/display/JENKINS/xUnit+Plugin)). AET supports this format and you may obtain xUnit report file (in the XML form) after suite processing is finished with [[AET WebAPI|WebAPI]]. [[Aet client script|ClientScripts#exit-status]] supports downloading xUnit after suite processing is finished out of the box. ======================= File: documentation/src/main/wiki/JSErrorsCollector.md ======================= <reponame>jwadolowski/aet<gh_stars>100-1000 #### JS Errors Collector JS Errors Collector is responsible for collecting javascript errors occuring on given page. Module name: **js-errors** ##### Parameters No parameters. ##### Example Usage ```xml <?xml version="1.0" encoding="UTF-8"?> <suite name="test-suite" company="cognifide" project="project"> <test name="js-errors-test"> <collect> ... <js-errors/> ... </collect> <compare> ... </compare> <urls> ... </urls> </test> ... <reports> ... </reports> </suite> ``` ======================= File: client/client-scripts/README.md ======================= ![Cognifide logo](http://cognifide.github.io/images/cognifide-logo.png) # AET <p align="center"> <img src="https://github.com/Cognifide/aet/blob/master/misc/img/aet-logo-black.png?raw=true" alt="AET Logo"/> </p> ## AET Client - shell script Script that allows executing AET tests. ### Usage ``` AET Test executor Usage: ./aet.sh <endpoint> [<suite_file_name>] [options] Options: -d --domain <DOMAIN> - Override domain attribute defined in suite file -c --correlationId <CORRELATION_ID> - Set id of patterns to run test against -p --patternSuite <SUITE_NAME> - Set the suite name to run test against its latest pattern (only used if -c is not set) -i --interval <POLL_INTERVAL> - Set interval in seconds for polling suite status. Default interval : 1 sec -w --waitForUnlock <TIMEOUT> - Set timeout for the script to wait for unlocked suite. Default timeout: 0 sec -v --verbose - Make it more descriptive ``` ### Prerequisites In order to run properly, following commands need to be available on PATH of the environment the script is executed on: * `curl` - used to make actual request against [[Test Executor API|TestExecutor]] and also to download `xUnit.xml` file after test completion. Comes preinstalled on most Unix systems. [Download link](https://curl.haxx.se/download.html) * `jq` - used to parse JSON responses from [[Test Executor API|TestExecutor]]. [Download link](https://stedolan.github.io/jq/download/) * `xmllint` - used to retirieve failure information from downloaded `xUnit.xml`. Comes preinstalled on most Unix systems. For Windows installation instructions, refer to [Jo Jordan's post](http://flowingmotion.jojordan.org/2011/10/08/3-steps-to-download-xmllint/). ======================= File: documentation/src/main/wiki/ReplaceTextModifier.md ======================= <reponame>jwadolowski/aet<filename>documentation/src/main/wiki/ReplaceTextModifier.md #### ReplaceText Modifier ReplaceText Modifier is responsible for replacing text inside html tags or in tags attributes. It affects [[Screen Collector|ScreenCollector]] results only. Module name: **replaceText** |! Important information | |:----------------------- | | In order to use this modifier it must be declared after the open module in the definition of the test suite XML. | ##### Parameters | Parameter | Value | Description | Mandatory | | --------- | ----- | ----------- | --------- | | `value` | default: "" (empty string)| new text value for given attribute or innerHtml of selected Element | no | | `attributeName` | default: "innerHTML" | attribute of selected element to be set, e.g. 'href' or 'value'; attribute value or inner HTML will be replaced/set to 'value' | no | | `xpath` | xpath_to_element | Xpath of element(s)| xpath or css | | `css` | css_selector_to_element | css selector of element(s) | xpath or css | | `timeout` | 1000ms | The timeout to wait for the element to be present, in milliseconds. The max value of this parameter is 15000 milliseconds (15 seconds). | no (default will be used) | ##### Example Usage ```xml <?xml version="1.0" encoding="UTF-8"?> <suite name="test-suite" company="cognifide" project="project"> <test name="ReplaceText-test"> <collect> <open /> ... <resolution width="1200" height="760" /> <replaceText xpath="//*[@id='day_of_the_week']" value="today"/> <replaceText css="#logo > a" attribute="href" value="#"/> <replaceText css="#logo > a" /> ... <screen /> ... </collect> <compare> ... </compare> <urls> ... </urls> </test> ... <reports> ... </reports> </suite> ``` #### Tips and tricks Some page elements such as images or third-party components might not load as fast as the rest of the page under test. In cases where we don't really need to test this slowly loading element we can either hide it or replace a large, heavy image with a small placeholder. ##### Replace image in an img element ```xml <test> <collect> ... <replaceText css="img" attributeName="src" value="/content/dam/test/uk/en_gb/dummy/dummy.png.renditions.original.png" /> ... <screen/> </collect> ... </test> ``` "replacetext" replaces the src attribute for all img elements on the page under test, this way the test can become more stable because it becomes independent of external image sources. ##### Replace background image in a page element ```xml <test> <collect> ... <replaceText attributeName="style" value="background-image: url('/content/dam/test/uk/en_gb/dummy/dummy.png.renditions.original.png')" css="#backgroundStuff" timeout="5000"/> ... <screen/> </collect> ... </test> ``` "replacetext" replaces the background image for the selected element, this way the test can become more stable because it becomes independent of external image sources. ======================= File: documentation/src/main/wiki/HideModifier.md ======================= #### Hide Modifier Hide Modifier is responsible for hiding an element on the page that is redundant for testing and/or can make the page look different each time a screenshot is taken. It affects [[Screen Collector|ScreenCollector]] results. Hiding is performed by setting the css `visibility` property to `hidden`. It works with webDriver only. You can hide many elements by defining many `<hide>` nodes. If the xpath covers more than one element then all the elements matching the xpath will be hidden. Module name: **hide** |! Important information | |:----------------------- | | *In order to use this modifier it must be declared after the open module in the definition of the test suite XML. *In order to use this modifier with Resolution Modifier it must be declared before the Resolution Modifier because the Hide modifier might affect the total height of the page (when used without `leaveBlankSpace="true"`. | ##### Parameters | Parameter | Value | Description | Mandatory | | --------- | ----- | ----------- | --------- | | `xpath` | xpath_to_element | Xpath to element(s) to hide | xpath or css | | `css` | css_selector_to_element | css selector to element(s) to hide | xpath or css | | `timeout` | 1000ms | The timeout for the element to appear, in milliseconds. The max value of this parameter is 15000 milliseconds (15 seconds). | no (default will be used) | | `leaveBlankSpace` | boolean | Defines if element(s) should be invisible (effect as using `display=none`) or should be not displayed (effect as using `visibility=hidden`). When set to `true`, blank and transparent space is left in place of the hidden element, otherwise, element is completely removed from the view. When not defined, hide modifier behaves as if `leaveBlankSpace` property was set to `true`. | no | ##### Example Usage ```xml <?xml version="1.0" encoding="UTF-8"?> <suite name="test-suite" company="cognifide" project="project"> <test name="hide-test"> <collect> <open /> ... <hide xpath="//*[@id='logo']" /> <hide css="#ad-section > a" /> ... <resolution width="1200" /> <screen /> ... </collect> <compare> ... </compare> <urls> ... </urls> </test> ... <reports> ... </reports> </suite> ``` ======================= File: documentation/src/main/wiki/ScreenCollector.md ======================= <gh_stars>1-10 #### Screen Collector |! Compare collected screenshot | |:------------------------------ | | Please remember that defining collector and not using it during comparison phase is configuration error. From now on suites that define screen collection and does not use it during comparison phase will be rejected during suite validation phase. | |! Notice | | :---------- | | Screen Collector is responsible for collecting screenshot of the page or just part of it by specifying element locator (xpath or css) under given URL. | | Screenshot of the page only covers the current viewport, i.e. the screenshot size (both width and height) will be equal to the browser's window size set by the [`Resolution Modifier`](https://github.com/Cognifide/aet/wiki/ResolutionModifier). | | If you want to take a screenshot of entire page, you should either skip the `height` parameter of `resolution` modifier (to let it be computed by JavaScript), or set it to a value which will cover the whole page. If you want to take a screenshot of specific element on the page (using `xpath` or `css` selector), then this entire element must be visible in current viewport - otherwise you will get an processing error. | Module name: **screen** ##### Parameters | Parameter | Value | Description | Mandatory | | --------- | ----- | ----------- | --------- | | `xpath` | xpath_to_element | Xpath to element(s) | optional (either xpath or css) | | `css` | css_selector_to_element | css selector to element(s)| optional (either xpath or css) | | `exclude-elements` | css_selector_to_element | Elements found with that selector will be ignored by layout comparator (they won't affect its results) but will be rendered on the report as captured. | no | | `timeout` | 1000ms | The timeout for the element to appear, in milliseconds. The max value of this parameter is 15000 milliseconds (15 seconds). | no (default will be used) this parameter applies only in conjunction with xpath or css param | ##### Example Usage ```xml <?xml version="1.0" encoding="UTF-8"?> <suite name="test-suite" company="cognifide" project="project"> <test name="screen-test"> <collect> ... <screen name="desktop" /> <screen name="carouselComponent" css=".carousel"/> ... </collect> <compare> ... </compare> <urls> ... </urls> </test> ... <reports> ... </reports> </suite> ``` Instead of ```xml <screen width="1280" height="1024" name="desktop" /> ``` please use: ```xml <resolution width="1280" height="1024"/> <sleep duration="1000" /> <screen name="desktop" /> ``` |! Note | |:------ | | Before taking screenshot [Hide modifier](https://github.com/Cognifide/aet/wiki/HideModifier) can be applied in order to hide from the screen some elements that are not necessary for comparison, i.e. Twitter feed. <br/><br/> Also [Resolution Modifier](https://github.com/Cognifide/aet/wiki/ResolutionModifier) and [Wait For Page Loaded Modifier](https://github.com/Cognifide/aet/wiki/WaitForPageLoadedModifier) can be applied before Screen Collector usage to change expected collect result. <br/><br/> As in example presented above, `name` parameter can be very useful when using screen collector. More information about this parameter can be found in [Collectors](https://github.com/Cognifide/aet/wiki/Collectors) section. | ======================= File: documentation/src/main/DocumentationTemplate.md ======================= <reponame>jwadolowski/aet<filename>documentation/src/main/DocumentationTemplate.md #include "wiki/Home.md" #include "wiki/AETIn10Minutes.md" #include "wiki/Dictionary.md" #include "wiki/HowToExtendAET.md" # How To Use #include "wiki/EnvironmentSetup.md" #include "wiki/BasicSetup.md" #include "wiki/AdvancedSetup.md" #include "wiki/DefiningSuite.md" #include "wiki/SuiteStructure.md" #include "wiki/RunningSuite.md" #include "wiki/TrackingProgress.md" #include "wiki/Features.md" #include "wiki/Open.md" #include "wiki/Collectors.md" #include "wiki/AccessibilityCollector.md" #include "wiki/ClientSidePerformanceCollector.md" #include "wiki/CookieCollector.md" #include "wiki/JSErrorsCollector.md" #include "wiki/ScreenCollector.md" #include "wiki/SourceCollector.md" #include "wiki/StatusCodesCollector.md" #include "wiki/Modifiers.md" #include "wiki/ClickModifier.md" #include "wiki/CookieModifier.md" #include "wiki/HeaderModifier.md" #include "wiki/HideModifier.md" #include "wiki/ExecuteJavaScriptModifier.md" #include "wiki/LoginModifier.md" #include "wiki/ResolutionModifier.md" #include "wiki/SleepModifier.md" #include "wiki/WaitForPageLoadedModifier.md" #include "wiki/WaitForElementToBeVisibleModifier.md" #include "wiki/WaitForImageCompletionModifier.md" #include "wiki/ExecuteJavaScriptModifier.md" #include "wiki/Comparators.md" #include "wiki/AccessibilityComparator.md" #include "wiki/ClientSidePerformanceComparator.md" #include "wiki/CookieComparator.md" #include "wiki/JSErrorsComparator.md" #include "wiki/LayoutComparator.md" #include "wiki/SourceComparator.md" #include "wiki/StatusCodesComparator.md" #include "wiki/W3CHTML5Comparator.md" #include "wiki/DataFilters.md" #include "wiki/AccessibilityDataFilter.md" #include "wiki/ExtractElementDataFilter.md" #include "wiki/JSErrorsDataFilter.md" #include "wiki/RemoveLinesDataFilter.md" #include "wiki/RemoveNodesDataFilter.md" #include "wiki/RemoveRegexDataFilter.md" #include "wiki/StatusCodesDataFilters.md" #include "wiki/W3CHTML5IssuesFilter.md" #include "wiki/Urls.md" #include "wiki/SuiteReport.md" ### Test cases #include "wiki/SuiteReportCookieCase.md" #include "wiki/SuiteReportJSErrorsCase.md" #include "wiki/SuiteReportLayoutCase.md" #include "wiki/SuiteReportSourceCase.md" #include "wiki/SuiteReportStatusCodesCase.md" #include "wiki/SuiteReportW3CCase.md" #include "wiki/SuiteReportAccessibilityCase.md" #include "wiki/SuiteReportClientSidePerformanceCase.md" #include "wiki/SuiteReportFeatures.md" #include "wiki/HowItWorks.md" #include "wiki/SystemComponents.md" #include "wiki/ClientApplication.md" #include "wiki/ClientScripts.md" #include "wiki/TestExecutor.md" #include "wiki/Runner.md" #include "wiki/Worker.md" #include "wiki/WebAPI.md" #include "wiki/Cleaner.md" #include "wiki/TestProcessing.md" #include "wiki/LockMechanism.md" #include "wiki/DatabaseStructure.md" #include "wiki/Logs.md" #include "wiki/WhatsNew.md" #include "wiki/FAQ.md" #include "wiki/Troubleshooting.md" ======================= File: documentation/src/main/wiki/DataFilters.md ======================= <filename>documentation/src/main/wiki/DataFilters.md ### Data Filters Data filters are modules which narrow down the area which the comparison will be performed on. They are nested in [[Comparators]] and apply only to the instance of the comparator which they are defined in. Each data filter consists of two elements: * module name, * parameters. ##### Module name This name is a unique identifier for each data filter (and each module in the compare phase). ##### Parameters This is a set of key-value pairs the user can make use of to pass some configuration and information to the data filter. Parameters can be divided into two groups: * mandatory - parameters which filtering will be not possible without, * optional - passing this parameter is not obligatory, usually it triggers some functionality extension. ======================= File: documentation/src/main/wiki/ClientSidePerformanceCollector.md ======================= #### Client Side Performance Collector BETA |! Beta Version | |:------------ | | This AET Plugin is currently in a BETA version. | Client Side Performance Collector is responsible for collecting performance analysis results. The collector makes use of the [YSlow](http://yslow.org/) tool to perform analysis. Module name: **client-side-performance** |! Important information | | :---------------------- | | In order to use this collector *[[proxy|SuiteStructure#proxy]]* must be used. | ##### Parameters No parameters. ##### Example Usage ```xml <?xml version="1.0" encoding="UTF-8"?> <suite name="test-suite" company="cognifide" project="project" environment="win7-ff16"> <test name="source-test" useProxy="rest"> <collect> ... <client-side-performance /> ... </collect> <compare> ... </compare> <urls> ... </urls> </test> ... <reports> ... </reports> </suite> ``` ======================= File: documentation/src/main/wiki/CookieModifier.md ======================= #### Cookie Modifier Cookie Modifier allows to modify cookies for a given page, i.e. add or remove some cookies. Module name: **modify-cookie** |! Important information | |:----------------------- | | In order to use this modifier it must be declared before the open module in the definition of the test suite XML. When declared after the open module (but before Cookie Collector) it can be used as a filter for Cookie Collector. | ##### Parameters | Parameter | Value | Description | Mandatory | | --------- | ----- | ----------- | --------- | | `action` | add <br/> remove | Specifies what action should be taken with a given cookie | yes | | `cookie-name` | | Cookie name | yes | | `cookie-value` | | Cookie value | Yes, if the `add action` is chosen | | `cookie-domain` | | Cookie domain attribute value | No, used only if the `add action` is chosen | | `cookie-path` | | Cookie path attribute value | No, used only if the `add action` is chosen | |! Note | |:------ | | If `cookie-domain` is provided WebDriver will reject cookies unless the Domain attribute specifies a scope for the cookie that includes the origin server. For example, the user agent will accept a cookie with the Domain attribute `example.com` or `foo.example.com` from `foo.example.com`, but the user agent will not accept a cookie with a Domain attribute of `bar.example.com` or of `baz.foo.example.com`. For more information read [here](https://tools.ietf.org/html/rfc6265#section-4.1.2.3). | |! Note | |:------ | | If `cookie-path` is provided WebDriver will reject cookie unless the path portion of the url matches (or is a subdirectory of) the cookie's Path attribute, where the `%x2F` (`/`) character is interpreted as a directory separator. | ##### Example Usage ```xml <?xml version="1.0" encoding="UTF-8"?> <suite name="test-suite" company="cognifide" project="project"> <test name="cookie-modify-test"> <collect> ... <modify-cookie action="add" cookie-name="sample-cookie" cookie-value="sample-cookie-value"/> <modify-cookie action="remove" cookie-name="another-cookie"/> ... <open /> ... </collect> <compare> ... </compare> <urls> ... </urls> </test> ... <reports> ... </reports> </suite> ``` ======================= File: documentation/src/main/wiki/StatusCodesComparator.md ======================= #### Status Codes Comparator Status Codes Comparator is responsible for processing collected status codes. In this case it is simply displaying the list of collected status codes from given page. Status Codes feature do not allow to collect patterns, so it does not compare results with any patterns - rebase action is also not available. Module name: **status-codes** Resource name: status-codes ##### Parameters | Parameter | Value | Example | Description | Mandatory | | --------- | ----- | ------- | ----------- | --------- | | `filterRange` | x,y (default: `400,600`) | 400,500 | Defines **range** of status codes that should be processed | no | | `filterCodes` | x,y,z | 400,401,404 | **List** of status codes that should be processed | no | | `showExcluded` | boolean (default: `true`) | true | Used to show excluded status codes on report (see *Status Codes Data Filters*). | no | If you provide both `filterRange` and `filterCodes`, it will be used as logical sum. It means that: - `<status-codes filterRange="400,500" filterCodes="501,502" />` is equivalent to `<status-codes filterRange="400,502" />` - `<status-codes filterRange="300,400" filterCodes="404" />` won't check `401-403` codes. ##### Example Usage ```xml <?xml version="1.0" encoding="UTF-8"?> <suite name="test-suite" company="cognifide" project="project"> <test name="status-codes-test" useProxy="rest"> <collect> ... <open /> ... <status-codes /> ... </collect> <compare> ... <status-codes filterRange="400,404" /> ... </compare> <urls> ... </urls> </test> ... <reports> ... </reports> </suite> ``` ======================= File: documentation/src/main/wiki/RemoveRegexDataFilter.md ======================= #### Remove Regex Data Filter Remove Regex Data Filter allows to remove parts of source based on regex expressions from compared source (data and/or pattern). This may be helpful when we need to compare page sources with dynamic content. We can then remove these dynamic content markup. See also [Remove Lines](RemoveLinesDataFilter) and [Remove Nodes](RemoveNodesDataFilter) data Filters. Module name: **remove-regexp** Resource name: source ##### Parameters | Parameter | Value | Mandatory | | --------- | ----- | --------- | | `dataRegExp` |RegExp that will replace matched parts of *data* sources |At least one of parameter is required. | | `patternRegExp` | RegExp that will replace matched parts of *pattern* sources | | `regExp` | RegExp that will replace matched parts of *pattern and data* sources | |! Note | |:------ | | `regExp` value overrides `dataRegExp` and `patternRegExp` | Tip: Use [http://www.regexplanet.com/advanced/java/index.html](http://www.regexplanet.com/advanced/java/index.html) to create check your Regular Expression and when ready use 'as a Java string' value in your testsuite. ##### Example Usage ```xml <?xml version="1.0" encoding="UTF-8"?> <suite name="my-test-suite" company="cognifide" project="project"> <test name="remove-regex-test"> <collect> ... <source/> ... </collect> <compare> ... <source comparator="source"> <remove-regexp regExp='\"correlationId\": \".*\"'/> </source> ... </compare> <urls> ... </urls> </test> ... </suite> ``` ======================= File: documentation/src/main/wiki/releases/2.0.0/Documentation-2.0.0.md ======================= <filename>documentation/src/main/wiki/releases/2.0.0/Documentation-2.0.0.md<gh_stars>100-1000 - [Getting Started](#getting-started) - [What is AET](#what-is-aet) - [Why AET](#why-aet) - [AET In 10 Minutes](#aet-in-10-minutes) - [Prerequisites](#prerequisites) - [Vagrant setup](#vagrant-setup) - [Test setup](#test-setup) - [Run test](#run-test) - [Check results](#check-results) - [Build and upload application](#build-and-upload-application) - [Dictionary](#dictionary) - [How To Use](#how-to-use) - [Environment Setup](#environment-setup) - [Basic Setup](#basic-setup) - [Advanced Setup](#advanced-setup) - [Defining Suite](#defining-suite) - [Test suite](#test-suite) - [Example test suite](#example-test-suite) - [suite](#suite) - [Suite Structure](#suite-structure) - [Running Suite](#running-suite) - [Requirements](#requirements) - [Running suite from command line](#running-suite-from-command-line) - [Tips and recommendations](#tips-and-recommendations) - [Tracking Progress](#tracking-progress) - [Features](#features) - [Open](#open) - [Collectors](#collectors) - [Modifiers](#modifiers) - [Comparators](#comparators) - [Data Filters](#data-filters) - [Parameters](#parameters) - [Suite Report](#suite-report) - [What is suite report?](#what-is-suite-report) - [Levels of report](#levels-of-report) - [Test cases](#test-cases) - [Features](#features-1) - [How It Works](#how-it-works) - [System Components](#system-components) - [AET System architecture](#aet-system-architecture) - [Third-party software used by system](#third-party-software-used-by-system) - [Client Application](#client-application) - [Runner](#runner) - [Worker](#worker) - [REST API](#rest-api) - [Cleaner](#cleaner) - [Test Processing](#test-processing) - [Collection](#collection) - [Comparison](#comparison) - [Lock Mechanism](#lock-mechanism) - [Test suite run flow](#test-suite-run-flow) - [Database Structure](#database-structure) - [Overview](#overview) - [Metadata](#metadata) - [Artifacts](#artifacts) - [Logs](#logs) - [Overview](#overview-1) - [Log structue](#log-structue) - [Logs configuration](#logs-configuration) - [What's new](#whats-new) - [Migrate AET Suite to AET 2.0](#migrate-aet-suite-to-aet-20) - [Preparing the suite XML](#preparing-the-suite-xml) <!-- END doctoc generated TOC please keep comment here to allow auto update --> ![AET](/Cognifide/aet/wiki/assets/misc/aet-logo.png) # Getting Started ## What is AET AET (**A**utomated **E**xploratory **T**esting) is an online testing tool which aids front end client side layout regression testing of websites and portfolios. It allows team to ensure that a change in one part of the software did not introduce any defects in other parts of application. AET is a flexible application that can be adapted and tailored to the requirements of a given project. ## Why AET The aim of AET is to assure better quality of the software. This goal is achieved by a couple of factors. AET allows to easily and quickly create and maintain test as well as analyze their results. Because of that it encourages to cover wide part of software with tests. Test automation also has strong influence on test coverage, because AET is able to cover much bigger part of software than manual testing. Automation also helps to eliminate human errors as well as saves time. Finally, AET supports the continuous delivery of software. ## AET In 10 Minutes This is a quick guide showing how to setup AET environment and run an example test. ### Prerequisites Before start make sure that you have enough memory on your machine (8 GB is minimum, 16 GB recommended though). You need to download and install following software: * [VirtualBox 5.0](https://www.virtualbox.org/wiki/Downloads) * [Vagrant 1.8.1](https://www.vagrantup.com/downloads.html) * [ChefDK 0.11.0](https://downloads.chef.io/chef-dk/) * [Maven](https://maven.apache.org/download.cgi) (at least version 3.0.4) ### Vagrant setup Open command prompt as an administrator and execute the following commands: * `vagrant plugin install vagrant-omnibus` * `vagrant plugin install vagrant-berkshelf` * `vagrant plugin install vagrant-hostmanager` Navigate to the `vagrant` module directory. Run `berks install` and then `vagrant up` to start virtual machine. This process may take a few minutes. ### Test setup Create file named `suite.xml` with following content: ```xml <?xml version="1.0" encoding="UTF-8"?> <suite name="test-suite" company="company" project="project"> <test name="first-test" useProxy="rest"> <collect> <open/> <resolution width="800" height="600" /> <sleep duration="1500"/> <screen/> <source/> <status-codes/> <js-errors/> </collect> <compare xmlns="http://www.cognifide.com/aet/compare/"> <screen comparator="layout"/> <source comparator="w3c-html5"/> <status-codes filterRange="400,600"/> <js-errors> <js-errors-filter source="http://w.iplsc.com/external/jquery/jquery-1.8.3.js" line="2" /> </js-errors> </compare> <urls> <url href="https://en.wikipedia.org/wiki/Main_Page"/> </urls> </test> </suite> ``` Then create another file named `pom.xml` with following content: ```xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>test-group</groupId> <artifactId>test-project</artifactId> <version>1.0.0</version> <packaging>pom</packaging> <name>Test project</name> <url>http://www.example.com</url> <properties> <aet.version>1.4.3</aet.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <build> <plugins> <plugin> <groupId>com.cognifide.aet</groupId> <artifactId>aet-maven-plugin</artifactId> <version>${aet.version}</version> </plugin> </plugins> </build> </project> ``` It does not need to be in the same directory as `suite.xml` file. ### Run test Once you have created both `suite.xml` and `pom.xml` files open command prompt in the directory which contains `pom.xml` file and execute following command: ``` mvn aet:run -DtestSuite=full/path/to/suite.xml ``` Remember to provide path to your `suite.xml` file. ### Check results Once the test run finishes there should be `target` directory created inside a dicrectory containing the `pom.xml` file. Inside the `target` directory you should find `redirect.html` file. Open this file and the test report will show up in your web browser. Congratulations! You have successfully created and run your first AET test. ### Build and upload application You need JDK 8 and Maven 3.3.1 or newer to build AET application. To build and upload application use following command from application root: ``` mvn clean install -P upload ``` #### Vagrant upload prequisities: In order to be able to deploy bundles to Karaf instance define vagrant vm location in your setting.xml file (`$USER_HOME/m2`): ``` <server> <id>aet-vagrant-instance</id> <username>developer</username> <password><PASSWORD></password> <configuration> <sshExecutable>plink</sshExecutable> <scpExecutable>pscp</scpExecutable> </configuration> </server> ``` ## Dictionary *Active MQ* a *JMS (Java Message Service)* Server which is a basic communication channel between AET System components. *AET* an acronym for **A**utomatic **E**xploratory **T**esting, an online testing tool developed by Cognifide. *AET Core* a set of system modules that are crucial to whole system work. The AET system will not work properly without all core modules configured and running properly. *AET Jobs* implementations of jobs that can perform a particular task (e.g. collect screenshots, compare sources, validate a page against *W3C HTML5*). *AET Maven Plugin* a default client application for the AET system that is used to trigger the execution of the *Test Suite*. *Amazon Web Services* Cloud Computing Services where AET environment is setup. *Apache Karaf* see *Karaf*. *Artifact* usually used in the context of a small piece of data, the result of some operation (e.g. a collected screenshot or a list of *W3C HTML5* validation errors). *AWS* see *Amazon Web Services*. *Baseline* The act of taking a snap shot of the url/page and saving it to a file for future comparison in a number of ways to find differences. *Browsermob* a proxy server used by AET to collect some kinds of data from tested pages. *Cleaner* a module responsible for removing old and unused artefacts from the database. *Collector* a module responsible for gathering data necessary for its further processing (e.g. validation, comparison). *Collection* the first phase of the AET service during which all specified data is collected (e.g. screenshots, page source, js errors). Once they are collected successfully, all collection results are saved in the database. *Comparator* a module responsible for comparing data currently collected to its existing pattern or validating it against a set of defined rules. *Comparison* the second phase of the AET service that performs the operation on the data. collected during the first phase In some cases the collected data is compared to patterns, in others special validation is performed (e.g. *W3C HTML5*). The second phase starts before the collection finishes - just the moment when required artefacts are collected and become ready to be compared (e.g. to compare two screenshots system does not have to wait until the source of a page is collected). *Cookie Collector* a collector responsible for collecting cookies. *Cookie Comparator* a comparator responsible for processing collected cookies. *Cookie Modifier* a modifier that allows to modify cookies for a given page, i.e. to add or remove cookies. *Data Filter* a module responsible for filtering the collected data before performing comparison e.g. filtering uninteresting js errors before the js errors check takes place. *Data Storage* a database abstraction layer which contains versioned data (data grid). *Extract Element Modifier* a modifier that allows to extract an element from the html source (collected by the Screen Collector) by providing the id attribute or the class attribute. *Feature* a part of the AET system which covers full testing case e.g. layout - this feature consists of the Screen Collector, the screen comparator and the layout reporter module. *Firefox* a browser the AET tool makes use of, currently the version that is used is 30 en-US. *Header Modifier* a modifier responsible for adding additional headers to a page. *Hide Modifiers* a modifier responsible for hiding an element on a page that is unnecessary for a given test. *Html-report* a basic report in a form of a HTML file. *Java* a programming language that is used to develop the AET tool. *Java Development Kit* see *JDK*. *Java Management Extensions* see *JMX*. *Java Message Service* see *JMS*. *JavaScript* see *JS*. *JDK* the *Java Development Kit* is a program development environment for developing Java applications. *Jenkins* a continuous Integration (CI) server which is used as the user interface wrapper for the *AET Maven Plugin*. *Jetty* a simple Http Server, used as a container for web applications. *JMS* an acronym for the *Java Message Service*, simple message standard that allows application components to communicate with one another. *JMX* *Java Management Extensions* (JMX) is a technology that is used to manage and monitor advanced interfaces of Java applications. In the AET tool it is used to manage *ActiveMQ*. *JS* a dynamic programming language. *JS Error* a JavaScript error that occurs in a script during its execution. *JS Errors Collector* a collector responsible for collecting JavaScript errors occurring on a given page. *JS Errors Comparator* a comparator responsible for processing the collected JavaScript error resource. *JS Errors Filter* a filter that filters the results returned by the JS Errors Collector. It removes matched JavaScript errors from reports. *JUnit* a simple framework allowing to develop repeatable tests. It is an instance of the xUnit architecture for unit testing frameworks. More information about it can be found at: http://junit.org/. *Karaf* in fact *Apache Karaf* is an OSGi container that provides a basic configuration for existing OSGi implementations (e.g. Apache Felix). *Layout Comparator* a comparator responsible for comparing a collected screenshot of page to its pattern. *Login Modifier* a modifier that allows to log in into the application and access secured sites. *Maven* a software project management and comprehension tool. It used as a base for the *AET Maven Plugin*. *Modifier* a module responsible for converting the target before the data collection process is performed e.g. modifying a requested header, adding a new cookie, hiding a visible element. *MongoDB* an open-source cross-platform document-oriented database that the AET tool makes use of for data storage and management. MongoDB is developed by MongoDB Inc. *Open* A module that is a special operand for the Collect Phase. *OSGi* a modular system and services platform for Java. It is used as an application environment for AET Java components. *Pattern* a sample model of data. Collection results are compared to their patterns to discover potential differences. *pom.xml* a Maven tool configuration file that contains information about the project and configuration details used by Maven to build the project. *Rebasing* am operation changing the existing pattern to the current result. *Regression testing* This is a type of software testing that seeks to uncover new software bugs, or regressions, in existing functional and non-functional areas of a system. It is especially useful after changes such as enhancements, patches or configuration changes, have been made. *Remove Lines Data Modifier* a modifier that allows to remove lines from the source (data or pattern) that a given page is compared to. *Remove Nodes Data Modifier* a modifier that allows to delete some node(s) from a html tree. Node(s) are defined by the xpath selector. *Report (Web application)* Web application for viewing / browsing AET tests results. (Only chrome browser is supported for now). *Representational State Transfer API* see *Rest API*. *Resolution Modifier* a modifier responsible for changing the size of the browser screen. *Resource type* a unique name for the resource produced by the collector and consumed by the comparator. *Rest API* a Representational State Transfer API for the data stored in the AET Database. It enables the user to browse the data and artifacts stored after a run of the *Test Suite* was completed. *Runner* a unit responsible for the communication with the client and dispatching processing among workers. *SCM repository* a data structure storing metadata for a set of files that is managed by a source control management (SCM) system responsible for managing changes in files. The most popular examples of SCM systems are Git (http://git-scm.com/) and SVN (https://subversion.apache.org/). *Screen Collector* a collector responsible for collecting a screenshot of the page under a given URL. *Selenium* a portable software testing framework for web applications. *Selenium Driver* a test tool that allows to perform specific actions in a browser environment (e.g. take a screenshot of a page). *Sleep Modifier* a modifier responsible for ceasing the execution of a given test temporarily. It causes a current thread to sleep. *Source Collector* a collector responsible for collecting the source of a page under a given URL. Unlike other collectors the *Source Collector* does not use *Web Driver*. It connects directly to a web server. *Source Comparator* a comparator responsible for comparing a collected page source with its pattern. *Status Code* a response code for the resource request. For a detailed list of codes please refer to the Hypertext Transfer Protocol documentation at: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html. *Status Codes Collector* a collector responsible for collecting status codes for links to resources on a page under a given URL. *Status Codes Comparator* a comparator responsible for processing collected *Status Codes*. *Step* a single operation performed on url defined in `<collect>` phase of suite. *Test* a definition of logical set of *Test Cases* performed on a set of URLs. *Test Suite* a set of *Tests* (at least one) finished with the *Report*. *Test Case* a single URL *Test* against a feature, e.g. a *W3C HTML* page test, a screenshot for the resolution 800x600 test. *Thresholds* a feature allowing to declare a Jenkins build as ‘success’, ‘unstable’ or ‘failed’ depending on the number of *Tests* that failed or were skipped. *Wait For Page Loaded Modifier* a modifier that waits until a page is loaded or a fixed amount of time is up. *Web Console* the OSGi console installed on Apache Karaf. By default it is accessible via a browser: http://localhost:8181/system/console/configMgr. The default user/password are as follows: <PASSWORD>/karaf. *Worker* a single processing unit that can perform a defined amount of tasks (e.g. collect a screenshot, compare a source). *W3C HTML5 Comparator* a comparator responsible for validating a collected page source against *W3C HTML5* standards. *xunit-report* a *Report* that visualizes risks on the Jenkins job board and that contains information about the number of performed tests and the number of failures (potential threats). # How To Use ## Environment Setup There are two ways to setup AET environment: basic and advanced. ##### basic Basic setup uses [Vagrant](https://www.vagrantup.com/) to create a single virtual machine running Linux OS (currently CentOS 6.7). This virtual machine contains all AET services as well as all required software. In this configuration, tests are using Linux version of Firefox web browser. Please note that there are differences in web pages rendering between Linux and Windows versions of Firefox and if you want to use Windows then you must use advanced setup. See **[[Basic Setup|BasicSetup]]** for more details. Diagram below shows basic AET setup. ![aet-setup-basic](assets/diagrams/aet-setup-basic.png) ##### advanced Advanced setup on the other hand consists of two machines - one with Linux OS and one with Windows, both complementary to each other. Linux machine hosts services such as MongoDB, and ActiveMQ whereas Windows machine hosts Karaf, Browsermob proxy and Firefox. In this configuration, tests are using Windows version of Firefox web browser. See **[[Linux and Windows Setup|LinuxAndWindowsSetup]]** for more details. Diagram below shows advanced AET setup. ![aet-setup-advanced](assets/diagrams/aet-setup-advanced.png) ### Basic Setup This setup uses vagrant module, a pseudo-cookbook which is responsible for local environment provisioning using Vagrant (powered by Chef + Berkshelf under the hood). #### Overview Currently a virtual machine with the following services is created: * Karaf * Apache * Tomcat * ActiveMQ * MongoDb * Brosermob * Firefox * X environment #### AET services All services are running using default ports. For communication please use IP address: * `192.168.123.100` #### General prerequisites By default Vagrant virtual machine needs 3 GB of RAM and 2 vCPUs, so please make sure that you have enough memory on your machine (8 GB is minimum, 16 GB recommended though). #### Installation * Download and install [VirtualBox 5.0](https://www.virtualbox.org/wiki/Downloads) * Download and install [Vagrant 1.8.1](https://www.vagrantup.com/downloads.html) * Download and install [ChefDK 0.11.0](https://downloads.chef.io/chef-dk/) As an administrator execute the following commands: * `vagrant plugin install vagrant-omnibus` * `vagrant plugin install vagrant-berkshelf` * `vagrant plugin install vagrant-hostmanager` Whenever you'd like to keep all Vagrant related data and virtual machine disks in non-standard directories please: * set `VAGRANT_HOME` variable to new location (by default it is set to `$HOME/vagrant.d`). * update VirtualBox settings (`File -> Preferences -> General`) to move all disks to other directory. #### Starting virtual machine Once you set all described things up just execute: ``` berks update && vagrant destroy -f && vagrant up ``` #### First run All commands have to be executed when you're inside a directory that contains `Vagrantfile`. Next please execute: * `berks install` - downloads Chef dependencies from external sources. It acts as `mvn clean install`, but for Chef cookbooks. * `vagrant up` - creates new virtual machine (`.box` file will be downloaded during first run), runs Chef inside it, sets domains and port forwarding up. #### Updates Whenever new version is released please execute the following: * `git pull` to get latest version of `Vagrantfile`. * `berks update` to update Chef dependencies. * `vagrant provision` to re-run Chef on the virtual machine. #### SSH access To get into the virtual machine via SSH please execute `vagrant ssh` from the same directory that contains `Vagrantfile`. After that please type `sudo -i` and press ENTER to switch to `root`. If you prefer to use PuTTY, mRemote or any other connection manager, please log in as user `vagrant` with password `<PASSWORD>` on `localhost` port `2222`. Keep in mind that the port may be different if you have more than one Vagrant machine running at the same time. You can check current assignment by executing `vagrant ssh-config` command from directory that contains your `Vagrantfile`. #### Useful Vagrant commands * `vagrant reload` restarts Vagrant machine and re-applies settings defined in `Vagrantfile`. It's useful whenever you've changed port forwarding or synced folder configuration. * `vagrant destroy -f` deletes entire virtual machine. * `vagrant reload --provision` restarts virtual machine and re-run Chef afterwards. * `vagrant suspend` suspends currently running virtual machine. * `vagrant resume` resumes suspended virtual machine. * `vagrant status` show status of virtual machine described in `Vagrantfile`. * `vagrant halt` halts/turns off virtual machine. #### Port forwarding Local port is a port exposed on your machine. You can access services via `localhost:<PORT>`. VM port refers to port assigned inside Vagrant's virtual machine. Port forwarding rules can be easily changed in `Vagrantfile`. | Local port | VM port | Description | | ---------- | ------- | ----------- | | 8181 | 8181 | Karaf | #### Known Issues * When getting following error on deploying application to local vagrant: ``` What went wrong: Execution failed for task ':deployDevClearCache'. > java.net.ConnectException: Connection timed out: connect ``` run `ifup eth1` command on vagrant using ssh. ### Advanced Setup #### Operating Systems setup ![aet-setup-advanced](assets/diagrams/aet-setup-advanced.png) This section describes advanced setup of AET using Linux and Windows. The main advantage of this approach is ability to run tests on Firefox on Windows, which is more reliable than Firefox on Linux. Please note that full list of required tools and its versions can be found in [System Components](SystemComponents) section. ##### Linux Setup 1. Turn off Firewall. This may be achieved differently on various linux distribution, for example on CentOS `selinux` and `iptables` should be disabled. 2. Install MongoDB in version 2.6.4-1 3. Install JDK from Oracle (1.7) 4. Install ActiveMQ in version 5.9.0 * Enable JMX for ActiveMQ with connector under port `11199` * Switch Persistence for ActiveMQ * Enable cleaning unused topic for ActiveMQ 5. Install Apache Server * Configure site for the following path: `/opt/aet/apache/aet_reports/current` ##### Windows Setup 1. Install Java 7 JDK and update JAVA_HOME environment variable. 2. Change default console resolution - install VNC server (e.g. http://www.tightvnc.com/), connect by VNC client to console and change resolution (min. 1024x768). 3. Turn off Windows Firewall (both, private and public network location settings). 4. Install Karaf in version 2.3.9 * Update Apache Felix Framework to version 4.2.1 * Install Karaf as a Windows service * Check if it's working under http://localhost:8181/system/console/ and credentials karaf/karaf. 5. Install Browsermob in version 2.0.0 * Install Browsermob as a Windows service * Check if it's working under http://localhost:9272/proxy. 6. Install Firefox 38.6.0 ESR * Turn off automatic updates 7. Check the following connections between Windows and Linux: * MongoDB: `telnet ${LINUX_MACHINE_PRIVATE_IP} 27017` * ActiveMQ: `telnet ${LINUX_MACHINE_PRIVATE_IP} 61616` * ActiveMQ's JMX: `jconsole.exe ${LINUX_MACHINE_PRIVATE_IP}:11199` ##### AET deployment Here's a description where to deploy all the artifacts. | Artifact | Environment | Default folder | | ------------ | --------------- | ----------------------------------- | | bundles.zip | Windows - Karaf | /deploy | | features.zip | Windows - Karaf | /deploy | | configs.zip | Windows - Karaf | /etc | | report.zip | Linux - Apache | /opt/aet/apache/aet_reports/current | #### OSGi Configuration This section describes how to configure the AET OSGi services so that they could connect to the appropriate system components. The services are configured through the Karaf Web Console which is hosted on Windows machine. Assuming that this machine's IP address is `192.168.0.2`, the Karaf console is available under following address: http://192.168.0.2:8181/system/console/configMgr. ##### Assumptions The example configuration assumes the following: * The IP address of Linux machine is `192.168.0.1` * The IP address of Windows machine is `192.168.0.2` * The Apache HTTP server serves Reports application under domain `http:\\aet-report` ##### Connections configuration The diagram below shows which AET OSGi service should connect to which system component on the appropriate machine. On the diagram the arrows point from the AET services to the system components. The notes on the arrows contain the properties of each service which should be set and example values according to assumptions stated above. ![aet-osgi-configuration](assets/diagrams/aet-osgi-configuration.png) ##### Collectors and comparators configuration There are two more services that require configuration which are not present on the diagram above. The services are **AET Collector Message Listener** and **AET Comparator Message Listener**. There must be at least one of each of those services configured. Below there are listed the properties of each of above mentioned services with required values. ###### AET Collector Message Listener | Property name | Value | | ------------- | ----- | | Collector name | Has to be unique within Collector Message Listeners. | | Consumer queue name | Fixed value `AET.collectorJobs` | | Producer queue name | Fixed value `AET.collectorResults` | | Embedded Proxy Server Port | Has to be unique within Collector Message Listeners. | ###### AET Comparator Message Listener | Property name | Value | | ------------- | ----- | | Comparator name | Has to be unique within Comparator Message Listeners. | | Consumer queue name | Fixed value `AET.comparatorJobs` | | Producer queue name | Fixed value `AET.comparatorResults` | ## Defining Suite ### Test suite In general the test suite is an XML document that defines tests performed over collection of web pages. This chapter covers test suite API, with description of each element. ### Example test suite ```xml <?xml version="1.0" encoding="UTF-8"?> <!-- Each test suite consists of one suite --> <suite name="test-suite" company="cognifide" project="project"> <!-- The First test of Test Suite --> <!-- The flow is [collect] [compare] [urls] --> <test name="first-test" useProxy="rest"> <!-- Description of the collect phase --> <collect> <open/> <resolution width="800" height="600" /> <!-- sleep 1500 ms before next steps - used on every url defined in urls --> <sleep duration="1500"/> <screen/> <source/> <status-codes/> <js-errors/> </collect> <!-- Description of compare phase, says what collected data should be compared to the patterns, can also define the exact comparator. If none chosen, the default one is taken. --> <compare xmlns="http://www.cognifide.com/aet/compare/"> <screen comparator="layout"/> <source comparator="w3c-html5"/> <status-codes filterRange="400,600"/> <js-errors> <js-errors-filter source="http://w.iplsc.com/external/jquery/jquery-1.8.3.js" line="2" /> </js-errors> </compare> <!-- List of urls which will be taken into tests --> <urls> <url href="http://www.cognifide.com"/> </urls> </test> </suite> ``` Root element of test suite definition is `suite` element. ### suite |! Important | |:----------- | | When defining a suite a user should think of three mandatory parameters properly: `name, company, project`. Those parameters are used by the AET System to identify the suite. <br/><br/> Any change in one of those parameters values in the future will occur in treating the suite as a completely new one, which will in effect gather all the patterns from scratch. | Root element for xml definition, each test suite definition consists of exactly one `suite` tag. | Attribute name | Description |Mandatory | | -------------- | ----------- | --------- | | `name` | Name of the test suite. Should consist only of lowercase letters, digits and/or characters: `-`, `_`. | yes | | `company` | Name of the company. Should consist only of lowercase letters, digits and/or characters: `-`.| yes | | `project` | Name of the project. Should consist only of lowercase letters, digits and/or characters: `-`.| yes | | `domain` | General domain name consistent for all considered urls. Every url link is built as a concatenation of *domain* name and *href* attribute of it. If `domain` property is not set, then `href` value in `url` definition should contain full valid url. See more in [[Urls|Urls]] section. | no | `suite` element contains one or more **[[test|SuiteStructure#test]]** elements. ### Suite Structure #### test This tag is definition of the single test in test suite. Test suite can contain many tests. | Attribute name | Description | Mandatory | | -------------- | ----------- | --------- | | `name` | Name of the test. Should consists only of letters, digits and/or characters: `-`, `_`. This value is also presented on report (more details in [[Suite Report|SuiteReport]] section). | yes | | `useProxy` | Defines which (if any) *Proxy* should be used during collection phase. If not provided, empty or set with `"false"`, proxy won't be used. If set to `"true"`, default *Proxy Manager* will be used. Otherwise *Proxy Manager* with provided name will be used (see [Proxy](#proxy)). Proxy is needed by Status Codes Collector and Header Modifier. | no | | `zIndex` | Specifies order of tests on *HTML Report*. A test with greater `zIndex` is always before test with lower value. Default value is `0`. This attribute accepts integers in range `<-2147483648; 2147483647>`. | no | Each **test** element contains: * **one [collect](#collect) and one [compare](#compare) element** - test execution phases, * **one [urls](#urls) element** - list of urls to process. ##### Proxy Proxy is provided by two separated implementations: *embedded* and *rest*. ###### *embedded* *Embedded* proxy does not need standalone *[[Browsermob Server|WindowsSetup#browsermob-proxy-setup]]*, but does not support SSL. *Embedded* proxy is used as default when `useProxy` is setted to "true" (which is equivalent to setting `useProxy="embedded"`*)*. **Example usage** ```xml <?xml version="1.0" encoding="UTF-8"?> <suite name="test-suite" company="cognifide" project="project"> <test name="header-modify-test" useProxy="embedded"> ... </test> ... </suite> ``` ###### rest *Rest* proxy requires standalone *[[Browsermob Server|WindowsSetup#browsermob-proxy-setup]]*. **Example usage** ```xml <?xml version="1.0" encoding="UTF-8"?> <suite name="test-suite" company="cognifide" project="project"> <test name="header-modify-test" useProxy="rest"> ... </test> ... </suite> ``` #### collect This tag contain list of collectors and modifiers which will be run. It specifies what pages' data should be collected and it allows for some data modification before collection step. All collect steps are processed in defined order. Each collector provides some specific result of gathering current data (i.e. png, html files) and a common metadata file - `result.json`. Following elements are available in `collect` element: * **[[Open|Open]]** * **[[Collectors|Collectors]]** * **[[Modifiers|Modifiers]]** #### compare This tag contain list of **[[Comparators]]**. Each comparator takes collected resource of defined type and runs it against comparator. It provides some specific result files illustrating found differences (i.e png, html files) and a common metadata file - `result.json`. Each resource type has default comparator, user can use other comparators for each type by providing attribute `comparator` with comparator name, e.g.: ```xml <source comparator="my_source_comparator"/> ``` runs `my_source_comparator` against each source collected during collection phase. Each comparator can contain list of **[[Data Filters|DataFilters]]** which will be performed before each compare phase. Data filters are used to modify gathered data before these data are passed to comparator. For example you may remove some node from html tree. Data filters are defined in test suite xml as subnodes of `comparator` node. Each Data Filter has predefined type of data on which it operates. #### urls See [[Urls]]. ## Running Suite Currently, running an AET suite requires using *aet-maven-plugin* which is an AET client application. ### Requirements * Maven installed (recommended version - 3.0.4). * Proper version of AET Maven plugin installed. * Well-formed and valid xml test suite file available (described with details in [[Defining Suite|DefiningSuite]] chapter), * `pom.xml` file with defined *aet-maven-plugin* configuration (described below). #### pom.xml This file (`pom.xml`) is a *Maven* tool configuration file that contains information about the project and configuration details used by *Maven* to build the project. Running AET suite requires creating and configuring such a file. The File presented below might be used as a template for setup AET suite runs: ```xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>{PROJECT-GROUP}</groupId> <artifactId>{PROJECT-NAME}</artifactId> <version>1.0.0</version> <packaging>pom</packaging> <name>Tests</name> <url>http://www.example.com</url> <properties> <aet.version>{PLUGIN-VERSION}</aet.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <build> <plugins> <plugin> <groupId>com.cognifide.aet</groupId> <artifactId>aet-maven-plugin</artifactId> <version>${aet.version}</version> </plugin> </plugins> </build> </project> ``` User should configure three variables before proceeding to the next steps: * `{PROJECT-GROUP}` which is a group the project belongs to. It should follow the package name rules, i.e. it is reversed domain name controlled by project owner and consists of lowercase letters and dots, * example: `com.example.test` * `{PROJECT-NAME}` which is this build identifier for *Maven* tool. It should consist only of lowercase letters and `-` characters, * example: `aet-sanity-test` * `{PLUGIN-VERSION}` which should be set to the *aet-maven-plugin* version currently used * example: `1.0.0` Having the version as the maven property (`${aet.version}`) enables defining this parameter from the command line later, e.g. `-Daet.version=1.1.0`. ### Running suite from command line Running the AET suite with *AET Maven plugin* from the command line can be done by invoking a maven command in the directory where the `pom.xml` file has been defined: ``` mvn aet:run -DtestSuite=FULL_PATH_TO_TEST_SUITE ``` The `testSuite` parameter is the path to the xml suite configuration file. During test suite processing there will be information on its progress displayed in the console. It reflects how many artifacts were currently collected, compared and reported. When processing is finished the information about the processing status - `BUILD SUCCESS` or `BUILD FAILURE` - is displayed in the console. When the test run completes, the resulting report files can be found in the maven run `target` folder. Check [[Client Application|ClientApplication]] for more details about `aet-maven-plugin`. ### Tips and recommendations Generally it is a good idea to create a separate **SCM repository** (e.g. *GIT* or *SVN*) for AET suites. This will enable running AET suites using Jenkins easily. ### Tracking Progress #### How to read AET Reports and real time progress AET test reports are updated on real time basis and can be viewed on the console. This progress information is accessible in using two methods: as a command line and with use of Jenkins job. To see progress * log on Jenkins * choose proper build execution from Build history panel and * click Console Output. For every test suite started the execution information is provided in the progress log: ``` [INFO] ******************************************************************************** [INFO] ********************** Job Setup finished at 10:14:43.249.********************** [INFO] *** Suite is now processed by the system, progress will be available below. **** [INFO] ******************************************************************************** ``` During test processing detailed information about actual progress is displayed as in the following example: ``` ... [INFO] [06:34:20.680]: COLLECTED: [success: 0, total: 72] ::: COMPARED: [success: 0, total: 0] [INFO] [06:34:31.686]: COLLECTED: [success: 1, total: 72] ::: COMPARED: [success: 1, total: 1] [INFO] [06:34:35.689]: COLLECTED: [success: 2, total: 72] ::: COMPARED: [success: 1, total: 2] [INFO] [06:34:36.691]: COLLECTED: [success: 2, total: 72] ::: COMPARED: [success: 2, total: 2] [INFO] [06:34:43.695]: COLLECTED: [success: 3, total: 72] ::: COMPARED: [success: 2, total: 3] [INFO] [06:34:44.698]: COLLECTED: [success: 3, total: 72] ::: COMPARED: [success: 3, total: 3] ... ``` where: **collected** - shows results of collectors' work - how many artifacts have been successfully collected and what is the total number of all artifacts to be collected, **compared** - shows results of comparators' work - how many artifacts have been successfully compared and what is the total number of all artifacts to be compared. The total number of artifacts to be compared depends on collectors' work progress - increases when the number of successfully collected artifacts increase. If there are problems during processing, warning information with some description of processing step and its parameters is displayed: ``` [WARN] CollectionStep: source named source with parameters: {} thrown exception. TestName: comparator-Source-Long-Response-FAILED UrlName: comparators/source/failed_long_response.jsp Url: http://192.168.123.100:9090/sample-site/sanity/comparators/source/failed_long_response.jsp ``` In this example source collector failed to collect necessary artifacts. This information is subsequently reflected in the progress log: ``` ... [INFO] [06:36:44.832]: COLLECTED: [success: 46, failed: 1, total: 72] ::: COMPARED: [success: 46, total: 46] [INFO] [06:36:50.837]: COLLECTED: [success: 47, failed: 1, total: 72] ::: COMPARED: [success: 47, total: 47] [INFO] [06:36:52.840]: COLLECTED: [success: 48, failed: 1, total: 72] ::: COMPARED: [success: 47, total: 48] ... ``` In the example above one artifact has failed during collection phase. #### When tests successfully finish - command line When the AET test processing completes the information about received reports and processing status - BUILD SUCCESS or BUILD FAILURE is shown on the console - as shown below: ``` [INFO] Received report message: ReportMessage{company=aet-demo-sanity, project=demo-sanity-test, testSuiteName=main, status=OK, environment=win7-ff16, domain=http://192.168.123.100:9090/sample-site/sanity/, correlationId=aet-demo-sanity-demo-sanity-test-main-1426570459612} [INFO] [06:38:03.549]: COLLECTED: [success: 71, failed: 1, total: 72] ::: COMPARED: [success: 71, total: 71] [INFO] Received report message: ReportMessage{company=aet-demo-sanity, project=demo-sanity-test, testSuiteName=main, status=OK, environment=win7-ff16, domain=http://192.168.123.100:9090/sample-site/sanity/, correlationId=aet-demo-sanity-demo-sanity-test-main-1426570459612} [INFO] Total: 2 of 2 reports received. [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 3:45.645s [INFO] Finished at: Tue Mar 17 06:38:03 CET 2015 [INFO] Final Memory: 14M/246M [INFO] ------------------------------------------------------------------------ ``` BUILD SUCCESS - status means that test processing is successfully finished and reports are generated in target folder. BUILD FAILURE - status means that there were some technical problem during processing for example database is not responding and it is not possible to receive reports. #### When test is successfully finished - Jenkins job Jenkins console output presents the same information as described above, but if test suite is defined to generate xunit-report additional information such as Junit processing is logged on console: ``` [xUnit] [INFO] - Starting to record. [xUnit] [INFO] - Processing JUnit [xUnit] [INFO] - [JUnit] - 1 test report file(s) were found with the pattern 'test-suite/target/xunit-report.xml' relative to '/var/lib/jenkins/jobs/aet-sanity-test-integration/workspace' for the testing framework 'JUnit'. [xUnit] [INFO] - Converting '/var/lib/jenkins/jobs/aet-sanity-test-integration/workspace/test-suite/target/xunit-report.xml'. [xUnit] [INFO] - Check 'Failed Tests' threshold. [xUnit] [INFO] - The new number of tests for this category exceeds the specified 'new unstable' threshold value. [xUnit] [INFO] - Setting the build status to UNSTABLE [xUnit] [INFO] - Stopping recording. Build step 'Publish xUnit test result report' changed build result to UNSTABLE Finished: UNSTABLE ``` The meaning of '*Successful*' and '*Failed*' build is quite different here, because final build status depends mainly on tests results and thresholds configuration. The build can result with BUILD SUCCESS status (which means that all workers - collectors, comparators, reporters finish their work and proper reports were generated), but final Jenkins build status can be for example UNSTABLE becase there were some new test failures. A Jenkins build is considered as UNSTABLE (yellow) or FAILURE (red) if the new (tests that failed now, but did not fail in previous run) or total number of failed tests exceeds the specified thresholds. For example:when "yellow total" threshold is set to 0 and one or more test cases failed, then build is mark as UNSTABLE. ## Features AET tests can use a number of useful features which check different elements of the page. You can find more information about them in subpages of this page. Below you can find a few common cases which demonstrate how to use those features. ##### Compare layout without dynamic content This is the case where you want to test layout of some page by making a screenshot of page in specified resolution. Your page has some dynamic content e.g. carousel or advertisement and you don't want it to influence the results of your test. The following code snippet shows the test suite for such case: ```xml <?xml version="1.0" encoding="UTF-8"?> <suite name="test-suite" company="company" project="project"> <test name="first-test" useProxy="rest"> <collect> <open/> <hide xpath="//div[@id='mw-panel']" /> <resolution width="800" height="600" /> <sleep duration="1500"/> <screen/> </collect> <compare> <screen comparator="layout"/> </compare> <urls> <url href="https://en.wikipedia.org/wiki/Main_Page"/> </urls> </test> </suite> ``` This test checks the layout of Wikipedia's main page. After opening page the [[Hide Modifier|HideModifier]] is used to hide the navigation bar on the left side of page. Then the [[Resolution Modifier|ResolutionModifier]] is used to set the screenshot resolution to `800x600` and [[Screen Collector|ScreenCollector]] makes a screenshot. Finally [[Layout Comparator|LayoutComparator]] compares page layout with previous test run. ##### Collect status codes from desired range This is the case when you want to check the status codes of requests generated by page and you are only interested in specific range of codes, e.g. client errors (codes 400-499). The following code snippet shows the test suite for such case: ```xml <?xml version="1.0" encoding="UTF-8"?> <suite name="test-suite" company="company" project="project"> <test name="first-test" useProxy="rest"> <collect> <open/> <status-codes /> </collect> <compare> <status-codes filterRange="400,499" /> </compare> <urls> <url href="https://en.wikipedia.org/wiki/Main_Pagee"/> </urls> </test> </suite> ``` This test uses [[Status Codes Collector|StatusCodesCollector]] to gather status codes for given url (which in this case points to non-existent resource). Then the [[Status Codes Comparator|StatusCodesComparator]] is used to display status codes that fit within range from `400` to `499`. ##### Add cookie to remove cookie consent dialog This is the case when you want to dismiss a dialog asking for a consent for storing cookies which has to be displayed if the page needs to be compliant with EU legislation. Some pages use cookies to determine if the dialog should be displayed. The following code snippet shows the test suite for such case: ```xml <suite name="test-suite" company="company" project="project"> <test name="first-test" useProxy="rest"> <collect> <modify-cookie action="add" cookie-name="eu_cn" cookie-value="1" /> <open/> <sleep duration="1500"/> <screen/> </collect> <compare> <screen comparator="layout"/> </compare> <urls> <url href="http://example.com/"/> </urls> </test> </suite> ``` This test uses [[Cookie Modifier|CookieModifier]] to add a cookie named `eu_cn` with value `1` which in this example tells that the user already gave consent to store cookies. After that the screenshots is collected and the layout of page is compared with previous test. ##### Collect JavaScript errors and ignore specific ones This is the case when you want to check if there are any JavaScript errors on the page. You know that, for example, some third party library used has an error but you don't want it to affect your test. The following code snippet shows the test suite for such case: ```xml <suite name="test-suite" company="company" project="project"> <test name="first-test" useProxy="rest"> <collect> <open/> <js-errors/> </collect> <compare> <js-errors> <js-errors-filter error="Uncaught ReferenceError: variable is not defined"/> </js-errors> </compare> <urls> <url href="http://example.com/"/> </urls> </test> </suite> ``` This test uses [[JS Errors Collector|JSErrorsCollector]] to collect JavaScript errors. Then the [[JS Errors Comparator|JSErrorsComparator]] is used do display the issues. Within comparator the [[JS Errors Data Filter|JSErrorsDataFilter]] ignoring specified error is defined. ##### Compare source ignoring embedded scripts This is the case, when you want to check source of the page but you want to exclude some code from comparison. It could be, for instance, an embedded analytics script. The following code snippet shows the test suite for such case: ```xml <suite name="test-suite" company="company" project="project"> <test name="first-test" useProxy="rest"> <collect> <source /> </collect> <compare> <source comparator="source" compareType="allFormatted"> <remove-nodes xpath="//script" /> </source> </compare> <urls> <url href="https://en.wikipedia.org/wiki/Main_Page"/> </urls> </test> </suite> ``` This test uses [[Source Collector|SourceCollector]] to gather source code. Then [[Source Comparator|SourceComparator]] compares source of the page with previous test. The applied [[Remove Nodes Data Filter|RemoveNodesDataFilter]] removes all `<script>` nodes from source before comparison takes place. ### Open Open module is special operand for collect phase. It is responsible for opening web page for given url and preparing browser environment to perform chain of collections and modifications. Second usage of this module is to allow user easily perform actions before page is being opened, such as modify headers, cookies etc. |! Open module | |:------------- | | Each collect phase **must** contain open module. | |! Note | |:------ | | In some cases it is recommended to use **[[Sleep Modifier|SleepModifier]]** or **[[Wait For Page Loaded Modifier|WaitForPageLoadedModifier]]** after open module. | Module name: **open** #### Parameters No parameters #### Example Usage ```xml <?xml version="1.0" encoding="UTF-8"?> <suite name="test-suite" company="cognifide" project="project"> <test name="open-test"> <collect> ... <!-- example action before page is opened --> <open/> <!-- collect page data --> ... </collect> <compare> ... </compare> <urls> ... </urls> </test> ... <reports> ... </reports> </suite> ``` ### Collectors Collector is module which main task is to collect data from tested pages. Each collector presented in section below consist of two elements: * module name (produced resource type), * parameters. ##### Module name (produced resource type) This name is unique identifier of system functionality. Each collector has its unique name, this name should be also unique for all modules in *[[collect|SuiteStructure#collect]]* phase. This is always name of tag definition for collector. AET System does not know what work will be performed by collector when it reads suite definition. The only thing that is known is **module name**. System will recognize which collector should be called by matching definition from *[[collect|SuiteStructure#collect]]* phase with name registered in system. When no collector in system with defined name is found, system exception will occur and test will be not performed. This solution enables adding new features to the system without system downtime (just by installing new feature bundle). Each collector produces resource of defined type. This type can be later recognized by [[comparators |Comparators]] and [[data filters|DataFilters]]. Two collectors can't produce data with the same resource type. **Produced resource type is always equal to collector module name.** ##### Parameters This is set of key-value pairs using which user can pass some configuration and information to collector. Parameters for collectors are usually not mandatory - passing this parameter is not obligatory, usually this is some collector functionality extension. However, there is one special property: **name**. Collector with set name can be treated in special way by [[comparators|Comparators]] (some comparators may look only for collection results from specifically named collectors), example: ```xml ... <collect> <open/> <sleep duration="1000"/> <screen width="1280" height="1024" name="desktop"/> <screen width="768" height="1024" name="tablet"/> <screen width="320" height="480" name="mobile"/> </collect> <compare> <screen collectorName="mobile"/> </compare> ... ``` During collect phase, three screenshot with different resolutions will be taken and saved to database. However, only one of them (*mobile*) will be compared with pattern during comparison phase and presented on report (under "*Layout For Mobile*" section). ##### Definitions illustration Following picture presents elements described earlier: ![Collect phase definitions](assets/diagrams/collect-phase-definitions.png) where: 1. Module name (produced resource type), 2. Parameters, 3. Special collector property: name, 4. Special comparator property: collectorName. #### Accessibility Collector BETA |! Beta Version | |:------------ | | This AET Plugin is currently in BETA version. | Accessibility Collector is responsible for collecting validation result containing violations of a defined coding standard found on a page. It uses [HTML_CodeSniffer](http://squizlabs.github.io/HTML_CodeSniffer/) tool to find violations. Module name: **accessibility** ##### Parameters | Parameter | Value | Description | Mandatory | | --------- | ----- | ----------- | --------- | | `standard` |WCAG2A<br/> WCAG2AA (default)<br/> WCAG2AAA | Parameter specifies a standard against which the page is validated. More information on standards: [WCAG2](http://squizlabs.github.io/HTML_CodeSniffer/Standards/WCAG2/) | no | ##### Example Usage ```xml <?xml version="1.0" encoding="UTF-8"?> <suite name="test-suite" company="cognifide" project="project"> <test name="source-test"> <collect> ... <accessibility standard="WCAG2AAA" /> ... </collect> <compare> ... </compare> <urls> ... </urls> </test> ... <reports> ... </reports> </suite> ``` #### Client Side Performance Collector BETA |! Beta Version | |:------------ | | This AET Plugin is currently in BETA version. | Client Side Performance Collector is responsible for collecting performance analysis result. It uses [YSlow](http://yslow.org/) tool to perform analysis. Module name: **client-side-performance** |! Important information | |:----------------------- | | In order to use this collector **proxy** must be used. | ##### Parameters No parameters. ##### Example Usage ```xml <?xml version="1.0" encoding="UTF-8"?> <suite name="test-suite" company="cognifide" project="project" environment="win7-ff16"> <test name="source-test" useProxy="rest"> <collect> ... <client-side-performance /> ... </collect> <compare> ... </compare> <urls> ... </urls> </test> ... <reports> ... </reports> </suite> ``` #### Cookie Collector Cookie collector is responsible for collecting cookies. Module name: **cookie** ##### Parameters No parameters. ##### Example Usage ```xml <?xml version="1.0" encoding="UTF-8"?> <suite name="test-suite" company="cognifide" project="project"> <test name="cookie-test"> <collect> ... <cookie/> ... </collect> <compare> ... </compare> <urls> ... </urls> </test> ... <reports> ... </reports> </suite> ``` #### JS Errors Collector JS Errors Collector is responsible for collecting javascript errors occuring on given page. Module name: **js-errors** ##### Parameters No parameters. ##### Example Usage ```xml <?xml version="1.0" encoding="UTF-8"?> <suite name="test-suite" company="cognifide" project="project"> <test name="js-errors-test"> <collect> ... <js-errors/> ... </collect> <compare> ... </compare> <urls> ... </urls> </test> ... <reports> ... </reports> </suite> ``` #### Screen Collector |! Compare collected screenshot | |:------------------------------ | | Please remember that defining collector and not using it during comparison phase is configuration error. From now on suites that define screen collection and does not use it during comparison phase will be rejected during suite validation phase. | |! Notice | | :---------- | | Since AET 1.4.0 version AET Screen Collector will have no parameters. Please use [[Resolution Modifier|ResolutionModifier]] in order to perform browser resolution change. Using Screen collector without resolution change will not guarantee any specific screenshot resolution. | Screen Collector is responsible for collecting screenshot of the page under given URL. Module name: **screen** **Note that you cannot maximize the window and specify the dimension at the same time. If no parameters provided, default browser size is set before taking screenshot.** ##### Example Usage ```xml <?xml version="1.0" encoding="UTF-8"?> <suite name="test-suite" company="cognifide" project="project"> <test name="screen-test"> <collect> ... <screen name="desktop" /> ... </collect> <compare> ... </compare> <urls> ... </urls> </test> ... <reports> ... </reports> </suite> ``` Instead of ```xml <screen width="1280" height="1024" name="desktop" /> ``` please use: ```xml <resolution width="1280" height="1024"/> <sleep duration="1000" /> <screen name="desktop" /> ``` |! Note | |:------ | | Before taking screenshot [[Hide modifier|HideModifier]] can be applied in order to hide from the screen some elements that are not necessary for comparison, i.e. Twitter feed. <br/><br/> Also [[Resolution Modifier|ResolutionModifier]] and [[Wait For Page Loaded Modifier|WaitForPageLoadedModifier]] can be applied before Screen Collector usage to change expected collect result. <br/><br/> As in example presented above, `name` parameter can be very useful when using screen collector. More information about this parameter can be found in [[Collectors|Collectors]] section. | #### Source Collector Source Collector is responsible for collecting source of the page under given URL. Unlike others collectors source collector doesn't use web driver, it connects directly to web server. Module name: **source** |! Note | | :-------- | | System is waiting up to 20 seconds before request is timed out. This parameter is not configurable. | ##### Parameters No parameters. ##### Example Usage ```xml <?xml version="1.0" encoding="UTF-8"?> <suite name="test-suite" company="cognifide" project="project"> <test name="source-test"> <collect> ... <source /> ... </collect> <compare> ... </compare> <urls> ... </urls> </test> ... <reports> ... </reports> </suite> ``` #### Status Codes Collector Status Codes Collector is responsible for collecting status codes of links to resources on the page under given URL. Module name: **status-codes** |! Important information | | :---------------------- | | In order to use this collector *[[proxy|SuiteStructure#proxy]]* must be used. | ##### Parameters No parameters. ##### Example Usage ```xml <?xml version="1.0" encoding="UTF-8"?> <suite name="test-suite" company="cognifide" project="project"> <test name="status-codes-test"> <collect> ... <status-codes /> ... </collect> <compare> ... </compare> <urls> ... </urls> </test> ... <reports> ... </reports> </suite> ``` ### Modifiers Modifier is module which performs particular modification on data before collection happens. Each modifier consists of two elements: * module name, * parameters. ##### Module name This name is unique identifier for each modifier (and each module in collect phase). ##### Parameters This is set of key-value pairs using which user can pass some configuration and information to modifier. Parameters for modifiers can be divided into two groups: * mandatory - parameters without which modification will not be possible, * optional - passing this parameter is not obligatory, usually they trigger some functionality extensions. #### Click Modifier Click Modifier allows to perform click action on some element on page. When element is not found (e.g. by improper xpath value) warning will be logged but test will be passed to the next steps. Module name: **click** |! Important information | |:----------------------- | | In order to use this modifier it must be declared after open module in test suite XML definition.<br/><br/> Remember that element that will be clicked **must be visible** in the moment of performing click action. | ##### Parameters | Parameter | Default value | Description | Mandatory | | --------- | ------------- | ----------- | --------- | | `xpath` | | xpath of element to click | yes | | `timeout` | | Timeout for element to appear, in milliseconds. Max value of this parameter is 15000 milliseconds (15 seconds). | yes | ##### Example Usage ```xml <?xml version="1.0" encoding="UTF-8"?> <suite name="test-suite" company="cognifide" project="project"> <test name="click-test"> <collect> <open /> ... <click xpath="//*[@id='header_0_container1_0_pRow']/div[1]/div/div/a/img" timeout="3000" /> <sleep duration="2000" /> ... <resolution width="1280" height="800" /> <screen name="desktop" /> ... </collect> <compare> ... <screen comparator="layout" /> ... </compare> <urls> ... </urls> </test> ... <reports> ... </reports> </suite> ``` #### Cookie Modifier Cookie Modifier allows to modify cookies for given page, i.e. add or remove some cookies. Module name: **modify-cookie** |! Important information | |:----------------------- | | In order to use this modifier it must be declared before open module in test suite XML definition. When declared after open module (but before Cookie Collector) it can be used as filter for Cookie Collector. | ##### Parameters | Parameter | Value | Description | Mandatory | | --------- | ----- | ----------- | --------- | | `action` | add <br/> remove | Specifies what action should be taken with given cookie | yes | | `cookie-name` | | Cookie name | yes | | `cookie-value` | | Cookie value | Yes, if `add action` is chosen | | `cookie-domain` | | Cookie domain attribute value | No, used only if `add action` is chosen | | `cookie-path` | | Cookie path attribute value | No, used only if `add action` is chosen | |! Note | |:------ | | If `cookie-domain` provided WebDriver will reject cookies unless the Domain attribute specifies a scope for the cookie that would include the origin server. For example, the user agent will accept a cookie with a Domain attribute of `example.com` or of `foo.example.com` from `foo.example.com`, but the user agent will not accept a cookie with a Domain attribute of `bar.example.com` or of `baz.foo.example.com`. For more information read [here](https://tools.ietf.org/html/rfc6265#section-4.1.2.3). | |! Note | |:------ | | If `cookie-path` provided WebDriver will reject cookie unless the path portion of the url matches (or is a subdirectory of) the cookie's Path attribute, where the `%x2F` (`/`) character is interpreted as a directory separator. | ##### Example Usage ```xml <?xml version="1.0" encoding="UTF-8"?> <suite name="test-suite" company="cognifide" project="project"> <test name="cookie-modify-test"> <collect> ... <modify-cookie action="add" cookie-name="sample-cookie" cookie-value="sample-cookie-value"/> <modify-cookie action="remove" cookie-name="another-cookie"/> ... <open /> ... </collect> <compare> ... </compare> <urls> ... </urls> </test> ... <reports> ... </reports> </suite> ``` #### Header Modifier Header Modifier is responsible for injecting additional headers to page before it is opened to test. Module name: **header** |! Important information | |:----------------------- | | In order to use this modifier it must be declared before open module in test suite XML definition and *[[proxy|SuiteStructure#proxy]]* must be used. | ##### Parameters | Parameter | Value | Description | Mandatory | | --------- | ----- | ----------- | --------- | | `key` | x | Key for header | yes | | `value` | y | Value for header | yes | ##### Example Usage ```xml <?xml version="1.0" encoding="UTF-8"?> <suite name="test-suite" company="cognifide" project="project"> <test name="header-modify-test"> <collect> ... <header key="Authorization" value="Basic emVuT2FyZXVuOnozbkdAckQZbiE=" /> ... <open /> ... </collect> <compare> ... </compare> <urls> ... </urls> </test> ... <reports> ... </reports> </suite> ``` #### Hide Modifier Hide Modifier is responsible for hiding some unnecessary for test element on page. Affects [[Screen Collector|ScreenCollector]] results. Hiding is done by setting css `visibility` property to `hidden`. Works with webDriver only. You can hide many elements by defining many `<hide>` nodes. If xpath covers more than one element then all elements that match defined xpath will be hidden. Module name: **hide** |! Important information | |:----------------------- | | In order to use this modifier it must be declared after open module in test suite XML definition. | ##### Parameters | Parameter | Value | Description | Mandatory | | --------- | ----- | ----------- | --------- | | `xpath` | xpath_to_element | Xpath to element(s) to hide | yes | | `leaveBlankSpace` | boolean | Defines if element(s) should be invisible (effect as using `display=none`) or should be not displayed (effect as using `visibility=hidden`). When set to `true`, blank and transparent space is left in place of the hidden element, otherwise, element is completely removed from the view. When not defined, hide modifier behaves as if `leaveBlankSpace` property was set to `true`. | no | ##### Example Usage ```xml <?xml version="1.0" encoding="UTF-8"?> <suite name="test-suite" company="cognifide" project="project"> <test name="hide-test"> <collect> <open /> ... <hide xpath="//*[@id='logo']" /> <hide xpath="//*[@id='primaryNavMenu']/li[2]/a/div" /> ... <resolution width="1280" height="800" /> <screen name="desktop" /> ... </collect> <compare> ... </compare> <urls> ... </urls> </test> ... <reports> ... </reports> </suite> ``` #### Login Modifier |! Note | |:------ | | This module is no longer supported and may not work correctly. It may be removed in future version. | Login Modifier allows to login into pages that have access secured with login form. If input element wont be available (wont be loaded yet) then Login Modifier will wait up to 10s for login input, then for password input and at the end for submit button to appear. If any element won't be ready then TimeoutException will be thrown. Module name: **login** |! Important information | |:----------------------- | | In order to use this modifier it must be declared before open module in test suite XML definition. | ##### Parameters | Parameter | Value | Mandatory | Default value | | --------- | ----- | --------- | ------------- | | `login` | User's login | no | admin | | `password` | Password | no | <PASSWORD> | | `login-page` | Url to login page | no | [http://localhost:4502/libs/granite/core/content/login.html](http://localhost:4502/libs/granite/core/content/login.html) | | `login-input-selector` | Xpath expression for login input | no | //input[@name='j_username'] | | `password-input-selector` | Xpath expression for password input | no | //input[@name='j_password'] | | `submit-button-selector` | Xpath expression for submit button | no | //*[@type='submit'] | | `login-token-key` | Name for cookie we get after successfull login | no | login-token | | `timeout` | Number of milliseconds (between 0 and 10000) that modifier will wait to login page response after submiting credentials. | no | 0 | | `force-login` | Enforces login even when login cookie is present. | no | false | ##### Example Usage ```xml <?xml version="1.0" encoding="UTF-8"?> <suite name="test-suite" company="cognifide" project="project"> <test name="login-test"> <collect> <login login="user" password="password" login-page="http://192.168.180.19:5503/libs/cq/core/content/login.html" login-input-selector="//input[@name='j_username']" password-input-selector="//input[@name='j_password']" submit-button-selector="//*[@type='submit']" /> <open /> ... </collect> <compare> ... </compare> <urls> ... </urls> </test> ... <reports> ... </reports> </suite> ``` #### Resolution Modifier Resolution Modifier is responsible for changing browser screen size. Affects [[Screen Collector | ScreenCollector]] results. |! Note | |:------ | | Please note that final resoulution of screenshots may be different when scrollbar is dispayed. <br/><br/> Default width of Firefox's Scrollbar is equal to 33px. (so when you want to grab viewport of size 1024, then set width parameter to 1057px) | Module name: **resolution** ##### Parameters | Parameter | Value | Description | Mandatory | | --------- | ----- | ----------- | --------- | | ~~`maximize`~~ | ~~true <br/> false (default)~~ | ~~Maximize browser window~~ | This property is deprecated and will be removed in future release. | | `width` | int (1 to 100000) | Window width | no | | `height` | int (1 to 100000) | Window height | no | |! Important information | |:----------------------- | | You cannot maximize the window and specify the dimension at the same time. If you specify height param you have to also specify width param and vice versa. | ##### Example Usage ```xml <?xml version="1.0" encoding="UTF-8"?> <suite name="test-suite" company="cognifide" project="project"> <test name="resolution-modify-test"> <collect> ... <resolution width="200" height="300"/> <screen /> ... </collect> <compare> ... </compare> <urls> ... </urls> </test> ... <reports> ... </reports> </suite> ``` #### Sleep Modifier Sleep Modifier is responsible for temporarily ceasing execution, causes current thread to sleep. It is useful in situations when page resources have a long loading time - it suspends next collectors for some time. Module name: **sleep** ##### Parameters | Parameter | Value | Description | Mandatory | | --------- | ----- | ----------- | --------- | | `duration` | int (1 to 30000) | Sleep time, in milliseconds | yes | |! Important information | |:----------------------- | | One sleep duration cannot be longer than 30000 milliseconds (30 seconds).<br/><br/> Two consecutive sleep modifiers are not allowed.<br/><br/> Total sleep duration (sum of all sleeps) in test collection phase cannot be longer than 120000 milliseconds (2 minutes). | ##### Example Usage ```xml <?xml version="1.0" encoding="UTF-8"?> <suite name="test-suite" company="cognifide" project="project"> <test name="sleep-test"> <collect> ... <open /> ... <sleep duration="3000" /> ... </collect> <compare> ... </compare> <urls> ... </urls> </test> ... <reports> ... </reports> </suite> ``` #### Wait For Page Loaded Modifier Wait For Page Loaded Modifier waits until page is loaded (all DOM elements are loaded - this does not wait for dynamically loaded elements by e.g. JavaScript) or fixed amount of time is up. The idea of waiting for page is counting amount of elements [by `findElements(By.xpath("//*"))`] on current page state in loop. If number of elements has increased since last checkout, continue loop (or break if timeout). Else if number of elements is still, assume the page is loaded and finish waiting. Module name: **wait-for-page-loaded** ##### Parameters No parameters. |! Important information | |:----------------------- | | Timeout for waiting is 10000 milliseconds.<br/><br/> Page is checked every 1000 milliseconds. | ##### Example Usage ```xml <?xml version="1.0" encoding="UTF-8"?> <suite name="test-suite" company="cognifide" project="project"> <test name="wait-for-page-loaded-test"> <collect> ... <open /> ... <wait-for-page-loaded /> ... </collect> <compare> ... </compare> <urls> ... </urls> </test> ... <reports> ... </reports> </suite> ``` ### Comparators Comparator is module which main task is to consume data and compare it with pattern or against defined set of rules. Each comparator presented in section below consists of three elements: * consumed resource type, * module name (comparator), * parameters. ##### Consumed resource type This is name of resource type consumed by defined comparator. This is always name of tag definition for comparator. This name says the system which **resource type** should be consumed by defined comparator. When no comparator in system can consume defined resource type, system exception will occur and test will not be performed. This solution enables adding new features to the system without system downtime (just by installing new feature bundle). Each comparator can consume only one type of resource. ##### Module name (comparator) This is special parameter, unique name for comparator type treated as interpretation of given resource type. System will recognize which implementation of comparator should be called by this name. This parameter is required for each comparator but system will assume default comparator for each resource type when no `comparator` property is defined. ###### Default comparators for consumed resource names * [[cookie|CookieCollector]] -> [[CookieComparator]], * [[js errors|JSErrorsCollector]] -> [[JSErrorsComparator]], * [[screen|ScreenCollector]] -> [[LayoutComparator]], * [[source|SourceCollector]] -> [[SourceComparator]], * [[status-codes|StatusCodesCollector]] -> [[StatusCodesComparator]]. Example of usage can be found in system for *source* comparison, where two comparators exists: [[W3C HTML5 Comparator|W3CHTML5Comparator]] and [[Source Comparator|SourceComparator]]. Example below shows sample usage: ```xml ... <collect> <open/> <source/> </collect> <compare> <source comparator="source"/> <source comparator="w3c-html5"/> </compare> ... ``` When test defined as above is executed, only one collection of page source is performed. But result of this collection is used twice during comparison phase. First by [[Source Comparator|SourceComparator]] and then by [[W3C HTML5 Comparator|W3C HTML5 Comparator]]. ##### Parameters This is set of key-value pairs using which user can pass some configuration and information to comparator. Parameters for comparators can be divided into two groups: * mandatory - parameters without which comparison will be not possible, * optional - passing this parameter is not obligatory, usually this is some comparator functionality extension. ###### collectorName There exists special comparator property `collectorName` which is connected with collector's `name` property. By using `collectorName` property combined with collector's `name` property, user can control which comparator instance compares results collected by particular collector. See examples below: ```xml ... <collect> <open/> <sleep duration="1000"/> <resolution width="1280" height="1024" name="desktop"/> <screen name="desktop"/> <resolution width="768" height="1024" name="tablet"/> <screen name="tablet"/> <resolution width="320" height="480" name="mobile"/> <screen name="mobile"/> </collect> <compare> <screen collectorName="mobile"/> <screen collectorName="tablet"/> </compare> ... ``` Configuration above will trigger three screens collections (desktop, tablet and mobile) and two comparisons (mobile and tablet). Screenshot taken for *desktop* will be not compared. ```xml ... <collect> <open/> <sleep duration="1000"/> <resolution width="1280" height="1024" name="desktop"/> <screen name="desktop"/> <resolution width="768" height="1024" name="tablet"/> <screen name="tablet"/> <resolution width="320" height="480" name="mobile"/> <screen name="mobile"/> </collect> <compare> <screen/> </compare> ... ``` Configuration above will trigger three screens collections (desktop, tablet and mobile) and three comparisons (desktop, table, mobile). ```xml ... <collect> <open/> <sleep duration="1000"/> <resolution width="1280" height="1024" name="desktop"/> <screen name="desktop"/> <resolution width="768" height="1024" name="tablet"/> <screen name="tablet"/> <resolution width="320" height="480" name="mobile"/> <screen name="mobile"/> </collect> <compare> <screen/> <screen collectorName="tablet"/> </compare> ... ``` Configuration above will trigger three screens collections (desktop, tablet and mobile) and four comparisons (desktop, tablet, mobile and one additional for tablet). ##### Definitions illustration Following picture presents definitions described earlier: ![Compare phase definitions](assets/diagrams/compare-phase-definitions.png) where: 1. Consumed resource type, 2. Special property: collectorName, 3. Special property: comparator, 4. Module name (comparator). #### Accessibility Comparator |! Beta Version | |:------------ | | This AET Plugin is currently in BETA version. | Accessibility Comparator is responsible for processing of collected accessibility validation result. It uses [html CodeSniffer](http://squizlabs.github.io/HTML_CodeSniffer/) library. Module name: **accessibility** Resource name: accessibility ##### Parameters | Parameter | Value | Description | Mandatory | | --------- | ----- | ----------- | --------- | | `report-level` | ERROR (default)<br/><br/> WARN<br/><br/> NOTICE | Only violations of type ERROR are displayed on report.<br/><br/> Violations of type WARN and ERROR are displayed on report.<br/><br/> All violations are displayed on report. | no | | ignore-notice | boolean<br/> (default: `true`) | If `ignore-notice=true` test status does not depend on the notices amount.<br/> If `ignore-notice=false` notices are treated as warnings in calculating test status. Enforces report-level = NOTICE. | no | | `showExcluded` | boolean<br/> (default: `true`) | Flag that says if excluded issues (see [[Accessibility Data Filter|AccessibilityDataFilter]]) should be displayed in report. By default set to `true`. | no | ##### Example Usage ```xml <?xml version="1.0" encoding="UTF-8"?> <suite name="test-suite" company="cognifide" project="project"> <test name="accessibility-test"> <collect> ... <accessibility /> ... </collect> <compare> ... <accessibility report-level="WARN" /> ... </compare> <urls> ... </urls> </test> ... <reports> ... </reports> </suite> ``` #### Client Side Performance Comparator |! Beta Version | |:------------ | | This AET Plugin is currently in BETA version. | Client Side Performance Comparator is responsible for processing of collected client side performance analysis result. Comparator uses [YSlow](http://yslow.org/) tool in order to perform comparison phase on collected results. Module name: **client-side-performance** Resource name: client-side-performance ##### Parameters No parameters ##### Example Usage ```xml <?xml version="1.0" encoding="UTF-8"?> <suite name="test-suite" company="cognifide" project="project"> <test name="client-side-performance-test"> <collect> ... <client-side-performance /> ... </collect> <compare> ... <client-side-performance /> ... </compare> <urls> ... </urls> </test> ... <reports> ... </reports> </suite> ``` #### Cookie Comparator Cookie Comparator is responsible for processing of collected cookies. This can be simply listing of collected cookies, verifying if cookie exists or comparing collected cookie with pattern. Cookie feature allows to collect patterns and can be rebased from report only in compare action mode*.* Module name: **cookie** Resource name: cookie ##### Parameters | Parameter | Value | Description | Mandatory | | --------- | ----- | ----------- | --------- | | `action` | list<br/><br/> test<br/><br/> compare | Displays the list of cookies<br/><br/> Tests if cookie with the given name and value exists<br/><br/> Compares the current data with the pattern (compares only cookie names, values are ignored) | no<br/><br/> If `action` parameter is not provided, default `list` action is performed | | `cookie-name` | | Name of the cookie to test, applicable only for test action | yes, if `action` set to `test` | | `cookie-value` | | Value of the cookie to test, applicable only for test action | no | | `showMatched` | boolean<br/> (default: `true`) | **Works only in compare mode.** Flag that says if matched cookies should be displayed in report. By default set to `true`. | no | ##### Example Usage ```xml <?xml version="1.0" encoding="UTF-8"?> <suite name="test-suite" company="cognifide" project="project"> <test name="cookie-test"> <collect> ... <cookie /> ... </collect> <compare> ... <cookie /> ... </compare> <urls> ... </urls> </test> ... <reports> ... </reports> </suite> ``` #### JS Errors Comparator JS Errors Comparator is responsible for processing of collected javascript errors resource. In this case it is simply displaying list of javascript errors. JS Errors feature do not allow to collect patterns, so it does not compare results with any patterns - rebase action is also not avaliable. Module name: **js-errors** Resource name: js-errors ##### Parameters No parameters ##### Example Usage ```xml <?xml version="1.0" encoding="UTF-8"?> <suite name="test-suite" company="cognifide" project="project"> <test name="js-errors-test"> <collect> ... <js-errors /> ... </collect> <compare> ... <js-errors /> ... </compare> <urls> ... </urls> </test> ... <reports> ... </reports> </suite> ``` |! Important information | |:----------------------- | | [[JS Errors Data Filter|JSErrorsDataFilter]] can be applied to collected javascript errors result before comparison to modify data that is to be processed. | #### Layout Comparator Layout Comparator is responsible for comparing collected screenshot of page with pattern. This is default comparator for `screen` resource. Can be rebased from report. Module name: **layout** Resource name: screen ##### Parameters No parameters ##### Example Usage ```xml <?xml version="1.0" encoding="UTF-8"?> <suite name="test-suite" company="cognifide" project="project"> <test name="layout-compare-test"> <collect> ... <screen /> ... </collect> <compare> ... <screen comparator="layout" /> ... </compare> <urls> ... </urls> </test> ... <reports> ... </reports> </suite> ``` ##### Fast pre-comparison Since AET 1.3 fast comparison of screenshots will be implemented. Taken screenshot MD5 will be matched against current pattern. If hashes will be the same, screenshot will be treated as one without differences and no further comparison will be performed. #### Source Comparator Source Comparator is responsible for comparing collected page source with pattern. Can be rebased from report. Module name: **source** Resource name: source ##### Parameters | Parameter | Value | Description | Mandatory | | --------- | ----- | ----------- | --------- | | `compareType` | content | Compare only text inside HTML nodes. Ignore formatting, tag names and attributes. | no<br/> If `compareType` is not provided default `all` value is taken. | | | markup | Compare only HTML markup and attributes. Ignore text inside HTML tags, formatting and white-spaces. Remove empty lines. | | | | allFormatted | Compare full source with formatting and white-spaces ignored. Remove empty lines. | | | | all | Compare all source (default). | | ##### Example Usage ```xml <?xml version="1.0" encoding="UTF-8"?> <suite name="test-suite" company="cognifide" project="project"> <test name="source-compare-test"> <collect> ... <source /> ... </collect> <compare> ... <source comparator="source" compareType="markup" /> ... </compare> <urls> ... </urls> </test> ... <reports> ... </reports> </suite> ``` |! Important information | |:----------------------- | | [[Extract Element Data Filter|ExtractElementDataFilter]], [[Remove Lines Data Filter|RemoveLinesDataFilter]] and [[Remove Nodes Data Filter|RemoveNodesDataFilter]] can be applied to collected source before comparison to modify source data that is to be compared. | #### Status Codes Comparator Status Codes Comparator is responsible for processing collected status codes. In this case it is simply displaying the list of collected status codes from given page. Status Codes feature do not allow to collect patterns, so it does not compare results with any patterns - rebase action is also not available. Module name: **status-codes** Resource name: status-codes ##### Parameters | Parameter | Value | Example | Description | Mandatory | | --------- | ----- | ------- | ----------- | --------- | | `filterRange` | x,y | 400,500 | Defines range of status codes that should be processed | yes, if `filterCodes` is not present | | `filterCodes` | x,y,z | 400,401,404 | List of status codes that should be processed | yes, if `filterRange` is not present | | `showExcluded` | boolean (default: `true`) | true | Flag that says if excluded codes (see [[Status Codes Data Filters | StatusCodesDataFilters]]) should be displayed in report. By default set to `true`. | no | ##### Example Usage ```xml <?xml version="1.0" encoding="UTF-8"?> <suite name="test-suite" company="cognifide" project="project"> <test name="status-codes-test"> <collect> ... <open /> ... <status-codes /> ... </collect> <compare> ... <status-codes filterRange="400,404" /> ... </compare> <urls> ... </urls> </test> ... <reports> ... </reports> </suite> ``` #### W3C HTML5 Comparator W3C HTML5 Comparator is responsible for validating collected page source against w3c standards using [validator.nu](https://validator.nu/). HTML5 is supported by this library. W3C HTML5 feature do not allow to collect patterns, so it does not compare results with any patterns - rebase action is also not available. Module name: **w3c-html5** Resource name: source ##### Parameters | Parameter | Value | Description | Mandatory | | --------- | ----- | ----------- | --------- | | `ignore-warnings` | boolean (default: true) | If `ignore-warnings="true"` test status does not depend on the warnings amount, otherwise warnings counts as w3c errors when computing testcase status. | no | | `errors-only` | boolean(default: true) | **This parameter will be removed from 1.5 AET Version!**<br/> Has the same result as `ignore-warnings` parameter. | no | |! Mandatory parameter | |:--------------------- | | Please remember, that using parameter `comparator="w3c-html5"` is mandatory while defining this comparator. More information about this parameter can be found in [[Comparators]] section. | ##### Example Usage ```xml <?xml version="1.0" encoding="UTF-8"?> <suite name="test-suite" company="cognifide" project="project"> <test name="w3c-html5-test"> <collect> ... <open /> ... <source /> ... </collect> <compare> ... <source comparator="w3c-html5" /> ... </compare> <urls> ... </urls> </test> ... <reports> ... </reports> </suite> ``` ### Data Filters Data filters are modules which narrow area on which comparison will be performed. They are nested in [[Comparators]] and apply only to instance of comparator in which they are defined. Each data filter consists of two elements: * module name, * parameters. ##### Module name This name is unique identifier for each data filter (and each module in compare phase). ##### Parameters This is set of key-value pairs using which user can pass some configuration and information to data filter. Parameters can be divided into two groups: * mandatory - parameters without which filtering will be not possible, * optional - passing this parameter is not obligatory, usually they trigger some functionality extension. #### Accessibility Data Filter Accessibility Data Filter filters Accessibility issues - it removes matched accessibility issues from reports. This filter can be only applied to `accessibility` comparator tag in test case. When more than one parameter is provided then only fully matched issues are filtered. Module name: **accessibility-filter** Resource name: accessibility ##### Parameters | Parameter | Value | Description | Mandatory | | --------------- | ----- | ----------- | --------- | | `error` | string error | Exact error message | At least one of parameter is required | | `principle` | string principle | Exact accessibility issue principle | | `line` | integer line number | Line number in file in which issue occurred | | `column` | integer column number | Column number in file in which issue occurred | ##### Example Usage In this sample exact match of accessibility issue breaking principle "WCAG2A.Principle4.Guideline4_1.4_1_2.H91.Button.Name", at line 21, column 5 with message "This button element does not have a name available to an accessibility API. Valid names are: title attribute, element content." will be totally ignored. ```xml <?xml version="1.0" encoding="UTF-8"?> <suite name="test-suite" company="cognifide" project="project"> <test name="accessibility-filter-test"> <collect> ... <open/> ... <accessibility/> ... </collect> <compare> ... <accessibility> <accessibility-filter error="This button element does not have a name available to an accessibility API. Valid names are: title attribute, element content." principle="WCAG2A.Principle4.Guideline4_1.4_1_2.H91.Button.Name" line="21" column="5" /> </accessibility> ... </compare> <urls> ... </urls> </test> ... <reports> ... </reports> </suite> ``` There can be more than one `accessibility-filter` tag in `accessibility` comparator eg: ```xml <accessibility> <accessibility-filter principle="WCAG2A.Principle1.Guideline1_3.1_3_1.F68" /> <accessibility-filter error="This select element does not have a name available to an accessibility API. Valid names are: label element, title attribute." /> <accessibility-filter line="270" /> <accessibility-filter line="314" /> <accessibility-filter column="5" /> </accessibility> ``` #### Extract Element Data Filter Extract Element Data Filter allows to extract element from html source (collected by Source Collector) by providing id attribute or class attribute. Found element's source is processed by comparator. Module name: **extract-element** Resource name: source ##### Parameters | Parameter | Value | Description | Mandatory | | --------- | ----- | ----------- | --------- | | `elementId` | HTML id | Id for element to extract | See note below | | `class` | HTML class | Class name for element to extract | See note below | |! Note | |:------ | | One of these parameters is required. Only one parameter (either `elementId` attribute or `class` attribute) can be provided. | ##### Example Usage ```xml <?xml version="1.0" encoding="UTF-8"?> <suite name="test-suite" company="cognifide" project="project">     <test name="extract-element-test">         <collect>             ...             <open/>             ...             <source/>             ...         </collect>         <compare>             ...             <source comparator="source">                 <extract-element elementId="login_form"/>             <!-- OR -->                 <extract-element class="class_form"/>             </source>             ...         </compare>         <urls>             ...         </urls>     </test>     ...     <reports>         ...     </reports> </suite> ``` #### JS Errors Data Filter Js Errors Data Filter filters JS Errors Collector result - it removes matched javascript errors from reports. This filter can be only applied to `js-errors` comparator tag in test case. When more than one parameter is provided then only fully matched errors are filtered. If some XML-specific charactes (e.g. `&`) are in parameter's value, then they must be escaped. Module name: **js-errors-filter** Resource name: js-errors ##### Parameters | Parameter | Value | Description | Mandatory | | --------- | ----- | ----------- | --------- | |`error`|string error|Exact error message|At least one of parameter is required| |`source`|string file name|Source file name (full path including `http://`) in which error occurred| |`line`|integer line number|Line number in file in which error occurred| ##### Example Usage In this sample exact match of js error from file "[http://w.iplsc.com/external/jquery/jquery-1.8.3.js](http://w.iplsc.com/external/jquery/jquery-1.8.3.js)", line 2 with message "Error: Syntax error, unrecognized expression:.iwa_block=pasek-ding" will be totally ignored (not included in report) ```xml <?xml version="1.0" encoding="UTF-8"?> <suite name="test-suite" company="cognifide" project="project">     <test name="js-errors-filter-test">         <collect>             ...             <open/>             ...             <js-errors/>             ...         </collect>         <compare>             ...             <js-errors>                 <js-errors-filter error="Error: Syntax error, unrecognized expression:.iwa_block=pasek-ding" line="2" source="http://w.iplsc.com/external/jquery/jquery-1.8.3.js" />             </js-errors>             ...         </compare>         <urls>             ...         </urls>     </test>     ...     <reports>         ...     </reports> </suite> ``` There can be more than one `js-errors-filter` tag in `js-errors` comparator eg: ```xml <js-errors> <js-errors-filter error="Error: Syntax error, unrecognized expression:.iwa_block=pasek-ding" /> <js-errors-filter source="http://w.iplsc.com/external/jquery/jquery-1.8.3.js" line="2" /> </js-errors> ``` #### Remove Lines Data Filter Remove Lines Data Filter allows to remove lines from compared source (data or pattern). This may be helpful when we need to compare page sources with dynamic content. We can then remove these dynamic content markup. Line number in reports represents lines state after modification, so have in mind that marked lines have different lines number in real source. Module name: **remove-lines** Resource name: source ##### Parameters | Parameter | Value | Description | Mandatory | | --------- | ----- | ----------- | --------- | |`dataRanges`|ranges of lines to remove from data|Ranges should be provided in form **a,b**, this will be interpreted as closed interval of integers [a,b].Particular ranges should be separated by semicolons: **a,b;c,d;e,f** a>0, b>0|At least one of parameters is required.| |`patternRanges`|ranges of lines to remove from pattern|Ranges should be provided in form **a,b**, this will be interpreted as closed interval of integers [a,b].Particular ranges should be separated by semicolons: **a,b;c,d;e,f** a>0, b>0|| Examples: Suppose we want to remove line 10: `10,10` Suppose we want to remove lines from 10 to 15: `10,15` Suppose we want to remove lines from 10 to 15, line 27 and lines from 30 to 38: `10,15;27,27;30,38` ##### Example Usage ```xml <?xml version="1.0" encoding="UTF-8"?> <suite name="my-test-suite" company="cognifide" project="project"> <test name="remove-lines-test"> <collect> ... <source/> ... </collect> <compare> ... <source comparator="source"> <remove-lines dataRanges="10,15;27,27" patternRanges="10,14;27,28"/> </source> ... </compare> <urls> ... </urls> </test> ... <reports> ... </reports> </suite> ``` #### Remove Nodes Data Filter Remove Nodes Data Filter allows to delete some node(s) from html tree. Node(s) are defined by xpath selector. |! Important information | |:----------------------- | | Html source has to be valid xml document | Name: **remove-nodes** Resource name: source ##### Parameters | Parameter | Value | Description | Mandatory | | --------- | ----- | ----------- | --------- | | `xpath` | xpath_to_node| Xpath selector for nodes to remove | yes | ##### Example Usage ```xml <?xml version="1.0" encoding="UTF-8"?> <suite name="test-suite" company="Cognifide" project="project">     <test name="remove-nodes-test">         <collect>             ...             <open/>             ...             <source/>             ...         </collect>         <compare>             ...             <source comparator="source">                 <remove-nodes xpath="//*[@id='blueBarNAXAnchor']/div/div/div/a/i"/>             </source>             ...         </compare>         <urls>             ...         </urls>     </test>     <reports>         ...     </reports> </suite> ``` #### Remove Regex Data Filters Remove Regex Data Filter allows to remove parts of source based on regex expressions from compared source (data and/or pattern). This may be helpful when we need to compare page sources with dynamic content. We can then remove these dynamic content markup. See also Remove Lines and Remove Nodes data Filters. Module name: **remove-regexp** Resource name: source ##### Parameters | Parameter | Value | Mandatory | | --------- | ----- | --------- | | `dataRegExp` |RegExp that will replace matched parts of *data* sources |At least one of parameter is required. | | `patternRegExp` | RegExp that will replace matched parts of *pattern* sources | | `regExp` | RegExp that will replace matched parts of *pattern and data* sources | |! Note | |:------ | | `regExp` value overrides `dataRegExp` and `patternRegExp` | Tip: Use [http://www.regexplanet.com/advanced/java/index.html](http://www.regexplanet.com/advanced/java/index.html) to create check your Regular Expression and when ready use 'as a Java string' value in your testsuite. ##### Example Usage ```xml <?xml version="1.0" encoding="UTF-8"?> <suite name="my-test-suite" company="cognifide" project="project"> <test name="remove-regex-test"> <collect> ... <source/> ... </collect> <compare> ... <source comparator="source"> <remove-regexp regExp='\"correlationId\": \".*\"'/> </source> ... </compare> <urls> ... </urls> </test> ... </suite> ``` #### Status Codes Data Filters ##### Exclude Filter Exclude Filter removes from reports Status Codes results that match specified parameters. Name: **exclude** Resource name: status-codes ###### Parameters | Parameter | Value | Description | Mandatory | | --------- | ----- | ----------- | --------- | | `url` | String url | Exact url to be removed from results. | At least one of parameter is required. | | `pattern` | String regex pattern| Regex pattern that urls should match to be removed from results. | | If both parameters are provided then result is removed when it matches at least one of the parameters. ###### Example Usage In this sample match results with url http://www.cognifide.com/_cog_opt_js_f359581ea4bd3379b4c25591838a5dd8.js or url that matches pattern **^.\*js$** will be ignored (not included in report). ```xml <?xml version="1.0" encoding="UTF-8"?> <suite name="test-suite" company="Cognifide" project="project"> <test name="exclude-test" useProxy="rest"> <collect> ... <open/> ... <status-codes/> ... </collect> <compare> ... <status-codes filterRange="200,999"> <exclude url="http://www.cognifide.com/_cog_opt_js_f359581ea4bd3379b4c25591838a5dd8.js" pattern="^.*js$"/> </status-codes> ... </compare> <urls> ... </urls> </test> <reports> ... </reports> </suite> ``` There can be more than one `exclude` tags in `status-codes` comparator. They are processed in turns. Example below is equivalent to defined above: ```xml <status-codes> <exclude url="http://www.cognifide.com/_cog_opt_js_f359581ea4bd3379b4c25591838a5dd8.js"/> <exclude pattern="^.*js$"/> </status-codes> ``` In this case both results with url http://www.cognifide.com/_cog_opt_js_f359581ea4bd3379b4c25591838a5dd8.js and urls that match pattern **^.\*js$** (ending with js) will not be displayed on reports. **Exclude** and **include** modifiers can be both applied to **status-codes comparator**. They are processed in turns. Example: ```xml <status-codes> <include pattern="^.*js$"/> <exclude url="http://www.cognifide.com/_cog_opt_js_f359581ea4bd3379b4c25591838a5dd8.js"/> </status-codes> ``` In this case, at first all urls that do not match **^.\*js$** pattern are removed. Then url http://www.cognifide.com/_cog_opt_js_f359581ea4bd3379b4c25591838a5dd8.js is removed. Therefore only urls ending with `js` except http://www.cognifide.com/_cog_opt_js_f359581ea4bd3379b4c25591838a5dd8.js will be included in reports. ##### Include Filter Include Filter removes from reports Status Codes results that **do not** match specified parameters. Name: **include** Resource name: status-codes ###### Parameters | Parameter | Value | Description | Mandatory | | --------- | ----- | ----------- | --------- | | `url` | String url | Exact url to be included in reports. Results that do not match will be removed. | At least one of parameter is required. | | `pattern` | String regex pattern | Regex pattern that urls should match to be included in reports. Results that do not match will be removed. | | If both parameters are provided then result is only included in the report when it matches both of the parameters. ###### Example Usage In example below **only** result with url http://www.cognifide.com/_cog_opt_js_f359581ea4bd3379b4c25591838a5dd8.js will be included in report. ```xml <?xml version="1.0" encoding="UTF-8"?> <suite name="test-suite" company="Cognifide" project="project" environment="win7-ff16"> <test name="include-test" useProxy="rest"> <collect> ... <open/> ... <status-codes/> ... </collect> <compare> ... <status-codes filterRange="200,999"> <include url="http://www.cognifide.com/_cog_opt_js_f359581ea4bd3379b4c25591838a5dd8.js"/> </status-codes> ... </compare> <urls> ... </urls> </test> <reports> ... </reports> </suite> ``` There can be more than one `include` tags in `status-codes` comparator. They are processed in turns. Example: ```xml <status-codes> <include pattern="^.*js$"/> <include url="http://www.cognifide.com/_cog_opt_js_f359581ea4bd3379b4c25591838a5dd8.js"/> </status-codes> ``` In this case only http://www.cognifide.com/_cog_opt_js_f359581ea4bd3379b4c25591838a5dd8.js url will be included on reports: first all results that do not match **^.\*js$** pattern (ending with `js`) are removed. Then within that result all urls different that "http://www.cognifide.com/_cog_opt_js_f359581ea4bd3379b4c25591838a5dd8.js" are removed. In example above, first `<include>` can be omitted and result will be the same. **Include** and **exclude** modifiers can be both applied to **status-codes comparator**. They are processed in turns. Example: ```xml <status-codes> <include pattern="^.*js$"/> <exclude url="http://www.cognifide.com/_cog_opt_js_f359581ea4bd3379b4c25591838a5dd8.js"/> </status-codes> ``` In this case only first all urls that do not match **^.\*js$** pattern are removed. Then url http://www.cognifide.com/_cog_opt_js_f359581ea4bd3379b4c25591838a5dd8.js is removed. Therefore only urls ending with `js` except http://www.cognifide.com/_cog_opt_js_f359581ea4bd3379b4c25591838a5dd8.js will be included in reports. #### W3C HTML5 Issues Filter W3C HTML5 Issues Filter allows to exclude some W3C HTML5 issues from result. Excluded issues will appear at the bottom of issues table and won't be taken into account when calculating status. Name: **w3c-filter** Resource name: source Comparators: **w3c-html5** ### Parameters | Parameter | Value | Description | Mandatory | | --------- | ----- | ----------- | --------- | | `message` | string | Prefix or all message text of issue to be filter out | At least one of params should be used and all of used params should be not empty. | | `line` | integer | Line in source file where issue appear | | | `column` | integer | Column in source file where issue appear | | |! Note | |:------ | | If there are some If some XML-specific charactes (e.g. `&`) are in parameter's value, then they have to be escaped. See example below. | ##### Example Usage for w3c-html5 comparator ```xml <?xml version="1.0" encoding="UTF-8"?> <suite name="test-suite" company="Cognifide" project="project" environment="win7-ff16"> <test name="remove-nodes-test"> <collect> ... <open/> ... <source/> ... </collect> <compare> ... <source comparator="w3c-html5" errors-only="false"> <w3c-filter message = "The first occurrence of" /> <w3c-filter message = "&#8220;&amp;&#8221; did not start a character reference"/> <w3c-filter line="1" column="119"/> </source> ... </compare> <urls> ... </urls> </test> <reports> ... </reports> </suite> ``` #### Urls `<urls>` element lists all urls which will be processed within current test. Contains one or more **[url](#url)** elements. ##### url A single url which will be processed by particular test. ###### Parameters | Attribute name | Description | Mandatory | | -------------- | ----------- | --------- | | `href` | Page address (also see note under name attribute) | yes | | `name` | Identifier for url. It is used to identify data for url. If provided should be unique for each test in test suite. If not provided is set to encoded `href` value. Should consists only of letters, digits and/or characters: `-`, `-`. Note that if `href=""` with provided url `name` attribute and suite `domain` attribute is also valid | no | | ~~`description`~~ | ~~Additional description for url that will be shown in html report~~ | no longer supported | ###### Example Usage ```xml <?xml version="1.0" encoding="UTF-8"?> <suite name="test-suite" company="cognifide" project="project"> <test name="urls-test"> <collect> ... </collect> <compare> ... </compare> <urls> <url href="http://www.example.com"/> ... </urls> </test> ... <reports> ... </reports> </suite> ``` ## Suite Report ### What is suite report? Suite Report is testing results' presentation. It's composed of single tests. Each of them contains one or more URLs, on which tests were run. |! Important information | |:----------------------- | |AET reports are tested and written for Google Chrome web browser. | Each test's result will be presented in one of three colors: * **green** - if all group result passed and no risks was detected, * **yellow** - if there is small risk detected, * **red** - if there were some risks detected and result requires inspection There is also 4th colour, which is not correlated with test's results. It is **blue**, which appears when user accepts certain pattern. Report is made up of 3 main parts (see also screenshot below): * toolbar, * sidepanel (which contains two sub-parts): * filtering, * navigation-tree, * main. ![report's naming](assets/suiteReport/report-naming.png) With given suite report you can: * accept or revert patterns, * create notes, * filter results, * search for specific test/URL, * navigate on report with keyboard shortcuts. For more information about AET reports' features see [[AET Report Features|SuiteReportFeatures]]. ### Levels of report The highest report's level is suite. Every suite contains tests and the certain test contains one or more URLs on which tests are run. #### Suite On this level you can see such information as: * all tests which was launched via certain suite, * project name, * test cases' status, * date and time of running the test suite. #### Test If you go to the certain test level, you can obtain information about: * test case's name, * status' representation of tested URLs, * URLs included in the test. #### URL with Cases Tabs On URL level you can learn about: * cases on which certain site was tested (represented as tabs on upper part of report), * test case's details for given URL. ### Test cases #### Cookies ##### Description Cookie test results can be presented in three diffrent forms which depend on the action parameter defined in test definition. The forms are: * list, * test, * compare. ##### List ###### Description Lists all cookies found on the tested page. This result will always have success status. ![cookie list](assets/suiteReport/cookie-list.png) ##### What vulnerabilities it discovers You can check all of site's cookies in order to find the invalid one. However, this mode is not intended to discover website issues. This list should be empty when tested page does not intend to use cookies and The EU Cookie Law is respected. ##### Test ###### Description It shows result of checking presence of cookie with defined parameters on the tested page. ![Cookie-test successfull](assets/suiteReport/cookie-test-success.png) In case of cookie being not found on the page or having an unexpected value the result is marked as risk (red). ![Cookie-test failure](assets/suiteReport/cookie-test-failure.png) ##### What vulnerabilities it discovers There are a few things you should pay attention to: * lack of a cookie that occurred before might be caused by some website error (e.g. bug in system functionality), * lack of a cookie might result in further system erros (e.g. losing some user specific data), * lack of an important cookie (e.g. cookie with user localization data) may cause a page to be dispalyed improperly. ##### Compare ###### Description Cookies found on the tested page are compared to the others, which were saved in the pattern (if there is no pattern, then cookies collected during the first page entry are set as the pattern). Differences are searched only for cookies' names. Result will be successful if all found cookies' names are identical to those in the pattern. ![Cookie-compare success](assets/suiteReport/cookie-compare-success.png) Otherwise the result in the report will be marked as at risk (red). Differences will be presented in the form (see "1" on screenshot below) and there will be "accept test case" action available (see "2" on screenshot below). ![Cookie-compare failure](assets/suiteReport/cookie-compare-failure.png) ##### What vulnerabilities it discovers * lack of a cookie that occurred before might be caused by some website error (e.g. bug in system functionality), * lack of a cookie might result in further system erros (e.g. losing some user specific data), * an additional cookie may be generated by some unwanted content on a page (e.g. some 3rd party software add own cookies), * when a page does not intend to use cookies and The EU Cookie Law is respected, lists of additional and detected cookies should always be empty. #### JS Errors ##### Description This case displays success status when there were no JS errors found. |! Important information | |:----------------------- | |All errors filtered with [[JS Errors Data Filter|JSErrorsDataFilter]] are ommited. | ![JS errors success](assets/suiteReport/jserrors-success.png) Otherwise the report is marked as risk (red) when at least one error has been found. ![JS errors failure](assets/suiteReport/jserrors-failure.png) ##### What vulnerabilities it discovers * JS Errors can cause improper behaviour of a page (e.g. dynamic components may not work properly in some (or even all) browsers, * JS Error can also occur when good practices are not followed in the javascript code. #### Screen - layout ##### Description For layout tests the results are presented as compared screenshots (as on screenshot below). ![Layout failure](assets/suiteReport/layout-failure.png) 1. Test case's name (red font means failure). 2. "Accept test case" button (available only when differences have been detected). 3. "Show mask" switch - when the mask is on, differences are marked in a red colour over the collected screenshot, otherwise a raw screenshot is presented. 4. Pattern - a screen which the "view" is compared to (if there is no pattern, the first collected screenshot is saved as the pattern). 5. View - a screen that was taken during the test and it is compared to the pattern. 6. Example of difference area. 7. Date of obtaining current pattern. Test case's result is marked as successful when there is no difference between view and pattern (see screenshot below). ![Layout success](assets/suiteReport/layout-success.png) ##### What vulnerabilities it discovers * Differences found in page screenshots may indicate undesired changes in the page layout (css, html structure) e.g. when a new functionality was implemented in a system it may have an impact on another system component(s). This may show itself as a changed page layout. * Content changes can be divided into two groups: wanted (are intended) and unwanted (a result of a mistake or an error). An example of a change that is not a defect (wanted) is: the carousel component with the latest news items displayed or the twitter component displaying latest tweets. In order to avoid detecting these sorts of changes in these dynamic components, the user can use the [[Hide Modifier|HideModifier]] feature in the suite definition. Another example of the ‘wanted’ dynamic content is a cookies policy popup that may be hidden using the [[Cookie Modifier|CookieModifier]]. #### Source ##### Description Source test cases' results display compared sources. (see screenshot below). ![Source failure](assets/suiteReport/source-failure.png) 1. Test case's name (red font means failure), 2. "Accept test case" button (available only when differences have been detected), 3. "Show full source" switch - when the switch is off only differences are shown on the screen, otherwise full source is shown, 4. Pattern - source file to which collected source is compared. When there is no pattern, first collected source is saved as pattern automatically, 5. Source - source file which is compared with pattern, 6. Sample block with visible differences (e.g. changed characters). Test case's result is marked as successful when there is no difference between source and pattern (see screenshot below). ![Source success](assets/suiteReport/source-success.png) ##### What vulnerabilities it discovers * Differences found by source comparison may indicate undesired changes in a page layout (html structure) and content, e.g. when a new functionality is implemented in a system it might have an impact on other system component(s). This may occur as a changed page source. * Content changes can be divided into two groups: wanted (intended) and unwanted (result of a mistake or an error). In order to filter out wanted changes and detect changes that are a result of a mistake or an error, the user can use one of following filters in the suite definition: * [[The Extract Element Data Modifier|ExtractElementDataFilter]] (e.g. to find changes only in the main menu that has the parameter id='main-menu' set), * [[The Remove Lines Data Filter|RemoveLinesDataFilter]] (to remove lines that changes every time - e.g. a current timestamp), * [[The Remove Nodes Data Filter|RemoveNodesDataFilter]] (e.g. to remove content displayed by the dynamic news carousel component). #### Status codes ##### Description In this test case you can check response codes from certain URLs. There is possibility of excluding individual codes, URLs and patterns (they are ignored by that test) as well as including them (only them will be tested by that test). For more information about excluding/including see [[Status Codes Data Filters|StatusCodesDataFilters]]. If any code is filtered by certain test, the result is failure (see screenshot below). ![Status codes failure](assets/suiteReport/status-codes-failure.png) Otherwise test's result is successful (like on the screenshot below). ![Status codes success](assets/suiteReport/status-codes-success.png) Additionally, if [[excluding filter|StatusCodesDataFilters]] is used, excluded codes are presented in additional section. ##### What vulnerabilities it discovers * All status codes with a number higher than 400 are potential errors and indicate that the resource that is used by a page is unreachable (e.g. a page logo image, a page layout css file) * Status code errors affect SEO (e.g. google page ranking is lowered for pages with 404 status codes). #### W3C (HTML5) ##### Description |! Important information | |:----------------------- | |W3C validator is compatible with HTML5 standard. | W3C report results display page source W3C validation output. If no W3C errors were found, result is marked as success - green (see screenshot bellow). ![W3C success](assets/suiteReport/w3c-success.png) There is possibility to see warning (yellow), if W3C warnings were present and parameter `ignore-warnings` was set to false (as on screenshot bellow). ![W3C warning](assets/suiteReport/w3c-warning.png) If at least one W3C validation error was found, report is marked as risk - red (see screenshot bellow). ![W3C failure](assets/suiteReport/w3c-failure.png) Result shows total count of validation errors and validation warnings. ##### What vulnerabilities it discovers * The W3C validation is important from the SEO point of view. Pages that do not comply to W3C standards are ranked low in Google PageRank and other rankings. * Detected W3C errors may indicate serious html structure bugs (e.g. tags that haven't been closed) or content issues (
1,535
Repo: meltinglab/battery-management ======================= File: workspace/bms_ert_rtw/bms_types.h ======================= /* * Academic License - for use in teaching, academic research, and meeting * course requirements at degree granting institutions only. Not for * government, commercial, or other organizational use. * * File: bms_types.h * * Code generated for Simulink model 'bms'. * * Model version : 1.27 * Simulink Coder version : 9.5 (R2021a) 14-Nov-2020 * C/C++ source code generated on : Sat May 29 15:36:42 2021 * * Target selection: ert.tlc * Embedded hardware selection: Intel->x86-64 (Windows64) * Code generation objectives: Unspecified * Validation result: Not run */ #ifndef RTW_HEADER_bms_types_h_ #define RTW_HEADER_bms_types_h_ #include "rtwtypes.h" #include "SystemState_t.h" /* Model Code Variants */ #ifndef DEFINED_TYPEDEF_FOR_BMSBatteryPackData_ #define DEFINED_TYPEDEF_FOR_BMSBatteryPackData_ typedef struct { real_T SegmentTempVector[30]; real_T SegmentVoltageVector[30]; real_T SegmentCurrentVector[30]; real_T SegmentRealSOCVector[30]; } BMSBatteryPackData; #endif #ifndef DEFINED_TYPEDEF_FOR_BMSContactorModuleData_ #define DEFINED_TYPEDEF_FOR_BMSContactorModuleData_ typedef struct { real_T VCharger; real_T VInverter; real_T ICharger; real_T IInverter; real_T IBatt; real_T VBatt; } BMSContactorModuleData; #endif #ifndef DEFINED_TYPEDEF_FOR_BusInputBMS_ #define DEFINED_TYPEDEF_FOR_BusInputBMS_ typedef struct { BMSBatteryPackData BMSBatteryPackData; BMSContactorModuleData BMSContactorModuleData; } BusInputBMS; #endif #ifndef DEFINED_TYPEDEF_FOR_SimulationSystemInput_ #define DEFINED_TYPEDEF_FOR_SimulationSystemInput_ typedef struct { SystemState_t SystemState; real_T DrivingCurrentRqst; real_T ChargingCurrentRequest; } SimulationSystemInput; #endif #ifndef DEFINED_TYPEDEF_FOR_SimulationBatteryPackInput_ #define DEFINED_TYPEDEF_FOR_SimulationBatteryPackInput_ typedef struct { boolean_T ShortCircuitInjection[30]; boolean_T OpenCircuitInjection[30]; } SimulationBatteryPackInput; #endif #ifndef DEFINED_TYPEDEF_FOR_BusSimulationInput_ #define DEFINED_TYPEDEF_FOR_BusSimulationInput_ typedef struct { SimulationSystemInput SimulationSystemInput; SimulationBatteryPackInput SimulationBatteryPackInput; } BusSimulationInput; #endif #ifndef DEFINED_TYPEDEF_FOR_BMSContactorModuleCmd_ #define DEFINED_TYPEDEF_FOR_BMSContactorModuleCmd_ typedef struct { real_T ContactorCmd[3]; real_T PreChrgCmd[2]; real_T DisChrgCmd[2]; real_T DrivetrainEn[2]; } BMSContactorModuleCmd; #endif #ifndef DEFINED_TYPEDEF_FOR_BMSBatteryPackInput_ #define DEFINED_TYPEDEF_FOR_BMSBatteryPackInput_ typedef struct { boolean_T BalCmdVector[30]; real_T balancingDeltaVCell[3]; boolean_T balancingFlags[3]; } BMSBatteryPackInput; #endif #ifndef DEFINED_TYPEDEF_FOR_BusSOCEstimation_ #define DEFINED_TYPEDEF_FOR_BusSOCEstimation_ typedef struct { real_T EKFEstimation[30]; real_T CDCEstimation[30]; } BusSOCEstimation; #endif #ifndef DEFINED_TYPEDEF_FOR_BMSFaultOutput_ #define DEFINED_TYPEDEF_FOR_BMSFaultOutput_ typedef struct { boolean_T OverCurrentWarning; boolean_T OverCurrentFault; boolean_T OverTemperatureWarning; boolean_T OverTemperatureFault; boolean_T OverVoltageWarning; boolean_T OverVoltageFault; boolean_T UnderVoltageWarning; boolean_T UnderVoltageFault; } BMSFaultOutput; #endif #ifndef DEFINED_TYPEDEF_FOR_BusOutputBMS_ #define DEFINED_TYPEDEF_FOR_BusOutputBMS_ typedef struct { BMSContactorModuleCmd BMSContactorModuleCmd; BMSBatteryPackInput BMSBatteryPackInput; BusSOCEstimation BusSOCEstimation; BMSFaultOutput BMSFaultOutput; } BusOutputBMS; #endif /* Forward declaration for rtModel */ typedef struct tag_RTM_bms_T RT_MODEL_bms_T; #endif /* RTW_HEADER_bms_types_h_ */ /* * File trailer for generated code. * * [EOF] */ ======================= File: workspace/bms_ert_rtw/bms.c ======================= /* * Academic License - for use in teaching, academic research, and meeting * course requirements at degree granting institutions only. Not for * government, commercial, or other organizational use. * * File: bms.c * * Code generated for Simulink model 'bms'. * * Model version : 1.27 * Simulink Coder version : 9.5 (R2021a) 14-Nov-2020 * C/C++ source code generated on : Sat May 29 15:36:42 2021 * * Target selection: ert.tlc * Embedded hardware selection: Intel->x86-64 (Windows64) * Code generation objectives: Unspecified * Validation result: Not run */ #include "bms.h" #include "bms_private.h" /* Named constants for Chart: '<S4>/Chart1' */ #define bms_IN_Balancing ((uint8_T)1U) #define bms_IN_BalancingFinished ((uint8_T)2U) #define bms_IN_MeasureVoltages ((uint8_T)3U) #define bms_IN_NO_ACTIVE_CHILD ((uint8_T)0U) #define bms_IN_OFF ((uint8_T)1U) #define bms_IN_ON ((uint8_T)2U) #define bms_IN_WaitRelaxation ((uint8_T)4U) /* Named constants for Chart: '<S3>/Chart' */ #define bms_IN_charging ((uint8_T)1U) #define bms_IN_dis_charger ((uint8_T)2U) #define bms_IN_dis_inverter ((uint8_T)3U) #define bms_IN_driving ((uint8_T)4U) #define bms_IN_en_charger ((uint8_T)5U) #define bms_IN_en_charger_prechrg ((uint8_T)6U) #define bms_IN_en_inverter ((uint8_T)7U) #define bms_IN_en_inverter_prechrg ((uint8_T)8U) #define bms_IN_init ((uint8_T)9U) /* Block signals (default storage) */ B_bms_T bms_B; /* Block states (default storage) */ DW_bms_T bms_DW; /* External inputs (root inport signals with default storage) */ ExtU_bms_T bms_U; /* External outputs (root outports fed by signals with default storage) */ ExtY_bms_T bms_Y; /* Real-time model */ static RT_MODEL_bms_T bms_M_; RT_MODEL_bms_T *const bms_M = &bms_M_; real_T look1_binlxpw(real_T u0, const real_T bp0[], const real_T table[], uint32_T maxIndex) { real_T frac; real_T yL_0d0; uint32_T bpIdx; uint32_T iLeft; uint32_T iRght; /* Column-major Lookup 1-D Search method: 'binary' Use previous index: 'off' Interpolation method: 'Linear point-slope' Extrapolation method: 'Linear' Use last breakpoint for index at or above upper limit: 'off' Remove protection against out-of-range input in generated code: 'off' */ /* Prelookup - Index and Fraction Index Search method: 'binary' Extrapolation method: 'Linear' Use previous index: 'off' Use last breakpoint for index at or above upper limit: 'off' Remove protection against out-of-range input in generated code: 'off' */ if (u0 <= bp0[0U]) { iLeft = 0U; frac = (u0 - bp0[0U]) / (bp0[1U] - bp0[0U]); } else if (u0 < bp0[maxIndex]) { /* Binary Search */ bpIdx = maxIndex >> 1U; iLeft = 0U; iRght = maxIndex; while (iRght - iLeft > 1U) { if (u0 < bp0[bpIdx]) { iRght = bpIdx; } else { iLeft = bpIdx; } bpIdx = (iRght + iLeft) >> 1U; } frac = (u0 - bp0[iLeft]) / (bp0[iLeft + 1U] - bp0[iLeft]); } else { iLeft = maxIndex - 1U; frac = (u0 - bp0[maxIndex - 1U]) / (bp0[maxIndex] - bp0[maxIndex - 1U]); } /* Column-major Interpolation 1-D Interpolation method: 'Linear point-slope' Use last breakpoint for index at or above upper limit: 'off' Overflow mode: 'portable wrapping' */ yL_0d0 = table[iLeft]; return (table[iLeft + 1U] - yL_0d0) * frac + yL_0d0; } /* * System initialize for atomic system: * '<S4>/Chart1' * '<S4>/Chart2' * '<S4>/Chart3' */ void bms_Chart1_Init(boolean_T rty_balancingCmd[10], real_T *rty_DeltaVCell, boolean_T *rty_balancingFlag) { int32_T i; for (i = 0; i < 10; i++) { rty_balancingCmd[i] = false; } *rty_DeltaVCell = 0.0; *rty_balancingFlag = false; } /* * Output and update for atomic system: * '<S4>/Chart1' * '<S4>/Chart2' * '<S4>/Chart3' */ void bms_Chart1(SystemState_t rtu_SystemState, const real_T rtu_SegmentVoltageVector[10], real_T rtu_CellMaxV, real_T rtu_CellMinV, boolean_T rty_balancingCmd[10], real_T *rty_DeltaVCell, boolean_T *rty_balancingFlag, DW_Chart1_bms_T *localDW) { int32_T i; boolean_T exitg1; if (localDW->temporalCounter_i1 < MAX_uint32_T) { localDW->temporalCounter_i1++; } /* Chart: '<S4>/Chart1' */ if (localDW->is_active_c2_bms == 0U) { localDW->is_active_c2_bms = 1U; localDW->is_c2_bms = bms_IN_OFF; for (i = 0; i < 10; i++) { rty_balancingCmd[i] = false; } *rty_balancingFlag = false; *rty_DeltaVCell = rtu_CellMaxV - rtu_CellMinV; } else if (localDW->is_c2_bms == bms_IN_OFF) { if ((rtu_SystemState == SystemState_t_Balancing) && (*rty_DeltaVCell > 0.001)) { localDW->is_c2_bms = bms_IN_ON; *rty_balancingFlag = true; localDW->is_ON = bms_IN_Balancing; localDW->temporalCounter_i1 = 0U; for (i = 0; i < 10; i++) { rty_balancingCmd[i] = (rtu_SegmentVoltageVector[i] - rtu_CellMinV > 0.001); } localDW->flagBalancingDone = true; i = 0; exitg1 = false; while ((!exitg1) && (i < 10)) { if (rty_balancingCmd[i]) { localDW->flagBalancingDone = false; exitg1 = true; } else { i++; } } *rty_balancingFlag = true; } else { *rty_DeltaVCell = rtu_CellMaxV - rtu_CellMinV; } /* case IN_ON: */ } else if (rtu_SystemState!= SystemState_t_Balancing) { localDW->is_ON = bms_IN_NO_ACTIVE_CHILD; localDW->is_c2_bms = bms_IN_OFF; for (i = 0; i < 10; i++) { rty_balancingCmd[i] = false; } *rty_balancingFlag = false; *rty_DeltaVCell = rtu_CellMaxV - rtu_CellMinV; } else { switch (localDW->is_ON) { case bms_IN_Balancing: if (localDW->flagBalancingDone) { localDW->is_ON = bms_IN_BalancingFinished; *rty_DeltaVCell = rtu_CellMaxV - rtu_CellMinV; *rty_balancingFlag = false; } else if ((!localDW->flagBalancingDone) && ((uint32_T)((int32_T) localDW->temporalCounter_i1 * 10) >= 2000U)) { localDW->is_ON = bms_IN_WaitRelaxation; localDW->temporalCounter_i1 = 0U; for (i = 0; i < 10; i++) { rty_balancingCmd[i] = false; } } break; case bms_IN_BalancingFinished: if (*rty_DeltaVCell > 0.001) { localDW->is_ON = bms_IN_Balancing; localDW->temporalCounter_i1 = 0U; for (i = 0; i < 10; i++) { rty_balancingCmd[i] = (rtu_SegmentVoltageVector[i] - rtu_CellMinV > 0.001); } localDW->flagBalancingDone = true; i = 0; exitg1 = false; while ((!exitg1) && (i < 10)) { if (rty_balancingCmd[i]) { localDW->flagBalancingDone = false; exitg1 = true; } else { i++; } } *rty_balancingFlag = true; } else { *rty_DeltaVCell = rtu_CellMaxV - rtu_CellMinV; *rty_balancingFlag = false; } break; case bms_IN_MeasureVoltages: localDW->is_ON = bms_IN_Balancing; localDW->temporalCounter_i1 = 0U; for (i = 0; i < 10; i++) { rty_balancingCmd[i] = (rtu_SegmentVoltageVector[i] - rtu_CellMinV > 0.001); } localDW->flagBalancingDone = true; i = 0; exitg1 = false; while ((!exitg1) && (i < 10)) { if (rty_balancingCmd[i]) { localDW->flagBalancingDone = false; exitg1 = true; } else { i++; } } *rty_balancingFlag = true; break; default: /* case IN_WaitRelaxation: */ if ((uint32_T)((int32_T)localDW->temporalCounter_i1 * 10) >= 1000U) { localDW->is_ON = bms_IN_MeasureVoltages; *rty_DeltaVCell = rtu_CellMaxV - rtu_CellMinV; } break; } } /* End of Chart: '<S4>/Chart1' */ } /* Model step function */ void bms_step(void) { real_T rtb_Selector[10]; real_T rtb_Selector1[10]; real_T rtb_Selector2[10]; real_T maxV; real_T maxV_0; real_T maxV_1; real_T maxV_2; real_T maxV_3; real_T maxV_4; real_T minV; real_T minV_0; real_T minV_tmp; real_T minV_tmp_0; real_T minV_tmp_1; real_T rtb_Gain; real_T rtb_Max3; real_T rtb_Min3; real_T rtb_Min4; int32_T i; int32_T maxV_tmp; SystemState_t tmp; /* Concatenate: '<S1>/Matrix Concatenate1' incorporates: * DiscreteIntegrator: '<S10>/Discrete-Time Integrator' * DiscreteIntegrator: '<S11>/Discrete-Time Integrator' * DiscreteIntegrator: '<S12>/Discrete-Time Integrator' * DiscreteIntegrator: '<S13>/Discrete-Time Integrator' * DiscreteIntegrator: '<S14>/Discrete-Time Integrator' * DiscreteIntegrator: '<S15>/Discrete-Time Integrator' * DiscreteIntegrator: '<S16>/Discrete-Time Integrator' * DiscreteIntegrator: '<S17>/Discrete-Time Integrator' * DiscreteIntegrator: '<S18>/Discrete-Time Integrator' * DiscreteIntegrator: '<S19>/Discrete-Time Integrator' * DiscreteIntegrator: '<S20>/Discrete-Time Integrator' * DiscreteIntegrator: '<S21>/Discrete-Time Integrator' * DiscreteIntegrator: '<S22>/Discrete-Time Integrator' * DiscreteIntegrator: '<S23>/Discrete-Time Integrator' * DiscreteIntegrator: '<S24>/Discrete-Time Integrator' * DiscreteIntegrator: '<S25>/Discrete-Time Integrator' * DiscreteIntegrator: '<S26>/Discrete-Time Integrator' * DiscreteIntegrator: '<S27>/Discrete-Time Integrator' * DiscreteIntegrator: '<S28>/Discrete-Time Integrator' * DiscreteIntegrator: '<S29>/Discrete-Time Integrator' * DiscreteIntegrator: '<S30>/Discrete-Time Integrator' * DiscreteIntegrator: '<S31>/Discrete-Time Integrator' * DiscreteIntegrator: '<S32>/Discrete-Time Integrator' * DiscreteIntegrator: '<S33>/Discrete-Time Integrator' * DiscreteIntegrator: '<S34>/Discrete-Time Integrator' * DiscreteIntegrator: '<S35>/Discrete-Time Integrator' * DiscreteIntegrator: '<S36>/Discrete-Time Integrator' * DiscreteIntegrator: '<S37>/Discrete-Time Integrator' * DiscreteIntegrator: '<S8>/Discrete-Time Integrator' * DiscreteIntegrator: '<S9>/Discrete-Time Integrator' */ bms_Y.ToPlant.BusSOCEstimation.CDCEstimation[0] = bms_DW.DiscreteTimeIntegrator_DSTATE; bms_Y.ToPlant.BusSOCEstimation.CDCEstimation[3] = bms_DW.DiscreteTimeIntegrator_DSTATE_a; bms_Y.ToPlant.BusSOCEstimation.CDCEstimation[6] = bms_DW.DiscreteTimeIntegrator_DSTAT_au; bms_Y.ToPlant.BusSOCEstimation.CDCEstimation[9] = bms_DW.DiscreteTimeIntegrator_DSTATE_m; bms_Y.ToPlant.BusSOCEstimation.CDCEstimation[12] = bms_DW.DiscreteTimeIntegrator_DSTATE_b; bms_Y.ToPlant.BusSOCEstimation.CDCEstimation[15] = bms_DW.DiscreteTimeIntegrator_DSTATE_p; bms_Y.ToPlant.BusSOCEstimation.CDCEstimation[18] = bms_DW.DiscreteTimeIntegrator_DSTATE_c; bms_Y.ToPlant.BusSOCEstimation.CDCEstimation[21] = bms_DW.DiscreteTimeIntegrator_DSTAT_mh; bms_Y.ToPlant.BusSOCEstimation.CDCEstimation[24] = bms_DW.DiscreteTimeIntegrator_DSTATE_g; bms_Y.ToPlant.BusSOCEstimation.CDCEstimation[27] = bms_DW.DiscreteTimeIntegrator_DSTAT_g0; bms_Y.ToPlant.BusSOCEstimation.CDCEstimation[1] = bms_DW.DiscreteTimeIntegrator_DSTATE_d; bms_Y.ToPlant.BusSOCEstimation.CDCEstimation[4] = bms_DW.DiscreteTimeIntegrator_DSTAT_b0; bms_Y.ToPlant.BusSOCEstimation.CDCEstimation[7] = bms_DW.DiscreteTimeIntegrator_DSTAT_dc; bms_Y.ToPlant.BusSOCEstimation.CDCEstimation[10] = bms_DW.DiscreteTimeIntegrator_DSTATE_o; bms_Y.ToPlant.BusSOCEstimation.CDCEstimation[13] = bms_DW.DiscreteTimeIntegrator_DSTAT_aw; bms_Y.ToPlant.BusSOCEstimation.CDCEstimation[16] = bms_DW.DiscreteTimeIntegrator_DSTATE_n; bms_Y.ToPlant.BusSOCEstimation.CDCEstimation[19] = bms_DW.DiscreteTimeIntegrator_DSTATE_e; bms_Y.ToPlant.BusSOCEstimation.CDCEstimation[22] = bms_DW.DiscreteTimeIntegrator_DSTATE_f; bms_Y.ToPlant.BusSOCEstimation.CDCEstimation[25] = bms_DW.DiscreteTimeIntegrator_DSTAT_aj; bms_Y.ToPlant.BusSOCEstimation.CDCEstimation[28] = bms_DW.DiscreteTimeIntegrator_DSTAT_bc; bms_Y.ToPlant.BusSOCEstimation.CDCEstimation[2] = bms_DW.DiscreteTimeIntegrator_DSTAT_ps; bms_Y.ToPlant.BusSOCEstimation.CDCEstimation[5] = bms_DW.DiscreteTimeIntegrator_DSTAT_ed; bms_Y.ToPlant.BusSOCEstimation.CDCEstimation[8] = bms_DW.DiscreteTimeIntegrator_DSTAT_mg; bms_Y.ToPlant.BusSOCEstimation.CDCEstimation[11] = bms_DW.DiscreteTimeIntegrator_DSTAT_fy; bms_Y.ToPlant.BusSOCEstimation.CDCEstimation[14] = bms_DW.DiscreteTimeIntegrator_DSTAT_gd; bms_Y.ToPlant.BusSOCEstimation.CDCEstimation[17] = bms_DW.DiscreteTimeIntegrator_DSTATE_i; bms_Y.ToPlant.BusSOCEstimation.CDCEstimation[20] = bms_DW.DiscreteTimeIntegrator_DSTAT_ce; bms_Y.ToPlant.BusSOCEstimation.CDCEstimation[23] = bms_DW.DiscreteTimeIntegrator_DSTAT_p0; bms_Y.ToPlant.BusSOCEstimation.CDCEstimation[26] = bms_DW.DiscreteTimeIntegrator_DSTAT_fb; bms_Y.ToPlant.BusSOCEstimation.CDCEstimation[29] = bms_DW.DiscreteTimeIntegrator_DSTAT_d3; /* Selector: '<S4>/Selector' incorporates: * Inport: '<Root>/FromPlant' */ for (i = 0; i < 10; i++) { rtb_Selector[i] = bms_U.FromPlant.BMSBatteryPackData.SegmentVoltageVector[3 * i]; } /* MinMax: '<S4>/Max' incorporates: * Inport: '<Root>/FromPlant' * Selector: '<S4>/Selector' */ rtb_Gain = bms_U.FromPlant.BMSBatteryPackData.SegmentVoltageVector[0]; for (i = 0; i < 9; i++) { rtb_Gain = fmax(rtb_Gain, bms_U.FromPlant.BMSBatteryPackData.SegmentVoltageVector[(i + 1) * 3]); } /* Selector: '<S4>/Selector1' incorporates: * Inport: '<Root>/FromPlant' */ for (i = 0; i < 10; i++) { rtb_Selector1[i] = bms_U.FromPlant.BMSBatteryPackData.SegmentVoltageVector[3 * i + 1]; } /* MinMax: '<S4>/Max1' incorporates: * Inport: '<Root>/FromPlant' * Selector: '<S4>/Selector1' */ maxV = bms_U.FromPlant.BMSBatteryPackData.SegmentVoltageVector[1]; for (i = 0; i < 9; i++) { maxV = fmax(maxV, bms_U.FromPlant.BMSBatteryPackData.SegmentVoltageVector[(i + 1) * 3 + 1]); } /* Selector: '<S4>/Selector2' incorporates: * Inport: '<Root>/FromPlant' */ for (i = 0; i < 10; i++) { rtb_Selector2[i] = bms_U.FromPlant.BMSBatteryPackData.SegmentVoltageVector[3 * i + 2]; } /* MinMax: '<S4>/Max2' incorporates: * Inport: '<Root>/FromPlant' * Selector: '<S4>/Selector2' */ maxV_0 = bms_U.FromPlant.BMSBatteryPackData.SegmentVoltageVector[2]; /* MinMax: '<S4>/Min' incorporates: * Inport: '<Root>/FromPlant' * Selector: '<S4>/Selector' */ rtb_Max3 = bms_U.FromPlant.BMSBatteryPackData.SegmentVoltageVector[0]; /* MinMax: '<S4>/Min1' incorporates: * Inport: '<Root>/FromPlant' * Selector: '<S4>/Selector1' */ minV = bms_U.FromPlant.BMSBatteryPackData.SegmentVoltageVector[1]; /* MinMax: '<S4>/Min2' incorporates: * Inport: '<Root>/FromPlant' * Selector: '<S4>/Selector2' */ minV_0 = bms_U.FromPlant.BMSBatteryPackData.SegmentVoltageVector[2]; for (i = 0; i < 9; i++) { /* MinMax: '<S4>/Max2' incorporates: * Inport: '<Root>/FromPlant' * MinMax: '<S4>/Min' * MinMax: '<S4>/Min1' * MinMax: '<S4>/Min2' * Selector: '<S4>/Selector' * Selector: '<S4>/Selector1' * Selector: '<S4>/Selector2' */ maxV_tmp = (i + 1) * 3; rtb_Min3 = bms_U.FromPlant.BMSBatteryPackData.SegmentVoltageVector[maxV_tmp + 2]; maxV_0 = fmax(maxV_0, rtb_Min3); /* MinMax: '<S4>/Min' incorporates: * Inport: '<Root>/FromPlant' * Selector: '<S4>/Selector' */ rtb_Max3 = fmin(rtb_Max3, bms_U.FromPlant.BMSBatteryPackData.SegmentVoltageVector[maxV_tmp]); /* MinMax: '<S4>/Min1' incorporates: * Inport: '<Root>/FromPlant' * Selector: '<S4>/Selector1' */ minV = fmin(minV, bms_U.FromPlant.BMSBatteryPackData.SegmentVoltageVector[maxV_tmp + 1]); /* MinMax: '<S4>/Min2' */ minV_0 = fmin(minV_0, rtb_Min3); } /* MinMax: '<S4>/Min3' incorporates: * MinMax: '<S4>/Max' * MinMax: '<S4>/Max1' * MinMax: '<S4>/Max2' */ rtb_Min3 = fmax(fmax(rtb_Gain, maxV), maxV_0); /* MinMax: '<S4>/Min4' incorporates: * MinMax: '<S4>/Min' * MinMax: '<S4>/Min1' * MinMax: '<S4>/Min2' */ rtb_Min4 = fmin(fmin(rtb_Max3, minV), minV_0); /* Chart: '<S3>/Chart' incorporates: * Inport: '<Root>/FromPlant' * Inport: '<Root>/InputSimulationBus' */ switch (bms_DW.is_c1_bms) { case bms_IN_charging: bms_B.VectorConcatenate[0] = 0.0; bms_B.VectorConcatenate3[0] = 1.0; break; case bms_IN_dis_charger: bms_B.VectorConcatenate1[0] = 0.0; bms_B.VectorConcatenate2[0] = 1.0; bms_B.VectorConcatenate3[0] = 0.0; break; case bms_IN_dis_inverter: bms_B.VectorConcatenate1[1] = 0.0; bms_B.VectorConcatenate2[1] = 1.0; bms_B.VectorConcatenate3[1] = 0.0; break; case bms_IN_driving: bms_B.VectorConcatenate[1] = 0.0; bms_B.VectorConcatenate3[1] = 1.0; break; case bms_IN_en_charger: bms_B.VectorConcatenate1[0] = 1.0; break; case bms_IN_en_charger_prechrg: bms_B.VectorConcatenate[0] = 1.0; bms_B.VectorConcatenate1[2] = 1.0; break; case bms_IN_en_inverter: bms_B.VectorConcatenate1[1] = 1.0; break; case bms_IN_en_inverter_prechrg: bms_B.VectorConcatenate[1] = 1.0; bms_B.VectorConcatenate1[2] = 1.0; break; default: /* case IN_init: */ bms_B.VectorConcatenate1[2] = 0.0; bms_B.VectorConcatenate[0] = 0.0; bms_B.VectorConcatenate[1] = 0.0; bms_B.VectorConcatenate1[0] = 0.0; bms_B.VectorConcatenate1[1] = 0.0; bms_B.VectorConcatenate2[0] = 0.0; bms_B.VectorConcatenate2[1] = 0.0; bms_B.VectorConcatenate3[0] = 0.0; bms_B.VectorConcatenate3[1] = 0.0; break; } if (bms_DW.isNotInit && (bms_DW.temporalCounter_i1 < MAX_uint32_T)) { bms_DW.temporalCounter_i1++; } bms_DW.isNotInit = true; switch (bms_DW.is_c1_bms) { case bms_IN_charging: tmp = bms_U.InputSimulationBus.SimulationSystemInput.SystemState; if (tmp!= SystemState_t_Charging) { bms_DW.is_c1_bms = bms_IN_dis_charger; } else if (tmp == SystemState_t_Charging) { bms_DW.is_c1_bms = bms_IN_charging; } break; case bms_IN_dis_charger: if (bms_U.FromPlant.BMSContactorModuleData.VCharger < 0.2 * bms_U.FromPlant.BMSContactorModuleData.VBatt) { bms_DW.is_c1_bms = bms_IN_init; } break; case bms_IN_dis_inverter: if (bms_U.FromPlant.BMSContactorModuleData.VInverter < 0.2 * bms_U.FromPlant.BMSContactorModuleData.VBatt) { bms_DW.is_c1_bms = bms_IN_init; } break; case bms_IN_driving: tmp = bms_U.InputSimulationBus.SimulationSystemInput.SystemState; if (tmp!= SystemState_t_Driving) { bms_DW.is_c1_bms = bms_IN_dis_inverter; } else if (tmp == SystemState_t_Driving) { bms_DW.is_c1_bms = bms_IN_driving; } break; case bms_IN_en_charger: if (bms_DW.temporalCounter_i1 >= 10U) { bms_DW.is_c1_bms = bms_IN_charging; } break; case bms_IN_en_charger_prechrg: maxV_4 = 0.8 * bms_U.FromPlant.BMSContactorModuleData.VBatt; if (bms_U.FromPlant.BMSContactorModuleData.VCharger >= maxV_4) { bms_DW.is_c1_bms = bms_IN_en_charger; bms_DW.temporalCounter_i1 = 0U; } else if (bms_U.FromPlant.BMSContactorModuleData.VCharger < maxV_4) { bms_DW.is_c1_bms = bms_IN_en_charger_prechrg; } else if (bms_U.InputSimulationBus.SimulationSystemInput.SystemState!= SystemState_t_Driving) { bms_DW.is_c1_bms = bms_IN_init; } break; case bms_IN_en_inverter: if (bms_DW.temporalCounter_i1 >= 10U) { bms_DW.is_c1_bms = bms_IN_driving; } break; case bms_IN_en_inverter_prechrg: maxV_4 = 0.8 * bms_U.FromPlant.BMSContactorModuleData.VBatt; if (bms_U.FromPlant.BMSContactorModuleData.VInverter >= maxV_4) { bms_DW.is_c1_bms = bms_IN_en_inverter; bms_DW.temporalCounter_i1 = 0U; } else if (bms_U.FromPlant.BMSContactorModuleData.VInverter < maxV_4) { bms_DW.is_c1_bms = bms_IN_en_inverter_prechrg; } else if (bms_U.InputSimulationBus.SimulationSystemInput.SystemState!= SystemState_t_Driving) { bms_DW.is_c1_bms = bms_IN_init; } break; default: /* case IN_init: */ tmp = bms_U.InputSimulationBus.SimulationSystemInput.SystemState; if ((bms_U.FromPlant.BMSContactorModuleData.VBatt > 1.0) && (tmp == SystemState_t_Charging)) { bms_DW.is_c1_bms = bms_IN_en_charger_prechrg; } else if ((bms_U.FromPlant.BMSContactorModuleData.VBatt > 1.0) && (tmp == SystemState_t_Driving)) { bms_DW.is_c1_bms = bms_IN_en_inverter_prechrg; } break; } /* End of Chart: '<S3>/Chart' */ /* Chart: '<S4>/Chart1' incorporates: * Inport: '<Root>/InputSimulationBus' */ bms_Chart1(bms_U.InputSimulationBus.SimulationSystemInput.SystemState, rtb_Selector, rtb_Min3, rtb_Min4, &bms_B.MatrixConcatenate[0], &bms_B.VectorConcatenate_k[0], &bms_B.VectorConcatenate1_a[0], &bms_DW.sf_Chart1); /* Chart: '<S4>/Chart2' incorporates: * Inport: '<Root>/InputSimulationBus' */ bms_Chart1(bms_U.InputSimulationBus.SimulationSystemInput.SystemState, rtb_Selector1, rtb_Min3, rtb_Min4, &bms_B.MatrixConcatenate[10], &bms_B.VectorConcatenate_k[1], &bms_B.VectorConcatenate1_a[1], &bms_DW.sf_Chart2); /* Chart: '<S4>/Chart3' incorporates: * Inport: '<Root>/InputSimulationBus' */ bms_Chart1(bms_U.InputSimulationBus.SimulationSystemInput.SystemState, rtb_Selector2, rtb_Min3, rtb_Min4, &bms_B.MatrixConcatenate[20], &bms_B.VectorConcatenate_k[2], &bms_B.VectorConcatenate1_a[2], &bms_DW.sf_Chart3); /* Math: '<S4>/Transpose' incorporates: * Concatenate: '<S4>/Matrix Concatenate' */ for (i = 0; i < 10; i++) { bms_Y.ToPlant.BMSBatteryPackInput.BalCmdVector[3 * i] = bms_B.MatrixConcatenate[i]; bms_Y.ToPlant.BMSBatteryPackInput.BalCmdVector[3 * i + 1] = bms_B.MatrixConcatenate[i + 10]; bms_Y.ToPlant.BMSBatteryPackInput.BalCmdVector[3 * i + 2] = bms_B.MatrixConcatenate[i + 20]; } /* End of Math: '<S4>/Transpose' */ /* MinMax: '<S2>/Max15' incorporates: * Inport: '<Root>/FromPlant' * Selector: '<S2>/Selector12' */ rtb_Max3 = bms_U.FromPlant.BMSBatteryPackData.SegmentVoltageVector[2]; /* MinMax: '<S2>/Max13' incorporates: * Inport: '<Root>/FromPlant' * Selector: '<S2>/Selector10' */ minV = bms_U.FromPlant.BMSBatteryPackData.SegmentVoltageVector[0]; /* MinMax: '<S2>/Max14' incorporates: * Inport: '<Root>/FromPlant' * Selector: '<S2>/Selector11' */ minV_0 = bms_U.FromPlant.BMSBatteryPackData.SegmentVoltageVector[1]; /* MinMax: '<S2>/Max4' incorporates: * Inport: '<Root>/FromPlant' * Selector: '<S2>/Selector1' */ rtb_Gain = bms_U.FromPlant.BMSBatteryPackData.SegmentCurrentVector[0]; /* MinMax: '<S2>/Max5' incorporates: * Inport: '<Root>/FromPlant' * Selector: '<S2>/Selector2' */ maxV = bms_U.FromPlant.BMSBatteryPackData.SegmentCurrentVector[1]; /* MinMax: '<S2>/Max6' incorporates: * Inport: '<Root>/FromPlant' * Selector: '<S2>/Selector3' */ maxV_0 = bms_U.FromPlant.BMSBatteryPackData.SegmentCurrentVector[2]; /* MinMax: '<S2>/Max7' incorporates: * Inport: '<Root>/FromPlant' * Selector: '<S2>/Selector4' */ maxV_1 = bms_U.FromPlant.BMSBatteryPackData.SegmentTempVector[0]; /* MinMax: '<S2>/Max8' incorporates: * Inport: '<Root>/FromPlant' * Selector: '<S2>/Selector5' */ maxV_2 = bms_U.FromPlant.BMSBatteryPackData.SegmentTempVector[1]; /* MinMax: '<S2>/Max9' incorporates: * Inport: '<Root>/FromPlant' * Selector: '<S2>/Selector6' */ maxV_3 = bms_U.FromPlant.BMSBatteryPackData.SegmentTempVector[2]; /* MinMax: '<S2>/Max10' incorporates: * Inport: '<Root>/FromPlant' * Selector: '<S2>/Selector7' */ rtb_Min3 = bms_U.FromPlant.BMSBatteryPackData.SegmentVoltageVector[0]; /* MinMax: '<S2>/Max11' incorporates: * Inport: '<Root>/FromPlant' * Selector: '<S2>/Selector8' */ rtb_Min4 = bms_U.FromPlant.BMSBatteryPackData.SegmentVoltageVector[1]; /* MinMax: '<S2>/Max12' incorporates: * Inport: '<Root>/FromPlant' * Selector: '<S2>/Selector9' */ maxV_4 = bms_U.FromPlant.BMSBatteryPackData.SegmentVoltageVector[2]; for (i = 0; i < 9; i++) { /* MinMax: '<S2>/Max15' incorporates: * Inport: '<Root>/FromPlant' * MinMax: '<S2>/Max10' * MinMax: '<S2>/Max12' * MinMax: '<S2>/Max13' * MinMax: '<S2>/Max14' * MinMax: '<S2>/Max4' * MinMax: '<S2>/Max7' * Selector: '<S2>/Selector1' * Selector: '<S2>/Selector10' * Selector: '<S2>/Selector11' * Selector: '<S2>/Selector12' * Selector: '<S2>/Selector4' * Selector: '<S2>/Selector7' * Selector: '<S2>/Selector9' */ maxV_tmp = (i + 1) * 3; minV_tmp_1 = bms_U.FromPlant.BMSBatteryPackData.SegmentVoltageVector[maxV_tmp + 2]; rtb_Max3 = fmin(rtb_Max3, minV_tmp_1); /* MinMax: '<S2>/Max13' incorporates: * Inport: '<Root>/FromPlant' * MinMax: '<S2>/Max10' * Selector: '<S2>/Selector10' * Selector: '<S2>/Selector7' */ minV_tmp = bms_U.FromPlant.BMSBatteryPackData.SegmentVoltageVector[maxV_tmp]; minV = fmin(minV, minV_tmp); /* MinMax: '<S2>/Max14' incorporates: * Inport: '<Root>/FromPlant' * MinMax: '<S2>/Max11' * Selector: '<S2>/Selector11' * Selector: '<S2>/Selector8' */ minV_tmp_0 = bms_U.FromPlant.BMSBatteryPackData.SegmentVoltageVector[maxV_tmp + 1]; minV_0 = fmin(minV_0, minV_tmp_0); /* MinMax: '<S2>/Max4' incorporates: * Inport: '<Root>/FromPlant' * Selector: '<S2>/Selector1' */ rtb_Gain = fmax(rtb_Gain, bms_U.FromPlant.BMSBatteryPackData.SegmentCurrentVector[maxV_tmp]); /* MinMax: '<S2>/Max5' incorporates: * Inport: '<Root>/FromPlant' * MinMax: '<S2>/Max14' * Selector: '<S2>/Selector11' * Selector: '<S2>/Selector2' */ maxV = fmax(maxV, bms_U.FromPlant.BMSBatteryPackData.SegmentCurrentVector[maxV_tmp + 1]); /* MinMax: '<S2>/Max6' incorporates: * Inport: '<Root>/FromPlant' * MinMax: '<S2>/Max15' * Selector: '<S2>/Selector12' * Selector: '<S2>/Selector3' */ maxV_0 = fmax(maxV_0, bms_U.FromPlant.BMSBatteryPackData.SegmentCurrentVector[maxV_tmp + 2]); /* MinMax: '<S2>/Max7' incorporates: * Inport: '<Root>/FromPlant' * Selector: '<S2>/Selector4' */ maxV_1 = fmax(maxV_1, bms_U.FromPlant.BMSBatteryPackData.SegmentTempVector[maxV_tmp]); /* MinMax: '<S2>/Max8' incorporates: * Inport: '<Root>/FromPlant' * MinMax: '<S2>/Max14' * Selector: '<S2>/Selector11' * Selector: '<S2>/Selector5' */ maxV_2 = fmax(maxV_2, bms_U.FromPlant.BMSBatteryPackData.SegmentTempVector[maxV_tmp + 1]); /* MinMax: '<S2>/Max9' incorporates: * Inport: '<Root>/FromPlant' * MinMax: '<S2>/Max15' * Selector: '<S2>/Selector12' * Selector: '<S2>/Selector6' */ maxV_3 = fmax(maxV_3, bms_U.FromPlant.BMSBatteryPackData.SegmentTempVector[maxV_tmp + 2]); /* MinMax: '<S2>/Max10' */ rtb_Min3 = fmax(rtb_Min3, minV_tmp); /* MinMax: '<S2>/Max11' */ rtb_Min4 = fmax(rtb_Min4, minV_tmp_0); /* MinMax: '<S2>/Max12' */ maxV_4 = fmax(maxV_4, minV_tmp_1); } /* MinMax: '<S2>/Max3' incorporates: * MinMax: '<S2>/Max13' * MinMax: '<S2>/Max14' * MinMax: '<S2>/Max15' */ rtb_Max3 = fmin(fmin(minV, minV_0), rtb_Max3); /* RelationalOperator: '<S44>/Compare' incorporates: * Constant: '<S44>/Constant' */ bms_Y.ToPlant.BMSFaultOutput.UnderVoltageWarning = (rtb_Max3 <= 2.7); /* MinMax: '<S2>/Max' incorporates: * MinMax: '<S2>/Max4' * MinMax: '<S2>/Max5' * MinMax: '<S2>/Max6' */ rtb_Gain = fmax(fmax(rtb_Gain, maxV), maxV_0); /* RelationalOperator: '<S38>/Compare' incorporates: * Constant: '<S38>/Constant' */ bms_Y.ToPlant.BMSFaultOutput.OverCurrentWarning = (rtb_Gain >= 20.0); /* RelationalOperator: '<S39>/Compare' incorporates: * Constant: '<S39>/Constant' */ bms_Y.ToPlant.BMSFaultOutput.OverCurrentFault = (rtb_Gain >= 50.0); /* MinMax: '<S2>/Max1' incorporates: * MinMax: '<S2>/Max7' * MinMax: '<S2>/Max8' * MinMax: '<S2>/Max9' */ rtb_Gain = fmax(fmax(maxV_1, maxV_2), maxV_3); /* RelationalOperator: '<S40>/Compare' incorporates: * Constant: '<S40>/Constant' */ bms_Y.ToPlant.BMSFaultOutput.OverTemperatureWarning = (rtb_Gain >= 323.15); /* RelationalOperator: '<S41>/Compare' incorporates: * Constant: '<S41>/Constant' */ bms_Y.ToPlant.BMSFaultOutput.OverTemperatureFault = (rtb_Gain >= 338.15); /* MinMax: '<S2>/Max2' incorporates: * MinMax: '<S2>/Max10' * MinMax: '<S2>/Max11' * MinMax: '<S2>/Max12' */ rtb_Gain = fmax(fmax(rtb_Min3, rtb_Min4), maxV_4); /* RelationalOperator: '<S42>/Compare' incorporates: * Constant: '<S42>/Constant' */ bms_Y.ToPlant.BMSFaultOutput.OverVoltageWarning = (rtb_Gain >= 4.21); /* RelationalOperator: '<S43>/Compare' incorporates: * Constant: '<S43>/Constant' */ bms_Y.ToPlant.BMSFaultOutput.OverVoltageFault = (rtb_Gain >= 4.25); /* RelationalOperator: '<S45>/Compare' incorporates: * Constant: '<S45>/Constant' */ bms_Y.ToPlant.BMSFaultOutput.UnderVoltageFault = (rtb_Max3 <= 2.65); /* BusCreator generated from: '<Root>/ToPlant' */ bms_Y.ToPlant.BMSContactorModuleCmd.ContactorCmd[0] = bms_B.VectorConcatenate1[0]; bms_Y.ToPlant.BMSContactorModuleCmd.ContactorCmd[1] = bms_B.VectorConcatenate1[1]; bms_Y.ToPlant.BMSContactorModuleCmd.ContactorCmd[2] = bms_B.VectorConcatenate1[2]; bms_Y.ToPlant.BMSContactorModuleCmd.PreChrgCmd[0] = bms_B.VectorConcatenate[0]; bms_Y.ToPlant.BMSContactorModuleCmd.DisChrgCmd[0] = bms_B.VectorConcatenate2[0]; bms_Y.ToPlant.BMSContactorModuleCmd.DrivetrainEn[0] = bms_B.VectorConcatenate3[0]; bms_Y.ToPlant.BMSContactorModuleCmd.PreChrgCmd[1] = bms_B.VectorConcatenate[1]; bms_Y.ToPlant.BMSContactorModuleCmd.DisChrgCmd[1] = bms_B.VectorConcatenate2[1]; bms_Y.ToPlant.BMSContactorModuleCmd.DrivetrainEn[1] = bms_B.VectorConcatenate3[1]; /* BusCreator generated from: '<Root>/ToPlant' */ bms_Y.ToPlant.BMSBatteryPackInput.balancingDeltaVCell[0] = bms_B.VectorConcatenate_k[0]; bms_Y.ToPlant.BMSBatteryPackInput.balancingFlags[0] = bms_B.VectorConcatenate1_a[0]; bms_Y.ToPlant.BMSBatteryPackInput.balancingDeltaVCell[1] = bms_B.VectorConcatenate_k[1]; bms_Y.ToPlant.BMSBatteryPackInput.balancingFlags[1] = bms_B.VectorConcatenate1_a[1]; bms_Y.ToPlant.BMSBatteryPackInput.balancingDeltaVCell[2] = bms_B.VectorConcatenate_k[2]; bms_Y.ToPlant.BMSBatteryPackInput.balancingFlags[2] = bms_B.VectorConcatenate1_a[2]; /* BusCreator generated from: '<Root>/ToPlant' incorporates: * Concatenate: '<S1>/Matrix Concatenate' */ memcpy(&bms_Y.ToPlant.BusSOCEstimation.EKFEstimation[0], &bms_ConstB.EKFEstimation[0], 30U * sizeof(real_T)); /* Update for DiscreteIntegrator: '<S17>/Discrete-Time Integrator' incorporates: * Gain: '<S17>/Gain' * Inport: '<Root>/FromPlant' * Lookup_n-D: '<S17>/n-D Lookup Table' * Product: '<S17>/Divide' * Selector: '<S1>/Selector1' * Selector: '<S1>/Selector2' */ bms_DW.DiscreteTimeIntegrator_DSTATE += -0.00027777778450399637 * bms_U.FromPlant.BMSBatteryPackData.SegmentCurrentVector[0] / look1_binlxpw (bms_U.FromPlant.BMSBatteryPackData.SegmentTempVector[0], bms_ConstP.pooled8, bms_ConstP.pooled7, 2U) * 0.01; if (bms_DW.DiscreteTimeIntegrator_DSTATE >= 1.0) { bms_DW.DiscreteTimeIntegrator_DSTATE = 1.0; } else if (bms_DW.DiscreteTimeIntegrator_DSTATE <= 0.0) { bms_DW.DiscreteTimeIntegrator_DSTATE = 0.0; } /* End of Update for DiscreteIntegrator: '<S17>/Discrete-Time Integrator' */ /* Update for DiscreteIntegrator: '<S8>/Discrete-Time Integrator' incorporates: * Gain: '<S8>/Gain' * Inport: '<Root>/FromPlant' * Lookup_n-D: '<S8>/n-D Lookup Table' * Product: '<S8>/Divide' * Selector: '<S1>/Selector1' * Selector: '<S1>/Selector2' */ bms_DW.DiscreteTimeIntegrator_DSTATE_a += -0.00027777778450399637 * bms_U.FromPlant.BMSBatteryPackData.SegmentCurrentVector[3] / look1_binlxpw (bms_U.FromPlant.BMSBatteryPackData.SegmentTempVector[3], bms_ConstP.pooled8, bms_ConstP.pooled7, 2U) * 0.01; if (bms_DW.DiscreteTimeIntegrator_DSTATE_a >= 1.0) { bms_DW.DiscreteTimeIntegrator_DSTATE_a = 1.0; } else if (bms_DW.DiscreteTimeIntegrator_DSTATE_a <= 0.0) { bms_DW.DiscreteTimeIntegrator_DSTATE_a = 0.0; } /* End of Update for DiscreteIntegrator: '<S8>/Discrete-Time Integrator' */ /* Update for DiscreteIntegrator: '<S9>/Discrete-Time Integrator' incorporates: * Gain: '<S9>/Gain' * Inport: '<Root>/FromPlant' * Lookup_n-D: '<S9>/n-D Lookup Table' * Product: '<S9>/Divide' * Selector: '<S1>/Selector1' * Selector: '<S1>/Selector2' */ bms_DW.DiscreteTimeIntegrator_DSTAT_au += -0.00027777778450399637 * bms_U.FromPlant.BMSBatteryPackData.SegmentCurrentVector[6] / look1_binlxpw (bms_U.FromPlant.BMSBatteryPackData.SegmentTempVector[6], bms_ConstP.pooled8, bms_ConstP.pooled7, 2U) * 0.01; if (bms_DW.DiscreteTimeIntegrator_DSTAT_au >= 1.0) { bms_DW.DiscreteTimeIntegrator_DSTAT_au = 1.0; } else if (bms_DW.DiscreteTimeIntegrator_DSTAT_au <= 0.0) { bms_DW.DiscreteTimeIntegrator_DSTAT_au = 0.0; } /* End of Update for DiscreteIntegrator: '<S9>/Discrete-Time Integrator' */ /* Update for DiscreteIntegrator: '<S10>/Discrete-Time Integrator' incorporates: * Gain: '<S10>/Gain' * Inport: '<Root>/FromPlant' * Lookup_n-D: '<S10>/n-D Lookup Table' * Product: '<S10>/Divide' * Selector: '<S1>/Selector1' * Selector: '<S1>/Selector2' */ bms_DW.DiscreteTimeIntegrator_DSTATE_m += -0.00027777778450399637 * bms_U.FromPlant.BMSBatteryPackData.SegmentCurrentVector[9] / look1_binlxpw (bms_U.FromPlant.BMSBatteryPackData.SegmentTempVector[9], bms_ConstP.pooled8, bms_ConstP.pooled7, 2U) * 0.01; if (bms_DW.DiscreteTimeIntegrator_DSTATE_m >= 1.0) { bms_DW.DiscreteTimeIntegrator_DSTATE_m = 1.0; } else if (bms_DW.DiscreteTimeIntegrator_DSTATE_m <= 0.0) { bms_DW.DiscreteTimeIntegrator_DSTATE_m = 0.0; } /* End of Update for DiscreteIntegrator: '<S10>/Discrete-Time Integrator' */ /* Update for DiscreteIntegrator: '<S11>/Discrete-Time Integrator' incorporates: * Gain: '<S11>/Gain' * Inport: '<Root>/FromPlant' * Lookup_n-D: '<S11>/n-D Lookup Table' * Product: '<S11>/Divide' * Selector: '<S1>/Selector1' * Selector: '<S1>/Selector2' */ bms_DW.DiscreteTimeIntegrator_DSTATE_b += -0.00027777778450399637 * bms_U.FromPlant.BMSBatteryPackData.SegmentCurrentVector[12] / look1_binlxpw (bms_U.FromPlant.BMSBatteryPackData.SegmentTempVector[12], bms_ConstP.pooled8, bms_ConstP.pooled7, 2U) * 0.01; if (bms_DW.DiscreteTimeIntegrator_DSTATE_b >= 1.0) { bms_DW.DiscreteTimeIntegrator_DSTATE_b = 1.0; } else if (bms_DW.DiscreteTimeIntegrator_DSTATE_b <= 0.0) { bms_DW.DiscreteTimeIntegrator_DSTATE_b = 0.0; } /* End of Update for DiscreteIntegrator: '<S11>/Discrete-Time Integrator' */ /* Update for DiscreteIntegrator: '<S12>/Discrete-Time Integrator' incorporates: * Gain: '<S12>/Gain' * Inport: '<Root>/FromPlant' * Lookup_n-D: '<S12>/n-D Lookup Table' * Product: '<S12>/Divide' * Selector: '<S1>/Selector1' * Selector: '<S1>/Selector2' */ bms_DW.DiscreteTimeIntegrator_DSTATE_p += -0.00027777778450399637 * bms_U.FromPlant.BMSBatteryPackData.SegmentCurrentVector[15] / look1_binlxpw (bms_U.FromPlant.BMSBatteryPackData.SegmentTempVector[15], bms_ConstP.pooled8, bms_ConstP.pooled7, 2U) * 0.01; if (bms_DW.DiscreteTimeIntegrator_DSTATE_p >= 1.0) { bms_DW.DiscreteTimeIntegrator_DSTATE_p = 1.0; } else if (bms_DW.DiscreteTimeIntegrator_DSTATE_p <= 0.0) { bms_DW.DiscreteTimeIntegrator_DSTATE_p = 0.0; } /* End of Update for DiscreteIntegrator: '<S12>/Discrete-Time Integrator' */ /* Update for DiscreteIntegrator: '<S13>/Discrete-Time Integrator' incorporates: * Gain: '<S13>/Gain' * Inport: '<Root>/FromPlant' * Lookup_n-D: '<S13>/n-D Lookup Table' * Product: '<S13>/Divide' * Selector: '<S1>/Selector1' * Selector: '<S1>/Selector2' */ bms_DW.DiscreteTimeIntegrator_DSTATE_c += -0.00027777778450399637 * bms_U.FromPlant.BMSBatteryPackData.SegmentCurrentVector[18] / look1_binlxpw (bms_U.FromPlant.BMSBatteryPackData.SegmentTempVector[18], bms_ConstP.pooled8, bms_ConstP.pooled7, 2U) * 0.01; if (bms_DW.DiscreteTimeIntegrator_DSTATE_c >= 1.0) { bms_DW.DiscreteTimeIntegrator_DSTATE_c = 1.0; } else if (bms_DW.DiscreteTimeIntegrator_DSTATE_c <= 0.0) { bms_DW.DiscreteTimeIntegrator_DSTATE_c = 0.0; } /* End of Update for DiscreteIntegrator: '<S13>/Discrete-Time Integrator' */ /* Update for DiscreteIntegrator: '<S14>/Discrete-Time Integrator' incorporates: * Gain: '<S14>/Gain' * Inport: '<Root>/FromPlant' * Lookup_n-D: '<S14>/n-D Lookup Table' * Product: '<S14>/Divide' * Selector: '<S1>/Selector1' * Selector: '<S1>/Selector2' */ bms_DW.DiscreteTimeIntegrator_DSTAT_mh += -0.00027777778450399637 * bms_U.FromPlant.BMSBatteryPackData.SegmentCurrentVector[21] / look1_binlxpw (bms_U.FromPlant.BMSBatteryPackData.SegmentTempVector[21], bms_ConstP.pooled8, bms_ConstP.pooled7, 2U) * 0.01; if (bms_DW.DiscreteTimeIntegrator_DSTAT_mh >= 1.0) { bms_DW.DiscreteTimeIntegrator_DSTAT_mh = 1.0; } else if (bms_DW.DiscreteTimeIntegrator_DSTAT_mh <= 0.0) { bms_DW.DiscreteTimeIntegrator_DSTAT_mh = 0.0; } /* End of Update for DiscreteIntegrator: '<S14>/Discrete-Time Integrator' */ /* Update for DiscreteIntegrator: '<S15>/Discrete-Time Integrator' incorporates: * Gain: '<S15>/Gain' * Inport: '<Root>/FromPlant' * Lookup_n-D: '<S15>/n-D Lookup Table' * Product: '<S15>/Divide' * Selector: '<S1>/Selector1' * Selector: '<S1>/Selector2' */ bms_DW.DiscreteTimeIntegrator_DSTATE_g += -0.00027777778450399637 * bms_U.FromPlant.BMSBatteryPackData.SegmentCurrentVector[24] / look1_binlxpw (bms_U.FromPlant.BMSBatteryPackData.SegmentTempVector[24], bms_ConstP.pooled8, bms_ConstP.pooled7, 2U) * 0.01; if (bms_DW.DiscreteTimeIntegrator_DSTATE_g >= 1.0) { bms_DW.DiscreteTimeIntegrator_DSTATE_g = 1.0; } else if (bms_DW.DiscreteTimeIntegrator_DSTATE_g <= 0.0) { bms_DW.DiscreteTimeIntegrator_DSTATE_g = 0.0; } /* End of Update for DiscreteIntegrator: '<S15>/Discrete-Time Integrator' */ /* Update for DiscreteIntegrator: '<S16>/Discrete-Time Integrator' incorporates: * Gain: '<S16>/Gain' * Inport: '<Root>/FromPlant' * Lookup_n-D: '<S16>/n-D Lookup Table' * Product: '<S16>/Divide' * Selector: '<S1>/Selector1' * Selector: '<S1>/Selector2' */ bms_DW.DiscreteTimeIntegrator_DSTAT_g0 += -0.00027777778450399637 * bms_U.FromPlant.BMSBatteryPackData.SegmentCurrentVector[27] / look1_binlxpw (bms_U.FromPlant.BMSBatteryPackData.SegmentTempVector[27], bms_ConstP.pooled8, bms_ConstP.pooled7, 2U) * 0.01; if (bms_DW.DiscreteTimeIntegrator_DSTAT_g0 >= 1.0) { bms_DW.DiscreteTimeIntegrator_DSTAT_g0 = 1.0; } else if (bms_DW.DiscreteTimeIntegrator_DSTAT_g0 <= 0.0) { bms_DW.DiscreteTimeIntegrator_DSTAT_g0 = 0.0; } /* End of Update for DiscreteIntegrator: '<S16>/Discrete-Time Integrator' */ /* Update for DiscreteIntegrator: '<S27>/Discrete-Time Integrator' incorporates: * Gain: '<S27>/Gain' * Inport: '<Root>/FromPlant' * Lookup_n-D: '<S27>/n-D Lookup Table' * Product: '<S27>/Divide' * Selector: '<S1>/Selector4' * Selector: '<S1>/Selector5' */ bms_DW.DiscreteTimeIntegrator_DSTATE_d += -0.00027777778450399637 * bms_U.FromPlant.BMSBatteryPackData.SegmentCurrentVector[1] / look1_binlxpw (bms_U.FromPlant.BMSBatteryPackData.SegmentTempVector[1], bms_ConstP.pooled8, bms_ConstP.pooled7, 2U) * 0.01; if (bms_DW.DiscreteTimeIntegrator_DSTATE_d >= 1.0) { bms_DW.DiscreteTimeIntegrator_DSTATE_d = 1.0; } else if (bms_DW.DiscreteTimeIntegrator_DSTATE_d <= 0.0) { bms_DW.DiscreteTimeIntegrator_DSTATE_d = 0.0; } /* End of Update for DiscreteIntegrator: '<S27>/Discrete-Time Integrator' */ /* Update for DiscreteIntegrator: '<S18>/Discrete-Time Integrator' incorporates: * Gain: '<S18>/Gain' * Inport: '<Root>/FromPlant' * Lookup_n-D: '<S18>/n-D Lookup Table' * Product: '<S18>/Divide' * Selector: '<S1>/Selector4' * Selector: '<S1>/Selector5' */ bms_DW.DiscreteTimeIntegrator_DSTAT_b0 += -0.00027777778450399637 * bms_U.FromPlant.BMSBatteryPackData.SegmentCurrentVector[4] / look1_binlxpw (bms_U.FromPlant.BMSBatteryPackData.SegmentTempVector[4], bms_ConstP.pooled8, bms_ConstP.pooled7, 2U) * 0.01; if (bms_DW.DiscreteTimeIntegrator_DSTAT_b0 >= 1.0) { bms_DW.DiscreteTimeIntegrator_DSTAT_b0 = 1.0; } else if (bms_DW.DiscreteTimeIntegrator_DSTAT_b0 <= 0.0) { bms_DW.DiscreteTimeIntegrator_DSTAT_b0 = 0.0; } /* End of Update for DiscreteIntegrator: '<S18>/Discrete-Time Integrator' */ /* Update for DiscreteIntegrator: '<S19>/Discrete-Time Integrator' incorporates: * Gain: '<S19>/Gain' * Inport: '<Root>/FromPlant' * Lookup_n-D: '<S19>/n-D Lookup Table' * Product: '<S19>/Divide' * Selector: '<S1>/Selector4' * Selector: '<S1>/Selector5' */ bms_DW.DiscreteTimeIntegrator_DSTAT_dc += -0.00027777778450399637 * bms_U.FromPlant.BMSBatteryPackData.SegmentCurrentVector[7] / look1_binlxpw (bms_U.FromPlant.BMSBatteryPackData.SegmentTempVector[7], bms_ConstP.pooled8, bms_ConstP.pooled7, 2U) * 0.01; if (bms_DW.DiscreteTimeIntegrator_DSTAT_dc >= 1.0) { bms_DW.DiscreteTimeIntegrator_DSTAT_dc = 1.0; } else if (bms_DW.DiscreteTimeIntegrator_DSTAT_dc <= 0.0) { bms_DW.DiscreteTimeIntegrator_DSTAT_dc = 0.0; } /* End of Update for DiscreteIntegrator: '<S19>/Discrete-Time Integrator' */ /* Update for DiscreteIntegrator: '<S20>/Discrete-Time Integrator' incorporates: * Gain: '<S20>/Gain' * Inport: '<Root>/FromPlant' * Lookup_n-D: '<S20>/n-D Lookup Table' * Product: '<S20>/Divide' * Selector: '<S1>/Selector4' * Selector: '<S1>/Selector5' */ bms_DW.DiscreteTimeIntegrator_DSTATE_o += -0.00027777778450399637 * bms_U.FromPlant.BMSBatteryPackData.SegmentCurrentVector[10] / look1_binlxpw (bms_U.FromPlant.BMSBatteryPackData.SegmentTempVector[10], bms_ConstP.pooled8, bms_ConstP.pooled7, 2U) * 0.01; if (bms_DW.DiscreteTimeIntegrator_DSTATE_o >= 1.0) { bms_DW.DiscreteTimeIntegrator_DSTATE_o = 1.0; } else if (bms_DW.DiscreteTimeIntegrator_DSTATE_o <= 0.0) { bms_DW.DiscreteTimeIntegrator_DSTATE_o = 0.0; } /* End of Update for DiscreteIntegrator: '<S20>/Discrete-Time Integrator' */ /* Update for DiscreteIntegrator: '<S21>/Discrete-Time Integrator' incorporates: * Gain: '<S21>/Gain' * Inport: '<Root>/FromPlant' * Lookup_n-D: '<S21>/n-D Lookup Table' * Product: '<S21>/Divide' * Selector: '<S1>/Selector4' * Selector: '<S1>/Selector5' */ bms_DW.DiscreteTimeIntegrator_DSTAT_aw += -0.00027777778450399637 * bms_U.FromPlant.BMSBatteryPackData.SegmentCurrentVector[13] / look1_binlxpw (bms_U.FromPlant.BMSBatteryPackData.SegmentTempVector[13], bms_ConstP.pooled8, bms_ConstP.pooled7, 2U) * 0.01; if (bms_DW.DiscreteTimeIntegrator_DSTAT_aw >= 1.0) { bms_DW.DiscreteTimeIntegrator_DSTAT_aw = 1.0; } else if (bms_DW.DiscreteTimeIntegrator_DSTAT_aw <= 0.0) { bms_DW.DiscreteTimeIntegrator_DSTAT_aw = 0.0; } /* End of Update for DiscreteIntegrator: '<S21>/Discrete-Time Integrator' */ /* Update for DiscreteIntegrator: '<S22>/Discrete-Time Integrator' incorporates: * Gain: '<S22>/Gain' * Inport: '<Root>/FromPlant' * Lookup_n-D: '<S22>/n-D Lookup Table' * Product: '<S22>/Divide' * Selector: '<S1>/Selector4' * Selector: '<S1>/Selector5' */ bms_DW.DiscreteTimeIntegrator_DSTATE_n += -0.00027777778450399637 * bms_U.FromPlant.BMSBatteryPackData.SegmentCurrentVector[16] / look1_binlxpw (bms_U.FromPlant.BMSBatteryPackData.SegmentTempVector[16], bms_ConstP.pooled8, bms_ConstP.pooled7, 2U) * 0.01; if (bms_DW.DiscreteTimeIntegrator_DSTATE_n >= 1.0) { bms_DW.DiscreteTimeIntegrator_DSTATE_n = 1.0; } else if (bms_DW.DiscreteTimeIntegrator_DSTATE_n <= 0.0) { bms_DW.DiscreteTimeIntegrator_DSTATE_n = 0.0; } /* End of Update for DiscreteIntegrator: '<S22>/Discrete-Time Integrator' */ /* Update for DiscreteIntegrator: '<S23>/Discrete-Time Integrator' incorporates: * Gain: '<S23>/Gain' * Inport: '<Root>/FromPlant' * Lookup_n-D: '<S23>/n-D Lookup Table' * Product: '<S23>/Divide' * Selector: '<S1>/Selector4' * Selector: '<S1>/Selector5' */ bms_DW.DiscreteTimeIntegrator_DSTATE_e += -0.00027777778450399637 * bms_U.FromPlant.BMSBatteryPackData.SegmentCurrentVector[19] / look1_binlxpw (bms_U.FromPlant.BMSBatteryPackData.SegmentTempVector[19], bms_ConstP.pooled8, bms_ConstP.pooled7, 2U) * 0.01; if (bms_DW.DiscreteTimeIntegrator_DSTATE_e >= 1.0) { bms_DW.DiscreteTimeIntegrator_DSTATE_e = 1.0; } else if (bms_DW.DiscreteTimeIntegrator_DSTATE_e <= 0.0) { bms_DW.DiscreteTimeIntegrator_DSTATE_e = 0.0; } /* End of Update for DiscreteIntegrator: '<S23>/Discrete-Time Integrator' */ /* Update for DiscreteIntegrator: '<S24>/Discrete-Time Integrator' incorporates: * Gain: '<S24>/Gain' * Inport: '<Root>/FromPlant' * Lookup_n-D: '<S24>/n-D Lookup Table' * Product: '<S24>/Divide' * Selector: '<S1>/Selector4' * Selector: '<S1>/Selector5' */ bms_DW.DiscreteTimeIntegrator_DSTATE_f += -0.00027777778450399637 * bms_U.FromPlant.BMSBatteryPackData.SegmentCurrentVector[22] / look1_binlxpw (bms_U.FromPlant.BMSBatteryPackData.SegmentTempVector[22], bms_ConstP.pooled8, bms_ConstP.pooled7, 2U) * 0.01; if (bms_DW.DiscreteTimeIntegrator_DSTATE_f >= 1.0) { bms_DW.DiscreteTimeIntegrator_DSTATE_f = 1.0; } else if (bms_DW.DiscreteTimeIntegrator_DSTATE_f <= 0.0) { bms_DW.DiscreteTimeIntegrator_DSTATE_f = 0.0; } /* End of Update for DiscreteIntegrator: '<S24>/Discrete-Time Integrator' */ /* Update for DiscreteIntegrator: '<S25>/Discrete-Time Integrator' incorporates: * Gain: '<S25>/Gain' * Inport: '<Root>/FromPlant' * Lookup_n-D: '<S25>/n-D Lookup Table' * Product: '<S25>/Divide' * Selector: '<S1>/Selector4' * Selector: '<S1>/Selector5' */ bms_DW.DiscreteTimeIntegrator_DSTAT_aj += -0.00027777778450399637 * bms_U.FromPlant.BMSBatteryPackData.SegmentCurrentVector[25] / look1_binlxpw (bms_U.FromPlant.BMSBatteryPackData.SegmentTempVector[25], bms_ConstP.pooled8, bms_ConstP.pooled7, 2U) * 0.01; if (bms_DW.DiscreteTimeIntegrator_DSTAT_aj >= 1.0) { bms_DW.DiscreteTimeIntegrator_DSTAT_aj = 1.0; } else if (bms_DW.DiscreteTimeIntegrator_DSTAT_aj <= 0.0) { bms_DW.DiscreteTimeIntegrator_DSTAT_aj = 0.0; } /* End of Update for DiscreteIntegrator: '<S25>/Discrete-Time Integrator' */ /* Update for DiscreteIntegrator: '<S26>/Discrete-Time Integrator' incorporates: * Gain: '<S26>/Gain' * Inport: '<Root>/FromPlant' * Lookup_n-D: '<S26>/n-D Lookup Table' * Product: '<S26>/Divide' * Selector: '<S1>/Selector4' * Selector: '<S1>/Selector5' */ bms_DW.DiscreteTimeIntegrator_DSTAT_bc += -0.00027777778450399637 * bms_U.FromPlant.BMSBatteryPackData.SegmentCurrentVector[28] / look1_binlxpw (bms_U.FromPlant.BMSBatteryPackData.SegmentTempVector[28], bms_ConstP.pooled8, bms_ConstP.pooled7, 2U) * 0.01; if (bms_DW.DiscreteTimeIntegrator_DSTAT_bc >= 1.0) { bms_DW.DiscreteTimeIntegrator_DSTAT_bc = 1.0; } else if (bms_DW.DiscreteTimeIntegrator_DSTAT_bc <= 0.0) { bms_DW.DiscreteTimeIntegrator_DSTAT_bc = 0.0; } /* End of Update for DiscreteIntegrator: '<S26>/Discrete-Time Integrator' */ /* Update for DiscreteIntegrator: '<S37>/Discrete-Time Integrator' incorporates: * Gain: '<S37>/Gain' * Inport: '<Root>/FromPlant' * Lookup_n-D: '<S37>/n-D Lookup Table' * Product: '<S37>/Divide' * Selector: '<S1>/Selector7' * Selector: '<S1>/Selector8' */ bms_DW.DiscreteTimeIntegrator_DSTAT_ps += -0.00027777778450399637 * bms_U.FromPlant.BMSBatteryPackData.SegmentCurrentVector[2] / look1_binlxpw (bms_U.FromPlant.BMSBatteryPackData.SegmentTempVector[2], bms_ConstP.pooled8, bms_ConstP.pooled7, 2U) * 0.01; if (bms_DW.DiscreteTimeIntegrator_DSTAT_ps >= 1.0) { bms_DW.DiscreteTimeIntegrator_DSTAT_ps = 1.0; } else if (bms_DW.DiscreteTimeIntegrator_DSTAT_ps <= 0.0) { bms_DW.DiscreteTimeIntegrator_DSTAT_ps = 0.0; } /* End of Update for DiscreteIntegrator: '<S37>/Discrete-Time Integrator' */ /* Update for DiscreteIntegrator: '<S28>/Discrete-Time Integrator' incorporates: * Gain: '<S28>/Gain' * Inport: '<Root>/FromPlant' * Lookup_n-D: '<S28>/n-D Lookup Table' * Product: '<S28>/Divide' * Selector: '<S1>/Selector7' * Selector: '<S1>/Selector8' */ bms_DW.DiscreteTimeIntegrator_DSTAT_ed += -0.00027777778450399637 * bms_U.FromPlant.BMSBatteryPackData.SegmentCurrentVector[5] / look1_binlxpw (bms_U.FromPlant.BMSBatteryPackData.SegmentTempVector[5], bms_ConstP.pooled8, bms_ConstP.pooled7, 2U) * 0.01; if (bms_DW.DiscreteTimeIntegrator_DSTAT_ed >= 1.0) { bms_DW.DiscreteTimeIntegrator_DSTAT_ed = 1.0; } else if (bms_DW.DiscreteTimeIntegrator_DSTAT_ed <= 0.0) { bms_DW.DiscreteTimeIntegrator_DSTAT_ed = 0.0; } /* End of Update for DiscreteIntegrator: '<S28>/Discrete-Time Integrator' */ /* Update for DiscreteIntegrator: '<S29>/Discrete-Time Integrator' incorporates: * Gain: '<S29>/Gain' * Inport: '<Root>/FromPlant' * Lookup_n-D: '<S29>/n-D Lookup Table' * Product: '<S29>/Divide' * Selector: '<S1>/Selector7' * Selector: '<S1>/Selector8' */ bms_DW.DiscreteTimeIntegrator_DSTAT_mg += -0.00027777778450399637 * bms_U.FromPlant.BMSBatteryPackData.SegmentCurrentVector[8] / look1_binlxpw (bms_U.FromPlant.BMSBatteryPackData.SegmentTempVector[8], bms_ConstP.pooled8, bms_ConstP.pooled7, 2U) * 0.01; if (bms_DW.DiscreteTimeIntegrator_DSTAT_mg >= 1.0) { bms_DW.DiscreteTimeIntegrator_DSTAT_mg = 1.0; } else if (bms_DW.DiscreteTimeIntegrator_DSTAT_mg <= 0.0) { bms_DW.DiscreteTimeIntegrator_DSTAT_mg = 0.0; } /* End of Update for DiscreteIntegrator: '<S29>/Discrete-Time Integrator' */ /* Update for DiscreteIntegrator: '<S30>/Discrete-Time Integrator' incorporates: * Gain: '<S30>/Gain' * Inport: '<Root>/FromPlant' * Lookup_n-D: '<S30>/n-D Lookup Table' * Product: '<S30>/Divide' * Selector: '<S1>/Selector7' * Selector: '<S1>/Selector8' */ bms_DW.DiscreteTimeIntegrator_DSTAT_fy += -0.00027777778450399637 * bms_U.FromPlant.BMSBatteryPackData.SegmentCurrentVector[11] / look1_binlxpw (bms_U.FromPlant.BMSBatteryPackData.SegmentTempVector[11], bms_ConstP.pooled8, bms_ConstP.pooled7, 2U) * 0.01; if (bms_DW.DiscreteTimeIntegrator_DSTAT_fy >= 1.0) { bms_DW.DiscreteTimeIntegrator_DSTAT_fy = 1.0; } else if (bms_DW.DiscreteTimeIntegrator_DSTAT_fy <= 0.0) { bms_DW.DiscreteTimeIntegrator_DSTAT_fy = 0.0; } /* End of Update for DiscreteIntegrator: '<S30>/Discrete-Time Integrator' */ /* Update for DiscreteIntegrator: '<S31>/Discrete-Time Integrator' incorporates: * Gain: '<S31>/Gain' * Inport: '<Root>/FromPlant' * Lookup_n-D: '<S31>/n-D Lookup Table' * Product: '<S31>/Divide' * Selector: '<S1>/Selector7' * Selector: '<S1>/Selector8' */ bms_DW.DiscreteTimeIntegrator_DSTAT_gd += -0.00027777778450399637 * bms_U.FromPlant.BMSBatteryPackData.SegmentCurrentVector[14] / look1_binlxpw (bms_U.FromPlant.BMSBatteryPackData.SegmentTempVector[14], bms_ConstP.pooled8, bms_ConstP.pooled7, 2U) * 0.01; if (bms_DW.DiscreteTimeIntegrator_DSTAT_gd >= 1.0) { bms_DW.DiscreteTimeIntegrator_DSTAT_gd = 1.0; } else if (bms_DW.DiscreteTimeIntegrator_DSTAT_gd <= 0.0) { bms_DW.DiscreteTimeIntegrator_DSTAT_gd = 0.0; } /* End of Update for DiscreteIntegrator: '<S31>/Discrete-Time Integrator' */ /* Update for DiscreteIntegrator: '<S32>/Discrete-Time Integrator' incorporates: * Gain: '<S32>/Gain' * Inport: '<Root>/FromPlant' * Lookup_n-D: '<S32>/n-D Lookup Table' * Product: '<S32>/Divide' * Selector: '<S1>/Selector7' * Selector: '<S1>/Selector8' */ bms_DW.DiscreteTimeIntegrator_DSTATE_i += -0.00027777778450399637 * bms_U.FromPlant.BMSBatteryPackData.SegmentCurrentVector[17] / look1_binlxpw (bms_U.FromPlant.BMSBatteryPackData.SegmentTempVector[17], bms_ConstP.pooled8, bms_ConstP.pooled7, 2U) * 0.01; if (bms_DW.DiscreteTimeIntegrator_DSTATE_i >= 1.0) { bms_DW.DiscreteTimeIntegrator_DSTATE_i = 1.0; } else if (bms_DW.DiscreteTimeIntegrator_DSTATE_i <= 0.0) { bms_DW.DiscreteTimeIntegrator_DSTATE_i = 0.0; } /* End of Update for DiscreteIntegrator: '<S32>/Discrete-Time Integrator' */ /* Update for DiscreteIntegrator: '<S33>/Discrete-Time Integrator' incorporates: * Gain: '<S33>/Gain' * Inport: '<Root>/FromPlant' * Lookup_n-D: '<S33>/n-D Lookup Table' * Product: '<S33>/Divide' * Selector: '<S1>/Selector7' * Selector: '<S1>/Selector8' */ bms_DW.DiscreteTimeIntegrator_DSTAT_ce += -0.00027777778450399637 * bms_U.FromPlant.BMSBatteryPackData.SegmentCurrentVector[20] / look1_binlxpw (bms_U.FromPlant.BMSBatteryPackData.SegmentTempVector[20], bms_ConstP.pooled8, bms_ConstP.pooled7, 2U) * 0.01; if (bms_DW.DiscreteTimeIntegrator_DSTAT_ce >= 1.0) { bms_DW.DiscreteTimeIntegrator_DSTAT_ce = 1.0; } else if (bms_DW.DiscreteTimeIntegrator_DSTAT_ce <= 0.0) { bms_DW.DiscreteTimeIntegrator_DSTAT_ce = 0.0; } /* End of Update for DiscreteIntegrator: '<S33>/Discrete-Time Integrator' */ /* Update for DiscreteIntegrator: '<S34>/Discrete-Time Integrator' incorporates: * Gain: '<S34>/Gain' * Inport: '<Root>/FromPlant' * Lookup_n-D: '<S34>/n-D Lookup Table' * Product: '<S34>/Divide' * Selector: '<S1>/Selector7' * Selector: '<S1>/Selector8' */ bms_DW.DiscreteTimeIntegrator_DSTAT_p0 += -0.00027777778450399637 * bms_U.FromPlant.BMSBatteryPackData.SegmentCurrentVector[23] / look1_binlxpw (bms_U.FromPlant.BMSBatteryPackData.SegmentTempVector[23], bms_ConstP.pooled8, bms_ConstP.pooled7, 2U) * 0.01; if (bms_DW.DiscreteTimeIntegrator_DSTAT_p0 >= 1.0) { bms_DW.DiscreteTimeIntegrator_DSTAT_p0 = 1.0; } else if (bms_DW.DiscreteTimeIntegrator_DSTAT_p0 <= 0.0) { bms_DW.DiscreteTimeIntegrator_DSTAT_p0 = 0.0; } /* End of Update for DiscreteIntegrator: '<S34>/Discrete-Time Integrator' */ /* Update for DiscreteIntegrator: '<S35>/Discrete-Time Integrator' incorporates: * Gain: '<S35>/Gain' * Inport: '<Root>/FromPlant' * Lookup_n-D: '<S35>/n-D Lookup Table' * Product: '<S35>/Divide' * Selector: '<S1>/Selector7' * Selector: '<S1>/Selector8' */ bms_DW.DiscreteTimeIntegrator_DSTAT_fb += -0.00027777778450399637 * bms_U.FromPlant.BMSBatteryPackData.SegmentCurrentVector[26] / look1_binlxpw (bms_U.FromPlant.BMSBatteryPackData.SegmentTempVector[26], bms_ConstP.pooled8, bms_ConstP.pooled7, 2U) * 0.01; if (bms_DW.DiscreteTimeIntegrator_DSTAT_fb >= 1.0) { bms_DW.DiscreteTimeIntegrator_DSTAT_fb = 1.0; } else if (bms_DW.DiscreteTimeIntegrator_DSTAT_fb <= 0.0) { bms_DW.DiscreteTimeIntegrator_DSTAT_fb = 0.0; } /* End of Update for DiscreteIntegrator: '<S35>/Discrete-Time Integrator' */ /* Update for DiscreteIntegrator: '<S36>/Discrete-Time Integrator' incorporates: * Gain: '<S36>/Gain' * Inport: '<Root>/FromPlant' * Lookup_n-D: '<S36>/n-D Lookup Table' * Product: '<S36>/Divide' * Selector: '<S1>/Selector7' * Selector: '<S1>/Selector8' */ bms_DW.DiscreteTimeIntegrator_DSTAT_d3 += -0.00027777778450399637 * bms_U.FromPlant.BMSBatteryPackData.SegmentCurrentVector[29] / look1_binlxpw (bms_U.FromPlant.BMSBatteryPackData.SegmentTempVector[29], bms_ConstP.pooled8, bms_ConstP.pooled7, 2U) * 0.01; if (bms_DW.DiscreteTimeIntegrator_DSTAT_d3 >= 1.0) { bms_DW.DiscreteTimeIntegrator_DSTAT_d3 = 1.0; } else if (bms_DW.DiscreteTimeIntegrator_DSTAT_d3 <= 0.0) { bms_DW.DiscreteTimeIntegrator_DSTAT_d3 = 0.0; } /* End of Update for DiscreteIntegrator: '<S36>/Discrete-Time Integrator' */ } /* Model initialize function */ void bms_initialize(void) { /* InitializeConditions for DiscreteIntegrator: '<S17>/Discrete-Time Integrator' */ bms_DW.DiscreteTimeIntegrator_DSTATE = 1.0; /* InitializeConditions for DiscreteIntegrator: '<S8>/Discrete-Time Integrator' */ bms_DW.DiscreteTimeIntegrator_DSTATE_a = 1.0; /* InitializeConditions for DiscreteIntegrator: '<S9>/Discrete-Time Integrator' */ bms_DW.DiscreteTimeIntegrator_DSTAT_au = 1.0; /* InitializeConditions for DiscreteIntegrator: '<S10>/Discrete-Time Integrator' */ bms_DW.DiscreteTimeIntegrator_DSTATE_m = 1.0; /* InitializeConditions for DiscreteIntegrator: '<S11>/Discrete-Time Integrator' */ bms_DW.DiscreteTimeIntegrator_DSTATE_b = 1.0; /* InitializeConditions for DiscreteIntegrator: '<S12>/Discrete-Time Integrator' */ bms_DW.DiscreteTimeIntegrator_DSTATE_p = 1.0; /* InitializeConditions for DiscreteIntegrator: '<S13>/Discrete-Time Integrator' */ bms_DW.DiscreteTimeIntegrator_DSTATE_c = 1.0; /* InitializeConditions for DiscreteIntegrator: '<S14>/Discrete-Time Integrator' */ bms_DW.DiscreteTimeIntegrator_DSTAT_mh = 1.0; /* InitializeConditions for DiscreteIntegrator: '<S15>/Discrete-Time Integrator' */ bms_DW.DiscreteTimeIntegrator_DSTATE_g = 1.0; /* InitializeConditions for DiscreteIntegrator: '<S16>/Discrete-Time Integrator' */ bms_DW.DiscreteTimeIntegrator_DSTAT_g0 = 1.0; /* InitializeConditions for DiscreteIntegrator: '<S27>/Discrete-Time Integrator' */ bms_DW.DiscreteTimeIntegrator_DSTATE_d = 1.0; /* InitializeConditions for DiscreteIntegrator: '<S18>/Discrete-Time Integrator' */ bms_DW.DiscreteTimeIntegrator_DSTAT_b0 = 1.0; /* InitializeConditions for DiscreteIntegrator: '<S19>/Discrete-Time Integrator' */ bms_DW.DiscreteTimeIntegrator_DSTAT_dc = 1.0; /* InitializeConditions for DiscreteIntegrator: '<S20>/Discrete-Time Integrator' */ bms_DW.DiscreteTimeIntegrator_DSTATE_o = 1.0; /* InitializeConditions for DiscreteIntegrator: '<S21>/Discrete-Time Integrator' */ bms_DW.DiscreteTimeIntegrator_DSTAT_aw = 1.0; /* InitializeConditions for DiscreteIntegrator: '<S22>/Discrete-Time Integrator' */ bms_DW.DiscreteTimeIntegrator_DSTATE_n = 1.0; /* InitializeConditions for DiscreteIntegrator: '<S23>/Discrete-Time Integrator' */ bms_DW.DiscreteTimeIntegrator_DSTATE_e = 1.0; /* InitializeConditions for DiscreteIntegrator: '<S24>/Discrete-Time Integrator' */ bms_DW.DiscreteTimeIntegrator_DSTATE_f = 1.0; /* InitializeConditions for DiscreteIntegrator: '<S25>/Discrete-Time Integrator' */ bms_DW.DiscreteTimeIntegrator_DSTAT_aj = 1.0; /* InitializeConditions for DiscreteIntegrator: '<S26>/Discrete-Time Integrator' */ bms_DW.DiscreteTimeIntegrator_DSTAT_bc = 1.0; /* InitializeConditions for DiscreteIntegrator: '<S37>/Discrete-Time Integrator' */ bms_DW.DiscreteTimeIntegrator_DSTAT_ps = 1.0; /* InitializeConditions for DiscreteIntegrator: '<S28>/Discrete-Time Integrator' */ bms_DW.DiscreteTimeIntegrator_DSTAT_ed = 1.0; /* InitializeConditions for DiscreteIntegrator: '<S29>/Discrete-Time Integrator' */ bms_DW.DiscreteTimeIntegrator_DSTAT_mg = 1.0; /* InitializeConditions for DiscreteIntegrator: '<S30>/Discrete-Time Integrator' */ bms_DW.DiscreteTimeIntegrator_DSTAT_fy = 1.0; /* InitializeConditions for DiscreteIntegrator: '<S31>/Discrete-Time Integrator' */ bms_DW.DiscreteTimeIntegrator_DSTAT_gd = 1.0; /* InitializeConditions for DiscreteIntegrator: '<S32>/Discrete-Time Integrator' */ bms_DW.DiscreteTimeIntegrator_DSTATE_i = 1.0; /* InitializeConditions for DiscreteIntegrator: '<S33>/Discrete-Time Integrator' */ bms_DW.DiscreteTimeIntegrator_DSTAT_ce = 1.0; /* InitializeConditions for DiscreteIntegrator: '<S34>/Discrete-Time Integrator' */ bms_DW.DiscreteTimeIntegrator_DSTAT_p0 = 1.0; /* InitializeConditions for DiscreteIntegrator: '<S35>/Discrete-Time Integrator' */ bms_DW.DiscreteTimeIntegrator_DSTAT_fb = 1.0; /* InitializeConditions for DiscreteIntegrator: '<S36>/Discrete-Time Integrator' */ bms_DW.DiscreteTimeIntegrator_DSTAT_d3 = 1.0; /* Chart: '<S3>/Chart' */ bms_DW.is_c1_bms = bms_IN_init; /* SystemInitialize for Chart: '<S4>/Chart1' */ bms_Chart1_Init(&bms_B.MatrixConcatenate[0], &bms_B.VectorConcatenate_k[0], &bms_B.VectorConcatenate1_a[0]); /* SystemInitialize for Chart: '<S4>/Chart2' */ bms_Chart1_Init(&bms_B.MatrixConcatenate[10], &bms_B.VectorConcatenate_k[1], &bms_B.VectorConcatenate1_a[1]); /* SystemInitialize for Chart: '<S4>/Chart3' */ bms_Chart1_Init(&bms_B.MatrixConcatenate[20], &bms_B.VectorConcatenate_k[2], &bms_B.VectorConcatenate1_a[2]); } /* Model terminate function */ void bms_terminate(void) { /* (no terminate code required) */ } /* * File trailer for generated code. * * [EOF] */ ======================= File: workspace/bms_f4_ert_rtw/bms_f4_data.c ======================= /* * Academic License - for use in teaching, academic research, and meeting * course requirements at degree granting institutions only. Not for * government, commercial, or other organizational use. * * File: bms_f4_data.c * * Code generated for Simulink model 'bms_f4'. * * Model version : 1.33 * Simulink Coder version : 9.5 (R2021a) 14-Nov-2020 * C/C++ source code generated on : Wed Jun 2 11:40:20 2021 * * Target selection: ert.tlc * Embedded hardware selection: ARM Compatible->ARM Cortex * Code generation objectives: Unspecified * Validation result: Not run */ #include "bms_f4.h" #include "bms_f4_private.h" /* Block parameters (default storage) */ P_bms_f4_T bms_f4_P = { /* Variable: CellCurrentLimitThreshold_Fault * Referenced by: '<S39>/Constant' */ 50.0, /* Variable: CellCurrentLimitThreshold_Warning * Referenced by: '<S38>/Constant' */ 20.0, /* Variable: CellTemperatureLimitThreshold_Fault * Referenced by: '<S41>/Constant' */ 338.15, /* Variable: CellTemperatureLimitThreshold_Warning * Referenced by: '<S40>/Constant' */ 323.15, /* Variable: CellVoltageLimitHigh_Fault * Referenced by: '<S43>/Constant' */ 4.25, /* Variable: CellVoltageLimitHigh_Warning * Referenced by: '<S42>/Constant' */ 4.21, /* Variable: CellVoltageLimitLow_Fault * Referenced by: '<S45>/Constant' */ 2.65, /* Variable: CellVoltageLimitLow_Warning * Referenced by: '<S44>/Constant' */ 2.7, /* Variable: DeltaVTargetMin * Referenced by: * '<S4>/Chart1' * '<S4>/Chart2' * '<S4>/Chart3' */ 0.001, /* Variable: DrivetrainEnDelay * Referenced by: '<S3>/Chart' */ 0.1, /* Variable: VbattMin * Referenced by: '<S3>/Chart' */ 1.0, /* Variable: VbattThersholdChrg * Referenced by: '<S3>/Chart' */ 0.8, /* Variable: VbattThresholdDis * Referenced by: '<S3>/Chart' */ 0.2, /* Variable: balancingRelaxationTime * Referenced by: * '<S4>/Chart1' * '<S4>/Chart2' * '<S4>/Chart3' */ 1000.0, /* Variable: balancingTime * Referenced by: * '<S4>/Chart1' * '<S4>/Chart2' * '<S4>/Chart3' */ 2000.0, /* Computed Parameter: DiscreteTimeIntegrator_gainval * Referenced by: '<S17>/Discrete-Time Integrator' */ 0.01, /* Computed Parameter: DiscreteTimeIntegrator_IC * Referenced by: '<S17>/Discrete-Time Integrator' */ 1.0, /* Expression: 1 * Referenced by: '<S17>/Discrete-Time Integrator' */ 1.0, /* Expression: 0 * Referenced by: '<S17>/Discrete-Time Integrator' */ 0.0, /* Computed Parameter: DiscreteTimeIntegrator_gainva_d * Referenced by: '<S8>/Discrete-Time Integrator' */ 0.01, /* Computed Parameter: DiscreteTimeIntegrator_IC_h * Referenced by: '<S8>/Discrete-Time Integrator' */ 1.0, /* Expression: 1 * Referenced by: '<S8>/Discrete-Time Integrator' */ 1.0, /* Expression: 0 * Referenced by: '<S8>/Discrete-Time Integrator' */ 0.0, /* Computed Parameter: DiscreteTimeIntegrator_gainva_o * Referenced by: '<S9>/Discrete-Time Integrator' */ 0.01, /* Computed Parameter: DiscreteTimeIntegrator_IC_d * Referenced by: '<S9>/Discrete-Time Integrator' */ 1.0, /* Expression: 1 * Referenced by: '<S9>/Discrete-Time Integrator' */ 1.0, /* Expression: 0 * Referenced by: '<S9>/Discrete-Time Integrator' */ 0.0, /* Computed Parameter: DiscreteTimeIntegrator_gainva_m * Referenced by: '<S10>/Discrete-Time Integrator' */ 0.01, /* Computed Parameter: DiscreteTimeIntegrator_IC_m * Referenced by: '<S10>/Discrete-Time Integrator' */ 1.0, /* Expression: 1 * Referenced by: '<S10>/Discrete-Time Integrator' */ 1.0, /* Expression: 0 * Referenced by: '<S10>/Discrete-Time Integrator' */ 0.0, /* Computed Parameter: DiscreteTimeIntegrator_gainv_do * Referenced by: '<S11>/Discrete-Time Integrator' */ 0.01, /* Computed Parameter: DiscreteTimeIntegrator_IC_l * Referenced by: '<S11>/Discrete-Time Integrator' */ 1.0, /* Expression: 1 * Referenced by: '<S11>/Discrete-Time Integrator' */ 1.0, /* Expression: 0 * Referenced by: '<S11>/Discrete-Time Integrator' */ 0.0, /* Computed Parameter: DiscreteTimeIntegrator_gainv_mu * Referenced by: '<S12>/Discrete-Time Integrator' */ 0.01, /* Computed Parameter: DiscreteTimeIntegrator_IC_p * Referenced by: '<S12>/Discrete-Time Integrator' */ 1.0, /* Expression: 1 * Referenced by: '<S12>/Discrete-Time Integrator' */ 1.0, /* Expression: 0 * Referenced by: '<S12>/Discrete-Time Integrator' */ 0.0, /* Computed Parameter: DiscreteTimeIntegrator_gainva_i * Referenced by: '<S13>/Discrete-Time Integrator' */ 0.01, /* Computed Parameter: DiscreteTimeIntegrator_IC_o * Referenced by: '<S13>/Discrete-Time Integrator' */ 1.0, /* Expression: 1 * Referenced by: '<S13>/Discrete-Time Integrator' */ 1.0, /* Expression: 0 * Referenced by: '<S13>/Discrete-Time Integrator' */ 0.0, /* Computed Parameter: DiscreteTimeIntegrator_gainva_l * Referenced by: '<S14>/Discrete-Time Integrator' */ 0.01, /* Computed Parameter: DiscreteTimeIntegrator_IC_m3 * Referenced by: '<S14>/Discrete-Time Integrator' */ 1.0, /* Expression: 1 * Referenced by: '<S14>/Discrete-Time Integrator' */ 1.0, /* Expression: 0 * Referenced by: '<S14>/Discrete-Time Integrator' */ 0.0, /* Computed Parameter: DiscreteTimeIntegrator_gainv_oo * Referenced by: '<S15>/Discrete-Time Integrator' */ 0.01, /* Computed Parameter: DiscreteTimeIntegrator_IC_e * Referenced by: '<S15>/Discrete-Time Integrator' */ 1.0, /* Expression: 1 * Referenced by: '<S15>/Discrete-Time Integrator' */ 1.0, /* Expression: 0 * Referenced by: '<S15>/Discrete-Time Integrator' */ 0.0, /* Computed Parameter: DiscreteTimeIntegrator_gainva_p * Referenced by: '<S16>/Discrete-Time Integrator' */ 0.01, /* Computed Parameter: DiscreteTimeIntegrator_IC_ou * Referenced by: '<S16>/Discrete-Time Integrator' */ 1.0, /* Expression: 1 * Referenced by: '<S16>/Discrete-Time Integrator' */ 1.0, /* Expression: 0 * Referenced by: '<S16>/Discrete-Time Integrator' */ 0.0, /* Computed Parameter: DiscreteTimeIntegrator_gainva_k * Referenced by: '<S27>/Discrete-Time Integrator' */ 0.01, /* Computed Parameter: DiscreteTimeIntegrator_IC_b * Referenced by: '<S27>/Discrete-Time Integrator' */ 1.0, /* Expression: 1 * Referenced by: '<S27>/Discrete-Time Integrator' */ 1.0, /* Expression: 0 * Referenced by: '<S27>/Discrete-Time Integrator' */ 0.0, /* Computed Parameter: DiscreteTimeIntegrator_gainv_ks * Referenced by: '<S18>/Discrete-Time Integrator' */ 0.01, /* Computed Parameter: DiscreteTimeIntegrator_IC_dx * Referenced by: '<S18>/Discrete-Time Integrator' */ 1.0, /* Expression: 1 * Referenced by: '<S18>/Discrete-Time Integrator' */ 1.0, /* Expression: 0 * Referenced by: '<S18>/Discrete-Time Integrator' */ 0.0, /* Computed Parameter: DiscreteTimeIntegrator_gainva_c * Referenced by: '<S19>/Discrete-Time Integrator' */ 0.01, /* Computed Parameter: DiscreteTimeIntegrator_IC_lq * Referenced by: '<S19>/Discrete-Time Integrator' */ 1.0, /* Expression: 1 * Referenced by: '<S19>/Discrete-Time Integrator' */ 1.0, /* Expression: 0 * Referenced by: '<S19>/Discrete-Time Integrator' */ 0.0, /* Computed Parameter: DiscreteTimeIntegrator_gainva_a * Referenced by: '<S20>/Discrete-Time Integrator' */ 0.01, /* Computed Parameter: DiscreteTimeIntegrator_IC_oq * Referenced by: '<S20>/Discrete-Time Integrator' */ 1.0, /* Expression: 1 * Referenced by: '<S20>/Discrete-Time Integrator' */ 1.0, /* Expression: 0 * Referenced by: '<S20>/Discrete-Time Integrator' */ 0.0, /* Computed Parameter: DiscreteTimeIntegrator_gainva_n * Referenced by: '<S21>/Discrete-Time Integrator' */ 0.01, /* Computed Parameter: DiscreteTimeIntegrator_IC_dk * Referenced by: '<S21>/Discrete-Time Integrator' */ 1.0, /* Expression: 1 * Referenced by: '<S21>/Discrete-Time Integrator' */ 1.0, /* Expression: 0 * Referenced by: '<S21>/Discrete-Time Integrator' */ 0.0, /* Computed Parameter: DiscreteTimeIntegrator_gainv_co * Referenced by: '<S22>/Discrete-Time Integrator' */ 0.01, /* Computed Parameter: DiscreteTimeIntegrator_IC_on * Referenced by: '<S22>/Discrete-Time Integrator' */ 1.0, /* Expression: 1 * Referenced by: '<S22>/Discrete-Time Integrator' */ 1.0, /* Expression: 0 * Referenced by: '<S22>/Discrete-Time Integrator' */ 0.0, /* Computed Parameter: DiscreteTimeIntegrator_gainva_f * Referenced by: '<S23>/Discrete-Time Integrator' */ 0.01, /* Computed Parameter: DiscreteTimeIntegrator_IC_c * Referenced by: '<S23>/Discrete-Time Integrator' */ 1.0, /* Expression: 1 * Referenced by: '<S23>/Discrete-Time Integrator' */ 1.0, /* Expression: 0 * Referenced by: '<S23>/Discrete-Time Integrator' */ 0.0, /* Computed Parameter: DiscreteTimeIntegrator_gainv_cu * Referenced by: '<S24>/Discrete-Time Integrator' */ 0.01, /* Computed Parameter: DiscreteTimeIntegrator_IC_lt * Referenced by: '<S24>/Discrete-Time Integrator' */ 1.0, /* Expression: 1 * Referenced by: '<S24>/Discrete-Time Integrator' */ 1.0, /* Expression: 0 * Referenced by: '<S24>/Discrete-Time Integrator' */ 0.0, /* Computed Parameter: DiscreteTimeIntegrator_gainva_e * Referenced by: '<S25>/Discrete-Time Integrator' */ 0.01, /* Computed Parameter: DiscreteTimeIntegrator_IC_k * Referenced by: '<S25>/Discrete-Time Integrator' */ 1.0, /* Expression: 1 * Referenced by: '<S25>/Discrete-Time Integrator' */ 1.0, /* Expression: 0 * Referenced by: '<S25>/Discrete-Time Integrator' */ 0.0, /* Computed Parameter: DiscreteTimeIntegrator_gainv_pk * Referenced by: '<S26>/Discrete-Time Integrator' */ 0.01, /* Computed Parameter: DiscreteTimeIntegrator_IC_dc * Referenced by: '<S26>/Discrete-Time Integrator' */ 1.0, /* Expression: 1 * Referenced by: '<S26>/Discrete-Time Integrator' */ 1.0, /* Expression: 0 * Referenced by: '<S26>/Discrete-Time Integrator' */ 0.0, /* Computed Parameter: DiscreteTimeIntegrator_gainv_nb * Referenced by: '<S37>/Discrete-Time Integrator' */ 0.01, /* Computed Parameter: DiscreteTimeIntegrator_IC_j * Referenced by: '<S37>/Discrete-Time Integrator' */ 1.0, /* Expression: 1 * Referenced by: '<S37>/Discrete-Time Integrator' */ 1.0, /* Expression: 0 * Referenced by: '<S37>/Discrete-Time Integrator' */ 0.0, /* Computed Parameter: DiscreteTimeIntegrator_gainv_a5 * Referenced by: '<S28>/Discrete-Time Integrator' */ 0.01, /* Computed Parameter: DiscreteTimeIntegrator_IC_hw * Referenced by: '<S28>/Discrete-Time Integrator' */ 1.0, /* Expression: 1 * Referenced by: '<S28>/Discrete-Time Integrator' */ 1.0, /* Expression: 0 * Referenced by: '<S28>/Discrete-Time Integrator' */ 0.0, /* Computed Parameter: DiscreteTimeIntegrator_gainv_md * Referenced by: '<S29>/Discrete-Time Integrator' */ 0.01, /* Computed Parameter: DiscreteTimeIntegrator_IC_dv * Referenced by: '<S29>/Discrete-Time Integrator' */ 1.0, /* Expression: 1 * Referenced by: '<S29>/Discrete-Time Integrator' */ 1.0, /* Expression: 0 * Referenced by: '<S29>/Discrete-Time Integrator' */ 0.0, /* Computed Parameter: DiscreteTimeIntegrator_gainv_lm * Referenced by: '<S30>/Discrete-Time Integrator' */ 0.01, /* Computed Parameter: DiscreteTimeIntegrator_IC_l1 * Referenced by: '<S30>/Discrete-Time Integrator' */ 1.0, /* Expression: 1 * Referenced by: '<S30>/Discrete-Time Integrator' */ 1.0, /* Expression: 0 * Referenced by: '<S30>/Discrete-Time Integrator' */ 0.0, /* Computed Parameter: DiscreteTimeIntegrator_gainv_ae * Referenced by: '<S31>/Discrete-Time Integrator' */ 0.01, /* Computed Parameter: DiscreteTimeIntegrator_IC_i * Referenced by: '<S31>/Discrete-Time Integrator' */ 1.0, /* Expression: 1 * Referenced by: '<S31>/Discrete-Time Integrator' */ 1.0, /* Expression: 0 * Referenced by: '<S31>/Discrete-Time Integrator' */ 0.0, /* Computed Parameter: DiscreteTimeIntegrator_gainv_lx * Referenced by: '<S32>/Discrete-Time Integrator' */ 0.01, /* Computed Parameter: DiscreteTimeIntegrator_IC_f * Referenced by: '<S32>/Discrete-Time Integrator' */ 1.0, /* Expression: 1 * Referenced by: '<S32>/Discrete-Time Integrator' */ 1.0, /* Expression: 0 * Referenced by: '<S32>/Discrete-Time Integrator' */ 0.0, /* Computed Parameter: DiscreteTimeIntegrator_gain_pkl * Referenced by: '<S33>/Discrete-Time Integrator' */ 0.01, /* Computed Parameter: DiscreteTimeIntegrator_IC_ln * Referenced by: '<S33>/Discrete-Time Integrator' */ 1.0, /* Expression: 1 * Referenced by: '<S33>/Discrete-Time Integrator' */ 1.0, /* Expression: 0 * Referenced by: '<S33>/Discrete-Time Integrator' */ 0.0, /* Computed Parameter: DiscreteTimeIntegrator_gain_lxl * Referenced by: '<S34>/Discrete-Time Integrator' */ 0.01, /* Computed Parameter: DiscreteTimeIntegrator_IC_mf * Referenced by: '<S34>/Discrete-Time Integrator' */ 1.0, /* Expression: 1 * Referenced by: '<S34>/Discrete-Time Integrator' */ 1.0, /* Expression: 0 * Referenced by: '<S34>/Discrete-Time Integrator' */ 0.0, /* Computed Parameter: DiscreteTimeIntegrator_gainv_ea * Referenced by: '<S35>/Discrete-Time Integrator' */ 0.01, /* Computed Parameter: DiscreteTimeIntegrator_IC_mz * Referenced by: '<S35>/Discrete-Time Integrator' */ 1.0, /* Expression: 1 * Referenced by: '<S35>/Discrete-Time Integrator' */ 1.0, /* Expression: 0 * Referenced by: '<S35>/Discrete-Time Integrator' */ 0.0, /* Computed Parameter: DiscreteTimeIntegrator_gainv_ol * Referenced by: '<S36>/Discrete-Time Integrator' */ 0.01, /* Computed Parameter: DiscreteTimeIntegrator_IC_m1 * Referenced by: '<S36>/Discrete-Time Integrator' */ 1.0, /* Expression: 1 * Referenced by: '<S36>/Discrete-Time Integrator' */ 1.0, /* Expression: 0 * Referenced by: '<S36>/Discrete-Time Integrator' */ 0.0, /* Computed Parameter: nDLookupTable_tableData * Referenced by: '<S8>/n-D Lookup Table' */ { 3.0299999713897705, 3.0, 2.9200000762939453 }, /* Computed Parameter: nDLookupTable_bp01Data * Referenced by: '<S8>/n-D Lookup Table' */ { 278.14999389648438, 293.14999389648438, 323.14999389648438 }, /* Computed Parameter: Gain_Gain * Referenced by: '<S8>/Gain' */ -0.00027777778450399637, /* Computed Parameter: nDLookupTable_tableData_f * Referenced by: '<S9>/n-D Lookup Table' */ { 3.0299999713897705, 3.0, 2.9200000762939453 }, /* Computed Parameter: nDLookupTable_bp01Data_o * Referenced by: '<S9>/n-D Lookup Table' */ { 278.14999389648438, 293.14999389648438, 323.14999389648438 }, /* Computed Parameter: Gain_Gain_f * Referenced by: '<S9>/Gain' */ -0.00027777778450399637, /* Computed Parameter: nDLookupTable_tableData_e * Referenced by: '<S10>/n-D Lookup Table' */ { 3.0299999713897705, 3.0, 2.9200000762939453 }, /* Computed Parameter: nDLookupTable_bp01Data_m * Referenced by: '<S10>/n-D Lookup Table' */ { 278.14999389648438, 293.14999389648438, 323.14999389648438 }, /* Computed Parameter: Gain_Gain_m * Referenced by: '<S10>/Gain' */ -0.00027777778450399637, /* Computed Parameter: nDLookupTable_tableData_a * Referenced by: '<S11>/n-D Lookup Table' */ { 3.0299999713897705, 3.0, 2.9200000762939453 }, /* Computed Parameter: nDLookupTable_bp01Data_c * Referenced by: '<S11>/n-D Lookup Table' */ { 278.14999389648438, 293.14999389648438, 323.14999389648438 }, /* Computed Parameter: Gain_Gain_fa * Referenced by: '<S11>/Gain' */ -0.00027777778450399637, /* Computed Parameter: nDLookupTable_tableData_h * Referenced by: '<S12>/n-D Lookup Table' */ { 3.0299999713897705, 3.0, 2.9200000762939453 }, /* Computed Parameter: nDLookupTable_bp01Data_h * Referenced by: '<S12>/n-D Lookup Table' */ { 278.14999389648438, 293.14999389648438, 323.14999389648438 }, /* Computed Parameter: Gain_Gain_l * Referenced by: '<S12>/Gain' */ -0.00027777778450399637, /* Computed Parameter: nDLookupTable_tableData_m * Referenced by: '<S13>/n-D Lookup Table' */ { 3.0299999713897705, 3.0, 2.9200000762939453 }, /* Computed Parameter: nDLookupTable_bp01Data_g * Referenced by: '<S13>/n-D Lookup Table' */ { 278.14999389648438, 293.14999389648438, 323.14999389648438 }, /* Computed Parameter: Gain_Gain_c * Referenced by: '<S13>/Gain' */ -0.00027777778450399637, /* Computed Parameter: nDLookupTable_tableData_j * Referenced by: '<S14>/n-D Lookup Table' */ { 3.0299999713897705, 3.0, 2.9200000762939453 }, /* Computed Parameter: nDLookupTable_bp01Data_gg * Referenced by: '<S14>/n-D Lookup Table' */ { 278.14999389648438, 293.14999389648438, 323.14999389648438 }, /* Computed Parameter: Gain_Gain_n * Referenced by: '<S14>/Gain' */ -0.00027777778450399637, /* Computed Parameter: nDLookupTable_tableData_i * Referenced by: '<S15>/n-D Lookup Table' */ { 3.0299999713897705, 3.0, 2.9200000762939453 }, /* Computed Parameter: nDLookupTable_bp01Data_p * Referenced by: '<S15>/n-D Lookup Table' */ { 278.14999389648438, 293.14999389648438, 323.14999389648438 }, /* Computed Parameter: Gain_Gain_o * Referenced by: '<S15>/Gain' */ -0.00027777778450399637, /* Computed Parameter: nDLookupTable_tableData_fr * Referenced by: '<S16>/n-D Lookup Table' */ { 3.0299999713897705, 3.0, 2.9200000762939453 }, /* Computed Parameter: nDLookupTable_bp01Data_j * Referenced by: '<S16>/n-D Lookup Table' */ { 278.14999389648438, 293.14999389648438, 323.14999389648438 }, /* Computed Parameter: Gain_Gain_la * Referenced by: '<S16>/Gain' */ -0.00027777778450399637, /* Computed Parameter: nDLookupTable_tableData_g * Referenced by: '<S17>/n-D Lookup Table' */ { 3.0299999713897705, 3.0, 2.9200000762939453 }, /* Computed Parameter: nDLookupTable_bp01Data_k * Referenced by: '<S17>/n-D Lookup Table' */ { 278.14999389648438, 293.14999389648438, 323.14999389648438 }, /* Computed Parameter: Gain_Gain_c4 * Referenced by: '<S17>/Gain' */ -0.00027777778450399637, /* Computed Parameter: nDLookupTable_tableData_l * Referenced by: '<S18>/n-D Lookup Table' */ { 3.0299999713897705, 3.0, 2.9200000762939453 }, /* Computed Parameter: nDLookupTable_bp01Data_i * Referenced by: '<S18>/n-D Lookup Table' */ { 278.14999389648438, 293.14999389648438, 323.14999389648438 }, /* Computed Parameter: Gain_Gain_p * Referenced by: '<S18>/Gain' */ -0.00027777778450399637, /* Computed Parameter: nDLookupTable_tableData_md * Referenced by: '<S19>/n-D Lookup Table' */ { 3.0299999713897705, 3.0, 2.9200000762939453 }, /* Computed Parameter: nDLookupTable_bp01Data_pr * Referenced by: '<S19>/n-D Lookup Table' */ { 278.14999389648438, 293.14999389648438, 323.14999389648438 }, /* Computed Parameter: Gain_Gain_d * Referenced by: '<S19>/Gain' */ -0.00027777778450399637, /* Computed Parameter: nDLookupTable_tableData_aj * Referenced by: '<S20>/n-D Lookup Table' */ { 3.0299999713897705, 3.0, 2.9200000762939453 }, /* Computed Parameter: nDLookupTable_bp01Data_ch * Referenced by: '<S20>/n-D Lookup Table' */ { 278.14999389648438, 293.14999389648438, 323.14999389648438 }, /* Computed Parameter: Gain_Gain_e * Referenced by: '<S20>/Gain' */ -0.00027777778450399637, /* Computed Parameter: nDLookupTable_tableData_p * Referenced by: '<S21>/n-D Lookup Table' */ { 3.0299999713897705, 3.0, 2.9200000762939453 }, /* Computed Parameter: nDLookupTable_bp01Data_l * Referenced by: '<S21>/n-D Lookup Table' */ { 278.14999389648438, 293.14999389648438, 323.14999389648438 }, /* Computed Parameter: Gain_Gain_i * Referenced by: '<S21>/Gain' */ -0.00027777778450399637, /* Computed Parameter: nDLookupTable_tableData_mk * Referenced by: '<S22>/n-D Lookup Table' */ { 3.0299999713897705, 3.0, 2.9200000762939453 }, /* Computed Parameter: nDLookupTable_bp01Data_gb * Referenced by: '<S22>/n-D Lookup Table' */ { 278.14999389648438, 293.14999389648438, 323.14999389648438 }, /* Computed Parameter: Gain_Gain_fu * Referenced by: '<S22>/Gain' */ -0.00027777778450399637, /* Computed Parameter: nDLookupTable_tableData_o * Referenced by: '<S23>/n-D Lookup Table' */ { 3.0299999713897705, 3.0, 2.9200000762939453 }, /* Computed Parameter: nDLookupTable_bp01Data_ll * Referenced by: '<S23>/n-D Lookup Table' */ { 278.14999389648438, 293.14999389648438, 323.14999389648438 }, /* Computed Parameter: Gain_Gain_b * Referenced by: '<S23>/Gain' */ -0.00027777778450399637, /* Computed Parameter: nDLookupTable_tableData_o3 * Referenced by: '<S24>/n-D Lookup Table' */ { 3.0299999713897705, 3.0, 2.9200000762939453 }, /* Computed Parameter: nDLookupTable_bp01Data_b * Referenced by: '<S24>/n-D Lookup Table' */ { 278.14999389648438, 293.14999389648438, 323.14999389648438 }, /* Computed Parameter: Gain_Gain_k * Referenced by: '<S24>/Gain' */ -0.00027777778450399637, /* Computed Parameter: nDLookupTable_tableData_pv * Referenced by: '<S25>/n-D Lookup Table' */ { 3.0299999713897705, 3.0, 2.9200000762939453 }, /* Computed Parameter: nDLookupTable_bp01Data_f * Referenced by: '<S25>/n-D Lookup Table' */ { 278.14999389648438, 293.14999389648438, 323.14999389648438 }, /* Computed Parameter: Gain_Gain_bj * Referenced by: '<S25>/Gain' */ -0.00027777778450399637, /* Computed Parameter: nDLookupTable_tableData_mx * Referenced by: '<S26>/n-D Lookup Table' */ { 3.0299999713897705, 3.0, 2.9200000762939453 }, /* Computed Parameter: nDLookupTable_bp01Data_hs * Referenced by: '<S26>/n-D Lookup Table' */ { 278.14999389648438, 293.14999389648438, 323.14999389648438 }, /* Computed Parameter: Gain_Gain_bi * Referenced by: '<S26>/Gain' */ -0.00027777778450399637, /* Computed Parameter: nDLookupTable_tableData_b * Referenced by: '<S27>/n-D Lookup Table' */ { 3.0299999713897705, 3.0, 2.9200000762939453 }, /* Computed Parameter: nDLookupTable_bp01Data_f4 * Referenced by: '<S27>/n-D Lookup Table' */ { 278.14999389648438, 293.14999389648438, 323.14999389648438 }, /* Computed Parameter: Gain_Gain_ix * Referenced by: '<S27>/Gain' */ -0.00027777778450399637, /* Computed Parameter: nDLookupTable_tableData_lf * Referenced by: '<S28>/n-D Lookup Table' */ { 3.0299999713897705, 3.0, 2.9200000762939453 }, /* Computed Parameter: nDLookupTable_bp01Data_ky * Referenced by: '<S28>/n-D Lookup Table' */ { 278.14999389648438, 293.14999389648438, 323.14999389648438 }, /* Computed Parameter: Gain_Gain_dp * Referenced by: '<S28>/Gain' */ -0.00027777778450399637, /* Computed Parameter: nDLookupTable_tableData_k * Referenced by: '<S29>/n-D Lookup Table' */ { 3.0299999713897705, 3.0, 2.9200000762939453 }, /* Computed Parameter: nDLookupTable_bp01Data_ot * Referenced by: '<S29>/n-D Lookup Table' */ { 278.14999389648438, 293.14999389648438, 323.14999389648438 }, /* Computed Parameter: Gain_Gain_kc * Referenced by: '<S29>/Gain' */ -0.00027777778450399637, /* Computed Parameter: nDLookupTable_tableData_o2 * Referenced by: '<S30>/n-D Lookup Table' */ { 3.0299999713897705, 3.0, 2.9200000762939453 }, /* Computed Parameter: nDLookupTable_bp01Data_bp * Referenced by: '<S30>/n-D Lookup Table' */ { 278.14999389648438, 293.14999389648438, 323.14999389648438 }, /* Computed Parameter: Gain_Gain_ek * Referenced by: '<S30>/Gain' */ -0.00027777778450399637, /* Computed Parameter: nDLookupTable_tableData_n * Referenced by: '<S31>/n-D Lookup Table' */ { 3.0299999713897705, 3.0, 2.9200000762939453 }, /* Computed Parameter: nDLookupTable_bp01Data_d * Referenced by: '<S31>/n-D Lookup Table' */ { 278.14999389648438, 293.14999389648438, 323.14999389648438 }, /* Computed Parameter: Gain_Gain_pp * Referenced by: '<S31>/Gain' */ -0.00027777778450399637, /* Computed Parameter: nDLookupTable_tableData_bj * Referenced by: '<S32>/n-D Lookup Table' */ { 3.0299999713897705, 3.0, 2.9200000762939453 }, /* Computed Parameter: nDLookupTable_bp01Data_iz * Referenced by: '<S32>/n-D Lookup Table' */ { 278.14999389648438, 293.14999389648438, 323.14999389648438 }, /* Computed Parameter: Gain_Gain_oh * Referenced by: '<S32>/Gain' */ -0.00027777778450399637, /* Computed Parameter: nDLookupTable_tableData_oo * Referenced by: '<S33>/n-D Lookup Table' */ { 3.0299999713897705, 3.0, 2.9200000762939453 }, /* Computed Parameter: nDLookupTable_bp01Data_ow * Referenced by: '<S33>/n-D Lookup Table' */ { 278.14999389648438, 293.14999389648438, 323.14999389648438 }, /* Computed Parameter: Gain_Gain_pe * Referenced by: '<S33>/Gain' */ -0.00027777778450399637, /* Computed Parameter: nDLookupTable_tableData_aa * Referenced by: '<S34>/n-D Lookup Table' */ { 3.0299999713897705, 3.0, 2.9200000762939453 }, /* Computed Parameter: nDLookupTable_bp01Data_ko * Referenced by: '<S34>/n-D Lookup Table' */ { 278.14999389648438, 293.14999389648438, 323.14999389648438 }, /* Computed Parameter: Gain_Gain_g * Referenced by: '<S34>/Gain' */ -0.00027777778450399637, /* Computed Parameter: nDLookupTable_tableData_d * Referenced by: '<S35>/n-D Lookup Table' */ { 3.0299999713897705, 3.0, 2.9200000762939453 }, /* Computed Parameter: nDLookupTable_bp01Data_lc * Referenced by: '<S35>/n-D Lookup Table' */ { 278.14999389648438, 293.14999389648438, 323.14999389648438 }, /* Computed Parameter: Gain_Gain_cn * Referenced by: '<S35>/Gain' */ -0.00027777778450399637, /* Computed Parameter: nDLookupTable_tableData_f0 * Referenced by: '<S36>/n-D Lookup Table' */ { 3.0299999713897705, 3.0, 2.9200000762939453 }, /* Computed Parameter: nDLookupTable_bp01Data_mh * Referenced by: '<S36>/n-D Lookup Table' */ { 278.14999389648438, 293.14999389648438, 323.14999389648438 }, /* Computed Parameter: Gain_Gain_j * Referenced by: '<S36>/Gain' */ -0.00027777778450399637, /* Computed Parameter: nDLookupTable_tableData_hk * Referenced by: '<S37>/n-D Lookup Table' */ { 3.0299999713897705, 3.0, 2.9200000762939453 }, /* Computed Parameter: nDLookupTable_bp01Data_d4 * Referenced by: '<S37>/n-D Lookup Table' */ { 278.14999389648438, 293.14999389648438, 323.14999389648438 }, /* Computed Parameter: Gain_Gain_oa * Referenced by: '<S37>/Gain' */ -0.00027777778450399637 }; /* * File trailer for generated code. * * [EOF] */ ======================= File: workspace/bms_f4_ert_rtw/bms_f4.h ======================= /* * Academic License - for use in teaching, academic research, and meeting * course requirements at degree granting institutions only. Not for * government, commercial, or other organizational use. * * File: bms_f4.h * * Code generated for Simulink model 'bms_f4'. * * Model version : 1.33 * Simulink Coder version : 9.5 (R2021a) 14-Nov-2020 * C/C++ source code generated on : Wed Jun 2 11:40:20 2021 * * Target selection: ert.tlc * Embedded hardware selection: ARM Compatible->ARM Cortex * Code generation objectives: Unspecified * Validation result: Not run */ #ifndef RTW_HEADER_bms_f4_h_ #define RTW_HEADER_bms_f4_h_ #include <math.h> #include <stddef.h> #ifndef bms_f4_COMMON_INCLUDES_ #define bms_f4_COMMON_INCLUDES_ #include "rtwtypes.h" #endif /* bms_f4_COMMON_INCLUDES_ */ #include "bms_f4_types.h" #include "MW_target_hardware_resources.h" #include "rt_nonfinite.h" #include "rtGetInf.h" /* Macros for accessing real-time model data structure */ #ifndef rtmGetErrorStatus #define rtmGetErrorStatus(rtm) ((rtm)->errorStatus) #endif #ifndef rtmSetErrorStatus #define rtmSetErrorStatus(rtm, val) ((rtm)->errorStatus = (val)) #endif /* Block states (default storage) for system '<S4>/Chart1' */ typedef struct { uint32_T temporalCounter_i1; /* '<S4>/Chart1' */ uint8_T is_active_c2_bms_f4; /* '<S4>/Chart1' */ uint8_T is_c2_bms_f4; /* '<S4>/Chart1' */ uint8_T is_ON; /* '<S4>/Chart1' */ boolean_T flagBalancingDone; /* '<S4>/Chart1' */ } DW_Chart1_bms_f4_T; /* Block signals (default storage) */ typedef struct { real_T Selector[10]; /* '<S4>/Selector' */ real_T Selector1[10]; /* '<S4>/Selector1' */ real_T Selector2[10]; /* '<S4>/Selector2' */ real_T VectorConcatenate1[3]; /* '<S3>/Vector Concatenate1' */ real_T VectorConcatenate[2]; /* '<S3>/Vector Concatenate' */ real_T VectorConcatenate2[2]; /* '<S3>/Vector Concatenate2' */ real_T VectorConcatenate3[2]; /* '<S3>/Vector Concatenate3' */ real_T VectorConcatenate_k[3]; /* '<S4>/Vector Concatenate' */ boolean_T MatrixConcatenate[30]; /* '<S4>/Matrix Concatenate' */ real_T maxV; real_T maxV_m; real_T minV; real_T minV_c; real_T maxV_k; real_T maxV_c; real_T maxV_b; real_T Max3; /* '<S2>/Max3' */ real_T Gain; /* '<S37>/Gain' */ real_T Min3; /* '<S4>/Min3' */ real_T Min4; /* '<S4>/Min4' */ boolean_T VectorConcatenate1_a[3]; /* '<S4>/Vector Concatenate1' */ } B_bms_f4_T; /* Block states (default storage) for system '<Root>' */ typedef struct { real_T DiscreteTimeIntegrator_DSTATE;/* '<S17>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_DSTATE_a;/* '<S8>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_DSTAT_au;/* '<S9>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_DSTATE_m;/* '<S10>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_DSTATE_b;/* '<S11>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_DSTATE_p;/* '<S12>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_DSTATE_c;/* '<S13>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_DSTAT_mh;/* '<S14>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_DSTATE_g;/* '<S15>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_DSTAT_g0;/* '<S16>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_DSTATE_d;/* '<S27>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_DSTAT_b0;/* '<S18>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_DSTAT_dc;/* '<S19>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_DSTATE_o;/* '<S20>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_DSTAT_aw;/* '<S21>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_DSTATE_n;/* '<S22>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_DSTATE_e;/* '<S23>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_DSTATE_f;/* '<S24>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_DSTAT_aj;/* '<S25>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_DSTAT_bc;/* '<S26>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_DSTAT_ps;/* '<S37>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_DSTAT_ed;/* '<S28>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_DSTAT_mg;/* '<S29>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_DSTAT_fy;/* '<S30>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_DSTAT_gd;/* '<S31>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_DSTATE_i;/* '<S32>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_DSTAT_ce;/* '<S33>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_DSTAT_p0;/* '<S34>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_DSTAT_fb;/* '<S35>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_DSTAT_d3;/* '<S36>/Discrete-Time Integrator' */ uint32_T temporalCounter_i1; /* '<S3>/Chart' */ uint8_T is_c1_bms_f4; /* '<S3>/Chart' */ boolean_T isNotInit; /* '<S3>/Chart' */ DW_Chart1_bms_f4_T sf_Chart3; /* '<S4>/Chart3' */ DW_Chart1_bms_f4_T sf_Chart2; /* '<S4>/Chart2' */ DW_Chart1_bms_f4_T sf_Chart1; /* '<S4>/Chart1' */ } DW_bms_f4_T; /* External inputs (root inport signals with default storage) */ typedef struct { BusInputBMS FromPlant; /* '<Root>/FromPlant' */ BusSimulationInput InputSimulationBus;/* '<Root>/InputSimulationBus' */ } ExtU_bms_f4_T; /* External outputs (root outports fed by signals with default storage) */ typedef struct { BusOutputBMS ToPlant; /* '<Root>/ToPlant' */ } ExtY_bms_f4_T; /* Parameters (default storage) */ struct P_bms_f4_T_ { real_T CellCurrentLimitThreshold_Fault; /* Variable: CellCurrentLimitThreshold_Fault * Referenced by: '<S39>/Constant' */ real_T CellCurrentLimitThreshold_Warning; /* Variable: CellCurrentLimitThreshold_Warning * Referenced by: '<S38>/Constant' */ real_T CellTemperatureLimitThreshold_Fault; /* Variable: CellTemperatureLimitThreshold_Fault * Referenced by: '<S41>/Constant' */ real_T CellTemperatureLimitThreshold_Warning; /* Variable: CellTemperatureLimitThreshold_Warning * Referenced by: '<S40>/Constant' */ real_T CellVoltageLimitHigh_Fault; /* Variable: CellVoltageLimitHigh_Fault * Referenced by: '<S43>/Constant' */ real_T CellVoltageLimitHigh_Warning; /* Variable: CellVoltageLimitHigh_Warning * Referenced by: '<S42>/Constant' */ real_T CellVoltageLimitLow_Fault; /* Variable: CellVoltageLimitLow_Fault * Referenced by: '<S45>/Constant' */ real_T CellVoltageLimitLow_Warning; /* Variable: CellVoltageLimitLow_Warning * Referenced by: '<S44>/Constant' */ real_T DeltaVTargetMin; /* Variable: DeltaVTargetMin * Referenced by: * '<S4>/Chart1' * '<S4>/Chart2' * '<S4>/Chart3' */ real_T DrivetrainEnDelay; /* Variable: DrivetrainEnDelay * Referenced by: '<S3>/Chart' */ real_T VbattMin; /* Variable: VbattMin * Referenced by: '<S3>/Chart' */ real_T VbattThersholdChrg; /* Variable: VbattThersholdChrg * Referenced by: '<S3>/Chart' */ real_T VbattThresholdDis; /* Variable: VbattThresholdDis * Referenced by: '<S3>/Chart' */ real_T balancingRelaxationTime; /* Variable: balancingRelaxationTime * Referenced by: * '<S4>/Chart1' * '<S4>/Chart2' * '<S4>/Chart3' */ real_T balancingTime; /* Variable: balancingTime * Referenced by: * '<S4>/Chart1' * '<S4>/Chart2' * '<S4>/Chart3' */ real_T DiscreteTimeIntegrator_gainval; /* Computed Parameter: DiscreteTimeIntegrator_gainval * Referenced by: '<S17>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_IC; /* Computed Parameter: DiscreteTimeIntegrator_IC * Referenced by: '<S17>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_UpperSat;/* Expression: 1 * Referenced by: '<S17>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_LowerSat;/* Expression: 0 * Referenced by: '<S17>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_gainva_d; /* Computed Parameter: DiscreteTimeIntegrator_gainva_d * Referenced by: '<S8>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_IC_h; /* Computed Parameter: DiscreteTimeIntegrator_IC_h * Referenced by: '<S8>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_UpperS_n;/* Expression: 1 * Referenced by: '<S8>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_LowerS_e;/* Expression: 0 * Referenced by: '<S8>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_gainva_o; /* Computed Parameter: DiscreteTimeIntegrator_gainva_o * Referenced by: '<S9>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_IC_d; /* Computed Parameter: DiscreteTimeIntegrator_IC_d * Referenced by: '<S9>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_UpperS_m;/* Expression: 1 * Referenced by: '<S9>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_LowerS_l;/* Expression: 0 * Referenced by: '<S9>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_gainva_m; /* Computed Parameter: DiscreteTimeIntegrator_gainva_m * Referenced by: '<S10>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_IC_m; /* Computed Parameter: DiscreteTimeIntegrator_IC_m * Referenced by: '<S10>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_Upper_mg;/* Expression: 1 * Referenced by: '<S10>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_Lower_lh;/* Expression: 0 * Referenced by: '<S10>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_gainv_do; /* Computed Parameter: DiscreteTimeIntegrator_gainv_do * Referenced by: '<S11>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_IC_l; /* Computed Parameter: DiscreteTimeIntegrator_IC_l * Referenced by: '<S11>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_Upper_nt;/* Expression: 1 * Referenced by: '<S11>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_LowerS_c;/* Expression: 0 * Referenced by: '<S11>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_gainv_mu; /* Computed Parameter: DiscreteTimeIntegrator_gainv_mu * Referenced by: '<S12>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_IC_p; /* Computed Parameter: DiscreteTimeIntegrator_IC_p * Referenced by: '<S12>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_UpperS_i;/* Expression: 1 * Referenced by: '<S12>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_LowerS_p;/* Expression: 0 * Referenced by: '<S12>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_gainva_i; /* Computed Parameter: DiscreteTimeIntegrator_gainva_i * Referenced by: '<S13>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_IC_o; /* Computed Parameter: DiscreteTimeIntegrator_IC_o * Referenced by: '<S13>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_UpperS_e;/* Expression: 1 * Referenced by: '<S13>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_LowerS_h;/* Expression: 0 * Referenced by: '<S13>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_gainva_l; /* Computed Parameter: DiscreteTimeIntegrator_gainva_l * Referenced by: '<S14>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_IC_m3; /* Computed Parameter: DiscreteTimeIntegrator_IC_m3 * Referenced by: '<S14>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_UpperS_f;/* Expression: 1 * Referenced by: '<S14>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_LowerS_f;/* Expression: 0 * Referenced by: '<S14>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_gainv_oo; /* Computed Parameter: DiscreteTimeIntegrator_gainv_oo * Referenced by: '<S15>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_IC_e; /* Computed Parameter: DiscreteTimeIntegrator_IC_e * Referenced by: '<S15>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_UpperS_g;/* Expression: 1 * Referenced by: '<S15>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_LowerS_o;/* Expression: 0 * Referenced by: '<S15>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_gainva_p; /* Computed Parameter: DiscreteTimeIntegrator_gainva_p * Referenced by: '<S16>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_IC_ou; /* Computed Parameter: DiscreteTimeIntegrator_IC_ou * Referenced by: '<S16>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_UpperS_j;/* Expression: 1 * Referenced by: '<S16>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_LowerS_g;/* Expression: 0 * Referenced by: '<S16>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_gainva_k; /* Computed Parameter: DiscreteTimeIntegrator_gainva_k * Referenced by: '<S27>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_IC_b; /* Computed Parameter: DiscreteTimeIntegrator_IC_b * Referenced by: '<S27>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_Upper_jp;/* Expression: 1 * Referenced by: '<S27>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_Lower_ge;/* Expression: 0 * Referenced by: '<S27>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_gainv_ks; /* Computed Parameter: DiscreteTimeIntegrator_gainv_ks * Referenced by: '<S18>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_IC_dx; /* Computed Parameter: DiscreteTimeIntegrator_IC_dx * Referenced by: '<S18>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_Upper_g2;/* Expression: 1 * Referenced by: '<S18>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_LowerS_k;/* Expression: 0 * Referenced by: '<S18>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_gainva_c; /* Computed Parameter: DiscreteTimeIntegrator_gainva_c * Referenced by: '<S19>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_IC_lq; /* Computed Parameter: DiscreteTimeIntegrator_IC_lq * Referenced by: '<S19>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_Upper_gd;/* Expression: 1 * Referenced by: '<S19>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_Lower_c5;/* Expression: 0 * Referenced by: '<S19>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_gainva_a; /* Computed Parameter: DiscreteTimeIntegrator_gainva_a * Referenced by: '<S20>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_IC_oq; /* Computed Parameter: DiscreteTimeIntegrator_IC_oq * Referenced by: '<S20>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_UpperS_b;/* Expression: 1 * Referenced by: '<S20>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_LowerS_b;/* Expression: 0 * Referenced by: '<S20>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_gainva_n; /* Computed Parameter: DiscreteTimeIntegrator_gainva_n * Referenced by: '<S21>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_IC_dk; /* Computed Parameter: DiscreteTimeIntegrator_IC_dk * Referenced by: '<S21>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_Upper_f5;/* Expression: 1 * Referenced by: '<S21>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_Lower_pb;/* Expression: 0 * Referenced by: '<S21>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_gainv_co; /* Computed Parameter: DiscreteTimeIntegrator_gainv_co * Referenced by: '<S22>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_IC_on; /* Computed Parameter: DiscreteTimeIntegrator_IC_on * Referenced by: '<S22>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_Upper_i0;/* Expression: 1 * Referenced by: '<S22>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_Lower_gd;/* Expression: 0 * Referenced by: '<S22>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_gainva_f; /* Computed Parameter: DiscreteTimeIntegrator_gainva_f * Referenced by: '<S23>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_IC_c; /* Computed Parameter: DiscreteTimeIntegrator_IC_c * Referenced by: '<S23>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_UpperS_h;/* Expression: 1 * Referenced by: '<S23>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_Lower_hb;/* Expression: 0 * Referenced by: '<S23>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_gainv_cu; /* Computed Parameter: DiscreteTimeIntegrator_gainv_cu * Referenced by: '<S24>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_IC_lt; /* Computed Parameter: DiscreteTimeIntegrator_IC_lt * Referenced by: '<S24>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_Upper_e1;/* Expression: 1 * Referenced by: '<S24>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_Lower_pz;/* Expression: 0 * Referenced by: '<S24>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_gainva_e; /* Computed Parameter: DiscreteTimeIntegrator_gainva_e * Referenced by: '<S25>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_IC_k; /* Computed Parameter: DiscreteTimeIntegrator_IC_k * Referenced by: '<S25>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_Upper_g4;/* Expression: 1 * Referenced by: '<S25>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_LowerS_m;/* Expression: 0 * Referenced by: '<S25>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_gainv_pk; /* Computed Parameter: DiscreteTimeIntegrator_gainv_pk * Referenced by: '<S26>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_IC_dc; /* Computed Parameter: DiscreteTimeIntegrator_IC_dc * Referenced by: '<S26>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_UpperS_o;/* Expression: 1 * Referenced by: '<S26>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_Lower_k0;/* Expression: 0 * Referenced by: '<S26>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_gainv_nb; /* Computed Parameter: DiscreteTimeIntegrator_gainv_nb * Referenced by: '<S37>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_IC_j; /* Computed Parameter: DiscreteTimeIntegrator_IC_j * Referenced by: '<S37>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_UpperS_p;/* Expression: 1 * Referenced by: '<S37>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_LowerS_a;/* Expression: 0 * Referenced by: '<S37>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_gainv_a5; /* Computed Parameter: DiscreteTimeIntegrator_gainv_a5 * Referenced by: '<S28>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_IC_hw; /* Computed Parameter: DiscreteTimeIntegrator_IC_hw * Referenced by: '<S28>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_UpperS_c;/* Expression: 1 * Referenced by: '<S28>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_Lower_ae;/* Expression: 0 * Referenced by: '<S28>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_gainv_md; /* Computed Parameter: DiscreteTimeIntegrator_gainv_md * Referenced by: '<S29>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_IC_dv; /* Computed Parameter: DiscreteTimeIntegrator_IC_dv * Referenced by: '<S29>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_UpperS_d;/* Expression: 1 * Referenced by: '<S29>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_LowerS_d;/* Expression: 0 * Referenced by: '<S29>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_gainv_lm; /* Computed Parameter: DiscreteTimeIntegrator_gainv_lm * Referenced by: '<S30>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_IC_l1; /* Computed Parameter: DiscreteTimeIntegrator_IC_l1 * Referenced by: '<S30>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_Upper_eg;/* Expression: 1 * Referenced by: '<S30>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_Lower_do;/* Expression: 0 * Referenced by: '<S30>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_gainv_ae; /* Computed Parameter: DiscreteTimeIntegrator_gainv_ae * Referenced by: '<S31>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_IC_i; /* Computed Parameter: DiscreteTimeIntegrator_IC_i * Referenced by: '<S31>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_Upper_hx;/* Expression: 1 * Referenced by: '<S31>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_Lower_em;/* Expression: 0 * Referenced by: '<S31>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_gainv_lx; /* Computed Parameter: DiscreteTimeIntegrator_gainv_lx * Referenced by: '<S32>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_IC_f; /* Computed Parameter: DiscreteTimeIntegrator_IC_f * Referenced by: '<S32>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_Upper_ng;/* Expression: 1 * Referenced by: '<S32>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_Lower_oi;/* Expression: 0 * Referenced by: '<S32>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_gain_pkl; /* Computed Parameter: DiscreteTimeIntegrator_gain_pkl * Referenced by: '<S33>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_IC_ln; /* Computed Parameter: DiscreteTimeIntegrator_IC_ln * Referenced by: '<S33>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_Upper_ei;/* Expression: 1 * Referenced by: '<S33>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_LowerS_i;/* Expression: 0 * Referenced by: '<S33>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_gain_lxl; /* Computed Parameter: DiscreteTimeIntegrator_gain_lxl * Referenced by: '<S34>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_IC_mf; /* Computed Parameter: DiscreteTimeIntegrator_IC_mf * Referenced by: '<S34>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_Upper_cc;/* Expression: 1 * Referenced by: '<S34>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_Lower_cp;/* Expression: 0 * Referenced by: '<S34>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_gainv_ea; /* Computed Parameter: DiscreteTimeIntegrator_gainv_ea * Referenced by: '<S35>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_IC_mz; /* Computed Parameter: DiscreteTimeIntegrator_IC_mz * Referenced by: '<S35>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_Upper_jh;/* Expression: 1 * Referenced by: '<S35>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_Lower_ig;/* Expression: 0 * Referenced by: '<S35>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_gainv_ol; /* Computed Parameter: DiscreteTimeIntegrator_gainv_ol * Referenced by: '<S36>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_IC_m1; /* Computed Parameter: DiscreteTimeIntegrator_IC_m1 * Referenced by: '<S36>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_Upper_m0;/* Expression: 1 * Referenced by: '<S36>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_Lower_ou;/* Expression: 0 * Referenced by: '<S36>/Discrete-Time Integrator' */ real_T nDLookupTable_tableData[3]; /* Computed Parameter: nDLookupTable_tableData * Referenced by: '<S8>/n-D Lookup Table' */ real_T nDLookupTable_bp01Data[3];/* Computed Parameter: nDLookupTable_bp01Data * Referenced by: '<S8>/n-D Lookup Table' */ real_T Gain_Gain; /* Computed Parameter: Gain_Gain * Referenced by: '<S8>/Gain' */ real_T nDLookupTable_tableData_f[3]; /* Computed Parameter: nDLookupTable_tableData_f * Referenced by: '<S9>/n-D Lookup Table' */ real_T nDLookupTable_bp01Data_o[3]; /* Computed Parameter: nDLookupTable_bp01Data_o * Referenced by: '<S9>/n-D Lookup Table' */ real_T Gain_Gain_f; /* Computed Parameter: Gain_Gain_f * Referenced by: '<S9>/Gain' */ real_T nDLookupTable_tableData_e[3]; /* Computed Parameter: nDLookupTable_tableData_e * Referenced by: '<S10>/n-D Lookup Table' */ real_T nDLookupTable_bp01Data_m[3]; /* Computed Parameter: nDLookupTable_bp01Data_m * Referenced by: '<S10>/n-D Lookup Table' */ real_T Gain_Gain_m; /* Computed Parameter: Gain_Gain_m * Referenced by: '<S10>/Gain' */ real_T nDLookupTable_tableData_a[3]; /* Computed Parameter: nDLookupTable_tableData_a * Referenced by: '<S11>/n-D Lookup Table' */ real_T nDLookupTable_bp01Data_c[3]; /* Computed Parameter: nDLookupTable_bp01Data_c * Referenced by: '<S11>/n-D Lookup Table' */ real_T Gain_Gain_fa; /* Computed Parameter: Gain_Gain_fa * Referenced by: '<S11>/Gain' */ real_T nDLookupTable_tableData_h[3]; /* Computed Parameter: nDLookupTable_tableData_h * Referenced by: '<S12>/n-D Lookup Table' */ real_T nDLookupTable_bp01Data_h[3]; /* Computed Parameter: nDLookupTable_bp01Data_h * Referenced by: '<S12>/n-D Lookup Table' */ real_T Gain_Gain_l; /* Computed Parameter: Gain_Gain_l * Referenced by: '<S12>/Gain' */ real_T nDLookupTable_tableData_m[3]; /* Computed Parameter: nDLookupTable_tableData_m * Referenced by: '<S13>/n-D Lookup Table' */ real_T nDLookupTable_bp01Data_g[3]; /* Computed Parameter: nDLookupTable_bp01Data_g * Referenced by: '<S13>/n-D Lookup Table' */ real_T Gain_Gain_c; /* Computed Parameter: Gain_Gain_c * Referenced by: '<S13>/Gain' */ real_T nDLookupTable_tableData_j[3]; /* Computed Parameter: nDLookupTable_tableData_j * Referenced by: '<S14>/n-D Lookup Table' */ real_T nDLookupTable_bp01Data_gg[3]; /* Computed Parameter: nDLookupTable_bp01Data_gg * Referenced by: '<S14>/n-D Lookup Table' */ real_T Gain_Gain_n; /* Computed Parameter: Gain_Gain_n * Referenced by: '<S14>/Gain' */ real_T nDLookupTable_tableData_i[3]; /* Computed Parameter: nDLookupTable_tableData_i * Referenced by: '<S15>/n-D Lookup Table' */ real_T nDLookupTable_bp01Data_p[3]; /* Computed Parameter: nDLookupTable_bp01Data_p * Referenced by: '<S15>/n-D Lookup Table' */ real_T Gain_Gain_o; /* Computed Parameter: Gain_Gain_o * Referenced by: '<S15>/Gain' */ real_T nDLookupTable_tableData_fr[3]; /* Computed Parameter: nDLookupTable_tableData_fr * Referenced by: '<S16>/n-D Lookup Table' */ real_T nDLookupTable_bp01Data_j[3]; /* Computed Parameter: nDLookupTable_bp01Data_j * Referenced by: '<S16>/n-D Lookup Table' */ real_T Gain_Gain_la; /* Computed Parameter: Gain_Gain_la * Referenced by: '<S16>/Gain' */ real_T nDLookupTable_tableData_g[3]; /* Computed Parameter: nDLookupTable_tableData_g * Referenced by: '<S17>/n-D Lookup Table' */ real_T nDLookupTable_bp01Data_k[3]; /* Computed Parameter: nDLookupTable_bp01Data_k * Referenced by: '<S17>/n-D Lookup Table' */ real_T Gain_Gain_c4; /* Computed Parameter: Gain_Gain_c4 * Referenced by: '<S17>/Gain' */ real_T nDLookupTable_tableData_l[3]; /* Computed Parameter: nDLookupTable_tableData_l * Referenced by: '<S18>/n-D Lookup Table' */ real_T nDLookupTable_bp01Data_i[3]; /* Computed Parameter: nDLookupTable_bp01Data_i * Referenced by: '<S18>/n-D Lookup Table' */ real_T Gain_Gain_p; /* Computed Parameter: Gain_Gain_p * Referenced by: '<S18>/Gain' */ real_T nDLookupTable_tableData_md[3]; /* Computed Parameter: nDLookupTable_tableData_md * Referenced by: '<S19>/n-D Lookup Table' */ real_T nDLookupTable_bp01Data_pr[3]; /* Computed Parameter: nDLookupTable_bp01Data_pr * Referenced by: '<S19>/n-D Lookup Table' */ real_T Gain_Gain_d; /* Computed Parameter: Gain_Gain_d * Referenced by: '<S19>/Gain' */ real_T nDLookupTable_tableData_aj[3]; /* Computed Parameter: nDLookupTable_tableData_aj * Referenced by: '<S20>/n-D Lookup Table' */ real_T nDLookupTable_bp01Data_ch[3]; /* Computed Parameter: nDLookupTable_bp01Data_ch * Referenced by: '<S20>/n-D Lookup Table' */ real_T Gain_Gain_e; /* Computed Parameter: Gain_Gain_e * Referenced by: '<S20>/Gain' */ real_T nDLookupTable_tableData_p[3]; /* Computed Parameter: nDLookupTable_tableData_p * Referenced by: '<S21>/n-D Lookup Table' */ real_T nDLookupTable_bp01Data_l[3]; /* Computed Parameter: nDLookupTable_bp01Data_l * Referenced by: '<S21>/n-D Lookup Table' */ real_T Gain_Gain_i; /* Computed Parameter: Gain_Gain_i * Referenced by: '<S21>/Gain' */ real_T nDLookupTable_tableData_mk[3]; /* Computed Parameter: nDLookupTable_tableData_mk * Referenced by: '<S22>/n-D Lookup Table' */ real_T nDLookupTable_bp01Data_gb[3]; /* Computed Parameter: nDLookupTable_bp01Data_gb * Referenced by: '<S22>/n-D Lookup Table' */ real_T Gain_Gain_fu; /* Computed Parameter: Gain_Gain_fu * Referenced by: '<S22>/Gain' */ real_T nDLookupTable_tableData_o[3]; /* Computed Parameter: nDLookupTable_tableData_o * Referenced by: '<S23>/n-D Lookup Table' */ real_T nDLookupTable_bp01Data_ll[3]; /* Computed Parameter: nDLookupTable_bp01Data_ll * Referenced by: '<S23>/n-D Lookup Table' */ real_T Gain_Gain_b; /* Computed Parameter: Gain_Gain_b * Referenced by: '<S23>/Gain' */ real_T nDLookupTable_tableData_o3[3]; /* Computed Parameter: nDLookupTable_tableData_o3 * Referenced by: '<S24>/n-D Lookup Table' */ real_T nDLookupTable_bp01Data_b[3]; /* Computed Parameter: nDLookupTable_bp01Data_b * Referenced by: '<S24>/n-D Lookup Table' */ real_T Gain_Gain_k; /* Computed Parameter: Gain_Gain_k * Referenced by: '<S24>/Gain' */ real_T nDLookupTable_tableData_pv[3]; /* Computed Parameter: nDLookupTable_tableData_pv * Referenced by: '<S25>/n-D Lookup Table' */ real_T nDLookupTable_bp01Data_f[3]; /* Computed Parameter: nDLookupTable_bp01Data_f * Referenced by: '<S25>/n-D Lookup Table' */ real_T Gain_Gain_bj; /* Computed Parameter: Gain_Gain_bj * Referenced by: '<S25>/Gain' */ real_T nDLookupTable_tableData_mx[3]; /* Computed Parameter: nDLookupTable_tableData_mx * Referenced by: '<S26>/n-D Lookup Table' */ real_T nDLookupTable_bp01Data_hs[3]; /* Computed Parameter: nDLookupTable_bp01Data_hs * Referenced by: '<S26>/n-D Lookup Table' */ real_T Gain_Gain_bi; /* Computed Parameter: Gain_Gain_bi * Referenced by: '<S26>/Gain' */ real_T nDLookupTable_tableData_b[3]; /* Computed Parameter: nDLookupTable_tableData_b * Referenced by: '<S27>/n-D Lookup Table' */ real_T nDLookupTable_bp01Data_f4[3]; /* Computed Parameter: nDLookupTable_bp01Data_f4 * Referenced by: '<S27>/n-D Lookup Table' */ real_T Gain_Gain_ix; /* Computed Parameter: Gain_Gain_ix * Referenced by: '<S27>/Gain' */ real_T nDLookupTable_tableData_lf[3]; /* Computed Parameter: nDLookupTable_tableData_lf * Referenced by: '<S28>/n-D Lookup Table' */ real_T nDLookupTable_bp01Data_ky[3]; /* Computed Parameter: nDLookupTable_bp01Data_ky * Referenced by: '<S28>/n-D Lookup Table' */ real_T Gain_Gain_dp; /* Computed Parameter: Gain_Gain_dp * Referenced by: '<S28>/Gain' */ real_T nDLookupTable_tableData_k[3]; /* Computed Parameter: nDLookupTable_tableData_k * Referenced by: '<S29>/n-D Lookup Table' */ real_T nDLookupTable_bp01Data_ot[3]; /* Computed Parameter: nDLookupTable_bp01Data_ot * Referenced by: '<S29>/n-D Lookup Table' */ real_T Gain_Gain_kc; /* Computed Parameter: Gain_Gain_kc * Referenced by: '<S29>/Gain' */ real_T nDLookupTable_tableData_o2[3]; /* Computed Parameter: nDLookupTable_tableData_o2 * Referenced by: '<S30>/n-D Lookup Table' */ real_T nDLookupTable_bp01Data_bp[3]; /* Computed Parameter: nDLookupTable_bp01Data_bp * Referenced by: '<S30>/n-D Lookup Table' */ real_T Gain_Gain_ek; /* Computed Parameter: Gain_Gain_ek * Referenced by: '<S30>/Gain' */ real_T nDLookupTable_tableData_n[3]; /* Computed Parameter: nDLookupTable_tableData_n * Referenced by: '<S31>/n-D Lookup Table' */ real_T nDLookupTable_bp01Data_d[3]; /* Computed Parameter: nDLookupTable_bp01Data_d * Referenced by: '<S31>/n-D Lookup Table' */ real_T Gain_Gain_pp; /* Computed Parameter: Gain_Gain_pp * Referenced by: '<S31>/Gain' */ real_T nDLookupTable_tableData_bj[3]; /* Computed Parameter: nDLookupTable_tableData_bj * Referenced by: '<S32>/n-D Lookup Table' */ real_T nDLookupTable_bp01Data_iz[3]; /* Computed Parameter: nDLookupTable_bp01Data_iz * Referenced by: '<S32>/n-D Lookup Table' */ real_T Gain_Gain_oh; /* Computed Parameter: Gain_Gain_oh * Referenced by: '<S32>/Gain' */ real_T nDLookupTable_tableData_oo[3]; /* Computed Parameter: nDLookupTable_tableData_oo * Referenced by: '<S33>/n-D Lookup Table' */ real_T nDLookupTable_bp01Data_ow[3]; /* Computed Parameter: nDLookupTable_bp01Data_ow * Referenced by: '<S33>/n-D Lookup Table' */ real_T Gain_Gain_pe; /* Computed Parameter: Gain_Gain_pe * Referenced by: '<S33>/Gain' */ real_T nDLookupTable_tableData_aa[3]; /* Computed Parameter: nDLookupTable_tableData_aa * Referenced by: '<S34>/n-D Lookup Table' */ real_T nDLookupTable_bp01Data_ko[3]; /* Computed Parameter: nDLookupTable_bp01Data_ko * Referenced by: '<S34>/n-D Lookup Table' */ real_T Gain_Gain_g; /* Computed Parameter: Gain_Gain_g * Referenced by: '<S34>/Gain' */ real_T nDLookupTable_tableData_d[3]; /* Computed Parameter: nDLookupTable_tableData_d * Referenced by: '<S35>/n-D Lookup Table' */ real_T nDLookupTable_bp01Data_lc[3]; /* Computed Parameter: nDLookupTable_bp01Data_lc * Referenced by: '<S35>/n-D Lookup Table' */ real_T Gain_Gain_cn; /* Computed Parameter: Gain_Gain_cn * Referenced by: '<S35>/Gain' */ real_T nDLookupTable_tableData_f0[3]; /* Computed Parameter: nDLookupTable_tableData_f0 * Referenced by: '<S36>/n-D Lookup Table' */ real_T nDLookupTable_bp01Data_mh[3]; /* Computed Parameter: nDLookupTable_bp01Data_mh * Referenced by: '<S36>/n-D Lookup Table' */ real_T Gain_Gain_j; /* Computed Parameter: Gain_Gain_j * Referenced by: '<S36>/Gain' */ real_T nDLookupTable_tableData_hk[3]; /* Computed Parameter: nDLookupTable_tableData_hk * Referenced by: '<S37>/n-D Lookup Table' */ real_T nDLookupTable_bp01Data_d4[3]; /* Computed Parameter: nDLookupTable_bp01Data_d4 * Referenced by: '<S37>/n-D Lookup Table' */ real_T Gain_Gain_oa; /* Computed Parameter: Gain_Gain_oa * Referenced by: '<S37>/Gain' */ }; /* Real-time Model Data Structure */ struct tag_RTM_bms_f4_T { const char_T *errorStatus; }; /* Block parameters (default storage) */ extern P_bms_f4_T bms_f4_P; /* Block signals (default storage) */ extern B_bms_f4_T bms_f4_B; /* Block states (default storage) */ extern DW_bms_f4_T bms_f4_DW; /* External inputs (root inport signals with default storage) */ extern ExtU_bms_f4_T bms_f4_U; /* External outputs (root outports fed by signals with default storage) */ extern ExtY_bms_f4_T bms_f4_Y; /* Model entry point functions */ extern void bms_f4_initialize(void); extern void bms_f4_step(void); extern void bms_f4_terminate(void); /* Real-time Model object */ extern RT_MODEL_bms_f4_T *const bms_f4_M; extern volatile boolean_T stopRequested; extern volatile boolean_T runModel; /*- * These blocks were eliminated from the model due to optimizations: * * Block '<S1>/Selector3' : Unused code path elimination * Block '<S1>/Selector6' : Unused code path elimination * Block '<S1>/Selector9' : Unused code path elimination * Block '<S3>/Data Type Conversion' : Eliminate redundant data type conversion * Block '<S3>/Data Type Conversion1' : Eliminate redundant data type conversion * Block '<S3>/Data Type Conversion2' : Eliminate redundant data type conversion * Block '<S3>/Data Type Conversion3' : Eliminate redundant data type conversion */ /*- * The generated code includes comments that allow you to trace directly * back to the appropriate location in the model. The basic format * is <system>/block_name, where system is the system number (uniquely * assigned by Simulink) and block_name is the name of the block. * * Use the MATLAB hilite_system command to trace the generated code back * to the model. For example, * * hilite_system('<S3>') - opens system 3 * hilite_system('<S3>/Kp') - opens and selects block Kp which resides in S3 * * Here is the system hierarchy for this model * * '<Root>' : 'bms_f4' * '<S1>' : 'bms_f4/PackSOC' * '<S2>' : 'bms_f4/Subsystem' * '<S3>' : 'bms_f4/Subsystem Reference' * '<S4>' : 'bms_f4/Subsystem Reference1' * '<S5>' : 'bms_f4/PackSOC/Subsystem' * '<S6>' : 'bms_f4/PackSOC/Subsystem1' * '<S7>' : 'bms_f4/PackSOC/Subsystem2' * '<S8>' : 'bms_f4/PackSOC/Subsystem/Subsystem Reference1' * '<S9>' : 'bms_f4/PackSOC/Subsystem/Subsystem Reference2' * '<S10>' : 'bms_f4/PackSOC/Subsystem/Subsystem Reference24' * '<S11>' : 'bms_f4/PackSOC/Subsystem/Subsystem Reference25' * '<S12>' : 'bms_f4/PackSOC/Subsystem/Subsystem Reference26' * '<S13>' : 'bms_f4/PackSOC/Subsystem/Subsystem Reference27' * '<S14>' : 'bms_f4/PackSOC/Subsystem/Subsystem Reference28' * '<S15>' : 'bms_f4/PackSOC/Subsystem/Subsystem Reference29' * '<S16>' : 'bms_f4/PackSOC/Subsystem/Subsystem Reference30' * '<S17>' : 'bms_f4/PackSOC/Subsystem/Subsystem Reference43' * '<S18>' : 'bms_f4/PackSOC/Subsystem1/Subsystem Reference1' * '<S19>' : 'bms_f4/PackSOC/Subsystem1/Subsystem Reference2' * '<S20>' : 'bms_f4/PackSOC/Subsystem1/Subsystem Reference24' * '<S21>' : 'bms_f4/PackSOC/Subsystem1/Subsystem Reference25' * '<S22>' : 'bms_f4/PackSOC/Subsystem1/Subsystem Reference26' * '<S23>' : 'bms_f4/PackSOC/Subsystem1/Subsystem Reference27' * '<S24>' : 'bms_f4/PackSOC/Subsystem1/Subsystem Reference28' * '<S25>' : 'bms_f4/PackSOC/Subsystem1/Subsystem Reference29' * '<S26>' : 'bms_f4/PackSOC/Subsystem1/Subsystem Reference30' * '<S27>' : 'bms_f4/PackSOC/Subsystem1/Subsystem Reference43' * '<S28>' : 'bms_f4/PackSOC/Subsystem2/Subsystem Reference1' * '<S29>' : 'bms_f4/PackSOC/Subsystem2/Subsystem Reference2' * '<S30>' : 'bms_f4/PackSOC/Subsystem2/Subsystem Reference24' * '<S31>' : 'bms_f4/PackSOC/Subsystem2/Subsystem Reference25' * '<S32>' : 'bms_f4/PackSOC/Subsystem2/Subsystem Reference26' * '<S33>' : 'bms_f4/PackSOC/Subsystem2/Subsystem Reference27' * '<S34>' : 'bms_f4/PackSOC/Subsystem2/Subsystem Reference28' * '<S35>' : 'bms_f4/PackSOC/Subsystem2/Subsystem Reference29' * '<S36>' : 'bms_f4/PackSOC/Subsystem2/Subsystem Reference30' * '<S37>' : 'bms_f4/PackSOC/Subsystem2/Subsystem Reference43' * '<S38>' : 'bms_f4/Subsystem/Compare To Constant' * '<S39>' : 'bms_f4/Subsystem/Compare To Constant1' * '<S40>' : 'bms_f4/Subsystem/Compare To Constant2' * '<S41>' : 'bms_f4/Subsystem/Compare To Constant3' * '<S42>' : 'bms_f4/Subsystem/Compare To Constant4' * '<S43>' : 'bms_f4/Subsystem/Compare To Constant5' * '<S44>' : 'bms_f4/Subsystem/Compare To Constant6' * '<S45>' : 'bms_f4/Subsystem/Compare To Constant7' * '<S46>' : 'bms_f4/Subsystem Reference/Chart' * '<S47>' : 'bms_f4/Subsystem Reference1/Chart1' * '<S48>' : 'bms_f4/Subsystem Reference1/Chart2' * '<S49>' : 'bms_f4/Subsystem Reference1/Chart3' */ #endif /* RTW_HEADER_bms_f4_h_ */ /* * File trailer for generated code. * * [EOF] */ ======================= File: workspace/bms_f4_ert_rtw/pil/xil_instrumentation.c ======================= <reponame>meltinglab/battery-management /* * File: xil_instrumentation.c * * Code generated for instrumentation. * */ #include "xil_instrumentation.h" /* Code instrumentation offset(s) for model bms_f4 */ #define taskTimeStart_bms_f4_offset 0 #define taskTimeEnd_bms_f4_offset 0 /* Code instrumentation offset(s) for model bms_f4 */ #define captureMode_bms_f4_offset 3 /* A function parameter may be intentionally unused */ #ifndef UNUSED_PARAMETER # if defined(__LCC__) # define UNUSED_PARAMETER(x) # else # define UNUSED_PARAMETER(x) (void) (x) # endif #endif #define SIZEOF_TIMER_TYPE sizeof(uint32_T) static uint32_T xsd_xil_timer_corrected = 0; static uint32_T xsd_xil_timer_unfreeze = 0; static uint32_T xsd_xil_freezing_busy = 0; void xilUploadProfilingData(uint32_T sectionId) { xilUploadCodeInstrData((void *)(&xsd_xil_timer_corrected), (uint32_T) (SIZEOF_TIMER_TYPE), sectionId); } /* The internal freeze and unfreeze methods cannot be nested. The customer-visible implementation avoids nesting problems */ void xilProfilingTimerFreezeInternal(void) { /* Update the value of the corrected timer to exclude time spent in the * instrumentation code. * * Using a timer that increments on each tick. */ xsd_xil_timer_corrected = xsd_xil_timer_corrected + (((uint32_T) (profileTimerRead())) - xsd_xil_timer_unfreeze); } void xilProfilingTimerUnFreezeInternal(void) { xsd_xil_timer_unfreeze = ( uint32_T ) (profileTimerRead()); } void xilProfilingTimerFreeze(void) { if (xsd_xil_freezing_busy == 0) { xilProfilingTimerFreezeInternal(); } /* if */ } void xilProfilingTimerUnFreeze(void) { if (xsd_xil_freezing_busy == 0) { xilProfilingTimerUnFreezeInternal(); } /* if */ } void taskTimeStart(uint32_T sectionId) { captureModeStart(sectionId); xilProfilingTimerUnFreezeInternal(); } void taskTimeEnd(uint32_T sectionId) { xilProfilingTimerFreezeInternal(); captureModeEnd(sectionId); } #define MAX_EXECUTION_SECTION_ID 3 #define MAP_CAPTURE_IDS(X) (((X) > 0 && (X) <= 3)? (X) : 0) static uint32_T xsd_xil_last_start_time[MAX_EXECUTION_SECTION_ID] = { 0 }; static uint32_T xsd_xil_capture_mode_max[MAX_EXECUTION_SECTION_ID] = { 0 }; static uint32_T xsd_xil_capture_mode_avg[MAX_EXECUTION_SECTION_ID] = { 0 }; static uint32_T xsd_xil_capture_mode_calls[MAX_EXECUTION_SECTION_ID] = { 0 }; void captureMode(uint32_T sectionId) { xilUploadCodeInstrData((void *)(&xsd_xil_capture_mode_max), (uint32_T) (MAX_EXECUTION_SECTION_ID * sizeof(uint32_T)), sectionId); xilUploadCodeInstrData((void *)(&xsd_xil_capture_mode_avg), (uint32_T) (MAX_EXECUTION_SECTION_ID * sizeof(uint32_T)), sectionId + 1); xilUploadCodeInstrData((void *)(&xsd_xil_capture_mode_calls), (uint32_T) (MAX_EXECUTION_SECTION_ID * sizeof(uint32_T)), sectionId + 2); } void captureModeStart(uint32_T sectionId) { uint32_T mappedId = MAP_CAPTURE_IDS(sectionId); if (mappedId > 0) { xsd_xil_last_start_time[mappedId - 1] = xsd_xil_timer_corrected; } /* if */ } void captureModeEnd(uint32_T sectionId) { uint32_T mappedId = MAP_CAPTURE_IDS(sectionId); uint32_T* pCaptureValue; uint32_T turnaroundTime; if (mappedId > 0) { mappedId = mappedId - 1; /* Update maximum execution */ pCaptureValue = &(xsd_xil_capture_mode_max[mappedId]); turnaroundTime = xsd_xil_timer_corrected - xsd_xil_last_start_time[mappedId]; if (turnaroundTime > *pCaptureValue) { *pCaptureValue = turnaroundTime; } /* if */ /* Try to update to total execution counter */ pCaptureValue = &(xsd_xil_capture_mode_avg[mappedId]); if ((*pCaptureValue + turnaroundTime) > *pCaptureValue) { *pCaptureValue = *pCaptureValue + turnaroundTime; /* Update total number of calls */ pCaptureValue = &(xsd_xil_capture_mode_calls[mappedId]); *pCaptureValue = *pCaptureValue + 1; } /* if */ } /* if */ } /* Code instrumentation method(s) for model bms_f4 */ void taskTimeStart_bms_f4(uint32_T sectionId) { taskTimeStart(taskTimeStart_bms_f4_offset + sectionId); } void taskTimeEnd_bms_f4(uint32_T sectionId) { taskTimeEnd(taskTimeEnd_bms_f4_offset + sectionId); } /* Code instrumentation method(s) for model bms_f4 */ void captureMode_bms_f4(uint32_T sectionId) { captureMode(captureMode_bms_f4_offset + sectionId); } void PauseEvent (void) { /* callbacks executed when the sim is paused */ } void TerminateEvent (void) { /* callbacks executed when the sim ends */ captureMode_bms_f4(1); } void StepCompletedEvent (void) { /* callbacks executed when a step ends */ } ======================= File: workspace/bms_f4_ert_rtw/pil/xil_interface.c ======================= /* * File: xil_interface.c * * PIL generated interface for code: "bms_f4" * */ #include "bms_f4.h" #include "bms_f4_private.h" #include "xil_interface.h" #include "xil_instrumentation.h" /* Functions with a C call interface */ #ifdef __cplusplus extern "C" { #endif #include "xil_data_stream.h" #include "codeinstr_data_stream.h" #ifdef __cplusplus } #endif static XILIOData xil_fcnid0_task1_output_u[16]; static XILIOData xil_fcnid0_task1_y[18]; static XILIOData xil_fcnid0_init_y[18]; static XILIOData xil_fcnid0_ws_params[16]; /* In-the-Loop Interface functions - see xil_interface.h */ XIL_INTERFACE_ERROR_CODE xilProcessParams(uint32_T xilFcnId) { /* Single In-the-Loop Component */ if (xilFcnId!= 0) { return XIL_INTERFACE_UNKNOWN_FCNID; } return XIL_INTERFACE_SUCCESS; } void xilUploadCodeInstrData(void * pData, uint32_T numMemUnits, uint32_T sectionId) { /* Send code instrumentation data to host */ if (codeInstrWriteData((MemUnit_T *) &numMemUnits, sizeof(numMemUnits))!= XIL_DATA_STREAM_SUCCESS) { for (;;) ; } if (codeInstrWriteData((MemUnit_T *) &sectionId, sizeof(uint32_T))!= XIL_DATA_STREAM_SUCCESS) { for (;;) ; } if (codeInstrWriteData((MemUnit_T *) pData, numMemUnits)!= XIL_DATA_STREAM_SUCCESS) { for (;;) ; } } XIL_INTERFACE_ERROR_CODE xilGetDataTypeInfo(void) { { /* send response id code */ MemUnit_T memUnitData = XIL_RESPONSE_TYPE_SIZE; if (xilWriteData(&memUnitData, sizeof(memUnitData))!= XIL_DATA_STREAM_SUCCESS) { return XIL_INTERFACE_COMMS_FAILURE; } /* send type id */ memUnitData = 0; if (xilWriteData(&memUnitData, sizeof(memUnitData))!= XIL_DATA_STREAM_SUCCESS) { return XIL_INTERFACE_COMMS_FAILURE; } /* PIL_DOUBLE_SIZE should only be already defined for MathWorks testing */ #ifndef PIL_DOUBLE_SIZE #define PIL_DOUBLE_SIZE sizeof(double) #endif /* send size in bytes */ memUnitData = (MemUnit_T) PIL_DOUBLE_SIZE; #ifndef HOST_WORD_ADDRESSABLE_TESTING /* convert MemUnits to bytes */ memUnitData *= MEM_UNIT_BYTES; #endif if (xilWriteData(&memUnitData, sizeof(memUnitData))!= XIL_DATA_STREAM_SUCCESS) { return XIL_INTERFACE_COMMS_FAILURE; } } return XIL_INTERFACE_SUCCESS; } XIL_INTERFACE_ERROR_CODE xilInitialize(uint32_T xilFcnId) { XIL_INTERFACE_ERROR_CODE errorCode = XIL_INTERFACE_SUCCESS; /* initialize output storage owned by In-the-Loop */ /* Single In-the-Loop Component */ if (xilFcnId == 0) { taskTimeStart_bms_f4(1U); bms_f4_initialize(); taskTimeEnd_bms_f4(1U); } else { errorCode = XIL_INTERFACE_UNKNOWN_FCNID; } return errorCode; } XIL_INTERFACE_ERROR_CODE xilPause(uint32_T xilFcnId) { XIL_INTERFACE_ERROR_CODE errorCode = XIL_INTERFACE_SUCCESS; if (xilFcnId == 0) { PauseEvent(); } else { errorCode = XIL_INTERFACE_UNKNOWN_FCNID; } /* if */ return errorCode; } XIL_INTERFACE_ERROR_CODE xilSystemInitialize(uint32_T xilFcnId) { XIL_INTERFACE_ERROR_CODE errorCode = XIL_INTERFACE_SUCCESS; /* Single In-the-Loop Component */ if (xilFcnId == 0) { /* No Function to Call */ } else { errorCode = XIL_INTERFACE_UNKNOWN_FCNID; } return errorCode; } XIL_INTERFACE_ERROR_CODE xilSystemReset(uint32_T xilFcnId) { XIL_INTERFACE_ERROR_CODE errorCode = XIL_INTERFACE_SUCCESS; /* Single In-the-Loop Component */ if (xilFcnId == 0) { /* No Function to Call */ } else { errorCode = XIL_INTERFACE_UNKNOWN_FCNID; } return errorCode; } XIL_INTERFACE_ERROR_CODE xilGetHostToTargetData(uint32_T xilFcnId, XIL_COMMAND_TYPE_ENUM xilCommandType, uint32_T xilCommandIdx, XILIOData ** xilIOData) { XIL_INTERFACE_ERROR_CODE errorCode = XIL_INTERFACE_SUCCESS; *xilIOData = 0; /* Single In-the-Loop Component */ if (xilFcnId!= 0) { errorCode = XIL_INTERFACE_UNKNOWN_FCNID; return errorCode; } switch (xilCommandType) { case XIL_PROCESS_PARAMS_COMMAND: { static int initComplete = 0; if (!initComplete) { uint32_T tableIdx = 0; { void * dataAddress = (void *) &(bms_f4_P.CellCurrentLimitThreshold_Fault); xil_fcnid0_ws_params[tableIdx].memUnitLength = 1 * sizeof(real_T); xil_fcnid0_ws_params[tableIdx++].address = (MemUnit_T *) dataAddress; } { void * dataAddress = (void *) &(bms_f4_P.CellCurrentLimitThreshold_Warning); xil_fcnid0_ws_params[tableIdx].memUnitLength = 1 * sizeof(real_T); xil_fcnid0_ws_params[tableIdx++].address = (MemUnit_T *) dataAddress; } { void * dataAddress = (void *) &(bms_f4_P.CellTemperatureLimitThreshold_Fault); xil_fcnid0_ws_params[tableIdx].memUnitLength = 1 * sizeof(real_T); xil_fcnid0_ws_params[tableIdx++].address = (MemUnit_T *) dataAddress; } { void * dataAddress = (void *) &(bms_f4_P.CellTemperatureLimitThreshold_Warning); xil_fcnid0_ws_params[tableIdx].memUnitLength = 1 * sizeof(real_T); xil_fcnid0_ws_params[tableIdx++].address = (MemUnit_T *) dataAddress; } { void * dataAddress = (void *) &(bms_f4_P.CellVoltageLimitHigh_Fault); xil_fcnid0_ws_params[tableIdx].memUnitLength = 1 * sizeof(real_T); xil_fcnid0_ws_params[tableIdx++].address = (MemUnit_T *) dataAddress; } { void * dataAddress = (void *) &(bms_f4_P.CellVoltageLimitHigh_Warning); xil_fcnid0_ws_params[tableIdx].memUnitLength = 1 * sizeof(real_T); xil_fcnid0_ws_params[tableIdx++].address = (MemUnit_T *) dataAddress; } { void * dataAddress = (void *) &(bms_f4_P.CellVoltageLimitLow_Fault); xil_fcnid0_ws_params[tableIdx].memUnitLength = 1 * sizeof(real_T); xil_fcnid0_ws_params[tableIdx++].address = (MemUnit_T *) dataAddress; } { void * dataAddress = (void *) &(bms_f4_P.CellVoltageLimitLow_Warning); xil_fcnid0_ws_params[tableIdx].memUnitLength = 1 * sizeof(real_T); xil_fcnid0_ws_params[tableIdx++].address = (MemUnit_T *) dataAddress; } { void * dataAddress = (void *) &(bms_f4_P.DeltaVTargetMin); xil_fcnid0_ws_params[tableIdx].memUnitLength = 1 * sizeof(real_T); xil_fcnid0_ws_params[tableIdx++].address = (MemUnit_T *) dataAddress; } { void * dataAddress = (void *) &(bms_f4_P.DrivetrainEnDelay); xil_fcnid0_ws_params[tableIdx].memUnitLength = 1 * sizeof(real_T); xil_fcnid0_ws_params[tableIdx++].address = (MemUnit_T *) dataAddress; } { void * dataAddress = (void *) &(bms_f4_P.VbattMin); xil_fcnid0_ws_params[tableIdx].memUnitLength = 1 * sizeof(real_T); xil_fcnid0_ws_params[tableIdx++].address = (MemUnit_T *) dataAddress; } { void * dataAddress = (void *) &(bms_f4_P.VbattThersholdChrg); xil_fcnid0_ws_params[tableIdx].memUnitLength = 1 * sizeof(real_T); xil_fcnid0_ws_params[tableIdx++].address = (MemUnit_T *) dataAddress; } { void * dataAddress = (void *) &(bms_f4_P.VbattThresholdDis); xil_fcnid0_ws_params[tableIdx].memUnitLength = 1 * sizeof(real_T); xil_fcnid0_ws_params[tableIdx++].address = (MemUnit_T *) dataAddress; } { void * dataAddress = (void *) &(bms_f4_P.balancingRelaxationTime); xil_fcnid0_ws_params[tableIdx].memUnitLength = 1 * sizeof(real_T); xil_fcnid0_ws_params[tableIdx++].address = (MemUnit_T *) dataAddress; } { void * dataAddress = (void *) &(bms_f4_P.balancingTime); xil_fcnid0_ws_params[tableIdx].memUnitLength = 1 * sizeof(real_T); xil_fcnid0_ws_params[tableIdx++].address = (MemUnit_T *) dataAddress; } xil_fcnid0_ws_params[tableIdx].memUnitLength = 0; xil_fcnid0_ws_params[tableIdx++].address = (MemUnit_T *) 0; initComplete = 1; } /* if */ *xilIOData = &xil_fcnid0_ws_params[0]; break; } case XIL_OUTPUT_COMMAND: { static int initComplete = 0; if (!initComplete) { uint32_T tableIdx = 0; { void * dataAddress = (void *) &(bms_f4_U.FromPlant.BMSBatteryPackData.SegmentTempVector[0]); xil_fcnid0_task1_output_u[tableIdx].memUnitLength = 30 * sizeof(real_T); xil_fcnid0_task1_output_u[tableIdx++].address = (MemUnit_T *) dataAddress; } { void * dataAddress = (void *) &(bms_f4_U.FromPlant.BMSBatteryPackData.SegmentVoltageVector[0]); xil_fcnid0_task1_output_u[tableIdx].memUnitLength = 30 * sizeof(real_T); xil_fcnid0_task1_output_u[tableIdx++].address = (MemUnit_T *) dataAddress; } { void * dataAddress = (void *) &(bms_f4_U.FromPlant.BMSBatteryPackData.SegmentCurrentVector[0]); xil_fcnid0_task1_output_u[tableIdx].memUnitLength = 30 * sizeof(real_T); xil_fcnid0_task1_output_u[tableIdx++].address = (MemUnit_T *) dataAddress; } { void * dataAddress = (void *) &(bms_f4_U.FromPlant.BMSBatteryPackData.SegmentRealSOCVector[0]); xil_fcnid0_task1_output_u[tableIdx].memUnitLength = 30 * sizeof(real_T); xil_fcnid0_task1_output_u[tableIdx++].address = (MemUnit_T *) dataAddress; } { void * dataAddress = (void *) &(bms_f4_U.FromPlant.BMSContactorModuleData.VCharger); xil_fcnid0_task1_output_u[tableIdx].memUnitLength = 1 * sizeof(real_T); xil_fcnid0_task1_output_u[tableIdx++].address = (MemUnit_T *) dataAddress; } { void * dataAddress = (void *) &(bms_f4_U.FromPlant.BMSContactorModuleData.VInverter); xil_fcnid0_task1_output_u[tableIdx].memUnitLength = 1 * sizeof(real_T); xil_fcnid0_task1_output_u[tableIdx++].address = (MemUnit_T *) dataAddress; } { void * dataAddress = (void *) &(bms_f4_U.FromPlant.BMSContactorModuleData.ICharger); xil_fcnid0_task1_output_u[tableIdx].memUnitLength = 1 * sizeof(real_T); xil_fcnid0_task1_output_u[tableIdx++].address = (MemUnit_T *) dataAddress; } { void * dataAddress = (void *) &(bms_f4_U.FromPlant.BMSContactorModuleData.IInverter); xil_fcnid0_task1_output_u[tableIdx].memUnitLength = 1 * sizeof(real_T); xil_fcnid0_task1_output_u[tableIdx++].address = (MemUnit_T *) dataAddress; } { void * dataAddress = (void *) &(bms_f4_U.FromPlant.BMSContactorModuleData.IBatt); xil_fcnid0_task1_output_u[tableIdx].memUnitLength = 1 * sizeof(real_T); xil_fcnid0_task1_output_u[tableIdx++].address = (MemUnit_T *) dataAddress; } { void * dataAddress = (void *) &(bms_f4_U.FromPlant.BMSContactorModuleData.VBatt); xil_fcnid0_task1_output_u[tableIdx].memUnitLength = 1 * sizeof(real_T); xil_fcnid0_task1_output_u[tableIdx++].address = (MemUnit_T *) dataAddress; } { void * dataAddress = (void *) &(bms_f4_U.InputSimulationBus.SimulationSystemInput.SystemState); xil_fcnid0_task1_output_u[tableIdx].memUnitLength = 1 * sizeof (SystemState_t); xil_fcnid0_task1_output_u[tableIdx++].address = (MemUnit_T *) dataAddress; } { void * dataAddress = (void *) &(bms_f4_U.InputSimulationBus.SimulationSystemInput.DrivingCurrentRqst); xil_fcnid0_task1_output_u[tableIdx].memUnitLength = 1 * sizeof(real_T); xil_fcnid0_task1_output_u[tableIdx++].address = (MemUnit_T *) dataAddress; } { void * dataAddress = (void *) &(bms_f4_U.InputSimulationBus.SimulationSystemInput.ChargingCurrentRequest); xil_fcnid0_task1_output_u[tableIdx].memUnitLength = 1 * sizeof(real_T); xil_fcnid0_task1_output_u[tableIdx++].address = (MemUnit_T *) dataAddress; } { void * dataAddress = (void *) &(bms_f4_U.InputSimulationBus.SimulationBatteryPackInput.ShortCircuitInjection [0]); xil_fcnid0_task1_output_u[tableIdx].memUnitLength = 30 * sizeof (boolean_T); xil_fcnid0_task1_output_u[tableIdx++].address = (MemUnit_T *) dataAddress; } { void * dataAddress = (void *) &(bms_f4_U.InputSimulationBus.SimulationBatteryPackInput.OpenCircuitInjection [0]); xil_fcnid0_task1_output_u[tableIdx].memUnitLength = 30 * sizeof (boolean_T); xil_fcnid0_task1_output_u[tableIdx++].address = (MemUnit_T *) dataAddress; } xil_fcnid0_task1_output_u[tableIdx].memUnitLength = 0; xil_fcnid0_task1_output_u[tableIdx++].address = (MemUnit_T *) 0; initComplete = 1; } /* if */ *xilIOData = &xil_fcnid0_task1_output_u[0]; break; } default: errorCode = XIL_INTERFACE_UNKNOWN_TID; break; } UNUSED_PARAMETER(xilCommandIdx); return errorCode; } XIL_INTERFACE_ERROR_CODE xilGetTargetToHostPreData(uint32_T xilFcnId, XIL_COMMAND_TYPE_ENUM xilCommandType, uint32_T xilCommandIdx, XILIOData ** xilIOData, MemUnit_T responseId, uint32_T serverFcnId) { XIL_INTERFACE_ERROR_CODE errorCode = XIL_INTERFACE_SUCCESS; *xilIOData = 0; if (xilFcnId!= 0) { errorCode = XIL_INTERFACE_UNKNOWN_FCNID; return errorCode; } /* if */ errorCode = XIL_INTERFACE_UNKNOWN_TID; UNUSED_PARAMETER(xilCommandType); UNUSED_PARAMETER(xilCommandIdx); UNUSED_PARAMETER(responseId); UNUSED_PARAMETER(serverFcnId); return errorCode; } XIL_INTERFACE_ERROR_CODE xilOutput(uint32_T xilFcnId, uint32_T xilTID) { /* Single In-the-Loop Component */ if (xilFcnId!= 0) { return XIL_INTERFACE_UNKNOWN_FCNID; } switch (xilTID) { case 1: taskTimeStart_bms_f4(2U); bms_f4_step(); taskTimeEnd_bms_f4(2U); break; default: return XIL_INTERFACE_UNKNOWN_TID; } StepCompletedEvent(); return XIL_INTERFACE_SUCCESS; } XIL_INTERFACE_ERROR_CODE xilUpdate(uint32_T xilFcnId, uint32_T xilTID) { /* Single In-the-Loop Component */ if (xilFcnId!= 0) { return XIL_INTERFACE_UNKNOWN_FCNID; } /* No Update Function */ UNUSED_PARAMETER(xilTID); return XIL_INTERFACE_SUCCESS; } XIL_INTERFACE_ERROR_CODE xilGetTargetToHostData(uint32_T xilFcnId, XIL_COMMAND_TYPE_ENUM xilCommandType, uint32_T xilCommandIdx, XILIOData ** xilIOData, MemUnit_T responseId, uint32_T serverFcnId) { XIL_INTERFACE_ERROR_CODE errorCode = XIL_INTERFACE_SUCCESS; /* Single In-the-Loop Component */ *xilIOData = 0; if (xilFcnId!= 0) { errorCode = XIL_INTERFACE_UNKNOWN_FCNID; return errorCode; } switch (xilCommandType) { case XIL_INITIALIZE_COMMAND: { static int initComplete = 0; if (!initComplete) { uint32_T tableIdx = 0; { void * dataAddress = (void *) &(bms_f4_Y.ToPlant.BMSContactorModuleCmd.ContactorCmd[0]); xil_fcnid0_init_y[tableIdx].memUnitLength = 3 * sizeof(real_T); xil_fcnid0_init_y[tableIdx++].address = (MemUnit_T *) dataAddress; } { void * dataAddress = (void *) &(bms_f4_Y.ToPlant.BMSContactorModuleCmd.PreChrgCmd[0]); xil_fcnid0_init_y[tableIdx].memUnitLength = 2 * sizeof(real_T); xil_fcnid0_init_y[tableIdx++].address = (MemUnit_T *) dataAddress; } { void * dataAddress = (void *) &(bms_f4_Y.ToPlant.BMSContactorModuleCmd.DisChrgCmd[0]); xil_fcnid0_init_y[tableIdx].memUnitLength = 2 * sizeof(real_T); xil_fcnid0_init_y[tableIdx++].address = (MemUnit_T *) dataAddress; } { void * dataAddress = (void *) &(bms_f4_Y.ToPlant.BMSContactorModuleCmd.DrivetrainEn[0]); xil_fcnid0_init_y[tableIdx].memUnitLength = 2 * sizeof(real_T); xil_fcnid0_init_y[tableIdx++].address = (MemUnit_T *) dataAddress; } { void * dataAddress = (void *) &(bms_f4_Y.ToPlant.BMSBatteryPackInput.BalCmdVector[0]); xil_fcnid0_init_y[tableIdx].memUnitLength = 30 * sizeof(boolean_T); xil_fcnid0_init_y[tableIdx++].address = (MemUnit_T *) dataAddress; } { void * dataAddress = (void *) &(bms_f4_Y.ToPlant.BMSBatteryPackInput.balancingDeltaVCell[0]); xil_fcnid0_init_y[tableIdx].memUnitLength = 3 * sizeof(real_T); xil_fcnid0_init_y[tableIdx++].address = (MemUnit_T *) dataAddress; } { void * dataAddress = (void *) &(bms_f4_Y.ToPlant.BMSBatteryPackInput.balancingFlags[0]); xil_fcnid0_init_y[tableIdx].memUnitLength = 3 * sizeof(boolean_T); xil_fcnid0_init_y[tableIdx++].address = (MemUnit_T *) dataAddress; } { void * dataAddress = (void *) &(bms_f4_Y.ToPlant.BusSOCEstimation.EKFEstimation[0]); xil_fcnid0_init_y[tableIdx].memUnitLength = 30 * sizeof(real_T); xil_fcnid0_init_y[tableIdx++].address = (MemUnit_T *) dataAddress; } { void * dataAddress = (void *) &(bms_f4_Y.ToPlant.BusSOCEstimation.CDCEstimation[0]); xil_fcnid0_init_y[tableIdx].memUnitLength = 30 * sizeof(real_T); xil_fcnid0_init_y[tableIdx++].address = (MemUnit_T *) dataAddress; } { void * dataAddress = (void *) &(bms_f4_Y.ToPlant.BMSFaultOutput.OverCurrentWarning); xil_fcnid0_init_y[tableIdx].memUnitLength = 1 * sizeof(boolean_T); xil_fcnid0_init_y[tableIdx++].address = (MemUnit_T *) dataAddress; } { void * dataAddress = (void *) &(bms_f4_Y.ToPlant.BMSFaultOutput.OverCurrentFault); xil_fcnid0_init_y[tableIdx].memUnitLength = 1 * sizeof(boolean_T); xil_fcnid0_init_y[tableIdx++].address = (MemUnit_T *) dataAddress; } { void * dataAddress = (void *) &(bms_f4_Y.ToPlant.BMSFaultOutput.OverTemperatureWarning); xil_fcnid0_init_y[tableIdx].memUnitLength = 1 * sizeof(boolean_T); xil_fcnid0_init_y[tableIdx++].address = (MemUnit_T *) dataAddress; } { void * dataAddress = (void *) &(bms_f4_Y.ToPlant.BMSFaultOutput.OverTemperatureFault); xil_fcnid0_init_y[tableIdx].memUnitLength = 1 * sizeof(boolean_T); xil_fcnid0_init_y[tableIdx++].address = (MemUnit_T *) dataAddress; } { void * dataAddress = (void *) &(bms_f4_Y.ToPlant.BMSFaultOutput.OverVoltageWarning); xil_fcnid0_init_y[tableIdx].memUnitLength = 1 * sizeof(boolean_T); xil_fcnid0_init_y[tableIdx++].address = (MemUnit_T *) dataAddress; } { void * dataAddress = (void *) &(bms_f4_Y.ToPlant.BMSFaultOutput.OverVoltageFault); xil_fcnid0_init_y[tableIdx].memUnitLength = 1 * sizeof(boolean_T); xil_fcnid0_init_y[tableIdx++].address = (MemUnit_T *) dataAddress; } { void * dataAddress = (void *) &(bms_f4_Y.ToPlant.BMSFaultOutput.UnderVoltageWarning); xil_fcnid0_init_y[tableIdx].memUnitLength = 1 * sizeof(boolean_T); xil_fcnid0_init_y[tableIdx++].address = (MemUnit_T *) dataAddress; } { void * dataAddress = (void *) &(bms_f4_Y.ToPlant.BMSFaultOutput.UnderVoltageFault); xil_fcnid0_init_y[tableIdx].memUnitLength = 1 * sizeof(boolean_T); xil_fcnid0_init_y[tableIdx++].address = (MemUnit_T *) dataAddress; } xil_fcnid0_init_y[tableIdx].memUnitLength = 0; xil_fcnid0_init_y[tableIdx++].address = (MemUnit_T *) 0; initComplete = 1; } /* if */ { if (xilWriteData(&responseId, sizeof(responseId))!= XIL_DATA_STREAM_SUCCESS) { return XIL_INTERFACE_COMMS_FAILURE; } /* if */ if (responseId == XIL_RESPONSE_CS_REQUEST_SERVICE) { if (xilWriteData((MemUnit_T *) &serverFcnId, sizeof(serverFcnId))!= XIL_DATA_STREAM_SUCCESS) { return XIL_INTERFACE_COMMS_FAILURE; } /* if */ } /* if */ } *xilIOData = &xil_fcnid0_init_y[0]; break; } case XIL_OUTPUT_COMMAND: { static int initComplete = 0; if (!initComplete) { uint32_T tableIdx = 0; { void * dataAddress = (void *) &(bms_f4_Y.ToPlant.BMSContactorModuleCmd.ContactorCmd[0]); xil_fcnid0_task1_y[tableIdx].memUnitLength = 3 * sizeof(real_T); xil_fcnid0_task1_y[tableIdx++].address = (MemUnit_T *) dataAddress; } { void * dataAddress = (void *) &(bms_f4_Y.ToPlant.BMSContactorModuleCmd.PreChrgCmd[0]); xil_fcnid0_task1_y[tableIdx].memUnitLength = 2 * sizeof(real_T); xil_fcnid0_task1_y[tableIdx++].address = (MemUnit_T *) dataAddress; } { void * dataAddress = (void *) &(bms_f4_Y.ToPlant.BMSContactorModuleCmd.DisChrgCmd[0]); xil_fcnid0_task1_y[tableIdx].memUnitLength = 2 * sizeof(real_T); xil_fcnid0_task1_y[tableIdx++].address = (MemUnit_T *) dataAddress; } { void * dataAddress = (void *) &(bms_f4_Y.ToPlant.BMSContactorModuleCmd.DrivetrainEn[0]); xil_fcnid0_task1_y[tableIdx].memUnitLength = 2 * sizeof(real_T); xil_fcnid0_task1_y[tableIdx++].address = (MemUnit_T *) dataAddress; } { void * dataAddress = (void *) &(bms_f4_Y.ToPlant.BMSBatteryPackInput.BalCmdVector[0]); xil_fcnid0_task1_y[tableIdx].memUnitLength = 30 * sizeof(boolean_T); xil_fcnid0_task1_y[tableIdx++].address = (MemUnit_T *) dataAddress; } { void * dataAddress = (void *) &(bms_f4_Y.ToPlant.BMSBatteryPackInput.balancingDeltaVCell[0]); xil_fcnid0_task1_y[tableIdx].memUnitLength = 3 * sizeof(real_T); xil_fcnid0_task1_y[tableIdx++].address = (MemUnit_T *) dataAddress; } { void * dataAddress = (void *) &(bms_f4_Y.ToPlant.BMSBatteryPackInput.balancingFlags[0]); xil_fcnid0_task1_y[tableIdx].memUnitLength = 3 * sizeof(boolean_T); xil_fcnid0_task1_y[tableIdx++].address = (MemUnit_T *) dataAddress; } { void * dataAddress = (void *) &(bms_f4_Y.ToPlant.BusSOCEstimation.EKFEstimation[0]); xil_fcnid0_task1_y[tableIdx].memUnitLength = 30 * sizeof(real_T); xil_fcnid0_task1_y[tableIdx++].address = (MemUnit_T *) dataAddress; } { void * dataAddress = (void *) &(bms_f4_Y.ToPlant.BusSOCEstimation.CDCEstimation[0]); xil_fcnid0_task1_y[tableIdx].memUnitLength = 30 * sizeof(real_T); xil_fcnid0_task1_y[tableIdx++].address = (MemUnit_T *) dataAddress; } { void * dataAddress = (void *) &(bms_f4_Y.ToPlant.BMSFaultOutput.OverCurrentWarning); xil_fcnid0_task1_y[tableIdx].memUnitLength = 1 * sizeof(boolean_T); xil_fcnid0_task1_y[tableIdx++].address = (MemUnit_T *) dataAddress; } { void * dataAddress = (void *) &(bms_f4_Y.ToPlant.BMSFaultOutput.OverCurrentFault); xil_fcnid0_task1_y[tableIdx].memUnitLength = 1 * sizeof(boolean_T); xil_fcnid0_task1_y[tableIdx++].address = (MemUnit_T *) dataAddress; } { void * dataAddress = (void *) &(bms_f4_Y.ToPlant.BMSFaultOutput.OverTemperatureWarning); xil_fcnid0_task1_y[tableIdx].memUnitLength = 1 * sizeof(boolean_T); xil_fcnid0_task1_y[tableIdx++].address = (MemUnit_T *) dataAddress; } { void * dataAddress = (void *) &(bms_f4_Y.ToPlant.BMSFaultOutput.OverTemperatureFault); xil_fcnid0_task1_y[tableIdx].memUnitLength = 1 * sizeof(boolean_T); xil_fcnid0_task1_y[tableIdx++].address = (MemUnit_T *) dataAddress; } { void * dataAddress = (void *) &(bms_f4_Y.ToPlant.BMSFaultOutput.OverVoltageWarning); xil_fcnid0_task1_y[tableIdx].memUnitLength = 1 * sizeof(boolean_T); xil_fcnid0_task1_y[tableIdx++].address = (MemUnit_T *) dataAddress; } { void * dataAddress = (void *) &(bms_f4_Y.ToPlant.BMSFaultOutput.OverVoltageFault); xil_fcnid0_task1_y[tableIdx].memUnitLength = 1 * sizeof(boolean_T); xil_fcnid0_task1_y[tableIdx++].address = (MemUnit_T *) dataAddress; } { void * dataAddress = (void *) &(bms_f4_Y.ToPlant.BMSFaultOutput.UnderVoltageWarning); xil_fcnid0_task1_y[tableIdx].memUnitLength = 1 * sizeof(boolean_T); xil_fcnid0_task1_y[tableIdx++].address = (MemUnit_T *) dataAddress; } { void * dataAddress = (void *) &(bms_f4_Y.ToPlant.BMSFaultOutput.UnderVoltageFault); xil_fcnid0_task1_y[tableIdx].memUnitLength = 1 * sizeof(boolean_T); xil_fcnid0_task1_y[tableIdx++].address = (MemUnit_T *) dataAddress; } xil_fcnid0_task1_y[tableIdx].memUnitLength = 0; xil_fcnid0_task1_y[tableIdx++].address = (MemUnit_T *) 0; initComplete = 1; } /* if */ { if (xilWriteData(&responseId, sizeof(responseId))!= XIL_DATA_STREAM_SUCCESS) { return XIL_INTERFACE_COMMS_FAILURE; } /* if */ if (responseId == XIL_RESPONSE_CS_REQUEST_SERVICE) { if (xilWriteData((MemUnit_T *) &serverFcnId, sizeof(serverFcnId))!= XIL_DATA_STREAM_SUCCESS) { return XIL_INTERFACE_COMMS_FAILURE; } /* if */ } /* if */ } *xilIOData = &xil_fcnid0_task1_y[0]; break; } default: errorCode = XIL_INTERFACE_UNKNOWN_TID; break; } UNUSED_PARAMETER(xilCommandIdx); UNUSED_PARAMETER(responseId); UNUSED_PARAMETER(serverFcnId); return errorCode; } XIL_INTERFACE_ERROR_CODE xilTerminate(uint32_T xilFcnId) { if (xilFcnId!= 0) { return XIL_INTERFACE_UNKNOWN_FCNID; } /* if */ /* Invoke any terminate Function */ taskTimeStart_bms_f4(3U); bms_f4_terminate(); taskTimeEnd_bms_f4(3U); TerminateEvent(); return XIL_INTERFACE_SUCCESS; } XIL_INTERFACE_ERROR_CODE xilEnable(uint32_T xilFcnId, uint32_T xilTID) { /* Single In-the-Loop Component */ if (xilFcnId!= 0) { return XIL_INTERFACE_UNKNOWN_FCNID; } UNUSED_PARAMETER(xilTID); /* No Enable Function - this function should never be called */ return XIL_INTERFACE_UNKNOWN_TID; } XIL_INTERFACE_ERROR_CODE xilDisable(uint32_T xilFcnId, uint32_T xilTID) { /* Single In-the-Loop Component */ if (xilFcnId!= 0) { return XIL_INTERFACE_UNKNOWN_FCNID; } UNUSED_PARAMETER(xilTID); /* No Disable Function - this function should never be called */ return XIL_INTERFACE_UNKNOWN_TID; } ======================= File: workspace/bms_ert_rtw/bms.h ======================= <filename>workspace/bms_ert_rtw/bms.h /* * Academic License - for use in teaching, academic research, and meeting * course requirements at degree granting institutions only. Not for * government, commercial, or other organizational use. * * File: bms.h * * Code generated for Simulink model 'bms'. * * Model version : 1.27 * Simulink Coder version : 9.5 (R2021a) 14-Nov-2020 * C/C++ source code generated on : Sat May 29 15:36:42 2021 * * Target selection: ert.tlc * Embedded hardware selection: Intel->x86-64 (Windows64) * Code generation objectives: Unspecified * Validation result: Not run */ #ifndef RTW_HEADER_bms_h_ #define RTW_HEADER_bms_h_ #include <math.h> #include <string.h> #ifndef bms_COMMON_INCLUDES_ #define bms_COMMON_INCLUDES_ #include "rtwtypes.h" #endif /* bms_COMMON_INCLUDES_ */ #include "bms_types.h" /* Macros for accessing real-time model data structure */ #ifndef rtmGetErrorStatus #define rtmGetErrorStatus(rtm) ((rtm)->errorStatus) #endif #ifndef rtmSetErrorStatus #define rtmSetErrorStatus(rtm, val) ((rtm)->errorStatus = (val)) #endif /* Block states (default storage) for system '<S4>/Chart1' */ typedef struct { uint32_T temporalCounter_i1; /* '<S4>/Chart1' */ uint8_T is_active_c2_bms; /* '<S4>/Chart1' */ uint8_T is_c2_bms; /* '<S4>/Chart1' */ uint8_T is_ON; /* '<S4>/Chart1' */ boolean_T flagBalancingDone; /* '<S4>/Chart1' */ } DW_Chart1_bms_T; /* Block signals (default storage) */ typedef struct { real_T VectorConcatenate1[3]; /* '<S3>/Vector Concatenate1' */ real_T VectorConcatenate[2]; /* '<S3>/Vector Concatenate' */ real_T VectorConcatenate2[2]; /* '<S3>/Vector Concatenate2' */ real_T VectorConcatenate3[2]; /* '<S3>/Vector Concatenate3' */ real_T VectorConcatenate_k[3]; /* '<S4>/Vector Concatenate' */ boolean_T MatrixConcatenate[30]; /* '<S4>/Matrix Concatenate' */ boolean_T VectorConcatenate1_a[3]; /* '<S4>/Vector Concatenate1' */ } B_bms_T; /* Block states (default storage) for system '<Root>' */ typedef struct { real_T DiscreteTimeIntegrator_DSTATE;/* '<S17>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_DSTATE_a;/* '<S8>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_DSTAT_au;/* '<S9>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_DSTATE_m;/* '<S10>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_DSTATE_b;/* '<S11>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_DSTATE_p;/* '<S12>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_DSTATE_c;/* '<S13>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_DSTAT_mh;/* '<S14>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_DSTATE_g;/* '<S15>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_DSTAT_g0;/* '<S16>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_DSTATE_d;/* '<S27>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_DSTAT_b0;/* '<S18>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_DSTAT_dc;/* '<S19>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_DSTATE_o;/* '<S20>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_DSTAT_aw;/* '<S21>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_DSTATE_n;/* '<S22>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_DSTATE_e;/* '<S23>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_DSTATE_f;/* '<S24>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_DSTAT_aj;/* '<S25>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_DSTAT_bc;/* '<S26>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_DSTAT_ps;/* '<S37>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_DSTAT_ed;/* '<S28>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_DSTAT_mg;/* '<S29>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_DSTAT_fy;/* '<S30>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_DSTAT_gd;/* '<S31>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_DSTATE_i;/* '<S32>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_DSTAT_ce;/* '<S33>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_DSTAT_p0;/* '<S34>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_DSTAT_fb;/* '<S35>/Discrete-Time Integrator' */ real_T DiscreteTimeIntegrator_DSTAT_d3;/* '<S36>/Discrete-Time Integrator' */ uint32_T temporalCounter_i1; /* '<S3>/Chart' */ uint8_T is_c1_bms; /* '<S3>/Chart' */ boolean_T isNotInit; /* '<S3>/Chart' */ DW_Chart1_bms_T sf_Chart3; /* '<S4>/Chart3' */ DW_Chart1_bms_T sf_Chart2; /* '<S4>/Chart2' */ DW_Chart1_bms_T sf_Chart1; /* '<S4>/Chart1' */ } DW_bms_T; /* Invariant block signals (default storage) */ typedef struct { const real_T TmpSignalConversionAtTransp[10]; const real_T Transpose[10]; /* '<S5>/Transpose' */ const real_T TmpSignalConversionAtTran_n[10]; const real_T Transpose_p[10]; /* '<S6>/Transpose' */ const real_T TmpSignalConversionAtTran_j[10]; const real_T Transpose_f[10]; /* '<S7>/Transpose' */ const real_T EKFEstimation[30]; /* '<S1>/Matrix Concatenate' */ } ConstB_bms_T; /* Constant parameters (default storage) */ typedef struct { /* Pooled Parameter (Expression: single(LUTBattery_Charge);) * Referenced by: * '<S8>/n-D Lookup Table' * '<S9>/n-D Lookup Table' * '<S10>/n-D Lookup Table' * '<S11>/n-D Lookup Table' * '<S12>/n-D Lookup Table' * '<S13>/n-D Lookup Table' * '<S14>/n-D Lookup Table' * '<S15>/n-D Lookup Table' * '<S16>/n-D Lookup Table' * '<S17>/n-D Lookup Table' * '<S18>/n-D Lookup Table' * '<S19>/n-D Lookup Table' * '<S20>/n-D Lookup Table' * '<S21>/n-D Lookup Table' * '<S22>/n-D Lookup Table' * '<S23>/n-D Lookup Table' * '<S24>/n-D Lookup Table' * '<S25>/n-D Lookup Table' * '<S26>/n-D Lookup Table' * '<S27>/n-D Lookup Table' * '<S28>/n-D Lookup Table' * '<S29>/n-D Lookup Table' * '<S30>/n-D Lookup Table' * '<S31>/n-D Lookup Table' * '<S32>/n-D Lookup Table' * '<S33>/n-D Lookup Table' * '<S34>/n-D Lookup Table' * '<S35>/n-D Lookup Table' * '<S36>/n-D Lookup Table' * '<S37>/n-D Lookup Table' */ real_T pooled7[3]; /* Pooled Parameter (Expression: single(LUTBattery_Charge_Temp);) * Referenced by: * '<S8>/n-D Lookup Table' * '<S9>/n-D Lookup Table' * '<S10>/n-D Lookup Table' * '<S11>/n-D Lookup Table' * '<S12>/n-D Lookup Table' * '<S13>/n-D Lookup Table' * '<S14>/n-D Lookup Table' * '<S15>/n-D Lookup Table' * '<S16>/n-D Lookup Table' * '<S17>/n-D Lookup Table' * '<S18>/n-D Lookup Table' * '<S19>/n-D Lookup Table' * '<S20>/n-D Lookup Table' * '<S21>/n-D Lookup Table' * '<S22>/n-D Lookup Table' * '<S23>/n-D Lookup Table' * '<S24>/n-D Lookup Table' * '<S25>/n-D Lookup Table' * '<S26>/n-D Lookup Table' * '<S27>/n-D Lookup Table' * '<S28>/n-D Lookup Table' * '<S29>/n-D Lookup Table' * '<S30>/n-D Lookup Table' * '<S31>/n-D Lookup Table' * '<S32>/n-D Lookup Table' * '<S33>/n-D Lookup Table' * '<S34>/n-D Lookup Table' * '<S35>/n-D Lookup Table' * '<S36>/n-D Lookup Table' * '<S37>/n-D Lookup Table' */ real_T pooled8[3]; } ConstP_bms_T; /* External inputs (root inport signals with default storage) */ typedef struct { BusInputBMS FromPlant; /* '<Root>/FromPlant' */ BusSimulationInput InputSimulationBus;/* '<Root>/InputSimulationBus' */ } ExtU_bms_T; /* External outputs (root outports fed by signals with default storage) */ typedef struct { BusOutputBMS ToPlant; /* '<Root>/ToPlant' */ } ExtY_bms_T; /* Real-time Model Data Structure */ struct tag_RTM_bms_T { const char_T * volatile errorStatus; }; /* Block signals (default storage) */ extern B_bms_T bms_B; /* Block states (default storage) */ extern DW_bms_T bms_DW; /* External inputs (root inport signals with default storage) */ extern ExtU_bms_T bms_U; /* External outputs (root outports fed by signals with default storage) */ extern ExtY_bms_T bms_Y; extern const ConstB_bms_T bms_ConstB; /* constant block i/o */ /* Constant parameters (default storage) */ extern const ConstP_bms_T bms_ConstP; /* Model entry point functions */ extern void bms_initialize(void); extern void bms_step(void); extern void bms_terminate(void); /* Real-time Model object */ extern RT_MODEL_bms_T *const bms_M; /*- * These blocks were eliminated from the model due to optimizations: * * Block '<S1>/Selector3' : Unused code path elimination * Block '<S1>/Selector6' : Unused code path elimination * Block '<S1>/Selector9' : Unused code path elimination * Block '<S3>/Data Type Conversion' : Eliminate redundant data type conversion * Block '<S3>/Data Type Conversion1' : Eliminate redundant data type conversion * Block '<S3>/Data Type Conversion2' : Eliminate redundant data type conversion * Block '<S3>/Data Type Conversion3' : Eliminate redundant data type conversion */ /*- * The generated code includes comments that allow you to trace directly * back to the appropriate location in the model. The basic format * is <system>/block_name, where system is the system number (uniquely * assigned by Simulink) and block_name is the name of the block. * * Use the MATLAB hilite_system command to trace the generated code back * to the model. For example, * * hilite_system('<S3>') - opens system 3 * hilite_system('<S3>/Kp') - opens and selects block Kp which resides in S3 * * Here is the system hierarchy for this model * * '<Root>' : 'bms' * '<S1>' : 'bms/PackSOC' * '<S2>' : 'bms/Subsystem' * '<S3>' : 'bms/Subsystem Reference' * '<S4>' : 'bms/Subsystem Reference1' * '<S5>' : 'bms/PackSOC/Subsystem' * '<S6>' : 'bms/PackSOC/Subsystem1' * '<S7>' : 'bms/PackSOC/Subsystem2' * '<S8>' : 'bms/PackSOC/Subsystem/Subsystem Reference1' * '<S9>' : 'bms/PackSOC/Subsystem/Subsystem Reference2' * '<S10>' : 'bms/PackSOC/Subsystem/Subsystem Reference24' * '<S11>' : 'bms/PackSOC/Subsystem/Subsystem Reference25' * '<S12>' : 'bms/PackSOC/Subsystem/Subsystem Reference26' * '<S13>' : 'bms/PackSOC/Subsystem/Subsystem Reference27' * '<S14>' : 'bms/PackSOC/Subsystem/Subsystem Reference28' * '<S15>' : 'bms/PackSOC/Subsystem/Subsystem Reference29' * '<S16>' : 'bms/PackSOC/Subsystem/Subsystem Reference30' * '<S17>' : 'bms/PackSOC/Subsystem/Subsystem Reference43' * '<S18>' : 'bms/PackSOC/Subsystem1/Subsystem Reference1' * '<S19>' : 'bms/PackSOC/Subsystem1/Subsystem Reference2' * '<S20>' : 'bms/PackSOC/Subsystem1/Subsystem Reference24' * '<S21>' : 'bms/PackSOC/Subsystem1/Subsystem Reference25' * '<S22>' : 'bms/PackSOC/Subsystem1/Subsystem Reference26' * '<S23>' : 'bms/PackSOC/Subsystem1/Subsystem Reference27' * '<S24>' : 'bms/PackSOC/Subsystem1/Subsystem Reference28' * '<S25>' : 'bms/PackSOC/Subsystem1/Subsystem Reference29' * '<S26>' : 'bms/PackSOC/Subsystem1/Subsystem Reference30' * '<S27>' : 'bms/PackSOC/Subsystem1/Subsystem Reference43' * '<S28>' : 'bms/PackSOC/Subsystem2/Subsystem Reference1' * '<S29>' : 'bms/PackSOC/Subsystem2/Subsystem Reference2' * '<S30>' : 'bms/PackSOC/Subsystem2/Subsystem Reference24' * '<S31>' : 'bms/PackSOC/Subsystem2/Subsystem Reference25' * '<S32>' : 'bms/PackSOC/Subsystem2/Subsystem Reference26' * '<S33>' : 'bms/PackSOC/Subsystem2/Subsystem Reference27' * '<S34>' : 'bms/PackSOC/Subsystem2/Subsystem Reference28' * '<S35>' : 'bms/PackSOC/Subsystem2/Subsystem Reference29' * '<S36>' : 'bms/PackSOC/Subsystem2/Subsystem Reference30' * '<S37>' : 'bms/PackSOC/Subsystem2/Subsystem Reference43' * '<S38>' : 'bms/Subsystem/Compare To Constant' * '<S39>' : 'bms/Subsystem/Compare To Constant1' * '<S40>' : 'bms/Subsystem/Compare To Constant2' * '<S41>' : 'bms/Subsystem/Compare To Constant3' * '<S42>' : 'bms/Subsystem/Compare To Constant4' * '<S43>' : 'bms/Subsystem/Compare To Constant5' * '<S44>' : 'bms/Subsystem/Compare To Constant6' * '<S45>' : 'bms/Subsystem/Compare To Constant7' * '<S46>' : 'bms/Subsystem Reference/Chart' * '<S47>' : 'bms/Subsystem Reference1/Chart1' * '<S48>' : 'bms/Subsystem Reference1/Chart2' * '<S49>' : 'bms/Subsystem Reference1/Chart3' */ #endif /* RTW_HEADER_bms_h_ */ /* * File trailer for generated code. * * [EOF] */ ======================= File: workspace/bms_f4_ert_rtw/pil/xil_instrumentation.h ======================= <reponame>meltinglab/battery-management /* * File: xil_instrumentation.h * * Code generated for instrumentation. * */ /* Functions with a C call interface */ #ifdef __cplusplus extern "C" { #endif #include "profiler_timer.h" #ifdef __cplusplus } #endif #include "rtwtypes.h" /* Upload code instrumentation data point */ void xilUploadCodeInstrData( void* pData, uint32_T numMemUnits, uint32_T sectionId); /* Called before starting a profiled section of code */ void taskTimeStart(uint32_T); /* Called on finishing a profiled section of code */ void taskTimeEnd(uint32_T); /* Uploads data */ void xilUploadProfilingData(uint32_T sectionId); /* Pause the timer while running code associated with storing and uploading the data. */ void xilProfilingTimerFreeze(void); /* Restart the timer after a pause */ void xilProfilingTimerUnFreeze(void); /* Request upload of metrics evaluated on target */ void captureMode(uint32_T sectionId); /* Update methods */ void captureModeStart(uint32_T sectionId); void captureModeEnd(uint32_T sectionId); /* Code instrumentation method(s) for model bms_f4 */ void taskTimeStart_bms_f4(uint32_T sectionId); void taskTimeEnd_bms_f4(uint32_T sectionId); /* Code instrumentation method(s) for model bms_f4 */ void captureMode_bms_f4(uint32_T sectionId); /* Callback called when the simulation is paused */ void PauseEvent (void); /* Callback called when the simulation ends */ void TerminateEvent (void); /* Callback called when a step ends */ void StepCompletedEvent (void); ======================= File: workspace/bms_f4_ert_rtw/coderassumptions/bms_f4_ca.c ======================= <reponame>meltinglab/battery-management<filename>workspace/bms_f4_ert_rtw/coderassumptions/bms_f4_ca.c /* * File: bms_f4_ca.c * * Abstract: Tests assumptions in the generated code. */ #include "bms_f4_ca.h" CA_HWImpl_TestResults CA_bms_f4_HWRes; CA_PWS_TestResults CA_bms_f4_PWSRes; const CA_HWImpl CA_bms_f4_ExpHW = { 8, /* BitPerChar */ 16, /* BitPerShort */ 32, /* BitPerInt */ 32, /* BitPerLong */ 64, /* BitPerLongLong */ 32, /* BitPerFloat */ 64, /* BitPerDouble */ 32, /* BitPerPointer */ 32, /* BitPerSizeT */ 32, /* BitPerPtrDiffT */ CA_LITTLE_ENDIAN, /* Endianess */ CA_ZERO, /* IntDivRoundTo */ 1, /* ShiftRightIntArith */ 0, /* LongLongMode */ 0, /* PortableWordSizes */ "ARM Compatible->ARM Cortex", /* HWDeviceType */ 0, /* MemoryAtStartup */ 0, /* DynamicMemoryAtStartup */ 0, /* DenormalFlushToZero */ 0 /* DenormalAsZero */ }; CA_HWImpl CA_bms_f4_ActHW; void bms_f4_caRunTests(void) { /* verify hardware implementation */ caVerifyPortableWordSizes(&CA_bms_f4_ActHW, &CA_bms_f4_ExpHW, &CA_bms_f4_PWSRes); caVerifyHWImpl(&CA_bms_f4_ActHW, &CA_bms_f4_ExpHW, &CA_bms_f4_HWRes); } ======================= File: workspace/bms_ert_rtw/bms_data.c ======================= <filename>workspace/bms_ert_rtw/bms_data.c /* * Academic License - for use in teaching, academic research, and meeting * course requirements at degree granting institutions only. Not for * government, commercial, or other organizational use. * * File: bms_data.c * * Code generated for Simulink model 'bms'. * * Model version : 1.27 * Simulink Coder version : 9.5 (R2021a) 14-Nov-2020 * C/C++ source code generated on : Sat May 29 15:36:42 2021 * * Target selection: ert.tlc * Embedded hardware selection: Intel->x86-64 (Windows64) * Code generation objectives: Unspecified * Validation result: Not run */ #include "bms.h" #include "bms_private.h" /* Invariant block signals (default storage) */ const ConstB_bms_T bms_ConstB = { { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 },/* synthesized block */ { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 },/* '<S5>/Transpose' */ { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 },/* synthesized block */ { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 },/* '<S6>/Transpose' */ { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 },/* synthesized block */ { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 },/* '<S7>/Transpose' */ { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }/* '<S1>/Matrix Concatenate' */ }; /* Constant parameters (default storage) */ const ConstP_bms_T bms_ConstP = { /* Pooled Parameter (Expression: single(LUTBattery_Charge);) * Referenced by: * '<S8>/n-D Lookup Table' * '<S9>/n-D Lookup Table' * '<S10>/n-D Lookup Table' * '<S11>/n-D Lookup Table' * '<S12>/n-D Lookup Table' * '<S13>/n-D Lookup Table' * '<S14>/n-D Lookup Table' * '<S15>/n-D Lookup Table' * '<S16>/n-D Lookup Table' * '<S17>/n-D Lookup Table' * '<S18>/n-D Lookup Table' * '<S19>/n-D Lookup Table' * '<S20>/n-D Lookup Table' * '<S21>/n-D Lookup Table' * '<S22>/n-D Lookup Table' * '<S23>/n-D Lookup Table' * '<S24>/n-D Lookup Table' * '<S25>/n-D Lookup Table' * '<S26>/n-D Lookup Table' * '<S27>/n-D Lookup Table' * '<S28>/n-D Lookup Table' * '<S29>/n-D Lookup Table' * '<S30>/n-D Lookup Table' * '<S31>/n-D Lookup Table' * '<S32>/n-D Lookup Table' * '<S33>/n-D Lookup Table' * '<S34>/n-D Lookup Table' * '<S35>/n-D Lookup Table' * '<S36>/n-D Lookup Table' * '<S37>/n-D Lookup Table' */ { 2.4100000858306885, 2.3900001049041748, 2.2999999523162842 }, /* Pooled Parameter (Expression: single(LUTBattery_Charge_Temp);) * Referenced by: * '<S8>/n-D Lookup Table' * '<S9>/n-D Lookup Table' * '<S10>/n-D Lookup Table' * '<S11>/n-D Lookup Table' * '<S12>/n-D Lookup Table' * '<S13>/n-D Lookup Table' * '<S14>/n-D Lookup Table' * '<S15>/n-D Lookup Table' * '<S16>/n-D Lookup Table' * '<S17>/n-D Lookup Table' * '<S18>/n-D Lookup Table' * '<S19>/n-D Lookup Table' * '<S20>/n-D Lookup Table' * '<S21>/n-D Lookup Table' * '<S22>/n-D Lookup Table' * '<S23>/n-D Lookup Table' * '<S24>/n-D Lookup Table' * '<S25>/n-D Lookup Table' * '<S26>/n-D Lookup Table' * '<S27>/n-D Lookup Table' * '<S28>/n-D Lookup Table' * '<S29>/n-D Lookup Table' * '<S30>/n-D Lookup Table' * '<S31>/n-D Lookup Table' * '<S32>/n-D Lookup Table' * '<S33>/n-D Lookup Table' * '<S34>/n-D Lookup Table' * '<S35>/n-D Lookup Table' * '<S36>/n-D Lookup Table' * '<S37>/n-D Lookup Table' */ { 278.14999389648438, 293.14999389648438, 323.14999389648438 } }; /* * File trailer for generated code. * * [EOF] */ ======================= File: workspace/bms_f4_ert_rtw/coderassumptions/coder_assumptions.h ======================= /* * File: coder_assumptions.h * * Abstract: Coder assumptions header file */ #ifndef CODER_ASSUMPTIONS_H #define CODER_ASSUMPTIONS_H /* include model specific checks */ #include "bms_f4_ca.h" /* global results variable mapping for static code */ #define CA_Expected_HWImpl CA_bms_f4_ExpHW #define CA_Actual_HWImpl CA_bms_f4_ActHW #define CA_HWImpl_Results CA_bms_f4_HWRes #define CA_PortableWordSizes_Results CA_bms_f4_PWSRes /* entry point function mapping for static code */ #define CA_Run_Tests bms_f4_caRunTests #endif /* CODER_ASSUMPTIONS_H */ ======================= File: workspace/bms_f4_ert_rtw/coderassumptions/bms_f4_ca.h ======================= /* * File: bms_f4_ca.h * * Abstract: Tests assumptions in the generated code. */ #ifndef BMS_F4_CA_H #define BMS_F4_CA_H /* preprocessor validation checks */ #include "bms_f4_ca_preproc.h" #include "coder_assumptions_hwimpl.h" /* variables holding test results */ extern CA_HWImpl_TestResults CA_bms_f4_HWRes; extern CA_PWS_TestResults CA_bms_f4_PWSRes; /* variables holding "expected" and "actual" hardware implementation */ extern const CA_HWImpl CA_bms_f4_ExpHW; extern CA_HWImpl CA_bms_f4_ActHW; /* entry point function to run tests */ void bms_f4_caRunTests(void); #endif /* BMS_F4_CA_H */ ======================= File: workspace/bms_f4_ert_rtw/pil/bms_f4_pbs.c ======================= <filename>workspace/bms_f4_ert_rtw/pil/bms_f4_pbs.c /* * bms_f4_pbs.c * * Automatically generated s-function with I/O interface for: * Component: bms_f4 * Component Simulink Path: bms_f4 * Simulation Mode: PIL * */ #define S_FUNCTION_NAME bms_f4_pbs #define S_FUNCTION_LEVEL 2 #if!defined(RTW_GENERATED_S_FUNCTION) #define RTW_GENERATED_S_FUNCTION #endif #include <stdio.h> #include <string.h> #include "simstruc.h" #include "simtarget/slMdlrefSimTargetCoreHeaders.h" #include "simtarget/slMdlrefSimTargetInstrumentationHeaders.h" #include "fixedpoint.h" #include "coder/connectivity_core/xilutils/xilutils.h" #include "coder/simulinkcoder/xilutils_sl/xilutils_sl.h" #include "rtiostream_utils.h" #include "coder/connectivity/xilcomms_rtiostream/xilcomms_rtiostream.h" #include "coder/connectivity/XILHostAppSvc/XILHostAppSvc_CInterface.h" #include "messages/slMessagesSfcnBridge.h" #include "strings/slStringSfcnAPI.h" #include "mwstringutil.h" #include "coder/connectivity/CodeInstrHostAppSvc/CodeInstrHostAppSvc_CInterface.h" #include "coder/connectivity/CoderAssumpHostAppSvc/CoderAssumpHostAppSvc_CInterface.h" static real_T rtInf; static real_T rtMinusInf; /* Response case labels */ enum ResponseIDs { RESPONSE_ERROR = 0, RESPONSE_OUTPUT_PRE_DATA = 1, RESPONSE_OUTPUT_DATA = 2, RESPONSE_PRINTF = 3, RESPONSE_FOPEN = 4, RESPONSE_FPRINTF = 5, RESPONSE_SIGNAL_RAISED = 6 }; typedef struct { FILE ** Fd; mwSize size; int32_T fidOffset; } targetIOFd_T; typedef enum { XIL_INIT_COMMAND = 0, XIL_INITIALIZE_COMMAND, XIL_SYSTEM_INITIALIZE_COMMAND, XIL_OUTPUT_COMMAND, XIL_TERMINATE_COMMAND, XIL_ENABLE_COMMAND, XIL_DISABLE_COMMAND, XIL_CONST_OUTPUT_COMMAND, XIL_PROCESS_PARAMS_COMMAND, XIL_CLIENT_SERVER_COMMAND, XIL_SHUTDOWN_COMMAND, XIL_UPDATE_COMMAND, XIL_SYSTEM_RESET_COMMAND, XIL_PAUSE_COMMAND } XIL_COMMAND_TYPE_ENUM; typedef struct { uint16_T bitPattern; } real16_T; static RegMdlInfo rtMdlInfo_bms_f4[1] = { "", MDL_INFO_ID_GLOBAL_RTW_CONSTRUCT, 0, 0, NULL }; static char * getSimulinkBlockPath(SimStruct *S) { char * simulinkBlockPath = NULL; const char * origBlockPath = ssGetPath(S); const char * searchString = "TmpSFcnForModelReference_"; char * searchPtr; size_t origLength, searchAndNameLength, copyAmount; char * secondPart; size_t nameLength; origLength = strlen(origBlockPath); searchPtr = strstr(origBlockPath, searchString); if (searchPtr == NULL) { return simulinkBlockPath; } searchAndNameLength = strlen(searchPtr); copyAmount = origLength - searchAndNameLength; simulinkBlockPath = (char *) mxCalloc((mwSize) (origLength + 1), sizeof(char)); simulinkBlockPath = strncpy(simulinkBlockPath, origBlockPath, copyAmount); simulinkBlockPath[copyAmount] = '\0'; nameLength = searchAndNameLength - strlen(searchString); secondPart = &simulinkBlockPath[copyAmount]; secondPart = strncpy(secondPart, &origBlockPath[origLength - nameLength], nameLength); secondPart[nameLength] = '\0'; return simulinkBlockPath; } static void callStopHookAndFreeSFcnMemory(SimStruct *S); static void mdlTerminate(SimStruct *S); /* grow the buffer for target I/O Fd array * targetIOFd->Fd is NULL on failure */ static void growTargetIOFd(SimStruct *S, targetIOFd_T * IOFd, mwSize requiredSize) { if (IOFd->size < requiredSize) { IOFd->Fd = (FILE**)mxRealloc(IOFd->Fd, requiredSize * sizeof(FILE*)); if (IOFd->Fd == NULL) { ssSetErrorStatus( S,"growTargetIOFd: mxRealloc failed."); } else { mexMakeMemoryPersistent(IOFd->Fd); IOFd->size = requiredSize; } /* if */ } /* if */ } static void closeAndFreeTargetIOFd(SimStruct *S) { int i; if (ssGetPWork(S)!= NULL) { targetIOFd_T * targetIOFdPtr = (targetIOFd_T *) ssGetPWorkValue(S, 3); if (targetIOFdPtr!= NULL) { if (targetIOFdPtr->Fd!= NULL) { for (i=0; i<targetIOFdPtr->size; i++) { if (targetIOFdPtr->Fd[i]!= NULL) { fclose(targetIOFdPtr->Fd[i]); } /* if */ } /* for */ mxFree(targetIOFdPtr->Fd); } /* if */ mxFree(targetIOFdPtr); } /* if */ ssSetPWorkValue(S, 3, NULL); } /* if */ } /* receive one packet of data and dispatch to owning application */ static boolean_T recvData(SimStruct *S, void* pComms) { int * pCommErrorOccurred = (int *) ssGetPWorkValue(S, 4); void * pXILUtils = (void *) ssGetPWorkValue(S, 6); if (pCommErrorOccurred == NULL) { ssSetErrorStatus( S,"pCommErrorOccurred is NULL."); return XILHOSTAPPSVC_ERROR; } /* if */ if (pXILUtils == NULL) { ssSetErrorStatus( S,"pXILUtils is NULL."); return XILHOSTAPPSVC_ERROR; } /* if */ *pCommErrorOccurred = (xilCommsRun(pComms, pXILUtils)!= XILCOMMS_RTIOSTREAM_SUCCESS); return (*pCommErrorOccurred?XILHOSTAPPSVC_ERROR:XILHOSTAPPSVC_SUCCESS); } /* send data via xil comms */ static boolean_T sendData(SimStruct *S, void* pXILService, XIL_IOBuffer_T * IOBuffer, mwSize sendSize) { int * pCommErrorOccurred = (int *) ssGetPWorkValue(S, 4); if (pCommErrorOccurred == NULL) { ssSetErrorStatus( S,"pCommErrorOccurred is NULL."); return XILHOSTAPPSVC_ERROR; } /* if */ *pCommErrorOccurred = (xilHostAppSvcSend(pXILService, IOBuffer->data, sendSize) != XILHOSTAPPSVC_SUCCESS); return (*pCommErrorOccurred?XILHOSTAPPSVC_ERROR:XILHOSTAPPSVC_SUCCESS); } /* implements command dispatch */ static boolean_T commandDispatch(SimStruct *S, XIL_IOBuffer_T* IOBuffer, mwSize dataOutSize) { void * pXILService = (void *) ssGetPWorkValue(S, 9); if (pXILService == NULL) { ssSetErrorStatus( S,"pXILService is NULL!"); return XILHOSTAPPSVC_ERROR; } /* if */ /* send the data */ if (sendData(S, pXILService, IOBuffer, dataOutSize)!= XILHOSTAPPSVC_SUCCESS) { return XILHOSTAPPSVC_ERROR; } /* if */ return XILHOSTAPPSVC_SUCCESS; } /* implements command response */ static boolean_T commandResponse(SimStruct *S, mwSize* dataInSize, XILCommandResponseType* commandType) { void * pXILService = (void *) ssGetPWorkValue(S, 9); if (pXILService == NULL) { ssSetErrorStatus( S,"pXILService is NULL!"); return XILHOSTAPPSVC_ERROR; } /* if */ { /* receive the response data */ uint8_T COMMAND_COMPLETE = 0; void * pComms = (void *) ssGetPWorkValue(S, 7); if (pComms == NULL) { ssSetErrorStatus( S,"pComms is NULL!"); return XILHOSTAPPSVC_ERROR; } /* if */ while (!COMMAND_COMPLETE) { xilHostAppSvcSetIsResponseComplete(pXILService, 0); if (recvData(S, pComms)!= XILHOSTAPPSVC_SUCCESS) { return XILHOSTAPPSVC_ERROR; } /* if */ COMMAND_COMPLETE = xilHostAppSvcGetIsResponseComplete(pXILService); } /* while */ /* determine command response type */ *commandType = (XILCommandResponseType) COMMAND_COMPLETE; *dataInSize = xilHostAppSvcGetPayloadSizeForOneStep(pXILService); return XILHOSTAPPSVC_SUCCESS; } } static void copyIOData(void * const dstPtr, void * const srcPtr, uint8_T ** const tgtPtrPtr, size_t numElements, size_t cTypeSize) { size_t maxBytesConsumed = numElements * cTypeSize; memcpy(dstPtr, srcPtr, maxBytesConsumed); (*tgtPtrPtr)+=(maxBytesConsumed/sizeof(**tgtPtrPtr)); } static void copyStringIOData(void * const dstPtr, void * const srcPtr, uint8_T ** const tgtPtrPtr, size_t numElements, size_t cTypeSize, uint8_T isInput) { size_t maxBytesConsumed = numElements * cTypeSize; if (isInput) { suWriteSILStringInput(dstPtr, (int32_T)numElements, srcPtr); } else { suWriteSILStringOutput(dstPtr, srcPtr, (int32_T)numElements); } /* if */ (*tgtPtrPtr)+=(maxBytesConsumed/sizeof(**tgtPtrPtr)); } /* returns data needed by code instrumentation service */ static CodeInstrServiceData_T* codeInstrServiceData(SimStruct *S, uint8_T memUnitSizeBytes) { CodeInstrServiceData_T* pCodeInstrServiceData = (CodeInstrServiceData_T*) mxCalloc(1, sizeof(CodeInstrServiceData_T)); char * simulinkBlockPath = getSimulinkBlockPath(S); if (simulinkBlockPath == NULL) { ssSetErrorStatus(S, "ModelBlock SIL/PIL unexpected error: getSimulinkBlockPath returned NULL pointer. Check search string was found in ssGetPath.\n"); return NULL; } if (pCodeInstrServiceData == NULL) { ssSetErrorStatus( S, "Error in allocating memory for code instrumentation data through mxCalloc."); return NULL; } /* if */ pCodeInstrServiceData->infoPath = "C:/Users/miche/Documents/GitHub/meltinglab/battery-management/workspace/bms_f4_ert_rtw/pil"; pCodeInstrServiceData->blockPath = simulinkBlockPath; pCodeInstrServiceData->rootModel = ssGetPath(ssGetRootSS(S)); pCodeInstrServiceData->memUnitSize = memUnitSizeBytes; pCodeInstrServiceData->isProfilingEnabled = true; pCodeInstrServiceData->inTheLoopType = 4; pCodeInstrServiceData->silPilInterfaceFcn = "@coder.connectivity.SimulinkInterface.getSILPILInterface"; return pCodeInstrServiceData; } static void callStopHookAndFreeSFcnMemory(SimStruct *S) { closeAndFreeTargetIOFd(S); if (ssGetPWork(S)!= NULL) { int * pCommErrorOccurred = (int *) ssGetPWorkValue(S, 4); int * pIsXILApplicationStarted = (int *) ssGetPWorkValue(S, 5); if ((pIsXILApplicationStarted!= NULL) && (*pIsXILApplicationStarted == 1)) { { void * pXILUtils = (void *) ssGetPWorkValue(S, 6); if (pXILUtils) { mxArray *rhs[3]; char * simulinkBlockPath = getSimulinkBlockPath(S); if (simulinkBlockPath == NULL) { ssSetErrorStatus(S, "ModelBlock SIL/PIL unexpected error: getSimulinkBlockPath returned NULL pointer. Check search string was found in ssGetPath.\n"); return; } rhs[ 0 ] = mxCreateString( "@coder.connectivity.SimulinkInterface.getSILPILInterface"); rhs[ 1 ] = mxCreateDoubleScalar( 4 ); rhs[ 2 ] = mxCreateString(simulinkBlockPath); xilUtilsCallMATLAB(pXILUtils, 0, NULL, 3, rhs, "rtw.pil.SILPILInterface.sfunctionPILStopHook"); mxFree((void *) simulinkBlockPath); } /* if */ } } /* if */ if (pIsXILApplicationStarted!= NULL) { *pIsXILApplicationStarted = 0; } /* if */ } /* if */ if (ssGetPWork(S)!= NULL) { XIL_IOBuffer_T* IOBufferPtr; XIL_RtIOStreamData_T * rtIOStreamDataPtr = (XIL_RtIOStreamData_T *) ssGetPWorkValue(S, 0); SIL_DEBUGGING_DATA_T * silDebuggingDataPtr = (SIL_DEBUGGING_DATA_T *) ssGetPWorkValue(S, 2); if (rtIOStreamDataPtr!= NULL) { { int errorStatus = rtIOStreamUnloadLib(&rtIOStreamDataPtr->libH); if (errorStatus) { ssSetErrorStatus( S,"rtIOStreamUnloadLib failed."); } /* if */ } mxFree(rtIOStreamDataPtr->lib); mxDestroyArray(rtIOStreamDataPtr->MATLABObject); mxFree(rtIOStreamDataPtr); ssSetPWorkValue(S, 0, NULL); } /* if */ if (silDebuggingDataPtr!= NULL) { mxFree(silDebuggingDataPtr->componentBlockPath); mxFree(silDebuggingDataPtr->SILPILInterfaceFcnStr); mxFree(silDebuggingDataPtr); ssSetPWorkValue(S, 2, NULL); } /* if */ IOBufferPtr = (XIL_IOBuffer_T *) ssGetPWorkValue(S, 1); if (IOBufferPtr!= NULL) { mxFree(IOBufferPtr->data); mxFree(IOBufferPtr); ssSetPWorkValue(S, 1, NULL); } /* if */ closeAndFreeTargetIOFd(S); if (ssGetPWork(S)!= NULL) { void * pXILUtils = (void *) ssGetPWorkValue(S, 6); void * pComms = (void *) ssGetPWorkValue(S, 7); void * pXILService = (void *) ssGetPWorkValue(S, 9); void * pCodeInstrService = (void *) ssGetPWorkValue(S, 10); void * pCoderAssumptionsApp = (void *) ssGetPWorkValue(S, 12); if (pCodeInstrService!= NULL) { uint8_T memUnitSizeBytes = 1; CodeInstrServiceData_T* pCodeInstrServiceData = codeInstrServiceData(S, memUnitSizeBytes); codeInstrHostAppSvcDestroy(pCodeInstrService, pCodeInstrServiceData); mxFree((void *)pCodeInstrServiceData->blockPath); mxFree(pCodeInstrServiceData); } /* if */ ssSetPWorkValue(S, 10, NULL); if (pCoderAssumptionsApp!= NULL) { coderAssumpHostAppSvcDestroy(pCoderAssumptionsApp); ssSetPWorkValue(S, 12, NULL); } /* if */ if (pXILService!= NULL) { xilHostAppSvcDestroy(pXILService); ssSetPWorkValue(S, 9, NULL); } /* if */ if (pComms!= NULL) { xilCommsDestroy(pComms); ssSetPWorkValue(S, 7, NULL); } /* if */ } /* if */ } /* if */ } static boolean_T processResponseError(SimStruct * S, uint8_T ** mxMemUnitPtrPtr) { uint8_T errorId = **mxMemUnitPtrPtr; (*mxMemUnitPtrPtr)++; if (errorId) { { void * pXILUtils = (void *) ssGetPWorkValue(S, 6); mxArray * rhs[ 2 ]; rhs[0] = mxCreateString("PIL:pilverification:PILError"); rhs[1] = mxCreateDoubleScalar(errorId); xilUtilsHandleError(pXILUtils, 2, rhs ); return XILHOSTAPPSVC_ERROR; } } /* if */ return XILHOSTAPPSVC_SUCCESS; } static boolean_T processResponsePrintf(SimStruct * S, uint8_T ** mxMemUnitPtrPtr) { const int TARGET_IO_SUCCESS = 0; uint8_T PRINTF_ERROR; uint16_T PRINTF_SIZE; { { uint8_T * simDataMemUnitPtr; simDataMemUnitPtr = (uint8_T *) &PRINTF_ERROR; { size_t num_elements = 1; { copyIOData(simDataMemUnitPtr, *mxMemUnitPtrPtr, &*mxMemUnitPtrPtr, num_elements, sizeof(uint8_T)); } } } } { { uint8_T * simDataMemUnitPtr; simDataMemUnitPtr = (uint8_T *) &PRINTF_SIZE; { size_t num_elements = 1; { copyIOData(simDataMemUnitPtr, *mxMemUnitPtrPtr, &*mxMemUnitPtrPtr, num_elements, sizeof(uint16_T)); } } } } if (PRINTF_ERROR!= TARGET_IO_SUCCESS) { { void * pXILUtils = (void *) ssGetPWorkValue(S, 6); mxArray * rhs[ 2 ]; rhs[0] = mxCreateString("PIL:pil:TargetIOError"); rhs[1] = mxCreateDoubleScalar(PRINTF_ERROR); xilUtilsHandleError(pXILUtils, 2, rhs ); return XILHOSTAPPSVC_ERROR; } } else { uint8_T *pPrintBuff; pPrintBuff = *mxMemUnitPtrPtr; if (pPrintBuff[PRINTF_SIZE-1] == '\0') { mexPrintf("%s", pPrintBuff); } /* if */ } /* if */ (*mxMemUnitPtrPtr) = (*mxMemUnitPtrPtr) + PRINTF_SIZE; return XILHOSTAPPSVC_SUCCESS; } static boolean_T processResponseFopen(SimStruct * S, uint8_T ** mxMemUnitPtrPtr) { uint16_T FOPEN_FID; uint16_T FOPEN_NAME_SIZE; targetIOFd_T *targetIOFdPtr; { { uint8_T * simDataMemUnitPtr; simDataMemUnitPtr = (uint8_T *) &FOPEN_FID; { size_t num_elements = 1; { copyIOData(simDataMemUnitPtr, *mxMemUnitPtrPtr, &*mxMemUnitPtrPtr, num_elements, sizeof(uint16_T)); } } } } { { uint8_T * simDataMemUnitPtr; simDataMemUnitPtr = (uint8_T *) &FOPEN_NAME_SIZE; { size_t num_elements = 1; { copyIOData(simDataMemUnitPtr, *mxMemUnitPtrPtr, &*mxMemUnitPtrPtr, num_elements, sizeof(uint16_T)); } } } } targetIOFdPtr = (targetIOFd_T *) ssGetPWorkValue(S, 3); if (targetIOFdPtr!= NULL) { /* check fid increments by 1 */ if (targetIOFdPtr->fidOffset + 1 == FOPEN_FID) { targetIOFdPtr->fidOffset = FOPEN_FID; growTargetIOFd(S, targetIOFdPtr, targetIOFdPtr->fidOffset + 1); if (targetIOFdPtr->Fd!= NULL) { uint8_T *pFopenBuff; targetIOFdPtr->Fd[targetIOFdPtr->fidOffset] = NULL; pFopenBuff = (*mxMemUnitPtrPtr); if (pFopenBuff[FOPEN_NAME_SIZE-1] == '\0') { FILE * tmpFd = NULL; tmpFd = fopen((char *) pFopenBuff,"w"); if (tmpFd!= NULL) { /* save the file descriptor */ targetIOFdPtr->Fd[targetIOFdPtr->fidOffset] = tmpFd; } else { { void * pXILUtils = (void *) ssGetPWorkValue(S, 6); mxArray * rhs[ 2 ]; rhs[0] = mxCreateString("PIL:pil:TargetIOFopenError"); rhs[1] = mxCreateString((char *) pFopenBuff); xilUtilsHandleError(pXILUtils, 2, rhs ); return XILHOSTAPPSVC_ERROR; } } /* if */ } /* if */ } /* if */ } else { { void * pXILUtils = (void *) ssGetPWorkValue(S, 6); mxArray * rhs[ 2 ]; rhs[0] = mxCreateString("PIL:pil:TargetIOFopenFidError"); rhs[1] = mxCreateDoubleScalar(FOPEN_FID); xilUtilsHandleError(pX